/*
 * Google Maps API V3
 */
var strLat, strLng, strName, strAddr, strCsz;
var strToHtml, strFromHtml, strHtml, strStartAddr, strDestAddr;
var strLocation;
var boolIsSafari = false;
var objDirRend, objDirServ, objMarker, objMap, objInfoWindow;
var intDirectionWidth = 120;
var dirError = new Array();
dirError["INVALID_REQUEST"] = "<h3>The request you entered was invalid.  Please try again.  If the problem persists please contact us.</h3>";
dirError["NOT_FOUND"] = "<h3>The location you entered could not be found.  Please try again.  If the problem persists please contact us.</h3>";
dirError["UNKNOWN_ERROR"] = "<h3>An unknown error occured.  Please try again.  If the problem persists please contact us.</h3>";
dirError["ZERO_RESULTS"] = "<h3>No route could be determined for the location you entered.</h3>";
dirError["ERROR"] = "<h3>Unable to connect to Google Servers.  Please try again later.  If the problem persists please contact us.</h3>";
dirError["OVER_QUERY_LIMIT"] = "<h3>To many queries have been submitted.  Please try again later.  If the problem persists please contact us.</h3>";
dirError["REQUEST_DENIED"] = "<h3>The request has been denied.  Please try again later.  If the problem persists please contact us.</h3>";

$(document).ready(function() 
{
   if(navigator.userAgent.toLowerCase().indexOf("safari") != -1)
   {
      boolIsSafari = true;
   }
   // create the small map
   $('#map').css({'background-image': 'url(http://maps.google.com/maps/api/staticmap?center='+strLat+','+strLng+'&zoom=15&size=200x200&maptype=hybrid&markers='+strLat+','+strLng+'&sensor=false)'});
   initMap();
});

function init(){
   initMap();
   tohere();
   objInfoWindow.open(objMap, objMarker);
   google.maps.event.trigger(objMap, 'resize');
}

function initMap()
{
   strLocation = new google.maps.LatLng(strLat, strLng);
   mapTypes = new Array(google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP)
   var mapOptions = {
      zoom: 15,
      center: strLocation,      
      mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
      mapTypeId: google.maps.MapTypeId.HYBRID
   }
   objMap = new google.maps.Map(document.getElementById("map2"),mapOptions);
   
   createMarker(strLocation);
   
   var dirRendOptions = {
      map: objMap,
      draggable: true
   };
   
   objDirRend = new google.maps.DirectionsRenderer(dirRendOptions);
   objDirRend.setPanel(document.getElementById("directionsResult"));
}

// request the directions
function getDirections() 
{
   //clears the last result
   $('#directionsResult').text('');

   // set the start and end locations
   strStartAddr = document.getElementById("saddr").value;
   strDestAddr = document.getElementById("daddr").value;
   
   var dirServOptions = {
      origin: strStartAddr,
      destination: strDestAddr,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
   };
   
   objDirServ = new google.maps.DirectionsService();
   
   objDirServ.route(dirServOptions, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
         objDirRend.setDirections(response);
      }
      else
      {
         $('#directionsResult').html(dirError[status]);
      }
   });
   
   if($('#directions').is(':hidden'))
   {
      var intWidth = getCenterWidth('#mapPopup') - intDirectionWidth;
      $('#mapPopup').animate({
         left : intWidth}, 1000, function(){
         if(boolIsSafari)
         {
            $('#directions').css({"display": "block"});
         }
         else
         {
            $('#directions').show(1000);
         }
      });
   }
}

// sets the info for the map to display
function setMap(strLatitude, strLongitude, strLocationName, strLocationAddress,  strCityStateZip) 
{
   strLat = strLatitude;
   strLng = strLongitude;
   strName = strLocationName;
   strAddr = strLocationAddress;
   strCsz = strCityStateZip;
}

