﻿var directionsService = new google.maps.DirectionsService();

//Function calcMilesage
//returns object[meters,miles,kilometers]
function calcMileage(objMileage) {

    if (objMileage["units"] === undefined) { objMileage["units"] = "MI" };
    if (objMileage["function"] === undefined) { objMileage["function"] = function() {} };
    if (objMileage["origin"] === undefined) { captureFail(); };
    if (objMileage["end"] === undefined) { captureFail(); };
    if (objMileage["field"] === undefined) {objMileage["field"] = "calcDistance"; };

    var startLocation;
    if (objMileage["origin"]["address"] === undefined) {
        startLocation = objMileage["origin"]
    }
    else {
        if (objMileage["origin"]["country"] == 'United States') {
            startLocation = objMileage["origin"]["address"] + ' ' + objMileage["origin"]["city"] + ', ' + objMileage["origin"]["state"] + ' ' + objMileage["origin"]["zip"];
        }
        else {
            startLocation = objMileage["origin"]["address"] + ', ' + objMileage["origin"]["city"] + ', ' + objMileage["origin"]["state"] + ', ' + objMileage["origin"]["zip"] + ', ' + objMileage["origin"]["country"];
        }
    }

    var request = {
        origin: startLocation,
        destination: objMileage["end"],
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    //send request
    directionsService.route(request, function (response, status) {

        if (status == google.maps.DirectionsStatus.OK) {

            //This example only uses one trip and one route
            var myRoute = response.routes[0].legs[0];

            //Gives you distance in meters
            var myRouteMeters = myRoute.distance.value;

            //Gives you text representation using units of origin country (34.5 mi)
            var myRouteOrigin = myRoute.distance.text;

            //alert(myRouteOrigin);

            //Removing "mi" from mileage
            var myRouteMiles = myRouteOrigin.split(' ');

            var distanceObject = [];
            distanceObject["M"] = myRouteMeters;
            distanceObject["MI"] = myRouteMeters * 0.000621371192;
            distanceObject["KM"] = myRouteMeters * 0.001;

            $('#' + objMileage["field"]).val(distanceObject[objMileage["units"]].toFixed(1));

            objMileage["function"]();

        }
        else {


            if (gAttempts == 2) {
                captureFail();
            }
            else {
                calcMileage({
                    "origin": objMileage["origin"]["zip"],
                    "end": $('#LocationZip').val(),
                    "field": "calculatedDistance",
                    "units": objMileage["units"],
                    "function": function () {
                        if (($('#calculatedDistance').val() == '') || ($('#calculatedDistance').val() === undefined)) {
                            alert('Error Please Contact Administrator!');
                        }
                        else {
                            $('#frmQuoteGenerator').trigger('submit');
                        }
                    }
                });
            }
            gAttempts += 1;

        }


    });

}

//Action on failed Distance Calculation
function captureFail() {
    $('#calculatedDistance').val(-1);
    $('#frmQuoteGenerator').trigger('submit');
}

var isAutoQuote, gOrigin, gAttempts;
$(document).ready(function () {
    gAttempts = 0;
    $('.intelligence_tool_options tr:nth-child(even)').addClass('alternate');

    isAutoQuote = $('body').data('isAutoQuote');

    var gOrigin = {
        "address": $('body').data('startAddress'),
        "city": $('body').data('startCity'),
        "state": $('body').data('startState'),
        "zip": $('body').data('startZip'),
        "country": $('body').data('startCountry')
    }
    var chosenUnits = $('body').data('chosenUnits');

    $('form').validate();
    $('#submitForm').click(function () {

        if (($('#LocationZip').val() == '') || ($('#LocationZip').val() === undefined)) {
            alert('Please enter a Venue Zip Code');
            $('input[name=LocationZip]').focus();
            return false;
        }

        if (isAutoQuote > 0) {
            calcMileage({
                "origin": gOrigin,
                "end": $('#LocationZip').val(),
                "field": "calculatedDistance",
                "units": chosenUnits,
                "function": function () {
                    if (($('#calculatedDistance').val() == '') || ($('#calculatedDistance').val() === undefined)) {
                        alert('Error Please Contact Administrator!');
                    }
                    else {
                        $('#frmQuoteGenerator').trigger('submit');
                    }
                }
            });
        }
        else {
            $('#frmQuoteGenerator').trigger('submit');
        }

        return false;

    });

    //Used to reset Vendor/Advertisement Form
    function getInputs(myElement) {
        var inputs = [];
        $(':input, select, textarea', myElement).each(function () {
            if (this.name != '__VIEWSTATE' && this.name != '__EVENTVALIDATION') {
                inputs[this.name] = escape(this.value);
            }
        })
        return inputs;
    }

});
