// Google functions
//<![CDATA[

function GM(){}

GM.Init = function()
{
/*    $(window).resize(function(){
      GM.ResizeMap();
    });
*/
    GM.Map;
    GM.Geocoder;
    GM.DirectionDisplay = null;
    GM.DirectionsService = null;
	GM.Info = new Array();
	GM.Locs = new Array();
	GM.Nums = new Array();
	GM.Pubs = new Array();

    GM.CrntMarker = null;
    GM.CrntInfoWindow = null;
	GM.CrntCenterX = 0;
	GM.CrntCenterY = 0;
  	GM.CrntPubName = "";
  	GM.CrntPubLat = 0;
  	GM.CrntPubLng = 0;
    GM.CrntBreweryID = 0;
    
	GM.PrevZoom = 0;
	GM.PrevXmin = 0;
	GM.PrevXdist = 0;
	GM.PrevYmin = 0;
	GM.PrevYdist = 0;
	
	GM.SearchZoom = 12;

	GM.ClientZoom = 3;
	GM.ClientY = 38.00;
	GM.ClientX = -96.00;
	GM.ClientAddress = "";
	GM.DefLoc = "US," + GM.ClientY + "," + GM.ClientX + "," + GM.ClientZoom;
    GM.GeolocationSource = "";
    GM.ShowGeolocation = false;
    
    GM.StartAddress = "";
    GM.StartPoint = null;
    GM.EndPoint = null;
    GM.BubbleOpen = false;
    GM.FirstPubDisplay = true;
    GM.MapInfoShowing = true;
    GM.MapDirectionShowing = false;
    
    //SF.InitAddressInput();
    GM.AddressInputMsg = "Enter a Location";
    GM.BreweryInputMSg = "Enter a Craft Brewery";
    $("#txtAddress").val(GM.AddressInputMsg);
    $("#txtBrewery").val(GM.BreweryInputMSg);
    $("#txtAddress").css("color", "#666");
    $("#txtBrewery").css("color", "#666");
    $("#lstCountry").attr("selectedIndex", 0);
    $("#lstDirections").attr("selectedIndex", 0);

    // Bind CR to address box (when you press carriage return it checks the address)
    //$("#txtAddress").bind("keyup", function(e) { if (e.keyCode == 13) {SF.ProcessAddress(); } } );
	
	//GM.ResizeMap();
	
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=GM.LoadMap";
    document.body.appendChild(script);
};

GM.ToggleMapInfo = function()
{
    if (GM.MapInfoShowing)
    {
        $("#sidebar-pub-list").hide();
        $("#pub-dist-list-text").html("Show Brewery List");
    } else {
        $("#sidebar-pub-list").show();
        $("#pub-dist-list-text").html("Hide Brewery List");
    }
    GM.MapInfoShowing = !GM.MapInfoShowing;
};

GM.ToggleDirectionInfo = function()
{
    if (GM.MapDirectionShowing)
    {
        $("#sidebar-direction-info").hide();
        $("#sidebar-map-info").show();
        $("#map-directions-text").html("Show Directions");
    } else {
        $("#sidebar-map-info").hide();
        $("#sidebar-direction-info").show();
        $("#map-directions-text").html("Show Brewery List");
    }
    GM.MapDirectionShowing = !GM.MapDirectionShowing;
};

GM.LoadMap = function()
{
	var options = {
        zoom: GM.ClientZoom,
        center: new google.maps.LatLng(GM.ClientY, GM.ClientX),
        mapTypeControl: true,
    	mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
        zoomControl: true,
    	zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE },
        scaleControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

	GM.Map = new google.maps.Map(document.getElementById("map"), options);
    GM.Geocoder = new google.maps.Geocoder();
	
	google.maps.event.addListener(GM.Map, "bounds_changed", function()
	{
        if (GM.BubbleOpen)
        {
            // Opening the marker bubble caused the map to move
            GM.BubbleOpen = false;
            return;
        }
        
		var z = parseInt(this.getZoom());
		if (z < 6) 
        {
            // Too far out to show pubs
            GM.SetNoPubsList();
            return;
        }

		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;

		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
       	});
	});

    //GM.CenterMap(GM.ClientX, GM.ClientY, GM.ClientZoom);

    initializeGeolocation();
};

