﻿var base64DecodeChars = new Array(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
var map;
var gdir;
var hotIcon = new GIcon();
hotIcon.image = "images/010.png";
hotIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
hotIcon.iconSize = new GSize(20, 34);
hotIcon.shadowSize = new GSize(37, 34);
hotIcon.iconAnchor = new GPoint(9, 34);
hotIcon.infoWindowAnchor = new GPoint(9, 2);
hotIcon.infoShadowAnchor = new GPoint(18, 25);
var coldIcon = new GIcon(hotIcon);
var coldIconsp = new GIcon(hotIcon);
coldIcon.image = "images/154.png";
coldIconsp.image = "images/149.png";
var cmarkers = [];
var hmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var mkct = 0;
var acuct = 0;
var bounds = new GLatLngBounds();
function OnLoad(saddr,daddr) {
	if (document.body.clientWidth < 960) document.body.style.width = 960; 
	if (GBrowserIsCompatible())
		showMaps(saddr,daddr);
	else
    	document.getElementById("map").innerHTML = "<h1>Browser not compatible with Google Maps. Sorry...</h1>" ;
}
function isDigit (ch) { return ((ch == "0") || (ch == "1") || (ch == "2") || (ch == "3") || (ch == "4") || (ch == "5") || (ch == "6") || (ch == "7") || (ch == "8") || (ch == "9")); }
function isEmpty(str){ return ((str == null) || (str.length == 0))}
  
function isInteger (str) { 
    var i;
    if (isEmpty(str)) {
       if (isInteger.arguments.length == 1) { return true; }
       else { return (isInteger.arguments[1] == true); } }
    for (i = 0; i < str.length; i++) {  
        var ch = str.charAt(i);
        if (!isDigit(ch)) { return false; }
    }
    return true;
}
function isZIPCode (str) {
    if (isEmpty(str)){
       if (isZIPCode.arguments.length == 1){ return true;}
       else {return (isZIPCode.arguments[1] == true);}}
   return (isInteger(str) &&  (str.length == 5));
}
    
function checkzip(form) {
    if ( form.elements['izip'].value != '' ) {
        if (!isZIPCode(form.elements['izip'].value)) {
            alert(form.elements['izip'].value+' is a invalid ZIP code. It should be 5 digit.');
            form.elements['izip'].focus();
            return false;
        } else return true;    
    }
}
function showMaps(saddr,daddr) {
    // create the map
	map = new GMap2(document.getElementById("acumap"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(51.84,-114.96),3);
    izoom=map.getBoundsZoomLevel(bounds);
    if (izoom > 16) izoom=16;
    map.setZoom(izoom);
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
    showMakers();
    if (saddr.length > 1) {
		gdir = new GDirections(map, document.getElementById("route"));
	    GEvent.addListener(gdir, "load", onGDirectionsLoad);
	    GEvent.addListener(gdir, "error", handleErrors);
	    setDirections(saddr, daddr)
	}
}
function tohere(i) {cmarkers[i].openInfoWindowHtml(to_htmls[i]);}
function fromhere(i) {cmarkers[i].openInfoWindowHtml(from_htmls[i]);}
function setDirections(fromAddress, toAddress) {gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "en_US" });}
function createMarker(lat,lng,html,acuprefix,addr) {
	lat=base64decode(lat);
	lng=base64decode(lng);
	var point = new GLatLng(lat,lng);
	if (acuprefix) {
		var marker = new GMarker(point,coldIconsp);
		acuct++;
	} else
		var marker = new GMarker(point,coldIcon);
    to_htmls[mkct] = base64decode(html) + '<br/>Directions: <b>To here</b> - <a href="javascript:fromhere(' + mkct + ')">From here</a>' +
		'<br/>Start address:<form action="?mid=directions" method="post">' +
        '<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="' + base64decode(addr) + 
        '"/>';
    from_htmls[mkct] = base64decode(html) + '<br/>Directions: <a href="javascript:tohere(' + mkct + ')">To here</a> - <b>From here</b>' +
        '<br/>End address:<form action="?mid=directions" method="post">' +
        '<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="' + base64decode(addr) +
        '"/>';
    html = base64decode(html) + '<br/>Directions: <a href="javascript:tohere('+mkct+')">To here</a> - <a href="javascript:fromhere('+mkct+')">From here</a>';
    GEvent.addListener(marker, "click", function() {
    	marker.openInfoWindowHtml(html);
    });
    cmarkers[mkct] = marker;
    hmarkers[mkct] = new GMarker(point,hotIcon);
    htmls[mkct] = html;
    bounds.extend(point);
    mkct++;
}
function myclick(i) {hmarkers[i].openInfoWindowHtml(htmls[i]);}
function mymouseover(i) {
    map.removeOverlay(cmarkers[i]);
    map.addOverlay(hmarkers[i]);
    hmarkers[i].openInfoWindowHtml(htmls[i]);
}
function mymouseout(i) {
    map.removeOverlay(hmarkers[i]);
    map.addOverlay(cmarkers[i]);
}
function showMakers() {
	map.clearOverlays();
	for (var i = mkct-1; i >= 0; --i) {
    	map.addOverlay(cmarkers[i]);
  	}
}
function removeMakers() {
	map.clearOverlays();
}
function base64decode(str) {
    var c1, c2, c3, c4;
    var i, len, out;
    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
        do { c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        } while(i < len && c1 == -1);
        if(c1 == -1) break;
        do { c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        } while(i < len && c2 == -1);
        if(c2 == -1) break;
        out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
        do { c3 = str.charCodeAt(i++) & 0xff;
        	if(c3 == 61) return out;
            c3 = base64DecodeChars[c3];
        } while(i < len && c3 == -1);
        if(c3 == -1) break;
        out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
        do { c4 = str.charCodeAt(i++) & 0xff;
            if(c4 == 61) return out;
            c4 = base64DecodeChars[c4];
        } while(i < len && c4 == -1);
        if(c4 == -1) break;
        out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
}

function setDirections(fromAddress, toAddress) {
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "en_US" });
}

function handleErrors(){
       if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
         alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\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_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\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("An unknown error occurred.");
}

function onGDirectionsLoad(){
      // Use this function to access information about the latest load()
      // results.
      //  document.getElementById("getDistance").innerHTML = gdir.getDistance().html;
} 
