var bias = 0;

var map,geocoder,aRequest,thisPoint,qString,thisIco,thisResultUL,bounds;
var tooltip = document.createElement("div");
var infoWindows = document.createElement("div");
var infoWindowOpen = "<div class='thisInfoPop'><img src='images/arrow_infoWindow.gif' id='aiw'><a href='#' onclick='$(\".thisInfoPop\").hide();return false;' id='infoClose'></a>";
var infoWindowClose = "</div>";

//	Flag to see if user clicked marker
var sliderActive = 0;

arrSort = new Array("NAME","CITY");
var sortInt = 0;

//	The min and max zoom used for the slider and map zoom
zoomLimits = {
	"min":4,
	"max":19 };

//	This is the center point for the full zoom out
var arrStartCoords = {
	"lat" : 38,
	"lon" :-101 };

var arrMarkers = new Array();

cMarker = {
	"bn":"marker_bn",
	"mcd":"marker_mcd",
	"sb":"marker_sb",
	"group":"marker_group",
	"act":"marker_active"};


var icon_mcd,icon_bn,icon_sb,icon_act,icon_group;

function fillIcon(ico,g) {
	ico.iconSize = new GSize(14, 18);
	ico.iconAnchor = new GPoint(6, 17);
	ico.shadowSize = new GSize(16, 20);
	ico.image = "images/"+g+".gif";
	ico.printImage = "images/"+g+".gif";
	ico.mozPrintImage = "images/"+g+".gif";
	ico.shadow = "images/marker_shadow.png";
}



function unZoom() {
	if(map.getZoom() > zoomLimits["min"]) {
		map.setZoom(parseInt(map.getZoom()-1));
	}
}
function doZoom() {
	if(map.getZoom() < zoomLimits["max"]) {
		map.setZoom(parseInt(map.getZoom()+1));
	}
}
function setZoomPin(xOff) {
	$('#zoom_marker').css('left',xOff-2+'px');
}


function dragPin(eX) {
	pinMin = parseInt($('#markFirst').offset().left);
	pinMin = Math.round(pinMin/10)*10;
	pinMax = parseInt($('#markLast').offset().left)-pinMin-10;
	pinMax = Math.round(pinMax/10)*10;
	bias = Math.max(20, parseInt(eX-pinMin-10));
	bias = Math.min(bias, pinMax)
	setZoomPin(bias);
}



//	Function that is given name, addy, city, state, zipcode
//	returns anchor tag link to google maps directions
function getDirs(n,a,c,s,z) {
	var tempStr = "http://maps.google.com/maps?z=14&daddr=";
	tempStr += escape(a+","+c+","+s+" "+z+" ("+n+")");
	tempStr = "<a href='"+tempStr+"' onclick='window.open(this.href);return false;'>Directions</a>";
	return tempStr;
}
//	Function that is given name, addy, city, state, zipcode
//	returns anchor tag link to google map
function getMap(n,a,c,s,z) {
	var tempStr = "http://maps.google.com/maps?z=14&q=";
	tempStr += escape(a+","+c+","+s+" "+z+" ("+n+")");
	tempStr = "<a href='"+tempStr+"' onclick='window.open(this.href);return false;'>Map</a>";
	return tempStr;
}


//	Return an array of lat/lon bounds
function getArrayLatLon(thisSet) {
	arrBounds = new Array();
	arrBounds['nelat']= thisSet.getNorthEast().lat();
	arrBounds['nelon']= thisSet.getNorthEast().lng();
	arrBounds['swlat']= thisSet.getSouthWest().lat();
	arrBounds['swlon']= thisSet.getSouthWest().lng();
	return arrBounds;
}



