// --------------------------------------------------------------------------------
// ns_GoogleMapsUserControl.js
// --------------------------------------------------------------------------------
///<reference path="~/ow_util.js">

// define the OneWeb GoogleMaps namespace
OneWeb.GoogleMaps = { };

// maps array to hold any maps to create
OneWeb.GoogleMaps.maps = [];

// Map object
OneWeb.GoogleMaps.Map = function(id, coords, zoom, type, overlays, controls, info, dirid, mode, latitudetextboxid, longitudetextboxid) {
    this.id = id;
    this.coords = coords;
    this.zoom = zoom;
    this.type = type;
    this.overlays = overlays;
    this.controls = controls;
    this.info = info;
    this.dirid = dirid;
    this.mode = mode;
    this.latitudetextboxid = latitudetextboxid;
    this.longitudetextboxid = longitudetextboxid;
    this.gDirections = null;
    this.gMap = null;
};

google.setOnLoadCallback(
	function () {
		// check browser compatibility and call the load event
		if (google.maps.BrowserIsCompatible() && !(typeof ClickTaleIsPlayback=="function" && ClickTaleIsPlayback() )) {
			for (var i = 0; i < OneWeb.GoogleMaps.maps.length; i++) {
				OneWeb.GoogleMaps.maps[i].initialize();
			}
		}
	}
);

//one object in the array
	OneWeb.GoogleMaps.Map.prototype.initialize = function() {
	  var me = this;
	  var div = document.getElementById(this.id);

	  if (div != null) {
	    var GM = google.maps;
	    var map = new GM.Map2(div);
	    //if coords are zero then we got nothing for lat and long and address geocoding yielded nothing.
	    //should only get this situation when rendering back end mode.
	    //in this case set lat/long to approximate center of NS (45.35, -63.3).
	    if (this.coords[0] == 0 && this.coords[1] == 0) {
	      this.coords[0] = "45.35";
	      this.coords[1] = "-63.3";
	      this.zoom = 7;
	    }
	    var pt = new GM.LatLng(this.coords[0], this.coords[1]);
	    map.setCenter(pt, this.zoom);
	    map.setMapType(this.type);
	    this.gMap = map;

	    // overlays
	    if (this.overlays.length > 0) {
	      for (var i = 0; i < this.overlays.length; i++) {
	        map.addOverlay(new GM.GeoXml(this.overlays[i]));
	      }
	    }

	    // controls
	    if (this.controls["largePanZoom"]) map.addControl(new GM.LargeMapControl());
	    if (this.controls["scale"]) map.addControl(new GM.ScaleControl());
	    if (this.controls["type"]) map.addControl(new GM.MapTypeControl());
	    if (this.controls["overview"]) map.addControl(new GM.OverviewMapControl());

	    //read mode and pass to js function which will control how control renders itself through styling
	    //add case statement here. Depending on mode, different functions will need to be called.
	    if (this.mode === "default") {
	      if (this.controls["marker"]) {
	        var marker = new GM.Marker(pt);

	        //add event listener to open the info window
	        GM.Event.addListener(marker, "click", function() {
	          map.openInfoWindowHtml(pt, me.info);
	        });
	        this.gMarker = marker;
	        map.addOverlay(this.gMarker);
	      }

	      // open info window upon rendering
	      if (this.info.length !== 0) map.openInfoWindowHtml(pt, this.info);

	      // add the directions control, and provide the div if it is given
	      if (this.dirid !== null) {
	        var dirpanl = document.getElementById(this.dirid)
	        this.gDirections = new GM.Directions(this.gMap, dirpanl);
	      } else
	        this.gDirections = new GM.Directions(this.gMap);
	      GM.Event.bind(this.gDirections, "load", this, this.onDirectionsLoaded);
	      GM.Event.bind(this.gDirections, "error", this, this.onDirectionsError);

	      document.getElementById("nsgm_LatLng").style.display = "none";

	    } else {
	      //this is for the back end mode "popup"
	      if (this.controls["marker"]) {
	        this.gMarker = new GM.Marker(pt, { draggable: true });
	        this.gMarker.enableDragging();

	        GM.Event.addListener(this.gMarker, "dragend", function() {
	          var LatLng = this.getLatLng();

	          var txtSourceLatitude = document.getElementById("nsgm_txtLatitude");
	          if (txtSourceLatitude != null)
	            txtSourceLatitude.value = LatLng.lat();

	          var txtSourceLongitude = document.getElementById("nsgm_txtLongitude");
	          if (txtSourceLongitude != null)
	            txtSourceLongitude.value = LatLng.lng();
	        });
	        map.addOverlay(this.gMarker);

	        var txtSourceLatitude = document.getElementById("nsgm_txtLatitude");
	        if (txtSourceLatitude != null)
	          txtSourceLatitude.value = this.coords[0];

	        var txtSourceLongitude = document.getElementById("nsgm_txtLongitude");
	        if (txtSourceLongitude != null)
	          txtSourceLongitude.value = this.coords[1];

	        nsgm_ShowLatLngForm();
	      }
	    }
	  }
	};

