// Constant definitions
var css_canvas_class_name = 'mysbxMapCanvas';
var css_address_display_class_name = 'mysbxMapAddress';
var css_map_it_button_class_name = 'button mapIt';
var html_map_it_button_text = 'Map It';
var html_address_display_title = '<label>Current Map Location:</label>';

var sbx_location_on_demand_gmap_load_flag = false;
var sbx_location_on_demand_gmap_init_flag = false;
var sbxPost_state_short    = null;
var sbxPost_country_code   = null;
var sbxPost_city_or_place  = null;
var sbxPost_postal_code    = null;
var sbxPost_lat            = null;
var sbxPost_lng            = null;
var sbxPost_address        = null;
var curr_lat = 0;
var curr_lng = 0;
var curr_loc_details_comp = null;
var curr_loc_details_pick = null;
var location_selection = "";
var comp_zip = '';
var gmap_canvas = null;
var address_display = null;
var location_type = null;
var location_val_label = null;
var location_val = null;
var location_code_label = null;
var location_code = null;
var map_it_button = null;

////
var company_postal_code_name = '';
var location_val_label_name = '';
var location_val_name = '';
var location_code_label_name = '';
var location_code_name = '';
var location_type_name = '';
var state_short_field_name = '';
var country_code_field_name = '';
var city_or_place_field_name = '';
var postal_code_field_name = '';
var lat_field_name = '';
var lng_field_name = '';
var address_field_name = '';
var user_location_str_field_name = '';
////

function sbx_location_view_init_standard_post () {
  var sbx_loc_view_cfg = {
    company_postal_code_name : 'company_postal_code',
    location_val_label_name : 'edit-location-val',
    location_val_name : 'location_val',
    location_code_label_name : 'edit-location-code',
    location_code_name : 'location_code',
    location_type_name : 'location_type',
    state_short_field_name : 'sbxPost_state_short',
    country_code_field_name : 'sbxPost_country_code',
    city_or_place_field_name : 'sbxPost_city_or_place',
    postal_code_field_name : 'sbxPost_postal_code',
    lat_field_name : 'sbxPost_lat',
    lng_field_name : 'sbxPost_lng',
    address_field_name : 'sbxPost_address',
    user_location_str_field_name : 'user_location_str'
  };
  $(window).load ( function () {
    sbx_location_view_init (sbx_loc_view_cfg);
  });
}


function sbx_location_view_init_standard_search () {
  var sbx_loc_view_cfg = {
    company_postal_code_name : 'company_postal_code',
    location_val_label_name : 'edit-sbxSearch-location-val',
    location_val_name : 'sbxSearch_location_val',
    location_code_label_name : 'edit-sbxSearch-location-code',
    location_code_name : 'sbxSearch_location_code',
    location_type_name : 'sbxSearch_location_type',
    state_short_field_name : 'sbxSearch_state_short',
    country_code_field_name : 'sbxSearch_country_code',
    city_or_place_field_name : 'sbxSearch_city_or_place',
    postal_code_field_name : 'sbxSearch_postal_code',
    lat_field_name : 'sbxSearch_lat',
    lng_field_name : 'sbxSearch_lng',
    address_field_name : 'sbxSearch_address',
    user_location_str_field_name : 'user_location_str'
  };
  $(window).load ( function () {
    sbx_location_view_init (sbx_loc_view_cfg);
  });
}

