//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Gmap functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function loadDirections(from, map) {
  if (from != "") {
    var community = properties[0];
    directions = new GDirections(map, $("#route")[0]); 
    GEvent.addListener(directions, "error", handleErrors); 
    var to_from = "from: " + from + " to: " + community.latitude + ", " + community.longitude;
    directions.load(to_from);
  }
}

function handleErrors(){
  var panel = $("#route")[0];
  if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
    panel.innerHTML = "<div style='color:red'>No corresponding geographic location could be found for one of the specified addresses. <br/>This may be due to the fact that the address is relatively new, or it may be incorrect.<br/>Error code: " + directions.getStatus().code + "</div>";
  } else if (directions.getStatus().code == G_GEO_SERVER_ERROR) {
    panel.innerHTML = "<div style='color:red'>A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.<br/> Error code: " + directions.getStatus().code+ "</div>";
  } else if (directions.getStatus().code == G_GEO_MISSING_QUERY) {
    panel.innerHTML = "<div style='color:red'>The HTTP q parameter was either missing or had no value. <br/>For geocoder requests, this means that an empty address was specified as input. <br/>For directions requests, this means that no query was specified in the input.<br/> Error code: " + directions.getStatus().code+ "</div>";
//  } else if (directions.getStatus().code == G_UNAVAILABLE_ADDRESS) {
//    panel.innerHTML = "<div style='color:red'>The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.<br/> Error code: " + directions.getStatus().code+ "</div>";
  } else if (directions.getStatus().code == G_GEO_BAD_KEY){
    panel.innerHTML = "<div style='color:red'>The given key is either invalid or does not match the domain for which it was given. <br/> Error code: " + directions.getStatus().code+ "</div>";
  } else if (directions.getStatus().code == G_GEO_BAD_REQUEST){
    panel.innerHTML = "<div style='color:red'>A directions request could not be successfully parsed.<br/> Error code: " + directions.getStatus().code+ "</div>";
  } else if (directions.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS) {
	panel.innerHTML = "<div style='color:red'>Could not find directions between the points given. Retry your query with more specific criteria.<br/></div>";
  } else {
    panel.innerHTML = "<div style='color:red'>An unknown error occurred. Error code: " + directions.getStatus().code+ "</div>";
  }
}
var map;
function loadMap() {
  var currentMarker = null;
  map = new GMap2($("#map")[0]); 
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());

  var pin = new GIcon(G_DEFAULT_ICON);

  var firstProperty = true;
  var maxLat = 0;
  var maxLong = 0;
  var minLat = 0;
  var minLong = 0;
  $(properties).each(function() {
    var coordinate = new GLatLng(this.latitude, this.longitude);
    if (this.latitude < minLat || firstProperty)
      minLat = parseFloat(this.latitude);
    if (this.latitude > maxLat || firstProperty)
      maxLat = parseFloat(this.latitude);
    if (this.longitude < minLong || firstProperty)
      minLong = parseFloat(this.longitude);
    if (this.latitude > maxLat || firstProperty)
      maxLong = parseFloat(this.longitude);
    var marker = new GMarker(coordinate, pin);
    var name         = this.name;
    var url          = this.url;
    var photo        = this.photo;
    var city         = this.city;
    var zipcode      = this.zipcode;
    var bedrooms     = this.bedrooms;
    var price        = this.price;
    var phone_number = this.phone_number;
    var state        = this.state;
    
    //this.setMarker(marker);
     GEvent.addListener(marker, "click", function() {
      if (currentMarker != null) {
          currentMarker.closeInfoWindow();
      }
      info_html = "<div class=\"search_map_bubble\">\n <div class=\"pic\"><a href=\"" + url + "\"><img src=\"" + photo + "\" alt=\"" + name + "\" width=\"70\" height=\"55\"/></a></div>\n  <span class=\"address\">" + name + "</span>\n  <span class=\"listingid\">" + city + "," + state + " " + zipcode + "</span>\n";  
      if (bedrooms.length > 0){
        info_html += "<span class=\"bdbth\">" + bedrooms + " beds</span>\n";
      }
      info_html += "<span class=\"price\">" + price + "</span>\n  <span class=\"phone\">" + phone_number + "</span>\n  </div>";
                    
      marker.openInfoWindowHtml(info_html);
      currentMarker = marker;
    });
    
    map.addOverlay(marker);
    firstProperty = false;
  });
  
  var minLatLng = new GLatLng(minLat, minLong);
  var maxLatLng = new GLatLng(maxLat, maxLong);
  var bounds = new GLatLngBounds(minLatLng,maxLatLng);
  var center = bounds.getCenter();
  map.setCenter(center, map.getBoundsZoomLevel(bounds));
  map.panTo(map.getCenter());
}