OneWeb.GoogleMaps.Map.prototype.reset = function() {

    var pt = new google.maps.LatLng(this.coords[0], this.coords[1]);
    this.gMap.checkResize();
    this.gMap.setCenter(pt, this.zoom);
    // add the directions control, and provide the div if it is given
/*    if (this.mode === "default") {
        if (this.dirid !== null) {
            var dirpanl = document.getElementById(this.dirid)
            this.gDirections = new google.maps.Directions(this.gMap, dirpanl);
        } else
            this.gDirections = new google.maps.Directions(this.gMap);
    } */
}

OneWeb.GoogleMaps.Map.prototype.getDirections = function(from) {

    if (GBrowserIsCompatible() && typeof(this.gDirections) !== "undefined") {

        this.dirsource = from;
        var query = "from: " + this.dirsource + " to: " + this.coords[0] + ", " + this.coords[1];
        //Create Google Directions Object and specify Google Map Object and Div 

        //Clear the map and directions of any old information 
        this.gDirections.clear();

        //clear the driving directions div of any previous output
        //var nsgm_DrivingDirections = document.getElementById("nsgm_DrivingDirections").innerHTML = "";

        //Load the map and directions from the specified waypoints
        this.gDirections.load(query);

    }

}

OneWeb.GoogleMaps.Map.prototype.onDirectionsLoaded = function() {
    var status = this.gDirections.getStatus();
    if (typeof (console) !== "undefined") console.log("Directions loaded " + status.toString());
    else if (typeof (Sys) !== "undefined" && Sys.Debug) Sys.Debug.trace("Directions loaded " + status.toString());
}

OneWeb.GoogleMaps.Map.prototype.onDirectionsError = function() {
    var status = this.gDirections.getStatus();
    if (typeof(console)!=="undefined") console.log("Directions error " + status.toString());
    else if (typeof (Sys) !== "undefined" && Sys.Debug) Sys.Debug.trace("Directions error " + status.toString());
}

// --------------------------------------------------------------------------------
// setLatLng()
// Return Lat and Long values from user control to the lat and long textboxes on the page where the control is sited.
// --------------------------------------------------------------------------------
// Arguments:
//	- none
// Returns:
//	- none
// --------------------------------------------------------------------------------
OneWeb.GoogleMaps.Map.prototype.setLatLng = function() {
    
    var re_latitude = /^-?([1-8]?[1-9]|[1-9]0)(\.{1}\d{1,15})?$/;
    var txtSourceLatitude = document.getElementById("nsgm_txtLatitude");
    if (txtSourceLatitude != null){
        if (txtSourceLatitude.value.length == 0 || !txtSourceLatitude.value.match(re_latitude)){
            alert("Latitude must be supplied in the correct format. Ex.(45.254784)");
            txtSourceLatitude.focus();
			txtSourceLatitude.select();
            return false;
        }
    }
     
    var re_longitude = /^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])(\.{1}\d{1,15})?$/;
    
    var txtSourceLongitude = document.getElementById("nsgm_txtLongitude");
    if (txtSourceLongitude != null){
        if (txtSourceLongitude.value.length == 0 || !txtSourceLongitude.value.match(re_longitude)){
            alert("Longitude must be supplied in the format. Ex.(-63.874525)");
            return false;
        }
    }
    
    var txtTargetLatitude = document.getElementById(OneWeb.GoogleMaps.maps[0].latitudetextboxid);
    if (txtTargetLatitude != null){
        txtTargetLatitude.value = txtSourceLatitude.value;
    }
    
    var txtTargetLongitude = document.getElementById(OneWeb.GoogleMaps.maps[0].longitudetextboxid);
    if (txtTargetLongitude != null){
        txtTargetLongitude.value = txtSourceLongitude.value;
    }
    
    //hide pop-up div
    document.getElementById("events_googlemap").style.display = "none";

}