GM.CenterMap = function(x, y, z)
{
	var point = new google.maps.LatLng(y, x);
	GM.Map.setCenter(point);
	GM.Map.setZoom(z);
};

GM.SetNoPubsList = function()
{
    GM.ClearPubsFromMap();
    
    $("#pubListContainer").html("<select id='lstPub'><option value='-1'>-- No Craft Brewery Locations on Map --</option></select>");
    $("#sidebar-map-header").html("No Craft Brewery Locations on Map");
    $("#sidebar-pub-list").html("");
};

GM.ClearPubsFromMap = function()
{
    for (idx in GM.Locs) {
        GM.Locs[idx].setMap(null);
    }
    for (idx in GM.Nums) {
        GM.Nums[idx].setMap(null);
    }
    GM.Locs.length = 0;
    GM.Nums.length = 0;
	GM.Pubs.length = 0;
};           

GM.LoadPubs = function(data, status)
{
    //alert("GM.LoadPubs = " + data.count);
    
	if (data.count == 0)
	{
	    if (PQ.PubID != "") PQ.PubID = "";
        //alert("GM.LoadPubs 0 Found");
        GM.SetNoPubsList();

        if (GM.ShowGeolocation) GM.SetupStartLocation();
        
		return;
	}

	var point = new google.maps.LatLng(40.0,-105.0);
	var content, type, sym, sym1, idx, zIdx;
	var bubbleKey = -1;
	//a = {count:2, items:[{id:'12', name:'onetwo'},{id:'34', name:'threefour'}]};
	var p = new Array();
	var nl = "", br = "", dkey = 0, zIdx = 0;
    
    GM.ClearPubsFromMap();
	
	data.pubs.sort(GM.SortFromCenter);

    $.each(data.pubs, function(key, val)
	{
	    //alert("Key = " + key + ", Val = " + val.NAME);
		//if (key > 0) return false;

		var color, cat, catcolor;
		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";
            cat = "Brewpub";
            catcolor = "#E0E000";
			sym = "http://www.pubquest.com/images/icons/base_pub.png";
		}else if (type=="brewhouse"){
			color = "r";
            cat = "Brewhouse";
            catcolor = "#EA7500";
			sym = "http://www.pubquest.com/images/icons/base_house.png";
		}else{
			color = "w";
            cat = "Brewery";
            catcolor = "#009999";
			sym = "http://www.pubquest.com/images/icons/base_brewery.png";
		}
		content = "<strong><font color='" + catcolor + "'>" + cat + "</font>"
		        + "<br/>" + name + "</strong>"
		        + "<br/><br/>" + val.ADDRESS
		        + "<br/>" + val.CITY + ",&nbsp;" + val.STATE + "&nbsp;" + val.ZIP
		        + "<br/>" + val.PHONE;
		if (val.WEBSITE.indexOf("http") >= 0)
		{
			content += "<br><br><a href='" + val.WEBSITE + "' target='_blank'>" + val.WEBSITE + "</a>";
		}
		
		var param = '"' + safeName + '",' + val.Y + ',' + val.X;
		content += "<br><br>Directions - Start Address:"
                 + "<br><input id='txtStartAddress' class='addr-box' type='text' value='" + GM.StartAddress + "' onkeyup='DF.StartAddressChanged(event,\"" + safeName + "\"," + val.Y + "," + val.X + ");' />"
                 + "<div id='bubble-dir-mode'>"
                 + "<input type='radio' id='radDirMode' name='radDirMode' class='dir-radio' onchange='DF.ModeChanged(0);' value='DRIVING' />Driving"
                 + "<input type='radio' id='radDirMode' name='radDirMode' class='dir-radio' onchange='DF.ModeChanged(1);' value='WALKING' />Walking"
                 + "<input type='radio' id='radDirMode' name='radDirMode' class='dir-radio' onchange='DF.ModeChanged(2);' value='BICYCLING' />Bicycling</div>"
                 + "<div id='dd-button'>"
                 + "<a onclick='DF.FindStartAddress(\"" + safeName + "\"," + val.Y + "," + val.X + ");' >"
                 + "<span>Get&nbsp;Directions</span></a></div>";
		
		//html = GM.CreateBubbleContent(type, html);
        
        var image = new google.maps.MarkerImage(
            sym,
            new google.maps.Size(25, 28),  // Marker is 20 pixels wide by 32 pixels tall
            new google.maps.Point(0, 0),   // Origin for image is 0,0
            new google.maps.Point(12, 28)  // Anchor for image is the point at the base 12,28
        );  
        
        zIdx++;
        var marker = new google.maps.Marker({
            position: point,
            flat: false,
            title: safeName,
            map: GM.Map,
            icon: image,
            zIndex: zIdx
        });

        var html = "<div style='width:219px;text-align:center;'>" + content + "</div>";
        var iw = new google.maps.InfoWindow( {content: html} );
    
        google.maps.event.addListener(marker, 'click', function() {
            if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
            GM.CrntMarker = marker;
            GM.BubbleOpen = true;
            GM.CrntInfoWindow = iw;
            iw.open(GM.Map, marker);
        });

		GM.Locs[key] = marker;
		GM.Info[key] = html;
		
		if (key < 30)
		{
            // Overlay the numbers for the first 30 markers
            var id = key + 1;
            sym1 = "http://www.pubquest.com/images/icons/" + color + id + ".png";
            var mi2 = new google.maps.MarkerImage(
                sym1,
                new google.maps.Size(19, 12),  // Marker is 19 pixels wide by 12 pixels tall
                new google.maps.Point(0, 0),   // Origin for image is 0,0
                new google.maps.Point(9, 23)   // Anchor for image is the center of the box 9,23
            );  
            zIdx++;
            var mrkr2 = new google.maps.Marker({
                position: point,
                flat: false,
                title: safeName,
                map: GM.Map,
                icon: mi2,
                zIndex: zIdx
            });
            google.maps.event.addListener(mrkr2, 'click', function() {
                if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
                GM.CrntMarker = mrkr2;
                GM.BubbleOpen = true;
                GM.CrntInfoWindow = iw;
                iw.open(GM.Map, mrkr2);
            });
            GM.Nums[key] = mrkr2;
		    dkey = key;
			// <tr><td>1)</td><td>The Pub</td></tr>
			nl += "<tr><td class='pub-list-number'>" + (key+1) + ")</td><td class='pub-list-name'><a onclick='GM.SetPubListIdx(" + key + ",true);'>" + name + "</a></td></tr>";
			//    + "<tr><td>&nbsp;</td><td class='pub-list-address'>" + 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);
	});

	var pl = "<select id='lstPub' onchange='GM.DisplayInfo()'>";
	if (PQ.PubID)
	{
	    pl += "<option value='-1'>Show All Craft Brewery Locations</option>";
	} else {
	    pl += "<option value='-1'>-- Select Craft Brewery Location --</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();
    
    $("#sidebar-map-header").html("Closest " + (dkey+1) + " Breweries<br/><span style='font-weight:normal;'>(to center of map)</span>");
	$("#sidebar-pub-list").html("<table>" + nl + "</table>");
    
    if (GM.FirstPubDisplay)
    {
        GM.FirstPubDisplay = false;
        $("#sidebar-map-info").show();
    }
    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]);
        //alert("BubbleKey = " + bubbleKey);
        var iw = new google.maps.InfoWindow( {content: GM.Info[bubbleKey]} );
        if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
        GM.CrntMarker = GM.Locs[bubbleKey];
        GM.BubbleOpen = true;
        GM.CrntInfoWindow = iw;
        iw.open(GM.Map, GM.CrntMarker);
	}
};

