// Find a JJ javascript functions
   
////////////////////////////////////////////////////////////////////
// Global Variables
///////////////////////////////////////////////////////////////////

var map;

// Location Arrays
var points = [];
var gmarkers = [];
var gmarkershtml = [];
var storeids = [];

// Flags
var mapInitialized = 0;
var storesPlotted = 0;
var listenersInitialized = 0;
var plotAllView = 0;


// HTML Builders
var listHTML;
var plotAllHTML;

// Counters
var i = 0;

// Grab querystring variables
var state;
var zip
var city

if(getQueryVariable('state') == false){
    state = "";
}else{
    state = getQueryVariable('state');
}

if(getQueryVariable('city') == false){
    city = "";
}else{
    city = getQueryVariable('city');
    city = city.replace("%20", " ");
    city = city.replace("'", "");
}

if(getQueryVariable('zip') == false){
    zip = "";
    var initLookup = "../services/findajjs_lookup.asmx/getLocationsByCityState?city=" + city + "&state=" + state;
}else{
    zip = getQueryVariable('zip');
    var initLookup = "../services/findajjs_lookup.asmx/getLocationsByZip?zip=" + zip;
}
    
////////////////////////////////////////////////////////////////////
// Initialize page data
////////////////////////////////////////////////////////////////////