OneWeb.Util.appendUnloadEvent(
function() {
	// call the Google Maps API unload event
	if (typeof google.maps != "undefined")
		google.maps.Unload();
}
);

OneWeb.Util.appendLoadEvent(
function() {
    var OU = OneWeb.Util;
    if (document.getElementById("nsgm_btnGetDirections") != null)
        OU.addEvent(document.getElementById("nsgm_btnGetDirections"), "click", nsgm_ShowDirections, false);

    if (document.getElementById("nsgm_btnClear") != null) 
        OU.addEvent(document.getElementById("nsgm_btnClear"), "click", nsgm_clearData, false);

    if (document.getElementById("nsgm_btnBack") != null)
        OU.addEvent(document.getElementById("nsgm_btnBack"), "click", nsgm_ShowAddressForm, false);

    if (document.getElementById("nsgm_btnPrint") != null)
        OU.addEvent(document.getElementById("nsgm_btnPrint"), "click", nsgm_PrintDrivingDirections_google, false);
        
    if (document.getElementById("nsgm_btnOk") != null)
        OU.addEvent(document.getElementById("nsgm_btnOk"), "click", OneWeb.GoogleMaps.maps[0].setLatLng, false);
        
    if (document.getElementById("nsgm_btnCancel") != null)
        OU.addEvent(document.getElementById("nsgm_btnCancel"), "click", nsgm_Cancel, false);

    var inputs = document.getElementById("nsgm_FromAddress").getElementsByTagName("input");
    for (var i = 0; i<inputs.length;i++) {
        if (inputs[i].type==="text")
            OU.addEvent(inputs[i], "keypress", nsgm_onKeyPressed, false);
    }
});

function nsgm_onKeyPressed(e) {
    ///<summary>Handler for a key press on the directions form textfield</summary>
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if (code == 13) {
        var nsgm_btnGetDirections = document.getElementById("nsgm_btnGetDirections");
        if (nsgm_btnGetDirections!==null && nsgm_btnGetDirections.clientWidth>0)
            nsgm_btnGetDirections.click();
        if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
    }
}

function nsgm_Cancel() {
  //hide pop-up div
  document.getElementById("events_googlemap").style.display = "none";
}

function nsgm_getSourceAddress() {
    ///<summary>Gets the source (from) address for the directions query.</summary>
		
	var nsgm_txtAddress = document.getElementById("nsgm_txtAddress");
	var nsgm_txtCity = document.getElementById("nsgm_txtCity");
	var nsgm_txtPostalCode = document.getElementById("nsgm_txtPostalCode");
	var nsgm_ddlProvince = document.getElementById("nsgm_ddlProvince");

	if ((nsgm_txtAddress !== null && nsgm_txtCity !== null && nsgm_txtPostalCode !== null) &&
		(nsgm_txtAddress.value === "" && nsgm_txtCity.value === "" && nsgm_txtPostalCode.value === "")) {
			alert("Not enough information supplied to perform a search. Hint: You must at least supply a valid postal/zip code");
			return false;
	}

    var address = ""
    if (nsgm_txtAddress != null && nsgm_txtAddress.value.length > 0)
	    address = nsgm_txtAddress.value + ' '
    
    if (nsgm_txtCity != null && nsgm_txtCity.value.length > 0)
		    address += nsgm_txtCity.value + ' '
		
	if (nsgm_ddlProvince != null)
	    address += nsgm_ddlProvince.options[nsgm_ddlProvince.selectedIndex].value + ' '

	if (nsgm_txtPostalCode != null && nsgm_txtPostalCode.value.length > 0)
	    address += nsgm_txtPostalCode.value

	return address;
}

// --------------------------------------------------------------------------------
// nsgm_ShowDirections()
// Validates the data entered on the Get Directions portion of the Google Maps User Control.
// --------------------------------------------------------------------------------
// Arguments:
//	- none
// Returns:
//	- the results of the validation [boolean]
// --------------------------------------------------------------------------------
function nsgm_ShowDirections() {
    // get the directions
    var address = nsgm_getSourceAddress();
    if (!address == false){
        OneWeb.GoogleMaps.maps[0].getDirections(address);
        // hide the address form
        nsgm_HideAddressForm();
    }
}	

