var map = null;
var geocoder = null;
var markerArray = new Array();
var functionArray = new Array();
var markerIndex = 0;
var HelpWindow = null
var bListClicked=false;
var AlphaOptions = null;
var MapCenter = null
var CenterAddress = null;
var CenterIcon = null;
var CenterMarker = null;

// Start GlhMarker Object
function GlhMarker(marker,name,address,url,markerIndex)
{
this.Marker = marker;
this.Name = name;
this.Address = address;
this.Url = url;
this.MarkerIndex = markerIndex;
this.DistanceFromCenter = -1;
}
GlhMarker.prototype =
{
   GetLat: function()
   {
        return this.Marker.getPoint().lat();
   },
   GetLng: function()
   {
        return this.Marker.getPoint().lng();
   },
   LatLngString: function()
   {
		LatLng = this.Marker.getPoint();
		return LatLng.lat() + "," + LatLng.lng();
   },
   InfoWindowText: function()
   {
		if (this.Url!="")
		{
			strHeading = "<a class='mapBalloonHeading' href='" + this.Url + "' target='_blank'>" + this.Name + "</a><br>";
		}
		else
			strHeading = "<div class='mapBalloonHeading'>" + this.Name + "</div>";	
		strDistance = "";
		if (this.DistanceFromCenter!=-1)
		{
			MilesToCenter = this.DistanceFromCenter / 1609.344;
			MilesToCenter = Math.round(MilesToCenter*10) / 10;
			strDistance=" (" + MilesToCenter + " miles)";
		}
		strZoom = "<br>Zoom: <a class='mapBalloonInfo' href='#' onclick='BubbleZoom(" + this.LatLngString() + ",1);return false;'> In</a>";
		strZoom += " - <a class='mapBalloonInfo' href='#' onclick='BubbleZoom(" + this.LatLngString() + ",-1);return false;'>Out</a>";
		strZoom += " - <a class='mapBalloonInfo' href='#' onclick='BubbleZoomToClicked(" + this.LatLngString() + ");return false;'>Street</a>";
 		strBubbleInfo = this.Address + strDistance + strZoom;
		return strHeading + strBubbleInfo;
   }
}
// End of Marker Object
function SetBounds(marker1,marker2)

{
	var bounds = new GLatLngBounds();
	bounds.extend(marker1.getPoint());
	bounds.extend(marker2.getPoint());
	map.setZoom(map.getBoundsZoomLevel(bounds)-1);
	map.setCenter(bounds.getCenter());
}
function CenterOnAddressButtonClicked()
{
	var address = document.getElementById("CenterAddress").value;
	if (address.indexOf("Lat,Lng=")>=0)
	{
		var strParams = address.split("=",2);
		var LatLng = strParams[1].split(",",2);
		var point = new GLatLng(LatLng[0],LatLng[1]);
		map.setCenter(point);
		return;
	}
	geocoder.getLatLng(address,CenterMap);
}
function MoveCenterMarker()
{
    if (MapCenter==null)
        MapCenter = map.getCenter();
    if (CenterMarker==null)
    {
        var icon = GetCenterIcon();
        CenterMarker = new GMarker(MapCenter,icon);
        GEvent.addListener(CenterMarker, "click",
           function()
           {
               ZoomLink = "<br>Marks the address in the textbox";
               if (!IsAlphaSort())
                   ZoomLink += "<br><a class='mapBalloonInfo' href='#' onclick='ShowClosestRetailer();return false;'>Zoom to closest retailer</a>";
               CenterMarker.openInfoWindowHtml(document.getElementById("CenterAddress").value + ZoomLink);
           });
        map.addOverlay(CenterMarker);
    }
    else
    {
        CenterMarker.setPoint(MapCenter);
    }
}
function ShowClosestRetailer()
{
    if (IsAlphaSort())
        return;
    glhMarkerObj = GetMarkerAtList(0);
    SetBounds(CenterMarker,glhMarkerObj.Marker);
    glhMarkerObj.Marker.openInfoWindowHtml(glhMarkerObj.InfoWindowText());
}
function SortAlphaCheckBoxClicked()
{
    ReSortListLinkOff();
    radioAlpha = document.getElementById("radioSortAlpha");
    radioDistance = document.getElementById("radioSortDistance");
    radioAlpha.checked=true;
    radioDistance.checked=false;

    SortAlpha();
}
function SortDistanceCheckBoxClicked()
{
    if (!IsAlphaSort())
        return;
    SortDistance();
    SetAddressToMapCenter();
}
function NewCenterLinkClicked()
{
    SortDistance();
    SetAddressToMapCenter();
}
function SortAlpha()
{
    options = document.getElementById("RetailerListBox").options;

    for (index1=0;index1<markerIndex-1;index1++)
    {
        for (index2=index1+1;index2<markerIndex;index2++)
        {
            if (options[index1].text > options[index2].text)
                SwapOptions(options,index1,index2);
        }
    }
}
function MyDebug(message)
{
    alert(message);
}
function IsAlphaSort()
{
    return document.getElementById("radioSortAlpha").checked;
}
function SortDistance()
{
    ReSortListLinkOff();
    radioAlpha = document.getElementById("radioSortAlpha");
    radioDistance = document.getElementById("radioSortDistance");
    radioAlpha.checked=false;
    radioDistance.checked=true;
    listBox = document.getElementById("RetailerListBox");

    var options = listBox.options;

    MapCenter = map.getCenter();
    for (index=0;index<markerIndex;index++)
    {
        distance = MapCenter.distanceFrom(markerArray[index].Marker.getPoint());
        markerArray[index].DistanceFromCenter = distance;
    }
    for (var index1=0;index1<markerIndex-1;index1++)
    {
        for(var index2=index1+1;index2<markerIndex;index2++)
        {
            if (GetMarkerAtList(index1).DistanceFromCenter > GetMarkerAtList(index2).DistanceFromCenter)
               {
                SwapOptions(options,index1,index2);
               }
        }
    }
    listBox.selectedIndex=0;
    listBox.selectedIndex=-1;
}
function SwapOptions(options,swapIndex1,swapIndex2)
{
    tempoption=document.createElement('option');
    temptext=options[swapIndex2].text;
    tempvalue=options[swapIndex2].value;
    options[swapIndex2].text = options[swapIndex1].text;
    options[swapIndex2].value = options[swapIndex1].value;
    options[swapIndex1].text = temptext;
    options[swapIndex1].value = tempvalue;
}
function addToList(listControl, newText, newValue)
{
	var len = listControl.length++; // Increase the size of list and return the size
	listControl.options[len].value = newValue;
	listControl.options[len].text = newText;
} // Ends the check to see if the value entered on the form is empty

