var map = null;
var actionID = 1001;
var curcenter = null;
var curbounds = null;
var markers = [];
var icon = null;
var stackicon = null;
var thumbnailurl = "";
var pending = false;

function initMap()
{
	var mapDiv;

	mapDiv = $("#map")[0];

	if (!mapDiv)
		return;

	if (GBrowserIsCompatible())
	{
		// Center the map
		map = new GMap2(mapDiv);
		GEvent.addDomListener(map, "load", completeLoad);

		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();

		point = new GLatLng(37.0625,-95.677068);
		curcenter = point;
		map.setCenter(point, 1);

		icon = new GIcon(G_DEFAULT_ICON, 'image/gsi_mapIcon.png');
		stackicon = new GIcon(G_DEFAULT_ICON, 'image/gsi_mapIcon_cluster.png');

		GEvent.addListener(map, "click",
			function(overlay, point) { return onMapClick(overlay, point); });

		GEvent.addListener(map, "moveend", doMove);
		GEvent.addListener(map, "zoomend", doRefresh);
	}
	else
	{
		alert("Your browser cannot display a Google Map!");
	}
}

function completeLoad()
{
	curbounds = map.getBounds();
	doRefresh();
}

function onMapClick(overlay, point)
{
	var i;

	if (overlay)
	{
		for (i=0; i<markers.length; i++)
		{
			if (markers[i].marker == overlay)
			{
				doOpenPopup(i, -1);
				break;
			}
		}
	}
}

function doMove()
{
	var point;

	if (null == curcenter)
		return;

	point = map.getCenter();
	if ((point.lat() > curbounds.getNorthEast().lat()) ||
			(point.lat() < curbounds.getSouthWest().lat()) ||
			(point.lng() > curbounds.getNorthEast().lng()) ||
			(point.lng() < curbounds.getSouthWest().lng()))
	{
		doRefresh();
	}	
}

function doOpenPopup(index, num)
{
	var html;
	var addr;
	var zoom = map.getZoom();
	var i;

	if (-1 == num)
	{
		if (!markers[index].locations)
		{
			html = "<span class='mappopup'>Your search has <b>" +
				String(markers[index].count) + "</b>" +
				" stores.<br />Please zoom in for more detail.</span>";
		}
		else if ((markers[index].count > 1) && (markers[index].count <= 5))
		{
			html = "<span class='mappopup'><b>" + String(markers[index].count) + "</b>" +
				" Locations:<br />";
			for (i=0; i<markers[index].locations.length; i++)
			{
				addr = markers[index].locations[i].Address1 + ", " +
					markers[index].locations[i].PostCode + ", " +
					markers[index].locations[i].Country;
	
				html += "<br /><a href='javascript:void(0)' onclick='doReopenPopup(" + String(index) + "," + String(i) + ")'>" + markers[index].locations[i].StoreName + "</a>";
			}
			html += "</span>";
		}
	}

	if ((-1 != num) || (1 == markers[index].count))
	{
		if (1 == markers[index].count)
			num = 0;

		addr = markers[index].locations[num].Address1 + ", " +
			markers[index].locations[num].PostCode + ", " +
			markers[index].locations[num].Country;

		if ("" != markers[index].locations[num].PhotoPath)
		{
			html = "<table class='mappopup'><tr><td><img src='" + thumbnailurl + markers[index].locations[num].PhotoPath +
				"' alt='' width='" + String(markers[index].locations[num].imgwidth) +
				"' height='" + String(markers[index].locations[num].imgheight) + "' /></td>" +
				"<td style='width: 20px;'>&nbsp;</td><td><table>" +
				"<tr><td><b><a target='_blank' href='http://maps.google.com/maps?q=" + urlencode(addr) + "'>" + markers[index].locations[num].StoreName + "</a></b></td></tr>" +
				"<tr><td>" + markers[index].locations[num].Address1 + "</td></tr>" +
				"<tr><td>" + markers[index].locations[num].City + " " +
					markers[index].locations[num].CountryState + " " +
					markers[index].locations[num].PostCode + " " +
					markers[index].locations[num].CountryCode + "</td></tr>";
			if ("" != trim(markers[index].locations[num].Phone))
				html +=	"<tr><td>p: " + markers[index].locations[num].Phone + "</td></tr>";
			if ("" != trim(markers[index].locations[num].StoreEmail))
				html += "<tr><td>e: <a href='mailto:" + markers[index].locations[num].StoreEmail + "'>" +
					markers[index].locations[num].StoreEmail + "</a></td></tr>";
			if ("" != trim(markers[index].locations[num].WebSite))
				html += "<tr><td>w: <a target='_blank' href='" + markers[index].locations[num].WebSite + "'>" +
					"Visit Website" + "</a></td></tr>";
			if (markers[index].locations[num].HasSurfSchool)
				html += "<tr><td>Has Surf School: Yes</td></tr>";
			if (markers[index].locations[num].HasDemoBoards)
				html += "<tr><td>Has Demo Boards: Yes</td></tr>";
			html += "</table></td></tr></table>";
		}
		else
		{
			html = "<table class='mappopup'>" +
				"<tr><td><b><a target='_blank' href='http://maps.google.com/maps?q=" + urlencode(addr) + "'>" + markers[index].locations[num].StoreName + "</a></b></td></tr>" +
				"<tr><td>" + markers[index].locations[num].Address1 + "</td></tr>" +
				"<tr><td>" + markers[index].locations[num].City + " " +
					markers[index].locations[num].CountryState + " " +
					markers[index].locations[num].PostCode + " " +
					markers[index].locations[num].CountryCode + "</td></tr>";
			if ("" != trim(markers[index].locations[num].Phone))
				html +=	"<tr><td>p: " + markers[index].locations[num].Phone + "</td></tr>";
			if ("" != trim(markers[index].locations[num].StoreEmail))
				html += "<tr><td>e: <a href='mailto:" + markers[index].locations[num].StoreEmail + "'>" +
					markers[index].locations[num].StoreEmail + "</a></td></tr>";
			if ("" != trim(markers[index].locations[num].WebSite))
				html += "<tr><td>w: <a target='_blank' href='" + markers[index].locations[num].WebSite + "'>" +
					"Visit Website" + "</a></td></tr>";
			if (markers[index].locations[num].HasSurfSchool)
				html += "<tr><td>Has Surf School: Yes</td></tr>";
			if (markers[index].locations[num].HasDemoBoards)
				html += "<tr><td>Has Demo Boards: Yes</td></tr>";
			html += "</table>";
		}
	}

	markers[index].marker.openInfoWindowHtml(html);
}

