var map, manager, refreshTime;
//var centerLatitude = 33.321349, centerLongitude = -111.873779, startZoom = 12;

function createMarkerClickHandler(marker, text, link, nick, phone, fav, active, hours) {
	return function() {
		if(nick == storeName){
			f = '<b>This is set as your favorite store</b>';
		}else{
			f = '<a href="javascript:jack(\'storeName\',\''+nick+'\',\'cookie\',\'\');"><b>Save as My Favorite Sprouts</b></a>';
		}
		if(active == "Y"){
			marker.openInfoWindowHtml(
				'<h3>' + text + '</h3><div style="margin-bottom:0px; font-weight:bold;">phone: '+phone+'</div>' +
				'<div style="margin-bottom:4px; font-weight:bold;">hours: '+hours+'</div>' +
				'<div id="favDiv">'+f+'</div>' +
				'<a href="/_setCookie.php?what=session&cookieName=storeName&cookieValue='+nick+'&where=/home.php?goto=ad" target="_top">View Weekly Ad for this Store</a><br>' +
				'<a href="/_setCookie.php?what=session&cookieName=storeName&cookieValue='+nick+'&where=/home.php?goto=events" target="_top">View Events for this region</a><br>' +
				'<a href="/_setCookie.php?what=session&cookieName=storeName&cookieValue='+nick+'&where=/home.php?goto=career" target="_top">View Job Postings</a>' +
				'<br><a href="' + link + '" target="_blank">Get Directions from Google</a>'
			);
		}else{
			marker.openInfoWindowHtml(
				'<h3>' + text + '</h3><div style="margin-bottom:10px; font-weight:bold;color:red">coming soon</div>' +
				'<a href="/home.php?goto=newS" target="_top">View Job Fair Info</a>' +
				'<br><a href="' + link + '" target="_blank">Get Directions from Google</a>'
			);
		}
		return false;
	};
}


function createMarker(pointData) {
	var latlng = new GLatLng(pointData.latitude, pointData.longitude);
	var icon = new GIcon();
	icon.image = '/images/square.gif';
	icon.iconSize = new GSize(32, 32);
	icon.iconAnchor = new GPoint(16, 16);
	icon.infoWindowAnchor = new GPoint(25, 7);

	opts = {
		"icon": icon,
		"clickable": true,
		"labelText": pointData.abbr,
		"labelOffset": new GSize(-16, -16)
	};
	var marker = new LabeledMarker(latlng, opts);
	var handler = createMarkerClickHandler(marker, pointData.name, pointData.wp, pointData.nickname, pointData.phone, pointData.fav, pointData.active, pointData.hours);
	
	GEvent.addListener(marker, "click", handler);

	if(pointData.info != '' && pointData.info != '                  ' && pointData.info != null){
		info = '<span style="font-weight:bold;color:black;">'+pointData.info+'</span><br>';	
	}else{
		info = "";	
	}
	var listItem = document.createElement('li');
	listItem.innerHTML = '<a href="' + pointData.wp + '"><div class="label">'+pointData.abbr+'</div>'+info + pointData.name + '</a>';
	listItem.getElementsByTagName('a')[0].onclick = handler;

	document.getElementById('sidebar-list').appendChild(listItem);

	return marker;
}

function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case. 
	return 0;
}

function handleResize() {
	//var height = windowHeight() - document.getElementById('toolbar').offsetHeight - 30;
	//document.getElementById('map').style.height = height + 'px';
	//document.getElementById('sidebar').style.height = height + 'px';
}

function init() {
	handleResize();
	
	map = new GMap(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), 4);
	map.addControl(new GMapTypeControl());

	manager = new GMarkerManager(map);
	
	document.getElementById('sidebar-list').innerHTML = "";
	
	// This is a sorting trick, don't worry too much about it.
	//markers.sort(function(a, b) { return (a.abbr > b.abbr) ? +1 : -1; }); 
	
	var topItem = document.createElement('li');
	
	if(myTown != ''){
		topItem.innerHTML = '<div style="margin-left:-40px;">Stores Near:<br><h3>'+myTown+' '+myZip+'</h3></div>';
	}else if(state != ''){
		topItem.innerHTML = '<div style="margin-left:-40px;"><h3>Stores in '+state+'</h3></div>';
	}else{
		topItem.innerHTML = '<h3 style="margin-left:-40px;">Sprouts Locations</h3>';
	}
	document.getElementById('sidebar-list').appendChild(topItem);
	
	//
	
	batch = [];
	for(id in markers) {
		batch.push(createMarker(markers[id]));
	}
	manager.addMarkers(batch, 2);
	manager.refresh();
	//
	refreshTime = setTimeout ( "zoomp()", 3000 );
}


	function zoomp(){
		
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);	
		clearTimeout ( refreshTime );
		
	}

	function jack(cname,cval,what,where){
		
		//alert(task);
		document.getElementById('favDiv').innerHTML = "please wait...";
		
		eval(cname+" = '"+cval+"'");
	
		url  = "/_setCookie.php?what="+what+"&cookieName="+cname+"&cookieValue="+cval+"&where="+where;
		
		//alert(url);
		loadXMLDoc(url);
	  
		
	}
	
	
	
	function loadXMLDoc(url) 
	{
		// branch for native XMLHttpRequest object
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send(null);
		// branch for IE/Windows ActiveX version
		} else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
				req.onreadystatechange = processReqChange;
				req.open("GET", url, true);
				req.send();
			}
		}
	}
	
	function processReqChange() 
	{
		// only if req shows "complete"
		if (req.readyState == 4) {
			// only if "OK"
			if (req.status == 200) {
				// ...processing statements go here...
				response  = req.responseXML.documentElement;
				result = response.getElementsByTagName('result')[0].firstChild.data;
				
				document.getElementById('favDiv').innerHTML = "This is set as your favorite store";
				
				//alert("result is "+result);
				
			} else {
				alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}else{
			//alert("2There was a problem retrieving the XML data:\nreadyState is: " + req.readyState);
		}
	}
	
	

//window.onresize = handleResize;
//window.onload = init;
//window.onunload = GUnload;
