////////   Include JSON Class Library Code- Check with Jun if need to make changes ////////
////////   Ref : http://ws.geonames.org/export/jsr_class.js
////////
// JSONscriptRequest -- a simple class for accessing Yahoo! Web Services
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}


//// Reverse geocoding support by using geonames.org JSON web service

SbxLocation_callbackName = null;
SbxLocation_scriptTagObj = null;

function SbxLocation_reverseGeocoding (lat, lng, callback_name) {
  if (SbxLocation_scriptTagObj) {
    SbxLocation_scriptTagObj.removeScriptTag ();
  }
  request = 'http://ws.geonames.org/findNearbyPostalCodesJSON?lat='+lat+'&lng='+lng+'&callback='+callback_name;
  SbxLocation_scriptTagObj = new JSONscriptRequest (request);
  SbxLocation_scriptTagObj.buildScriptTag ();
  SbxLocation_scriptTagObj.addScriptTag ();
}

var SbxLocation_globalPlacemark = null;

function SbxLocation_reverseGeocoding2 (lat, lng, callback_name) {
  SbxGmapZipView_gcg.getLocations (new GLatLng (lat, lng), function (loc) {
    if (loc.Status.code != 200) {
      return;
    }
    SbxLocation_globalPlacemark = loc.Placemark[0];
    var loc_details = new Array ();
    loc_details['state_short'] = get_object_value ('SbxLocation_globalPlacemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName', '');
    loc_details['state_long'] = get_object_value ('SbxLocation_globalPlacemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName', '');
    loc_details['county_name'] = get_object_value ('SbxLocation_globalPlacemark.AddressDetails.Country.CountryName', '');
    loc_details['country_code'] = get_object_value ('SbxLocation_globalPlacemark.AddressDetails.Country.CountryNameCode', '');
    loc_details['city_or_place'] = get_object_value ('SbxLocation_globalPlacemark.AddressDetails.Country.AdministrativeArea.Locality.LocalityName', '');
    loc_details['postal_code'] = get_object_value ('SbxLocation_globalPlacemark.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber', '');
    loc_details['latitude'] = SbxLocation_globalPlacemark.Point.coordinates[1];
    loc_details['longitude'] = SbxLocation_globalPlacemark.Point.coordinates[0];
    loc_details['address'] = SbxLocation_globalPlacemark.address;
    eval (callback_name + '(loc_details)');
  });
}

function get_object_value (global_var_name, default_val) {
  var ret;
  try {
    ret = eval (global_var_name);
    if (ret == 'undefined') {
      ret = default_val;
    }
  }
  catch (error) {
    ret = default_val;
  }
  return ret;
}
function SbxLocation_setGetLocationCallback (callback) {
  SbxLocation_callbackName = callback;
}

function SbxLocation_getLocationInfo (jData) {
  var loc_details = SbxLocation_parseLocationJsonData (jData);
  if (SbxLocation_callbackName) {
    SbxLocation_callbackName (loc_details);
  }
}

function SbxLocation_getLocationInfo2 (loc_details) {
  if (SbxLocation_callbackName) {
    SbxLocation_callbackName (loc_details);
  }
}

function SbxLocation_parseLocationJsonData (jData) {
  var ret = new Array ();
  ret['state_short'] = jData.postalCodes[0].adminCode1;
  ret['state_long'] = jData.postalCodes[0].adminName1;
  ret['county_name'] = jData.postalCodes[0].adminName2;
  ret['country_code'] = jData.postalCodes[0].countryCode;
  ret['city_or_place'] = jData.postalCodes[0].placeName;
  ret['postal_code'] = jData.postalCodes[0].postalCode;
  ret['latitude'] = jData.postalCodes[0].lat;
  ret['longitude'] = jData.postalCodes[0].lng;
  return ret;
}
/////////////////////////////////////////////////////////////////////////////////////////


var SbxGmapZipView_circle;
var SbxGmapZipView_center_marker;
var SbxGmapZipView_center_mark_draggable;
var SbxGmapZipView_init_zoom_level;
var SbxGmapZipView_proximity_miles;
var SbxGmapZipView_gmap2;
var SbxGmapZipView_gcg;
var SbxGmapZipView_click_zip_code_change_callback = null;
var SbxGmapZipView_map_onclick_callback = null;

function SbxGmapZipView_initGmapView () {
  SbxGmapZipView_center_mark_draggable = true;
  SbxGmapZipView_init_zoom_level = 9;
  SbxGmapZipView_proximity_miles = 10;
  SbxGmapZipView_gmap2 = new GMap2 (document.getElementById ("map_canvas"));
  //SbxGmapZipView_gmap2 = new GMap2 (map_canvas);
  SbxGmapZipView_gcg = new GClientGeocoder();        
  SbxGmapZipView_gmap2.addControl (new GSmallZoomControl());
  SbxGmapZipView_gmap2.removeMapType (G_HYBRID_MAP);
  SbxGmapZipView_gmap2.removeMapType (G_SATELLITE_MAP);
  SbxGmapZipView_gmap2.enableScrollWheelZoom();
  
  GEvent.addListener (SbxGmapZipView_gmap2, 'click', function (overlay, latlng) {
    if (latlng) {
      var latitude = latlng.lat();
      var longitude = latlng.lng();
      //SbxLocation_reverseGeocoding (latitude, longitude, 'SbxLocation_getLocationInfo');
      SbxLocation_reverseGeocoding2 (latitude, longitude, 'SbxLocation_getLocationInfo2');
      if (SbxGmapZipView_map_onclick_callback) {
        SbxGmapZipView_map_onclick_callback (latitude, longitude);
      }
    }
  });
}

