// global/scripts/store_selector.js
// ================================


var xml_escape_map = {
    '&': '&amp;',
    '"': '&quot;',
    '<': '&lt;',
    '>': '&gt;'
};
 
var xml_unescape_map = {
    '&amp;': '&',
    '&quot;': '"',
    '&lt;': '<',
    '&gt;': '>'
};
 
function encodeXml(value) {
	if(!value) {
		return value;
	}
    return value.replace(/([\&"<>])/g, function(str, item) {
        return xml_escape_map[item];
    });
};
 
function decodeXml(value) {
 	if(!value) {
		return value;
	}
   return value.replace(/(&quot;|&lt;|&gt;|&amp;)/g,
        function(str, item) {
            return xml_unescape_map[item];
    });
}
StoreSelector = Class.create();
StoreSelector.prototype = {	

	stateDictionary: null,
	
	states: [],
	global_response: null,
	locationSelector: [],
	storeSelector: [],
	submitButton: false,
	cookiedLocation: false,
	cookiedStore: false,
	activateButton: false,
	urlStoreAppleId: null,
	urlStoreLocation: null,
	stateWithName: function(value) {
		var result = this.stateDictionary[value];
		if(!result) {
			result = (this.stateDictionary[value] = {stores: []});
			result.name = value;
		}
		return result;
	},
	
	// linkType options: genius, procare, business, personal, promo, workshop, and store.
	initialize: function(country, locationSelector, storeSelector, submitButton, linkType, delegate, phonePropertyName, pageType) {
    
        //Backward compatibility and default check:
        this.phonePropertyName = (typeof phonePropertyName === "string") ? phonePropertyName : "phone";
		this.stateDictionary = {
		AK: {name: "Alaska", stores: []},
		AL: {name: "Alabama", stores: []},
		AZ: {name: "Arizona", stores: []},
		AR: {name: "Arkansas", stores: []},
		CA: {name: "California", stores: []},
		CO: {name: "Colorado", stores: []},
		CT: {name: "Connecticut", stores: []},
		DE: {name: "Delaware", stores: []},
		DC: {name: "District of Columbia", stores: []},
		FL: {name: "Florida", stores: []},
		GA: {name: "Georgia", stores: []},
		HI: {name: "Hawaii", stores: []},
		ID: {name: "Idaho", stores: []},
		IL: {name: "Illinois", stores: []},
		IN: {name: "Indiana", stores: []},
		IA: {name: "Iowa", stores: []},
		KS: {name: "Kansas", stores: []},
		KY: {name: "Kentucky", stores: []},
		LA: {name: "Louisiana", stores: []},
		ME: {name: "Maine", stores: []},
		MD: {name: "Maryland", stores: []},
		MA: {name: "Massachusetts", stores: []},
		MI: {name: "Michigan", stores: []},
		MN: {name: "Minnesota", stores: []},
		MS: {name: "Mississippi", stores: []},
		MO: {name: "Missouri", stores: []},
		MT: {name: "Montana", stores: []},
		NE: {name: "Nebraska", stores: []},
		NV: {name: "Nevada", stores: []},
		NH: {name: "New Hampshire", stores: []},
		NJ: {name: "New Jersey", stores: []},
		NM: {name: "New Mexico", stores: []},
		NY: {name: "New York", stores: []},
		NC: {name: "North Carolina", stores: []},
		ND: {name: "North Dakota", stores: []},
		OH: {name: "Ohio", stores: []},
		OK: {name: "Oklahoma", stores: []},
		OR: {name: "Oregon", stores: []},
		PA: {name: "Pennsylvania", stores: []},
		RI: {name: "Rhode Island", stores: []},
		SC: {name: "South Carolina", stores: []},
		SD: {name: "South Dakota", stores: []},
		TN: {name: "Tennessee", stores: []},
		TX: {name: "Texas", stores: []},
		UT: {name: "Utah", stores: []},
		VT: {name: "Vermont", stores: []},
		VA: {name: "Virginia", stores: []},
		WA: {name: "Washington", stores: []},
		WV: {name: "West Virginia", stores: []},
		WI: {name: "Wisconsin", stores: []},
      	WY: {name: "Wyoming", stores: []},
      	Tokyo:    {name: "Tokyo", stores: []},
      	Fukuoka: {name: "Fukuoka", stores: []},
      	Germany: {name: "Germany", stores: []},
      	NSW:     {name: "New South Wales", stores: []},
      	VIC:     {name: "Victoria", stores: []},
      	QLD:     {name: "Queensland", stores: []},
      	QC:      {name: "Quebec", stores: []},
      	ON:      {name: "Ontario", stores: []},
        AB:      {name: "Alberta", stores: []},
        MB:      {name: "Manitoba", stores: []},
      	BC:      {name: "British Columbia", stores: []},
      	France:  {name: "France", stores: []},
      	Italy:   {name: "Italy", stores: []},
      	CHDE:    {name: "Switzerland German", stores: []},
      	Geneva:  {name: "Geneva", stores: []},
      	UK:      {name: "UK", stores: []},
      	Surrey:  {name: "Surrey", stores: []},
      	Kent:    {name: "Kent", stores: []}
    };

	var lang = document.getElementsByTagName("html")[0].getAttribute('lang');
	if(lang.toUpperCase() === "FR-CA") {
		this.stateDictionary["BC"] =  {name: "Colombie Britannique", stores: []};
		this.stateDictionary["British Columbia"] = this.stateDictionary["BC"];
		this.stateDictionary["QC"] =  {name: "QuÃ©bec", stores: []};
		this.stateDictionary["Quebec"] = this.stateDictionary["QC"];
	}
	
		this.urlStoreAppleId = getUrlVars()["store"];		

		this.locationSelector = locationSelector;
		this.storeSelector = storeSelector;
		this.submitButton = submitButton;
		this.linkType = linkType;
		this.delegate = delegate;
		this.skipStateFlag = this.locationSelector.style.display=="none" ? true : false;   //flag to hide optionbox if no states
		
		if(Cookie.get('retail_storeloc') && this.submitButton) this.cookiedLocation = Cookie.get('retail_storeloc');
		if(Cookie.get('retail_storenumb') && this.submitButton) this.cookiedStore = Cookie.get('retail_storenumb');
		
		
		if(country == null){
			this.sendRequest(pageType);
		}else {
			this.global_response = country;
			this.populateLocationsWithin();
		}
		
		if(this.cookiedStore && this.submitButton) this.submitButton.addClassName('active');
		
		if(!this.skipStateFlag){
			Event.observe(this.locationSelector, 'change', function(event) {

				var selectedIndex = this.locationSelector.selectedIndex;
				var selectedState = this.locationSelector.getElementsByTagName('option')[selectedIndex];
			
				this.showStores(this.stateWithName(selectedState.value).stores);
			
			}.bindAsEventListener(this));
		}
		
		Event.observe(this.storeSelector, 'change', function(event) {

			var selectedIndex = this.storeSelector.selectedIndex;
			var selectedStore = this.storeSelector.getElementsByTagName('option')[selectedIndex];
			
			if (typeof(selectedStore.value) != 'undefined' && selectedIndex != 0) {
				if(!this.submitButton) {
					var selectedIndex = this.locationSelector.selectedIndex;
					var selectedState = this.locationSelector.getElementsByTagName('option')[selectedIndex];
					
					if(Cookie.get('retail_storeloc')) Cookie.erase('retail_storeloc');
					Cookie.set('retail_storeloc', selectedState.value, 14);
					if(Cookie.get('retail_storenumb')) Cookie.erase('retail_storenumb');
					Cookie.set('retail_storenumb', selectedStore.getAttribute('name'), 14);
					
					window.location = selectedStore.value;
				} else { 
					this.submitButton.addClassName('active');
				}
			} else {
				if(this.submitButton) this.submitButton.removeClassName('active');
			}
			
		}.bindAsEventListener(this));
		
		if(this.submitButton && this.linkType != 'phone') {
			Event.observe(this.submitButton, 'click', function(event) {
				Event.stop(event);
				
				var selectedIndex = this.locationSelector.selectedIndex;
				var selectedState = this.locationSelector.getElementsByTagName('option')[selectedIndex];
		
				var selectedIndex = this.storeSelector.selectedIndex;
				var selectedStore = this.storeSelector.getElementsByTagName('option')[selectedIndex];
				
				if(this.submitButton.hasClassName('active') && typeof(selectedStore.value) != 'undefined') {
					if(Cookie.get('retail_storeloc')) Cookie.erase('retail_storeloc');
					Cookie.set('retail_storeloc', selectedState.value, 14);
					if(Cookie.get('retail_storenumb')) Cookie.erase('retail_storenumb');
					Cookie.set('retail_storenumb', selectedStore.getAttribute('name'), 14);
					
					window.location = selectedStore.value;
				} else {
					if(typeof(selectedState.value) == 'undefined') this.locationSelector.focus();
					else this.storeSelector.focus();
				}
			}.bindAsEventListener(this));
		}
		
		if(this.submitButton && this.linkType == 'phone') {
			Event.observe(this.submitButton, 'click', function(event) {
				Event.stop(event);
				
				var selectedIndex = this.locationSelector.selectedIndex;
				var selectedState = this.locationSelector.getElementsByTagName('option')[selectedIndex];
				
				var selectedIndex = this.storeSelector.selectedIndex;
				var selectedStore = this.storeSelector.getElementsByTagName('option')[selectedIndex];
				
				if(this.submitButton.hasClassName('active') && typeof(selectedStore.value) != 'undefined') {
					if(Cookie.get('retail_storeloc')) Cookie.erase('retail_storeloc');
					Cookie.set('retail_storeloc', selectedState.value, 14);
					if(Cookie.get('retail_storenumb')) Cookie.erase('retail_storenumb');
					Cookie.set('retail_storenumb', selectedStore.getAttribute('name'), 14);
					
					this.sendReq($H({'store':selectedStore.value}));
				} else {
					if(typeof(selectedState.value) == 'undefined') this.locationSelector.focus();
					else this.storeSelector.focus();
				}
				
			}.bindAsEventListener(this));
			
			Event.observe($('phoneToggle'), 'click', this.phoneToggleClicked.bindAsEventListener(this));
		}
		
	},
	 
	getStateAbbr: function(state){
		for(var item in this.stateDictionary){
			if(this.stateDictionary[item].name==state){
				return item;
			}
		}
	},
	
	phoneToggleClicked: function(event) {
	if(event) Event.stop(event);
		var element = $('phoneResults');
		if(element) {
			element.hide();
		}
		element = $('phoneFields');
		if(element) {
			element.show();
		}
		//this.changeOverlayHeight($('phoneFields'));
	} ,
	
	sendReq: function(params) {
		// send request for store workshops with the R#
		var send = new Ajax.Request('/retail/scripts/storewidget.php', {
			method: 'POST', 
			parameters: params,
			onComplete: this.acknowledgeComplete.bind(this)
		})
	},
	
	acknowledgeComplete: function(request) {
		var jsonText = request.responseText;
		var result = this.scopedEval(jsonText);
		if(result) {
			var storeInfo = result[0];			
			this.setStoreInfo(storeInfo);
			$('phoneFields').hide();
			$('phoneResults').show();
			//this.changeOverlayHeight($('phoneResults'));
		}
	},
	
	changeOverlayHeight: function(content) {
		var locationOverlay = $$('.overlay.locationoverlay')[0];
		var locationOverlayShadow = $$('.overlayshadow.locationoverlay')[0];
		var overlayHeight = AC.OverlayPanel.overlay.height();
		var resultsHeight = content.getHeight();
		AC.OverlayPanel.overlay.setHeight(resultsHeight);
	},
	
	scopedEval: function(stringValue) {
		try {
			//alert(stringValue);
			return (function() {return eval("("+stringValue+")");})();
		}
		catch(e) {
			//alert('Error: '+e);
			return null;
		}
	},
	
	setStoreInfo: function(storeInfo) {
		var phoneResults = $('phoneResults');
		
		/**
			phoneResults.down('.fn').innerHTML = storeInfo.storeName;
			phoneResults.down('.street-address').innerHTML = storeInfo.address1;
			phoneResults.down('.extended-address').innerHTML = storeInfo.address2;
			phoneResults.down('.locality').innerHTML = storeInfo.city;
			phoneResults.down('.region').innerHTML = storeInfo.state;
			phoneResults.down('.postal-code').innerHTML = storeInfo.zip;
			phoneResults.down('.tel').innerHTML = storeInfo[this.phonePropertyName];
		**/
			
		/**
		"storeName":"SanLiTun",
		"address1":"Building 6, No. 19, Sanlitun Road",
		"address2":"The Village at Sanlitun",
		"city":"Chaoyang District",
		"state":"",
		"zip":"",
		"phone":"(8610) 6419-8900",
		"bus_phone":"(8610)6419-8900",
		*/
		if(storeInfo.storeName == "SanLiTun")
		{
			phoneResults.down('.fn').innerHTML = "三里屯 Apple Store 零售店";
			phoneResults.down('.street-address').innerHTML = "北京市朝阳区";
			phoneResults.down('.extended-address').innerHTML = "三里屯路 19 号院";
			phoneResults.down('.locality').innerHTML = "三里屯 Village 6 号楼";
			phoneResults.down('.region').innerHTML = storeInfo.state;
			phoneResults.down('.postal-code').innerHTML = storeInfo.zip;
			phoneResults.down('.tel').innerHTML = storeInfo[this.phonePropertyName];
		}
		
		/**
		"storeName":"SanLiTun",
		"address1":"Building 6, No. 19, Sanlitun Road",
		"address2":"The Village at Sanlitun",
		"city":"Chaoyang District",
		"state":"",
		"zip":"",
		"phone":"(8621) 6084 6800",
		"bus_phone":"(8621) 6084 6800",
		*/
		
		if(storeInfo.storeName == "Pudong")
		{
			phoneResults.down('.fn').innerHTML = "浦东 Apple Store 零售店";
			phoneResults.down('.street-address').innerHTML = "上海市浦东新区陆家嘴世纪大道 8 号";
			phoneResults.down('.extended-address').innerHTML = "上海国金中心";
			phoneResults.down('.locality').innerHTML = "IFC 商场 LG2－27 号店铺";
			phoneResults.down('.region').innerHTML = storeInfo.state;
			phoneResults.down('.postal-code').innerHTML = storeInfo.zip;
			phoneResults.down('.tel').innerHTML = storeInfo[this.phonePropertyName];
		}
		
		/**
		"storeName":"SanLiTun",
		"address1":"Building 6, No. 19, Sanlitun Road",
		"address2":"The Village at Sanlitun",
		"city":"Chaoyang District",
		"state":"",
		"zip":"",
		"phone":"(8621) 6084 6800",
		"bus_phone":"(8621) 6084 6800",
		*/
		
		if(storeInfo.storeName == "Xidan Joy City")
		{
			phoneResults.down('.fn').innerHTML = "西单大悦城 Apple Store 零售店";
			phoneResults.down('.street-address').innerHTML = "北京市西城区";
			phoneResults.down('.extended-address').innerHTML = "西单北大街 131 号";
			phoneResults.down('.locality').innerHTML = "大悦城";
			phoneResults.down('.region').innerHTML = storeInfo.state;
			phoneResults.down('.postal-code').innerHTML = storeInfo.zip;
			phoneResults.down('.tel').innerHTML = storeInfo[this.phonePropertyName];
		}
		
		/**
		"storeName":"SanLiTun",
		"address1":"Building 6, No. 19, Sanlitun Road",
		"address2":"The Village at Sanlitun",
		"city":"Chaoyang District",
		"state":"",
		"zip":"",
		"phone":"(8621) 6084 6800",
		"bus_phone":"(8621) 6084 6800",
		*/
		
		if(storeInfo.storeName == "Hong Kong Plaza")
		{
			phoneResults.down('.fn').innerHTML = "香港广场 Apple Store 零售店";
			phoneResults.down('.street-address').innerHTML = "上海市";
			phoneResults.down('.extended-address').innerHTML = "淮海中路 282 号";
			phoneResults.down('.locality').innerHTML = "香港广场北座";
			phoneResults.down('.region').innerHTML = storeInfo.state;
			phoneResults.down('.postal-code').innerHTML = storeInfo.zip;
			phoneResults.down('.tel').innerHTML = storeInfo[this.phonePropertyName];
		}
		
		// Hard code the CN store infomation since US can't get it localzied
	},
	
	
	
	/*utility function to convert a json object to xml*/
	convert_string_to_xml:function(xml_str)
	{
		var localxml_strcopy = xml_str;
		try
	  	{
	  		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  		xmlDoc.async="false";
	  		xmlDoc.loadXML(localxml_strcopy);
	  		return xmlDoc;
	  	}
		catch(e)
	  	{
	  		parser=new DOMParser();
	  		xmlDoc=parser.parseFromString(localxml_strcopy,"text/xml");
	 		return xmlDoc;
	  	}
	},
	//converts json to xml
	getXMLObj: function(response){
	
		if(response.responseObject) {
			oCountryStoreStack = response.responseObject;
		}
		else {
			var global_response = response.responseText;
			var oCountryStoreStack = eval('(' + global_response + ')');
		}
		var requestedCountry = oCountryStoreStack[0].country;

   		var cache_states = new Array();

   		var xmlstr = "<records storeWidgetVersion='1.0' conciergeWidgetVersion='1.0'>";
   		xmlstr += "<country name='" + requestedCountry + "'>";
   		this._hideStates = false;//flag to identify countries without states

		for (i=0; i < oCountryStoreStack[0].availableStores.length; i++) {
			  oCountryStoreStack[0].availableStores[i].state = null;
			 
			  switch (oCountryStoreStack[0].availableStores[i].name) {
			  	
				  case "Sanlitun"      				 : oCountryStoreStack[0].availableStores[i].name = "三里屯"; break;
				  case "Pudong"             			 : oCountryStoreStack[0].availableStores[i].name = "浦东"; break;
				  case "Xidan Joy City"             	: oCountryStoreStack[0].availableStores[i].name = "西单大悦城"; break;
				  case "Hong Kong Plaza"         : oCountryStoreStack[0].availableStores[i].name = "香港广场"; break;
			  };
			  
			  switch (oCountryStoreStack[0].availableStores[i].city) {
				  case "Chaoyang District"      	  : oCountryStoreStack[0].availableStores[i].city = "北京"; break;
				  case "Shanghai"             		  : oCountryStoreStack[0].availableStores[i].city = "上海"; break;
				  case "Beijing"             			  : oCountryStoreStack[0].availableStores[i].city = "北京"; break;
				  case "Shanghai"             		  : oCountryStoreStack[0].availableStores[i].city = "上海"; break;
			  };
			  
		  }

		
        if(oCountryStoreStack[0].availableStores[0].state == oCountryStoreStack[0].country){
   		  this._hideStates = true;	
          this.locationSelector.style.display="none";
        }else {
	      this.locationSelector.style.display="inline";
        }
       
		
		for (var i = 0; i < oCountryStoreStack[0].availableStores.length; i++) 
		{
			var stateName = this.getStateAbbr([oCountryStoreStack[0].availableStores[i].state]);
			if(stateName === undefined) {
				stateName = oCountryStoreStack[0].availableStores[i].state || requestedCountry;
			}
			var tempstr = "<state name='"+ encodeXml(stateName) +"'>";
			
			var use_it = "true";
				
			if(cache_states.length == 0) {
		       cache_states.push(oCountryStoreStack[0].availableStores[i].state);
		    } else {
		       for(var x = 0; x < cache_states.length; x++) {
		         if(oCountryStoreStack[0].availableStores[i].state == cache_states[x]) {
		           use_it = "false";
		         }
		       }
		     }
				
			 if(use_it == "true") {
		       cache_states.push(oCountryStoreStack[0].availableStores[i].state);
		       xmlstr += tempstr;
		       for (var g = 0; g < oCountryStoreStack[0].availableStores.length; g++) {
		         if(oCountryStoreStack[0].availableStores[g].state == oCountryStoreStack[0].availableStores[i].state) {
		             xmlstr += "<store><appleid>" + oCountryStoreStack[0].availableStores[g].appleid + "</appleid><name>" + encodeXml(oCountryStoreStack[0].availableStores[g].name) + "</name><city>" + encodeXml(oCountryStoreStack[0].availableStores[g].city) + "</city><phone>(555) 366-8477</phone><link>default</link></store>";
		           }
		         }
		         xmlstr += "</state>";
		       }
		
				if(this.urlStoreAppleId === oCountryStoreStack[0].availableStores[i].appleid) {
					this.urlStoreLocation = stateName;
				}
		     }
		     xmlstr += "</country>";

			xmlstr += "</records>";	
			//console.log("xmlstr ="+xmlstr);
			this.global_response = this.convert_string_to_xml(xmlstr);
			this.populateLocationsWithin();						
	},
	_selectAStateOptionLabel: "Select a State",
	_selectAStoreOptionLabel: 'Select a Store',
	populateLocationsWithin: function() {
      
		var self = this, statesArray, states, statesArray = [];
		states = this.states = (this.global_response).getElementsByTagName('state');
		if(states.length == 0) {
			states = this.states = [this.global_response];
		}
							
		if(this.states.length > 1)	{
			for (var i = 0, countI = states.length; i < countI; i++) {
				statesArray[i] = states[i];
			}
			
			statesArray.sort(function(a,b) { 
				var aName = self.stateWithName(a.getAttribute('name')).name,
					bName = self.stateWithName(b.getAttribute('name')).name;
				 return aName!=bName ? aName<bName ? -1 : 1 : 0 
			});
			
			this.states = statesArray;
		}

		this.storeSelector.getElementsByTagName('option')[0].innerHTML = "";
		var selectAStateOption = document.getElementById("selectState");
		var selectAStoreOption = document.getElementById("selectStore");
		var myDelegate = this.delegate;
		var hasShouldAddState = myDelegate && (typeof myDelegate.shouldAddStateNamed === "function");
		var shouldAddState = true;
		var shouldHideStates = this._hideStates;
		
		if(this.delegate && (typeof myDelegate.shouldHideStates === "function")) {
			shouldHideStates = myDelegate.shouldHideStates(this.states);
			if(!!shouldHideStates === true && !this._hideStates ) {
	          	this.locationSelector.style.display = "none";
			}
	        else {
		      this.locationSelector.style.display = "inline";
	        }
			this._hideStates = !!shouldHideStates;
	   		
		}
		
		
		if(selectAStateOption) {
			StoreSelector.prototype._selectAStateOptionLabel = selectAStateOption.innerHTML;
			selectAStateOption.parentNode.removeChild(selectAStateOption);
		}
		if(selectAStoreOption) {
			StoreSelector.prototype._selectAStoreOptionLabel = selectAStoreOption.innerHTML;
			selectAStoreOption.parentNode.removeChild(selectAStoreOption);
		}
		var firstState, firstStateCode;
		for (var i = 0; i < this.states.length; i++) {
			var state = this.states[i];			
			var stateCode = state.getAttribute('name');
			var stateName = this.stateWithName(state.getAttribute('name')).name;
			
			if(i===0) {
				firstState = state;
				firstStateCode = stateCode;
			}
			
			shouldAddState = true;
			if(hasShouldAddState) {
				shouldAddState = myDelegate.shouldAddStateNamed(stateName);
			}
			if(!shouldAddState) continue;
			var selected = ((stateCode == this.cookiedLocation) || (this.states.length === 1)) ? true : false;
           if(this.skipStateFlag){
		     selected = true;

		   }else {//for countries with no states, do not display state option-so display stores
			 //selected = (stateCode == this.cookiedLocation) ? true : false;
			var stateOption = this.createOption(stateCode, stateName, selected, '');
			this.locationSelector.appendChild(stateOption);
           }
			var currentStateObject, currentStateTag, currentStateCode, stores;
			if(this._hideStates) {
				selected = true;
				currentStateObject = this.stateWithName(firstStateCode);
				currentStateTag = firstState;
				currentStateCode = firstStateCode;
				stores = this.createStores(state);
				if(currentStateObject.stores.length) {
					currentStateObject.stores.push.apply(currentStateObject.stores,stores);
				}
				else {
					currentStateObject.stores = stores;
				}
			}
			else {
				currentStateObject = this.stateWithName(stateCode);
				currentStateTag = state;
				currentStateCode = stateCode;
				currentStateObject.stores = this.createStores(currentStateTag);
			}
			if(selected) {
				this.showStores(this.stateWithName(currentStateCode).stores);
				this.storeSelector.getElementsByTagName('option')[0].innerHTML = this._selectAStoreOptionLabel;
				if(this.storeSelector.selectedIndex === -1) {
					this.storeSelector.getElementsByTagName('option')[0].selected = true;
				}
				else {
					if(this.submitButton) {
						this.submitButton.addClassName('active');
					}
				}
			}
		}
		
		
		if(this.states.length === 1 && this._hideStates) {
			this.locationSelector.style.display = "none";
		}
	     if(!this.skipStateFlag){
		
			this.locationSelector.getElementsByTagName('option')[0].innerHTML = this._selectAStateOptionLabel;
			//this.locationSelector.getElementsByTagName('option')[0].innerHTML = selectAStateOption ? selectAStateOption.innerHTML : "Select a State";
			this.locationSelector.removeAttribute('disabled');
	   }
	},
		
	showStores: function(stores) {

		if(this.submitButton) this.submitButton.removeClassName('active');
		
		Element2.Methods.removeAllChildNodes(this.storeSelector);
		
		if(typeof(stores) == 'undefined') {
			this.storeSelector.setAttribute('disabled', 'disabled');
			return;
		}
		
		if(stores.length > 0) {
			this.storeSelector.appendChild(this.createOption('', this._selectAStoreOptionLabel, false, ''));
	       // Sort the stores before we add them to the Stores PickList
		   var oStoresToSort = [];
	       for (var i=0;i<stores.length;i++) {
	   	   		oStoresToSort.push( [ stores[i].text, stores[i] ] );  // In this context, stores[x] will read like "<option name="R999" value="/retail/camp/results.html">"
	       }
	       oStoresToSort.sort( function(a,b) { return a[0]!=b[0] ? a[0]<b[0] ? -1 : 1 : 0 } );  // Sort the stores
	
	       for (var i = 0; i < stores.length; i++) {
	           this.storeSelector.appendChild(oStoresToSort[i][1]);
	       }

	 	   this.storeSelector.removeAttribute('disabled');
		}
		
	},
	
	createStores: function(state) {
		var storeOptions = [];
		var shouldAddStore = true
		var myDelegate = this.delegate;
		var hasShouldAddStore = myDelegate && (typeof myDelegate.shouldAddStoreWithConciergeIdForStateNamed === "function");
		var hasShouldSelectStore = myDelegate && (typeof myDelegate.shouldSelectStoreWithCode_defaultValue_ === "function");
		var hasStoreLink = myDelegate && (typeof myDelegate.storeLinkForStoreWithConciergeIdStateNamed === "function");
		var stores = state.getElementsByTagName('store'), storeArray = [], i=0, countI = stores.length;
		var storeToSelect = this.urlStoreAppleId || this.cookiedStore;

		while(i<countI) {
			storeArray[i] = stores[i++];
		}
		
        storeArray.sort(function(a,b) { 
						var aStoreName = a.getElementsByTagName('city')[0].firstChild.nodeValue,
							bStoreName = b.getElementsByTagName('city')[0].firstChild.nodeValue;
						 return aStoreName!=bStoreName ? aStoreName<bStoreName ? -1 : 1 : 0 
					} );  // Sort the options

		for(var i = 0; i < countI; i++ ) {
			var store = storeArray[i];
			var storeCode = store.getElementsByTagName('appleid')[0].firstChild.nodeValue;
			var storeName = store.getElementsByTagName('city')[0].firstChild.nodeValue + ', ' + store.getElementsByTagName('name')[0].firstChild.nodeValue;
			var selected = (storeCode == storeToSelect) ? true : false;
			var storeSelected = selected;
			
			
			switch(this.linkType) {
				case 'genius':
					var storeLink = 'http://concierge.apple.com/store/' + storeCode;
					break;
				case 'procare':
					var storeLink = '/retail/onetoone/concierge.php?store=' + storeCode;
					break;
				case 'business':
					var storeLink = 'http://concierge.apple.com/biz/' + storeCode;
					break;
				case 'personal':
					var storeLink = 'http://concierge.apple.com/ps/' + storeCode;
					break;
				case 'promo':
					var storeLink = 'http://concierge.apple.com/promo/store/' + storeCode;
					break;
				case 'setup':
					var storeLink = 'http://concierge.apple.com/setup/' + storeCode;
					break;
				case 'workshop':
					var storeLink = 'http://concierge.apple.com/workshops/' + storeCode;
					break;
				case 'phone':
					var storeLink = storeCode;
					break;
				case 'store':
					var storeLink = store.getElementsByTagName('link')[0].firstChild.nodeValue;
					break;
				default:
					var storeLink = store.getElementsByTagName('link')[0].firstChild.nodeValue;
					break;
			}
			
			shouldAddStore = true;
			if(hasShouldAddStore) {
				var stateName = this.stateWithName(state.getAttribute('name')).name;
				shouldAddStore = myDelegate.shouldAddStoreWithConciergeIdForStateNamed(storeCode, stateName);
			}
			if(!shouldAddStore) continue;

			if(hasStoreLink) {
				storeLink = myDelegate.storeLinkForStoreWithConciergeIdStateNamed(storeCode, stateName);
			}
			
			if(hasShouldSelectStore) {
				storeSelected = myDelegate.shouldSelectStoreWithCode_defaultValue_(storeCode,storeSelected);
			}
			
			var storeOption = this.createOption(storeLink, storeName, storeSelected, storeCode);
			if(!storeSelected) {
				this.storeSelector.getElementsByTagName('option')[0].innerHTML = this._selectAStoreOptionLabel;
			}
			else {
				state.setAttribute('selected','selected');
			}
			storeOptions.push(storeOption);
		}
		
		return storeOptions;
	},

	createOption: function(value, name, selected, storeCode) {
		var option = $(document.createElement('option'));
		if(storeCode != '') option.setAttribute('name', storeCode);
		option.setAttribute('value', value);
		if(selected) {
			option.setAttribute('selected','selected');
		}
		option.appendChild(document.createTextNode(name));

		return option;
	},
	sendRequest: function(pageType){
		var phpFile = getPHPFile();

		var lang = document.getElementsByTagName("html")[0].getAttribute('lang');
		var poststr = "appID=" + encodeURI("192") + "&";
		poststr += "overrideauthentication=" + encodeURI("true") + "&";
		poststr += "locale=" + encodeURI(lang ? lang : "en_US");
		var self = this;
		var url = "/retail/scripts/"+phpFile+"?type="+pageType;
        var host = window.location.host;
		//if chinese site, send cross domain request
        if(host.match(/\.cn|cn\./)){
			executeCrossDomainRequest(url,poststr, this.getXMLObj.bind(this)); 
        }
		else {
		new Ajax.Request(url,
		{
		  method:       'post',
		  asynchronous: true,
		  contentType:  'application/x-www-form-urlencoded',
		  encoding:     'UTF-8',
		  parameters:   poststr,
		  connection: 'close',
		  onSuccess: this.getXMLObj.bind(this)
		});
	}
}
	
};//storeSelector class ends

CrossDomainRequestCallback = [];
function executeCrossDomainRequest(url,urlArguments, callbackFunction) {

	var callback = function(value) {
		var response = {responseObject: value};
		callbackFunction(response);
	},
	callbackNumber,
	callbackString,
	scriptNode,
	head;
	
	CrossDomainRequestCallback.push(callback);
	callbackNumber = CrossDomainRequestCallback.length - 1;

	callbackString = encodeURIComponent('CrossDomainRequestCallback[' + callbackNumber + ']');

	scriptNode = document.createElement('script');
	scriptNode.setAttribute('charset', 'utf-8');
	scriptNode.setAttribute('type', 'text/javascript');
	
	if(url.indexOf("?") === -1) {
		url = url+"?"+urlArguments;
	}
	else {
		url = url+"&"+urlArguments;
	}
	
	url = url.replace(/&callback/g, "") + '&callback=' + callbackString;
	

    // Prevent client from passing along their own callback attribute to the iTunes Search Service
	scriptNode.setAttribute('src', url);

	head = document.getElementsByTagName('head')[0];

	// this.started = new Date();

	head.appendChild(scriptNode);
	head = null;
}


// Cookie
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
	  path = '; path=/';
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};


getUrlVars= function(){
	var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

/*if url has 'mode=dev' set, use dev db else use production db*/ 
getPHPFile= function()
{
	var query = getUrlVars();
	return  ((query.indexOf("mode")>-1 && query["mode"]=="dev") ? "concierge_data_dev.php" : "concierge_data.php");
}

