API Docs for:
Show:

File: Inventory\ShowDealerVanDetail.js

/*================================================================================================================\
+
+ Project     : GODATA-VCEV
+ Filename    : ShowDealerVanDetail.js
+ Module Name : Van Coverage Designer
+ Purpose     : To show details of a van and design its coverage for all SLAs and save that.
+ Coded By    : Pankaj Khandal
+
+================================================================================================================*/


var COVERAGE_JSON = []; // To store all the newly generated coverage
var GET_COVERAGE_JSON = []; // To store exiting coverage JSON objects
var EXISTING_COVERAGE_JSON = {};    // To store existing Coverage JSON for a Van

/**
* To show details of a van and design its coverage for all SLAs and save that.
* @module Inventory
*/

/**
* To show details of a van and design its coverage for all SLAs.
* @class VanCoverageDesigner
* @constructor
*/


//================= Global variables===============================
/**
* Global References: Initializing global stores for markers, images, icons, enable/disable bits etc.
* @for VanCoverageDesigner
*/
var map = null;
var directionService;
var geoCoder;
var distanceMatrixService;


var pointAngle = 30;   // Angle on which we want a point from a sorce point (Degree)
var radiusIncrement = 15;  // constant increament in radius to get optimal reachable point from a van
var radiusAccToSlaObj = { '90': 55, '120': 75 };    // Van's reachable point's minimum distance (KMs) for diffrent SLAs in minutes
var coverageMultiplier = 1.6;   // coverage enhancer factor
var slaTimeInMin = 0;   // to store SLA time globally
var slaId = 0;  // To store SLA Id globally
var latlngbounds;   // To store lat-long objects globally

var enableDiffCoverage = false; // to enable designing coverage for another SLA
var vanId = ''; // To store van id gloabally
var vanLat = 0; // To store van lay gloabally
var vanLng = 0; // To store van long globally
var allSlaCount = 0;    // To store all SLA count
var isCoverageExist = false;    // To check whether coveage exists or not
var coverageDesiged = false;    // To check if coveage is designed or not


//-----------------------------------------------
var disable_map_click_Listener = true;  // To disable map click
var disable_map_mousemove_Listener = true;  // To disable changing the cursor when move to map
var enableCoverageDesign = true;    // To enable the coverage design functionality
var popTheVanOut = true;    // if there is any error in designig coverage, then delete the last van inserted into Van Marker list

var VAN_MARKERS = [];   // To store van markers globally
var VAN_ROUTES = [];    // To store van routes globally
var POLYGONS = [];  // To store Polygon objects globally
var directionObj = {};  // to store Direction Objects globally
var VAN_REACHABLE_POINT = [];   // To store van reachbale points objects globally.
//--------------------------------------------

//initialize marker paths
var vanImagePath = "../../Content/css/images/avil-van.png",
    vanReachablePointImagePath = "../../Scripts/map_api/icons/red_circle.png",
    markerTransImgPath = "../../Scripts/map_api/icons/red_blink.gif",
    vanToolImagePath = "../../Content/css/images/avil-van-pointing.png",
    defaultLat = 26.912285124827,
    defaultLng = 75.7873203125;

//=================================================================


/////============================= Getting Circular points which is some time away from a source point =====================
/**
* To convert a degrees into radians.
* @method Number.prototype.toRad
* @for VanCoverageDesigner
*/
Number.prototype.toRad = function () {
    return this * Math.PI / 180;
}

/**
* To convert a radians into degrees.
* @method Number.prototype.toDeg
* @for VanCoverageDesigner
*/
Number.prototype.toDeg = function () {
    return this * 180 / Math.PI;
}

/**
* To get a position at an angle and at a distance on google map.
* @method google.maps.LatLng.prototype.destinationPoint
* @param {Number} angle angle in Degrees
* @param {Number} dist distance in KMs
* @for VanCoverageDesigner
*/
google.maps.LatLng.prototype.destinationPoint = function (angle, dist) {
    dist = dist / 6371;
    angle = angle.toRad();
    var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
    var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(angle));
    var lon2 = lon1 + Math.atan2(Math.sin(angle) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2));
    if (isNaN(lat2) || isNaN(lon2)) return null;
    return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}

/**
* To get a position at an angle and at a distance on google map.
* @method findReachablePointsForVan
* @param {Object} sourcePosition position(lat-long object) of source
* @param {Number} pointAngle angle in Degrees
* @param {Number} radius distance in KMs
* @for VanCoverageDesigner
*/
function findReachablePointsForVan(sourcePosition, pointAngle, radius) {
    var reachablePoints = [];
    for (var i = 0; i <= 360; i = i + pointAngle) {
        var point = sourcePosition.destinationPoint(i, radius);
        reachablePoints.push(point);
    }
    return reachablePoints;
}
/////================================================================================================================

///============== Delete/Remove Objects From Map Section Start ==============================


