var mapobject;
var geocoder = new GClientGeocoder();
var isInitialized = false;
var pZip;
var userLat;
var userLng;
var storeIDArray = new Array();
var locationArray = new Array();
var distanceArray = new Array();
var storeNameArray = new Array();
var hoursArray = new Array();
var phoneArray = new Array();
var contentArray = new Array();
var MovedSplitArray = new Array();
var resultSplitArray = new Array();
var iRecurseIndex = 0;
var formPostedZip;
var sortAlphabetically = 0;
var isntUsingDirections = false;
var isLessThan1k = false;
var isUsingZip = false;

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}
function initialize() {
  if (GBrowserIsCompatible()) {
	mapobject = new GMap2(document.getElementById("map_canvas"));
	mapobject.setCenter(new GLatLng(40.50, 80.22), 1);
	mapobject.setUIToDefault();
	isInitialized = true;
	isLessThan1k = false;
  }
}
function LoadMap(divID,locations,content,postZip,sortAlpha,useDirections) {
	initialize();
	contentArray = content;
	isntUsingDirections = useDirections;
	sortAlphabetically = sortAlpha;
	geocoder.getLocations(postZip, function(response) {
		place = response.Placemark[0];
		userLat = place.Point.coordinates[1];
		userLng = place.Point.coordinates[0];
		
		// create a latlng object of the users zip for optimization
		pZip = new GLatLng(userLat,userLng); //postZip;
		mapobject.setCenter(pZip,7);
		GrabDirections(locations);
	});
}
function LoadDetailMap(loc) {
	if (GBrowserIsCompatible()) {
		mapobject = new GMap2(document.getElementById("detail_map"));
		// find the store
		geocoder.getLocations(loc, function(res) {
			var p = res.Placemark[0];
			var pnt = new GLatLng(p.Point.coordinates[1], p.Point.coordinates[0]);
			mapobject.setCenter(pnt, 15);
			mapobject.setUIToDefault();
			isInitialized = true;
			
			// create the marker
			var icon = MapIconMaker.createLabeledMarkerIcon({addStar: true, label: "", primaryColor: "#97401b"});
			// crete a marker
			var marker = new GMarker(pnt, {icon: icon});			
								
			// add to the map
			mapobject.addOverlay(marker);	
		});
	}	
}
function ShowDirectionsForm() {
	jQuery('#directionsContainer').show("fast");
}
function LoadDirections(dirs) {
	var fromAddress = jQuery('#directionsFrom').val();
	var directionsPanel = document.getElementById('directionsContainer');
	var directions;
	
	// clear the previous content from the div
	directionsPanel.innerHTML = "";
	// change the directions link so they can print from google
	document.getElementById('directionsLink').innerHTML = "<a href='http://maps.google.com/maps?f=d&source=s_d&saddr="+ fromAddress +"&daddr="+ dirs +"' target='_blank'>View Printable Directions</a>"
	// remove the original marker
	//mapobject.clearOverlays(); 
	// get the directions
	directions = new GDirections(mapobject, directionsPanel);
	directions.load("from: " + fromAddress + " to: " + dirs);
	// add listener to update the scroller
	GEvent.addListener(directions, "load", function() { Scroller.updateAll(); });
}
function Radians(val) {
	return val * Math.PI / 180;
}
function SortArrays() {
	// sort array
	if (sortAlphabetically == 1) {
		for (var i = 0; i < storeNameArray.length; i ++) {
			for (var j = i + 1; j < storeNameArray.length; j ++) {
				if (parseInt(distanceArray[i]) <= 1000) {
					isLessThan1k = true;
				}
				if (storeNameArray[j] < storeNameArray[i]) {
					var temp = distanceArray[i];
					distanceArray[i] = distanceArray[j];
					distanceArray[j] = temp;
					
					temp = locationArray[i];
					locationArray[i] = locationArray[j];
					locationArray[j] = temp;
					
					temp = storeNameArray[i];
					storeNameArray[i] = storeNameArray[j];
					storeNameArray[j] = temp;
					
					temp = contentArray[i];
					contentArray[i] = contentArray[j];
					contentArray[j] = temp;
					
					temp = storeIDArray[i];
					storeIDArray[i] = storeIDArray[j];
					storeIDArray[j] = temp;
					
					temp = phoneArray[i];
					phoneArray[i] = phoneArray[j];
					phoneArray[j] = temp;
					
					temp = hoursArray[i];
					hoursArray[i] = hoursArray[j];
					hoursArray[j] = temp;

					temp = MovedSplitArray[i];
					MovedSplitArray[i] = MovedSplitArray[j];
					MovedSplitArray[j] = temp;
				}
			}
		}
	} else {
		for (var i = 0; i < distanceArray.length; i ++) {
			for (var j = i + 1; j < distanceArray.length; j ++) {
				if (parseInt(distanceArray[i]) <= 1000) {
					isLessThan1k = true;
				}
				if (parseInt(distanceArray[j]) < parseInt(distanceArray[i])) {
					var temp = distanceArray[i];
					distanceArray[i] = distanceArray[j];
					distanceArray[j] = temp;
					
					temp = locationArray[i];
					locationArray[i] = locationArray[j];
					locationArray[j] = temp;
					
					temp = storeNameArray[i];
					storeNameArray[i] = storeNameArray[j];
					storeNameArray[j] = temp;
					
					temp = contentArray[i];
					contentArray[i] = contentArray[j];
					contentArray[j] = temp;
					
					temp = storeIDArray[i];
					storeIDArray[i] = storeIDArray[j];
					storeIDArray[j] = temp;
					
					temp = phoneArray[i];
					phoneArray[i] = phoneArray[j];
					phoneArray[j] = temp;
					
					temp = hoursArray[i];
					hoursArray[i] = hoursArray[j];
					hoursArray[j] = temp;

					temp = MovedSplitArray[i];
					MovedSplitArray[i] = MovedSplitArray[j];
					MovedSplitArray[j] = temp;
				}
			}
		}
	}
	var sReturn = "";
	for (i = 0; i < distanceArray.length; i ++) {
		if (((isLessThan1k && parseInt(distanceArray[i]) <= 1000) || !isLessThan1k) || isntUsingDirections == "True") {
			var tempLocArray = locationArray[i].split(",");
			//sReturn += i+1 + ": <a href='javascript:GetPageContent(2,\"StoreID="+ storeIDArray[i] +"\",5);'>" + storeNameArray[i] + "</a>";
			if (MovedSplitArray[i] == "MOVED") {
			    sReturn += i + 1 + ": <a href='http://Sprouts.com/'>" + storeNameArray[i] + "</a>";
			}
			else {
			    sReturn += i + 1 + ": <a href='Locationsearchchild.aspx?ichild=" + storeIDArray[i] + "'>" + storeNameArray[i] + "</a>";
			}
			sReturn += "<br/>" + tempLocArray[0] + "<br/>" + tempLocArray[1] +"<br/>";
			sReturn += "Phone: " + phoneArray[i] +"<br/>";
			if (hoursArray[i] != "") {
				sReturn += "Hours: " + hoursArray[i] + "<br/>";
			}
			if (isntUsingDirections == "False") {
				sReturn += parseInt(distanceArray[i]) + " miles away";
			}
			sReturn += "<br/><br/>";
		}
	}

	document.getElementById('mydata').innerHTML = "<table border='0' class='whtContent'><tr><td>" + sReturn + "</td></tr></table>";
	Scroller.reset("mydata");
	
	// create the markers
	if (isArray(locationArray)) {
		CreateMarkers(locationArray,contentArray,0);
	}	
}
function GrabDirections(locArray) {
	locationArray = new Array();
	distanceArray = new Array();
	storeNameArray = new Array();
	resultSplitArray = new Array();
	storeIDArray = new Array();
	hoursArray = new Array();
	phoneArray = new Array();
	MovedSplitArray = new Array();
	CalculateDistance(locArray,0);
}
function CalculateDistance(locFrom,index) {
	var lat1;
	var lat2;
	var long1;
	var long2;
	
	// format the result string
	resultSplitArray = new Array();
	resultSplitArray = locFrom[index].split("|");
	
	// test if there is a lat/long value
	if (resultSplitArray[2] > 0) {
		var meters = pZip.distanceFrom(new GLatLng(resultSplitArray[2],resultSplitArray[3]));

		var km = meters / 1000;
		var miles = km / 1.609344;	
	
		locationArray.push(resultSplitArray[1]);
		storeNameArray.push(resultSplitArray[0]);
		distanceArray.push(miles.toFixed(2));
		storeIDArray.push(resultSplitArray[4]);
		phoneArray.push(resultSplitArray[5]);
		hoursArray.push(resultSplitArray[6]);
		MovedSplitArray.push(resultSplitArray[7]);	
			
		// recurse
		if ((index + 1) < locFrom.length) {
			CalculateDistance(locFrom,index+1);
		} else {
			// do the next step
			SortArrays();
		}
	} else {	
		// no coordinates found, find them based on the address
		geocoder.getLocations(resultSplitArray[1], function(locresponse) {
			var oplace = locresponse.Placemark[0];
			
			lat2 = oplace.Point.coordinates[1];
			long2 = oplace.Point.coordinates[0];
				
			var meters = pZip.distanceFrom(new GLatLng(lat2,long2));
			var km = meters / 1000;
			var miles = km / 1.609344;	
				
			locationArray.push(resultSplitArray[1]);
			distanceArray.push(miles.toFixed(2));
			storeNameArray.push(resultSplitArray[0]);
			storeIDArray.push(resultSplitArray[4]);
			phoneArray.push(resultSplitArray[5]);
			hoursArray.push(resultSplitArray[6]);
			MovedSplitArray.push(resultSplitArray[7]);	
			
			// recurse
			if ((index + 1) < locFrom.length) {
				CalculateDistance(locFrom,index+1);
			} else {
				// do the next step
				SortArrays();
			}
		});
	}
}
function CreateMarkers(loc,cont,index) {
	if (loc.length >= index) {
		geocoder.getLocations(loc[index], function(mresponse) {
			if (mresponse.Placemark != undefined) {
				var mplace = mresponse.Placemark[0];
				// get the lat/long
				var mpoint = new GLatLng(mplace.Point.coordinates[1], mplace.Point.coordinates[0]);
				// create the icon
				var icon = MapIconMaker.createLabeledMarkerIcon({addStar: false, label: ""+ parseInt(index+1) + "", primaryColor: "#97401b"});
				// crete a marker
				var marker = new GMarker(mpoint, {icon: icon});
				
				// create the bubble listener
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml("<div style='color:#000000; text-align:left;'>" + cont[index] + "</div>");
				});
			
				// add to the map
				mapobject.addOverlay(marker);
				CreateMarkers(loc,cont,parseInt(index)+1);
			}
		});	
	}
}
function addToMap(response) {
	place = response.Placemark[0];
	// get the lat/long
	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	
	// crete a marker
	var marker = new GMarker(point);
	
	markers.push(marker);

	// add to the map
	mapobject.addOverlay(marker);
}
function UpdateCoordinates(sAddress,iStoreID) {
	var lat;
	var lng;
	geocoder.getLocations(sAddress, function(res) {
		var p = res.Placemark[0];
		lat = p.Point.coordinates[1];
		lng = p.Point.coordinates[0];
		
		jQuery.post('StoreActionAJAX.aspx', { lat:lat, lng:lng, StoreID:iStoreID }, function(sData) { 
			if (sData == "success") {
				window.location = "StoreList.aspx";
			}
		});
	});
}
