var scriptexternalurl = '/app/site/hosting/scriptlet.nl?script=40&deploy=1&compid=839638&h=3d88925d373495cc27e0';
var scriptexternalurl_POST = '/app/site/hosting/scriptlet.nl?script=40&deploy=2&compid=839638&h=7a5f44a9beff4ce78e80';
var loadergif = "/site/storelocator/loader.gif";
// STORE
function Store(pAttributeList){
	
	this.attributes = pAttributeList;
	
	this.setFeatured = function(){
		this.attributes['featured'] = true;
	}
	this.setUnFeatured = function(){
		this.attributes['featured'] = false;
	}
	this.setStoreLineHTML = function(pHTML){
		this.attributes['storeline'] = pHTML;
	}
	this.setMapBalloonHTML = function(pHTML){
		this.attributes['balloonhtml'] = pHTML;
	}
	
}

// MANAGER
function StoreLocatorManager(){
	this.stores = new Array();
	this.featuredStores = new Array();	
	
	this.loadScriptInfo = function(pZip, pCountry, pRadius){
		var headID = document.getElementsByTagName("head")[0];         
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src ="http://www.suitecommerceapps.com/StoreLocatorApp/getzips.jsp?zipcode="+ pZip +"&radius=" + pRadius  + "&country=" + pCountry;
		headID.appendChild(newScript);
	}
	
	this.obtainOnlineStores = function(){
		this.stores = new Array();
		var ssUrl = scriptexternalurl;
		var country = "ca";
		
		var findby = "findby=online";
		var country = "country=ca";
		wsUrl = ssUrl + "&" + findby + "&zipcodes=&" + country;
		
		req = AJAXObject();
		req.onreadystatechange = handle_suiteLet_onlinestores;
		
		if(wsUrl.length < 250){
			req.open('GET',wsUrl, true)
			req.send(null);
		}else{
			var params =  findby + "&zipcodes=&" + country;
			req.open('POST',scriptexternalurl_POST, true)
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.send(params);

		}
	}
	
	this.obtainStoresByCityState = function(pCity, pState, pCountry){
		resetMap();
		
		this.stores = new Array();
		var ssUrl = scriptexternalurl;
		
		var country = document.getElementById("selectCountry").value;
		
		var ss_selector = document.getElementById("select_SS").value;
		var ss = "scsls=" + ss_selector;
		
		var zipcodes = "zipcodes=";
		var findby = "findby=";
		var filterCity = "city="+pCity;
		var filterState = "state="+pState;
		
		if(pCity.length > 0){
			findby += "city" + "&" + filterCity; 
		}else{
			if(pState.length > 0){
				findby += "state" + "&" + filterState ;
			}	
		}
		
		
		wsUrl = ssUrl + "&" + findby + "&" + zipcodes + "&" + ss;
		
		req = AJAXObject();
		req.onreadystatechange = handle_suiteLet;
		
		if(wsUrl.length < 250){
			req.open('GET',wsUrl, true)
			req.send(null);
		}else{
			var params =  findby + "&" + zipcodes + "&" + ss;
			req.open('POST',scriptexternalurl_POST, true)
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.send(params);

		}
	}
	
	this.obtainStoresByCountry = function(pCountry){
		resetMap();
		
		this.stores = new Array();
		var ssUrl = scriptexternalurl;
		var country = pCountry;
		
		var ss_selector = document.getElementById("select_SS").value;
		var ss = "scsls=" + ss_selector;
		
		var zipcodes = "zipcodes=";
		var findby = "findby=";
		var filterCountry = "country="+country;
		//var filterState = "state="+pState;
		
		findby += "country" + "&" + filterCountry; 
		
		wsUrl = ssUrl + "&" + findby + "&" + zipcodes + "&" + ss;
		
		req = AJAXObject();
		req.onreadystatechange = handle_suiteLet;
		
		if(wsUrl.length < 250){
			req.open('GET',wsUrl, true)
			req.send(null);
		}else{
			var params =  findby + "&" + zipcodes + "&" + ss;
			req.open('POST',scriptexternalurl_POST, true)
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.send(params);

		}
	}
	
	this.obtainStores = function(pZipArray){
		resetMap();
		
		this.stores = new Array();
		//var ssUrl = '/app/site/hosting/scriptlet.nl?script=12&deploy=1&compid=408900&h=fcc014d38076237afbc8'; 
		var ssUrl = scriptexternalurl;
		var country = document.getElementById("selectCountry").value;
		var findby = "findby=zipcode&country="+ country;
		var zipcodes = "zipcodes="+pZipArray.join("::");
		
		var ss_selector = document.getElementById("select_SS").value;
		var ss = "scsls=" + ss_selector;
		
		wsUrl = ssUrl + "&" + findby + "&" + zipcodes + "&" + ss;
		
		req = AJAXObject();
		req.onreadystatechange = handle_suiteLet;
		
		if(wsUrl.length < 250){
			req.open('GET',wsUrl, true)
			req.send(null);
		}else{
			var params =  findby + "&" + zipcodes+ "&" + ss;
			req.open('POST',scriptexternalurl_POST, true)
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.send(params);

		}
		
		
	}
	
	this.initializeAjax = function(){
		//var wsUrl = '/app/site/hosting/scriptlet.nl?script=12&deploy=1&compid=408900&h=fcc014d38076237afbc8'; 
		var wsUrl = scriptexternalurl;
		var findby = "&findby=zipcode&country=us";
		var zipcodes = "&zipcodes=97701::97702";
		wsUrl = wsUrl + findby + zipcodes;
		
		req = AJAXObject();
		req.onreadystatechange = handle_suiteLet;
		req.open('GET',wsUrl, true)
		req.send(null);
		
		function handle_suiteLet(){
			if(req.readyState == 4) {
				if(req.status == 200) {
					var data = req.responseText;
					//manager.processStores(data);
					//uiManager.drawStoreList();
				} else {
				  console.log("There has been an issue with the AJAX");
				}
				//req = null;
			}
		}

		
	}
	
	this.processStores = function(pSuiteLetTxt){
		this.stores = evalResponseList(unescape(pSuiteLetTxt));
	}
	
}
var req;
function handle_suiteLet(){
	if(req.readyState == 4) {
		if(req.status == 200) {
			var data = req.responseText;
			if(data.length > 0){
				manager.processStores(data);
				uiManager.drawStoreList();
			}else{
				uiManager.hideLoadingGif();
				uiManager.clearStoresDrawed();
				uiManager.mapDrawerNoStoresFound("on");
				setTimeout("uiManager.mapDrawerNoStoresFound('off')", 5000);
			}
		} else {
			uiManager.hideLoadingGif();
			console.log("There has been an issue with the AJAX");
		}
	}
}
function handle_suiteLet_onlinestores(){
	if(req.readyState == 4) {
		if(req.status == 200) {
			var data = req.responseText;
			if(data.length > 0){
				manager.processStores(data);
				uiManager.drawOnlineStoreList();
			}else{
				uiManager.hideLoadingGif();
			}
		} else {
			uiManager.hideLoadingGif();
			console.log("There has been an issue with the AJAX");
		}
	}
}


