// Google functions
//<![CDATA[

function GM(){}

GM.Init = function()
{
    GM.Map;
    GM.Geocoder;
	GM.AddrPoint;
	GM.AddrMarker;
	GM.StartPoint;
	GM.StartMarker;
	GM.Tooltip;
	GM.Directions;
	GM.DirectionsPolyline = null;
	GM.CrntFrom = "";
	GM.CrntTo = "";
	GM.CrntCenterX = 0;
	GM.CrntCenterY = 0;
	GM.CrntFromLat = 0;
	GM.CrntFromLng = 0;
	GM.CrntPubName = "";
	GM.CrntPubLat = 0;
	GM.CrntPubLng = 0;
	GM.CrntBreweryID = 0;
	GM.StartAddress = "";
	GM.PrevZoom = 0;
	GM.PrevXmin = 0;
	GM.PrevXdist = 0;
	GM.PrevYmin = 0;
	GM.PrevYdist = 0;
	GM.ShowSinglePub = false;
	GM.InfoWindowMove = false;
	GM.Info = new Array();
	GM.Locs = new Array();
	GM.Pubs = new Array();
	
	GM.ClientZoom = 4;
	GM.ClientY = 38.00;
	GM.ClientX = -97.00;
	GM.ClientCity = 0;
	GM.ClientCountry = 0;
	GM.ClientCountry_Code = 0;
	GM.ClientRegion = 0;
	GM.DefLoc = "US," + GM.ClientY + "," + GM.ClientX + "," + GM.ClientZoom;
	
	google.load("maps", "2", {"callback" : GM.LoadMap});
};