// A function to create the marker and set up the event window
function createMarker(point) 
{
   strHtml = strName + "<br />" + strAddr + "<br />" + strCsz;
   // The info window version with the "to here" form open
   strToHtml = strHtml
         + '<br>Directions: <strong>To here</strong> - <a href="javascript:fromhere()">From here<\/a>'
         + '<br>Start address:<form action="javascript:getDirections()">'
         + '<input type="text" size="35" maxlength=40 name="saddr" id="saddr" value="" /><br>'
         + '<input value="Get Directions" type="submit"><br>'
         + '<input type="hidden" id="daddr" value="' + strAddr + ','
         + strCsz + '"/>';
   // The info window version with the "from here" form open
   strFromHtml = strHtml
         + '<br>Directions: <a href="javascript:tohere()">To here<\/a> - <strong>From here</strong>'
         + '<br>End address:<form action="javascript:getDirections()">'
         + '<input type="text" size="35" maxlength=40 name="daddr" id="daddr" value="" /><br>'
         + '<input value="Get Directions" type="submit"><br>'
         + '<input type="hidden" id="saddr" value="' + strAddr + ','
         + strCsz + '"/>';

   objInfoWindow = new google.maps.InfoWindow({
        content: strToHtml,
        maxWidth: 250,
        zIndex: -1
    });
   
   var markerOptions = {
      position: strLocation,
      map: objMap
   }
   
   objMarker = new google.maps.Marker(markerOptions);
   
   google.maps.event.addListener(objMarker, "click", function() {
      objInfoWindow.open(objMap, objMarker);
   });
   return objMarker;
}

$(function() 
{
   $('.overlay').css( {
      "opacity" : .6
   });
   $('#getDirections').click(function() {
      checkScreenRes();
      $('html').css( {
          "overflow-x" : 'hidden'
      });   
      $('#mapPopup, .overlay').fadeIn();
      init();
      $('.overlay').css("height", $(document).height() + "px");
      $('.overlay').css("width", $(document).width() + "px");
      centerLightbox('#mapPopup');
   });
   $('#overlay').click(function() {
      $('#mapPopup, .overlay, #directions').fadeOut();
      $('html').css( {
         "overflow-x" : 'auto'
      });
   });
   $('#close').click(function() {
      $('#mapPopup, .overlay, #directions').fadeOut();
      $('html').css( {
         "overflow-x" : 'auto'
      });
   });
   $('#reset').click(function() {
      if($('#directions').is(':visible')){
         var intWidth = getCenterWidth('#mapPopup');
         $('#directions').hide(1000, function(){$('#mapPopup').animate({left : intWidth}, 1000)});
      }
      init();
   });
   
   $(window).bind('resize', function(){
      $('.overlay').css("width", $(document).width() + "px");
      checkScreenRes();
      centerLightbox('#mapPopup');
   });
});

function checkScreenRes(){
   if (($(window).width()<800) || ($(window).height()<550))
   {  
      $('#map2').css( {
         "width" : "300px", "height" : "300px"
      });
      $('#directions').css( {
         "width" : "200px", "height" : "290px"
      });
      intDirectionWidth = 100;
      $('#mapPopup').css( {
         "width" : "326px"
      });
   }
   else
   {
      $('#map2').css( {
         "width" : "500px", "height" : "500px"
      });
      $('#directions').css( {
         "width" : "240px", "height" : "490px"
      });
      intDirectionWidth = 120;
      $('#mapPopup').css( {
         "width" : "526px"
      });
   }
}

function printDirections() 
{
   window.open("http://maps.google.com/maps?f=d&source=s_d&saddr=" + strStartAddr
         + "&daddr=" + strDestAddr + "&mra=ls&t=h&z=12&layer=c&pw=2");
}

// opens the to here form
function tohere() 
{
   objInfoWindow.setContent(strToHtml);
}

// opens the from here form
function fromhere() 
{
   objInfoWindow.setContent(strFromHtml);
}
