if (typeof WCS == "undefined" || !WCS) {
	var WCS={};
}
if (typeof WCS.util == "undefined" || !WCS.util) {
	WCS.util={};
}
if (typeof WCS.data == "undefined" || !WCS.data) {
	WCS.data={};
}
/**
 * @class
 * @static
 */
WCS.util.ESpot = {
	/**
	 * @private 
	 * @
	 */
	callbacks:[],
	/**
	 * @private
	 */
    defaultsDisplayed:false,
    /**
     * @private
     */
    originDomain:null,
	/**
	 * @function
	 * @param {string}callback function to call after the eSpots are done loading
	 */
	addCallback : function(callback) {
		 WCS.util.ESpot.callbacks[WCS.util.ESpot.callbacks.length] = callback;
	},
	/**
	 * @private
	 */
	loadCounter : 0,
	/**
	 * @private
	 * @description Register that an eSpot has been loaded
	 * and fire off any registered callbacks if all the 
	 * eSpots have been loaded.
	 */
	registerEspotLoadComplete: function() {
		WCS.util.ESpot.loadCounter--;
		if (WCS.util.ESpot.loadCounter <= 0) {
			for ( var i = 0; i < WCS.util.ESpot.callbacks.length; i++) {
				WCS.util.ESpot.callbacks[i]();
			}
		}
	},
	/**
	 * @private
	 * @param {eSpotObject}
	 *            eSpot that you would like to display on
	 *            the page using the value specified in the value attribute
	 * @description Place the eSpot HTML into the proper location on a page
	 */
	displayCachedESpot : function(event, obj, eSpot) {
		if (YAHOO.util.Dom.get(eSpot.id)) {
			YAHOO.util.Dom.get(eSpot.id).innerHTML = eSpot.value;
			WCS.util.ESpot.displayElement(eSpot.id);
		}
		eSpot.value = null;
		WCS.util.ESpot.registerEspotLoadComplete();
	},
	/**
	 * @private
	 * @description Un-hide all div tags on the page with an ID that starts with
	 *              "eSpot_". Effectivly this displays default content for an
	 *              eSpot if the HTML in the eSpots div tag wasn't updated
	 */
	displayDefaultESpots : function() {
		WCS.util.ESpot.defaultsDisplayed=true;
		var divs = document.getElementsByTagName('div');
		for ( var i = 0; i < divs.length; i++) {
			if (divs[i].id.match(new RegExp("^eSpot_"))) {
				WCS.util.ESpot.displayElement(divs[i].id);
			}
		}
		WCS.util.ESpot.loadCounter = 0;
		WCS.util.ESpot.registerEspotLoadComplete();
	},
	/**
	 * @private
	 * @description If the content for the eSpots couldn't be retrieved display
	 *              the default eSpot content
	 * @param {string}espotName The name of the eSpot that couldn't be retrieved.
	 */
	displayFailedESpot : function(espotName) {
		if (YAHOO.util.Dom.get(espotName)) {
			WCS.util.ESpot.displayElement(espotName);
		}
		WCS.util.ESpot.registerEspotLoadComplete();
	},

	/**
	 * @private
	 * @description If the content for an eSpot couldn't be retrieved display
	 *              the default eSpot content
	 */
	displayDefaultESpot : function(eSpotName) {
		if (arguments.length > 2) {
			eSpotName = arguments[2];
		}
		if (YAHOO.util.Dom.get(eSpotName)) {
			WCS.util.ESpot.displayElement(eSpotName);
		}
		WCS.util.ESpot.registerEspotLoadComplete();
	},
	/**
	 * @private
	 * @param {Array}sortOrder Array of eSpot names in the order that 
	 * the eSpot content should be sorted into
	 * @description Sorts eSpot content in the order of the
	 * the supplied array of eSpot names.  
	 */
	sortEspots: function(sortOrder) {
	    if (sortOrder.length > 0 && sortOrder[0].toLowerCase() == 'random') {
	        sortOrder.splice(0,1);
	        sortOrder.sort(function randOrd(){return (Math.round(Math.random())-0.5);});
	    }
		var tmpArray = [];
		//Populate a temporary object with the eSpot objects on the Page
		var count = 0;
		for (var j = 0; j < WCS.data.ESpots.length; j++) {
			for (var i = 0; i < sortOrder.length; i++) {
				if (WCS.data.ESpots[j].id == sortOrder[i]) {
					tmpArray[count++] = YAHOO.lang.JSON.parse( YAHOO.lang.JSON.stringify( WCS.data.ESpots[j] ) );
					break;
				}
			}
		}
		//Update the URL appropriate sortOrder URL 
		var j = 0;
		for (var i = 0; i < sortOrder.length; i++) {
			for (j = 0; j < tmpArray.length; j++) {
				if (tmpArray[j].id == sortOrder[i]) {
					break;
				}
			}
			for (var k = 0; k < WCS.data.ESpots.length; k++) {
				if (WCS.data.ESpots[k].id == tmpArray[i].id) {
					WCS.data.ESpots[k].url = tmpArray[j].url;
				}
			}
		}
	},
	/**
	 * @private
	 * @description Display all of the eSpots defined in the array
	 *              WCS.data.ESpots in the corresponding div tags
	 */
	displayESpots : function() {
		var espot = null;
		/**
		 * @private
		 * @description If content for a specific eSpot could not be retrieved
		 *              from the specified content url for that eSpot display
		 *              the default eSpot content in the corresponding div tag
		 */
		var responseFailure = function(o) {
			if (YAHOO.util.Dom.get(o.argument.id)) {
				WCS.util.ESpot.displayFailedESpot(o.argument.id);
			} else {
				YAHOO.util.Event.onDOMReady(WCS.util.ESpot.displayFailedESpot, o.argument.id);
			}
		};
		/**
		 * @private
		 * @description If HTML content could be retrieved for a specific eSpot
		 *              display that eSpot in the corresponding div tag
		 */
		var responseSuccess = function(o) {
			if (YAHOO.util.Dom.get(o.argument.id)) {
				YAHOO.util.Dom.get(o.argument.id).innerHTML = o.responseText;
				WCS.util.ESpot.displayElement(o.argument.id);
				WCS.data.ESpots[o.argument.index].success = true;
				WCS.util.ESpot.registerEspotLoadComplete();
			} else {
				o.argument.value = o.responseText;
				YAHOO.util.Event.onDOMReady(WCS.util.ESpot.displayCachedESpot, o.argument, true);
			}

		};
		if (WCS.data.ESpots) {
			//Sort the eSpots
			for ( var i = 0; i < WCS.data.ESpots.length; i++) {
				if (WCS.data.ESpots[i] && WCS.data.ESpots[i].sortOrder) {
					var sortOrder = WCS.data.ESpots[i].sortOrder;
					WCS.data.ESpots.splice(i--,1);
					var eSpotArray = sortOrder.split(";");
					for (var j = 0; j < eSpotArray.length; j++) {
						eSpotArray[j] = "eSpot_" + eSpotArray[j];
					}
					WCS.util.ESpot.sortEspots(eSpotArray);
				}
			}
			//Get espot content
			for ( var i = 0; i < WCS.data.ESpots.length; i++) {
				if (WCS.data.ESpots[i] && WCS.data.ESpots[i].url != "null" && !WCS.data.ESpots[i].sortOrder) {
					var callback = {
						success :responseSuccess,
						failure :responseFailure,
						argument :WCS.data.ESpots[i]
					};
					try
					{
						WCS.util.ESpot.loadCounter++;
						WCS.data.ESpots[i].index = i;
						var url = WCS.data.ESpots[i].url
						if (url.indexOf("?") > 0) {
							url = url.substring(0, url.indexOf("?"));
						}
						YAHOO.util.Connect.asyncRequest("GET", "/"
									+ WCS.data.ESpots[i].url, callback, null);
					}catch (e) {
						YAHOO.util.Event.onDOMReady(WCS.util.ESpot.displayDefaultESpot,WCS.data.ESpots[i].id);
					}
				} else if (WCS.data.ESpots[i] && !WCS.data.ESpots[i].sortOrder){
					WCS.util.ESpot.loadCounter++;
					YAHOO.util.Event.onDOMReady(WCS.util.ESpot.displayDefaultESpot,WCS.data.ESpots[i].id);
				} else if (!WCS.data.ESpots[i].sortOrder) {
					WCS.util.ESpot.displayDefaultESpots();
					break;
				}
			}
			if (WCS.util.ESpot.loadCounter <= 0) {
				WCS.util.ESpot.registerEspotLoadComplete();
			}
		} else {
			YAHOO.util.Event.onDOMReady(WCS.util.ESpot.displayDefaultESpots);
		}
	},

	/**
	 * @private
	 * @function
	 * @description Populate an array of name value pairs of eSpot names and
	 *              URLS with the name WCS.data.ESpots by passing the WCS REST
	 *              service hdwcContentEspotCmd a list of eSpot names via that
	 *              same variable WCS.data.ESpots. Once the array is retrieved
	 *              the URLs are used to display the proper eSpot content in a
	 *              corresponding HTML div tag. The WCS.data.ESpots variable
	 *              must be set with a query string in the following format
	 *              before calling this method
	 * 
	 * <pre>
	 * &quot;WCS.data.ESpots=espot1=[eSpot Name]&amp;espot2=[eSpot Name]&amp;espot3=[eSpot Name]...etc&quot;
	 * </pre>
	 * 
	 * where [eSpot Name] is the name of the eSpot to be displayed on a page. A
	 * HTML div tag in the following format must exist for each eSpot that is
	 * included in the WCS.data.ESpots variable
	 * 
	 * <pre>
	 *              	&lt;div id=&quot;eSpot_[eSpot Name]&quot; style=&quot;visibility:hidden;&quot;&gt;
	 * 						defulat HTML content
	 * 					&lt;/div&gt;              
	 * </pre>
	 * 
	 * If for any reason this function is unable to retrieve URLs for the eSpots
	 * defined in the variable WCS.data.ESpots then the default HTML of the
	 * eSpot HTML div tags is displayed.
	 * 
	 */
	getESpotURLs : function() {
		var responseFailure = function(o) {
			WCS.util.ESpot.displayDefaultESpots();
		};
		var responseSuccess = function(o) {
			if (!WCS.util.ESpot.defaultsDisplayed) {
				if (WCS.data.ESpots[0] && WCS.data.ESpots[0].id!="undefined") {
					WCS.util.ESpot.displayESpots();
					if (window.location.search.match("[\?&]espotdebug=true")) {
						for ( var i = 0; i < WCS.data.ESpots.length; i++) {
							if (WCS.data.ESpots[i] && !WCS.data.ESpots[i].sortOrder) {
								window.document.body.innerHTML += "<br/>Name: "
										+ WCS.data.ESpots[i].id + "     URL: "
										+ WCS.data.ESpots[i].url;
							} 
						}
					}
				} else {
					WCS.util.ESpot.displayDefaultESpots();
				}
			}
		};
        var reqDomain = window.location.host;
        var reqscheme = window.location.protocol;
        if (WCS.util.ESpot.originDomain) {
            reqDomain = WCS.util.ESpot.originDomain;
        }
        
		var eSpotGetURL =  WCS.util.ESpot.getWCSWebURL(reqscheme, reqDomain, hdStoreId, hdCatalogId, hdLanguageId, WCS.data.ESpots);

		var callback = {
			onSuccess:responseSuccess,
			onFailure:responseFailure,
			onTimeout:responseFailure,
			varName:'WCS.data.ESpots',
			timeout:8000
		};
		try
		{
			YAHOO.util.Get.script(eSpotGetURL, callback);
		
		}catch (e) {
		
			WCS.util.ESpot.displayDefaultESpots();
		}
	},
	/**
	 * @private
	 * @description Build the WCS user used to get espot, accounts for
	 * preview requires
	 */
	getWCSWebURL : function(reqscheme, domain, storeId, catId, langId, eSpotData) {
		var wrkspcContext =  WCS.util.ESpot.getCookie("HDWC_WRKSPC_CONTEXT");
		var wcs_webcontext =  "/webapp/wcs/stores/servlet/";
		if (wrkspcContext) {
			wcs_webcontext = "/webapp/wcs/preview/servlet/";
		}
		
		var wcsURL = reqscheme + '//' + domain + wcs_webcontext + 'hdwcESpotURLServiceView' + 
				'?storeId='	+ storeId
				+ '&catalogId=' + catId
				+ '&langId=' + langId 
				+ '&' + eSpotData;
		if (wrkspcContext) {
			wcsURL += "&newPreviewSession=true"
		}		
		var segmentValue =  WCS.util.ESpot.getCookie("WC_CustomerSegment");
		if (segmentValue) {
			segmentValue = encodeURIComponent(segmentValue);
			wcsURL += '&WC_CustomerSegment=' + segmentValue;
		}	
		return wcsURL;
	},
	
	/**
	 * @private
	 * @description Gets the value of a browser cookie
	 */
	getCookie : function(c_name) {
		if (document.cookie.length > 0) {
			c_start = document.cookie.indexOf(c_name + "=");
			if (c_start != -1) {
				c_start = c_start + c_name.length + 1;
				c_end = document.cookie.indexOf(";", c_start);
				if (c_end == -1) {
					c_end = document.cookie.length;
				}
				return document.cookie.substring(c_start, c_end);
			}
		}
		return "";
	},
	
	/**
	 * @function
	 * @description Populate an array of name value pairs of eSpot names and
	 *              URLS with the name WCS.data.ESpots by passing the WCS REST
	 *              service hdwcESpotURLServiceView a list of eSpot names. Once the array is retrieved
	 *              the URLs are used to display the proper eSpot content in a
	 *              corresponding HTML div tag. This method should be passed a
	 *              query string that is the following format.
	 * 
	 * <pre>
	 * &quot;espot1=[eSpot Name]&amp;espot2=[eSpot Name]&amp;espot3=[eSpot Name]...etc&quot;
	 * </pre>
	 * 
	 * where [eSpot Name] is the name of the eSpot to be displayed on a page. A
	 * HTML div tag in the following format must also exist for each eSpot declared in the query 
	 * string
	 * 
	 * <pre>
	 *              	&lt;div id=&quot;eSpot_[eSpot Name]&quot;&gt;
	 * 						defulat HTML content
	 * 					&lt;/div&gt;              
	 * </pre>
	 * 
	 * If for any reason this function is unable to retrieve URLs for the eSpots
	 * defined in the queryString then the default HTML of the
	 * eSpot HTML div tags is displayed.<br><br>
	 * <b>Note: eSpot debug info can be added to the bottom of the page by 
	 * adding "espotdebug=true" to the query string of the page request</b>
	 * 
	 * @param {String}queryString A URL query string containing each of the eSpots
	 * that should be displayed on the current page
	 * @param {String}originDomain Optional Param - The domain to request eSpot meta data from.
	 * @
	 */
	display : function(queryString) {
	    if (arguments[1]) {
	     WCS.util.ESpot.originDomain = arguments[1];
	    }
		var qs = queryString.replace(/\+/g, ' ');
		// parse out name/value pairs separated via &
		var args = qs.split('&'); 
		//Loop through all arguments and hide the corresponding div tags if they exist
		for (var i = 0; i < args.length; i++) {
			// split out each name=value pair
			var pair = args[i].split('=');			
			WCS.util.ESpot.hideElement('eSpot_' + decodeURIComponent(pair[1]))
		}
		WCS.data.ESpots=queryString;
		WCS.util.ESpot.getESpotURLs();
	},
	/**
	 * @description Set the css to display an HTML element.
	 * @param {String}id id of HTML element to unhide/display
	 */
	displayElement : function(id) {
		var element = "#" + id; 
		YAHOO.util.StyleSheet('hdESpotStyle').unset(element, 'visibility');
	},
	/**
	 * @description Set the css to hide an HTML element.
	 * @param {String}id id of HTML element to hide
	 */
	hideElement : function(id) {
		var element = "#" + id;
		YAHOO.util.StyleSheet('hdESpotStyle').set(element, { visibility: 'hidden' }); 
	}
};