//thisIco.image,mName,addy,city,state,zip,phone,0||1
function buildResult(img,strName,strAddy,strCity,strState,strZip,strPhone,idx) {
	var strHTML = "<ul class='bg"+idx%2+"'>";
	strHTML += "<li class='strNum'>"+idx+".</li>"
	strHTML += "<li class='icon'><img src='" + img + "'>&nbsp;</li>";
	strHTML += "<li class='strName'><strong>"+ strName +"</strong></li>";
	strHTML += "<li class='strAddy'>"+ strAddy +"<br />"+ strCity +", "+ strState +" "+ strZip +"</li>";
	strHTML += "<li>"+ strPhone +"&nbsp;</li>";
	strHTML += "<li class='strLink'>"+ getMap(strName,strAddy,strCity,strState,strZip) +"&nbsp;&nbsp;"+ getDirs(strName,strAddy,strCity,strState,strZip) +"</li>";
	strHTML += "</ul>";
	return strHTML;
}

function getResults(kStart) {
	//	Argument is optional
	if(!kStart) kStart=0;

	$('#resultContainer').empty();
	var strPrevNext;

	//	If we approach the end of the result array, make that the limit
	//	else, do 6 results
	if(kStart+7 > arrMarkers.length) {
		kEnd = arrMarkers.length;
	} else {
		kEnd = kStart + 6;
	}

	// Loop through
	for(var j=kStart; j<kEnd; j++) {
		//	Build the html for the results
		//	Pass the icon,name,etc.. then a 0|1 flag for the background color class
		thisResultUL = $(arrMarkers[j].result);
		thisResultUL.attr("rID",j);
		$('#resultContainer').append(thisResultUL);
	}

	strPrevNext = "";

	if(kStart > 0) {
		strPrevNext += "<a href='#' onclick='getResults("+parseInt(kStart-6)+");return false;'>prev</a> ";
	} else {
		strPrevNext += "<span style='color:#ccc;'>prev</span> ";
	}

	if(arrMarkers.length>j) {
		strPrevNext += "<a href='#' onclick='getResults("+j+");return false;'>next</a> ";
	} else {
		strPrevNext += "<span style='color:#ccc;'>next</span> ";
	}
	$('#resultContainer').append("<p class='PrevNext'>"+strPrevNext+"</p>");


	$('#resultContainer ul').click(function() {
		GEvent.trigger(arrMarkers[$(this).attr("rID")],"click");
	});
	$('#resultContainer ul').mouseover(function() {
		arrMarkers[$(this).attr("rID")].setImage('images/marker_active.gif');
	});
	$('#resultContainer ul').mouseout(function() {
		resetIcon = arrMarkers[$(this).attr("rID")].getIcon().image;
		arrMarkers[$(this).attr("rID")].setImage(resetIcon);
	});
}


function showInfoWindow(marker) {
	$(infoWindows).html(marker.pophtml);
	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(infoWindows);
	$(infoWindows).css("visibility","visible");
}
function hideInfoMarker() {
	$(infoWindows).css("visibility","hidden");
}
function showTooltip(marker) {
	$(tooltip).html(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).css("display","block");
}



//	When the state dropdown is changed, zoom and center on the state
function doSearch() {
	if($('#inpZip').val() != $('#inpZip').attr('defaultValue')) {
		//	If the zipcode search is not empty, use it
		geocoder.getLocations($('#inpZip').val() + ", USA", addAddressToMap);
	} else {
		//	If the search button was hit and the form is at default, re-center
		map.setZoom(4);
		map.panTo(new GLatLng(arrStartCoords['lat'],arrStartCoords['lon']));
	}
	return false;
}


function addAddressToMap(response) {
	if (response && response.Status.code == 200) {
		place = response.Placemark[0];
		if($('#inpZip').val() == $('#inpZip').attr('defaultValue')) {
			thisZoom = 7;
		} else {
			thisZoom = $('#selDist option:selected').val();
		}
		map.setCenter(new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]), parseInt(thisZoom));
	}
}

//	Omniture evar6 tracking function
function track6(qLinkName) {
	s.linkTrackVars = 'eVar6';
	s.eVar6 = qLinkName;

	s.tl(this, 'o', qLinkName);
	s.linkTrackVars = 'None';
}



