$(document).ready(function() {
  //    top.frames[map].setMap('<%= @controller.get_dir %>');


  $("input[type=text]").focus(function(){
    // Select field contents
    this.select();
    //    this.value="";
    if (this.className == "dp-directions"){
      if (this.value == "Enter starting address"){
        this.value="";
      }

    }
  });

  $(".dp-directions").blur(function(){
    
    if (this.value == ""){
      if (this.name == "address_end"){
        this.value="Enter starting address";
      }
    }
  });

  $("input[type=text]").keypress(function (e) {
    if(e.keyCode==13){
      setDirections();
    }
  });

});

function setMapDefault(){
  geocoderto = new GClientGeocoder();
  if (geocoderto) {
    geocoderto.getLatLng(
      toAddress,
      function(point2) {
        var map = new GMap2(document.getElementById("map_div"));
        map.setCenter(point2, 15);
        marker = new GMarker(point2);
        map.addOverlay(marker);
        map.addControl(new GMapTypeControl());
        map.addControl(new GLargeMapControl());
    
      });
    $("body").append('<iframe src="http://members.webs.com/s/platformAPI/resizeIframe?height=450" style="visibility:hidden;width:0;height:0;border:0;"></iframe>');
  }
}
function setDirections() {
  var address_end=document.getElementById("address_end").value
  var fromAddress = ""
    
  if (address_end != "Address"){
    fromAddress=address_end
  }
  if (fromAddress !="Enter starting address"){
    geocoderto = new GClientGeocoder();
    if (geocoderto) {
      geocoderto.getLocations(
        toAddress,
        function(point2) {
          ////      Gets Point
          geocoder = new GClientGeocoder();
          if (geocoder) {
            geocoder.getLocations(
              fromAddress,
              function(point) {
                if (!point || point.Status.code != 200) {
                  alert(fromAddress + " not found");
                } else {
                  //              Draw in the map
                  document.getElementById("map_dir").innerHTML="";
                  $('#ButtonPrint1').hide();
                  map = new GMap2(document.getElementById("map_div"));
                  map.addControl(new GMapTypeControl());
                  map.addControl(new GLargeMapControl());
                  gdir = new GDirections(map,document.getElementById("map_dir"));
                  GEvent.addListener(gdir, "load", onGDirectionsLoad);
                  GEvent.addListener(gdir, "error", handleErrors);
                  GEvent.addListener(gdir, "addoverlay", resize);

                  // Remove postal code for United Kingdom there is a 602 bug for UK only.
                  var address1, address2;
                  var in_uk = false;
                  if (point.Placemark[0].AddressDetails.Country.CountryNameCode == "GB") {
                    in_uk = true;
                    address1 = remove_postal_code_from(point.Placemark[0].address);
                  } else {
                    address1 = point.Placemark[0].address;
                  }

                  // Remove postal code for United Kingdom there is a 602 bug for UK only.
                  if (point2.Placemark[0].AddressDetails.Country.CountryNameCode == "GB") {
                    in_uk = true;
                    address2 = remove_postal_code_from(point2.Placemark[0].address);
                  } else {
                    address2 = point2.Placemark[0].address;
                  }

                  // var waypoints = [new CM.LatLng(51.52039, -0.1485), new CM.LatLng(51.5203, -0.135)];
                  var long1 = point.Placemark[0].Point.coordinates[0];
                  var lat1 = point.Placemark[0].Point.coordinates[1];
                  var p1 = new GLatLng(parseFloat(lat1), parseFloat(long1));

                  var long2 = point2.Placemark[0].Point.coordinates[0];
                  var lat2 = point2.Placemark[0].Point.coordinates[1];
                  var p2 = new GLatLng(parseFloat(lat2), parseFloat(long2));

                  // Now resize window using cookie to communicate with parent
                  //jQuery(document).parent('#fwIframe').css('min-height', '800px');
                  //jQuery.cookie('fwIframeHeightSize', '800', { expires: 1 });
                  //jQuery(document).parent('#fwIframe').leo = 'pude!';
                  //alert('var pude: ' + jQuery(document).parent('#fwIframe').leo);
//                  window.location.hash = "800";
//                  alert('new hash: ' + window.location.href);
//                  window.location.href = window.location.href;

                  // leog: It seems that the Royal Mail have not given Google permission to geocode full UK
                  // post codes in the API. Any GDirections query that uses full UK post codes will fail with error 602.
                  // Using loadFromWaypoints is the only workaround i've found to easyly solve this issue, bug FWB-8905
                  if (in_uk)
                    gdir.loadFromWaypoints([p1, p2]);
                  else
                    gdir.load("from: " + address1 + " to: " + address2);

                }
              }
              );
          }
        });
    }
  }
}

function remove_postal_code_from(address) {
  // "10 Downing St, Westminster, London SW1A 2, UK"
  var cad = address;
  var pos1 = cad.lastIndexOf(',');
  var pos2 = cad.lastIndexOf(',', pos1 - 1);
  var first = cad.substr(0, pos2);
  var last = cad.substr(pos1 + 1);
  var middle = jQuery.trim(cad.substr(pos2 + 1, pos1 - pos2 - 1));
  var middle_limit = middle.indexOf(' ');
  middle = middle.substr(0, middle_limit);
  var newaddress = first + ", " + middle + "," + last;
  
  // "10 Downing St, WestminsteLondon, UK"
  return newaddress;
}

function resize(){
  var h
  h=$(document).height()
  h=h+50
  $("body").append('<iframe src="http://members.webs.com/s/platformAPI/resizeIframe?height=' +h + '" style="visibility:hidden;width:0;height:0;border:0;"></iframe>');
}

// Error
function handleErrors(){
    
  if(gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("Address unknown.\nError code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
  else alert("We could not calculate directions between these locations.");
  setMapDefault();
  
}

function onGDirectionsLoad(){
  document.getElementById("ButtonPrint1").style.visibility = 'visible';
  $('#ButtonPrint1').show();
}

function imprSelec(nombre){
  var ficha = document.getElementById(nombre);
  $('.no-print').hide();
  //        document.getElementById("ButtonPrint2").style.visibility = 'hide';
  var ventimp = window.open(' ', 'popimpr','width:10px,height:10px');
  ventimp.document.write( ficha.innerHTML );
  $('.no-print').show();
  //        document.getElementById("ButtonPrint2").style.visibility = 'visible';
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();
}

function SendMail(ToAddress){
  var sBrokenAddress ;
  sBrokenAddress = "mai" ;
  sBrokenAddress += "lto" ;
  sBrokenAddress += ":" ;

  //        var i=ToAddress.length;
  //        i=i-1;
  //        for (var x = i; x >=0; x--)
  //          {
  //          sBrokenAddress += ToAddress.charAt(x) ;
  //          }
	
  sBrokenAddress += ToAddress ;
  window.location.href = sBrokenAddress ;
}

function limitText(limitField, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  }
//	else {
//		limitCount.value = limitNum - limitField.value.length;
//	}
}

function ActForm(){
  iframeMap = document.getElementById("delapalo_map");
  iframeMap.src="http://delapalo1.webs.com/apps/locations3_dev/iframe/"
}