function doReopenPopup(index, num)
{
	markers[index].marker.closeInfoWindow();
	doOpenPopup(index, num);
}

function doRefresh()
{
	var boundsne, boundssw;;
	var obj;

	if (pending) return;
	pending = true;

	curcenter = map.getCenter();
	curbounds = map.getBounds();

	boundsne = curbounds.getNorthEast();
	boundssw = curbounds.getSouthWest();

	obj = {
		"cmd": "GETLOCATIONS",
		"actionID": actionID,
		"bounds": [[boundsne.lat(), boundsne.lng()], [boundssw.lat(), boundssw.lng()]],
		"zoom": map.getZoom()
	};

	sendAjaxRequest(obj, myServerCallback);
}

function displayLocations(obj)
{
	var marker;
	var i;

	if (obj && obj.locations)
		markers = obj.locations;

	map.clearOverlays();

	for (i=0; i<markers.length; i++)
	{
		if (markers[i].count > 1)
			marker = new GMarker(new GLatLng(markers[i].latitude, markers[i].longitude), stackicon);
		else
			marker = new GMarker(new GLatLng(markers[i].latitude, markers[i].longitude), icon);

		markers[i].marker = marker;
		map.addOverlay(marker);
	}	
}

function myServerCallback(obj)
{
	if (obj && (obj.actionID == actionID))
	{
		switch (obj.cmd)
		{
			case "GETLOCATIONS":
				pending = false;
				thumbnailurl = obj.thumbnailurl;
				displayLocations(obj);
				break;
			default:
				break;
		}

		actionID++;
	}
}

function urlencode(clearString)
{
  var output = '';
  var regex;
  var match;
  var charCode, hexVal;
  var x = 0;

  clearString = clearString.toString();
  regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length)
  {
    match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '')
    {
    	output += match[1];
      x += match[1].length;
    }
    else
    {
      if (clearString[x] == ' ')
        output += '+';
      else
      {
        charCode = clearString.charCodeAt(x);
        hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }

  return output;
}

function urldecode(encodedString)
{
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '')
	{
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
 
  return output;
}

function trim(str)
{
	var s = String(str);
	return s.replace(/^\s+|\s+$/, '');
}