function nsgm_clearData() {
	var nsgm_txtAddress = document.getElementById("nsgm_txtAddress");
	var nsgm_txtCity = document.getElementById("nsgm_txtCity");
	var nsgm_txtPostalCode = document.getElementById("nsgm_txtPostalCode");
	var nsgm_ddlOption = document.getElementById("nsgm_NS");

	if (nsgm_txtAddress !== null)
	    nsgm_txtAddress.value = ""

    if (nsgm_txtCity !== null)
	    nsgm_txtCity.value = ""
		
	if (nsgm_txtPostalCode !== null)
	    nsgm_txtPostalCode.value = ""
		
	if (nsgm_ddlOption !== null)
        nsgm_ddlOption.selected = true;
   
}

function nsgm_HideAddressForm() {

    var nsgm_FromAddress = document.getElementById("nsgm_FromAddress");
    if (nsgm_FromAddress !== null)
        nsgm_FromAddress.style.display = "none";

    var nsgm_printback_buttons = document.getElementById("nsgm_printback_buttons");
    if (nsgm_printback_buttons !== null) 
        nsgm_printback_buttons.style.display = "block";

    var nsgm_DrivingDirections = document.getElementById("nsgm_DrivingDirections");
    if (nsgm_DrivingDirections !== null) 
        nsgm_DrivingDirections.style.display = "block";
}

function nsgm_ShowAddressForm()
{
		
	var nsgm_FromAddress = document.getElementById("nsgm_FromAddress");
    if (nsgm_FromAddress !== null) {
        nsgm_FromAddress.style.display="block";
        nsgm_FromAddress.className = "test";
    }
    
    var nsgm_printback_buttons = document.getElementById("nsgm_printback_buttons");
    if (nsgm_printback_buttons !== null)
        nsgm_printback_buttons.style.display="none";
    
    var nsgm_DrivingDirections = document.getElementById("nsgm_DrivingDirections");
    if (nsgm_DrivingDirections !== null)
        nsgm_DrivingDirections.style.display="none";

}

function nsgm_ShowLatLngForm()
{
		
	var nsgm_FromAddress = document.getElementById("nsgm_FromAddress");
    if (nsgm_FromAddress !== null)
        nsgm_FromAddress.style.display="none";
    
    var nsgm_LatLng = document.getElementById("nsgm_LatLng");
    if (nsgm_LatLng !== null)
        nsgm_LatLng.style.display="block";
    
}

function nsgm_PrintDrivingDirections_google() {
    ///<summary>Generates a link to the Google Maps print window.</summary>
    var disp_setting = "toolbar=yes,location=no,directories=yes,menubar=yes,";
    disp_setting += "scrollbars=yes,width=800, height=750, left=100, top=25";

    var map = OneWeb.GoogleMaps.maps[0];
    var gmap = map.gMap;
    var div = document.getElementById(map.id);
    var ne = gmap.getBounds().getNorthEast(), sw = gmap.getBounds().getSouthWest();
    var sll = sw.toUrlValue();
    var sspn = new GLatLng(ne.lat() - sw.lat(), ne.lng() - sw.lng()).toUrlValue();
    var address = 'http://maps.google.com/maps?' +
            'f=d&' +                     // query style - d = directions
            'saddr=' + encodeURI(nsgm_getSourceAddress()) + '&' +
            'daddr=' + encodeURI(map.coords[0] + " " + map.coords[1]) + '&' +
            'hl=en&' + 					// language
            'geocode=&' + 				// unused
            'mra=ls&' + 					// unknown
            'doflg=ptk&' + 		        // metric
            'sll=' + sll + '&' + 	    // offset point
            'sspn=' + sspn + '&' +         // span	
            'ie=UTF8&' + 		        // input encoding
            'z=' + gmap.getZoom() + '&' + // zoom
            'pw=2'; 			            // print mode

    var docprint = window.open(address, "printmap", disp_setting);

    docprint.focus();

}