/**
* To delete all van reachbale points from the map
* @method deleteAllVanReachablePoint
* @for VanCoverageDesigner
*/
function deleteAllVanReachablePoint() {
    for (var i = 0; i < VAN_REACHABLE_POINT.length; i++) {
        VAN_REACHABLE_POINT[i].setMap(null);
    }
    // Making the MARKERS-Array empty.
    VAN_REACHABLE_POINT = [];
}

/**
* To delete all the van markers from the map
* @method deleteVanMarkers
* @for VanCoverageDesigner
*/
function deleteVanMarkers() {
    for (var i = 0; i < VAN_MARKERS.length; i++) {
        VAN_MARKERS[i].setMap(null);
    }
    VAN_MARKERS = [];    // Making the Global Van-Array empty.
}

/**
* To delete marker from the map based on the id
* @method deleteMarker
* @param {String} markerId id of marker
* @for VanCoverageDesigner
*/
function deleteMarker(markerId) {
    for (var i = 0; i < MARKERS.length; i++) {
        if (MARKERS[i].id == markerId) {
            MARKERS[i].setMap(null);
            MARKERS.splice(i, 1);
        }
    }
}

/**
* To delete all polygons from the map
* @method deleteAllPolygons
* @for VanCoverageDesigner
*/
function deleteAllPolygons() {
    for (var i = 0; i < POLYGONS.length; i++) {
        POLYGONS[i].setMap(null);
    }
    POLYGONS = [];
}

/**
* To delete polygon from the map based on the id
* @method deletePolygon
* @param {String} polygonId id of polygon
* @for VanCoverageDesigner
*/
function deletePolygon(polygonId) {
    for (var i = 0; i < POLYGONS.length; i++) {
        if (POLYGONS[i].title == polygonId) {
            POLYGONS[i].setMap(null);
            POLYGONS.splice(i, 1);
        }
    }
}

/**
* To delete a route based on the id (Blind Spot)
* @method deleteRoute
* @param {String} routeId Id of route
* @for VanCoverageDesigner
*/
function deleteRoute(routeId) {
    var route = directionObj[routeId];
    for (var i = 0; i < route.length; i++) {
        route[i].setMap(null);
    }
    directionObj[routeId] = [];
}

/**
* To delete all routes from the map based on the id (Blind Spot)
* @method deleteAllRoutes
* @for VanCoverageDesigner
*/
function deleteAllRoutes() {
    $.each(VAN_REACHABLE_POINT, function (index, marker) {
        deleteRoute(marker.id);
    });
    directionObj = {};
}
///============== Delete/Remove Objects From Map Section End ==============================
/**
* To reset blind spots generator
* @method resetBlindSpotGenerator
* @for VanCoverageDesigner
*/
function resetVanCoverage() {
    deleteVanMarkers(); // Deleting Van-Markers from the map.
    deleteAllRoutes();   // Deleting all the routes from the map
    deleteAllPolygons(); // Deleting all the polygons
    deleteAllVanReachablePoint();    // Deleting all van reachbale points

    $('.slaBtn').removeClass('slaBtnSelected');  // deselect SLA Buttons

    // Re-Initializing all the global variables for BlindSpot.
    disable_map_click_Listener = true;
    disable_map_mousemove_Listener = true;
    enableCoverageDesign = true;
    popTheVanOut = true;

    allSlaCount = 0;

    MARKERS = [];
    VAN_REACHABLE_POINT = [];
    COVERAGE_JSON = [];
    GET_COVERAGE_JSON = [];
}

/**
* To save the generated Van Coverage
* @method saveVanCoverage
* @for VanCoverageDesigner
*/
function saveVanCoverage() {
    $("#div_load").show(); // Showing loading
    SecurityToken = securityToken;

    // If vanId is not there, then don't save the coverage
    if (vanId == '') {
        jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['before_coverage_design_warning'], 'Message');
        $("#div_load").hide(); // Hiding loading
        return;
    }
    // If coverage for all SLAs is not designed, then don't save the coverage at all.
    if (COVERAGE_JSON.length != allSlaCount) {
        jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['all_sla_coverage_design_warning'], 'Message');
        $("#div_load").hide(); // Hiding loading
        return;
    }

    var updatedVanCoverageData = JSON.stringify(COVERAGE_JSON);  // serializing the JSON before sending to the server
    $.ajax({
        url: WCFRESTURL.GetInsertVanCoverage,
        type: "POST",
        data: { Token: "teramatrix", Operation: 'insert', VanId: vanId, VanDefaultLatitude: vanLat, VanDefaultLongitude: vanLng, CoverageJson: updatedVanCoverageData },
        dataType: "json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8", // This is the content type when posting Plain Text to server.
        success: function (data) {
            // showing success message when coverage is designed
            if (data.Status == '1') {
                jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['van_coverage_design_success'], 'Message');
            }
            $('#coverageBtns').hide();
        },
        complete: function () {
            $("#div_load").hide();  // Hiding loading
            COVERAGE_JSON = []; // Making empty the coverage design to store new coverage.
        },
        error: function (jqXHR, textStatus, errorThrown) {
            jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['van_coverage_design_error'], 'Message');
            $("#div_load").hide(); // Hiding loading
        }
    });
}


