/*
	jQuery is setup with noConflict to play well with any WordPress plugins
	that use other libraries. Using "$" will not trigger jQuery. 
	You can use "$j" or "jQuery", whichever one you prefer.
	
	[ Google Maps API Keys ]
	
	Staging URL: 	ABQIAAAANT4daNWyo92ahR94GPTWahRhooGrJ6En7Yfn589GafRfSo87XhRxciZrHV-dQr7ELqam_VZILV22hQ
	Live URL: 		ABQIAAAANT4daNWyo92ahR94GPTWahQUGR7peYAxjLPIW-I8fUhAHBFVthQgyv2E0KoGPCQoy81KMAn3b6Uxug
*/

// Extensions to jQuery
$j.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

// Document Load Event
$j(function()
{
  var city;
  var state = 'MA';
  var street;
  var zip;
  var full_address;
  var geocode;
  var bounds = new GLatLngBounds();
  var geo = new GClientGeocoder(); 				
  var reasons=[];
  
  reasons[G_GEO_SUCCESS]            = "Success";
  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address.";
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
  reasons[G_GEO_BAD_KEY]            = "Bad API Key";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
  reasons[G_GEO_SERVER_ERROR]       = "Server error";

  //Debug info  
  if(window.console&&window.console.log) { console.log('maps.js Loaded'); }

  //Set starting map location, and map attributes
  var map = new GMap2(document.getElementById('map'));
  map.setMapType(G_HYBRID_MAP);
  map.setUIToDefault();
  map.disableScrollWheelZoom();
  map.disableDoubleClickZoom();
  var maine = new GLatLng(43.661471,-70.255326);
  map.setCenter(maine, 8);
  
  function draw_error(error) { $j('#errors').html(error); }
  
  //Get gecode
  function geoEncode() {  	
  	geo.getLocations(full_address, function (result)
    {
  		if(result.Status.code == G_GEO_SUCCESS)
  		{
  			geocode = result.Placemark[0].Point.coordinates;
  			makePointFromGeocode(geocode);
  		}
  		else
  		{
  			var reason="Code "+result.Status.code;
  			if (reasons[result.Status.code]) { reason = reasons[result.Status.code] } 
  			draw_error(reason);
  			geocode = false;
  		}
    });
  }
  
  //Set camera
  function zoomToBounds(marker)
  {
    bounds = new GLatLngBounds();
    bounds.extend(marker.getPoint());
    map.setCenter(bounds.getCenter());
    map.setZoom(map.getBoundsZoomLevel(bounds)-1);
  }
  
  //Update map
  function makePointFromGeocode(geocode) {
    data = new Array();
  
  	data[0] = { name: "lng", value: geocode[0] };
  	data[1] = { name: "lat", value: geocode[1] };
  	
  	var new_loc = new GLatLng(geocode[1], geocode[0]);
    
    map = new GMap2(document.getElementById('map'));
    map.setMapType(G_HYBRID_MAP);
    map.setUIToDefault();
    map.clearOverlays();
    map.setCenter(new_loc, 8);
    
    //http://code.google.com/apis/maps/documentation/overlays.html#Draggable_Markers
    //http://www.powerhut.co.uk/googlemaps/custom_markers.php 
    
    var myIcon = new GIcon();
  	myIcon.image = '/wp-content/themes/alteris/images/maps/image.png';
  	myIcon.shadow = 'markers/shadow.png';
  	myIcon.iconSize = new GSize(30,30);
  	myIcon.shadowSize = new GSize(45,30);
  	myIcon.iconAnchor = new GPoint(15,30);
  	myIcon.infoWindowAnchor = new GPoint(15,0);
  	myIcon.printImage = '/wp-content/themes/alteris/images/maps/printImage.gif';
  	myIcon.mozPrintImage = '/wp-content/themes/alteris/images/maps/mozPrintImage.gif';
  	myIcon.printShadow = '/wp-content/themes/alteris/images/maps/printShadow.gif';
  	myIcon.transparent = '/wp-content/themes/alteris/images/maps/transparent.png';
  	myIcon.imageMap = [18,0,19,1,20,2,21,3,22,4,22,5,22,6,22,7,22,8,22,9,22,10,22,11,21,12,21,13,21,14,20,15,20,16,20,17,19,18,19,19,18,20,18,21,17,22,17,23,17,24,16,25,16,26,15,27,15,28,14,29,14,29,14,28,13,27,13,26,13,25,12,24,12,23,11,22,11,21,10,20,10,19,10,18,9,17,9,16,8,15,8,14,8,13,7,12,7,11,7,10,6,9,6,8,6,7,6,6,7,5,7,4,8,3,8,2,9,1,11,0];
    
    var marker = new GMarker(new_loc, {draggable: true, icon:myIcon});
    
    GEvent.addListener(marker, "dragstart", function() {
      marker.openInfoWindowHtml("Please drop the marker on top of your home.");
    });
    
    GEvent.addListener(marker, "drag", function() {
      marker.openInfoWindowHtml("Please drop the marker on top of your home.");
    });
        
    GEvent.addListener(marker, "dragend", function() {
      var latlng = marker.getLatLng();
      // Pass lat lng URL to SalesForce
      var geoLink = 'http://www.alterisinc.com/maps.php?lat=' + latlng.lat() + $j.URLDecode('&') + 'lng=' + latlng.lng();
      $j('.lead_latlngurl').val(geoLink);
      $j.URLDecode($j('.lead_latlngurl').val());
      if(window.console&&window.console.log) { console.log('ENCODED lead_latlngurl: '+$j.URLDecode($j('.lead_latlngurl').val())); }
      // Check "yes" for cursor verification
      $j('#res_eval_cursor_roof[value="Yes"]').trigger('click');
      // Pass latitude to SalesForce
      $j('.lead_latitude').val(latlng.lat());
      // Pass longitude to SalesForce
      $j('.lead_longitude').val(latlng.lng());
    });
    
    map.addOverlay(marker);
    
		zoomToBounds(marker);
  }
  
  //Track user's movement through form and check to see if we have enough information to request a geocode.
  $j('input').blur(function()
  {    
    connect = false;
  
    field_name = $j(this).attr('name');
    
    //Gather field values
    if(field_name == '00N40000001fLYV') { street = $j(this).val(); connect = true; }
    else if(field_name == '00N40000001fLZM') { city = $j(this).val(); connect = true; }
    else if(field_name == '00N40000001fLZg') { zip = $j(this).val(); connect = true; }
    
    //Build full address
    if(street && city && state && zip) { full_address = street + ' ' + city + ' ' + state + ' ' + zip; }
    
    //Send along to create geocode
    if(full_address && connect == true) { geoEncode(); }
  });
  
  $j('select').change(function()
  {
    field_name = $j(this).attr('name');
    
    if(field_name == '00N40000001fLZR') { state = $j(this).val(); }
  });
});