function initialize() {	
	// Populate City & zip fields:
	document.getElementById('city').value = city;
	document.getElementById('zip').value = zip;
	// Populate state field if used.
	var ddstate = state;
	if(ddstate !=''){
		var stateSelect = document.getElementById('state');
		for (var ss = 0; ss < 35; ss++) {
			if(stateSelect.options[ss].value == state){
				stateSelect.options[ss].selected = true;
			}
		}
	}
	// Fetch initial results based on search.
	var theRequest = GXmlHttp.create();
	theRequest.open("GET", initLookup, false);
	theRequest.send(null);
	var theXML = theRequest.responseXML;
	points.length = 0;
	var errors = theXML.documentElement.getElementsByTagName("error");
	if(errors.length == 1){
		var message = GXml.value(theXML.documentElement.getElementsByTagName("error")[0]);
			listHTML="";
			listHTML += "<div class='listingContainer'><div class='listingIcon'><img border='0' src='../images/findAJJs/icon_exclaim.gif' alt='' /><\/div>";
			listHTML += "<div class='errorInfo'><span class='error'>There were errors in your Search request. <strong>" + message + "<\/strong><\/span><\/div>";
			document.getElementById("scrollable").innerHTML = listHTML;
			document.getElementById('wrap').style.display = 'none';

	}else{
		var locations = theXML.documentElement.getElementsByTagName("locationinfo");
		var totalLat = 0;
		var totalLong = 0;
		var totalNumber = 0;
		listHTML="";
		plotAllHTML="";
		if(locations.length < 4){
			document.getElementById('wrap').style.display = 'none';
		}
		for (var z = 0; z < locations.length; z++) {
			var storeid = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("storeid")[0]);
			var storename = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("storename")[0]);
			var hours = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("hours")[0]);
			var address = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("address")[0]);
			var address2 = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("address2")[0]);
			var telephone = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("telephone")[0]);
			var lat = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("lat")[0]);
			var lng = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("long")[0]);
			var allowOrderOnline = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("allowOnlineOrdering")[0]);
			var theDistance = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("distance")[0]);
			var point = new GLatLng(parseFloat(lat),parseFloat(lng));
			
			storenameescapeda = storename.replace("'","&#39;");
			addressescapeda = address.replace("'","&#39;");
			address2escapeda = address2.replace("'","&#39;");			
			var plusEsc="+";
			var storenameescaped = storenameescapeda.replace(/ /g,plusEsc);
			var addressescaped = addressescapeda.replace(/ /g,plusEsc);
			var address2escaped = address2escapeda.replace(/ /g,plusEsc);
			
			points.push(point);
			storeids.push(storeid);
			listHTML += "<table class='listingContainer'><tr><td class='listingIcon' valign='top'>";
			listHTML += "<a href='javascript:listClick(" + lat + "," + lng + "," + z + ")' onfocus='this.blur();' title='Map It'>";
			listHTML += "Map It<\/a><\/td>";
			listHTML += "<td class='listingInfo'>";
			listHTML += "<a class='listingHeader' href='javascript:listClick("+ lat +","+ lng +","+ z +")'>";
			listHTML += storename + "<\/a><br/>"; // (" + theDistance + " mi)
			listHTML += address + "<br/>Tel: " + telephone + "<br/>";
			listHTML += "<a class='more_link' title='Make this my JJ' href='javascript:updateNav(\"" + allowOrderOnline + "\",\"" + storeid + "\");showStoreInfo(\"" + storeid + "\");showStoreInfoAlt();tb_show(\"\", \"myJJConfirm.aspx?height=342&amp;width=403&amp;city=" + storenameescaped + "&amp;telephone=" + telephone + "&amp;storeID=" +  storeid + "&amp;lat=" + lat + "&amp;lng=" + lng + "&amp;z=" + z + "&amp;address=" + addressescaped + "&amp;address2=" + address2escaped + "&amp;oo=" + allowOrderOnline + "\");'>MAKE THIS MY JJ<\/a>";
			listHTML += "<\/td><\/tr><\/table>";
    		totalNumber = totalNumber + 1;
			totalLat = parseFloat(totalLat) + parseFloat(lat);
			totalLong = parseFloat(totalLong) + parseFloat(lng);
			bubbleString = "<div id='location_holder' style='position: relative;'>Jimmy John's " + storename + "<br/>" + address + "<br />";
			if(address2 != '')
			{
			    bubbleString += address2 + "<br />";
			}
			bubbleString += telephone +"<br/><br/><a class='more_link' href='javascript:updateNav(\"" + allowOrderOnline + "\",\"" + storeid + "\");showStoreInfo(\"" + storeid + "\");showStoreInfoAlt();tb_show(\"\", \"myJJConfirm.aspx?height=342&amp;width=403&amp;city=" + storenameescaped + "&amp;telephone=" + telephone + "&amp;storeID=" +  storeid + "&amp;address=" + addressescaped + "&amp;address2=" + address2escaped + "&amp;oo=" + allowOrderOnline + "\");'>MAKE THIS MY JJ<\/a><\/div>";
			var infoTabs = [
				 new GInfoWindowTab("Location", bubbleString),
				 new GInfoWindowTab("Hours", "<div id='hours_holder' style='position: relative;'>Store Hours:<br/>" + hours +"<br/><br/><a class='more_link' href='javascript:updateNav(\"" + allowOrderOnline + "\",\"" + storeid + "\");showStoreInfo(\"" + storeid + "\");showStoreInfoAlt();tb_show(\"\", \"myJJConfirm.aspx?height=342&amp;width=403&amp;city=" + storenameescaped + "&amp;telephone=" + telephone + "&amp;storeID=" +  storeid + "&amp;address=" + addressescaped + "&amp;address2=" + address2escaped + "&amp;oo=" + allowOrderOnline +  "\");'>MAKE THIS MY JJ<\/a><\/div>")
			];
			gmarkershtml[z] = infoTabs;
		}
		var averageLat = parseFloat(totalLat)/totalNumber;
		var averageLong = totalLong/totalNumber;
		plotAllHTML += "<div id='mapAllButton'><a class='more_link' title='Map All' href='javascript:plotAllClick(" + averageLat + "," + averageLong + ");'>MAP ALL<\/a></div>";
		document.getElementById("scrollable").innerHTML = listHTML;
		document.getElementById("thePlotAll").innerHTML = plotAllHTML;
	}

	initializeScroller();
}


///////////////////////////////////////////////////////////////////
// Initialize Map
////////////////////////////////////////////////////////////////////

