﻿var geocoder = new GClientGeocoder();
var map;
var icon = new GIcon();

var ctrlPrefix = 'StockListSearchResults_';
var blnDebug = false;

var sGlobalAddressOriginal = '';
var sGlobalOriganisationName = '';
var sGlobalAddressManipulated = '';
var sGlobalMode = '';
var bGlobalAddressVarsSet = false;
var bGlobalAmbiguousLocation = false;
var bGlobalGeoAccuracy = 0;
var gMapCanvasID = 'googleMap';


function setAddressVars(Mode, AddressOriginal, OriganisationName) {

    //if (!(bGlobalAddressVarsSet))
    //{
    sGlobalAddressOriginal = AddressOriginal;
    sGlobalOriganisationName = OriganisationName;
    sGlobalMode = Mode;
    //bGlobalAddressVarsSet = true;	
    //}

} // fx : 	setAddressVars()



function loadGoogleMapAdmin(lat, lon, add) {
    // VOID ADMIN ONLY

} // fx : loadGoogleMap end 	


function loadGoogleMapFrontEnd(lat, lon) {
    alertTrace('loadGoogleMap(' + lat + ',' + lon + ') : start ');
    alertTrace('test :  GBrowserIsCompatible');
    if (GBrowserIsCompatible()) {
        alertTrace('test :  GBrowserIsCompatible : true');
        try {
            map = new GMap2(document.getElementById(gMapCanvasID));
        } catch (e) {
            alertTrace(e.description + '\n attempted to create map \n check the div canvas id is ' + gMapCanvasID);
        }
        alertTrace('add controls : map.addControl(new GSmallMapControl()); : map.addControl(new GMapTypeControl()); ');
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

        alertTrace('map.setCenter(new GLatLng(' + lat + ',' + lon + '), 15)');
        map.setCenter(new GLatLng(lat, lon), 15);
        alertTrace('map.setCenter : done');

        var point = new GLatLng(lat, lon);
        alertTrace('point created');
        var marker = null;

        marker = new GMarker(point);
        map.addOverlay(marker);
        shtmlInfo = formatFinalDisplayInfoBubble();
        marker.openInfoWindowHtml(shtmlInfo);
        alertTrace('finished');

    }
}  // fx : loadGoogleMapFrontEnd end 



function geoCode(mode, sAddress, orgTitle, latPoint, longPoint) {
    var args = geoCode.arguments;
    var blnGeoCode = true;
    setAddressVars(mode, sAddress, orgTitle);
    if (args.length == 5) {
        if ((latPoint != '') && (longPoint != '')) {
            blnGeoCode = false;
            loadGoogleMapFrontEnd(latPoint, longPoint);
        }
    }
    alertTrace('geocoder.getLatLng();');
    if (blnGeoCode) {
        geocoder.getLatLng(
				sAddress,
				function(point) {
				    if (!point) {
				        bGlobalAmbiguousLocation = true;
				        alertTrace('point not found : split address');
				        var mySplitVal = sAddress.split(",");
				        var newAddressVal = '';
				        for (i = 1; i < mySplitVal.length; i++) {
				            newAddressVal += mySplitVal[i] + ',';
				        }
				        newAddressVal = newAddressVal.slice(0, -1);
				        bGlobalGeoAccuracy = mySplitVal.length;
				        alertTrace('retest with address :' + newAddressVal);
				        // WARNING :  RECURSIVE CALL HERE
				        if ((bGlobalGeoAccuracy) >= 2) {
				            alertTrace('0 value = ' + mySplitVal[0] + '1 value = ' + mySplitVal[1]);
				        }
				        (bGlobalGeoAccuracy >= 2) ? geoCode(mode, newAddressVal) : alertTrace('Failed to find address');
				    } else {
				        if (mode == 'admin') {
				            loadGoogleMapAdmin(point.y, point.x, sAddress);
				            if (!bGlobalAmbiguousLocation) {
				                writeBackCoordinates(point.x, point.y, 'Driving function geoCode else point exists');
				            }
				        } else if (mode == 'frontend') {
				            loadGoogleMapFrontEnd(point.y, point.x, sAddress);
				            bGlobalAddressVarsSet = false;
				        }

				    } // else
				} // callback function
			);  //geocoder
    } // if blnGeoCode
} // fx : geoCode end 

function writeBackCoordinates(x, y, from) {
    // VOID ADMIN ONLY	

} // fx : writeBackCoordinates end

function formatFinalDisplayInfoBubble() {
    var sRetVal = '';
    var orgTitleHtml = '';
    var originalAddress = '';
    originalAddress = sGlobalAddressOriginal;

    if (sGlobalOriganisationName != '') {
        orgTitleHtml = "<strong>" + sGlobalOriganisationName + "</strong>";
        orgTitleHtml += "<br />";
    }
    var mySplitVal = originalAddress.split(",");
    var newVal = '';
    // preserve the last comma elements		
    var intOffSet = 0;
    if (mySplitVal.length >= 2) {
        intOffSet = 2;
    } else {
        intOffSet = mySplitVal.length;
    }
    for (i = 0; i < mySplitVal.length; i++) {
        if (i <= intOffSet) {
            newVal += mySplitVal[i] + '<br />';
        } else {
            newVal += mySplitVal[i] + ', ';
        }
    }
    newVal = newVal.slice(0, -2);
    sRetVal = "<div style='font-family : Tahoma; color : Black; font-size : 12px; text-align:center;'>" + orgTitleHtml + newVal + "</div>";

    return sRetVal;
} // fx : formatFinalDisplayInfoBubble end

function alertTrace(sVar) {
    if (blnDebug == true) {
        alert(sVar);
    }
} // fx : alertTrace end

//************* Error Handle **********************
function handleErrors() {
    if (directions.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: " + directions.getStatus().code);
    else if (directions.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: " + directions.getStatus().code);

    else if (directions.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: " + directions.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 (directions.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: " + directions.getStatus().code);

    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);

    else alert("Cannot calculate directions from the address specified.");

}
//*************************************************

//************* Directions **********************
function getDirections() {
    try {
        directionsPanel = document.getElementById("route");
        //clear panel before re-loading
        directionsPanel.innerHTML = "";
        directions = new GDirections(map, directionsPanel);

        //add listener for catching errors
        GEvent.addListener(directions, "error", handleErrors);

        //attempt load directions
        var tbFrom = document.getElementById("tbFrom");
        directions.load("from: " + tbFrom.value + " to: " + sGlobalAddressOriginal);

    } catch (e) {
        alert(e);
    }
}
//*************************************************