GM.LoadMap = function()
{
	//alert("GM.LoadMap");
    GM.Map = new google.maps.Map2(document.getElementById("map"));
	GM.Map.addControl(new google.maps.LargeMapControl3D());
	GM.Map.addControl(new google.maps.MapTypeControl());

    // Marker mouseover tooltip
    GM.Tooltip = document.createElement("div");
    GM.Map.getPane(G_MAP_FLOAT_PANE).appendChild(GM.Tooltip);
    GM.Tooltip.style.visibility = "hidden";

	
	GM.Geocoder = new google.maps.ClientGeocoder();

	GM.Directions = new google.maps.Directions(GM.Map, document.getElementById("dd-container"));
    GEvent.addListener(GM.Directions, "addoverlay", GM.DirectionsAddOverlay);
    //GEvent.addListener(GM.Directions, "load", GM.DirectionsLoad);
    //GEvent.addListener(GM.Directions, "error", GM.HandleErrors);
	
	google.maps.Event.addListener(GM.Map, "infowindowopen", function()
	{
	    //alert("infowindowopen");
		GM.InfoWindowMove = true;
	});
	
	google.maps.Event.addListener(GM.Map, "moveend", function()
	{
	    if (PQ.PubID != "")
		{
		    if (GM.ShowSinglePub) return;
			
            $.ajax(
            {
                type: "GET",
                url: "includes/pubdata.asp",
                data: "id=" + PQ.PubID,
                dataType: "json",
                error: PQ.AjaxError,
                success: GM.LoadPubs
            });
		    return;
		}
		
		var z = parseInt(this.getZoom());
		if (z < 6) return;  // Too far out to show pubs

		var ext = this.getBounds().toString();
    	ext = ext.replace(/\(/g, "");
    	ext = ext.replace(/\)/g, "");
    	var vals = ext.split(",");
    	var ymin = parseFloat(vals[0]);
    	var xmin = parseFloat(vals[1]);
		
		GM.CrntCenterX = (parseFloat(vals[3]) - xmin) / 2.0 + xmin;
		GM.CrntCenterY = (parseFloat(vals[2]) - ymin) / 2.0 + ymin;
		//alert("Xmin = " + xmin + ", Xmax = " + vals[3] + ", Center = " + GM.CrntCenterX
		//    + "\nYmin = " + ymin + ", Ymax = " + vals[2] + ", Center = " + GM.CrntCenterY);

/*		alert("Dist = " + Math.abs(GM.PrevXmin - xmin) 
		  + "\nPrev = " + GM.PrevXdist 
		  + "\nLess = " + ( Math.abs(GM.PrevXmin - xmin) < GM.PrevXdist ) 
		  + "\nInfo window = " + GM.InfoWindowMove);
*/
		if (GM.InfoWindowMove)
		{
		    GM.InfoWindowMove = false;
			return;
		}
		if (z == GM.PrevZoom)
		{
		    // If the map moved less than 20%, don't get pubs
		    if (Math.abs(GM.PrevXmin - xmin) < GM.PrevXdist &&
			    Math.abs(GM.PrevYmin - ymin) < GM.PrevYdist) return;
		}else{
		    GM.PrevZoom = z;
		}

		GM.PrevXmin = xmin;
		GM.PrevYmin = ymin;
	    GM.PrevXdist = Math.abs( (parseFloat(vals[3]) - xmin) / 5.0 ); // 20%
	    GM.PrevYdist = Math.abs( (parseFloat(vals[2]) - ymin) / 5.0 );

		$.ajax(
       	{
       		type: "GET",
       		url: "includes/pubdata.asp",
			data: "ext=" + ext,
       		dataType: "json",
       		error: PQ.AjaxError,
       		success: GM.LoadPubs
       	});
	});

	if (google.loader.ClientLocation && google.loader.ClientLocation.address.country_code == "US")
	{
	   
       GM.ClientX = google.loader.ClientLocation.longitude;
       GM.ClientY = google.loader.ClientLocation.latitude;
       GM.ClientCity = google.loader.ClientLocation.address.city;
       GM.ClientCountry = google.loader.ClientLocation.address.country;
       GM.ClientCountry_Code = google.loader.ClientLocation.address.country_code;
       GM.ClientRegion = google.loader.ClientLocation.address.region;
	   
	   var s = "<p><a onclick=\"GM.CenterMap(" + GM.ClientX + "," + GM.ClientY + "," + 12 + ");\" ><strong>" + GM.ClientCity + ", " + GM.ClientRegion + ", " + GM.ClientCountry + "</strong></a><p>";
	   //s += "<img class='divider' src='images/body/divider.jpg' border='0' alt=''>";
	   $("#homeContainer").html(s);
	   $("#homeContainer").show();
	  
	   //alert("client=" + GM.ClientX + ", " + GM.ClientY + ", " + GM.ClientCity + ", " + GM.ClientCountry + ", " + GM.ClientRegion);
	   GM.ClientZoom = 12;
	}else{
	   PQ.ProcessCountry();
	}

	GM.BaseIcon = new google.maps.Icon();
	
/*	GM.BaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	GM.BaseIcon.iconSize = new google.maps.Size(20, 34);
	GM.BaseIcon.shadowSize = new google.maps.Size(37, 34);
	GM.BaseIcon.iconAnchor = new google.maps.Point(9, 34);
	GM.BaseIcon.infoWindowAnchor = new google.maps.Point(9, 2);
	GM.BaseIcon.infoShadowAnchor = new google.maps.Point(18, 25);
*/
	GM.BaseIcon.iconSize = new google.maps.Size(25, 29);
	//GM.BaseIcon.shadowSize = new google.maps.Size(37, 34);
	GM.BaseIcon.iconAnchor = new google.maps.Point(12, 29);
	GM.BaseIcon.infoWindowAnchor = new google.maps.Point(12, 2);
	//GM.BaseIcon.infoShadowAnchor = new google.maps.Point(18, 25);

    GM.CenterMap(GM.ClientX, GM.ClientY, GM.ClientZoom);
};

GM.CenterMap = function(x, y, z)
{
	var point = new google.maps.LatLng(y, x);
	GM.Map.setCenter(point, z);
};