/**
* To get Van coverage, if exists.
* @method getExitingVanCoverage
* @param {String} van_id Id of Van
* @for VanCoverageDesigner
*/
function getExitingVanCoverage(van_id) {
    SecurityToken = securityToken;

    var getVanCoverageData = JSON.stringify(GET_COVERAGE_JSON);  // serializing the JSON before sending to the server
    $.ajax({
        url: WCFRESTURL.GetInsertVanCoverage,
        type: "POST",
        data: { Token: "teramatrix", Operation: 'get', VanId: van_id, VanDefaultLatitude: '', VanDefaultLongitude: '', CoverageJson: getVanCoverageData },
        dataType: "json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8", // This is the content type when posting Plain Text to server.
        success: function (data) {
            // If status is success
            if (data.Status == '1') {
                // If there is no van lat-long, then show coverage buttons to design the coverage
                if (data.VanDefaultLatitude === null) {
                    $('#coverageBtns').show();
                }
                // if coverage is there then store it globally
                else {
                    isCoverageExist = true;
                    EXISTING_COVERAGE_JSON = data;
                }
            }
        },
        complete: function () {
        },
        error: function (jqXHR, textStatus, errorThrown) {
            jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['van_coverage_not_exists'], 'Message');
        }
    });
}


/**
* SLA button click handler
* If there is existing van coverage available then plot that on map, else allow designing van coverage on map click.
* @method slaButtonClick
* @for VanCoverageDesigner
*/
function slaButtonClick(currBtn) {
    $('.slaBtn').removeClass('slaBtnSelected'); // deselecting all the SLA buttons
    $(currBtn).addClass('slaBtnSelected');  // selecting the currently clicked SLA button
    slaTimeInMin = $(currBtn).val();    // stroring SLA value
    slaId = $(currBtn).attr('id');  // getting SLA Id

    disable_map_click_Listener = false;
    disable_map_mousemove_Listener = false;

    if (isCoverageExist && EXISTING_COVERAGE_JSON.VanDefaultLatitude !== null) {
        deleteVanMarkers(); // Deleting Van-Markers from the map.
        deleteAllRoutes();   // Deleting all the routes from the map
        deleteAllPolygons(); // Deleting all the polygons
        deleteAllVanReachablePoint();    // Deleting all van reachbale points

        MARKERS = [];   // making the markers array empty to store fresh ones.
        VAN_ROUTES = [];    // making the routes array empty to store fresh ones.
        VAN_REACHABLE_POINT = [];   // making the van reachable points array empty to store fresh ones.

        var polyCoordinates = [];   // to store the van reachable points to draw polygon
        disable_map_click_Listener = true;  // disabling map click
        disable_map_mousemove_Listener = true;  // disabling cursor changing on mouse move on map

        vanId = $('#vanId').val();  // getting van id.
        vanLat = EXISTING_COVERAGE_JSON.VanDefaultLatitude; // getting van latitude
        vanLng = EXISTING_COVERAGE_JSON.VanDefaultLongitude;    // getting van longitude
        var sourceVan = new google.maps.LatLng(vanLat, vanLng);    // ceating van lat-long object

        // Iterating thourough the Exiting Van coverage JSOn to plot the coverage for a partcular SLA.
        $.each(EXISTING_COVERAGE_JSON.Coverage, function (index, slaCoverage) {
            if (slaCoverage.SlaId == slaId) {
                polyCoordinates = [];   // making the polygon store empty

                var van_marker = putMarkerOnMap(map, '', vanLat, vanLng, '', vanId, vanImagePath, false, false, false); // putting Van on map
                VAN_MARKERS.push(van_marker);   // storing Van marker globally

                // Plotting VAN's reachable points
                $.each(slaCoverage.ListCoverage, function (index, point) {
                    // If lattitude is non null and non-empty then plotting starts
                    if ((point.VanPositionCoverageVanLatitude != '') && (point.VanPositionCoverageVanLatitude !== null)) {
                        var reachablePointId = point.VanPositionCoverageVanId + '_' + point.VanPositionCoverageId;  // creating Id for van reachbale points
                        // Plot van reachbale point
                        var rPoint = putMarkerOnMap(map, '', point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude, '', reachablePointId, vanReachablePointImagePath, false, false, false)
                        VAN_REACHABLE_POINT.push(rPoint);   // storing van reachable ponit globally

                        // Storing Point Cordinaates to draw a polygon
                        var reachablePoint = new google.maps.LatLng(point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude);
                        polyCoordinates.push(reachablePoint);

                        //latlngbounds.extend(reachablePoint);    // extending lat-long object

                        // craeting Route Object and storing that globally.
                        var routeObj = new Object({ 'routeId': reachablePointId, 'source': sourceVan, 'destination': reachablePoint });
                        //ROUTES.push(routeObj);
                        VAN_ROUTES.push(routeObj);
                    }
                });
                // Draw polygon and storing them globally
                var polygon = drawPolygon(polyCoordinates, vanId);
                POLYGONS.push(polygon);

                // Drawing path by sending route request effectively to Direction Service
                drawPathManager();
            }
        });
    }

    // If there is no exiting coverage for a van and covearge is designed for at least one sla then disable the coverage design now.
    if (!isCoverageExist && VAN_MARKERS.length > 0) {
        disable_map_click_Listener = true;  // disabling map click
        disable_map_mousemove_Listener = true;  // dsiable the cursor changing on map

        // If coverage for diffrent SLA selection is on then remove exiting coverage and draw a new one for new SLA time.
        if (enableDiffCoverage) {
            deleteVanMarkers(); // Deleting Van-Markers from the map.
            deleteAllRoutes();   // Deleting all the routes from the map
            deleteAllPolygons(); // Deleting all the polygons
            deleteAllVanReachablePoint();    // Deleting all van reachbale points

            MARKERS = [];   // making matrker array empty to store frresh ones
            VAN_REACHABLE_POINT = [];   // making van reachable points array empty to store new ones

            var van_marker = putMarkerOnMap(map, '', vanLat, vanLng, '', vanId, vanImagePath, false, false, false); // plotting new van
            VAN_MARKERS.push(van_marker);   // storing van marker globally
            generateVanCoverage(van_marker);    // now genearte coverage for van.
        }
        return;
    }



}