function initializeMap(){
	//alert("init map");
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
	    var mt = map.getMapTypes();
		for (var j=0; j<mt.length; j++) {
			mt[j].getMinimumResolution = function() {return 10;}
			mt[j].getMaximumResolution = function() {return 15;}
  		}
   		map.addControl(new GSmallMapControl());
	mapInitialized = 1;
	}

}
	
	
////////////////////////////////////////////////////////////////////
// Initialize Map Move and Drag listeners
////////////////////////////////////////////////////////////////////

function initializeListeners(){
	GEvent.addListener(map, 'moveend', function() {
 	   		if(map.getZoom()<14){
 				var center = map.getCenter();
			var center_y = center.lat();
    		var center_x = center.lng();
  			getStores("../services/findajjs_lookup.asmx/getLocationsByLatLong?lat=" + center_y + "&lng=" + center_x);
		}
  		listenersInitialized = 1;
  	});
}
	
	
////////////////////////////////////////////////////////////////////
// Event handler for user click on a listing entry
////////////////////////////////////////////////////////////////////

   function listClick(listClickLat,listClickLong,listClickIndex){
	// If the map has not been initialized, initialize it.
	if(mapInitialized == 0){initializeMap();}
	// Close any open popup info balloons
	map.closeInfoWindow();
	// Center Map on store's lat/long
	map.setCenter(new GLatLng(parseFloat(listClickLat), parseFloat(listClickLong)), 14);
	// Check if stores have been plotted yet.  If not: Plot them!
	if (storesPlotted == 0){plotPoints();}
	// Open the pop up balloon for the clicked store.
	gmarkers[listClickIndex].openInfoWindowTabsHtml(gmarkershtml[listClickIndex]);
	// Check to see if the map listeners have been initialized.
	if (listenersInitialized == 0){initializeListeners();}
}


////////////////////////////////////////////////////////////////////
// Event handler for user click on 'Plot All'
////////////////////////////////////////////////////////////////////

function plotAllClick(plotalllat,plotalllong) {
	// Set flag indicating that map is in 'Plot All' mode.
	plotAllView = 1;
	// If the map has not been initialized, initialize it.
	if (mapInitialized == 0){initializeMap();}
	// Close any open popup info balloons
	map.closeInfoWindow();
	// Find the closest authorized zoom level that displays all points.
	var plotAllBounds = new GLatLngBounds();
	for (var z = 0; z < points.length; z++) {plotAllBounds.extend(points[z]);}
	var plotallzoom = map.getBoundsZoomLevel(plotAllBounds);
	map.setCenter(new GLatLng(parseFloat(plotalllat), parseFloat(plotalllong)), plotallzoom);
	// Check if stores have been plotted yet.  If not: Plot them!
	if (storesPlotted == 0){plotPoints();}
	// Check to see if the map listeners have been initialized.
	if (listenersInitialized == 0){initializeListeners();}
}


////////////////////////////////////////////////////////////////////
// Plots all points in current array
////////////////////////////////////////////////////////////////////

function plotPoints(){
	for (var z = 0; z < points.length; z++) {createMarker(points[z], z);}
	storesPlotted = 1;
}
	
	
////////////////////////////////////////////////////////////////////
// Draws a JJ Point Marker on the Map
////////////////////////////////////////////////////////////////////

function createMarker(point, theIndex) {
	var icon = new GIcon();
	icon.image = "../images/findAJJs/map_logo.png";
	icon.shadow = "";
	icon.iconSize = new GSize(60, 84);
	icon.shadowSize = new GSize(0, 0);
	icon.iconAnchor = new GPoint(30, 75);
	icon.infoWindowAnchor = new GPoint(30, 11);
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, 'click', function() {
		map.closeInfoWindow();
		marker.openInfoWindowTabsHtml(gmarkershtml[theIndex]);
	});
	gmarkers[theIndex] = marker;
	map.addOverlay(marker);
	i++
}
	
	
////////////////////////////////////////////////////////////////////
// Fetch store XML based on passed querystring
////////////////////////////////////////////////////////////////////