function sbx_location_view_set_params (sbx_loc_view_cfg) {
  company_postal_code_name = sbx_loc_view_cfg.company_postal_code_name;
  location_val_label_name = sbx_loc_view_cfg.location_val_label_name;
  location_val_name = sbx_loc_view_cfg.location_val_name;
  location_code_label_name = sbx_loc_view_cfg.location_code_label_name;
  location_code_name = sbx_loc_view_cfg.location_code_name;
  location_type_name = sbx_loc_view_cfg.location_type_name;
  state_short_field_name = sbx_loc_view_cfg.state_short_field_name;
  country_code_field_name = sbx_loc_view_cfg.country_code_field_name;
  city_or_place_field_name = sbx_loc_view_cfg.city_or_place_field_name;
  postal_code_field_name = sbx_loc_view_cfg.postal_code_field_name;
  lat_field_name = sbx_loc_view_cfg.lat_field_name;
  lng_field_name = sbx_loc_view_cfg.lng_field_name;
  address_field_name = sbx_loc_view_cfg.address_field_name;
  user_location_str_field_name = sbx_loc_view_cfg.user_location_str_field_name;
}

function sbx_location_view_init (sbx_loc_view_cfg) {
  sbx_location_view_set_params (sbx_loc_view_cfg);
 
  comp_zip = "" + $('[name="' + company_postal_code_name + '"]').fieldValue();
  location_type = $('[name="' + location_type_name + '"]');
  location_val_label = $('label[for="' + location_val_label_name +'"]');
  location_val = $('[name="' + location_val_name +'"]')
  location_code_label = $('label[for="' + location_code_label_name +'"]');
  location_code = $('[name="' + location_code_name +'"]');
  
  sbxPost_state_short = $('[name="' + state_short_field_name  + '"]');
  sbxPost_country_code = $('[name="' + country_code_field_name  + '"]');
  sbxPost_city_or_place = $('[name="' + city_or_place_field_name  + '"]');
  sbxPost_postal_code = $('[name="' + postal_code_field_name  + '"]');
  sbxPost_lat = $('[name="' + lat_field_name  + '"]');
  sbxPost_lng = $('[name="' + lng_field_name  + '"]');
  sbxPost_address = $('[name="' + address_field_name  + '"]');
  
  gmap_canvas = $('<div id="map_canvas" class="' + css_canvas_class_name + '"></div>');
  gmap_canvas.insertAfter (location_val);
  address_display = $('<div id="sbx_map_location_address" class="' + css_address_display_class_name + '"></div>');
  address_display.insertAfter (location_val);
  map_it_button = $('<input type="button" id="sbx_map_it_button" value="' + html_map_it_button_text + '" class="' + css_map_it_button_class_name + '" />');
  map_it_button.insertAfter (location_code);

  curr_lat = sbxPost_lat.fieldValue();
  curr_lng = sbxPost_lng.fieldValue();
  curr_address = sbxPost_address.fieldValue();
  
  sbx_init_loc_details();
  
  HideAndSeek();
  
  location_type.click (function () {
    HideAndSeek();
  });
  
  location_code.blur (sbx_on_location_code_change);
  location_code.bind ('keypress', function (e) {
    if (e.keyCode == 13) {
      sbx_on_location_code_change ();
      return false;
    }
    return true;
  });

  location_val.change (function() {
    drawCircle();
  });
}