function getMarks(s) {
	//	If the results are still fetching and a new request is made, abort
	if(aRequest) aRequest.abort();

	$('#plzHold').css("display","block");

	map.clearOverlays();
	$(tooltip).css("display","none");
	$(infoWindows).css("visibility","hidden");
	$('#resultContainer').empty();

	arrMarkers = new Array();

	bounds = getArrayLatLon(map.getBounds());

	//	Build a query string for the xml generator
	qString = 'gxml.php?zoom='+map.getZoom()+'&ney='+bounds['nelat']+'&nex='+bounds['nelon']+'&swy='+bounds['swlat']+'&swx='+bounds['swlon'];
	//	If a particular location was requested, pass it
	if( $("#selLoc :selected").val() != "" )
		qString += "&loc=" + $("#selLoc :selected").val();

	//	Sort is NAME by default (though this doesn't do much if the markers are grouped)
	if(!s) s = sortInt;

	qString += "&sort=" + arrSort[s];

	aRequest = $.get(qString,function(data) {
		//	Counter for array of markers
		var k=0;
		$(data).find('marker').each(function() {
			numLoc	= $(this).attr('numLocs');
			mName	= $(this).attr('name');
			addy	= $(this).attr('address');
			city	= $(this).attr('city');
			state	= $(this).attr('state');
			zip		= $(this).attr('zip');
			phone	= $(this).attr('phone');
			lat		= $(this).attr('lat');
			lon		= $(this).attr('lon');

			// Make the name title case. Mcdonalds will have to live.
			mName = mName.substr(0,1).toUpperCase()+mName.substr(1).toLowerCase();

			//	Grab an icon based on the name
			if(mName.indexOf("onald")>-1)
				thisIco=icon_mcd;
			else if(mName.indexOf("Star")>-1)
				thisIco=icon_sb;
			else if(mName.indexOf("Barnes")>-1)
				thisIco=icon_bn;

			if(numLoc > 0) thisIco = icon_group;

			var point = new GLatLng(lat,lon);
			var marker = new GMarker(point, thisIco);

			map.addOverlay(marker);

			marker.point = point;
			marker.finite = numLoc;
			marker.pophtml = infoWindowOpen + "<strong>"+ mName +"</strong><br>"+ addy +"<br>"+ city +", "+ state +"<div id='gDir'>"+ getDirs(mName,addy,city,state,zip) +"</div>"+ infoWindowClose;
			marker.result = buildResult(thisIco.image,mName,addy,city,state,zip,phone,arrMarkers.length+1);

			if(numLoc > 0)
				marker.tooltip = "<div class='thisTip'><strong>" + numLoc + "</strong> locations.<br>Click here to zoom in</div>";
			else
				marker.tooltip = "<div class='thisTip'><strong>"+ parseInt(arrMarkers.length+1) + ". " + mName +"</strong><br>"+ addy +"<br>"+ city + ", " + state +"</div>";


			GEvent.addListener(marker,"mouseover", function() {
				this.setImage("images/marker_active.gif");
				showTooltip(marker);
			});

			GEvent.addListener(marker,"mouseout", function() {
				this.setImage(this.getIcon().image);
				$(tooltip).css("display","none");
			});

			GEvent.addListener(marker, "click", function() {
				//	If the marker is a grouped marker, this.finite will be greater than 1
				if(this.finite < 1) {
					showInfoWindow(marker);
				} else {
					//	Take the current zoom and average it with the max zoom
					map.setCenter(this.point, Math.ceil(parseInt(zoomLimits["max"]+map.getZoom()-2)/2));
				}
			});

			if(!numLoc > 0) {
				//	Build an array of markers
				arrMarkers.push(marker);
			}
			k++;
		});
		if(!numLoc > 0) {
			$('#cntResults').html(k+" Qwest Wi-fi powered by AT&amp;T Wi-Fi Locations match your search criteria");
			$('#result_rail').css({"display":"block"});
			$('#ld_group').hide();
			$('#ld_single').show();
			//	call the display results function, take arrMakers() and display 6 of them
			getResults();
		} else {
			$('#cntResults').html("Zoom in or perform a search to view results.");
			$('#result_rail').css({"display":"none"});
			$('#ld_group').show();
			$('#ld_single').hide();
		}
		$('#plzHold').css("display","none");
	});
}