GM.GetDrivingDirections = function(fname, fy, fx, clear)
{
    GM.StartAddress = fname;
	PQ.ShowMapInfo(true);
	GM.Map.checkResize();
	
	GM.CrntFrom = fname + "@" + fy + "," + fx;
	GM.CrntTo = GM.CrntPubName + "@" + GM.CrntPubLat + "," + GM.CrntPubLng;
	//if (clear) $("#map-info").html("<div class='dd-container'><span class='dd-header'>Directions to:<br/>" + GM.CrntPubName + "</span></div>");
	GM.Directions.loadFromWaypoints( [GM.CrntFrom, GM.CrntTo] );

	if (GM.StartMarker) GM.Map.removeOverlay(GM.StartMarker);
    GM.StartPoint = new google.maps.LatLng(fy, fx);
    GM.StartMarker = GM.CreateAddressMarker("start", GM.StartPoint, fname);
    GM.Map.addOverlay(GM.StartMarker);
};

GM.DirectionsAddOverlay = function()
{
    //alert("GM.DirectionsAddOverlay = " + GM.Directions.getStatus().code + " == " + GM.Directions.getDistance().html + " == " + GM.Directions.getPolyline() );
	GM.DirectionsPolyline = GM.Directions.getPolyline();
};

GM.LoadPubs = function(data, status)
{
	//alert("GM.LoadPubs = " + data.count);

	if (data.count == 0)
	{
	    if (PQ.PubID != "") PQ.PubID = "";
	    $("#pubContainer").hide();
		if (PQ.DistanceInfoVisible) PQ.ToggleDistanceInfo();

		return;
	}

	GM.Map.clearOverlays();

	var point = new google.maps.LatLng(40.0,-105.0);
	var marker = new google.maps.Marker(point);
	var html, type, sym;
	var bubbleKey = -1;
	//a = {count:2, items:[{id:'12', name:'onetwo'},{id:'34', name:'threefour'}]};
	var p = new Array();
	var nl = "", br = "", dkey = 0;
	
	data.pubs.sort(GM.SortFromCenter);

	GM.Pubs.length = 0;
	
	$.each(data.pubs, function(key, val)
	{
	    //alert("Key = " + key + ", Val = " + val.NAME);
		//if (key > 0) return false;

		var color;
		var name = val.NAME;
		var safeName = val.NAME.replace(/'/g, "");
        point = new google.maps.LatLng(val.Y, val.X);
		type = val.TYPE.toLowerCase();
		if (type == "brewpub")
		{
			color = "b";
			sym = "http://www.pubquest.com/images/icons/base_pub.png";
		}else if (type=="brewhouse"){
			color = "r";
			sym = "http://www.pubquest.com/images/icons/base_house.png";
		}else{
			color = "w";
			sym = "http://www.pubquest.com/images/icons/base_brewery.png";
		}
		html = "<strong>" + name + "</strong><br><br>";
		html += val.ADDRESS + "<br>";
		html += val.CITY + ",&nbsp;" + val.STATE + "&nbsp;" + val.ZIP + "<br>";
		html += val.PHONE;
		if (val.WEBSITE.indexOf("http") >= 0)
		{
			html += "<br><br><a href='" + val.WEBSITE + "' target='_blank'>" + val.WEBSITE + "</a>";
		}
		
		var param = '"' + safeName + '",' + val.Y + ',' + val.X;
		html += "<br><br>Directions - Start Address:";
        html += "<br><input id='txtStartAddress' class='addr-box' type='text' value='" + GM.StartAddress + "' onkeyup='GM.StartAddressChanged(event,\"" + safeName + "\"," + val.Y + "," + val.X + ");' />";
        html += "<div id='dd-button'>";
        html += "<a onclick='GM.FindStartAddress(\"" + safeName + "\"," + val.Y + "," + val.X + ");' >";
        html += "<span>Get&nbsp;Directions</span></a></div>";
		
		html = GM.CreateBubbleContent(type, html);

        marker = GM.CreateMarker(safeName, point, sym, color, html, key);
		GM.Map.addOverlay(marker);
		GM.Locs[key] = marker;
		GM.Info[key] = html;
		
		if (key < 30)
		{
		    dkey = key;
			// <tr><td>1)</td><td>The Pub</td></tr>
			nl += "<tr><td class='pub-number'>" + (key+1) + ")</td><td><a onclick='PQ.SetPubListIdx(" + key + ",true);'>" + name + "</a></td></tr>"
			    + "<tr><td>&nbsp;</td><td>" + val.ADDRESS + "</td></tr>";
			br = "<br><br>";
		}

		if (val.ID == GM.CrntBreweryID)
		{
		    bubbleKey = key;
			GM.CrntBreweryID = 0;
		}
		if (name.length > 25)
		{
		    name = name.slice(0, 24);
			name += "...";
		} 
		p = new Array();
		p["key"] = key;
		p["name"] = name;
		GM.Pubs.push(p);
	});

	GM.Pubs.sort(GM.SortPubList);
	
	//alert("Pub 0 = " + GM.Pubs[0].name + ", 1 = " + GM.Pubs[1].name);
	var pl = "<select id='lstPub' onchange='GM.DisplayInfo()'>";
	if (PQ.PubID == "")
	{
	    pl += "<option value='-1'>-- Select Craft Brew Location --</option>";
	} else {
	    pl += "<option value='-1'>Show All Craft Brew Locations</option>";
	}
	for (var idx = 0; idx < GM.Pubs.length; idx++)
	{
	    pl += "<option value='" + GM.Pubs[idx].key + "'>" + GM.Pubs[idx].name + "</option>";
	}
	pl += "</select>";

	$("#pubListContainer").html(pl);
	$("#pubContainer").show();

    $("#di-title").html("Closest " + (dkey+1) + " Breweries");
	$("#di-container").html("<table>" + nl + "</table>");
	
	// Show the address marker if an address has been created
	if (GM.AddrMarker) GM.Map.addOverlay(GM.AddrMarker);
	if (GM.StartMarker) GM.Map.addOverlay(GM.StartMarker);

	if (GM.DirectionsPolyline != null) 
	{
	    //alert("Add polyline");
		GM.Map.addOverlay(GM.DirectionsPolyline);
	}
	
	if (PQ.PubID != "")
	{
		GM.PrevZoom = 13;
	    GM.ShowSinglePub = true;
		//alert("Go to pub = " + GM.Locs[0].getLatLng());
	    document.getElementById("lstPub").selectedIndex = 1;
		GM.Map.setCenter(GM.Locs[0].getLatLng(), GM.PrevZoom);
		GM.Locs[0].openInfoWindowHtml(GM.Info[0]);
	}
	if (bubbleKey > -1)
	{
	    document.getElementById("lstPub").selectedIndex = bubbleKey + 1;
		GM.Map.setCenter(GM.Locs[bubbleKey].getLatLng(), GM.PrevZoom);
		GM.Locs[bubbleKey].openInfoWindowHtml(GM.Info[bubbleKey]);
	}
};
GM.SortFromCenter = function(a, b)
{
	var xdist = Math.abs(GM.CrntCenterX - a.X);
	var ydist = Math.abs(GM.CrntCenterY - a.Y);
    var adist = Math.sqrt( (xdist * xdist) + (ydist * ydist) );

	xdist = Math.abs(GM.CrntCenterX - b.X);
	ydist = Math.abs(GM.CrntCenterY - b.Y);
    var bdist = Math.sqrt( (xdist * xdist) + (ydist * ydist) );

    if (adist == bdist) {
        return 0;
    } else {
        return (adist < bdist) ? -1 : 1;
    }
};
GM.SortFromTop = function(a, b)
{
    if (a.Y == b.Y) {
        return 0;
    } else {
        return (a.Y > b.Y) ? -1 : 1;
    }

};
GM.SortPubList = function(a, b)
{
    if (a.name == b.name) {
        return 0;
    } else {
        return (a.name < b.name) ? -1 : 1;
    }

};
GM.CreateBubbleContent = function(type, content) {
    var imgTagStart = "<img src='http://www.pubquest.com/images/body/bubble-title-bar.png' style='border: 0px none; margin: 0px; padding: 0px; position: absolute; left: ";
    var imgTagEnd = " top: 0px; width: 690px; height: 26px;' />";
    var headerStyles = "overflow: hidden; position: absolute; top: -15px; height: 26px; ";
	var imgType;

    if (type == "brewpub")
    {
        imgType = "brewpub";
    }else if (type=="brewhouse"){
        imgType = "brewhouse";
    }else{
        imgType = "brewery";
    }

	var s = "<div class='bubble' >";

    s += " <div style='" + headerStyles + "left: -15px; width: 250px;'>\n";
    s += "<img src='http://www.pubquest.com/images/body/title-" + imgType + ".png' "
	s += "style='border: 0px none; margin: 0px; padding: 0px; position: absolute; ";
	s += "left: 0px; top: 0px; width: 250px; height: 26px;' />";
    s += " </div>\n";

    s += " <div style='width:219px;height:25px;overflow:hidden;'></div>\n";

    s += " <div style='width:219px;text-align:center;'>" + content + "</div>";

    s += " </div>";
	
	return s;
};
GM.CreateMarker = function(name, point, sym, color, text, idx) {
	var icon = new google.maps.Icon(GM.BaseIcon);
	var marker = new google.maps.Marker(point, icon);
	var id = idx + 1; 

	icon.image = sym;
	if (id < 31)
	{
	    icon.label = {"url":"http://www.pubquest.com/images/icons/" + color + id + ".png", "anchor":new GLatLng(5,3), "size":new GSize(19,12)};
		icon.imageMap = [0,0, 25,0, 25,31, 0,21];
		//icon.transparent = "http://www.pubquest.com/images/icons/trans.png";
	} 
	marker.plidx = id;
	marker.tooltip = '<div class="tooltip"><nobr>'+name+'<\/nobr><\/div>';

	google.maps.Event.addListener(marker, "click", function()
	{
		//alert("idx = " + this.plidx);
		marker.openInfoWindowHtml(text);
		//PQ.SetPubListIdx(this.plidx, false);
		//document.getElementById("lstPub").selectedIndex = this.plidx;
		document.getElementById("lstPub").selectedIndex = 0;
	});

	google.maps.Event.addListener(marker, "mouseover", function()
	{
        GM.ShowTooltip(marker);
	});

	google.maps.Event.addListener(marker, "mouseout", function()
	{
        GM.Tooltip.style.visibility = "hidden";
	});
	
	return marker;
};
GM.ShowTooltip = function(marker) {
    GM.Tooltip.innerHTML = marker.tooltip;
    var point = GM.Map.getCurrentMapType().getProjection().fromLatLngToPixel(GM.Map.fromDivPixelToLatLng(new google.maps.Point(0,0),true),GM.Map.getZoom());
    var offset = GM.Map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),GM.Map.getZoom());
    var anchor = marker.getIcon().iconAnchor;
    var width = marker.getIcon().iconSize.width;
    var height = GM.Tooltip.clientHeight;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
    pos.apply(GM.Tooltip);
    GM.Tooltip.style.visibility="visible";
};
GM.CreateAddressMarker = function(type, point, text) {
	var bi = new google.maps.Icon();
	if (type == "addr")
	{
        bi.iconSize = new google.maps.Size(22, 22);
        bi.iconAnchor = new google.maps.Point(11, 11);
        bi.infoWindowAnchor = new google.maps.Point(10, 5);
	}else{
        bi.iconSize = new google.maps.Size(40, 17);
        bi.iconAnchor = new google.maps.Point(20, 9);
        bi.infoWindowAnchor = new google.maps.Point(10, 5);
	}
	
	var icon = new google.maps.Icon(bi);

	var marker = new google.maps.Marker(point, icon);
	marker.tooltip = '<div class="tooltip"><nobr>'+text+'<\/nobr><\/div>';

    var html;
	if (type == "addr")
	{
   	    html = "Search Location:<br><br><strong>" + text + "</strong>";
	    icon.image = "http://www.pubquest.com/images/icons/home.png";
	}else{
   	    html = "Directions Start Location:<br><br><strong>" + text + "</strong>";
	    icon.image = "http://www.pubquest.com/images/icons/car.png";
	}

	google.maps.Event.addListener(marker, "click", function()
	{
		marker.openInfoWindowHtml(html);
	});

	google.maps.Event.addListener(marker, "mouseover", function()
	{
        GM.ShowTooltip(marker);
	});

	google.maps.Event.addListener(marker, "mouseout", function()
	{
        GM.Tooltip.style.visibility = "hidden";
	});
	
	return marker;
};
GM.DisplayInfo = function() {
	//alert("Pub = " + $("#lstPub").val());
	//var idx = $("#lstPub").attr("selectedIndex");
	var idx = parseInt($("#lstPub").val()) + 1;

    if (idx > 0)
	{
		//GM.Map.setZoom(mZoom);
		idx -= 1;
		GM.Locs[idx].openInfoWindowHtml(GM.Info[idx]);
		//alert("Lat = " + GM.Locs[idx].getLatLng().lat() );
	} else {
		PQ.PubID = "";
	    GM.ShowSinglePub = false;
		GM.Map.setZoom(GM.PrevZoom - 1);
	}
};
GM.StartAddressChanged = function(e, pub, y, x)
{
    //alert("GM.StartAddressChanged = " + e.keyCode + " -->" + pub);
	if (e.keyCode == 13) GM.FindStartAddress(pub, y, x);
};
GM.FindStartAddress = function(pub, y, x)
{
	//alert("GM.FindStartAddress=" + pub + ", " + y + ", " + x + ", " + $("#txtStartAddress").val() );
	var address = $("#txtStartAddress").val();
  	GM.CrntPubName = pub;
  	GM.CrntPubLat = y;
  	GM.CrntPubLng = x;
	$("#dd-title").html(GM.CrntPubName);

	GM.Geocoder.getLocations(address, function(response)
	{
        if (!response || response.Status.code != 200) {
            alert(address + " not found, status code = " + response.Status.code);
        } else {
		    if (response.Placemark.length > 1)
			{
			    GM.ShowStartAddressList(response.Placemark);
			}else{
			    var addr;
    		    var place = response.Placemark[0];
    			GM.StartAddrPoint = new google.maps.LatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				if (place.AddressDetails.Accuracy > 5)
				{
				    addr = place.address; 
				    //addr = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName + ", "
					//     + place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName + ", "
					//     + place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
				} else {
				    addr = place.address; 
				}
				$("#dd-addr-list-container").hide();
				GM.GetDrivingDirections(addr, place.Point.coordinates[1], place.Point.coordinates[0], true);
			}
        }
    });
};
GM.ShowStartAddressList = function(places)
{
    //alert("PQ.ShowStartAddressList = " + places.length);
    var s = "", b = "", addr;
	
	s = "<span class=\"dd-addr-list-title\">Multiple Starting Locations Found:</span>";
	s += "<br/><br/><p>";
    for (var idx = 0; idx < places.length; idx++)
    {
		if (places[idx].AddressDetails.Accuracy > 5)
		{
		    addr = places[idx].address; 
		    //addr = places[idx].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName + ", "
			//     + places[idx].AddressDetails.Country.AdministrativeArea.Locality.LocalityName + ", "
			//     + places[idx].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
		} else {
		    addr = places[idx].address; 
		}
    	s += b + "<a onclick=\"GM.GetDrivingDirections('" + addr + "'," + places[idx].Point.coordinates[1] + "," + places[idx].Point.coordinates[0] + "," + false + ");\">" + places[idx].address + "</a>";
		b = "<br />";
	}
	s += "</p><span class=\"dd-addr-instructions\">(Click an address to select it)</span>";
	
	$("#dd-container").html("");
	$("#dd-addr-list-container").html(s);
	$("#dd-addr-list-container").show();
	PQ.ShowMapInfo(true);
};

//]]>