function sbx_location_on_demand_gmap_load (callback_name) {
  if (sbx_location_on_demand_gmap_load_flag == false) {
    sbx_location_on_demand_gmap_load_flag = true;
    var script = document.createElement ("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps?file=api&v=2.x&key=" + sbx_gmap_key + "&async=2&callback=" + callback_name;
    document.body.appendChild (script);
  }
  else {
    eval (callback_name + '()');
  }
}

function sbx_location_on_demand_gmap_init () {
  if (sbx_location_on_demand_gmap_init_flag == false) {
    sbx_location_on_demand_gmap_init_flag = true;
    SbxGmapZipView_initGmapView();
    SbxGmapZipView_setClickZipCodeChangeCallback(on_click_zip_code_change);
    SbxGmapZipView_setCenterMarkDraggable(true);
    SbxGmapZipView_setProximityMiles(SbxGmapZipView_convertProximityCodeToMiles(location_val.fieldValue()));
    SbxLocation_setGetLocationCallback(on_reverse_geocoding);
    SbxGmapZipView_setGmapOnclickCallback(on_map_click);
  }
}

function sbx_on_location_code_change () {
  SbxGmapZipView_resetCenterMarker();
  SbxGmapZipView_centerMapByZipCode("" + location_code.fieldValue(), new_geocode_center_callback);
}

function sbx_show_or_hide_location_map_ui_elements (show) {
  if (show) {
    if ($('#edit-page').val() != 'customers' && $('#edit-page').val() != 'customers-edit') {
      location_val_label.show();
      location_val.show();
    }
    else
    {
      location_val_label.hide();
      location_val.hide();
    }
    location_code_label.show();
    location_code.show();
    address_display.show();
    map_it_button.show();
  }
  else {
    location_val_label.hide();
    location_val.hide();
    location_code_label.hide();
    location_code.hide();
    address_display.hide();
    map_it_button.hide();
  }
}

function sbx_init_loc_details () {
  var state_short   = sbxPost_state_short.fieldValue ();
  var country_code  = sbxPost_country_code.fieldValue ();
  var city_or_place = sbxPost_city_or_place.fieldValue ();
  var postal_code   = sbxPost_postal_code.fieldValue ();
  var lat           = sbxPost_lat.fieldValue ();
  var lng           = sbxPost_lng.fieldValue ();
  var address       = sbxPost_address.fieldValue ();
  if (lat != '') {
    loc_details = new Array ();
    loc_details['latitude'] = lat;
    loc_details['longitude'] = lng;
    loc_details['state_short'] = state_short;
    loc_details['country_code'] = country_code;
    loc_details['city_or_place'] = city_or_place;
    loc_details['postal_code'] = postal_code;
    loc_details['address'] = address;
    sel = $('[name="' + location_type_name + '"]:checked').val();
    if (sel == '2') {
      curr_loc_details_comp = loc_details;
    }
    else if (sel == '3') {
      curr_loc_details_pick = loc_details;
    }
  }
}

function on_click_zip_code_change (zip_code) {
  location_code.val (zip_code);
}

function on_reverse_geocoding (loc_details) {
  location_code.val (loc_details['postal_code']);
  set_sbxPost_location_values (loc_details);
  sbx_set_curr_location_details (loc_details);
}

function HideAndSeek () {
  location_selection = $('[name="' + location_type_name + '"]:checked').val();
  if (location_selection == 2 || location_selection == 3) {
    sbx_location_on_demand_gmap_load ('sbx_refresh_selected_location_view');
  }
  else {
    sbx_refresh_selected_location_view ();
  }
}

function sbx_refresh_selected_location_view () {
  switch (location_selection) {
    case '1':
    case '5':
    case '6':
    case '7':
      sbx_show_or_hide_location_map_ui_elements (false);
      if ($('#edit-page').val() != 'customers' && $('#edit-page').val() != 'customers-edit') {
        location_code.val('');
      }
      sbxPost_state_short.val('');
      sbxPost_country_code.val('');
      sbxPost_city_or_place.val('');
      sbxPost_postal_code.val('');
      sbxPost_lat.val('');
      sbxPost_lng.val('');
      sbxPost_address.val('');
      hideMapCanvas();
      break;    
    case '2':
      sbx_show_or_hide_location_map_ui_elements (true);
      location_code.val($('[name="' + company_postal_code_name + '"]').fieldValue());
      (location_code.fieldValue()[0]) ? location_code.attr("readonly", true) : location_code.attr("readonly", false);
      showMapCanvas();
      sbx_location_on_demand_gmap_init ();
      SbxGmapZipView_setCenterMarkDraggable (false);
      SbxGmapZipView_resetCenterMarker ();
      SbxGmapZipView_centerMapByZipCode (comp_zip, new_geocode_center_callback);
      break;
    case '3':
     $(".sbx-search-advanced").show();
      location_code.attr("readonly", false);
      sbx_show_or_hide_location_map_ui_elements (true);
      showMapCanvas();
      sbx_location_on_demand_gmap_init ();
      SbxGmapZipView_setCenterMarkDraggable (true);
      SbxGmapZipView_resetCenterMarker ();
      if ((curr_lat == 0) && (curr_lng == 0)) {
        var user_loc_str = $('[name="' + user_location_str_field_name +'"]').fieldValue();
        var zip = location_code.fieldValue();
        zip = (zip=='' ? comp_zip : zip);
        zip = (zip=='' ? user_loc_str : zip);
        location_code.val (zip);
        //SbxGmapZipView_centerMapByZipCode("" + zip);
        SbxGmapZipView_centerMapByZipCode("" + zip, new_geocode_center_callback);
      }
      else {
        var lat = (curr_loc_details_pick==null)? curr_lat : curr_loc_details_pick['latitude'];
        var lng = (curr_loc_details_pick==null)? curr_lng : curr_loc_details_pick['longitude'];
        SbxGmapZipView_centerMapByLatlng (new GLatLng (lat, lng, true));
        set_sbxPost_location_values (curr_loc_details_pick);
        if (curr_loc_details_pick['address'] == '') {
          SbxLocation_reverseGeocoding2 (lat, lng, 'sbx_set_location_details2');
        }
      }
      //drawCircle();
      break;
    default:
      break;
  }
  return;
}

function hideMapCanvas() {
  $('#map_canvas').hide (); //('slow'); -- effect doesn't work well with IE('slow');
  //gmap_canvas.hide();
}

function showMapCanvas() {
  $('#map_canvas').show (); //('slow'); -- effect doesn't work well with IE
  //gmap_canvas.show();
  //drawCircle();  
} 

function drawCircle() {
  SbxGmapZipView_setProximityMiles (SbxGmapZipView_convertProximityCodeToMiles (location_val.fieldValue()));
  SbxGmapZipView_drawProximityCircleAndMark ();
}

function new_geocode_center_callback (lat, lng) {
  //SbxLocation_reverseGeocoding (lat, lng, 'sbx_set_location_details');
  SbxLocation_reverseGeocoding2 (lat, lng, 'sbx_set_location_details2');
}
  
function sbx_set_location_details (jsonData) {
  var loc_details = SbxLocation_parseLocationJsonData (jsonData);
  set_sbxPost_location_values (loc_details);
  sbx_set_curr_location_details (loc_details);
}

function sbx_set_location_details2 (loc_details) {
  set_sbxPost_location_values (loc_details);
  sbx_set_curr_location_details (loc_details);
}

function set_sbxPost_location_values (loc_details) {
  if (loc_details == null) {
    return;
  } 
  sbxPost_state_short.val (loc_details['state_short']);
  sbxPost_country_code.val (loc_details['country_code']);
  sbxPost_city_or_place.val (loc_details['city_or_place']);
  sbxPost_postal_code.val (loc_details['postal_code']);
  if (loc_details['sbxPost_address'] == "") {
    location_code.val(loc_details['postal_code']);
    address_display.html (html_address_display_title + loc_details['address'] + '');
  }
  else {
    location_code.val(loc_details['sbxPost_address']);
    address_display.html (html_address_display_title + location_code.val() + '');
  }
  sbxPost_lat.val (loc_details['latitude']);
  sbxPost_lng.val (loc_details['longitude']);
  sbxPost_address.val (loc_details['address']);
}

function on_map_click (lat, lng) {
  curr_lat = lat;
  curr_lng = lng;
  latlng = new GLatLng (curr_lat, curr_lng, true);
  SbxGmapZipView_centerMapByLatlng (latlng);
  //SbxGmapZipView_centerMapByLatlng (new GLatLng (curr_lat, curr_lng, false));
}

function sbx_set_curr_location_details (loc_details) {
  if (location_selection == '2') {
    curr_loc_details_comp = loc_details;
  }
  else if (location_selection == '3') {
    curr_loc_details_pick = loc_details;
  }
}