function SbxGmapZipView_setGmapOnclickCallback (callback) {
  SbxGmapZipView_map_onclick_callback = callback;
}

function SbxGmapZipView_centerMapByZipCode (zip_code, callback_func) {  
  if (zip_code) {
    SbxGmapZipView_gcg.getLatLng (zip_code, function (latlng) {
      if (latlng) {
        SbxGmapZipView_setGmapCenterAndZoomLevel (latlng);
        SbxGmapZipView_drawProximityCircleAndMark ();
        if (callback_func) {
          callback_func (latlng.lat(), latlng.lng());
        }
      }
    });
  }
}

function SbxGmapZipView_centerMapByLatlng (latlng, callback_func) {  
  if (latlng) {
    SbxGmapZipView_resetCenterMarker ();
    SbxGmapZipView_setGmapCenterAndZoomLevel (latlng);
    SbxGmapZipView_drawProximityCircleAndMark ();
    if (callback_func) {
      callback_func (latlng.lat(), latlng.lng());
    }
  }
}

function SbxGmapZipView_setGmapCenterAndZoomLevel (latlng) {
  if (SbxGmapZipView_init_zoom_level) {
    SbxGmapZipView_gmap2.setCenter (latlng, SbxGmapZipView_init_zoom_level);
    SbxGmapZipView_init_zoom_level = 0;
  }
  else {
    SbxGmapZipView_gmap2.setCenter (latlng);
  }
}

function SbxGmapZipView_setProximityMiles (miles) {
  SbxGmapZipView_proximity_miles = miles;
}

function SbxGmapZipView_setCenterMarker (dragend_callback) {
  if (SbxGmapZipView_center_marker) {
    SbxGmapZipView_setGmapCenterAndZoomLevel (SbxGmapZipView_center_marker.getLatLng());
  }
  else {
    SbxGmapZipView_center_marker = new GMarker (SbxGmapZipView_gmap2.getCenter(),
      {
        draggable:SbxGmapZipView_center_mark_draggable
      }
    );
    GEvent.addListener (SbxGmapZipView_center_marker, 'dragend', dragend_callback);
    SbxGmapZipView_gmap2.addOverlay (SbxGmapZipView_center_marker);
  } 
}

function SbxGmapZipView_resetCenterMarker () {
  if (SbxGmapZipView_center_marker) {
    SbxGmapZipView_gmap2.removeOverlay (SbxGmapZipView_center_marker);
    SbxGmapZipView_center_marker = null;
  }
}

function SbxGmapZipView_centerMarkDragEndHandler () {
  SbxGmapZipView_drawProximityCircleAndMark ();
  var latlng = SbxGmapZipView_center_marker.getLatLng();
  var lat = latlng.lat();
  var lng = latlng.lng();
  SbxLocation_reverseGeocoding2 (lat, lng, 'SbxLocation_getLocationInfo2');
}

function SbxGmapZipView_drawProximityCircleAndMark () {
  var circle_points = Array();
  if (SbxGmapZipView_circle) {
    SbxGmapZipView_gmap2.removeOverlay (SbxGmapZipView_circle);
  }

  //SbxGmapZipView_setCenterMarker (SbxGmapZipView_drawProximityCircleAndMark);
  SbxGmapZipView_setCenterMarker (SbxGmapZipView_centerMarkDragEndHandler);
  
  var center = SbxGmapZipView_gmap2.getCenter();
  var bounds = new GLatLngBounds();
  if (!SbxGmapZipView_proximity_miles) {
    return;
  }
  with (Math) {
    var d = SbxGmapZipView_proximity_miles/3963.189;	// radians
    var lat1 = (PI/180)* center.lat(); // radians
    var lng1 = (PI/180)* center.lng(); // radians

    for (var a = 0 ; a < 361 ; a++ ) {
      var tc = (PI/180)*a;
      var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
      var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
      var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
      var point = new GLatLng (parseFloat(y*(180/PI)), parseFloat(x*(180/PI)));
      circle_points.push (point);
	    bounds.extend(point);
    }

    if (d < 1.5678565720686044) {
      SbxGmapZipView_circle = new GPolygon (circle_points, '#888888', 1, 1, '#000000', 0.10);
    }
    else {
      SbxGmapZipView_circle = new GPolygon (circle_points, '#000000', 1, 1);
    }
    SbxGmapZipView_gmap2.addOverlay (SbxGmapZipView_circle);
    SbxGmapZipView_gmap2.setZoom (SbxGmapZipView_gmap2.getBoundsZoomLevel (bounds)); 
  }
}

function SbxGmapZipView_setCenterMarkDraggable (flag) {
  SbxGmapZipView_center_mark_draggable = flag;
}

function SbxGmapZipView_setProximityMiles (miles) {
  SbxGmapZipView_proximity_miles = miles;
}
function SbxGmapZipView_setClickZipCodeChangeCallback (callback) {
  SbxGmapZipView_click_zip_code_change_callback	= callback;
}

function SbxGmapZipView_convertProximityCodeToMiles (selected_code) {
  /*
  var miles = 0;
  if (selected_code == 1)      miles = 5;
  else if (selected_code == 2) miles = 10;
  else if (selected_code == 3) miles = 20;
  else if (selected_code == 4) miles = 30;
  else if (selected_code == 5) miles = 50;
  return miles;
  */
 return selected_code;
}

