﻿var directionsService = new google.maps.DirectionsService();
var isQuoteFail;

//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) {isQuoteFail = 1;};
    if (objMileage["end"] === undefined) {isQuoteFail = 1;};
    if (objMileage["field"] === undefined) {objMileage["field"] = "calcDistance"; };

    if (isQuoteFail == 1) {
        captureFail();
    }
    else {
        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 {

                gAttempts += 1;

                if (gAttempts == 3) {
                    captureFail();
                }

                if (gAttempts == 1) {
                    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');
                            }
                        }
                    });
                }

                if (gAttempts == 2) {
                    calcMileage({
                        "origin": objMileage["origin"],
                        "end": "center of " + $('#LocationZip').val(),
                        "field": "calculatedDistance",
                        "units": objMileage["units"],
                        "function": function () {
                            if (($('#calculatedDistance').val() == '') || ($('#calculatedDistance').val() === undefined)) {
                                alert('Error Please Contact Administrator!');
                            }
                            else {
                                $('#frmQuoteGenerator').trigger('submit');
                            }
                        }
                    });
                }
                

            }


        });
    }
}

//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;

    });
});

