// JavaScript Document

// equipped items namespace
YAHOO.namespace("gaia.apps");

// means onDOMready
YAHOO.util.Short(function($, Y){
	$("#id_wishlist a, #wishlist a").bind("click", function(e){
		Y.EVENT.preventDefault(e);
		var item=this.id.split("_")[1];
		YAHOO.gaia.apps.ei.getItemDetails(item);

	});
	$("#id_equipment, #equipped_id a").bind("click", function(e){
		Y.EVENT.preventDefault(e);
		var $eid = $('#equipped_id'),
			$dt = $("#details_title"),
			cur_id;

		if ($eid.length)
			cur_id = $eid[0].title;
		
		else if ($dt.length)
			cur_id = $dt[0].className;;
		

		YAHOO.gaia.apps.ei.getItemList(cur_id);
	});
});


(function(){
	// true will log to firebug, false will not
	var debug = 0;

	// our mini logger
	var firebug = function(strOrObj) {
		if (debug && window.console && window.console.log)
			console.log(strOrObj);
	}

	var myAppend = function(obj){
		 var _div = document.createElement('DIV');
		 _div.innerHTML = obj.responseText;
		 document.getElementsByTagName('body')[0].appendChild(_div);
	}

	// local vars in anonymous function, byte saving feature and sheilding from conflict
	var EVENT = YAHOO.util.Event;
	var DOM = YAHOO.util.Dom;

		YAHOO.gaia.apps.ei = function(){
			// private vars
			var storeUserItem = [];
			var storeOutfits = [];
			var user;
			var outfit_id;
			var getList = false;
			var getOutfit = false;
			var checkOutfitCache;
			var listContainer = 'equipped-list';
			var detailContainer = 'equipped-item-details';
			var myItemsPanel;
			var myItemDetailsPanel;
			var myItems;
			var myItemDetails;
			var template = false; // ei template has not been loaded
			var sigs = DOM.getElementsByClassName('extra_sigs');
			var curItem;
			var getCurItem = false;
			var curDetails;
			var $ = function(str){ return document.getElementById(str)};

      var config = { 'detailsOnly': false,
                     'template': 'template',
                     'offset': {'x': -15, 'y': 5}
                   };

			// return public methods
			return {
				// just to get template and append to body
				init : function (){
						// try to get template
						if(!template)
							YAHOO.util.Connect.asyncRequest('GET', '/equip/' + config.template + '?'+GAIA_config('cache_value'), YAHOO.gaia.apps.ei.template_callback, null);
				},//end init

				template_callback : {
					success: function(o){
						firebug(o);
						template = o;
						YAHOO.gaia.apps.ei.template_success();
					},
					failure: function(o){
						firebug(o);
						YAHOO.gaia.apps.ei.template_failure();
					}
				},

				template_success : function(){
					firebug("template successfully gotten");
					YAHOO.gaia.apps.ei.createPanel();
				},

				template_failure : function(){
					firebug("template failure");
					if (!user){
						user = '';
					}
					top.location.href = "/p/" + user;
				},

				createPanel: function(){
					myAppend(template);
					inited = true;

          if (!config.detailsOnly) {
					  myItemsPanel = new YAHOO.widget.Panel(listContainer, { 
						  zIndex: 1000,
	  			    fixedcenter: true,
  						/*constraintoviewport: true,  */
			  			underlay: "none",  
				  		close: false,  
					  	visible: false,  
						  draggable: false,
  						modal: true,
	  					effect : {effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.25}
		  			});

  					myItemsPanel.render();
          }
					
					myItemDetailsPanel = new YAHOO.widget.Panel(detailContainer, { 
						zIndex: 2000,
						underlay: "none",
						close: false,
						visible: false,
						draggable: false,
						modal: true,
						effect : {effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.25}
					});

					myItemDetailsPanel.render();

					// event handling after init
					EVENT.addListener( 'icon-close-list' , "click" , function(){
						YAHOO.gaia.apps.ei.allHide();
					});

					EVENT.addListener( 'icon-close-details' , "click" , function(){
						YAHOO.gaia.apps.ei.detailHide();
					});

					EVENT.addListener( 'equipped-item-details' , "mouseover" , function(){
						//prevent weird event behavior in ie, stupid hacks to please ie
						DOM.removeClass(this, 'yui-panel');
					});

					EVENT.addListener( window , "resize" , function(){
						myItemDetailsPanel.hide();
					});

					EVENT.addListener( window , "scroll" , function(e){
						myItemDetailsPanel.hide();
					});

					EVENT.addListener( 'itemDesc' , "scroll" , function(e){
						EVENT.stopEvent(e);
					});

					if (getList) {
						YAHOO.util.Connect.asyncRequest('GET', '/equip/list/'+user+'?_gaia_t_=850', YAHOO.gaia.apps.ei.itemList_callback, null);
						getList = false;
					}

					else if (getCurItem)
					{
						YAHOO.util.Connect.asyncRequest('GET', '/equip/list/'+user+'?_gaia_t_=850', YAHOO.gaia.apps.ei.wish_callback, null);
						getCurItem = false;
					}
					else if (getOutfit) {
					  YAHOO.util.Connect.asyncRequest('GET', '/equip/outfit/'+user+'/'+outfit_id, YAHOO.gaia.apps.ei.itemList_callback, null);
					  getOutfit = false;
					}
				},

				// get item list
				getItemList: function(userid){
					// woops template not gotten yet, get template first
					if (!template) {
						getList = true;
						user = userid;
						YAHOO.gaia.apps.ei.init();
					}
					else {
						// last load, no need to fetch data, just display
						if (user == userid)	{
							firebug("ran last load");
							user = userid;
							YAHOO.gaia.apps.ei.listShow();

						}

						// recent load, we get data from our cache/javascript_obj, and display
						else if (storeUserItem[userid])	{
							firebug("ran recent load");
							user = userid;
							YAHOO.gaia.apps.ei.itemList_success();
						}

						// fetch data from server and display;
						else {
							firebug("ran fetchdata and display");
							user = userid;
							YAHOO.util.Connect.asyncRequest('GET', '/equip/list/'+userid+'?_gaia_t_=850', YAHOO.gaia.apps.ei.itemList_callback, null);
						}

					}
				},
				// get outfit list
			        getOutfitList: function(userid, outfitid){
			                checkOutfitCache = true;
					// woops template not gotten yet, get template first
					if (!template) {
						getOutfit = true;
						user = userid;
						outfit_id = outfitid;
                                                config.template = 'template/outfititems';
						YAHOO.gaia.apps.ei.init();
					}
					else {
						// last load, no need to fetch data, just display
						if (outfit_id == outfitid)	{
							firebug("ran last load");
							outfit_id = outfitid;
							YAHOO.gaia.apps.ei.listShow();

						}

						// recent load, we get data from our cache/javascript_obj, and display
						else if (storeOutfits[outfitid])	{
							firebug("ran recent load");
							outfit_id = outfitid;
							YAHOO.gaia.apps.ei.itemList_success();
						}

						// fetch data from server and display;
						else {
							firebug("ran fetchdata and display");
							outfit_id = outfitid;
							YAHOO.util.Connect.asyncRequest('GET', '/equip/outfit/'+userid+'/'+outfitid, YAHOO.gaia.apps.ei.itemList_callback, null);
						}

					}
				},

				// get item list callback
				itemList_callback : {
					success: function(o){
						myItems = eval(o.responseText);
						firebug("Succeeded in getting item list");
						firebug("outputting json object");
						firebug(myItems);
						YAHOO.gaia.apps.ei.itemList_success()
					},
					failure: function(o){
						firebug(o);
						YAHOO.gaia.apps.ei.itemList_failure()
					}
				},

				itemList_success : function(){
			          if (checkOutfitCache) {
					if (storeOutfits[outfit_id]) {
						myItems = storeOutfits[outfit_id];
					}
					else {
						storeOutfits[outfit_id] = myItems;
					}
			                checkOutfitCache = false;
				  }
				  else {
				        if (storeUserItem[user]) {
						myItems = storeUserItem[user];
					}
					else {
						storeUserItem[user] = myItems;
					}
				  }
					firebug("iterating each obj");
					var myList = DOM.get('equipped-item-list');
					myList.innerHTML = '';
					if (myItems == -1)
					{
						myList.innerHTML = 'User does not allow viewing of currently equipped items';
					}
					if (myItems){
						for( item_id in myItems) {
							firebug(item_id);
							var _li = document.createElement("li");
							var _img = document.createElement("img");
							var _div = document.createElement("div");
							var _a = document.createElement("a");

							// filling in values
							_div.className = "itemIcon";
							_img.setAttribute("src", "/images/thumbnails/"+myItems[item_id].thumbfile);
							_a.className = "itemDesc";
							_a.innerHTML = myItems[item_id].name;

							// appending to DOM accordingly
							myList.appendChild(_li);
							_li.appendChild(_div);
							_li.appendChild(_a);
							_div.appendChild(_img);
							_a.id = item_id;

							// attach event to every single one of them
							EVENT.addListener( _a , "mouseover" , function(){
								YAHOO.gaia.apps.ei.itemDetails(this);
							});
						}
					}
					else {
						myList.innerHTML = 'No items found for this user.';
					}
					YAHOO.gaia.apps.ei.listShow();

				},

				itemList_failure : function(){
					firebug("item list failure");
					var myList = DOM.get('equipped-item-list');
					myList.innerHTML = 'We have encountered an internal error.';
					YAHOO.gaia.apps.ei.listShow();
				},

				populateDetails : function(cur) {
					
					var image = document.createElement("img");
					image.setAttribute("src", "/images/thumbnails/"+cur.thumbfile);

					$('itemIcon').innerHTML = '';
					$('itemIcon').appendChild(image);
					$('itemTitle').innerHTML = cur.name;
					$('itemDesc').innerHTML = cur.description;

					// reset for security
					$('itemAvail').innerHTML = '';
					$('itemAvail').style.display = "none"
                                        if ($('gotoShop') != null) {
					  $('gotoShop').style.display = "none";
					}
					$('buttons').style.display = "block";

					// if we detect that it's available on gold shop
					// show go to shop, item price and availability
					if (typeof (cur.store_id) == "object") {
					  if ($('gotoShop') != null) {
						$('gotoShop').style.display = "block";
						$('gotoShop').href = '/gaia/shopping.php/?key=' + cur.store_id.store_key +'&item_id=' + cur.item_id;
					  }
						$('itemAvail').style.display = "block";
						$('itemAvail').innerHTML ="Available at "+ cur.store_id.store_name + " for "+ cur.price + " Gold or " + cur.gpass + " Gaia Cash";
						if (cur.store_id.store_name == "Prize & Joy") {
							$('itemAvail').innerHTML ="Available at "+ cur.store_id.store_name + " for "+ cur.price + " tokens";
						}
					}
					// in cash only shop
					// show go to shop, item price and availability
					else if (cur.store_id == 18) {
						$('itemAvail').style.display = "block";
						$('itemAvail').innerHTML ="Available at Cash Shop La Victoire for "+ cur.gpass + " Gaia Cash";
					  if ($('gotoShop') != null) {
						$('gotoShop').style.display = "block";
						$('gotoShop').href = 'javascript:YAHOO.gaia.apps.ei.allHide();YAHOO.gaia.app.CashShop.SenderApplication.show({store:18,self:true,origin:"hero",goto_item: {item_id: '+ cur.item_id +',item_nonce: "'+cur.nonce+'",thumbnail: "\/images\/thumbnails\/'+cur.thumbfile+'",gpass: '+cur.gpass+',gold: '+cur.price+',name: "'+cur.name+'"}});';
					  }

						try	{
							if (disable_cashshop){
								$('gotoShop').href = '/market/?cashshop=true';
							}
						}
						catch (e){}

					}

					if (cur.item_key == '') {
						$('buttons').style.display = 'none';
					}

					// add to wish list
				        if ($('addWishlist') != null) {
					  $('addWishlist').href = '/account/addwishlist/?key=' + cur.item_key;
					}

					// this gets rid of the extra separate div when we disable the 
					// buttons for hte outfit item details and there is no shop data
					if ($('itemAvail').style.display == "none" && $('gotoShop') == null && $('addWishlist') == null) {
						$('buttons').style.display = 'none';
					}

					// populate market listing link
					$('itemMarketLink').href = '/marketplace/itemdetail/' + cur.item_id;

					// populate avg price
					$('currentPrice').innerHTML = cur.averages + ' Gold';
					$('currentDeviation').innerHTML = parseInt(cur.deviations) + '%';

					// positive or negative trend?
					if (cur.deviations == 0) $('currentDeviation').className = 'deltaSame';
					else (cur.deviations < 0) ? $('currentDeviation').className = 'deltaDown' :  $('currentDeviation').className = 'deltaUp';

				},

				itemDetails : function(obj){
					//myItemDetailsPanel.hide();
            var cur;
            if (config.strip_id != null) {
                var id_str = obj.id;
                id_str = id_str.replace(config.strip_id, "");
                cur = myItems[id_str];
            } else {
					      cur = myItems[obj.id];
            }

					YAHOO.gaia.apps.ei.populateDetails(cur);

					var curPos = DOM.getRegion(obj);
					var detailPos = DOM.getRegion($('equipped-item-details'));

					var ypos = curPos.top - (detailPos.bottom - detailPos.top) + config.offset.y;
					var xpos = curPos.left - (detailPos.right - detailPos.left)/2 + config.offset.x;

					myItemDetailsPanel.cfg.setProperty("x", xpos);
					myItemDetailsPanel.cfg.setProperty("y", ypos);

					// show the panel after populating the details
					myItemDetailsPanel.show();
				},

				onlyDetails: function(cur) {
					!template ? YAHOO.gaia.apps.ei.init() : '';
					YAHOO.util.Short('#equipped-list_c').parent().css('display', 'block');
					YAHOO.gaia.apps.ei.populateDetails(cur);

					var region = DOM.getClientRegion();
					var ei = DOM.getRegion(DOM.get('equipped-item-details'));
					var left = region.left + (region.right-region.left)/2-135;
					var top = region.top + (region.bottom-region.top)/2 - (ei.bottom-ei.top)/2 ;

					DOM.get('dialogArrow').style.display='none';

					myItemDetailsPanel.cfg.setProperty("x", left);
					myItemDetailsPanel.cfg.setProperty("y", top);
					myItemDetailsPanel.show();
					DOM.get('equipped-item-details_mask').style.display = 'block';
					DOM.get('equipped-item-details_mask').style.visibility = 'visible';
				},

				// show / hide functions below
				listShow : function (){
					YAHOO.util.Short('#equipped-list_c').parent().css('display', 'block');
					if (config.detailsOnly == false) myItemsPanel.show(); 

					DOM.setStyle('ad_inject', 'visibility', 'hidden'); 
					DOM.setStyle('grid_ad', 'visibility', 'hidden');
					DOM.setStyle(sigs, 'display', 'none'); 
				},

				listHide : function (){
					if (config.detailsOnly == false) {
  						myItemsPanel.hide();
						YAHOO.util.Short('#equipped-list_c').parent().css('display', 'none');
					}
					DOM.setStyle('ad_inject', 'visibility', 'visible');
					DOM.setStyle('grid_ad', 'visibility', 'visible');
					DOM.setStyle(sigs, 'display', 'block');
				},

				detailShow : function (){
					YAHOO.util.Short('#equipped-list_c').parent().css('display', 'block');
					myItemDetailsPanel.show();
				},

				detailHide : function (){
					myItemDetailsPanel.hide();

					var mask = DOM.get('equipped-item-details_mask');
					DOM.get('dialogArrow').style.display='block';
					if (mask) {
						mask.style.display = 'none';
						mask.style.visibility = 'hidden';
					}

					myItemDetailsPanel.cfg.setProperty("fixedcenter", false);
				},

				allHide: function(){

					if (config.detailsOnly == false) myItemsPanel.hide();
					YAHOO.util.Short('#equipped-list_c').parent().css('display', 'none');
					YAHOO.gaia.apps.ei.detailHide();
					DOM.setStyle('grid_ad', 'visibility', 'visible');
					DOM.setStyle('ad_inject', 'visibility', 'visible');
					DOM.setStyle(sigs, 'display', 'block');
					DOM.setStyle('id_aquarium', 'visibility', 'visible');
				},

				wishGetItem: function(o, curuser){
					curItem = o;
					user = curuser;
					getCurItem = true;
					firebug('wish get item init');
					YAHOO.util.Connect.asyncRequest('GET', '/equip/template?'+GAIA_config('cache_value'), YAHOO.gaia.apps.ei.template_callback, null);
				},

				wish_callback : {
					success: function(o){
						myItems = eval(o.responseText);
						YAHOO.gaia.apps.ei.wish_success();

					},
					failure: function(o){
						firebug(o);
						//YAHOO.gaia.apps.ei.wish_failure()
					}
				},

				wish_success: function(){
					firebug(myItems);
				},

				getItemDetails: function(item_id){
					YAHOO.gaia.apps.ei.init();
					YAHOO.util.Connect.asyncRequest('GET', '/equip/id/'+item_id+'?_gaia_t_=850', YAHOO.gaia.apps.ei.getItemDetails_callback, null);
				},

				getItemDetails_callback: {
					success: function(o) {
						var cur = eval(o.responseText);
						YAHOO.gaia.apps.ei.onlyDetails(cur);
					},
					failure: function(){
						// do nothing
					}
				},

        setItems: function(items) {
          myItems = items;
        },

        setConfig: function(data) {
          for(val in data) {
            config[val] = data[val];
          }
        }
			}
		}();

})(); // end anonymos function