function nsgm_PrintDrivingDirections_static() { 
    var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
    disp_setting += "scrollbars=yes,width=500, height=1000, left=100, top=25"; 
    var content_vlue = document.getElementById("tmpl_nsfes_Details_nsfesDetails_nsgmApp_1_nsgm_Map").innerHTML; 
    
    var content_dd = document.getElementById("nsgm_DrivingDirections").innerHTML; 

    var docprint=window.open("","",disp_setting); 

    docprint.document.open(); 
    
    docprint.document.write('<html><head><title>Nova Scotia Tourism</title>'); 

    docprint.document.write('</head><body onload="window.print();">'); 
    docprint.document.write('<div id="nsgm_map">' + content_vlue + '</div><br/>'); 
    docprint.document.write('<div id="nsgm_dd">' + content_dd + '</div>'); 
    docprint.document.write('<div id="nsgm_print">' + '<input id="nsgm_btnBack" name="nsgm_Back" type="submit" title="Click to print" value="Print" onclick="window.print();return false;" />' + '</div>');
    docprint.document.write('</body></html>'); 
    
    docprint.focus(); 
    
} 

function nsgm_PrintDrivingDirections_dynamic() { 
    var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
    disp_setting += "scrollbars=yes,width=500, height=750, left=100, top=25"; 
    //var content_vlue = document.getElementById("tmpl_nsfes_Details_nsfesDetails_nsgmApp_1_nsgm_Map").innerHTML; 
    
    //var content_dd = document.getElementById("nsgm_DrivingDirections").innerHTML; 

    var docprint=window.open("","printmap",disp_setting); 

    
    //docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ');
    //docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ');
    //docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml">');
    
    //<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
    
    //<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    var map = OneWeb.GoogleMaps.maps[0];
    var div = document.getElementById(map.id);
    
    //docprint.document.open();
    var markup = '<html><head><title>Nova Scotia Tourism - Driving Directions</title>\n' +
            '<script src="/ow_util.js" type="text/javascript"></script>\n' +
            '<script src="http://www.google.com/jsapi?key=' + google.loader.ApiKey + '" type="text/javascript"></script>\n' +
            '</head><body>\n' +
            '<div id="nsgm_map" style="width:' + div.offsetWidth + 'px;height:' + div.offsetHeight + 'px;"' + '></div><br/>\n' +
            '<div id="nsgm_dd"></div>\n' +
            '<div id="nsgm_print"><input id="nsgm_btnBack" name="nsgm_Back" type="submit" title="Click to print" value="Print" onclick="window.print();return false;" /></div>\n';  
    docprint.document.write(markup);
    markup = '<script language="JavaScript" type="text/javascript">\n/' + '/<![CD' + 'ATA[\n' +
//                'window.onload = function () { debugger;' +
                    'google.load("maps", "2", {"locale" : "en"}); google.setOnLoadCallback(function () { ' +
                        'var pmap = window.opener.OneWeb.GoogleMaps.maps[0].gmap;' +
                        'var map = new google.maps.Map2(document.getElementById("nsgm_map"));map.setCenter(pmap.getCenter(), pmap.getZoom());map.setMapType(pmap.getCurrentMapType());' +
            '});\n/' + '/]' + ']></script>\n' +
        '</body></html>';
    docprint.document.write(markup);

    docprint.document.close();
    
//        docprint.document.write('<html><head><title>Nova Scotia Tourism - Driving Directions</title>'); 
//        docprint.document.write('</head><body>'); 
//        docprint.document.write('<script src="http://www.google.com/jsapi?key=ABQIAAAADkj9RXjBNCTWt8J2jwXOABRcwhYcsroUQFMnl9pHUYVyX4NpjhTuvBVWNp6emhhQrci3obMSoC5RMg" type="text/javascript"></script>');
//        docprint.document.write('<script language="JavaScript" type="text/javascript">'); 
//        docprint.document.write('//<![CDATA['); 
//        docprint.document.write('google.load("maps", "2", {"locale" : "en"});'); 
//        docprint.document.write('//]]>'); 
//        //docprint.document.write(''); 
//        //docprint.document.write(''); 
//        docprint.document.write('</script>'); 
//        
//        docprint.document.write('<div id="nsgm_map">&nbsp;</div><br/>'); 
//        docprint.document.write('<div id="nsgm_dd">&nbsp;</div>'); 
//        docprint.document.write('<div id="nsgm_print">' + '<input id="nsgm_btnBack" name="nsgm_Back" type="submit" title="Click to print" value="Print" onclick="window.print();return false;" />' + '</div>');
//        docprint.document.write('</body></html>'); 
    
    docprint.focus(); 
    
    //debugger;

    //OneWeb.Util.addEvent(docprint, "load", function() { alert("loaded");  OneWeb.GoogleMaps.maps[0].getdirectionspopup(docprint); });
    
    //return false;
}