$(document).ready(function() {
	var newCenter = new GLatLng(arrStartCoords['lat'],arrStartCoords['lon']); // default US center
	map.setCenter(newCenter, 4);
	map.setMapType(G_NORMAL_MAP);

	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);

	geocoder = new GClientGeocoder();

	icon_mcd = new GIcon(G_DEFAULT_ICON);
	fillIcon(icon_mcd,cMarker['mcd']);
	icon_bn = new GIcon(G_DEFAULT_ICON);
	fillIcon(icon_bn,cMarker['bn']);
	icon_sb = new GIcon(G_DEFAULT_ICON);
	fillIcon(icon_sb,cMarker['sb']);
	icon_group = new GIcon(G_DEFAULT_ICON);
	fillIcon(icon_group,cMarker['group']);


	$(tooltip).attr("id","tipContainer");
	$("#wifimap").append(tooltip);
	$(tooltip).css("display","none");


	$(infoWindows).attr("id","infoWindows");
	$("#wifimap").append(infoWindows);
	$(infoWindows).css("visibility","hidden");



	GEvent.addListener(map, "moveend", function() {
		//	Get new result set
		getMarks();
		//	Place the zoom pin x left pixels using the zoom level
		setZoomPin(parseInt(this.getZoom()-zoomLimits["min"])*10+20);
	});

	$('#selLoc').change(function() {
		//	When we change the type of venue, reload the markers
		getMarks();
	});

	$("#selState").change(function() {
		if($("#selState :selected").val() != "") {
			geocoder.getLocations($("#selState :selected").val() + ", USA", addAddressToMap);
		}
		$("#inpZip").attr("value",$("#inpZip").attr("defaultValue"));
	});

	$("#inpZip").focus(function() {
		//	If the field is at it's default value, clear it on focus
		if($(this).attr('defaultValue') == $(this).val()) {
			$(this).attr('value','');
		}
		//	Set the text color to black instead of AAA (default)
		$(this).css('color','#000');
	});
	$("#inpZip").blur(function() {
		//	If the field is empty, give it the default value again on blur
		if($(this).val() == '') {
			$(this).attr('value',$(this).attr('defaultValue'));
			$(this).css({'color':'#AAA'});
		}
	});

	$("#btn_reset").click(function() {
		document.getElementById('frm_search').reset();
		$('#inpZip').css({'color':'#AAA'});
		doSearch();
	});

	//	Custom zoom control
	//	Create anchor tags based on min/max zoom requested (zoomLimits[])
	//	Add a click event to zoom the map
	for(var j=zoomLimits["min"]; j<zoomLimits["max"]+1; j++) {
		var tempObj = $("<a href='' class='pinTick'></a>");
		tempObj.attr("zoomLevel",j);
		tempObj.click(function() {
			// Move the zoom
			map.setZoom(parseInt($(this).attr("zoomLevel")));
			return false;
		});
		// Append our zoom hit area
		$('#markLast').before(tempObj);
	}


	$('#zoom_marker').mousedown(function() {
		sliderActive = 1;
		return false;
	});

	$(document).mouseup(function() {
		if(sliderActive == 1) {
			sliderActive = 0;
			map.setZoom(bias/10+2);
		}
	}).mousemove(function(e) {
		//	Run if sliderActive (mousedown)
		//	Let's only run every 5px, save a bunch of function calls
		if(sliderActive==1 && (e.pageX)%5 == 0)
			//	Pass the mouse x coord step 10
			dragPin(Math.round((e.pageX+14)/10)*10);
	});


	//	Get the initial map markers
	getMarks();
	//	Hide the returning results banner
	$('#plzHold').css("display","none");

});

$(document).unload(function () {
	if(aRequest) aRequest.abort();
	GUnload();
});