/**
* To populate SLA combobox.
* @method loadAllSla
* @for VanCoverageDesigner
*/
function loadAllSla() {
    SecurityToken = securityToken;
    utcMinutes = parseInt(UtcMinutes, 10);
    UserId = userId;

    $.ajax({
        type: "POST",
        url: WCFRESTURL.GetAllSLA,
        data: { Token: SecurityToken, UtcMinutes: utcMinutes, UserId: UserId },
        dataType: "json",
        success: function (data) {
            allSlaCount = data.length;
            var slaList = '';
            $.each(data, function (key, item) {
                slaList += '<tr><td><input type="button" id="' + item.Id + '" class="slaBtn" title="' + item.SlaTime + ' Minutes" value="' + item.SlaTime + '" onclick="return slaButtonClick(this)" /></td></tr>';

                //prepare get van coverage json
                prepare_GET_VAN_COVERAGE_JSON(item.Id, item.SlaTime);
            });
            $('#slaListBox').html(slaList);

            //console.log(GET_COVERAGE_JSON);
        },
        complete: function () {
            getExitingVanCoverage(vanId);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
}

/**
* To draw polygon on map with some lat-long
* @method drawPolygon
* @param {Array} polyCoordinates array of lat-long objects
* @param {String} polygonTitle polygon title
* @for VanCoverageDesigner
*/
function drawPolygon(polyCoordinates, polygonTitle) {
    // Construct the polygon.
    var polygon = new google.maps.Polygon({
        paths: polyCoordinates,
        strokeColor: '#AAA8A5',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#AAA8A5',
        fillOpacity: 0.35,
        title: polygonTitle
    });
    polygon.setMap(map);    // setting the polygon on map
    return polygon; // returing the creating polygon
}


/**
* To draw path between two points and setting am routeId for the same. (Blind Spot)
* @method drawPath
* @param {Object} sourcePoint source lat-long
* @param {Object} destinationPoint destination lat-long
* @param {Object} routeId route-id
* @for VanCoverageDesigner
*/
function drawPath(sourcePoint, destinationPoint, routeId) {
    if (!directionObj[routeId]) { directionObj[routeId] = []; }   // Storing directions

    // creting renderer options to draw path on map
    var rendererOptions = {
        preserveViewport: true,
        suppressMarkers: true,
        polylineOptions: { strokeColor: "#1b3f94" }
    };
    directionsRenderer = new google.maps.DirectionsRenderer(rendererOptions);   // creating renderer object
    directionsRenderer.setMap(map); // setting it on map
    directionObj[routeId].push(directionsRenderer);  // storing direction globally

    // craeting path request between two points
    var request = {
        origin: sourcePoint,
        destination: destinationPoint,
        travelMode: google.maps.TravelMode.DRIVING
    };
    // Route the directions and pass the response to a
    // function to create markers for each step.
    directionService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(response);
        }
    });
}