GM.SetPubListIdx = function(pubKey, show)
{
    var pubIdx = -1;
	for (var idx = 0; idx < GM.Pubs.length; idx++)
	{
	    if (GM.Pubs[idx].key == pubKey)
		{
		    pubIdx = idx + 1; // idx 0 is select a brewery so add 1
			break;
		} 
	}
    document.getElementById("lstPub").selectedIndex = pubIdx;
	//alert("PQ.SetPubListIdx = " + pubKey + ", " + pubIdx + ", show = " + show + ", " + GM.Pubs[pubIdx].name);
	if (show) GM.DisplayInfo();
};

GM.SetupStartLocation = function()
{
    GM.ShowGeolocation = false;
    var latlng = new google.maps.LatLng(GM.ClientY, GM.ClientX);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': latlng}, GM.ReverseGeocodeResult);
};

GM.ReverseGeocodeResult = function(results, status)
{
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
            GM.ClientAddress = results[1].formatted_address;
        } else {
            GM.ClientAddress = GM.ClientY + "," + GM.ClientX;
        }
        //alert("Geocoder result: " + GM.ClientAddress);
    } else {
        alert("Geocoder failed due to: " + status);
        GM.ClientAddress = GM.ClientY + "," + GM.ClientX;
    }
    GM.StartAddress = GM.ClientAddress;
    
    var loc = new google.maps.LatLng(GM.ClientY, GM.ClientX);
    var marker = new google.maps.Marker({
        position: loc,
        title: "Default start location: " + GM.ClientAddress,
        map: GM.Map,
        icon: "http://www.pubquest.com/images/icons/x.png",
        zIndex: 0
    });

    var html = "<font color='#336699'><strong>Note:</strong><br/>"
             + GM.GeolocationSource + " geolocation detected."
             + "<br/><br/><strong>" + GM.ClientAddress + "</strong>"
             + "<br/><br/>Using this location as your default starting point.</font>";

    var iw = new google.maps.InfoWindow( {content: html} );
    if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
    //GM.CrntInfoWindow = iw;
    //iw.open(GM.Map, marker);
    
    google.maps.event.addListener(marker, 'click', function() {
        if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
        GM.BubbleOpen = true;
        GM.CrntInfoWindow = iw;
        iw.open(GM.Map, marker);
    });
	   
    var s = "<p>Start Location:<br/>"
          + "<a onclick=\"GM.CenterMap(" + GM.ClientX + "," + GM.ClientY + "," + 12 + ");\" >"
          + GM.ClientAddress + "</a></p>";
    $("#sidebar-geolocation").html(s);
    $("#sidebar-geolocation-info").show();
    
    //alert("client=" + GM.ClientX + ", " + GM.ClientY + ", " + GM.ClientAddress);
    GM.ClientZoom = 13;
    GM.CenterMap(GM.ClientX, GM.ClientY, GM.ClientZoom);
};

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.CreateAddressMarker = function(type, point, text) {
	var html, sym;
	if (type == "addr")
	{
        sym = "http://www.pubquest.com/images/icons/base_addr.png";
   	    html = "Search Location:<br><br><strong>" + text.replace(/,/g,"<br/>") + "</strong>";
	}else{
   	    html = "Directions Start Location:<br><br><strong>" + text + "</strong>";
        sym = "http://www.pubquest.com/images/icons/base_house.png";
	}

    var marker = new google.maps.Marker({
        position: point,
        title: "Search location: " + GM.StartAddress,
        map: GM.Map,
        icon: sym
    });

    var iw = new google.maps.InfoWindow( {content: html} );
    if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
    GM.CrntInfoWindow = iw;
    iw.open(GM.Map, marker);
    
    google.maps.event.addListener(marker, 'click', function() {
        if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
        GM.BubbleOpen = true;
        GM.CrntInfoWindow = iw;
        iw.open(GM.Map, marker);
    });
	
	return marker;
};

GM.DisplayInfo = function() {
	//alert("Pub = " + $("#lstPub").val());
	//var idx = $("#lstPub").attr("selectedIndex");
	var idx = parseInt($("#lstPub").val()) + 1;

    if (idx > 0)
	{
		idx -= 1;
        var iw = new google.maps.InfoWindow( {content: GM.Info[idx]} );
        if (GM.CrntInfoWindow) GM.CrntInfoWindow.close();
        GM.BubbleOpen = true;
        GM.CrntInfoWindow = iw;
        iw.open(GM.Map, GM.Locs[idx]);
	} else {
		PQ.PubID = null;
	    GM.ShowSinglePub = false;
		GM.Map.setZoom(GM.PrevZoom - 1);
	}
};

/* When the DOM is ready, initialize the js libraries */
$(document).ready(GM.Init);

//]]>