function getStores(myPath){
	var theRequest = GXmlHttp.create();
	theRequest.open("GET", myPath, false);
	theRequest.send(null);
	var theXML = theRequest.responseXML;
	var locations = theXML.documentElement.getElementsByTagName("locationinfo");
	for (var z = 0; z < locations.length; z++) {
		var storeid = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("storeid")[0]);
		var storename = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("storename")[0]);
		var hours = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("hours")[0]);
		var address = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("address")[0]);
		var address2 = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("address2")[0]);
		var telephone = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("telephone")[0]);
		var allowOrderOnline = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("allowOnlineOrdering")[0]);
		var lat = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("lat")[0]);
		var lng = GXml.value(theXML.documentElement.getElementsByTagName("locationinfo")[z].getElementsByTagName("long")[0]);
		var point = new GLatLng(parseFloat(lat),parseFloat(lng));
		var testArray = points;
		storenameescaped = storename.replace("'","&#39;");
		addressescaped = address.replace("'","&#39;");
		address2escaped = address2.replace("'","&#39;");
		// Check if in array
		if(storeid in oc(storeids)){
		}else{
			points.push(point);
			bubbleString = "<div id='location_holder' style='position: relative;'>Jimmy John's " + storename + "<br/>" + address + "<br />";
			if(address2 != '')
			{
			    bubbleString += address2 + "<br />";
			}
			bubbleString += telephone +"<br/><br/><a class='more_link' href='javascript:updateNav(\"" + allowOrderOnline + "\",\"" + storeid + "\");showStoreInfo(\"" + storeid + "\");showStoreInfoAlt();tb_show(\"\", \"myJJConfirm.aspx?height=342&amp;width=403&amp;city=" + storenameescaped + "&amp;address=" + addressescaped + "&amp;address2=" + address2escaped + "&amp;telephone=" + telephone + "&amp;storeID=" +  storeid + "&amp;oo=" +  allowOrderOnline + "\");'>MAKE THIS MY JJ<\/a><\/div>";
            var infoTabs = [
	  			new GInfoWindowTab("Location", bubbleString),
	 			new GInfoWindowTab("Hours", "<div style='position: relative;'>Store Hours:<br/>" + hours +"<br/><br/><a href='javascript:updateNav(\"" + allowOrderOnline + "\",\"" + storeid + "\");showStoreInfo(\"" + storeid + "\");showStoreInfoAlt();tb_show(\"\", \"myJJConfirm.aspx?height=342&amp;width=403&amp;city=" + storenameescaped + "&amp;address=" + addressescaped + "&amp;telephone=" + telephone + "&amp;storeID=" +  storeid + "&amp;oo=" +  allowOrderOnline + "\");'><img src='../images/findAJJs/btn_make_this.jpg' alt='' width='105' height='11' border'0' /><\/a><\/div>")
			];
			gmarkershtml[i] = infoTabs;
			createMarker(point, i);

		}
	}
}	

	
////////////////////////////////////////////////////////////////////
// QUERY GRAB
////////////////////////////////////////////////////////////////////

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == variable) {
		return pair[1];
	    }
	}
	return false;
}


////////////////////////////////////////////////////////////////////
// Form Validation - Landing
////////////////////////////////////////////////////////////////////

function sndReq() {
	// Grab input
    inputZip = document.getElementById('zipLanding').value
    inputCity = document.getElementById('ctl00_ContentPlaceHolder2_cityList').value
    inputState = document.getElementById('ctl00_ContentPlaceHolder2_stateList').value

	if(inputZip == ''){
		//Zip field is blank
		if(inputState=='' || inputCity==''){
			alert('Please enter either a valid 5-digit numeric ZIP code or both a city and state.');
		}else{
			window.location = 'map.aspx?city=' + inputCity + '&state=' + inputState;
		}
	}else if(inputZip != ''){
	//Zip field is not blank
		if(inputZip.length < 5 || isNaN(inputZip)== true){
			// Zip is invalid; check city & state.
			if(inputState=='' || inputCity==''){
				alert('Please enter either a valid 5-digit numeric ZIP code or both a city and state.');
			}else{
				window.location = 'map.aspx?city=' + inputCity + '&state=' + inputState;
			}
		}else{
			window.location = 'map.aspx?zip=' + inputZip;
		}
	}
}
	
	
////////////////////////////////////////////////////////////////////
// Form Validation  map
////////////////////////////////////////////////////////////////////