/**
* To manage drawing paths on map at a time interval (Blind Spot)
* @method drawPathManagerForMovedVan
* @for VanCoverageDesigner
*/
function drawPathManager() {
    $("#div_load").show();  // showing loading
    var maxTime = 0;    // intializing maximum time

    // iterating through global route array.
    $.each(VAN_ROUTES, function (index, route) {
        setTimeout(function () { drawPath(route.source, route.destination, route.routeId); }, ((index + 1) * 600));  // drawing path at an interval
        maxTime = (index + 1) * 600;    // inceasing loading time
    });

    disable_map_click_Listener = true;
    disable_map_mousemove_Listener = true;

    setTimeout(function () {
        $("#div_load").hide();  // hiding loading
        // Fitting all the markers on map area present on screen
        map.fitBounds(latlngbounds);
    }, (maxTime + 500));
}



/**
* To get circular points at a distance and at an angle.
* @method getCoverageForVan
* @param {Double} newLatOfVan marker's new lattitude
* @param {Double} newLongOfVan marker's new longitude
* @param {Int} slaTimeInMin SLA time in minutes
* @param {Int} minRadius minimum radius
* @for VanCoverageDesigner
*/
function getCoverageForVan(newLatOfVan, newLongOfVan, slaTimeInMin) {
    var vanLocation = new google.maps.LatLng(newLatOfVan, newLongOfVan);
    minRadius = radiusAccToSlaObj[slaTimeInMin];

    var radiusArray = [];
    radiusArray.push(minRadius);
    radiusArray.push(minRadius + radiusIncrement);
    radiusArray.push(minRadius + (2 * radiusIncrement));
    radiusArray.push(minRadius + (3 * radiusIncrement));

    var points = [];
    for (var angle = 0; angle < 360; angle += pointAngle) {
        for (var i = 0; i < radiusArray.length; i++) {
            var point = vanLocation.destinationPoint(angle, radiusArray[i]);
            points.push(point);
        }
    }
    return points;
}



/**
* To get circular points at a distance and at an angle.
* @method getCoverageForVanStatic
* @param {Double} newLatOfVan marker's new lattitude
* @param {Double} newLongOfVan marker's new longitude
* @param {Int} slaTimeInMin SLA time in minutes
* @param {Int} minRadius minimum radius
* @for VanCoverageDesigner
*/
function getCoverageForVanStatic(newLatOfVan, newLongOfVan, slaTimeInMin) {
    var vanLocation = new google.maps.LatLng(newLatOfVan, newLongOfVan);
    minRadius = radiusAccToSlaObj[slaTimeInMin];

    var radiusArray = [];
    radiusArray.push(minRadius);

    var points = [];
    for (var angle = 0; angle < 360; angle += pointAngle) {
        for (var i = 0; i < radiusArray.length; i++) {
            var point = vanLocation.destinationPoint(angle, radiusArray[i]);
            points.push(point);
        }
    }
    return points;
}


/**
* To create Van Coverage JSON for a particular SLA and reachable Points.
* @method create_VAN_COVERAGE_JSON
* @param {Int} slaId SLA ID
* @param {Int} slaTimeInMin SLA Time (In minutes)
* @param {Array} reachablePoints Array contains lat-long objects.
* @for VanCoverageDesigner
*/
function create_VAN_COVERAGE_JSON(slaId, slaTimeInMin, reachablePoints) {
    // Taking temporary covearge JSON
    var temp_COVERAGE_JSON =
    {
        "SlaId": "",
        "SlaValue": null,
        "ListCoverage": [
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" }
        ]
    };

    //================ Design Coverage ======================
    temp_COVERAGE_JSON['SlaId'] = slaId;    // Binding SLA Id
    temp_COVERAGE_JSON['SlaValue'] = slaTimeInMin;  // Binding SLA Time
    // Binding reachable point's lat-long
    $.each(reachablePoints, function (index, item) {
        temp_COVERAGE_JSON['ListCoverage'][index]['VanPositionCoverageVanLatitude'] = item.lat();
        temp_COVERAGE_JSON['ListCoverage'][index]['VanPositionCoverageVanLongitude'] = item.lng();
    });
    // If main Coverage JSON is empty, then push the newly craeted JSON object to that, Else replace that with the existing object
    if (COVERAGE_JSON.length == 0) {
        COVERAGE_JSON.push(temp_COVERAGE_JSON);
    } else {
        for (var i = 0; i < COVERAGE_JSON.length; i++) {
            if (COVERAGE_JSON[i].SlaId == slaId) {
                COVERAGE_JSON.splice(i, 1);
                COVERAGE_JSON.push(temp_COVERAGE_JSON);
            } else {
                COVERAGE_JSON.push(temp_COVERAGE_JSON);
            }
        }
    }
    //================ Design Coverage ======================
}

