﻿// Copyright(c) 2008-2009 IT One, Ltd, Slovakia
// Do not use, change or distribute.

var routeStart;
var routeEnd;
var dirPolyLine;
var routeVias = new Array();

function handleRoutePointChanged(){
	if (routeStart == null || routeEnd == null)
		return;
		
	var startPos = routeStart.getLatLng();
	var endPos = routeEnd.getLatLng();
	
	var startText = startPos.lat().toString() + ", " + startPos.lng().toString();
	var endText = endPos.lat().toString() + ", " + endPos.lng().toString();

	var rtStrArray = new Array();
	rtStrArray.push(startText);
	for (i = 0; i < routeVias.length; i++) {
	    var latLng = routeVias[i].getLatLng();
	    rtStrArray.push(latLng.lat().toString() + ", " + latLng.lng().toString());
	}
	rtStrArray.push(endText);

	directions.loadFromWaypoints(rtStrArray, { preserveViewport: true, getSteps:true });
	google.maps.Event.addListener(directions, 'load', refreshRouteInfo);
}

function handleDirectionsLoaded(dirs){
	//clear markers got from direction
	var count = directions.getNumGeocodes();
	var i;
	for (i = 0; i < count; i++){
		var marker = directions.getMarker(i);
		if (marker != null)
			map.removeOverlay(marker);
	}
}

function setRouteEndFromContextMenu(){
	if (routeEnd == null){
		routeEnd = createDraggableMarker(contextMenuLatLng.lat(), contextMenuLatLng.lng(), "rtFinish.gif");
		google.maps.Event.addListener(routeEnd, "dragend", function(latLng) {
			handleRoutePointChanged();
		});
	}
	else {
		routeEnd.setLatLng(contextMenuLatLng);
	}
	handleRoutePointChanged();
}

function setRouteViaFromContextMenu() {
    var via = createDraggableMarker(contextMenuLatLng.lat(), contextMenuLatLng.lng(), "rtVia.gif");
    google.maps.Event.addListener(via, "dragend", function(latLng) {
        handleRoutePointChanged();
    });
    routeVias.push(via);
    handleRoutePointChanged();
}

function setRouteStartFromContextMenu(){
	if (routeStart == null){
		routeStart = createDraggableMarker(contextMenuLatLng.lat(), contextMenuLatLng.lng(), "rtStart.gif");
		google.maps.Event.addListener(routeStart, "dragend", function(latLng) {
			handleRoutePointChanged();
		});
	}
	else {	
		routeStart.setLatLng(contextMenuLatLng);
	}
	handleRoutePointChanged();
}

function handleDirectionsError(){
/*	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: " + gdir.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: " + gdir.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: " + 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 (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: " + gdir.getStatus().code);

   else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
     */
}

function handleDiscardRouteContextMenu(){
	if (routeStart != null)
		map.removeOverlay(routeStart);
	if (routeEnd != null)
	    map.removeOverlay(routeEnd);
	routeStart = null;
	routeEnd = null;
	directions.clear();
	var i;
	for (i = 0; i < routeVias.length; i++) {
	    map.removeOverlay(routeVias[i]);
	}
	routeVias.length = 0;
}

var cummulativeDistance = 0; //meters
var cummulativeDuration = 0; //seconds