/**
 *	AJAXObject Function
 *	@description	Create the XMLHttpRequest according to the browser
 *	@return			XMLHttpRequest
 */
function AJAXObject() {
	var httpobj = null;
	if(window.ActiveXObject) {
		httpobj = new window.ActiveXObject('Microsoft.XMLHTTP');
	} else if(window.XMLHttpRequest) {
		httpobj = new XMLHttpRequest();
	}
	return httpobj;
}

/**
* GRAPHICAL METHODS - DRAWING RELATED METHODS
* CREATED BY: Charlie, SuiteCommerce Inc.
* LAST MODIFIED BY: 
* DATE : 2/14/2010
*/

function UIManager(pManager, pResultsDivId, pSearchMessageDiv, pCellTemplateId, pMsgBalloonTemplateID){
	this.storesManager = pManager;
	this.listDivId = pResultsDivId;
	this.searchmessagedivid = pSearchMessageDiv;
	this.cellTemplateId = pCellTemplateId;
	this.balloonTemplateId = pMsgBalloonTemplateID;
	
	this.storesfound = 0;
	this.interval = 0;
	
	this.drawOnlineStoreList = function(){
		this.storesfound = 0;
		this.interval = 0;
		this.hideLoadingGif();
		var resultBox = document.getElementById(this.listDivId);
		resultBox.innerHTML = "";
		for(var i=0;i<this.storesManager.stores.length;i++){
			if(this.storesManager.stores[i].attributes['url']){
				resultBox.innerHTML += this.fillRowTemplate(this.storesManager.stores[i],i);
			}
		}
	}
	
	this.drawStoreList = function(){
		this.storesfound = 0;
		this.interval = 0;
		this.hideLoadingGif();
		var resultBox = document.getElementById(this.listDivId);
		resultBox.innerHTML = "";
		this.drawMapStores();
		for(var i=0;i<this.storesManager.stores.length;i++){
			if(this.storesManager.stores[i].attributes['altname']){
				resultBox.innerHTML += this.fillRowTemplate(this.storesManager.stores[i],i);
			}
		}
	}
	
	this.clearStoresDrawed = function(){
		document.getElementById(this.listDivId).innerHTML = "";
	}
	
	this.drawMapStores = function(){
		this.mapDrawerMessage("on");
		this.interval = setInterval("uiManager.drawStore()",1000);
	}
	
	this.mapDrawerMessage = function(pOnOff){
		if(pOnOff == "on"){
			var storeQty = this.storesManager.stores.length;
			if(storeQty > 10) storeQty = 10;
			var div = document.createElement("div");
			div.className = "drawingmapmessage"
			div.id = "drawingmapmessage"
			div.innerHTML = "Drawing the "+ storeQty +" nearest stores... 0/" + storeQty + " <br/>";
			var img = document.createElement("img");
			img.src = loadergif;
			img.id = "marker-loader";
			div.appendChild(img);
			document.getElementById("map-screen").appendChild(div);
		}else{
			var childDiv = document.getElementById("drawingmapmessage");
			document.getElementById("map-screen").removeChild(childDiv);
		}
	}
	
	this.mapDrawerNoStoresFound = function(pOnOff){
		if(pOnOff == "on"){
			var div = document.createElement("div");
			div.className = "drawingmapmessage"
			div.id = "drawingmapmessage"
			div.innerHTML = "Sorry, No Stores found..";
			document.getElementById("map-screen").appendChild(div);	
		}else{
			var childDiv = document.getElementById("drawingmapmessage");
			document.getElementById("map-screen").removeChild(childDiv);
		}
	}
	
	this.increaseMapDrawerMessage = function(){
		var reg = new RegExp(/(\d)\/(\d+)/);
		var res = document.getElementById("drawingmapmessage").innerHTML.match(reg);
		var newVal = parseInt(res[1]) + 1;
		var total = parseInt(res[2]);
		document.getElementById("drawingmapmessage").innerHTML = document.getElementById("drawingmapmessage").innerHTML.replace(/\d+\/\d+/, newVal+"/"+total);
	}
	
	this.drawStore = function(pStore){
		if(this.storesfound < this.storesManager.stores.length && this.storesfound < 10){
			var currentStore = this.storesManager.stores[this.storesfound];
			currentStore.setMapBalloonHTML(this.fillMessageTemplate(currentStore));
			showAddress(currentStore);
			this.increaseMapDrawerMessage();
			this.storesfound++;
			markerManager.refresh();
		}else{
			this.mapDrawerMessage("off");
			clearInterval(this.interval);
		}
	}
	
	this.fillRowTemplate = function(pStore, pLineNumber){
		var templateDiv = unescape(document.getElementById(this.cellTemplateId).innerHTML);
		var regex = new RegExp(/\{\![^\}]*\}/gim);
		var variables = templateDiv.match(regex);
		for(var i=0;i<variables.length;i++){
			var variableName = variables[i].replace(/[\{\}\!]/gi,"");
			var attributeValue = pStore.attributes[variableName];
			if(attributeValue != null){
				templateDiv = templateDiv.replace(variables[i],pStore.attributes[variableName]);
			}else{
				//console.log(variableName + " not existing at SavedSearch");
			}
			templateDiv = templateDiv.replace("resultRow_id","resultRow_"+pLineNumber)
			templateDiv = templateDiv.replace(/oIDo/ig,pLineNumber)
		}
		return templateDiv;

	}
	
	this.fillMessageTemplate = function(pStore){
		var templateDiv = document.getElementById(this.balloonTemplateId).innerHTML;
		var regex = new RegExp(/\{\![^\}]*\}/gim);
		var variables = templateDiv.match(regex);
		for(var i=0;i<variables.length;i++){
			var variableName = variables[i].replace(/[\{\}\!]/gi,"");
			var attributeValue = pStore.attributes[variableName];
			if(attributeValue != null){
				templateDiv = templateDiv.replace(variables[i],pStore.attributes[variableName]);
			}else{
				//console.log(variableName + " not existing at SavedSearch");
			}
		}
		return templateDiv;
	}
	
	this.saveResultBox = function(pHTML){
		var messageBoxes = document.getElementById(this.mapMessagesId).innerHTML;
		var newHTML =  pHTML.replace(/resultRow_/gi,"resultBox_Row_");
		messageBoxes += newHTML;
		document.getElementById(this.mapMessagesId).innerHTML = messageBoxes;
	}
	
	this.showLoadingGif = function(pOnline){
		if(document.getElementById(this.searchmessagedivid).innerHTML.indexOf("Please Wait") == -1){
			var div = document.createElement("div");
			div.className = "waitingmessage"
			if(pOnline){
				div.innerHTML = "Please Wait while we search for our favourite eStores... <br />Thank you for your patience, this might take some time <br />";
			}else{
				div.innerHTML = "Please Wait while we search for the Stores near by your location... <br />Thank you for your patience, this might take some time <br />";
			}
			var img = document.createElement("img");
			img.src = loadergif;
			img.id = "loading-gif";
			div.appendChild(img);
			document.getElementById(this.searchmessagedivid).appendChild(div);
		}
	}
	
	this.hideLoadingGif = function(){
		document.getElementById(this.searchmessagedivid).innerHTML = "";
	}
	
}

