/* This Javascript is based on code provided by the Blackpool Community Church Javascript Team
	http://www.commchurch.freeserve.co.uk/   
	http://www.econym.demon.co.uk/googlemaps/ 
*/


var simpleMap;
var trafficMap;
var geocoder = null;
var bounds = new GLatLngBounds();

/* Arrays to hold copies of the markers and html used by the side_bar */
var gmarkers = [];
var htmls = [];
var i = 0;
/* Arrays to hold variants of the info window html with get direction forms open */
var to_htmls = [];
var from_htmls = [];

var zoom;
var infoSeparator = "|";
var fullInfoCount = 6; /* count of info parts that include lat/lng (pattern of line - lat|lng|address|html) */

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);

//Safeguard icon
var safeIcon = new GIcon();
safeIcon.image = '/images/thumbtack.png';
safeIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
safeIcon.iconSize = new GSize(23, 38);
safeIcon.iconAnchor = new GPoint(12, 38);
safeIcon.shadowSize = new GSize(37, 34);
safeIcon.infoWindowAnchor = new GPoint(9, 2);
safeIcon.printImage = '/images/thumbtack.png';
safeIcon.mozPrintImage = '/images/thumbtack.png';	

var icons = [];
icons[0] = safeIcon;
var nerror = 0;

function displayStaticMap(mapId, startPointLat, startPointLng, airport, zm)
{
  if (GBrowserIsCompatible())
  {
    // create the map
    map = new GMap2(document.getElementById(mapId));

    geocoder = new GClientGeocoder();
    if ((startPointLat != 0) && (startPointLng != 0))
    {
      var point = new GLatLng(startPointLat, startPointLng);
      map.setCenter(point, zm);
      loadMarker(0, false, true);
    } else if (geocoder)
    {
      geocoder.getLatLng(airport, function(point)
      {
        if (!point)
        {
         // alert(airport + " not found.");
	  document.getElementById('mapId').style.display='none';
        }
        else
        {
          map.setCenter(point, zm);
          setTimeout(function(){loadMarker(0, false, true)}, 1725);
        }

      });
    }
  }
  else
  {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}

function loadMap(mapId, startPointLat, startPointLng, airport, zm, useLetters, displayTraffic, useDirections) {
  if (displayTraffic) map = trafficMap; else map = simpleMap;
  if (map) return;
  zoom = zm;
  if (GBrowserIsCompatible())
  {

    // create the map
    map = new GMap2(document.getElementById(mapId));
    if (displayTraffic) trafficMap = map; else simpleMap = map;
    map.addControl(new GSmallMapControl());
    //map.enableScrollWheelZoom();
    map.addControl(new GMapTypeControl());
    //map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
    if (displayTraffic) map.addOverlay(new GTrafficOverlay());
    geocoder = new GClientGeocoder();
    if ((startPointLat != 0) && (startPointLng != 0))
    {
      var point = new GLatLng(startPointLat, startPointLng);
      map.setCenter(point, zoom);
      loadMarker(0, useLetters, useDirections);
    } else if (geocoder)
    {
      geocoder.getLatLng(airport, function(point)
      {
        if (!point)
        {
          //alert(airport + " not found.");
		    document.getElementById('mapId').style.display='none';
        }
        else
        {
          map.setCenter(point, zoom);
	setTimeout(function(){loadMarker(0, useLetters, useDirections)}, 1725);

        }       
      });
    }
  }
  else
  {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}

function loadMarker(markerIndex, useLetters, useDirections)
{
  if (markerIndex < markersData.length)
  {
    parts = markersData[markerIndex].split(infoSeparator);
    markerIndex++;
    /* Lat/lng were given in a data string */
    if (parts.length == fullInfoCount)
    {
      var lat = parseFloat(parts[0]);
      var lng = parseFloat(parts[1]);
      var addr = parts[2];
      var html = parts[3];
      var brand = parts[4];
      var link = parts[5];
      if ((!isNaN(lat) && (lat != 0)) && (!isNaN(lng) && (lng != 0)))
      {
        var point = new GLatLng(lat, lng);
        addMarker(point, brand, html, markerIndex - 1, useLetters, useDirections);
        loadMarker(markerIndex, useLetters, useDirections);
      } else if (geocoder)
      {
        geocoder.getLatLng(addr, function(point)
        {
          if (!point)
          {
            //alert(addr + " not found.");
          }
          else
          {
            markersData[markerIndex - 1] = point.lat() + '|' + point.lng() + '|' + addr + '|' + html + '|' + brand+ '|' + link;
            addMarker(point, brand, html, markerIndex - 1, useLetters, useDirections);
          }
          setTimeout(function(){loadMarker(markerIndex, useLetters, useDirections)}, 1725);
      });
      }
    }
  }
  else
  {
      if(markerIndex>1)
      {
        map.setZoom(map.getBoundsZoomLevel(bounds));
       }
      else
      {
        map.setZoom(15);
      }
      map.setCenter(bounds.getCenter());
  }
}

function addMarker(point, brand, html, markerIndex, useLetters, useDirections)
{
  var htmlToMarker = '';
  if (brand != '')
  {
    htmlToMarker += "<img style='float:right; margin:0 10px 10px 0;' src='/images/" + brand + "Logo_sml.jpg'></img>";
  }
  htmlToMarker += html;
  htmlToMarker += "<br/>";
  var marker = createMarker(point, htmlToMarker, markerIndex, html, useLetters, useDirections);
  map.addOverlay(marker);
  bounds.extend(marker.getPoint());
}

/* A function to create the marker and set up the event window */
function createMarker(point, html, markerIndex, descHtml, useLetters, useDirections)
{
  if(useLetters)
  {
    var letter = String.fromCharCode("A".charCodeAt(0) + markerIndex);
    var letteredIcon = new GIcon(safeIcon);

//    letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
    letteredIcon.image = "/images/thumbtack.png";

    //document.getElementById('description').innerHTML += "<img src='" + letteredIcon.image + "' /> - " + descHtml + "<br/>";
    // Set up our GMarkerOptions object
    markerOptions = { icon:letteredIcon };
    var marker = new GMarker(point, markerOptions);
  }
  else
  {
    //var marker = new GMarker(point);
    //Load Safeguard's icon instead of Google's.

   }
  // The info window version with the "to here" form open

  if (useDirections)
  {
    var addr = markersData[markerIndex].split(infoSeparator)[2].replace(/'/g,"");
  
    to_htmls[i] = html + '<br>Get directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
    '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="SUBMIT">' +
    //'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
    '<input type="hidden" name="daddr" value="' + addr + 
    // "(" + name + ")" + 
    '"/>';
    // The info window version with the "to here" form open
    from_htmls[i] = html + '<br>Get directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
    '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="SUBMIT">' +
    //'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
    '<input type="hidden" name="saddr" value="' + addr +
    // "(" + name + ")" + 
    '"/>';
    // The inactive version of the direction info
    html += '<br/>Get directions: <a href="javascript:tohere(' + i + ')">To here</a> - <a href="javascript:fromhere(' + i + ')">From here</a>';
  }
  GEvent.addListener(marker, "click", function()
  {
    //marker.openInfoWindowHtml('<div style="font-size:11px;width:200px;">' + html + '</div>');
    //showStore(markerIndex, false);
    gotoLocationPage(markerIndex);
  });
  GEvent.addListener(marker, "mouseover", function()
  {
    newHtml = html.replace('<strong>','<strong onmouseover="showLink(this);" onmouseout="hideLink(this);" onclick="gotoLocationPage(' + markerIndex + ');">')

    marker.openInfoWindowHtml('<div style="font-size:11px;width:200px;">' + newHtml + '</div>');
    showStore(markerIndex, false);
  });
  GEvent.addListener(marker, "mouseout", function()
  {
    showStore(markerIndex, true);
  });
  gmarkers[i] = marker;
  htmls[i] = html;
  i++;
  return marker;
}
      
/* This function picks up the click and opens the corresponding info window */
function myclick(i)
{
  gmarkers[i].openInfoWindowHtml('<div style="font-size:11px;width:200px;">' + htmls[i] + '</div>');
}

/*  Functions that open the directions forms */
function tohere(i) {
  gmarkers[i].openInfoWindowHtml('<div style="font-size:11px;">' + to_htmls[i] + '</div>');
}

function fromhere(i) {
  gmarkers[i].openInfoWindowHtml('<div style="font-size:11px;">' + from_htmls[i] + '</div>');
}

/* Address examples:
	350 Perimeter Center North, Atlanta, GA 30346
	1600 Amphitheatre Pky, Mountain View, CA
*/
function changePosition(addrId)
{
  var addrValue = document.getElementById(addrId).value;
  if (geocoder)
  {
    geocoder.getLatLng(addrValue, function(point)
    {
      if (!point)
      {
        alert(addrValue + " not found.");
      }
      else
      {
        //map.setCenter(point, zoom);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(addrValue);
      }
    });
  }
}

function showStore(markerIndex,out)
{
  parts = markersData[markerIndex].split(infoSeparator);
  if (parts.length == fullInfoCount)
  {
    var storename = parts[3].replace("'","").split(",");
    var listDiv = document.getElementById('storeList');
    if (listDiv != null){
      var stores = listDiv.getElementsByTagName('a');
      for(var j=0;j<stores.length;j++)
      {
	if(storename[0].indexOf(stores[j].innerHTML)>-1)
	{
	  if (out) stores[j].style.backgroundColor = "#FFFFFF";
	  else stores[j].style.backgroundColor = "#FCD116";
	}
      }
    }
  }
}

//function gotoLocationPage(markerIndex)
//{
//  parts = markersData[markerIndex].split(infoSeparator);
//  
//  if (parts.length == fullInfoCount)
//  {
//    var storename = parts[3].replace("'","").split(",");
//    var listDiv = document.getElementById('storeList');
//    var str;
//    if (listDiv != null)
//    {
//      var stores = listDiv.getElementsByTagName('a');
//      for(var k=0;k<stores.length;k++)
//      {
//	str = stores[k].innerHTML.toLowerCase().replace('<strong>','').replace('</strong>','')
//  	if(storename[0].toLowerCase().indexOf(str)>-1)
//	{
//	  location.href = stores[k].href;
//	  break;
//	}
//      }
//    }
//  }
//}

function gotoLocationPage(markerIndex)
{
  parts = markersData[markerIndex].split(infoSeparator);
  if(parts[5]!="*") location.href = parts[5];
}

function showLink(obj)
{
  obj.style.cursor='hand';
}

function hideLink(obj)
{
  obj.style.cursor='pointer';
}

// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width-3, offset.y - point.y -anchor.y -height+48)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function listMouseOver(markerIndex)
{
  parts = markersData[markerIndex].split(infoSeparator);
  //markerIndex++;
  if (parts.length == fullInfoCount)
  {
    html = parts[3];
    lat = parseFloat(parts[0]);
    lng = parseFloat(parts[1]);
    point = new GLatLng(lat, lng);
    var addr = parts[2].replace(/'/g,"");

    to_htmls[markerIndex] = html + '<br>Get directions: <b>To here</b> - <a href="javascript:fromhere(' + markerIndex + ')">From here</a>' +
    '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="SUBMIT">' +
    //'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
    '<input type="hidden" name="daddr" value="' + addr + 
    // "(" + name + ")" + 
    '"/>';
    // The info window version with the "to here" form open
    from_htmls[markerIndex] = html + '<br>Get directions: <a href="javascript:tohere(' + markerIndex + ')">To here</a> - <b>From here</b>' +
    '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="SUBMIT">' +
    //'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
    '<input type="hidden" name="saddr" value="' + addr +
    // "(" + name + ")" + 
    '"/>';
    // The inactive version of the direction info
    html += '<br/><br/>Get directions: <a href="javascript:tohere(' + markerIndex + ')">To here</a> - <a href="javascript:fromhere(' + markerIndex + ')">From here</a>';


    newHtml = html.replace('<strong>','<strong onmouseover="showLink(this);" onmouseout="hideLink(this);" onclick="gotoLocationPage(' + markerIndex + ');">');

try{
    gmarkers[markerIndex].openInfoWindowHtml('<div style="font-size:11px;width:200px;">' + newHtml + '</div>');
}
catch(err) {
  //alert('Error with ID = ' + markerIndex + ' -- ' + err.message);
}
  }
}
// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
// It launches the tooltip on the icon      
function mymouseover(i) {
  showTooltip(gmarkers[i]);		
}
// ===== This function is invoked when the mouse leaves an entry in the side_bar =====
// It hides the tooltip      
function mymouseout() {
  tooltip.style.visibility="hidden";
}