function refreshRouteInfo() {
    setActiveToolTab("my");
    handleMyUpdate('Route', document.getElementById("myRoute"));

    cummulativeDistance = 0;
    cummulativeDuration = 0;
    
    var rtInfo = document.getElementById("myRtDiv1");
    rtInfo.innerHTML = "";

    var table = document.createElement("table");
    table.style.width = "98%";
    table.style.height = "100px";
    rtInfo.appendChild(table);
    
    //start
    var tr = table.insertRow(-1);
    tr.style.cursor = "pointer";
    tr.style.backgroundColor = "#aaaaCF";
    var cell = tr.insertCell(-1);
    cell.innerHTML = getLocaleString("RtStart");
    cell.style.width = "150px";
    cell.style.height = "20px";
    cell.style.fontSize = "10px";


    var i, j, curVia = 0;
    
    for (j = 0; j < directions.getNumRoutes(); j++) {

        var route = directions.getRoute(j);

        cummulativeDistance += route.getDistance().meters;
        cummulativeDuration += route.getDuration().seconds;
        
        for (i = 0; i < route.getNumSteps(); i++) {
            var step = route.getStep(i);
            var tr = table.insertRow(-1);
            tr.style.cursor = "pointer";

            if ((i % 2) > 0)
                tr.style.backgroundColor = "#aaFFCF";

            var cell = tr.insertCell(-1);
            cell.innerHTML = step.getDescriptionHtml();
            cell.style.width = "150px";
            cell.style.fontSize = "10px";

            cell = tr.insertCell(-1);
            cell.style.fontSize = "10px";
            cell.style.fontWeight = "bold";
            cell.style.width = "30px";
            cell.innerHTML = step.getDistance().html;

            cell = tr.insertCell(-1);
            cell.style.fontSize = "10px";
            cell.style.fontWeight = "bold";
            cell.style.width = "30px";
            cell.innerHTML = step.getDuration().html;

            var latLng = step.getLatLng();
            tr.setAttribute("lat", latLng.lat().toString());
            tr.setAttribute("lng", latLng.lng().toString());
            tr.setAttribute("onclick", "handleRtStepClick(this)");
        }

        //Via
        if (curVia < routeVias.length) {
            var tr = table.insertRow(-1);
            tr.style.cursor = "pointer";
            tr.style.backgroundColor = "#aaaaCF";
            var latLng = routeVias[curVia++].getLatLng();
            tr.setAttribute("lat", latLng.lat().toString());
            tr.setAttribute("lng", latLng.lng().toString());
            tr.setAttribute("onclick", "handleRtStepClick(this)");
            var cell = tr.insertCell(-1);
            cell.innerHTML = getLocaleString("RtVia") + " " + curVia.toString();
            cell.style.width = "150px";
            cell.style.height = "20px";
            cell.style.fontSize = "10px";
        }

    }
    
    //finish
    var tr = table.insertRow(-1);
    tr.style.cursor = "pointer";
    tr.style.backgroundColor = "#aaaaCF";
    var cell = tr.insertCell(-1);
    cell.innerHTML = getLocaleString("RtFinish");
    cell.style.width = "150px";
    cell.style.height = "20px";
    cell.style.fontSize = "10px";

    var bellowDiv = document.getElementById("myRtDiv2");
    var duration = document.getElementById("rtDuration");
    var ufDur = getUserFriendlyDuration(cummulativeDuration);
    var ufDist = getUserFriendlyDistance(cummulativeDistance);
    duration.innerHTML = ufDur.value.toString() + " " + getLocaleString(ufDur.unit);
    var distance = document.getElementById("rtDist");
    distance.innerHTML = ufDist.value.toString() + " " + getLocaleString(ufDist.unit);

    //update rout cals
    updateRouteCalculations();
}

function handleRtStepClick(row) {
    map.setCenter(new google.maps.LatLng(Number(row.getAttribute("lat")), 
        Number(row.getAttribute("lng"))), map.getZoom());
}

function getUserFriendlyDuration(seconds) {
    var ret = new Object();
    
    ret.value = seconds / 60;
    if (ret.value < 60){
        ret.unit = "rtMin";
        ret.value = Math.round(ret.value);
        return ret;
    }

    ret.value = ret.value / 60;
    if (ret.value < 24){
        ret.unit = "rtHrs";
        ret.value = Math.round(ret.value * 10) / 10;
        return ret;
    }

    ret.value = ret.value / 24;
    ret.value = Math.round(ret.value * 10) / 10;
    ret.unit = "rtDays";
    
    return ret;
}

function getUserFriendlyDistance(meters) {
    var ret = new Object();
    ret.value = meters;
   
    if (ret.value < 1000){
        ret.value = meters;
        ret.unit = "rtMtrs";
        return ret;
    }

    ret.value = ret.value / 1000;
    ret.value = Math.round(ret.value * 100) / 100;
    ret.unit = "rtKm";
    
    return ret;
}

function updateRouteCalculations() {
    var fuelTankCap = document.getElementById("rtFTCap").value;
    var rtFTSTElem = document.getElementById("rtFTState");
    var fuelTankState = rtFTSTElem.options[rtFTSTElem.selectedIndex].value;
    var litresInTan = fuelTankCap * fuelTankState;
    var minCons = Number(document.getElementById("rtMinCnsp").value);
    var maxCons = Number(document.getElementById("rtMaxCnsp").value);
    var avgCons = (minCons + maxCons) / 2;
    var dist100Km = cummulativeDistance / 100000;

    //more sophist. calc. from web svc
    var estCons = dist100Km * avgCons;

    var totalConsElem = document.getElementById("rtTotCnsp");
    totalConsElem.innerHTML = Math.round(estCons * 100) / 100;

    var tankStopsElem = document.getElementById("rtTankSt");
    //first stop
    if (estCons < litresInTan)
        tankStopsElem.innerHTML = "0";
    else {
        var firstStopAfter100Km = litresInTan * avgCons;
        var restKms = dist100Km - firstStopAfter100Km;
        var numStops = 0;
        
        if (restKms > 0) {
            numStops = Math.Round((restKms * avgCons) / fuelTankCap);
        }

        tankStopsElem.innerHTML = (numStops + 1).toString();
    }
}