function showDetails(pIntStoreID){
	markers[pIntStoreID].openInfoWindowHtml(uiManager.storesManager.stores[pIntStoreID].attributes['balloonhtml']);
}

function gotoDirections(pIntStoreID){
	var storeCoords = markers[pIntStoreID].getPoint().lat() + "," + markers[pIntStoreID].getPoint().lng();
	var storeAddress = uiManager.storesManager.stores[pIntStoreID].attributes['address'];
	var yourehereZip = document.getElementById("zipCodeInput").value;
	document.location.href = "/store-locator-get-directions?dto="+escape(storeAddress)+"&dfrom="+yourehereZip + "&dll="+ escape(storeCoords);
}

function hiLigth(pIntStoreID){
	//document.location.href= "#map-screen";
	showTooltip(markers[pIntStoreID]);
}

function showTooltip(marker) {
	var tooltip = document.getElementById("tooltip_div");
    document.getElementById("tooltip_div").innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function evalResponseList(pTxt){
	var storelist = new Array();
	var stores = pTxt.split(":x:");
	for(var i=0;i<stores.length;i++){
		var store = evalResposeStore(stores[i]);
		storelist.push(store);
	}
	return storelist;
}

function evalResposeStore(pTxt){
	var atts = new Array();
	var storeatts = pTxt.split(":o:");
	for(var j=0;j<storeatts.length;j++){
		var attLine = storeatts[j].split(":y:");
		atts[attLine[0]] = attLine[1];
	}
	return new Store(atts);
}
