﻿/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js" />

var dir;
var fromCity;
var toCity
google.load("maps", "2.x");
google.setOnLoadCallback(initialize);

$(function() {
    $("#fsResults").hide();
    $("#fsGasCardForm").hide();
    $("#divGasCardFormSubmit").hide();
    fromCity = $("#txtFromCity");
    toCity = $("#txtToCity");
    $("body").keydown(enterFiresCalculate);
});

function initialize() {
    setupWaterMark();
    $("#btnCalculate").click(function() {
        setDirections();
        toggleGasFormView();
    });
    $("#btnSkip").click(function() {
        toggleGasFormView();
        $("#fsResults").hide();
    });
    dir = new google.maps.Directions();
    google.maps.Event.addListener(dir, "load", onDirectionLoad);
    google.maps.Event.addListener(dir, "error", handleErrors);
    $(window).unload(function() { google.maps.Unload(); });
}

function enterFiresCalculate(e) {
    var charCode = e.which || e.keyCode;
    if (charCode == 13) {
        $("#btnCalculate").click();
        $("#fsGasCardForm input:first").focus();
        $("body").unbind("keydown", enterFiresCalculate);
        return false;
    }
}

function toggleGasFormView() {
    $("#fsGasForm").hide();
    $("#divGasFormSubmit").hide();
    $("#fsResults").show();
    $("#fsGasCardForm").show();
    $("#divGasCardFormSubmit").show();
}

function setupWaterMark() {
    var watermark = "City, ST";
    if (fromCity.val() == "") {
        fromCity.val(watermark);
        fromCity.addClass("watermark");
    }

    fromCity.focus(function() {
        if ($(this).val() == watermark) {
            $(this).val("");
            $(this).removeClass("watermark");
        }
    }).blur(function() {
    if ($(this).val() == "") {
            $(this).val(watermark);
            $(this).addClass("watermark");
        }
    });
}

function setAddress() {
    var fromCityValue = fromCity.val().toUpperCase;
    if (fromCityValue.indexOf("SHREVEPORT") < 0) {
        toCity.val("Shreveport-Bossier, LA");
    }
    else {
        fromCity.val("Shreveport-Bossier, LA");
    }
}

function setDirections() {
    var toCityValue = toCity.val();
    var fromCityValue = fromCity.val();
    dir.load("from:" + fromCityValue + " to:" + toCityValue);
}

function onDirectionLoad() {
    var strSummary
    var iMiles
    var iGasPrice
    var iMPG
    var iTripCost
    strSummary = dir.getSummaryHtml();
    strSummary = strSummary.replace(",", "");
    iMiles = parseFloat(strSummary.substring(0, strSummary.indexOf("&")));
    iGasPrice = parseFloat($("#txtPricePerGallon").val());
    iMPG = parseFloat($("#txtMpg").val());
    iTripCost = (iMiles / iMPG) * iGasPrice;
    $("#ddDistanceTime").html("The distance in miles is " + strSummary);
    $("#ddCost").html("The cost of gas will be " + formatCurrency(iTripCost));
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
	num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function handleErrors() {
    if (!(toCity.val() == "" || fromCity.val() == "")) {
        if (dir.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: " + dir.getStatus().code);
        else if (dir.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: " + dir.getStatus().code);

        else if (dir.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: " + dir.getStatus().code);

        else if (dir.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: " + dir.getStatus().code);

        else if (dir.getStatus().code == G_GEO_BAD_REQUEST)
            alert("A directions request could not be successfully parsed.\n Error code: " + dir.getStatus().code);

        else alert("An unknown error occurred. \n Error code: " + dir.getStatus().code);
    }
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
        return false;

    return true;
}