function OpenHelpWindow()
{
    if (HelpWindow==null)
        HelpWindow = window.open("MapHelp.htm","_blank","width=400,height=300,scrollbars");
    else
        {
            if (HelpWindow.closed)
                HelpWindow = window.open("MapHelp.htm","_blank","width=400,height=300,scrollbars");
            else
                HelpWindow.focus();
        }
}
function SetAddressToMapCenter()
{
    MapCenter = map.getCenter();
    addressEditBox = document.getElementById("CenterAddress");
    addressEditBox.value = "Lat,Lng=" + MapCenter.toUrlValue();
    MoveCenterMarker();
}
function Unloading()
{
    GUnload();
	if (HelpWindow==null)
		return;
	if (HelpWindow.closed)
		return;
	HelpWindow.close();
}
function createMarker(point, name, address, url, index)
{
    var latLng = point.lat() + "," + point.lng();
    addToList(document.getElementById("RetailerListBox"),name,latLng);
	var marker = new GMarker(point);
    MarkerObject = new GlhMarker(marker,name,address,url,markerIndex)
    markerArray[markerIndex] = MarkerObject;
    var index = markerIndex;
    functionArray[markerIndex]  = 
        function()
            {
                MarkerClicked(index);
 			}
	GEvent.addListener(marker, "click", functionArray[markerIndex]);
    markerIndex++;
	return marker;
}
function MarkerClicked(markerIndex)
{
    MarkerObj = markerArray[markerIndex];
    MarkerObj.Marker.openInfoWindowHtml(MarkerObj.InfoWindowText());
    
    if (bListClicked==false)
        document.getElementById("RetailerListBox").selectedIndex=GetListIndex(MarkerObj.Name);
}
function GetListIndex(markerName)
{
    listOptions=document.getElementById("RetailerListBox").options;
    for(index=0;index<markerIndex;index++)
    {
        if (listOptions[index].text == markerName)
            return index;
    }
    return -1;
}
function GetMarkerAtList(listIndex)
{
    listName = document.getElementById("RetailerListBox").options[listIndex].text;
    for (index=0;index<markerIndex;index++)
    {
        ListName = markerArray[index].Name;
        if (ListName==listName)
            return markerArray[index];
    }
    MyDebug("Couldn't Find '" + listName + "'");
}
function RetailerListClicked(LatLng,index)
{
    bListClicked = true;
    MarkerClicked(GetMarkerAtList(index).MarkerIndex);
    bListClicked = false;
}
function BubbleZoomToClicked(lat,lng)
{
    ZoomTo(lat,lng,15);
}
function BubbleZoom(lat,lng ,deltaZoom)
{
    newZoom = map.getZoom() + deltaZoom;
    if (newZoom > 17)
        newZoom = 17;
    ZoomTo(lat,lng,newZoom);
}
function ZoomTo(lat,lng,zoom)
{
    var point = new GLatLng(lat,lng);
    map.setCenter(point,zoom);
}
function CenterMap(point) 
{
    if (!point)
    {
        var address = document.getElementById("CenterAddress").value;
        alert(address + " not found");
    }
	else
	{
        map.setCenter(point, 13);
        SortDistance();
        MoveCenterMarker();
    }
}
function ReSortListLinkOn()
{
    link = document.getElementById("NewCenterLink");
    link.innerHTML="Set Address to center of map";
}
function ReSortListLinkOff()
{
    link = document.getElementById("NewCenterLink");
    link.innerHTML="";
}
function MapPanned()
{
   if (IsAlphaSort())
       return;
   ReSortListLinkOn();
}

function GetCenterIcon()
{
   if (CenterIcon==null)
   {
		// Create our "tiny" marker icon
		var icon = new GIcon();
		icon.image = "../images/map/mm_20_red.png";
		icon.shadow = "../images/map/mm_20_shadow.png";
		icon.iconSize = new GSize(12, 20);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
   }
   return icon;
}
function GoToRetailerMap()
{
    window.open("http://www.hatcherwinery.com/ourwine/retailermap.aspx","_self");
}