API Docs for:
Show:

File: TicketAdministration_Dealer\ticketAdministrationDealer.js

/*================================================================================================================\
+
+ Project     : GoData-VECV
+ Filename    : ticketAdministrationDealer.js
+ Module Name : Ticket
+ Purpose     : For ticketing              
+ Coded By    : Parul Gupta
+
+================================================================================================================*/


/**
* For ticketing
* @module Ticket
*/

/**
* This class contains functionality of Ticket administration for Dealer and his vans.
* @class TicketForDealer
* @constructor
*/

//Global Variables
var activeRequest, xhr_getTicketHistory, xhr_getTicketHistoryInterval, xhr_getCloseTickerDetails, xhr_getOpenTicketDetails, xhr_showActivity,
    xhr_showOpenActivity, xhr_addCustomer, xhr_addCustomerForExisting, xhr_getAllVans, xhr_addNewTicket;
var interval_id;
var ccplMap = null, markerImagePath = "../../Scripts/map_api/icons/red_blank.png",
    markerTransImgPath = "../../Scripts/map_api/icons/red_blink.gif",
    defaultLat = 26.912285124827,
    defaultLng = 75.7873203125,
   sourceMarker = '../../Scripts/map_api/icons/red_s.png', destinationMarker = '../../Scripts/map_api/icons/red_d.png';

var availableVansMarkers = '../../Content/css/images/avil-van.png';
var unavailableVansMarkers = '../../Content/css/images/unavl-van.png';
var dealerMarker = '../../Content/css/images/dealer-icon.png';
var breakdownLocationLatLng = "";

//initialize markers
var nearestVansDealersMarks = [];       //array of nearest vans and dealers markers
var detailsListOfVanDealer = [];        //array of objects of details of nearest vans and dealers 
var vanDealerLatLngArr = [];            //array of nearest vans and dealers lat lng
var ticketDetailsMarkerArray = [];

var _securityToken;
var _userId;
var marker, geoCoder, directionService;
var routeDirectionDisplay = "";
var routeDirectionsService = new google.maps.DirectionsService();
var routeDistanceService = new google.maps.DistanceMatrixService();

var displayDisplay = "";
var selectedTicket;
var assignedTo;