/**
* To create Van Coverage JSON for a particular SLA to store exiting Covearge.
* @method prepare_GET_VAN_COVERAGE_JSON
* @param {Int} slaId SLA ID
* @param {Int} slaTimeInMin SLA Time (In minutes)
* @for VanCoverageDesigner
*/
function prepare_GET_VAN_COVERAGE_JSON(slaId, slaTimeInMin) {
    // Taking temporary covearge JSON
    var temp_COVERAGE_JSON =
    {
        "SlaId": "",
        "SlaValue": null,
        "ListCoverage": [
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" },
            { "VanPositionCoverageId": "", "VanPositionCoverageVanLatitude": "", "VanPositionCoverageVanLongitude": "" }
        ]
    };
    temp_COVERAGE_JSON['SlaId'] = slaId;    // Binding SLA Id
    temp_COVERAGE_JSON['SlaValue'] = slaTimeInMin;  // Binding SLA Time
    GET_COVERAGE_JSON.push(temp_COVERAGE_JSON); // Adding this newly created object to global JSON (which stores existing Coverage objects)
}



/**
* To generate van coverage for a marker
* @method generateVanCoverage
* @param {Object} marker marker object
* @for VanCoverageDesigner
*/
function generateVanCoverageStatic(marker) {
    //$("#div_load").show();  // showing loading
    var vanId = marker.id;  // getting van id
    //enableCoverageDesign = true; // Enabling Coverage design

    var newLatOfVan = marker.position.lat();    // getting new lat of marker
    var newLongOfVan = marker.position.lng();   // getting new long of marker

    // Getting Van reachable points at a given radius
    var final_vanReachablePoints = getCoverageForVanStatic(newLatOfVan, newLongOfVan, slaTimeInMin);
   
    //================== Design Coverage =====================
    var sourceVan = new google.maps.LatLng(newLatOfVan, newLongOfVan);  // craeting source van lat-long object
    var polyCoordinates = [];    // takign polygon lat-long array

    coverageDesiged = true; // Coverage is designed once for this van

    // Plotting VAN's reachable points
    $.each(final_vanReachablePoints, function (index, point) {
        //if ((typeof point === 'undefined') || (enableCoverageDesign == false)) {
        //    if (popTheVanOut && VAN_MARKERS.length > 0) {
        //        var currentVanMarker = VAN_MARKERS[VAN_MARKERS.length - 1];   // getting last van marker
        //        VAN_MARKERS.pop();   // poping out last van from global array
        //        currentVanMarker.setMap(null);  // removing that from map
        //        popTheVanOut = false;    // disabling poping the van out further
        //    }
        //    jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['no_response_google_error'], 'Message');

        //    //$("#div_load").hide();  // hiding the loading
        //    return;
        //};
        latlngbounds.extend(point); // extending lat-long object

        var reachablePointId = vanId + '_' + index;
        var rPoint = putMarkerOnMap(map, "", point.lat(), point.lng(), "", reachablePointId, vanReachablePointImagePath, false, false, false);
        VAN_REACHABLE_POINT.push(rPoint);

        // Storing Point Cordinaates to draw a polygon
        var reachablePoint = new google.maps.LatLng(point.lat(), point.lng());
        polyCoordinates.push(reachablePoint);

        // craeting Route Object and storing that globally.
        var routeObj = new Object({ 'routeId': reachablePointId, 'source': sourceVan, 'destination': reachablePoint });
        //ROUTES.push(routeObj);
        VAN_ROUTES.push(routeObj);
    });
    // Draw polygon and storing them globally
    var polygon = drawPolygon(polyCoordinates, vanId);
    POLYGONS.push(polygon);

    // Create JSON for all possible SLAs.
    create_VAN_COVERAGE_JSON(slaId, slaTimeInMin, final_vanReachablePoints);

    // Drawing path Van
    drawPathManager();
    enableDiffCoverage = true;  // enabling diff SLA click to design coverage

    return;
    //================== Design Coverage =====================
}

