﻿var map;
var baseIcon;
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var pc;
var dist;
var lang;
var survtyp;
var sitnum;

/* Maps */
//init the map
function initialize() {
    if (!google.maps.BrowserIsCompatible())
        return;

    map = new google.maps.Map2(document.getElementById("map_canvas"));
    map.addControl(new google.maps.SmallMapControl());
    map.addControl(new google.maps.MapTypeControl());

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    baseIcon = new google.maps.Icon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new google.maps.Size(20, 34);
    baseIcon.shadowSize = new google.maps.Size(37, 34);
    baseIcon.iconAnchor = new google.maps.Point(9, 34);
    baseIcon.infoWindowAnchor = new google.maps.Point(9, 2);
    baseIcon.infoShadowAnchor = new google.maps.Point(18, 25);

    setDataPoints();
}
//to directions
function tohere(i) {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
//from directions
function fromhere(i) {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}
// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, number, address, html) {
    if (!google.maps.BrowserIsCompatible())
        return;
        var i = number-1;
        // The info window version with the "to here" form open
        to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
           '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + address + 
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + address +
           '"/>';
        // The inactive version of the direction info
        html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';

      // Create a lettered icon for this point using our icon class
      var letteredIcon = new google.maps.Icon(baseIcon);
      var apppath = document.getElementById("apppath").value;
      letteredIcon.image = apppath + "/assets/images/mapicons/marker" + number + ".png";

      // Set up our google.maps.MarkerOptions object
      markerOptions = { icon:letteredIcon };
      var marker = new google.maps.Marker(point, markerOptions);

      google.maps.Event.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
      });
      gmarkers[i] = marker;
      htmls[i] = html;
      return marker;
}
function getDirections(sourcePostalCode,destinationAddress)
{
    var url = "http://maps.google.com/maps?saddr=" + sourcePostalCode + "&daddr=" + destinationAddress;
    window.open(url);
}
function setMapCenter(lat, lng)
{
    if (!google.maps.BrowserIsCompatible())
        return;

    map.setCenter(new google.maps.LatLng(lat,lng), 11);
}
function setDataPoint(lat, lng, index, textToDisplay, address)
{
    if (!google.maps.BrowserIsCompatible())
        return;

    var latlng = new google.maps.LatLng(lat,lng);
    var name = textToDisplay;
    var html = "<strong>" + name + "</strong>";
    map.addOverlay(createMarker(latlng, index, address, html));
}
//Set points on map by retrieving info from the ui.
function setDataPoints()
{
    if (!google.maps.BrowserIsCompatible())
        return;

    var qs = new Querystring();
    var lat = qs.get("lat");
    var lng = qs.get("lng");
    if(lat==null || lng==null || isNaN(lat) || isNaN(lng))
    {
        //alert("Zip code not found.");
        return;
    }

    if (document.getElementById("lat1") == null) {
        setMapCenter(lat, lng);
        return;
    }
    var latName;
    var lngName;
    var txtName;
    var address;
    var max = document.getElementById("maxResults").value;
    
    for (var i = 0; i < max; i++) {
        latName = "lat" + i;
        lngName = "lng" + i;
        txtName = "txt" + i;
        address = "address" + i;
        if(document.getElementById(latName)) 
        { 	
            if(i==1)//use the first one
                setMapCenter(document.getElementById(latName).value,document.getElementById(lngName).value);

            setDataPoint(document.getElementById(latName).value, 
                document.getElementById(lngName).value, i, 
                document.getElementById(txtName).value,
                document.getElementById(address).value);
		}
    }
}

/* GeoCoding */
function mapsLoaded() {
  retrieveLatLng();
}

function loadMaps() {
  google.load("maps", "2", {"callback" : mapsLoaded});
}

function retrieveLatLng()
{
    var geocoder = new google.maps.ClientGeocoder();
    var lat;
    var lng;
    geocoder.getLatLng(pc,redirSearch);
}
function redirSearch(latlng)
{
    if(latlng==null)
    {
        alert("Zip code not found.");
        return;
    }
    var apppath = document.getElementById("apppath").value;
    window.location = apppath + "/locator/?pc="+pc+"&d="+dist+"&lat="+latlng.lat()+"&lng="+latlng.lng();
}
function searchStudios(postalCode,distance)
{
    if (postalCode == null || postalCode.length == 0 || !isZip(postalCode) || postalCode.length != 5)
    {
        alert("Please enter a valid zip code\nfor the locations nearest you.");
        return;
    }

    pc=postalCode;
    dist=distance;
    //retrieveLatLng();
    loadMaps();
}

/* Show/Hide tabs */
function showTab(id)
{
    var tabName;
    var tabAreaName;
    var max = document.getElementById("maxResults").value;

    //First collapse everything
    for (var i = 0; i < max; i++) {
        tabName = "tab" + i;
        tabAreaName = tabName + "Area";
        if(document.getElementById(tabName)) 
        { 	
	        document.getElementById(tabAreaName).style.display = "none";
	        document.getElementById(tabName).className = "none";
		}
    }
    
    //Now show the selected tab
    tabName = "tab" + id;
    tabAreaName = tabName + "Area";
    document.getElementById(tabAreaName).style.display = "block";
    document.getElementById(tabName).className = "on";
}

/* Helper */
function isInt(x) {
   //If there is a leading 0, remove it for this comparison
   if(x.charAt(0)=='0')
      x = x.substr(1,4);
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
 }

 function isZip(s) {
     // Check for correct zip code
     reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
     if (!reZip.test(s)) {
         return false;
     }
     return true;
 }

/* Survey */
function loadSurvey(postalCode, surveyType, sittingNumber, language)
{
    if (postalCode == null || postalCode.length == 0 || !isZip(postalCode) || postalCode.length != 5)
    {
        var message = language=='es' ? "Por favor, introduzca un c\363digo postal v\341lido." : "Please enter a valid zip code.";
        alert(message);
        return;
    }
    pc = postalCode;
    survtyp = surveyType;
    sitnum = sittingNumber;
    lang = language;
    retrieveLatLngSurvey();
}

function retrieveLatLngSurvey()
{
    var geocoder = new google.maps.ClientGeocoder();
    var lat;
    var lng;
    geocoder.getLatLng(pc,redirSurvey);
}
function redirSurvey(latlng)
{
    if(latlng==null)
    {
        var message = language=='es' ? "Por favor, introduzca un c\363digo postal v\341lido." : "Please enter a valid zip code.";
        alert(message);
        return;
    }
    var redir = "satisfaction-" + lang + ".aspx?st=" + survtyp + "&sn=" + sitnum + "&pc=" + pc + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
    window.location = redir;
}