function findPropertyById(propertyList, id) {
  for (i = 0; i < propertyList.length; i++) {
    if (propertyList[i].id == id) {
      return propertyList[i];
    }
  }
}

function getDynamicMap() {
  $.getScript("http://maps.google.com/maps?file=api&v=2&sensor=false&async=2&callback=loadMap&client=gme-csource&channel=LC");
}

$(document).ready(function(){
  $("#mapbutton").click(function(){
    $("#map").slideToggle("250", function(){
      if ($("#map").html() == "") getDynamicMap();
      toggle_mapbutton();
    });
  });
});

function toggle_mapbutton(){
  if ($("#mapbutton img").attr("src") == "/images/hide_map.jpg")  {
    $("#mapbutton img").attr("src", "/images/view_map.jpg");
  } else {
    $("#mapbutton img").attr("src", "/images/hide_map.jpg");
  }
}


$(document).ready(function(){

  // Accordion
  $("#accordion").accordion({ header: "h3" });

  // Tabs
  $('#tabs').tabs();

  // Dialog     
  $('.dialog').dialog({
    autoOpen: false,
    width: 500,
    modal: true,
    bgiframe: true
  });
  
  // Dialog Close
  $('.dialog #close').click(function(){
    $('.dialog').dialog('close');
    return false;
  });
  
  $.fn.get_lead_form = function(input_button){
     var lead_form = $(this);
     $(this).lead_service({
       update_form: function() {
         lead_form.removeClass('loading');
         $('.lead_first_name label', lead_form).html('Name');
         $('.lead_opt_in_newsletter label', lead_form).html('Receive information from LuxuryCommunities.com');
         if($(input_button).attr("class").match("dialog_link"))
           $('.lead_form', lead_form).prepend("<h3>" + $(input_button).attr("rel") + "</h3>");
       },
       form_params: {
         website          : "luxurycommunities",
         entity_type_id   : '0',
         endeca_id        : $(input_button).attr("id").split('_')[1],
         entity_id        : $(input_button).attr("id").split('_')[1],
         opt_in_newsletter: '1',
         required_fields  : ['first_name','email']
       },
       lead_saved: function() {
         lead_form.load("/thank_you/");
       }
     });
   }
 
  // Dialog Link
  // call lead service for when popup form is clicked
  $('.dialog_link').click(function(){
    $('#popup_leadform .lead_service_form')
      .html("")
      .addClass("loading")
      .get_lead_form(this);
    $('#check_availability.dialog').dialog('open');
    return false;
  });

  // call lead service on detail page after dom-ready
  if ($('#inline_leadform .lead_service_form').length > 0) {
    $('#inline_leadform .lead_service_form').get_lead_form($("#inline_leadform .lead_service_form"));
  }

  // Datepicker
  $('#datepicker').datepicker({
    inline: true
  });
  
  // Slider
  $('#slider').slider({
    range: true,
    values: [17, 67]
  });
  
  // Progressbar
  $("#progressbar").progressbar({
    value: 20 
  });
  
  //hover states on the static widgets
  $('#dialog_link, ul#icons li').hover(
    function() { $(this).addClass('ui-state-hover'); }, 
    function() { $(this).removeClass('ui-state-hover'); }
  );

  $("#search_refine .refine_by h5 a").click(function() {
    $(this).toggleClass('active');
    $(this).parent().siblings('.options').toggle('fast');
  });

  // detail page map
  $("#map img").click(function(){
    $('#driving_directions').show();
    getDynamicMap();
  });
  
  //Google maps directions search  GO click.
  $("input.btnGetDirections").live('keydown', function() {
    loadDirections($('.fromAddress').val(), map);
  });

  //Google maps directions search on "enter" key
  $('.fromAddress').live('keyup', function(e) {
    if(e.keyCode == 13) {
      loadDirections($('.fromAddress').val(), map);
    }
  });
});