/**
* To generate van coverage for a marker
* @method generateVanCoverage
* @param {Object} marker marker object
* @for VanCoverageDesigner
*/
function generateVanCoverage(marker) {
    //$("#div_load").show();  // showing loading
    var vanId = marker.id;  // getting van id
    enableCoverageDesign = true; // Enabling Coverage design
    coverageDesiged = false;    // Coverage is not designed yet
    popTheVanOut = true; // enabling deleting the last van
    VAN_ROUTES = [];   // Making the Moved-Van-Routes array empty.

    var newLatOfVan = marker.position.lat();    // getting new lat of marker
    var newLongOfVan = marker.position.lng();   // getting new long of marker

    // Getting Van reachable points at a given radius
    var vanReachablePoints = getCoverageForVan(newLatOfVan, newLongOfVan, slaTimeInMin);
    var vanReachablePoints1 = [];
    var vanReachablePoints2 = [];
    var mid = parseInt(vanReachablePoints.length / 2);
    for (var i = 0; i < mid ; i++) {
        vanReachablePoints1.push(vanReachablePoints[i])
        vanReachablePoints2.push(vanReachablePoints[mid + i]);
    }
    //----------------------
    var final_vanReachablePoints = [];
    //================== Design Coverage =====================
    // Getting optimal reachable points for first 0 to 180 degrees
    setTimeout(function () {
        var request1 = {
            origins: [marker.position],
            destinations: vanReachablePoints1,
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }
        distanceMatrixService.getDistanceMatrix(request1, function (response, status) {
            if (status == google.maps.DistanceMatrixStatus.OK) {
                var result = response.rows[0].elements;
                var start = 1;
                var counter = 0;
                // getting optimal points for 0 to 180 degrees
                for (var index = 0; index < result.length; index++) {
                    if (typeof result[index].duration === 'undefined') {
                        //if (VAN_MARKERS.length > 0) {
                        //    var currentVanMarker = VAN_MARKERS[VAN_MARKERS.length - 1];   // getting last van marker
                        //    VAN_MARKERS.pop();   // poping out last van from global array
                        //    currentVanMarker.setMap(null);  // removing that from map
                        //    popTheVanOut = false;    // disabling poping the van out further
                        //}
                        //jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['no_response_google_error'], 'Message');

                        ////MAIN_EXCHANGE_JSON = temp_MAIN_EXCHANGE_JSON;
                        //COVERAGE_JSON = [];

                        generateVanCoverageStatic(marker);
                        enableCoverageDesign = false;    // disabling coverage design
                        //$("#div_load").hide();  // hiding loading
                        return;
                    };
                    var durationInMin = parseInt(result[index].duration.value / 60, 10);    // getting duration in minutes
                    counter++;
                    // getting optimal points for current SLA time
                    if ((durationInMin > (slaTimeInMin * coverageMultiplier)) || (counter == 4)) {
                        ((index - 1) == -1) ? final_vanReachablePoints.push(vanReachablePoints1[index]) : final_vanReachablePoints.push(vanReachablePoints1[index - 1]);
                        index = start * 4;
                        start++;
                        counter = 0;
                    }
                }
            }
        });
    }, 300);

    //--------------------------------
    // Getting optimal reachable points for 180 to 360 degrees
    setTimeout(function () {
        if (coverageDesiged) { return;}
        var request2 = {
            origins: [marker.position],
            destinations: vanReachablePoints2,
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }
        distanceMatrixService.getDistanceMatrix(request2, function (response, status) {
            if (status == google.maps.DistanceMatrixStatus.OK) {
                var result = response.rows[0].elements;
                var start = 1;
                var counter = 0;
                // getting optimal points
                for (var index = 0; index < result.length; index++) {
                    if ((typeof result[index].duration === 'undefined') && (enableCoverageDesign == true)) {
                        //if (popTheVanOut && VAN_MARKERS.length > 0) {
                        //    var currentVanMarker = VAN_MARKERS[VAN_MARKERS.length - 1];   // getting last van marker
                        //    VAN_MARKERS.pop();   // poping out last van from global array
                        //    currentVanMarker.setMap(null);  // removing that from map
                        //    popTheVanOut = false;    // disabling poping the van out further
                        //}
                        //jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['no_response_google_error'], 'Message');

                        ////MAIN_EXCHANGE_JSON = temp_MAIN_EXCHANGE_JSON;
                        //COVERAGE_JSON = [];

                        generateVanCoverageStatic(marker);
                        //$("#div_load").hide();  // hiding loading
                        return;
                    };
                    var durationInMin = parseInt(result[index].duration.value / 60, 10);    // getting duration in minutes
                    counter++;
                    // getting optimal points for current SLA time
                    if ((durationInMin > (slaTimeInMin * coverageMultiplier)) || (counter == 4)) {
                        ((index - 1) == -1) ? final_vanReachablePoints.push(vanReachablePoints2[index]) : final_vanReachablePoints.push(vanReachablePoints2[index - 1]);
                        index = start * 4;
                        start++;
                        counter = 0;
                    }
                }

                //--------------------Plotting van, its points and drawing paths and polygon------------------
                var sourceVan = new google.maps.LatLng(newLatOfVan, newLongOfVan);  // craeting source van lat-long object
                var polyCoordinates = [];    // takign polygon lat-long array

                // Plotting VAN's reachable points
                $.each(final_vanReachablePoints, function (index, point) {
                    if ((typeof point === 'undefined') || (enableCoverageDesign == false)) {
                        if (popTheVanOut && VAN_MARKERS.length > 0) {
                            var currentVanMarker = VAN_MARKERS[VAN_MARKERS.length - 1];   // getting last van marker
                            VAN_MARKERS.pop();   // poping out last van from global array
                            currentVanMarker.setMap(null);  // removing that from map
                            popTheVanOut = false;    // disabling poping the van out further
                        }
                        jAlert(EOS_VAN_COVERAGE_DESIGN_MSG['no_response_google_error'], 'Message');

                        //$("#div_load").hide();  // hiding the loading
                        return;
                    };
                    latlngbounds.extend(point); // extending lat-long object

                    var reachablePointId = vanId + '_' + index;
                    var rPoint = putMarkerOnMap(map, "", point.lat(), point.lng(), "", reachablePointId, vanReachablePointImagePath, false, false, false);
                    VAN_REACHABLE_POINT.push(rPoint);

                    // Storing Point Cordinaates to draw a polygon
                    var reachablePoint = new google.maps.LatLng(point.lat(), point.lng());
                    polyCoordinates.push(reachablePoint);

                    // craeting Route Object and storing that globally.
                    var routeObj = new Object({ 'routeId': reachablePointId, 'source': sourceVan, 'destination': reachablePoint });
                    //ROUTES.push(routeObj);
                    VAN_ROUTES.push(routeObj);
                });
                // Draw polygon and storing them globally
                var polygon = drawPolygon(polyCoordinates, vanId);
                POLYGONS.push(polygon);

                // Create JSON for all possible SLAs.
                create_VAN_COVERAGE_JSON(slaId, slaTimeInMin, final_vanReachablePoints);

                // Drawing path Van
                drawPathManager();
                enableDiffCoverage = true;  // enabling diff SLA click to design coverage

                return;
                //------------------------------------------------------------------------------
            }
        });
    }, 1000);
    //================== Design Coverage =====================
}