function sndReq_map() {
	// Grab input
	inputZip = document.getElementById('zip').value
	inputCity = document.getElementById('city').value
	inputState = document.getElementById('state').value

	if(inputZip == ''){
		//Zip field is blank
		if(inputState=='' || inputCity==''){
			doError();
		}else{
			window.location = 'map.aspx?city=' + inputCity + '&state=' + inputState;
		}
	}else if(inputZip != ''){
	//Zip field is not blank
		if(inputZip.length < 5 || isNaN(inputZip)== true){
			// Zip is invalid; check city & state.
			if(inputState=='' || inputCity==''){
				doError();
			}else{
				window.location = 'map.aspx?city=' + inputCity + '&state=' + inputState;
			}
		}else{
			window.location = 'map.aspx?zip=' + inputZip;
		}
	}
}


////////////////////////////////////////////////////////////////////
// Clear Zip
////////////////////////////////////////////////////////////////////

function clearZip()
{
  document.getElementById('zip').value = '';
}

////////////////////////////////////////////////////////////////////
// Clear Zip Landing
////////////////////////////////////////////////////////////////////

function clearZipLanding() {
    document.getElementById('zipLanding').value = '';
}


////////////////////////////////////////////////////////////////////
// Converts array to object for fast comparison
////////////////////////////////////////////////////////////////////

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

   
////////////////////////////////////////////////////////////////////
// Do Error on Invalid Form
////////////////////////////////////////////////////////////////////

function doError(){
	listHTML="";
	listHTML += "<div class='listingContainer'><div class='listingIcon'><img border='0' src='../images/findAJJs/icon_exclaim.gif' alt='' /><\/div>";
	listHTML += "<div class='errorInfo'><span class='error'>There were errors in your Search request. <strong>Please enter either a valid 5-digit numeric ZIP code or both a city and state.<\/strong><\/span><\/div>";
	slider.setValue(0);
	document.getElementById("scrollable").innerHTML = listHTML;
	document.getElementById('wrap').style.display = 'none';
	//document.getElementById('btn_plot_all').style.display = 'none';
}

////////////////////////////////////////////////////////////////////
// submit on enter
////////////////////////////////////////////////////////////////////

function submitEnter(e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   sndReq_map();
   return false;
   }
else
   return true;
}


////////////////////////////////////////////////////////////////////
// submit on enter (Landing)
////////////////////////////////////////////////////////////////////

function submitEnterLanding(e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13 || keycode == 3)
   {
   sndReq();
   return false;
   }
else
   return true;
}


////////////////////////////////////////////////////////////////////
// Make this my JJ - set map if not set.
////////////////////////////////////////////////////////////////////

function doClose(lat, lng, z){
    if(mapInitialized ==0){
        listClick(lat,lng,z);
    }
}

////////////////////////////////////////////////////////////////////
// Update order online element of global nav
////////////////////////////////////////////////////////////////////

function updateNav(allowed, number){
    if(allowed == 'True'){
        document.getElementById('nav_order').innerHTML = '<a id="ctl00_GlobalNav1_hypOrder" href="http://online.jimmyjohns.com?store=' + number + '" title="Order Online" onfocus="this.blur();"/>';
        document.getElementById('nav_catering').innerHTML = '<a id="ctl00_GlobalNav1_hypCatering" href="http://online.jimmyjohns.com?store=' + number + '" title="Catering" onfocus="this.blur();"/>';
    }else{
        document.getElementById('nav_order').innerHTML = '<a id="ctl00_GlobalNav1_hypOrder" href="../orderOnline/orderOnline.aspx" title="Order Online" onfocus="this.blur();"/>';
        document.getElementById('nav_catering').innerHTML = '<a id="ctl00_GlobalNav1_hypCatering" href="../catering/catering.aspx" title="Catering" onfocus="this.blur();"/>';
    }
}