/**
* Load google map on page.
* @method initMap
* @for TicketForDealer
*/
function initMap(id) {
    var mapOptions = {
        center: new google.maps.LatLng(defaultLat, defaultLng),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    ccplMap = new google.maps.Map(document.getElementById(id), mapOptions);
    geoCoder = new google.maps.Geocoder();
}

/**
* Function call on click of Route label to show map
* @method onclickLabelRoute
* @for TicketForDealer
*/
function onclickLabelRoute() {
    //on click of label route
    $("#labelRoute").click(function () {
        // add selected class
        $('#labelActivity').removeClass("toolBtnActive");
        $('#labelRoute').addClass("toolBtnActive");
        $("#divMapContainer").show();
        $("#divActivity").css('display', 'none');
    });
}

/**
* Function call on click of Activity label to show ticket activity
* @method onclickLabelActivity
* @for TicketForDealer
*/
function onclickLabelActivity() {
    //on click of label Activitys
    $("#labelActivity").click(function () {
        // add selected class
        $('#labelRoute').removeClass("toolBtnActive");
        $('#labelActivity').addClass("toolBtnActive");
        $("#divActivity").css('display', 'inline-block');
        $("#divActivity").addClass("withtoolbar");
        $("#divMapContainer").hide();
        var ticketId;

        if ((document.getElementById('tableTicketHistory')) || (document.getElementById('tableCloseTicketHistory')) || ((document.getElementById('tableTicketHistory')) && (document.getElementById('tableCloseTicketHistory')))) {
            if (document.getElementById('tableTicketHistory')) {
                if ($("#tableTicketHistory > tbody > tr").hasClass('select')) {
                    ticketId = $("#tableTicketHistory > tbody > tr.select")[0].id;
                    //enable ticket status dropdown list and remarks text box and update button for open tickets list
                    $("#ddTicketStatus, #textBoxDescription").attr("disabled", false);
                    $("#button_submit").show();
                    if (xhr_showOpenActivity && xhr_showOpenActivity.readystate != 4) {
                       xhr_showOpenActivity.abort();
                     }
                    //get ticket activity details
                     xhr_showOpenActivity = $.ajax({
                       type: "POST",
                        url: "/TicketAdministration_Dealer/TicketAdministrationDealer_ShowTicketActivityOpenClose/",
                        data: { ticketId: ticketId, ticketStatus: 'open' },
                        success: function (data) {
                            $("#divActivity").html(data);
                           $("#ddTicketStatus, #textBoxDescription").attr("disabled", false);
                           $("#button_submit").show();
                       },
                       error: function (data) { }
                       });
                }
                else {
                    ticketId = $("#tableCloseTicketHistory > tbody > tr.select")[0].id;
                    //disable ticket status dropdown list and remarks text box and update button for close tickets list
                    $("#ddTicketStatus, #textBoxDescription").attr("disabled", true);
                    $("#button_submit").hide();
                    //get ticket activity details
                    if (xhr_showActivity && xhr_showActivity.readystate != 4) {
                        xhr_showActivity.abort();
                    }
                    xhr_showActivity = $.ajax({
                        type: "POST",
                        url: "/TicketAdministration_Dealer/TicketAdministrationDealer_ShowTicketActivityOpenClose/",
                        data: { ticketId: ticketId, ticketStatus: 'close' },
                        success: function (data) {
                            $("#divActivity").html(data);
                            $("#ddTicketStatus, #textBoxDescription, #ddReasonForOpportunityLost").attr("disabled", true);
                            $("#button_submit").hide();
                        },
                        error: function (data) { }
                    });
                }
            } else {
                ticketId = $("#tableCloseTicketHistory > tbody > tr.select")[0].id;
                $("#ddTicketStatus, #textBoxDescription").attr("disabled", true);
                $("#button_submit").hide();
                //get ticket activity details
                if (xhr_showActivity && xhr_showActivity.readystate != 4) {
                    xhr_showActivity.abort();
                }
                xhr_showActivity = $.ajax({
                    type: "POST",
                    url: "/TicketAdministration_Dealer/TicketAdministrationDealer_ShowTicketActivityOpenClose/",
                    data: { ticketId: ticketId, ticketStatus: 'close' },
                    success: function (data) {
                        $("#divActivity").html(data);
                        $("#ddTicketStatus, #textBoxDescription, #ddReasonForOpportunityLost").attr("disabled", true);
                        $("#button_submit").hide();
                    },
                    error: function (data) { }
                });
            }
        }
    });
}

/**
* Function to get open tickets history
* @method getOpenTicketsHistory
* @for TicketForDealer
*/
function getOpenTicketsHistory() {
    $("#tableTicketHistory > tbody > tr").click(function (e) {
        $("#div_loading").show();
        $("#labelRoute").trigger('click');
        $("#divActivity").html("");
        //Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
        if (displayDisplay) {
            //Remove direction display
            displayDisplay.setMap(null);
        }
        //Remove previous markers
        removeTicketDetailsMarkerArray();
        var ticketId = e.currentTarget.id;
        var assignedVanDealerLatLng, breakdownLocationLatLng;
        //remove select class
        $("#tableCloseTicketHistory > tbody > tr.select > td").removeClass("SelectRow");
        $("#tableCloseTicketHistory > tbody > tr").removeClass("select");
        $("#tableTicketHistory > tbody > tr.select > td").removeClass("SelectRow");
        $("#tableTicketHistory > tbody > tr").removeClass("select");
        $("#tableTicketHistory > tbody > tr[id=" + ticketId + "]").addClass('select');
        $("#tableTicketHistory > tbody > tr[id=" + ticketId + "].select > td").addClass('SelectRow');
        $("#divMap").css('width', '50%');
        $("#divMapContainer").addClass("withtoolbar");
        $("#divMapContainer").addClass("MapBox");
        $("#divTicketDetailTitle").css('display', 'inline-block');
        if (xhr_getOpenTicketDetails && xhr_getOpenTicketDetails.readystate != 4) {
            xhr_getOpenTicketDetails.abort();
        }
        //get ticket details
        xhr_getOpenTicketDetails = $.ajax({
            type: "POST",
            url: "/TicketAdministration_Dealer/TicketAdministrationDealer_GetTicketDetails/",
            data: { ticketId: ticketId, ticketStatus: 'open' },
            success: function (data) {
                //Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
                if (displayDisplay) {
                    //Remove direction display
                    displayDisplay.setMap(null);
                }
                //Remove previous markers
                removeTicketDetailsMarkerArray();
                $("#divDetail").html('');
                $("#divDetail").html(data);
                if (ccplMap) {
                    if ($("#labelRoute").hasClass('toolBtnActive') == true) {
                        var vanLat = $("#AssignedVanDealerLat").val();
                        var vanLng = $("#AssignedVanDealerLng").val();
                        var breakdownLat = $("#BreakdownLat").val();
                        var breakdownLng = $("#BreakdownLng").val();

                        if ((vanLat != "" && vanLat != null) && (vanLng != "" && vanLng != null) && (breakdownLat != "" && breakdownLat != null) && (breakdownLng != "" && breakdownLng != null)) {
                            assignedVanDealerLatLng = new google.maps.LatLng(vanLat, vanLng);
                            breakdownLocationLatLng = new google.maps.LatLng(breakdownLat, breakdownLng);
                            //Get address of the Lat Long click clicked
                            getReverseGeoCode(assignedVanDealerLatLng, function (data) {
                                //Here we got the address of the point clicked. Update this value to the form textbox.
                                var title = data;
                                //create marker at position
                                createMarkerVanDealer(assignedVanDealerLatLng, sourceMarker, title);
                                //Get address of the Lat Long click clicked
                                getReverseGeoCode(breakdownLocationLatLng, function (data) {
                                    //Here we got the address of the point clicked. Update this value to the form textbox.
                                    var title = data;
                                    //create marker at position
                                    createMarkerVanDealer(breakdownLocationLatLng, destinationMarker, title);
                                    //calculate route
                                    calcRoute(assignedVanDealerLatLng, breakdownLocationLatLng);
                                    //get map bound
                                    var _bounds = new google.maps.LatLngBounds();
                                    for (var count = 0; count < ticketDetailsMarkerArray.length; count++) {
                                        _bounds.extend(ticketDetailsMarkerArray[count].position);
                                    }
                                    ccplMap.fitBounds(_bounds);
                                });
                            });
                        } else {
                            $("#div_loading").hide();
                        }
                    }
                }
            },
            error: function (data) {
                console.log(data);
            }
        });
    });
}

/**
* Function to get close tickets history
* @method getCloseTicketsHistory
* @for TicketForDealer
*/
function getCloseTicketsHistory() {
    $("#tableCloseTicketHistory > tbody > tr").click(function (e) {
        $("#div_loading").show();
        $("#labelRoute").trigger('click');
        $("#divActivity").html("");
        //Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
        if (displayDisplay) {
            //Remove direction display
            displayDisplay.setMap(null);
        }
        //Remove previous markers
        removeTicketDetailsMarkerArray();
        var ticketId = e.currentTarget.id;
        var assignedVanDealerLatLng, breakdownLocationLatLng;
        //remove select class
        $("#tableTicketHistory > tbody > tr.select > td").removeClass("SelectRow");
        $("#tableTicketHistory > tbody > tr").removeClass("select");
        $("#tableCloseTicketHistory > tbody > tr.select > td").removeClass("SelectRow");
        $("#tableCloseTicketHistory > tbody > tr").removeClass("select");
        $("#tableCloseTicketHistory > tbody > tr[id=" + ticketId + "]").addClass('select');
        $("#tableCloseTicketHistory > tbody > tr[id=" + ticketId + "].select > td").addClass('SelectRow');
        $("#divMap").css('width', '50%');
        $("#divTicketDetailTitle").css('display', 'inline-block');
        if (xhr_getCloseTickerDetails && xhr_getCloseTickerDetails.readystate != 4) {
            xhr_getCloseTickerDetails.abort();
        }
        xhr_getCloseTickerDetails = $.ajax({
            type: "POST",
            url: "/TicketAdministration_Dealer/TicketAdministrationDealer_GetTicketDetails/",
            data: { ticketId: ticketId, ticketStatus: 'close' },
            success: function (data) {
                //Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
                if (displayDisplay) {
                    //Remove direction display
                    displayDisplay.setMap(null);
                }
                //Remove previous markers
                removeTicketDetailsMarkerArray();
                $("#divDetail").html('');
                $("#divDetail").html(data);

                if (ccplMap) {
                    if ($("#labelRoute").hasClass('toolBtnActive') == true) {
                        var vanLat = $("#AssignedVanDealerLat").val();
                        var vanLng = $("#AssignedVanDealerLng").val();
                        var breakdownLat = $("#BreakdownLat").val();
                        var breakdownLng = $("#BreakdownLng").val();

                        if ((vanLat != "" && vanLat != null) && (vanLng != "" && vanLng != null) && (breakdownLat != "" && breakdownLat != null) && (breakdownLng != "" && breakdownLng != null)) {
                            assignedVanDealerLatLng = new google.maps.LatLng(vanLat, vanLng);
                            breakdownLocationLatLng = new google.maps.LatLng(breakdownLat, breakdownLng);
                            //Get address of the Lat Long click clicked
                            getReverseGeoCode(assignedVanDealerLatLng, function (data) {
                                //Here we got the address of the point clicked. Update this value to the form textbox.
                                var title = data;
                                //create marker at position
                                createMarkerVanDealer(assignedVanDealerLatLng, sourceMarker, title);
                                //Get address of the Lat Long click clicked
                                getReverseGeoCode(breakdownLocationLatLng, function (data) {
                                    //Here we got the address of the point clicked. Update this value to the form textbox.
                                    var title = data;
                                    //create marker at position
                                    createMarkerVanDealer(breakdownLocationLatLng, destinationMarker, title);
                                    var _bounds = new google.maps.LatLngBounds();
                                   // console.log(ticketDetailsMarkerArray);
                                    for (var count = 0; count < ticketDetailsMarkerArray.length; count++) {
                                        _bounds.extend(ticketDetailsMarkerArray[count].position);
                                    }
                                    ccplMap.fitBounds(_bounds);
                                    //calculate route
                                    calcRoute(assignedVanDealerLatLng, breakdownLocationLatLng);
                                });
                            });
                        } else {
                            $("#div_loading").hide();
                        }
                    }
                }
            },
            error: function (data) {
                console.log(data);
            }
        });
    });
}

/**
* This fn return selected tab id.
* @method getSelectedTab
* @for TicketForDealer
*/
function getSelectedTab() {
    'use strict';
    var selectedTab;
    selectedTab = $(".tabs").find('ul > li.ActiveTab')[0].id;
    return selectedTab;
}

/**
* This fn get history of ticket
* @method getTicketsHistory
* @param {string} controller Controller name 
* @param {string} assignedToType Type to which, Ticket is assigned
* @param {string} divId HTML id of div
* @for TicketForDealer
*/
function getTicketsHistory(controller, assignedToType, divId) {
    'use strict';
    // check request already exist or not.
    if (xhr_getTicketHistory && xhr_getTicketHistory.readystate != 4) {
        xhr_getTicketHistory.abort();
    }
    xhr_getTicketHistory = $.post("/TicketAdministration_Dealer/" + controller + "/", { assignedToType: assignedToType }, function (data) {
        $('#divMyTickets, #divMyVansTickets').html('');
        $('#' + divId).html(data);
        $('#' + divId).show();
        if (!selectedTicket) {
            if (document.getElementById('tableTicketHistory') != null) {
                $("#tableTicketHistory > tbody > tr").first().trigger('click');
                $("#li_Activity").show();
            } else if (document.getElementById('tableCloseTicketHistory') != null) {
                $("#tableCloseTicketHistory > tbody > tr").first().trigger('click');
                $("#li_Activity").show();
            } else {
                $('#' + divId).html("<div><span>No open / close tickets are available !!</span></div>")
                $("#li_Activity").hide();
                $("#divActivity").hide();
                $("#labelRoute").trigger('click');
                if (displayDisplay) {
                    //Remove direction display
                    displayDisplay.setMap(null);

                    //Remove previous markers
                    removeTicketDetailsMarkerArray();
                }
                $("#divDetail").html('');
            }
        }
        else {
            $("#tableTicketHistory > tbody > tr[id='" + selectedTicket + "']").trigger('click');
            selectedTicket = "";
        }
    });
}

/**
* This fn show ticket history
* @method showTicketHistory
* @for TicketForDealer
*/
function showTicketHistory() {
    // get selected tab id.
    var tabId;
    tabId = getSelectedTab();
    if (tabId == "tabMyTickets") {
        getTicketsHistory("TicketAdministrationDealer_GetTicketHistory", "dealer", "divMyTickets");
    }
    else {
        getTicketsHistory("TicketAdministrationDealer_GetTicketHistory", "van", "divMyVansTickets");
    }
}

/**
* Maintain tab functionality. show particular div based on the tab id.
* @method graphicalTabAction
* @for TicketForDealer
*/
function graphicalTabAction() {
    'use strict';
    $(".divContent").hide();
    $("#tabGroup li").removeClass("ActiveTab");
    $('#tabGroup li').click(function (e) {
        e.stopPropagation();
        var target = $(this).attr("rel");
        $(".divContent").hide();
        $("#tabGroup li").removeClass("ActiveTab");
        $(".divContent[rel='" + target + "']").show();
        $("#tabGroup li[rel='" + target + "']").addClass("ActiveTab");
        showTicketHistory();
    });
}

/**
* Function to create markers on van's / dealer's location for ticket details 
* @method createMarkerVanDealer
* @param {String} position Position of van / dealer
* @param {String} icon Icon of placed marker
* @param {String} title Title of placed marker
* @for TicketForDealer
*/
function createMarkerVanDealer(position, icon, title) {
    //create a google marker with the given param
    var vanDealerMarker = new google.maps.Marker({
        position: position,
        map: ccplMap,
        icon: icon,
        title: title
    });
    //push marker to marksArray
    ticketDetailsMarkerArray.push(vanDealerMarker);
}

//------------------------------------------ calculate route -------------------------------------//

/**
* This fn removes all markers stored in ticketDetailsMarkerArray.
* @method removeTicketDetailsMarkerArray
* @for TicketForDealer
*/
function removeTicketDetailsMarkerArray() {
    //loop through arary
    for (var i = 0; i < ticketDetailsMarkerArray.length; i++) {
        //set marker map to null
        ticketDetailsMarkerArray[i].setMap(null);
    }
    //empty array
    ticketDetailsMarkerArray = [];
}

/**
* This fn calculates and draws the Route for the Ticket selected in the Ticket List using Google Direction API
* @method calcRoute
* @param {String} startLatLng Position of origin
* @param {String} endLatLng Position of destination
* @for TicketForDealer
*/
function calcRoute(startLatLng, endLatLng) {
    var merkerIcon;
    if (displayDisplay) {
        //Remove direction display
        displayDisplay.setMap(null);
    }
    var rendererOptions = {
        map: ccplMap,
        suppressMarkers: true,
        polylineOptions: { strokeColor: "#1b3f94" }
    }
    displayDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    //Make request obj to Direction Service API with starting and end LatLng
    var request = {
        origin: startLatLng,
        destination: endLatLng,
        travelMode: google.maps.TravelMode.DRIVING
    };
    //call Direction Service API with the reuqest obj
    routeDirectionsService.route(request, function (response, status) {
        //if status was a success
        if (status == google.maps.DirectionsStatus.OK) {
            displayDisplay.setOptions({ preserveViewport: true });
            //set Direction to the response
            displayDisplay.setDirections(response);
            var leg = response.routes[0].legs[0];
            $("#div_loading").hide();
        }
    });
}

//-------------------------------------------- end routing ---------------------------------------//

//======================================================================GeoCoding Functions=============================================================================//

/** 
* This function reverses the Lat Lng to Get the Approxmiate Address using the Google GeoCoding. Callback the result
* @method getReverseGeoCode
* @param {String} latLng lat lng of marker
* @param {String} callback function callback
* @for TicketForDealer
*/
function getReverseGeoCode(latLng, callback) {
    // Get google map LatLng object with the latLng in params
    var latlng = new google.maps.LatLng(latLng.lat(), latLng.lng());
    //Use google geocode library to get results
    geoCoder.geocode({ 'latLng': latlng }, function (results, status) {
        //If status is Ok
        if (status == google.maps.GeocoderStatus.OK) {
            //Find most intensive search result and callback it
            if (results[0]) {
                callback(results[0].formatted_address);
                //Else callback no result found
            } else {
                callback('No results found');
            }
        }
        return false;
    });
}
//========================== document ready function =========================//

$(document).ready(function () {
    initMap("divMapContainer");
    selectedTicket = getParameterByName("complaintNo");
    assignedTo = getParameterByName("assignedTo");
    graphicalTabAction();
    if (!selectedTicket) {
        $("#tabMyTickets").trigger('click');
    }
    else {
        if (assignedTo == "dealer") { $("#tabMyTickets").trigger('click'); } else { $("#tabMyVansTickets").trigger('click'); }
    }
});