/**
* To put a marker on map with supplied information. (Blind Spot)
* @method putMarkerOnMap
* @param {Object} map map object
* @param {String} markerInfoWindowContent info-window html string
* @param {Object} markerLat marker's lat
* @param {Object} markerLong marker's long
* @param {Object} markerTitle marker's title
* @param {Object} markerId marker's id
* @param {Object} markerImage marker's icon image
* @param {Object} isDraggable true if marker is draggable
* @param {Object} setMapCenter true if marker click will center the map
* @param {Object} openInfoWindow true if info window should open
* @for VanCoverageDesigner
*/
function putMarkerOnMap(map, markerInfoWindowContent, markerLat, markerLong, markerTitle, markerId, markerImage, isDraggable, setMapCenter, openInfoWindow) {
    var markerLatlng = new google.maps.LatLng(markerLat, markerLong);   // creating lat-long object
    var infowindow = new google.maps.InfoWindow({ content: markerInfoWindowContent });  // creating info-window object

    // creating marker object
    var marker = new google.maps.Marker({
        position: markerLatlng,
        map: map,
        title: markerTitle,
        icon: markerImage,
        draggable: isDraggable,
        id: markerId
    });
    return marker;
}




//===============================================================================
//===================== Google Map Initialization ===============================

/**
* To initialize the map and binding the event handlers
* @method initialize
* @for VanCoverageDesigner
*/
function initialize() {
    var myLatlng = new google.maps.LatLng(defaultLat, defaultLng);
    var mapOptions = {
        zoom: 7,
        center: myLatlng
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    //Initialize the Direction Service
    directionService = new google.maps.DirectionsService();
    // Creating an instance of Google Distance Matrix
    distanceMatrixService = new google.maps.DistanceMatrixService();

    //================ Map Events =========================
    google.maps.event.addListener(map, 'click', function (event) {
        if (disable_map_click_Listener) {
            return;
        }
        // if VAN is click on Map
        if (!disable_map_click_Listener) {
            vanId = $('#vanId').val();
            vanLat = event.latLng.lat();
            vanLng = event.latLng.lng();

            latlngbounds = new google.maps.LatLngBounds();  // Creating Lat-Long bounds instance to fit all the markers on the map
            latlngbounds.extend(event.latLng);    // extending lat-long object

            var van_marker = putMarkerOnMap(map, '', vanLat, vanLng, '', vanId, vanImagePath, false, false, false);
            VAN_MARKERS.push(van_marker);

            generateVanCoverage(van_marker);
        }
    });
    google.maps.event.addListener(map, 'mousemove', function (event) {
        if (disable_map_mousemove_Listener) {
            map.setOptions({ draggableCursor: '' });
        }
        if (!disable_map_mousemove_Listener) {
            map.setOptions({ draggableCursor: "url(" + vanToolImagePath + "), auto" })
        }
    });
    //============================================================
}
//===============================================================================
//===============================================================================

$(document).ready(function () {
    $('#coverageBtns').hide();  // hides coverage design buttons
    vanId = $('#vanId').val();  // getting VanId from hidden field

    $("#div_load").hide();  // hiding loading
    loadAllSla();   // Loading all SLA buttons
    setTimeout(function () { initialize(); }, 500); // Note::: Important: Intializing map after DOM has loaded in the popup
});