EOS/Scripts/TicketAdministration_Dealer/DealerTicketAdministration.js
Nidhi Bhargava f0c1ab20e1 code push
2025-09-04 16:25:07 +05:30

3632 lines
138 KiB
JavaScript

/*================================================================================================================\
+
+ Project : GoData-VECV
+ Filename : TicketAdministration.js
+ Module Name : Ticket
+ Purpose : For ticketing
+ Coded By : Parul Gupta
+
+================================================================================================================*/
/**
* For ticketing
* @module Ticket
*/
/**
* This class contains functionality of Ticket administration for CCE.
* @class TicketAdministration
* @constructor
*/
var prefixOtherReasonDealerTicket = "Others##"; //prefix for other reason for dealer ticket
//Global Variables
var activeRequest, xhr_getTicketHistory, xhr_getTicketHistoryInterval, xhr_getCloseTickerDetails, xhr_getOpenTicketDetails, xhr_showActivity,
xhr_showOpenActivity, xhr_addCustomer, xhr_addCustomerForExisting, xhr_getAllVans, xhr_addNewTicket, xhr_CheckHistory, geoCodeState;
var searchBox = null;
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
//initialize markers
var sourceMarker = '../../Scripts/map_api/icons/red_s.png'; //marker for source
var destinationMarker = '../../Scripts/map_api/icons/red_d.png'; //marker for destination
var availableVansMarkers = '../../Content/css/images/avil-van.png'; //marker for available vans
var unavailableVansMarkers = '../../Content/css/images/unavl-van.png'; //marker for unavailable vans
var dealerMarker = '../../Content/css/images/dealer-icon.png'; //marker for dealers
//initialize markers arrays
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 placeLocationMarkerArray = []; //array of placed location markers
var ticketDetailsMarkerArray = []; //array of source and destination markers
var copyResulEls = []; //replica array of result vans and dealers array
var userLanguage = '',
sourceOfTollFree = '',
driverName = '',
driverContact = '',
state = '',
nearestCity = '',
locationBreakdown = '',
landmarkLocation = '',
routeId = '',
loadCarryingType = '',
vehicleDirection = '',
vehicleTravelledDistance = '',
warranty = '',
problemnature = '',
breakdownLocationLat = '',
breakdownLocationLng = '',
breakdownLattitudeLongitude = '';
var _securityToken, editTicketFeedback;
var _userId;
var marker, geoCoder, directionService;
var breakdownLocationLatLng = "";
var routeDirectionDisplay = "";
var routeDirectionsService = new google.maps.DirectionsService(); //direction google map api
//var routeDistanceService = new google.maps.DistanceMatrixService(); //distance google map api
var displayDisplay = ""; //route direction display
var displayHighway = ""; //highway display
//Google Distance MAtrix Service API
var service = new google.maps.DistanceMatrixService();
var selectedTicket, selectedVehicle, selectedKamTicket, selectedKamNotification, saveTicketsList;
var globalHostAddress = document.location.origin + "/";
/**
* Load google map on page.
* @method initMap
* @param {String} id HTML element id where map is loaded.
* @for TicketAdministration
*/
function initMap(id) {
var mapOptions = {
center: new google.maps.LatLng(defaultLat, defaultLng),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//initialize map
ccplMap = new google.maps.Map(document.getElementById(id), mapOptions);
//initialize geo coder to get address from lat lng
geoCoder = new google.maps.Geocoder();
//initialize geo coder to get address from lat lng
// geoCoder = new google.maps.Geocoder();
// Create the search box and link it to the UI element.
//var input = /** @type {HTMLInputElement} */(
// document.getElementById('searchLocationTool'));
//ccplMap.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
//searchBox = new google.maps.places.SearchBox(
// /** @type {HTMLInputElement} */(input));
////initialize search places
//placeLocationOnMap();
}
//initialize infowindow
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(50, 50)
});
// created google search box by google prediction api
function onGoogleSearch() {
// reset search box and sugesstion list div
$("#sugList-holder").css('visibility', 'hidden');
$("#sugList").html("");
// function on search box.
$("#searchLocationTool").keydown(function (e) {
// up key
if (e.keyCode == 38) {
var currEle = $('#sugList li.key-highlight');
$(currEle).removeClass("key-highlight");
if ($(currEle).index() < 1) {
$('#sugList li:last').addClass("key-highlight");
}
else {
$(currEle).prev().addClass("key-highlight");
}
}
// down key
else if (e.keyCode == 40) {
var currEle = $('#sugList li.key-highlight');
$(currEle).removeClass("key-highlight");
if ($(currEle).index() > 3) {
$('#sugList li:first').addClass("key-highlight");
}
else {
$(currEle).next().addClass("key-highlight");
}
}
// enter key
else if (e.keyCode == 13) {
var currEle = $('#sugList li.key-highlight')[0];
var placeId = $(currEle).attr("placeid");
var selLoc = $(currEle).attr("location");
drawMarker(placeId, selLoc);
$("#sugList").html("");
}
else {
var displaySuggestions = function (predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
return;
}
predictions.forEach(function (prediction) {
var loc = prediction.description.split(' ').join('_');
var str = '<li class="list-item" location=' + loc + ' placeid=' + prediction.place_id + ' onclick= drawMarker("' + prediction.place_id + '","' + loc + '")> <i></i> &nbsp;' + prediction.description + '</li>';
$('#sugList').append(str);
//console.log($('#sugList'));
});
$("#sugList").css('visibility', 'visible');
$("#sugList li:first").addClass("key-highlight");
};
var stxt = $("#searchLocationTool").val();
//console.log(stxt);
if (stxt.length <= 1) {
//$("#sugList-holder").css('visibility', 'hidden');
$("#sugList").html("");
}
if (stxt.length > 1) {
if (stxt.length % 2 == 0) {
console.log("in googel srch stxt= ", stxt)
$("#sugList").html("");
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({
input: stxt
// types: address
}, displaySuggestions);
}
}
}
});
}
// place the marker by suggestion.
function drawMarker(placeId, selectedLoc) {
$("#searchLocationTool").val(selectedLoc.split('_').join(' '));
//infoWindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(ccplMap);
service.getDetails({
placeId: placeId,
fields: ["name", "address_component", "formatted_address", "geometry.location"]
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
removePlaceLocationMarkerArray();
//remove direction path amd markers
if (displayDisplay) {
//Remove previous markers
removeTicketDetailsMarkerArray();
//Remove direction display
displayDisplay.setMap(null);
}
//remove breakdown location marker
if (marker) {
marker.setMap(null);
marker = "";
}
// Address cration
//console.log(result);
var bounds = new google.maps.LatLngBounds();
// Create a marker for each place.
var markerLocation = new google.maps.Marker({
map: ccplMap,
place: {
placeId: placeId,
location: result.geometry.location
},
title: result.formatted_address,
// position: places[0].geometry.location
});
breakdownLocationLatLng = markerLocation.place.location;
placeLocationMarkerArray.push(markerLocation);
bounds.extend(result.geometry.location);
$("#eos_exact_location").val("");
$("#eos_exact_location").val($("#searchLocationTool").val());
ccplMap.fitBounds(bounds);
$("#sugList").html("").css('visibility', 'hidden');
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
//google.maps.event.addListener(ccplMap, 'bounds_changed', function () {
// var bounds = ccplMap.getBounds();
// searchBox.setBounds(bounds);
//});
//ccplMap.setCenter(marker.getPosition());
// var address = result.adr_address;
// var newAddr = address.split("</span>,");
// infoWindow.setContent(result.name + "<br>" + newAddr[0] + "<br>" + newAddr[1] + "<br>" + newAddr[2]);
//google.maps.event.addListener(infoWindow, 'domready', function () {
// map.setCenter(marker.getPosition());
//});
//infoWindow.open(map, marker);
});
}
//=================================== search places text box ================================//
/**
* function to remove place location markers.
* @method removePlaceLocationMarkerArray
* @for TicketAdministration
*/
function removePlaceLocationMarkerArray() {
for (var i = 0, placeMarker; placeMarker = placeLocationMarkerArray[i]; i++) {
placeMarker.setMap(null);
}
// For each place, get the icon, place name, and location.
placeLocationMarkerArray = [];
}
/**
* Function to search location using search places text box google map api.
* @method placeLocationOnMap
* @for TicketAdministration
*/
function placeLocationOnMap() {
//search location on map
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0 || places.length % 2 == 0) {
return;
}
removePlaceLocationMarkerArray();
//remove direction path amd markers
if (displayDisplay) {
//Remove previous markers
removeTicketDetailsMarkerArray();
//Remove direction display
displayDisplay.setMap(null);
}
//remove breakdown location marker
if (marker) {
marker.setMap(null);
marker = "";
}
var bounds = new google.maps.LatLngBounds();
// Create a marker for each place.
var markerLocation = new google.maps.Marker({
map: ccplMap,
title: places[0].name,
position: places[0].geometry.location
});
// console.log(markerLocation);
breakdownLocationLatLng = markerLocation.position;
placeLocationMarkerArray.push(markerLocation);
bounds.extend(places[0].geometry.location);
$("#eos_exact_location").val("");
$("#eos_exact_location").val($("#searchLocationTool").val());
ccplMap.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(ccplMap, 'bounds_changed', function () {
var bounds = ccplMap.getBounds();
searchBox.setBounds(bounds);
});
}
//================================== end of search place locations =================================//
/**
* Get Check History Form view
* @method viewCheckHistory
* @for TicketAdministration
*/
function viewCheckHistory() {
//Remove Source Destination Direction Display if visible
//if (displayDisplay) {
// //Remove direction display
// displayDisplay.setMap(null);
//}
//stopIntervalRefreshTicketList();
if (selectedTicket != "") {
selectedTicket = "";
}
//Remove previous markers if any present
removeTicketDetailsMarkerArray();
//add active class to selected tab
$("#tabCheckHistory").addClass('ActiveTab');
$("#divMap").css('width', '75%');
$("#divTicketDetailTitle").hide();
$("#divActivity").hide();
$("#divPaymentDeatils").hide();
$("#divAddPaymentDeatils").hide();
$("#divFeedback").hide();
$("#divMapContainer").hide();
$("#divStaticMapContainer").show();
//drawSticeMap("staticMapImgUrl", "1000", "800")
//drawSticeMapForDelaerTicketAdministration("staticMapImgUrl", "1000", "800")
$("#searchLocationTool").hide();
$('#labelActivity').removeClass("toolBtnActive");
$('#labelFeedback').removeClass("toolBtnActive");
$('#labelRoute').removeClass("toolBtnActive");
$('#labelpayment').removeClass("toolBtnActive");
$('#divPaymentDeatils').hide();
$("#divAddPaymentDeatils").hide();
//send ajax request
if (xhr_CheckHistory && xhr_CheckHistory.readystate != 4) {
xhr_CheckHistory.abort();
}
xhr_CheckHistory = $.ajax({
type: "GET",
url: "/Ticket/TicketAdministration_CheckHistory/",
success: function (data) {
$("#divCheckHistory").html(data);
$("#divMapDetail").addClass("display_none");
$("#divMapContainer,#divStaticMapContainer").removeClass("withtoolbar");
$("#divMapContainer,#divStaticMapContainer").removeClass("MapBox");
},
error: function (data) {
console.log(data);
}
});
}
/**
* Function call on click of Route label to show map
* @method onclickLabelRoute
* @for TicketAdministration
*/
//function onclickLabelRoute() {
// //on click of label route
// $("#labelRoute").click(function () {
// // add selected class
// $('#labelActivity').removeClass("toolBtnActive");
// $('#labelFeedback').removeClass("toolBtnActive");
// $('#labelRoute').addClass("toolBtnActive");
// $("#divStaticMapContainer").show();
// $("#divMapContainer").hide();
// $("#divFeedback").hide();
// $("#divActivity").css('display', 'none');
// });
//}
/**
* Function call on click of Activity label to show ticket activity
* @method onclickLabelActivity
* @for TicketAdministration
*/
//function onclickLabelActivity() {
// //on click of label Activities
// $("#labelActivity").click(function () {
// $("#divActivity").html('');
// // add selected class
// $('#labelRoute').removeClass("toolBtnActive");
// $('#labelFeedback').removeClass("toolBtnActive");
// $('#labelActivity').addClass("toolBtnActive");
// $("#divActivity").css('display', 'inline-block');
// $("#divActivity").addClass("withtoolbar");
// $("#divMapContainer,#divStaticMapContainer").hide();
// $("#divFeedback").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;
// //get ticket activity details
// if (xhr_showActivity && xhr_showActivity.readystate != 4) {
// xhr_showActivity.abort();
// }
// xhr_showActivity = $.ajax({
// type: "POST",
// url: "/Ticket/TicketAdministration_ShowTicketActivityOpenClose/",
// data: { ticketId: ticketId, ticketStatus: 'open' },
// success: function (data) {
// $("#divActivity").html(data);
// $("#ddTicketStatus, #textBoxDescription, #ddReasonForOpportunityLost, #ddReasonTypeForOpportunityLost#ddReasonForcloseTicketmorethan24Hrs").attr("disabled", false);
// $("#textBoxDescription").val("");
// if ($("#OdometerReading").val() == 0) {
// $("#OdometerReading").val("")
// } $("#button_submit").show();
// },
// error: function (data) { }
// });
// }
// else {
// ticketId = $("#tableCloseTicketHistory > tbody > tr.select")[0].id;
// //get ticket activity details
// if (xhr_showActivity && xhr_showActivity.readystate != 4) {
// xhr_showActivity.abort();
// }
// xhr_showActivity = $.ajax({
// type: "POST",
// url: "/Ticket/TicketAdministration_ShowTicketActivityOpenClose/",
// data: { ticketId: ticketId, ticketStatus: 'close' },
// success: function (data) {
// $("#divActivity").html(data);
// $("#ddTicketStatus, #textBoxDescription, #ddReasonForOpportunityLost, #ddReasonTypeForOpportunityLost,#ddReasonForcloseTicketmorethan24Hrs").attr("disabled", true);
// $("#button_submit").hide();
// },
// error: function (data) { }
// });
// }
// } else {
// ticketId = $("#tableCloseTicketHistory > tbody > tr.select")[0].id;
// //get ticket activity details
// if (xhr_showActivity && xhr_showActivity.readystate != 4) {
// xhr_showActivity.abort();
// }
// xhr_showActivity = $.ajax({
// type: "POST",
// url: "/Ticket/TicketAdministration_ShowTicketActivityOpenClose/",
// data: { ticketId: ticketId, ticketStatus: 'close' },
// success: function (data) {
// //console.log(data);
// $("#divActivity").html(data);
// $("#ddTicketStatus, #textBoxDescription, #ddReasonForOpportunityLost, #ddReasonTypeForOpportunityLost,#ddReasonForcloseTicketmorethan24Hrs").attr("disabled", true);
// $("#button_submit").hide();
// },
// error: function (data) { }
// });
// }
// }
// });
//}
/**
* Function call on click of Route label to show map
* @method onclickLabelRoute
* @for TicketAdministration
*/
function onclickLabelFeedback() {
//on click of label route
$("#labelFeedback").click(function () {
var selectTicketId;
var ticketCreationTime, isMoreThan24Hrs, isFeedBackDetails;
// add selected class
$('#labelActivity').removeClass("toolBtnActive");
$('#labelRoute').removeClass("toolBtnActive");
$('#labelFeedback').addClass("toolBtnActive");
$('#labelpayment').removeClass("toolBtnActive");
$('#divPaymentDeatils').hide();
$("#divAddPaymentDeatils").hide();
$("#divFeedback").show();
$("#divFeedback").addClass("withtoolbar");
$("#divMapContainer,#divStaticMapContainer").hide();
$("#divActivity").css('display', 'none');
showFeedback();
});
}
/**
* Function call on click of feedback label to show feedback form
* @method showFeedback
* @for TicketAdministration
*/
function showFeedback() {
var selectTicketId;
var ticketCreationTime, isMoreThan24Hrs, isFeedBackDetails;
if ($("#tableTicketHistory > tbody > tr.select")[0] != undefined) {
selectTicketId = $("#tableTicketHistory > tbody > tr.select")[0].id;
ticketCreationTime = document.getElementById(selectTicketId).getAttribute('data-ticketCreationTime');
isMoreThan24Hrs = parseFloat(document.getElementById(selectTicketId).getAttribute('data-reason24Hrs'), 10);
isFeedBackDetails = document.getElementById(selectTicketId).getAttribute('data-isFeedback');
}
else {
selectTicketId = $("#tableCloseTicketHistory > tbody > tr.select")[0].id;
ticketCreationTime = document.getElementById(selectTicketId).getAttribute('data-ticketCreationTime');
isMoreThan24Hrs = parseFloat(document.getElementById(selectTicketId).getAttribute('data-reason24Hrs'), 10);
isFeedBackDetails = document.getElementById(selectTicketId).getAttribute('data-isFeedback');
}
//console.log(selectTicketId);
$.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_Feedback/",
data: { selectTicketId: selectTicketId, ticketCreationTime: ticketCreationTime, isMoreThan24Hrs: isMoreThan24Hrs },
success: function (data) {
if (data) {
$("#divFeedback").html(data);
}
},
error: function (data) {
console.log(data);
}
});
}
/**
* Function call on click of back button
* @method onBackButtonClick
* @for TicketAdministration
*/
function onBackButtonClick() {
viewCheckHistory();
// ("#sugList-holder").css('visibility', 'hidden');
}
/**
* Function to get ticket history based on vehicle registration no., customer/owner mobile no. or ticket id/complaint no.
* @method getTicketHistory
* @for TicketAdministration
*/
function getTicketHistory() {
var registrationNo, mobileNo, complaintNo;
//registrationNo = $("#RegistrationNo").val();
mobileNo = ($("#MobileNo").val() == "" || typeof $("#MobileNo").val() == "undefined") ? "" : $("#MobileNo").val().trim();
if (selectedTicket) {
complaintNo = selectedTicket;
$("#tabCheckHistory").addClass('ActiveTab');
}
else {
complaintNo = ($("#ComplaintNo").val() == "" || typeof $("#ComplaintNo").val() == "undefined") ? "" : $("#ComplaintNo").val().trim();
}
if (selectedVehicle) {
registrationNo = selectedVehicle;
$("#tabCheckHistory").addClass('ActiveTab');
}
else {
registrationNo = ($("#RegistrationNo").val() == "" || typeof $("#RegistrationNo").val() == "undefined") ? "" : $("#RegistrationNo").val().trim();
}
//searching with new ticket id format
if (complaintNo.toLowerCase().trim().indexOf("ticketid") == -1) {
complaintNo = complaintNo.substr(6, (complaintNo.length - 6)).replace(/^0+/, '').trim();
}
if (xhr_getTicketHistory && xhr_getTicketHistory.readystate != 4) {
xhr_getTicketHistory.abort();
}
xhr_getTicketHistory = $.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_GetTicketHistory/",
data: { registrationNo: registrationNo, mobileNo: mobileNo, complaintNo: complaintNo },
success: function (data) {
if (data.fillFieldMesseage) {
jAlert(data.fillFieldMesseage, 'Message');
}
else {
$("#divCheckHistory").html("");
$("#divCheckHistory").html(data);
var searchedTicketId = $("#VComplaintNo").val();
var searchedRegistrationNo = $("#VRegistrationNo").val();
// console.log(searchedTicketId);
$('#labelRoute').addClass("toolBtnActive");
if (document.getElementById('tableTicketHistory')) { //if open tickets exist for entered vehicle registration no.
$("#divMap").css({ 'width': '50%', 'left': '25%', 'right': '25%' });
$("#divMapDetail").removeClass("display_none");
$("#divStaticMapContainer").addClass("withtoolbar");
$("#divStaticMapContainer").addClass("MapBox");
if (searchedTicketId != null && searchedTicketId != "") { //if redirected from open ticket report
var container = $('#divOpenCloseTickets'), scrollTo = $('#' + searchedTicketId);
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});
if ((editTicketFeedback == null || editTicketFeedback == "") && (selectedTicket == null || selectedTicket == "")) {
$("#" + searchedTicketId).trigger("click");
} else if (editTicketFeedback == null || editTicketFeedback == "") {
$("#" + searchedTicketId).trigger("click");
setTimeout(function () { $("#labelActivity").trigger("click"); }, 1000);
} else {
$("#" + searchedTicketId).trigger("click");
setTimeout(function () { $("#labelFeedback").trigger("click"); }, 1000);
}
} else { //else by default click on first row of open ticket table
$("#tableTicketHistory > tbody > tr:first").trigger("click");
}
} else if ((document.getElementById('tableCloseTicketHistory')) && (!document.getElementById('div_pendingTicketFound'))) { //if close tickets are exist
$("#divMapDetail").removeClass("display_none");
$("#divStaticMapContainer").addClass("withtoolbar");
$("#divStaticMapContainer").addClass("MapBox");
$("#divMap").css({ 'width': '50%', 'left': '25%', 'right': '25%' });
if (searchedTicketId != null && searchedTicketId != "") { //if redirected from close ticket report
var container = $('#divOpenCloseTickets'), scrollTo = $('#' + searchedTicketId);
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});
if ((editTicketFeedback == null || editTicketFeedback == "") && (selectedTicket == null || selectedTicket == "")) {
$("#" + searchedTicketId).trigger("click");
} else if (editTicketFeedback == null || editTicketFeedback == "") {
$("#" + searchedTicketId).trigger("click");
setTimeout(function () { $("#labelActivity").trigger("click"); }, 1000);
} else {
$("#" + searchedTicketId).trigger("click");
setTimeout(function () { $("#labelFeedback").trigger("click"); }, 1000);
}
} else if (selectedVehicle != null && selectedVehicle != "") { //if redirected from KAM open ticket notification
$("#div_loading").show();
addNewTicket();
setTimeout(function () { getKamOpenTicketDetails(selectedVehicle); }, 5000);
} else { //else by default click on first row of close ticket table
$("#tableCloseTicketHistory > tbody > tr:first").trigger("click");
}
} else if (document.getElementById('div_pendingTicketFound')) { //if pending tickets are exist
if (selectedVehicle != null && selectedVehicle != "" && (selectedTicketType != null && selectedTicketType != "")) { //if redirected from pending ticket report
assignPendingTicket();
} else if (document.getElementById('tableCloseTicketHistory')) { //if close tickets are also exist with pending tickets
$("#divMapDetail").removeClass("display_none");
$("#divStaticMapContainer").addClass("withtoolbar");
$("#divStaticMapContainer").addClass("MapBox");
$("#divMap").css({ 'width': '50%', 'left': '25%', 'right': '25%' });
if (searchedTicketId != null && searchedTicketId != "") { //if redirected from close ticket report
var container = $('#div_pendingTicketFound'), scrollTo = $('#' + searchedTicketId);
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});
if ((editTicketFeedback == null || editTicketFeedback == "") && (selectedTicket == null || selectedTicket == "")) {
$("#" + searchedTicketId).trigger("click");
} else if (editTicketFeedback == null || editTicketFeedback == "") {
$("#" + searchedTicketId).trigger("click");
setTimeout(function () { $("#labelActivity").trigger("click"); }, 1000);
} else {
$("#" + searchedTicketId).trigger("click");
setTimeout(function () { $("#labelFeedback").trigger("click"); }, 1000);
}
} else { //else by default click on first row of close ticket table
$("#tableCloseTicketHistory > tbody > tr:first").trigger("click");
}
} else { //else if no close ticket exist for the selected vehicle
$("#divMapDetail").addClass("display_none");
$("#divStaticMapContainer").removeClass("withtoolbar");
$("#divStaticMapContainer").removeClass("MapBox");
$("#divMap").removeClass("size50");
$("#divMap").css({ "width": "75%", "left": "25%", "right": "0%" });
}
} else { // if no close and open tickets available
if ((document.getElementById('divNoDataFound_CustomerHistory')) || (document.getElementById('divNoDataFound_TicketHistory')) || (document.getElementById('div_pendingTicketFound'))) {
if ((selectedVehicle != null && selectedVehicle != "") && (selectedTicketType == null || selectedTicketType == "")) {
$("#div_loading").show();
addNewTicket();
setTimeout(function () { getKamOpenTicketDetails(selectedVehicle); }, 5000);
} else if ((selectedVehicle != null && selectedVehicle != "") && (selectedTicketType != null && selectedTicketType != "")) {
assignPendingTicket();
}
}
}
}
selectedTicket = "";
editTicketFeedback = "";
selectedVehicle = "";
selectedTicketType = "";
},
complete: function () {
editTicketFeedback = "";
},
error: function (data) {
console.log(data);
}
});
}
/**
* Function to get close ticket details
* @method getCloseTicketDetails
* @for TicketAdministration
*/
function getCloseTicketDetails() {
$("#tableCloseTicketHistory > tbody > tr").click(function (e) {
$("#div_loading").show();
$("#labelRoute").trigger('click');
$("#listFeedback").show();
$("#divDetail").html('');
$("#divFeedback").html("");
$("#divActivity").html("");
//Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
//if (displayDisplay) {
// //Remove previous markers
// removeTicketDetailsMarkerArray();
// //Remove direction display
// displayDisplay.setMap(null);
//}
var assignedVanDealerLatLng, _breakdownLocationLatLng;
var ticketId = e.currentTarget.id;
var ticketStatus = document.getElementById(ticketId).getAttribute('data-ticketStatus');
var vRegistrationNo = $("#VRegistrationNo").val();
//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');
//call rest api
if (xhr_getCloseTickerDetails && xhr_getCloseTickerDetails.readystate != 4) {
xhr_getCloseTickerDetails.abort();
}
xhr_getCloseTickerDetails = $.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_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(data);
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);
assignedVanDealerLatLng = vanLat + "," + vanLng;
_breakdownLocationLatLng = breakdownLat + "," + breakdownLng;
drawStaticMap_MarkersPath("staticMapImgUrl", "700", "500", assignedVanDealerLatLng, _breakdownLocationLatLng)
//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, "", ccplMap, []);
// 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();
}
}
},
complete: function () {
$("#div_loading").hide();
$("#textBoxDescription").val("");
},
error: function (data) {
console.log(data);
}
});
});
}
/**
* Function to get open ticket details
* @method getTicketDetails
* @for TicketAdministration
*/
function getTicketDetails(tableId) {
$("#tableTicketHistory > tbody > tr").click(function (e) {
//Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
$("#div_loading").show();
$("#labelRoute").trigger('click');
$("#listFeedback").hide();
$("#divDetail").html('');
$("#divFeedback").html("");
$("#divActivity").html("");
//if (displayDisplay) {
// //Remove previous markers
// removeTicketDetailsMarkerArray();
// //Remove direction display
// displayDisplay.setMap(null);
//}
var assignedVanDealerLatLng, _breakdownLocationLatLng;
var ticketId = e.currentTarget.id;
var ticketStatus = document.getElementById(ticketId).getAttribute('data-ticketStatus');
var vRegistrationNo = $("#VRegistrationNo").val();
//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%');
$("#divStaticMapContainer").addClass("withtoolbar");
$("#divStaticMapContainer").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: "/Ticket/TicketAdministration_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(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 = vanLat + "," + vanLng;
_breakdownLocationLatLng = breakdownLat + "," + breakdownLng;
// drawStaticMap_MarkersPath("staticMapImgUrl", "700", "500", assignedVanDealerLatLng, _breakdownLocationLatLng)
// 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) {
// //console.log(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;
// //console.log(data);
// //create marker at position
// createMarkerVanDealer(_breakdownLocationLatLng, destinationMarker, title);
// //calculate route
// calcRoute(assignedVanDealerLatLng, _breakdownLocationLatLng, "", ccplMap, []);
// 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();
}
}
// }
},
complete: function () {
$("#div_loading").hide();
},
error: function (data) {
console.log(data);
}
});
});
}
/**
* Function to add new ticket
* @method addNewTicket
* @for TicketAdministration
*/
function addNewTicket() {
breakdownLocationLatLng = "";
var VRegistrationNo = $("#VRegistrationNo").val();
$("#searchLocationTool").attr('readonly', false);
$("#eos_exact_location, #nature_of_problem, #vehicle_direction, #vehicle_type_of_load, #breakdown_landmark, #searchLocationTool").val('');
$("#driver_name").val('-Select-');
getMobileNoCustomerWise();
getLanguageList("vehicle_owner_language"); //get languages list in drop down
getTollFreeSourceList("tollFreeNoSource"); //get sources list of toll free no. in drop down
getWarrentyAmcList("isVehicleInWarrentyOrAmc"); //get warrenty list in drop down
getStateList(); //get all states list in drop down
//LoadCityListOnStateChange();
getRoutesList(); // get all routes list in drop down
//get owner detailsLoadCityList(id)
$.getJSON("/Ticket_CustomerInventory/GetOwnerDetailsBasedOnMobilenNo/", { RegistrationNo: VRegistrationNo, OwnerMobileNo: "" }, function (result) {
//console.log(result);
if (result.CustomerOwnerDetails) {
var Details = result.CustomerOwnerDetails;
for (var count = 0; count < Details.length; count++) {
if (Details[count].CustomerVehicleIsOwner == true) {
$("#vehicle_owner_name").val(Details[count].CustomerCustomerName);
$("#vehicle_owner_contact_no").val(Details[count].CustomerMobileNumber1);
$("#vehicle_owner_location").val(Details[count].CustomerState);
$("#vehicle_owner_emailID").val(Details[count].CustomerEmailId);
$("#vehicle_owner_Address").val(Details[count].CustomerAddress);
$("#vehicle_owner_City").val(Details[count].CustomerCity);
}
}
}
});
//get vehicle details
$.getJSON("/Ticket_CustomerInventory/GetVehicleDetailsBasedOnRegistrationNo/", { RegistrationNo: VRegistrationNo }, function (result) {
if (result.VehicleDetails) {
var Details = result.VehicleDetails;
for (var count = 0; count < Details.length; count++) {
$("#vehicle_registration").val(Details[count].RegistrationNo);
$("#vehicle_numberPlate").val(Details[count].VehicleNumberPlate);
$("#vehicle_numberPlate").prop('title', Details[count].VehicleNumberPlate);
$("#vehicle_model").val(result.vehicleModelTaggingName);
$("#vehicle_model").prop('title', result.vehicleModelTaggingName);
$("#eos_VehicleType").val(Details[count].VehicleType);
$("#eos_VehicleInstallationDate").val(Details[count].VehicleInstallationDate);
$("#vehicle_product_varient").val(result.vehicleModelTagging);
//var VModel = $("#vehicle_model").val();
////get model tagging
//$.getJSON("/Ticket_CustomerInventory/GetVehicleModelTaggingBasedOnModelNo/", { ModelTypeId: VModel }, function (result) {
// if (result) {
// var ModelType = result.VehicleModelTagging;
// for (var count = 0; count < ModelType.length; count++) {
// $("#vehicle_product_varient").val(ModelType[0].VehicleTypeTagging);
// }
// }
//});
}
}
});
$("#Ticket_List").hide();
$("#divActivity").hide();
$("#divFeedback").hide();
$("#divPaymentDeatils").hide();
$("#divAddPaymentDeatils").hide();
$("#divStaticMapContainer").hide();
$("#divMapContainer").show();
$("#searchLocationTool").show();
$("#divCheckHistory, #divMapContainer").removeClass("withtoolbar");
$("#divMapContainer").removeClass("MapBox");
$("#divMapDetail").addClass("display_none");
$("#Tracker_form, #Tracker_from_BtnWrp").removeClass("display_none");
$("#divInnerWindow").css('width', '25%');
$("#divMap").removeClass("size50");
$("#divMap").css({ "width": "75%", "left": "25%", "right": "0%" });
$("#divTicketDetailTitle").css('display', 'none');
bindClickEventToMap(); // bind click event on map to select breakdown location
//placeLocationOnMap();
if (displayDisplay) {
//Remove previous markers
removeTicketDetailsMarkerArray();
//Remove direction display
displayDisplay.setMap(null);
}
//showing search box
$("#sugList-holder").css('visibility', 'visible');
$("#sugList").html("");
}
/**
* Function to bind all states in drop down
* @method getStateList
* @for TicketAdministration
*/
function getStateList() {
$.ajax({
type: "GET",
url: "/Ticket/GetAllStateList/",
success: function (data) {
// empty City dropdown
if ($("#eos_state").data("kendoMultiSelect") != undefined) {
var multiselect = $("#eos_state").data("kendoMultiSelect");
multiselect.destroy();
}
// add data to dropdown.
if (data.list) {
for (var counter = 0; counter < data.list.length; counter++) {
$("#eos_state").append(
$('<option></option>').val(data.list[counter].Value).html(data.list[counter].Text));
}
}
},
complete: function () {
var optional = $("#eos_state").kendoMultiSelect({
// autoClose: false,
maxSelectedItems: 2
}).data("kendoMultiSelect");
},
error: function (data) {
console.log(data);
}
});
}
/**
* Function to add new customer
* @method LoadCityList
* @param {string} ddlId HTML id of drop down list of city
* @param {string} cityValue HTML value of drop down list selected item of city
* @for TicketAdministration
*/
function LoadCityList(ddlId, cityValue) {
var DdlId = ddlId;
var ddCityId;
if (DdlId == "ddOwnerState") {
ddCityId = "#ddOwnerCity";
$("#customerOwnerStateName").val($('#ddOwnerState').find('option:selected').text());
}
else {
ddCityId = "#ddCustomerCity";
$("#customerStateName").val($('#ddCustomerState').find('option:selected').text());
}
var stateVal;
stateVal = $("#" + DdlId).val();
if (stateVal != "-Select-") {
stateVal = $("#" + DdlId).val();
}
else {
stateVal = 0;
}
if (stateVal != "") {
$.ajax({
type: "GET",
url: "/Ticket_CustomerInventory/showCityStateWise/",
data: { stateVal: stateVal },
success: function (data) {
// empty City dropdown
$(ddCityId).text("");
// by default add select text.
$(ddCityId).append($('<option></option>').val("").html("-Select-"));
// add data to dropdown.
if (data.list) {
for (var counter = 0; counter < data.list.length; counter++) {
$(ddCityId).append(
$('<option></option>').val(data.list[counter].Value).html(data.list[counter].Text));
}
}
},
complete: function () {
if (cityValue) {
$(ddCityId).val(cityValue);
}
},
error: function (data) {
console.log(data);
}
});
}
}
/**
* Function to bind all routes in drop down
* @method getRoutesList
* @for TicketAdministration
*/
function getRoutesList() {
$.ajax({
type: "GET",
url: "/Ticket/GetAllRoutesList/",
success: function (data) {
// empty routes dropdown
$("#routes").text("");
// by default add select text.
$("#routes").append($('<option></option>').val("").html("-Select-"));
// add data to dropdown.
if (data.list) {
for (var counter = 0; counter < data.list.length; counter++) {
$("#routes").append(
$('<option></option>').val(data.list[counter].Value).html(data.list[counter].Text));
}
}
},
error: function (data) {
console.log(data);
}
});
}
/**
* Function call onclick cancel button
* @method btnCancel
* @for TicketAdministration
*/
function btnCancel() {
onClickAssignTicketOrCancel();
if ($("#tableTicketHistory > tbody > tr.select")[0] != undefined) {
$("#tableTicketHistory > tbody > tr.select").trigger("click");
} else if ($("#tableCloseTicketHistory > tbody > tr.select")[0] != undefined) {
$("#tableCloseTicketHistory > tbody > tr.select").trigger("click");
} else {
$("#divMapContainer,#divStaticMapContainer").removeClass("MapBox");
$("#divMapContainer,#divStaticMapContainer").removeClass("withtoolbar");
$("#divTicketDetailTitle").hide();
$("#divMap").addClass("size50");
$("#divMap").css({ 'width': '75%', 'left': '25%' });
}
$("#sugList-holder").css('visibility', 'hidden');
}
/**
* Function call onclick of cancel or assign ticket
* @method onClickAssignTicketOrCancel
* @for TicketAdministration
*/
function onClickAssignTicketOrCancel() {
$('#labelRoute').addClass("toolBtnActive");
$('#labelFeedback').removeClass("toolBtnActive");
$('#labelActivity').removeClass("toolBtnActive");
$('#labelpayment').removeClass("toolBtnActive");
$('#divPaymentDeatils').hide();
$("#Ticket_List").show();
$("#searchLocationTool").hide();
$("#divFeedback").hide();
$("#divPaymentDeatils").hide();
$("#divAddPaymentDeatils").hide();
$("#divActivity").css('display', 'none');
$("#divCheckHistory").addClass("withtoolbar");
$("#divMapDetail").removeClass("display_none");
$("#divMapContainer").addClass("withtoolbar");
$("#divMapContainer").addClass("MapBox");
$("#Tracker_form, #Tracker_from_BtnWrp").addClass("display_none");
$("#divInnerWindow").css('width', '25%');
$("#divMap").addClass("size50");
$("#divMap").css({ 'width': '50%', 'left': '25%', 'right': '25%', 'height': '' });
$("#divVanDealerList").hide();
$("#divTicketDetailTitle").css('display', 'inline-block');
//Remove Source Destination Direction Display if visible
if (displayDisplay) {
//Remove direction display
displayDisplay.setMap(null);
}
//Remove highway Display if visible
if (displayHighway) {
//Remove direction display
displayHighway.setMap(null);
}
if (nearestVansDealersMarks.length > 0) {
//loop through arary
for (var i = 0; i < nearestVansDealersMarks.length; i++) {
//set marker map to null
nearestVansDealersMarks[i].setMap(null);
}
//empty array
nearestVansDealersMarks = [];
}
//loop through arary
for (var i = 0; i < ticketDetailsMarkerArray.length; i++) {
//set marker map to null
ticketDetailsMarkerArray[i].setMap(null);
}
//empty array
ticketDetailsMarkerArray = [];
removeClickEventToMap();
removePlaceLocationMarkerArray();
}
/**
* Function to add new customer
* @method addNewCustomer
* @for TicketAdministration
*/
function addNewCustomer() {
var vRegNo = $("#VRegistrationNo").val();
createAjaxRequest("Ticket_CustomerInventory", "Create", "#divAddCustomer", vRegNo);
}
//Global variable for Customer(owner) Mobile No.
var customerMobileNo1;
/**
* Function to check owner mobile no. on focus
* @method checkIfContactNoIsSame
* @for TicketAdministration
*/
function checkIfContactNoIsSame() {
$("#CustomerOwnerMobileNo1").focus(function () {
customerMobileNo1 = $("#CustomerOwnerMobileNo1").val();
});
}
/**
* Function to check is owner exist already
* @method checkIsOwnerExist
* @for TicketAdministration
*/
function checkIsOwnerExist() {
$("#CustomerOwnerMobileNo1").blur(function () {
var vehicleRegistrationNo = $("#VehicleRegistrationNumber").val();
var ownerMobileNo = $("#CustomerOwnerMobileNo1").val();
if (ownerMobileNo != customerMobileNo1) {
//call web api to check is owner exist true, if yes autofill other fields of vehicle
$.getJSON("/Ticket_CustomerInventory/GetOwnerDetailsBasedOnMobilenNo/", { RegistrationNo: vehicleRegistrationNo, OwnerMobileNo: ownerMobileNo }, function (result) {
if (result.CustomerOwnerDetails) {
var Details = result.CustomerOwnerDetails;
for (var count = 0; count < Details.length; count++) {
if (Details[count].CustomerId != null) {
if (Details[count].CustomerVehicleIsOwner == true) {
if (ownerMobileNo == "") {
$("#CustomerOwnerMobileNo1").val(Details[count].CustomerMobileNumber1);
}
$("#CustomerOwnerName").val(Details[count].CustomerCustomerName);
$("#CustomerOwnerEmailId").val(Details[count].CustomerEmailId);
//set selected state
var stateName = Details[count].CustomerState;
var dd = document.getElementById('ddOwnerState');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === stateName) {
dd.selectedIndex = i;
break;
}
}
LoadCityList("ddOwnerState", Details[count].CustomerCity);
$("#CustomerOwnerAddress").val(Details[count].CustomerAddress);
}
}
else {
if (ownerMobileNo == "") {
$("#CustomerOwnerMobileNo1").val('');
}
$("#CustomerOwnerName").val('');
$("#CustomerOwnerEmailId").val('');
$("#CustomerOwnerAddress").val('');
$("#ddOwnerState").val('');
$("#ddOwnerCity").val('');
}
}
}
});
}
});
}
//Global variable for Customer(owner) Vehicle Registration No.
var customerVehicleRegistrationNo;
/**
* Function to check owner vehicle registration no. on focus
* @method checkIfVRegistrationNoIsSame
* @for TicketAdministration
*/
function checkIfVRegistrationNoIsSame() {
$("#VehicleRegistrationNumber").focus(function () {
customerVehicleRegistrationNo = $("#VehicleRegistrationNumber").val().replace(/-/g, "");
});
}
/**
* Function to check is vehicle exist already
* @method checkIsVehicleExist
* @for TicketAdministration
*/
function checkIsVehicleExist() {
$("#VehicleRegistrationNumber").blur(function () {
var vehicleRegistrationNo = $("#VehicleRegistrationNumber").val().replace(/-/g, "");
if (vehicleRegistrationNo != customerVehicleRegistrationNo) {
//call web api to check is vehicle exist true, if yes autofill other fields of vehicle
$.getJSON("/Ticket_CustomerInventory/GetVehicleDetailsBasedOnRegistrationNo/", { RegistrationNo: vehicleRegistrationNo }, function (result) {
if (result.VehicleDetails) {
var Details = result.VehicleDetails;
for (var count = 0; count < Details.length; count++) {
console.log(Details);
if (Details[count].Id != null) {
//$("#VehicleNumberPlate").val(Details[count].VehicleNumberPlate);
//$("#ddVehicleModleNo").val(Details[count].ModelNumber);
//$("#ddVehicleType").val(Details[count].VehicleType);
//$("#CustomerVehicleModelTagging").val('');
//getVehicleModelTagging();
//$("#InstallationDate").val(Details[count].VehicleInstallationDate);
$("#VehicleNumberPlate").val(Details[count].VehicleNumberPlate);
$("#ddVehicleModleNo").val(result.vehicleModelTaggingName);
$("#ddVehicleModleNo").prop('title', result.vehicleModelTaggingName);
$("#ddVehicleType").val(Details[count].VehicleType);
$("#InstallationDate").val(Details[count].VehicleInstallationDate);
$("#CustomerVehicleModelTagging").val(result.vehicleModelTagging);
}
else {
GetVehicleDetailsBasedOnRegistrationNoThirdParty();
}
}
}
});
}
});
}
function GetVehicleDetailsBasedOnRegistrationNoThirdParty() {
var vehicleRegistrationNo = $("#VehicleRegistrationNumber").val().replace(/-/g, "");
$.getJSON("/Ticket_CustomerInventory/GetVehicleDetailsBasedOnRegistrationNoThirdParty/", { RegistrationNo: vehicleRegistrationNo }, function (result) {
if (result.Status != "0") {
var Details = result.VehicleDetails;
console.log(Details[0].CustomerState);
$("#thirdPartyInfoupdatedornot").prop("disabled", false);
$("#VehicleNumberPlate").val(Details[0].VehicleRegistrationNumber);
$("#ddVehicleModleNo").val(result.vehicleModelTaggingName);
$("#ddVehicleModleNo").prop('title', result.vehicleModelTaggingName);
$("#ddVehicleType").val(Details[0].VehicleType);
$("#InstallationDate").val(Details[0].VehicleInstallationDate);
$("#CustomerOwnerName").val(Details[0].CustomerCustomerName);
$("#CustomerOwnerEmailId").val(Details[0].CustomerEmailId);
$("#CustomerOwnerAddress").val(Details[0].CustomerAddress);
$("#CustomerOwnerMobileNo1").val(Details[0].CustomerMobileNumber1);
$("#ddOwnerState option").each(function () {
if ($(this).text() == Details[0].CustomerState) {
$(this).attr('selected', 'selected');
}
});
LoadCityList("ddOwnerState", Details[0].CustomerCity);
$("#CustomerVehicleModelTagging").val(result.vehicleModelTagging);
}
else
$("#thirdPartyInfoupdatedornot").prop("disabled", true);
});
}
/**
* Function to get vehicle model tagging based on vehicle model no
* @method getVehicleModelTagging
* @for TicketAdministration
*/
function getVehicleModelTagging() {
var VehicleModelTypeId = $("#ddVehicleModleNo").val();
$.getJSON("/Ticket_CustomerInventory/GetVehicleModelTaggingBasedOnModelNo/", { ModelTypeId: VehicleModelTypeId }, function (result) {
if (result) {
var ModelType = result.VehicleModelTagging;
for (var count = 0; count < ModelType.length; count++) {
$("#CustomerVehicleModelTagging").val(ModelType[count].VehicleTypeTagging);
}
}
});
}
/**
* Function call on success of add customer
* @method onSuccessAddCustomer
* @for TicketAdministration
*/
function onSuccessAddCustomer(data) {
var registrationNo, mobileNo, complaintNo;
if (data.success == true) {
registrationNo = data.vRegistrationNo;
mobileNo = "";
complaintNo = "";
if (xhr_addCustomer && xhr_addCustomer.readystate != 4) {
xhr_addCustomer.abort();
}
xhr_addCustomer = $.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_GetTicketHistory/",
data: { registrationNo: registrationNo, mobileNo: mobileNo, complaintNo: complaintNo },
success: function (data) {
if (data.fillFieldMesseage) {
jAlert(data.fillFieldMesseage, 'Message');
}
else {
$("#divCheckHistory").html("");
$("#divCheckHistory").html(data);
$("#divMapDetail").removeClass("display_none");
$("#divMapContainer,#divStaticMapContainer").addClass("withtoolbar");
$("#divMapContainer,#divStaticMapContainer").addClass("MapBox");
if (document.getElementById('tableTicketHistory')) {
$("#tableTicketHistory > tbody > tr:first").trigger("click");
} else if (document.getElementById('tableCloseTicketHistory')) {
$("#tableCloseTicketHistory > tbody > tr:first").trigger("click");
} else {
$("#divMapDetail").addClass("display_none");
$("#divMapContainer,#divStaticMapContainer").removeClass("withtoolbar");
$("#divMapContainer,#divStaticMapContainer").removeClass("MapBox");
}
}
},
complete: function () {
closeWindow("#divAddCustomer");
},
error: function (data) {
console.log(data);
}
});
}
else {
jAlert(data.message, 'Message', function () {
});
}
}
/**
* Function to create ajax request
* @method createAjaxRequest
* @param {string} controller Name of controller
* @param {string} actionName Name of action on controller
* @param {string} divId HTML id of div
* @param {string} VRegNo Registration no. of vehicle
* @for TicketAdministration
*/
function createAjaxRequest(controller, actionName, divId, VRegNo) {
var divIdToBeRemoveData;
if (divId == "#divAddCustomerForExistingVehicle") {
divIdToBeRemoveData = "#divAddCustomer";
}
else {
divIdToBeRemoveData = "#divAddCustomerForExistingVehicle";
}
//console.log(VRegNo);
// Ajax request
if (activeRequest && activeRequest.readystate != 4) {
activeRequest.abort();
}
activeRequest = $.ajax({
type: "GET",
url: "/" + controller + "/" + actionName + "/",
data: { VRegistrationNo: VRegNo },
success: function (data) {
$(divIdToBeRemoveData).html("");
$(divId).html("");
$(divId).html(data);
//open form in new dialog box
$(divId).data("kendoWindow").open();
openKendoWindowInCenter(divId);
if (divId == "#divAddCustomerForExistingVehicle") {
$("#customerOwnerMobileNo1").val($("#vehicle_owner_contact_no").val());
$("#CustomerOwnerEmailId").val($("#vehicle_owner_emailID").val());
$("#ddOwnerState").val($("#vehicle_owner_location").val());
$("#ddOwnerCity").val($("#vehicle_owner_City").val());
$("#CustomerOwnerAddress").val($("#vehicle_owner_Address").val());
$("#CustomerOwnerName").val($("#vehicle_owner_name").val());
$("#VehicleRegistrationNumber").val($("#vehicle_registration").val());
$("#VehicleNumberPlate, #hdnVehicleChassis").val($("#vehicle_numberPlate").val());
$("#VehicleNumberPlate").prop('title', $("#vehicle_numberPlate").val());
//$("#ddVehicleModleNo").val($("#vehicle_model").val());
$("#VehicleModelNumber").val(stringToDecode($("#vehicle_model").val(), "hiddenModelNo"));
$("#VehicleModelNumber").prop('title', stringToDecode($("#vehicle_model").val(), "hiddenModelNo"));
$("#CustomerVehicleModelTagging").val($("#vehicle_product_varient").val());
$("#VehicleType").val($("#eos_VehicleType").val());
$("#VehicleInstallationDate").val($("#eos_VehicleInstallationDate").val());
}
},
error: function (data) {
console.log(data);
}
});
}
/**
* Function to close kendo window
* @method closeWindow
* @param {String} divId The id of div
* @for TicketAdministration
*/
function closeWindow(divId) {
$(divId).data("kendoWindow").close();
}
/**
* Function call on click of cancel button of add customer window
* @method btnCancelAddCustomer
* @param {String} divId The id of div
* @for TicketAdministration
*/
function btnCancelAddCustomer(divId) {
closeWindow(divId);
}
/**
* Function to add new customer for already existing vehicle
* @method addCustomerForExistingVehicle
* @param {String} vRegNo Registration no of vehicle
* @for TicketAdministration
*/
function addCustomerForExistingVehicle(vRegNo) {
var VRegistrationNo = vRegNo;
//console.log(VRegistrationNo);
createAjaxRequest("Ticket_CustomerInventory", "CreateNewCustomerForExistingVehicle", "#divAddCustomerForExistingVehicle", VRegistrationNo);
}
/**
* Function call on success of add customer for already existing vehicle
* @method onSuccessAddCustomerForExistingVehicle
* @for TicketAdministration
*/
function onSuccessAddCustomerForExistingVehicle(data) {
if (data.success == true) {
if (data.dataUpdatedFor == "radio_chassis" || data.dataUpdatedFor == "radio_both") {
$("#vehicle_numberPlate").val($("#VehicleNumberPlate").val());
}
var VRegistrationNo = data.vRegistationNo;
if (xhr_addCustomerForExisting && xhr_addCustomerForExisting.readystate != 4) {
xhr_addCustomerForExisting.abort();
}
xhr_addCustomerForExisting = $.ajax({
type: "GET",
url: "/Ticket_CustomerInventory/ShowCustomerList/",
data: { VRegistrationNo: VRegistrationNo },
success: function (data) {
$("#driver_name").text("");
// add by default select text
$("#driver_name").append(
$('<option></option>').val("").html("-Select-"));
for (var counter = 0; counter < data.list.length; counter++) {
$("#driver_name").append(
$('<option></option>').val(data.list[counter].Value).html(data.list[counter].Text));
}
},
complete: function () {
closeWindow("#divAddCustomerForExistingVehicle");
},
error: function (data) {
console.log(data);
}
});
}
}
//======================= get all nearest vans and dealers ==========================//
/**
* Function call on begin of get all nearest vans list
* @method onBeginGetAllVansDealers
* @for TicketAdministration
*/
function onBeginGetAllVansDealers() {
var stateMultiselect = $("#eos_state").data("kendoMultiSelect").dataItems();
if ($('#vehicle_owner_language').find('option:selected').text() == "-Select-") { //check if owner language is selected or not
$("#spanLanguageRequired").show();
return false;
}
//else if ($('#tollFreeNoSource').find('option:selected').text() == "-Select-") { //check if toll free no source is selected or not
// $("#spanSourceTollFreeRequired").show();
// return false;
//}
else if ($('#driver_name').find('option:selected').text() == "-Select-") { //check if driver/customer name is selected or not
$("#spanCustomerRequired").show();
return false;
} else if (stateMultiselect == "" || stateMultiselect == null || stateMultiselect.length == 0) { //check if state is selected or not
$("#spanState").show();
return false;
} else if ($('#eos_city').val() == "") { //check if city is selected or not
$("#spanCity").show();
return false;
} else if ($('#routes').find('option:selected').text() == "-Select-") { //check if route is selected or not
$("#spanRoutes").show();
return false;
} else if ($('#nature_of_problem').val() == "") { //check if nature of problem is selected or not
$("#spanDescription").show();
return false;
}
//else if ($('#isVehicleInWarrentyOrAmc').find('option:selected').text() == "-Select-") { //check if warrenty is selected or not
// $("#spanWarrenty").show();
// return false;
//}
else if ($('#totalKmCovered').val() == "") { //check if warrenty is selected or not
$("#spanKmCovered").show();
return false;
}
return true;
}
//Global variables to get more than 25 vans/dealers
var arrOf25VanDealerLatLng = [];
var arrOf25VanDealerDetails = [];
var _LIMIT = 70;
/**
* Function to get all nearest vans / dealers list
* @method getNearestVansDealers
* @for TicketAdministration
*/
//function getNearestVansDealers() {
// debugger
// console.log("getNearestVansDealers");
// if (onBeginGetAllVansDealers() == true) {
// $("#spanEosLocation").hide();
// $("#spanRoutes").hide();
// $("#spanState").hide();
// $("#spanDescription").hide();
// $("#spanLanguageRequired").hide();
// //$("#spanSourceTollFreeRequired").hide();
// $("#spanCity").hide();
// //$("#spanWarrenty").hide();
// $("#spanKmCovered").hide();
// //empty van dealer lat lng array
// if (vanDealerLatLngArr.length > 0) {
// vanDealerLatLngArr = [];
// }
// //empty details list of van dealer array
// if (detailsListOfVanDealer.length > 0) {
// detailsListOfVanDealer = [];
// }
// //remove path between 2 markers
// if (displayDisplay) {
// //Remove direction display
// displayDisplay.setMap(null);
// }
// //empty array to get next 25 vans/dealers details.
// copyResulEls = [];
// //loop through arary
// for (var i = 0; i < nearestVansDealersMarks.length; i++) {
// //set marker map to null
// nearestVansDealersMarks[i].setMap(null);
// }
// //empty array
// nearestVansDealersMarks = [];
// var stateName1, stateName1, stateId, vanDealerLatlng, type, VDId, vanDealerLat, vanDealerLng, vanDealerCity, vanDealerName, vanDealerState,
// deviceAlias, vanRemainingTime, deviceStatus, noOfAssignedTickets, description, DealerSCode, DealerOrVanContactNo;
// //stateName = $('#eos_state').find('option:selected').text();
// //stateId = $('#eos_state').find('option:selected').val();
// var stateMultiselect = $("#eos_state").data("kendoMultiSelect").dataItems();
// if (stateMultiselect != "" && stateMultiselect != null && stateMultiselect.length > 0) {
// stateName1 = stateMultiselect[0].text;
// stateName2 = stateMultiselect.length > 1 ? stateMultiselect[1].text : "";
// }
// if (xhr_getAllVans && xhr_getAllVans.readystate != 4) {
// xhr_getAllVans.abort();
// }
// xhr_getAllVans = $.ajax({
// type: "GET",
// url: "/Ticket/GetVansDealersbyStates/",
// data: { StateName: stateName1, limit: _LIMIT, StateName2: stateName2 },
// success: function (data) {
// if (data.NearestVansDealers.length > 0) {
// console.log("van", data.NearestVansDealers)
// if (breakdownLocationLatLng != "") {
// //remove bind click
// google.maps.event.clearListeners(ccplMap, 'click');
// $("#searchLocationTool").attr('readonly', 'readonly');
// // comment
// // google.maps.event.clearListeners(searchBox, 'places_changed');
// }
// vanDealerLatLngArr.length = 0;
// for (var counter = 0; counter < data.NearestVansDealers.length; counter++) {
// var title, markerIcon, backgroundColor;
// var updatedDeviceStatus = "";
// var vanDealerObj = {};
// vanDealerLatlng = new google.maps.LatLng(data.NearestVansDealers[counter].DealerVanLattitude, data.NearestVansDealers[counter].DealerVanLongitude);
// type = data.NearestVansDealers[counter].Type;
// VDId = data.NearestVansDealers[counter].DealerVanId;
// vanDealerLat = data.NearestVansDealers[counter].DealerVanLattitude;
// vanDealerLng = data.NearestVansDealers[counter].DealerVanLongitude;
// vanDealerCity = data.NearestVansDealers[counter].DealerVanCity;
// noOfAssignedTickets = data.NearestVansDealers[counter].NoOfAssignedTicket;
// vanDealerName = data.NearestVansDealers[counter].DealerVanName;
// vanDealerState = data.NearestVansDealers[counter].DealerVanState;
// deviceAlias = data.NearestVansDealers[counter].DeviceAlias;
// vanRemainingTime = data.NearestVansDealers[counter].RemainingTime;
// deviceStatus = data.NearestVansDealers[counter].DeviceStatus;
// DealerSCode = data.NearestVansDealers[counter].DealerSCode;
// DealerOrVanContactNo = data.NearestVansDealers[counter].DealerOrVanContactNo;
// DealerSCode = data.NearestVansDealers[counter].DealerSCode;
// DealerOrVanContactNo = data.NearestVansDealers[counter].DealerOrVanContactNo;
// //check if remaining time is negative
// if (vanRemainingTime == null || vanRemainingTime == "") {
// vanRemainingTime = "0";
// }
// else {
// if (vanRemainingTime.indexOf('-') === -1) {
// vanRemainingTime = vanRemainingTime;
// } else {
// vanRemainingTime = "0";
// }
// }
// //check if device is connected or not
// if ((deviceStatus == "True") && (type == "van")) {
// //console.log(deviceStatus);
// updatedDeviceStatus = "green-circle";
// }
// else if ((deviceStatus == "False") && (type == "van")) {
// updatedDeviceStatus = "red-circle";
// } else {
// updatedDeviceStatus = "";
// }
// if (vanRemainingTime == "0") {
// backgroundColor = "green";
// }
// else {
// backgroundColor = "red";
// }
// //push van dealer lat lng in array
// vanDealerLatLngArr.push(vanDealerLatlng);
// //bind van / dealer details in object
// vanDealerObj.type = type;
// vanDealerObj.id = VDId;
// vanDealerObj.lat = vanDealerLat;
// vanDealerObj.lng = vanDealerLng;
// vanDealerObj.city = vanDealerCity;
// vanDealerObj.assignedTickets = noOfAssignedTickets;
// vanDealerObj.name = vanDealerName;
// vanDealerObj.state = vanDealerState;
// vanDealerObj.alias = deviceAlias;
// vanDealerObj.remainingTime = vanRemainingTime;
// vanDealerObj.deviceStatus = updatedDeviceStatus;
// vanDealerObj.backGroundColor = backgroundColor;
// vanDealerObj.DealerSCode = DealerSCode;
// vanDealerObj.DealerOrVanContactNo = DealerOrVanContactNo;
// //push van dealer details in array
// detailsListOfVanDealer.push(vanDealerObj);
// //Get address of the Lat Long click clicked
// getReverseGeoCode(vanDealerLatlng, function (data) {
// //console.log("jdjhfjehfje");
// //console.log(data);
// //Here we got the address of the point clicked. Update this value to the form textbox.
// title = data.formattedAddress;
// //geoCodeState = data.state;
// });
// }
// var forLoopLength, multiplier = 100, waitIndex = 0, setTimeOutSeconds = 0;
// var vanDealerLatLngArrLength = vanDealerLatLngArr.length;
// //check if breakdown location is marked or not
// if (breakdownLocationLatLng != "") {
// if (vanDealerLatLngArr.length < 15 && vanDealerLatLngArr.length > 0) {
// forLoopLength = 1;
// } else {
// if ((vanDealerLatLngArr.length % 15) > 0) {
// forLoopLength = parseInt((vanDealerLatLngArr.length / 15), 10) + 1;
// } else if ((vanDealerLatLngArr.length % 15) == 0) {
// forLoopLength = parseInt((vanDealerLatLngArr.length / 15), 10);
// }
// }
// var z;
// if (forLoopLength == 1) {
// arrOf25VanDealerLatLng = [];
// arrOf25VanDealerDetails = [];
// for (var i = 0; i < vanDealerLatLngArr.length; i++) {
// arrOf25VanDealerLatLng.push(vanDealerLatLngArr[i]);
// arrOf25VanDealerDetails.push(detailsListOfVanDealer[i]);
// }
// calcRouteDistance(breakdownLocationLatLng, arrOf25VanDealerLatLng, arrOf25VanDealerDetails);
// setTimeout(function () {// console.log(copyResulEls);
// createVanDealerSortedList();
// }, 1000);
// } else {
// for (var i = 0; i < forLoopLength; i++) {
// // setTimeout(function () {
// //console.log(setTimeOutSeconds, waitIndex, i);
// setTimeOutSeconds = waitIndex * multiplier;
// //console.log(i);
// if (vanDealerLatLngArrLength < 15) { z = 0; } else { z = vanDealerLatLngArrLength - 15; }
// arrOf25VanDealerLatLng = [];
// arrOf25VanDealerDetails = [];
// for (var j = vanDealerLatLngArrLength; j > z; j--) {
// arrOf25VanDealerLatLng.push(vanDealerLatLngArr[j - 1]);
// arrOf25VanDealerDetails.push(detailsListOfVanDealer[j - 1]);
// }
// vanDealerLatLngArrLength = vanDealerLatLngArrLength - 15;
// calculateDistanceInSetTimeOut(breakdownLocationLatLng, arrOf25VanDealerLatLng, arrOf25VanDealerDetails, setTimeOutSeconds);
// waitIndex++;
// }
// createVanDealerList();
// }
// } else {
// jAlert(CREATE_TICKET_MESSAGES.requiredBreakdownLocation);
// }
// }
// else {
// jAlert(CREATE_TICKET_MESSAGES.vanDealerUnavailable, 'Message', function () {
// $("#divVanDealerList").css('display', 'none');
// $("#divMap").css('height', '');
// });
// }
// },
// error: function (data) {
// console.log(data);
// }
// });
// }
//}
/**
* SetTimeOut function to calculate distance between van and dealer using google distance matrix api
* @method calculateDistanceInSetTimeOut
* @param {String} breakDownLatLng LatLng of breakdown vehicle
* @param {array} arrVanDealerLatLng LatLng of vans / dealers
* @param {array} arrVanDealerDetails details of vans/dealers
* @param {String} timeOutSeconds time in seconds for setTimeout function
* @for TicketAdministration
*/
function calculateDistanceInSetTimeOut(breakDownLatLng, arrVanDealerLatLng, arrVanDealerDetails, timeOutSeconds) {
setTimeout(function () {
calcRouteDistance(breakDownLatLng, arrVanDealerLatLng, arrVanDealerDetails);
}, timeOutSeconds);
}
/**
* setTimeOut function to create sorted van dealer list
* @method createVanDealerList
* @for TicketAdministration
*/
function createVanDealerList() {
setTimeout(function () {
createVanDealerSortedList();
}, 1000);
}
/**
* 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 TicketAdministration
*/
function createMarkerVanDealer(position, icon, title) {
console.log(icon);
//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);
}
/**
* Function to create markers on van's / dealer's locations
* @method createMarker
* @param {String} position Position of van / dealer
* @param {String} icon Icon of placed marker
* @param {String} vanDealerId Van / Dealer's id
* @param {String} content Content of mesage to show in infowindow
* @param {String} mapId map id
* @for TicketAdministration
*/
function createMarker(position, icon, vanDealerId, content, mapId) {
//create a google marker with the given param
var vanDealerMarker = new google.maps.Marker({
position: position,
map: mapId,
icon: icon,
customInfo: String(vanDealerId)
});
vanDealerMarker.infoCheck = false;
//push marker to marksArray
nearestVansDealersMarks.push(vanDealerMarker);
//update infowindow
updateInfoWindow(vanDealerMarker, content, mapId);
//on mouse over of marker
google.maps.event.addListener(vanDealerMarker, 'mouseover', function () {
//remove animation on marker
if (vanDealerMarker.getAnimation() != null) {
vanDealerMarker.setAnimation(null);
}
});
}
/**
* Function to update data of info window on markers of van's / dealer's locations
* @method updateInfoWindow
* @param {String} unitMarker Position of van / dealer
* @param {String} message Data of info window on placed marker
* @param {String} map map id
* @for TicketAdministration
*/
function updateInfoWindow(unitMarker, message, map) {
// Add click listener to open info window
google.maps.event.addListener(unitMarker, 'click', function () {
infowindow.setContent(message);
infowindow.open(map, unitMarker);
});
}
//=============================== end ==============================================//
//------------------------------------------ calculate route -------------------------------------//
/**
* This fn removes all markers stored in ticketDetailsMarkerArray.
* @method removeTicketDetailsMarkerArray
* @for TicketAdministration
*/
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
* @param {String} vanDealerType Type is Van or Dealer
* @param {String} mapID map id
* @for TicketAdministration
*/
function calcRoute(startLatLng, endLatLng, vanDealerType, mapID, wayPointArr) {
if (displayDisplay) {
//Remove direction display
displayDisplay.setMap(null);
}
var rendererOptions = {
map: mapID,
suppressMarkers: true,
polylineOptions: { strokeColor: "#1b3f94" }
}
var request = "";
displayDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//Make request obj to Direction Service API with starting and end LatLng
request = {
origin: startLatLng,
destination: endLatLng,
avoidHighways: false,
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();
} else {
$("#div_loading").hide();
}
});
}
/**
* This fn calculates and draws the Route for selected national highway using Google Direction API
* @method drawHighway
* @param {String} startLatLng Position of origin
* @param {String} endLatLng Position of destination
* @param {String} vanDealerType Type is Van or Dealer
* @param {String} mapID map id
* @for TicketAdministration
*/
function drawHighway(startLatLng, endLatLng, vanDealerType, mapID, wayPointArr, routeColor) {
if (displayHighway) {
//Remove direction display
displayHighway.setMap(null);
}
var rendererOptionsForHighway = {
map: mapID,
suppressMarkers: true,
polylineOptions: { strokeColor: routeColor }
}
var request = "";
displayHighway = new google.maps.DirectionsRenderer(rendererOptionsForHighway);
if (wayPointArr.length > 0) {
//Make request obj to Direction Service API with starting and end LatLng
request = {
origin: startLatLng,
destination: endLatLng,
waypoints: wayPointArr,
avoidHighways: false,
optimizeWaypoints: false,
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) {
displayHighway.setOptions({ preserveViewport: true });
//set Direction to the response
displayHighway.setDirections(response);
var leg = response.routes[0].legs[0];
} else {
}
});
}
}
//-------------------------------------------- end routing ---------------------------------------//
//===================================== calculate distance =========================================//
//------------------------------------- Check if dealer ticket then fill reason -------------------------------//
var delaerTicketReason = '';
var ticketStatusAssignOrReassign = '';
/**
* Function call on selection change of reasons drop down data list
* @method onChangeReasonForDelaerTicket
* @param {string} trIndex selected row index
* @param {string} $this HTML tag attributes container
* @for TicketAdministration
*/
function checkIfAssignToDealer(trIndex, $this) {
//console.log(trIndex, $this.value);
ticketStatusAssignOrReassign = $this.value;
var assignedTo = '', ddReasonId = '', divKendoWindowId = '', hdnTextBoxId = '', controller = '';
if (ticketStatusAssignOrReassign.trim().toLowerCase() == "assign") {
assignedTo = $('#displayVansDealersTable tr:eq(' + (trIndex + 1) + ') > td:eq(1)').text();
ddReasonId = 'ddReasonForDealerTicket';
divKendoWindowId = 'divReasonForTicketAssignToDealer';
hdnTextBoxId = 'hdnVanDealerIndex';
controller = 'Ticket_GetDealerTicketReasonView';
} else {
assignedTo = $('#displayVansDealersTable_reassign tr:eq(' + (trIndex + 1) + ') > td:eq(1)').text();
ddReasonId = 'ddReasonForDealerTicketReassign';
divKendoWindowId = 'divReasonForTicketReAssignToDealer';
hdnTextBoxId = 'hdnVanDealerIndexReassign';
controller = 'Ticket_GetDealerTicketReassignReasonView';
}
$('#' + hdnTextBoxId).val('');
$('#' + hdnTextBoxId).val(trIndex);
if (assignedTo.trim().toLowerCase() == "dealer") {
$.ajax({
type: "POST",
url: "/TicketAdministration_Dealer/" + controller + "/",
//url: "/Ticket/" + controller + "/",
success: function (result) {
if (result) {
//alert(divKendoWindowId);
getReasonForDealerTicket(ddReasonId);
$('#' + divKendoWindowId).html(result);
}
},
complete: function () {
//open form in new dialog box
$('#' + divKendoWindowId).data("kendoWindow").open();
openKendoWindowInCenter('#' + divKendoWindowId);
},
error: function () {
}
});
} else {
if (ticketStatusAssignOrReassign.trim().toLowerCase() == "assign") {
assignVan(trIndex);
} else {
reAssignVan(trIndex);
location.reload();
}
}
}
/**
* Function call on blur of HTML input type tag
* @method checkIfRequiredField
* @for TicketAdministration
*/
function checkIfRequiredField($this) {
var inputId = $this;
if ($("#" + inputId).val() != "") {
$("#" + inputId).removeClass("requiredField");
} else {
$("#" + inputId).addClass("requiredField");
}
}
/**
* Function call on selection change of reasons drop down data list
* @method onChangeReasonForDelaerTicket
* @param {string} $this HTML tag attributes container
* @param {string} textBoxId text box id for other reason
* @for TicketAdministration
*/
function onChangeReasonForDelaerTicket($this, textBoxId) {
if (ticketStatusAssignOrReassign.trim().toLowerCase() == "assign") {
$("#spanReasonForDealerTicket").hide();
$("#spanOtherReasonForDealerTicket").hide();
} else {
$("#spanReasonForDealerTicketReassign").hide();
$("#spanOtherReasonForDealerTicketReassign").hide();
}
var ddId = $this.id;
if ($("#" + ddId).val() == null) {
$("#" + textBoxId).removeClass("requiredField");
$("#" + textBoxId).attr('disabled', true);
$("#" + textBoxId).val('');
} else if (($("#" + ddId).val().indexOf("Others") != -1) == true) {
$("#" + textBoxId).addClass("requiredField");
$("#" + textBoxId).attr('disabled', false);
$("#" + textBoxId).val('');
} else {
$("#" + textBoxId).removeClass("requiredField");
$("#" + textBoxId).attr('disabled', true);
$("#" + textBoxId).val('');
}
}
/**
* Function call to check validations
* @method onBeginReasonForDealerTicket
* @for TicketAdministration
*/
function onBeginReasonForDealerTicket() {
var reason = '', otherTextBoxId = '', spanIdForReason = '', spanIdForOtherReason = '';
if (ticketStatusAssignOrReassign.trim().toLowerCase() == "assign") {
reason = $('#ddReasonForDealerTicket').val();
otherTextBoxId = 'txtOtherReasonForDealerTicket';
spanIdForReason = 'spanReasonForDealerTicket';
spanIdForOtherReason = 'spanOtherReasonForDealerTicket';
} else {
reason = $('#ddReasonForDealerTicketReassign').val();
otherTextBoxId = 'txtOtherReasonForDealerTicketReassign';
spanIdForReason = 'spanReasonForDealerTicketReassign';
spanIdForOtherReason = 'spanOtherReasonForDealerTicketReassign';
}
if (reason == null || reason == "") { //check if reason is selected or not
$("#" + spanIdForReason).show();
return false;
} else if ((reason.trim().toLowerCase() == "others") && ($("#" + otherTextBoxId).hasClass('requiredField') == true)) {
$("#" + spanIdForOtherReason).show();
return false;
} else {
$("#" + spanIdForReason).hide();
$("#" + spanIdForOtherReason).hide();
if (reason.trim().toLowerCase() == "others") {
delaerTicketReason = prefixOtherReasonDealerTicket + $("#" + otherTextBoxId).val(); //store dealer ticket reason globally
} else {
delaerTicketReason = reason; //store dealer ticket reason globally
}
return true;
}
}
/**
* Function call to submit reason for dealer ticket
* @method submitReasonForDealerTicket
* @for TicketAdministration
*/
function submitReasonForDealerTicket() {
var divKendoWindowId = '', hiddenValueId = '';
if (ticketStatusAssignOrReassign.trim().toLowerCase() == "assign") {
divKendoWindowId = 'divReasonForTicketAssignToDealer';
hiddenValueId = 'hdnVanDealerIndex';
} else {
divKendoWindowId = 'divReasonForTicketReAssignToDealer';
hiddenValueId = 'hdnVanDealerIndexReassign';
}
if (!onBeginReasonForDealerTicket()) { return; }
if (ticketStatusAssignOrReassign.trim().toLowerCase() == "assign") {
assignVan(parseInt($('#' + hiddenValueId).val(), 10));
closeWindow('#' + divKendoWindowId);
} else {
reAssignVan(parseInt($('#' + hiddenValueId).val(), 10));
closeWindow('#' + divKendoWindowId);
location.reload();
}
}
//------------------------------------- end of Check if dealer ticket then fill reason -------------------------------//
/**
* This fn removes and add class to show which Van is assigned.
* @method assignVan
* @param {String} index Index of selected row of van / dealer list
* @for TicketAdministration
*/
function assignVan(index) {
console.log("-----------------------")
console.log(geoCodeState)
//remove previous assigned class
$("#displayVansDealersTable").find('tr').removeClass('showMarked');
$("#displayVansDealersTable").find('tr:nth-child(' + (index + 2) + ')').addClass('showMarked');
var vehicleRegNo = $("#vehicle_registration").val();
//create object of ticket model
var TicketModel = {};
TicketModel.TicketId = "";
TicketModel.Description = $("#nature_of_problem").val();
TicketModel.listDescription = {};
TicketModel.AssignedTo = $('#displayVansDealersTable tr:eq(' + (index + 1) + ') > td:eq(1)').text();
TicketModel.ReportedVia = "";
if (TicketModel.AssignedTo == "van") {
TicketModel.TicketStatus = 1;
TicketModel.OtherRemarks = null;
}
else {
TicketModel.TicketStatus = 2;
TicketModel.OtherRemarks = delaerTicketReason;
}
TicketModel.Priority = 1;
TicketModel.CustomerScore = "";
//console.log(getParameterByName("vRegistrationNo").trim().toLowerCase(), $("#vehicle_registration").val().trim().toLowerCase());
if (getParameterByName("vRegistrationNo").trim().toLowerCase() == $("#vehicle_registration").val().trim().toLowerCase()) {
TicketModel.CreatedBy = selectedKamNotification;
} else { TicketModel.CreatedBy = ""; }
TicketModel.CreationTime = "";
TicketModel.LastModifiedBy = "";
TicketModel.LastModifiedTime = "";
TicketModel.BreakdownLocation = $("#eos_exact_location").val();
TicketModel.BreakdownLongitude = breakdownLocationLatLng.lng();
TicketModel.BreakdownLattitude = breakdownLocationLatLng.lat();
TicketModel.AssignedToUserId = $('#displayVansDealersTable tr:eq(' + (index + 1) + ') > td:eq(2)').text();
TicketModel.AssignedToUserLattitude = copyResulEls[index].lat;
TicketModel.AssignedToUserLongitude = copyResulEls[index].lng;
TicketModel.Isdeclined = false;
TicketModel.EstimatedTimeForJobCompletion = "";
TicketModel.TotalTicketLifecycleTimeSla = "";
TicketModel.EstimatedTimeForJobCompletionSubmitTime = "";
TicketModel.VehicleRegisterNumber = $("#vehicle_registration").val();
TicketModel.BreakdownLocationLandmark = $("#breakdown_landmark").val();
TicketModel.RouteId = parseInt($("#routes").val(), 10);
TicketModel.CustomerContactNo = $("#driver_contact_no").val();
TicketModel.TicketStatusAlias = "";
TicketModel.Token = "";
TicketModel.Status = "";
TicketModel.Message = "";
TicketModel.UtcMinute = 0;
TicketModel.RepairCost = "";
TicketModel.SlaMissedReason = "";
TicketModel.SuggestionComment = "";
TicketModel.JobCompleteResponseTime = "";
TicketModel.DefaultCol2 = $("#vehicle_type_of_load").val();
TicketModel.DefaultCol3 = $("#vehicle_direction").val();
TicketModel.StateName = geoCodeState;
//TicketModel.CityName = $("#eos_city").data("kendoComboBox").text();
TicketModel.CityName = $("#eos_city").val();
TicketModel.CallerLanguage = $('#vehicle_owner_language').find('option:selected').text();
TicketModel.KmCovered = $('#totalKmCovered').val();
TicketModel.Warranty = $('#isVehicleInWarrentyOrAmc').find('option:selected').text() == "-Select-" ? "" : $('#isVehicleInWarrentyOrAmc').find('option:selected').text();
TicketModel.TollFreeeNoSource = $('#tollFreeNoSource').find('option:selected').text() == "-Select-" ? "" : $('#tollFreeNoSource').find('option:selected').text();
TicketModel.VehicleTagging = $("#vehicle_product_varient").val();
var distanceInKm = $('#displayVansDealersTable tr:eq(' + (index + 1) + ') > td:eq(5)').text();
var distance;
if (distanceInKm != "" && distanceInKm != null) {
var splitDistance = distanceInKm.split(" ");
if (splitDistance[1] == "km") {
distance = splitDistance[0];
distance = distance.replace(',', '');
} else if (splitDistance[1] == "m") {
distance = parseFloat(splitDistance[0]) / 1000;
//distance = distance.replace(',', '');
} else {
distance = "0";
}
} else { distance = "0"; }
//var lastIndex = distanceInKm.lastIndexOf(" km");
//var distance = distanceInKm.substring(0, lastIndex);
//TicketModel.EstimateDistance = (distance == null || distance == "") ? "0" : distance;
TicketModel.EstimateDistance = distance;
//get route id
routeId = parseInt($("#routes").val(), 10);
$.ajax({
type: "POST",
url: "/Ticket/GetRouteWiseSlaTime/",
data: { RouteId: routeId },
success: function (result) {
if (result) {
for (var count = 0; count < result.RouteWiseSlaTime.length; count++) {
routeWiseSlaTime = parseInt(result.RouteWiseSlaTime[count].SlaTime, 10);
}
}
},
complete: function () {
TicketModel.DefaultSlaTime = routeWiseSlaTime;
//Send POST request with the ticket data
if (xhr_addNewTicket && xhr_addNewTicket.readystate != 4) {
xhr_addNewTicket.abort();
}
xhr_addNewTicket = $.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_CreateTicket/",
data: TicketModel,
success: function (data) {
if (data.success == true) {
var createdTicketId = data.ticketId;
if (displayDisplay) {
displayDisplay.setMap(null);
}
//remove marker
if (marker) {
marker.setMap(null);
//set address text field empty here
marker = "";
}
//empty van dealers marker array
if (nearestVansDealersMarks.length > 0) {
for (var counter = 0; counter < nearestVansDealersMarks.length; counter++) {
nearestVansDealersMarks[counter].setMap(null);
//set address text field empty here
nearestVansDealersMarks[counter] = "";
}
nearestVansDealersMarks = [];
}
//loop through arary
for (var i = 0; i < ticketDetailsMarkerArray.length; i++) {
//set marker map to null
ticketDetailsMarkerArray[i].setMap(null);
}
//remove highway path
if (displayHighway) {
displayHighway.setMap(null);
}
//empty array
ticketDetailsMarkerArray = [];
//empty city
// $("#eos_city").data("kendoComboBox").text('');
$("#eos_city").val('')
//remove place location markers
removePlaceLocationMarkerArray();
//remove click event
removeClickEventToMap();
//ajax request to show new ticket in ticket table
$.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_GetTicketHistory/",
data: { registrationNo: "", mobileNo: "", complaintNo: createdTicketId },
success: function (data) {
if (data.fillFieldMesseage) {
jAlert(data.fillFieldMesseage, 'Message');
}
else {
onClickAssignTicketOrCancel();
$("#divCheckHistory").html("");
$("#divCheckHistory").html(data);
$("#divVanDealerList").css('display', 'none');
$("#searchLocationTool").hide();
$("#divMap").css('height', '');
if (document.getElementById('tableTicketHistory')) {
$("#tableTicketHistory > tbody > tr[id=" + createdTicketId + "]").trigger("click");
}
}
},
error: function (data) {
console.log(data);
}
});
//Remove any click listener if any present
google.maps.event.clearListeners(ccplMap, 'click');
//set marker to null
marker = "";
selectedKamNotification = "";
}
else {
//console.log(data);
jAlert(data.message, 'Message', function () {
btnCancel();
});
}
},
complete: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
}
});
}
/**
* This fn calculate route distance and show sorted vans and dealers list in table
* @method calcRouteDistance
* @param {String} origin Location of origin
* @param {String} destinationArr array Locations of destination
* @for TicketAdministration
*/
function calcRouteDistance(origin, destinationArr, vanDealerDetailsArr) {
console.log("_________-calcRouteDistance");
console.log(origin);
console.log(destinationArr);
console.log(vanDealerDetailsArr);
debugger
//console.log(vanDealerDetailsArr);
service.getDistanceMatrix({
origins: [origin],
destinations: destinationArr,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, distanceMatrixCallback);
//Callback for Distance Matrix API
function distanceMatrixCallback(response, status) {
//If Status was an error, throw alert
console.log("distanceMatrixCallback");
console.log(status, response);
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
//Result ELements response from Distance Matrinx
var resultEls = response.rows[0].elements;
//Add vanId and to the response
for (var i = 0; i < resultEls.length; i++) {
if (resultEls[i].status == "OK") {
resultEls[i].vanDealerAddress = response.destinationAddresses[i];
resultEls[i].vanDealerID = vanDealerDetailsArr[i].id;
resultEls[i].type = vanDealerDetailsArr[i].type;
resultEls[i].lat = vanDealerDetailsArr[i].lat;
resultEls[i].lng = vanDealerDetailsArr[i].lng;
resultEls[i].city = vanDealerDetailsArr[i].city;
resultEls[i].assignedTicketsToVanDealer = vanDealerDetailsArr[i].assignedTickets;
resultEls[i].name = vanDealerDetailsArr[i].name;
resultEls[i].state = vanDealerDetailsArr[i].state;
resultEls[i].alias = vanDealerDetailsArr[i].alias;
resultEls[i].remainingTime = vanDealerDetailsArr[i].remainingTime;
resultEls[i].deviceStatus = vanDealerDetailsArr[i].deviceStatus;
resultEls[i].backgroundColor = vanDealerDetailsArr[i].backGroundColor;
resultEls[i].DealerSCode = vanDealerDetailsArr[i].DealerSCode;
resultEls[i].DealerOrVanContactNo = vanDealerDetailsArr[i].DealerOrVanContactNo;
}
}
console.log("resultEls", resultEls);
for (var counter = 0; counter < resultEls.length; counter++) {
if (resultEls[counter].status == "OK") {
copyResulEls.push(resultEls[counter]);
}
}
}
}
}
/**
* This fn create sorted van dealer list
* @method createVanDealerSortedList
* @for TicketAdministration
*/
function createVanDealerSortedList() {
//Sort our Array according to the duration values in ascending order. [See: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more reference]
copyResulEls.sort(function (a, b) {
var reg = new RegExp('^[0-9]+$');
if (a.status == "OK" && b.status == "OK") {
var k1 = a.duration.value;
var k2 = b.duration.value;
if (reg.test(k1) == true && reg.test(k2) == true) {
if (k1 > k2) {
return 1;
} else {
return -1;
}
}
}
else {
return -1;
}
return 0;
});
console.log("copyResulEls", copyResulEls);
$("#tableVansDealers").html('');
//var to hold table String to show in dialog-form
var trString = '';
//Loop through of array length of copyResulEls
for (var i = 0; i < copyResulEls.length; i++) {
//if i===0, add html for table.
if (copyResulEls[i].status == "OK") {
var markerIcon;
if (i === 0) {
trString += '<table id="displayVansDealersTable" class="modalTable"><thead><tr><th>S. No.</th><th>Van/Dealer</th><th style="display:none;">Van/Dealer Id</th><th>Van/Dealer Name</th><th style="width:25%;">Van/Dealer Location</th><th>Distance</th><th>Duration</th><th>No. of Open Tickets</th><th>Remaining Time(in mins)</th><th>Is Connected</th><th>Dealer Scode</th><th>Contact No.</th><th ></th></tr></thead><tbody>';
}
//add each row
trString += '<tr id="' + copyResulEls[i].vanDealerID + '"><td style="box-shadow: 4px 0px 0px ' + copyResulEls[i].backgroundColor + ' inset;" >' + (i + 1) + '</td><td >' + copyResulEls[i].type + '</td><td style="display:none;">' + copyResulEls[i].vanDealerID + '</td><td>' + copyResulEls[i].name + '</td><td>' + copyResulEls[i].vanDealerAddress + '</td><td>' + copyResulEls[i].distance.text + '</td><td>' + copyResulEls[i].duration.text + '</td><td>' + copyResulEls[i].assignedTicketsToVanDealer + '</td><td>' + copyResulEls[i].remainingTime + '</td><td><span class="' + copyResulEls[i].deviceStatus + '"></span></td><td >' + copyResulEls[i].DealerSCode + '</td><td >' + copyResulEls[i].DealerOrVanContactNo + '</td><td><button class="button_blue" value="Assign" style="width:auto;" onclick="checkIfAssignToDealer(' + i + ', this);">Assign</button></td></tr>';
//if i===2, end table tag.
if (i === copyResulEls.length) {
$("#tableVansDealers").append('</tbody></table>');
}
//add content to info window
var description = '<div id="divInfoWindow">' +
'<div class="">' +
' <div class="">' +
'<h2 class="EngName_heading"><span id="spanVanDealerName">' + copyResulEls[i].name + '</span></h2>' +
'<table width="100%" cellpadding="0" cellspacing="0" class="InfoWindowTbl">' +
'<tbody>' +
'<tr>' +
'<td class=""><span>Van/Dealer Location</span></td><td colspan="5"><span id="spanVanDealerLocation">' + copyResulEls[i].vanDealerAddress + '</span>' +
'</td></tr><tr><td><span>Distance</span></td> <td> <span id="spanVanDealerDistance">' + copyResulEls[i].distance.text + '</span></td><td><span>Duration</span> </td><td><span id="spanVanDealerDuration">' + copyResulEls[i].duration.text + '</span>' +
'</td><td class=""> <span>No. of Open Tickets</span> </td> <td> <span id="spanNoOfAssignedTickets">' + copyResulEls[i].assignedTicketsToVanDealer + '</span></td></tr></tbody></table></div></div></div>';
if (copyResulEls[i].type == "dealer") {
markerIcon = dealerMarker;
}
else {
if (copyResulEls[i].backgroundColor == 'green') {
markerIcon = availableVansMarkers;
} else {
markerIcon = unavailableVansMarkers;
}
}
var vanDealerLatlng = new google.maps.LatLng(copyResulEls[i].lat, copyResulEls[i].lng);
//create marker at position
createMarker(vanDealerLatlng, markerIcon, copyResulEls[i].vanDealerID, description, ccplMap);
}
}
var _bounds = new google.maps.LatLngBounds();
for (var count = 0; count < nearestVansDealersMarks.length; count++) {
_bounds.extend(nearestVansDealersMarks[count].position);
}
ccplMap.fitBounds(_bounds);
//Append the trString created in the dialog-form
$("#tableVansDealers").append(trString);
$("#divVanDealerList").css('display', 'inline-block');
$("#divMap").css('height', '60%');
$("#displayVansDealersTable > tbody > tr").click(function (e) {
var rowId = e.currentTarget.id;
if (infowindow) {
infowindow.close();
}
$("#displayVansDealersTable").find('tr').removeClass('showMarked');
$("#displayVansDealersTable").find('tr[id=' + rowId + ']').addClass('showMarked');
var selectedVanDealerLat, selectedVanDealerLng, vehicleLatLng, selectedVanDealerLatLng, selectedVanDealerType;
var selectedVanDealerId = e.currentTarget.id;
for (var counter = 0; counter < nearestVansDealersMarks.length; counter++) {
if (nearestVansDealersMarks[counter].customInfo == selectedVanDealerId) {
stopMarkerBounce();
getMarkerBounce(nearestVansDealersMarks[counter]);
}
}
for (var count = 0; count < copyResulEls.length; count++) {
if (copyResulEls[count].vanDealerID == selectedVanDealerId) {
selectedVanDealerLat = copyResulEls[count].lat;
selectedVanDealerLng = copyResulEls[count].lng;
selectedVanDealerType = copyResulEls[count].type;
}
}
vehicleLatLng = breakdownLocationLatLng;
selectedVanDealerLatLng = new google.maps.LatLng(selectedVanDealerLat, selectedVanDealerLng);
//calcRoute(vehicleLatLng, selectedVanDealerLatLng, selectedVanDealerType, ccplMap, []);
});
//start marker bounce
function getMarkerBounce(vanDealerMarker) {
if (vanDealerMarker.getAnimation() != null) {
vanDealerMarker.setAnimation(null);
} else {
vanDealerMarker.setAnimation(google.maps.Animation.BOUNCE);
}
}
//stop marker bounce
function stopMarkerBounce() {
for (var count = 0; count < nearestVansDealersMarks.length; count++) {
if (nearestVansDealersMarks[count].getAnimation() != null) {
nearestVansDealersMarks[count].setAnimation(null);
}
}
}
}
//=================================== end calculate distance =======================================//
//===========================================Click Events =========================================//
/**
* This fn binds Click Event to the Map when adding New Vehicle to location Vehicle Location.
* @method bindClickEventToMap
* @for TicketAdministration
*/
function bindClickEventToMap() {
console.log("map click event");
//Remove Source Destination Direction Display if visible as well as Remove Previous Markers if any Present
if (displayDisplay) {
//Remove previous markers
removeTicketDetailsMarkerArray();
//Remove direction display
displayDisplay.setMap(null);
}
//Remove any previous Click Listener on Map if any present.
removeClickEventToMap();
//Bind click listener on Map
google.maps.event.addListener(ccplMap, 'click', function (e) {
//Remove previous marker if present
if (marker) {
marker.setMap(null);
//set address text field empty here
marker = "";
}
if (displayDisplay) {
//Remove direction display
displayDisplay.setMap(null);
}
if (nearestVansDealersMarks.length > 0) {
for (var counter = 0; counter < nearestVansDealersMarks.length; counter++) {
nearestVansDealersMarks[counter].setMap(null);
//set address text field empty here
nearestVansDealersMarks[counter] = "";
}
nearestVansDealersMarks = [];
}
//remove place location marker array
removePlaceLocationMarkerArray();
//Create a new Marker on the position click on the map
marker = new google.maps.Marker({
position: e.latLng,
map: ccplMap
});
breakdownLocationLatLng = e.latLng;
console.log(breakdownLocationLatLng);
//Get address of the Lat Long click clicked
var latLngAddress = getReverseGeoCode(e.latLng, function (data) {
console.log("Location")
console.log(data)
//Here we got the address of the point clicked. Update this value to the form textbox.
$("#eos_exact_location").val("");
$("#eos_exact_location").val(data.formattedAddress);
$("#searchLocationTool").val(data.formattedAddress);
geoCodeState = data.state;
});
});
}
/**
* This fn removes Click Event Listener from the map
* @method removeClickEventToMap
* @for TicketAdministration
*/
function removeClickEventToMap() {
google.maps.event.clearListeners(ccplMap, 'click');
if (marker) {
marker.setMap(null);
marker = "";
}
}
//===================================================== end ==========================================//
//======================================================================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 TicketAdministration
*/
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
//console.log(status);
if (status == google.maps.GeocoderStatus.OK) {
console.log("testtttttt");
console.log(results[0]);
//Find most intensive search result and callback it
if (results[0]) {
var storableLocation = {};
for (var ac = 0; ac < results[0].address_components.length; ac++) {
var component = results[0].address_components[ac];
if (component.types.includes('administrative_area_level_1')) {
storableLocation.state = component.long_name;
storableLocation.formattedAddress = results[0].formatted_address;
// console.log(storableLocation)
callback(storableLocation)
}
}
// callback(results[0].formatted_address);
//Else callback no result found
} else {
callback('No results found');
}
}
else { callback('NA'); }
return 'NA';
});
}
/**
* This function set center and zoom of map when state or city change
* @method setMapCenterToAddress
* @param {String} address address to show on map
* @for TicketAdministration
*/
function setMapCenterToAddress(address) {
geoCoder = new google.maps.Geocoder();
geoCoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
ccplMap.setCenter(results[0].geometry.location);
if (typeof results[0].geometry.bounds !== 'undefined') {
ccplMap.fitBounds(results[0].geometry.bounds);
}
}
});
}
/**
* This function call on change of city ame
* @method onBlurCity
* @param {String} $this id of input text box
* @for TicketAdministration
*/
function onBlurCity($this) {
var id = $this;
//var cityName = $("#eos_city").data("kendoComboBox").text();
var cityName = $("#eos_city").val();
// will check
setMapCenterToAddress($('#eos_state').find('option:selected').text() + ", " + cityName);
}
//Global array to allow some special keys
var specialKeys = new Array();
specialKeys.push(8);//Backspace
specialKeys.push(13);//enter
//specialKeys.push(46);//dot
/**
* function to validate if ticket id is numeric or not
*/
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
//document.getElementById("error").style.display = ret ? "none" : "inline";
document.getElementById("spanOdometerReading").style.display = ret ? "none" : "inline";
return ret;
}
/**
* function to validate if reg no is alphanumeric or not
*/
function IsAlphaNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("errorRegNo").style.display = ret ? "none" : "inline";
return ret;
}
/**
* function to validate if complaint no. is in correct format or not
*/
function IsTicketFormat() {
if ($("#ComplaintNo").val() != "") {
//console.log(e);
// var regex = /[A-Z]{1}[0-9]{1}[A-Z]{1}[0-9]{10}/g;
var regex = /[a-zA-Z0-9]{12,13}/g;
var ticketFormat = $("#ComplaintNo").val();
var matchFormat = regex.test($("#ComplaintNo").val());
if (matchFormat) {
//console.log(matchFormat);
return matchFormat;
} else {
$("#ComplaintNo").val("");
//console.log(matchFormat);
return matchFormat;
}
}
}
/**
* function to validate if reg no is in correct format or not
*/
function IsRegistrationNoFormat() {
if ($("#RegistrationNo").val() != "") {
var regex1 = /[a-zA-Z]{2}[-][a-zA-Z0-9]{2}[-][a-zA-Z]{2}[-][0-9]{4,5}/g;
var regex2 = /[a-zA-Z]{2}[-][0-9]{4,5}/g;
var regex3 = /[a-zA-Z]{2}[-][a-zA-Z0-9]{2}[-][-][0-9]{4,5}/g;
var lengthRegNo = $("#RegistrationNo").val().replace(/-/g, "").length;
if (lengthRegNo == 11 || lengthRegNo == 10 || lengthRegNo == 6 || lengthRegNo == 7 || lengthRegNo == 8 || lengthRegNo == 9) {
//var match = ($("#RegistrationNo").val()).match(regex);
var match1 = regex1.test($("#RegistrationNo").val());
var match2 = regex2.test($("#RegistrationNo").val());
var match3 = regex3.test($("#RegistrationNo").val());
if (match1 || match2 || match3) {
//document.getElementById('button_search').click();
return true;
} else {
$("#RegistrationNo").val("");
jAlert("Please insert correct Registration No.!!", "Warning");
return false;
}
} else {
$("#RegistrationNo").val("");
jAlert("Please insert correct Registration No.!!", "Warning");
return false;
}
}
}
/**
* function to validate if ticket id is float or not
*/
function IsFloat(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 46) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
/**
* This function call on change of route name
* @method onChangeRoute
* @for TicketAdministration
*/
function onChangeRoute() {
var NH_ID = $("#routes").val();
var NH_PATH = HIGHWAY_PATH[NH_ID];
//console.log(NH_PATH);
// drawHighway(NH_PATH.source, NH_PATH.destination, "", ccplMap, NH_PATH.wayPoints, NH_PATH.color);
}
//============================== add KAM ticket ===============================
/**
* This function is called to get KAM ticket details
* @method getKamOpenTicketDetails
* @param {String} kamVehicleRegistrationNo Breakdown Vehicle Registration no. for KAM ticket
* @for TicketAdministration
*/
function getKamOpenTicketDetails(kamVehicleRegistrationNo) {
// alert("get kam")
console.log("getKamOpenTicketDetails=== here check state value")
$.ajax({
type: "POST",
url: "/Ticket/GetKamTicketDetails/",
data: { kamTicketId: selectedKamTicket },
success: function (data) {
if (data.success == true) {
var userLanguage = '',
sourceOfTollFree = '',
driverName = '',
driverContact = '',
state = '',
nearestCity = '',
locationBreakdown = '',
landmarkLocation = '',
routeId = '',
loadCarryingType = '',
vehicleDirection = '',
vehicleTravelledDistance = '',
warranty = '',
problemnature = '',
breakdownLocationLat = '',
breakdownLocationLng = '',
breakdownLattitudeLongitude = '';
//alert(data.kamTicketDetails.Warrenty);
userLanguage = data.kamTicketDetails.CallerLanguage;
sourceOfTollFree = data.kamTicketDetails.TollFreeNoSource;
driverName = data.kamTicketDetails.CustomerCustomerName;
driverContact = data.kamTicketDetails.CustomerContactNo;
state = data.kamTicketDetails.BreakdownLocationState;
nearestCity = data.kamTicketDetails.BreakdownLocationCity;
locationBreakdown = data.kamTicketDetails.BreakdownLocation;
landmarkLocation = data.kamTicketDetails.BreakdownLocationLandmark;
routeId = data.kamTicketDetails.RouteId;
loadCarryingType = data.kamTicketDetails.DefaultCol2;
vehicleDirection = data.kamTicketDetails.DefaultCol3;
vehicleTravelledDistance = data.kamTicketDetails.KmCovered;
warranty = data.kamTicketDetails.Warrenty;
problemnature = data.kamTicketDetails.Description;
breakdownLocationLat = data.kamTicketDetails.BreakdownLattitude;
breakdownLocationLng = data.kamTicketDetails.BreakdownLongitude;
breakdownLattitudeLongitude = new google.maps.LatLng(breakdownLocationLat, breakdownLocationLng);
//bind values to text boxes
$("#vehicle_owner_language").val(userLanguage);
$("#tollFreeNoSource").val(sourceOfTollFree);
$("#driver_name").val(driverName);
$("#driver_contact_no").val(driverContact);
// will check
$("#eos_state").val(state);
$("#eos_city").val(nearestCity);
$("#eos_exact_location").val(locationBreakdown);
$("#searchLocationTool").val(locationBreakdown);
$("#breakdown_landmark").val(landmarkLocation);
$("#routes").val(routeId);
$("#vehicle_type_of_load").val(loadCarryingType);
$("#vehicle_direction").val(vehicleDirection);
$("#totalKmCovered").val(vehicleTravelledDistance);
$("#isVehicleInWarrentyOrAmc").val(warranty);
$("#nature_of_problem").val(problemnature);
marker = new google.maps.Marker({
position: breakdownLattitudeLongitude,
map: ccplMap
});
breakdownLocationLatLng = breakdownLattitudeLongitude;
var bounds = new google.maps.LatLngBounds();
bounds.extend(breakdownLocationLatLng);
ccplMap.fitBounds(bounds);
}
},
complete: function (data) {
$("#div_loading").hide();
},
error: function (data) {
console.log(data);
}
});
}
//============================= end KAM ================================
//================================ show vans on change state while creating ticket =======================//
function onStateChange() {
// will check
var stateName = $('#eos_state').find('option:selected').text();
setMapCenterToAddress(stateName);
//getVansDealersStateWise();
LoadCityListOnStateChange();
}
//function getVansDealersStateWise() {
// debugger
// console.log("getVansDealersStateWise");
// //alert();
// $("#displayVansDealersTable").html('');
// $("#displayVansDealersTable").html("Please click on GET ALL VANS button.")
// //empty van dealer lat lng array
// if (vanDealerLatLngArr.length > 0) {
// vanDealerLatLngArr = [];
// }
// //empty details list of van dealer array
// if (detailsListOfVanDealer.length > 0) {
// detailsListOfVanDealer = [];
// }
// //remove path between 2 markers
// if (displayDisplay) {
// //Remove direction display
// displayDisplay.setMap(null);
// }
// removeTicketDetailsMarkerArray();
// //loop through arary
// for (var i = 0; i < nearestVansDealersMarks.length; i++) {
// //set marker map to null
// nearestVansDealersMarks[i].setMap(null);
// }
// //empty array
// nearestVansDealersMarks = [];
// var stateName1, stateName2, stateId, vanDealerLatlng, type, VDId, vanDealerLat, vanDealerLng, vanDealerCity, vanDealerName, vanDealerState,
// deviceAlias, vanRemainingTime, deviceStatus, noOfAssignedTickets, description, detailsListOfVanDealer_alias = [], vanDealerLatLngArr_alias = [], DealerSCode, DealerOrVanContactNo;
// //stateName = $('#eos_state').find('option:selected').text();
// //stateId = $('#eos_state').find('option:selected').val();
// // =========== new =====================
// var stateMultiselect = $("#eos_state").data("kendoMultiSelect").dataItems();
// if (stateMultiselect != "" && stateMultiselect != null && stateMultiselect.length > 0) {
// stateName1 = stateMultiselect[0].text;
// stateName2 = stateMultiselect.length > 1 ? stateMultiselect[1].text : "";
// }
// if (xhr_getAllVans && xhr_getAllVans.readystate != 4) {
// xhr_getAllVans.abort();
// }
// xhr_getAllVans = $.ajax({
// type: "GET",
// url: "/Ticket/GetVansDealersbyStates/",
// data: { StateName: stateName1, limit: _LIMIT, StateName2: stateName2 },
// success: function (data) {
// console.log("success GetAllNearestVansDealers");
// if (data.NearestVansDealers.length > 0) {
// vanDealerLatLngArr.length = 0;
// for (var counter = 0; counter < data.NearestVansDealers.length; counter++) {
// var title, markerIcon, backgroundColor;
// var updatedDeviceStatus = "";
// var vanDealerObj = {};
// vanDealerLatlng = new google.maps.LatLng(data.NearestVansDealers[counter].DealerVanLattitude, data.NearestVansDealers[counter].DealerVanLongitude);
// type = data.NearestVansDealers[counter].Type;
// VDId = data.NearestVansDealers[counter].DealerVanId;
// vanDealerLat = data.NearestVansDealers[counter].DealerVanLattitude;
// vanDealerLng = data.NearestVansDealers[counter].DealerVanLongitude;
// vanDealerCity = data.NearestVansDealers[counter].DealerVanCity;
// noOfAssignedTickets = data.NearestVansDealers[counter].NoOfAssignedTicket;
// vanDealerName = data.NearestVansDealers[counter].DealerVanName;
// vanDealerState = data.NearestVansDealers[counter].DealerVanState;
// deviceAlias = data.NearestVansDealers[counter].DeviceAlias;
// vanRemainingTime = data.NearestVansDealers[counter].RemainingTime;
// deviceStatus = data.NearestVansDealers[counter].DeviceStatus;
// DealerSCode = data.NearestVansDealers[counter].DealerSCode;
// DealerOrVanContactNo = data.NearestVansDealers[counter].DealerOrVanContactNo;
// //check if remaining time is negative
// if (vanRemainingTime == null || vanRemainingTime == "") {
// vanRemainingTime = "0";
// }
// else {
// if (vanRemainingTime.indexOf('-') === -1) {
// vanRemainingTime = vanRemainingTime;
// } else {
// vanRemainingTime = "0";
// }
// }
// //push van dealer lat lng in array
// vanDealerLatLngArr_alias.push(vanDealerLatlng);
// console.log("type : " + type);
// //bind van / dealer details in object
// vanDealerObj.type = type;
// vanDealerObj.id = VDId;
// vanDealerObj.lat = vanDealerLat;
// vanDealerObj.lng = vanDealerLng;
// vanDealerObj.city = vanDealerCity;
// vanDealerObj.assignedTickets = noOfAssignedTickets;
// vanDealerObj.name = vanDealerName;
// vanDealerObj.state = vanDealerState;
// vanDealerObj.alias = deviceAlias;
// vanDealerObj.remainingTime = vanRemainingTime;
// vanDealerObj.deviceStatus = updatedDeviceStatus;
// vanDealerObj.backGroundColor = backgroundColor;
// vanDealerObj.DealerSCode = DealerSCode;
// vanDealerObj.DealerOrVanContactNo = DealerOrVanContactNo;
// //Get address of the Lat Long click clicked
// //getReverseGeoCode(vanDealerLatlng, function (data) {
// //push van dealer details in array
// detailsListOfVanDealer_alias.push(vanDealerObj);
// getReverseGeoCode(vanDealerLatlng, function (data) {
// title = data.formattedAddress;
// });
// }
// var forLoopLength, multiplier = 100, waitIndex = 0, setTimeOutSeconds = 0;
// var vanDealerLatLngArrLength = vanDealerLatLngArr_alias.length;
// //check if breakdown location is marked or not
// if (vanDealerLatLngArrLength < 15 && vanDealerLatLngArrLength > 0) {
// forLoopLength = 1;
// } else {
// if ((vanDealerLatLngArrLength % 15) > 0) {
// forLoopLength = parseInt((vanDealerLatLngArrLength / 15), 10) + 1;
// } else if ((vanDealerLatLngArrLength % 15) == 0) {
// forLoopLength = parseInt((vanDealerLatLngArrLength / 15), 10);
// }
// }
// var z;
// if (forLoopLength == 1) {
// for (var i = 0; i < vanDealerLatLngArrLength; i++) {
// if (detailsListOfVanDealer_alias[i].type == "van") { markerIcon = availableVansMarkers; }
// else if (detailsListOfVanDealer_alias[i].type == "dealer") {
// markerIcon = dealerMarker;
// }
// createMarkerVanDealer(vanDealerLatLngArr_alias[i], markerIcon, title);
// }
// } else {
// for (var i = 0; i < forLoopLength; i++) {
// setTimeOutSeconds = waitIndex * multiplier;
// if (vanDealerLatLngArrLength < 15) { z = 0; } else { z = vanDealerLatLngArrLength - 15; }
// for (var j = vanDealerLatLngArrLength; j > z; j--) {
// if (detailsListOfVanDealer_alias[j - 1].type == "van") { markerIcon = availableVansMarkers; }
// else if (detailsListOfVanDealer_alias[j - 1].type == "dealer") {
// markerIcon = dealerMarker;
// }
// createMarkerVanDealer(vanDealerLatLngArr_alias[j - 1], markerIcon, title);
// }
// vanDealerLatLngArrLength = vanDealerLatLngArrLength - 15;
// waitIndex++;
// }
// }
// }
// else {
// jAlert(CREATE_TICKET_MESSAGES.vanDealerUnavailable, 'Message', function () {
// $("#divVanDealerList").css('display', 'none');
// $("#divMap").css('height', '');
// });
// }
// },
// error: function (data) {
// console.log("error");
// console.log(data);
// }
// });
//}
//=========================================== end ========================================================//
//=============================== Save Ticket Details Functionality =============================//
/**
* This function is called to get KAM ticket details
* @method getKamOpenTicketDetails
* @param {String} kamVehicleRegistrationNo Breakdown Vehicle Registration no. for KAM ticket
* @for TicketAdministration
*/
function getSaveTicketDetails() {
console.log(saveTicketsList[0]);
var userLanguage = '',
sourceOfTollFree = '',
driverName = '',
driverContact = '',
state = '',
nearestCity = '',
locationBreakdown = '',
landmarkLocation = '',
routeId = '',
loadCarryingType = '',
vehicleDirection = '',
vehicleTravelledDistance = '',
warranty = '',
problemnature = '',
breakdownLocationLat = '',
breakdownLocationLng = '',
breakdownLattitudeLongitude = '';
if (breakdownLocationLat && breakdownLocationLng)
breakdownLattitudeLongitude = new google.maps.LatLng(breakdownLocationLat, breakdownLocationLng);
//bind values to text boxes
$("#vehicle_owner_language").val(userLanguage);
$("#tollFreeNoSource").val(sourceOfTollFree);
$("#driver_name").val(driverName);
$("#driver_contact_no").val(driverContact);
$("#eos_state").data("kendoMultiSelect").value(state)
//$("#eos_state").val(geoCodeState);
$("#eos_exact_location").val(locationBreakdown);
$("#searchLocationTool").val(locationBreakdown);
$("#breakdown_landmark").val(landmarkLocation);
$("#routes").val(routeId);
$("#vehicle_type_of_load").val(loadCarryingType);
$("#vehicle_direction").val(vehicleDirection);
$("#totalKmCovered").val(vehicleTravelledDistance);
$("#isVehicleInWarrentyOrAmc").val(warranty);
$("#nature_of_problem").val(problemnature);
if (breakdownLocationLat && breakdownLocationLng) {
marker = new google.maps.Marker({
position: breakdownLattitudeLongitude,
map: ccplMap
});
breakdownLocationLatLng = breakdownLattitudeLongitude;
var bounds = new google.maps.LatLngBounds();
bounds.extend(breakdownLocationLatLng);
ccplMap.fitBounds(bounds);
}
setTimeout(function () {
if (state != null && state != "") {
onStateChange();
setTimeout(function () {
if (typeof $("#eos_city").data('kendoComboBox') != "undefined") {
$("#eos_city").data('kendoComboBox').value(nearestCity);
} else {
$("#eos_city").val(nearestCity);
}
}, 1000);
}
if (routeId != null && routeId != "") {
onChangeRoute();
}
}, 500);
}
function assignPendingTicket() {
$("#div_loading").show();
addNewTicket();
setTimeout(function () {
if (saveTicketsList.length > 0) {
getSaveTicketDetails();
}
$("#div_loading").hide();
}, 10000);
}
function saveTicketDetails() {
var TicketModel = {}, vehicleRegistrationNo = "";
if (getParameterByName("vRegistrationNo").trim().toLowerCase() == $("#vehicle_registration").val().trim().toLowerCase()) {
TicketModel.CreatedBy = selectedKamNotification;
} else { TicketModel.CreatedBy = ""; }
TicketModel.TicketId = "";
TicketModel.Description = $("#nature_of_problem").val();
TicketModel.listDescription = {};
TicketModel.AssignedTo = "";
TicketModel.ReportedVia = "";
TicketModel.TicketStatus = null;
TicketModel.OtherRemarks = null;
TicketModel.Priority = 1;
TicketModel.CustomerScore = "";
TicketModel.CreationTime = "";
TicketModel.LastModifiedBy = "";
TicketModel.LastModifiedTime = "";
TicketModel.BreakdownLocation = $("#eos_exact_location").val();
if (breakdownLocationLatLng) {
TicketModel.BreakdownLongitude = breakdownLocationLatLng.lng();
TicketModel.BreakdownLattitude = breakdownLocationLatLng.lat();
} else {
TicketModel.BreakdownLongitude = '';
TicketModel.BreakdownLattitude = '';
}
TicketModel.AssignedToUserId = "";
TicketModel.AssignedToUserLattitude = "";
TicketModel.AssignedToUserLongitude = "";
TicketModel.Isdeclined = false;
TicketModel.EstimatedTimeForJobCompletion = "";
TicketModel.TotalTicketLifecycleTimeSla = "";
TicketModel.EstimatedTimeForJobCompletionSubmitTime = "";
TicketModel.VehicleRegisterNumber = $("#vehicle_registration").val();
vehicleRegistrationNo = $("#vehicle_registration").val();
TicketModel.BreakdownLocationLandmark = $("#breakdown_landmark").val();
TicketModel.RouteId = ($("#routes").val() == "") ? "" : parseInt($("#routes").val(), 10);
TicketModel.CustomerContactNo = $("#driver_contact_no").val();
TicketModel.TicketStatusAlias = "";
TicketModel.Token = "";
TicketModel.Status = "";
TicketModel.Message = "";
TicketModel.UtcMinute = 0;
TicketModel.RepairCost = "";
TicketModel.SlaMissedReason = "";
TicketModel.SuggestionComment = "";
TicketModel.JobCompleteResponseTime = "";
TicketModel.DefaultCol2 = $("#vehicle_type_of_load").val();
TicketModel.DefaultCol3 = $("#vehicle_direction").val();
//TicketModel.StateName = ($('#eos_state').val() == "") ? "" : $('#eos_state').find('option:selected').text();
// will check
var stateMultiselect = $("#eos_state").data("kendoMultiSelect").dataItems();
TicketModel.StateName = (stateMultiselect != "" && stateMultiselect != null && stateMultiselect.length > 0) ? stateMultiselect[0].value : null;
//TicketModel.StateName = ($('#eos_state').val() == "") ? null : $('#eos_state').val();
TicketModel.CityName = $("#eos_city").val();
TicketModel.CallerLanguage = ($('#vehicle_owner_language').val() == "") ? "" : $('#vehicle_owner_language').find('option:selected').text();
TicketModel.KmCovered = $('#totalKmCovered').val();
TicketModel.Warranty = ($('#isVehicleInWarrentyOrAmc').val() == "") ? "" : $('#isVehicleInWarrentyOrAmc').find('option:selected').text();
TicketModel.TollFreeeNoSource = ($('#tollFreeNoSource').val() == "") ? "" : $('#tollFreeNoSource').find('option:selected').text();
TicketModel.VehicleTagging = $("#vehicle_product_varient").val();
$.ajax({
type: "POST",
url: "/Ticket/TicketAdministration_SaveTicket/",
data: TicketModel,
success: function (data) {
console.log(data);
if (data.success == true) {
jAlert(data.successMessage, 'Message', function () {
var url = globalHostAddress + "Ticket/TicketAdministration";
window.open(url, '_self');
});
}
else {
//console.log(data);
jAlert(data.message, 'Message', function () {
btnCancel();
});
}
},
complete: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
}
function chkBoxSameasCustomerChange() {
$("#CustomerMobileNumber1").val($("#CustomerOwnerMobileNo1").val());
$("#CustomerCustomerName").val($("#CustomerOwnerName").val());
$("#CustomerEmailId").val($("#CustomerOwnerEmailId").val());
//$("#CustomerCustomerName").val($("#CustomerOwnerAddress").val());
$("#CustomerAddress").val($("#CustomerOwnerAddress").val());
var dd = document.getElementById('ddOwnerState');
var ddCustomerState = document.getElementById('ddCustomerState');
var ddOwnerCity = document.getElementById('ddOwnerCity');
$("#ddCustomerState option").each(function () {
if ($(this).val() == dd.value) {
$(this).attr('selected', 'selected');
LoadCityList("ddCustomerState", dd.value);
setTimeout(function () {
$("#ddCustomerCity option").each(function () {
if ($(this).val() == ddOwnerCity.value) {
$(this).attr('selected', 'selected');
}
});
}, 3000);
}
});
//for (var i = 0; i < ddCustomerState.options.length; i++) {
// console.log(ddCustomerState.options[i].val);
// if (ddCustomerState.options[i].val === dd.value) {
// ddCustomerState.selectedIndex = i;
// break;
// }
//}
setTimeout(function () {
$("#ddCustomerCity").val($("#ddOwnerCity").val());
}, 2000);
setTimeout(function () {
$("#ddCustomerCity").val($("#ddOwnerCity").val());
}, 2000);
}
//=============================== End of Save Ticket Details Functionality =====================//
//============================================ document ready function ======================================== //
$(document).ready(function () {
// $("#searchLocationTool").hide();
selectedTicket = getParameterByName("complaintNo");
selectedVehicle = getParameterByName("vRegistrationNo"); // get vehicle registration no. for kam ticket
selectedKamTicket = getParameterByName("KamComplaintNo"); // get kam ticket/complaint no. for kam ticket
selectedKamNotification = getParameterByName("Notification"); // get notification id for kam ticket
editTicketFeedback = getParameterByName("feedback"); // get parameter while redirecting from ticket report to edit feedback
selectedTicketType = getParameterByName("TicketType"); // get ticket type for dummy ticket
if (selectedTicket != "" || selectedVehicle != "") {
getTicketHistory();
} else { }
$("#tabCheckHistory").addClass('ActiveTab');
$("#div_loading").hide();
//drawSticeMap("staticMapImgUrl", "1000", "800")
// drawSticeMapForDelaerTicketAdministration("staticMapImgUrl", "1000", "800")
//setTimeout(function () {
// initMap("divMapContainer");
//}, 1);
addKendoWindow("#divAddCustomer", "Add Customer", "1000px", 340, 120);
addKendoWindow("#divAddCustomerForExistingVehicle", "Add Customer", "1000px", 340, 120);
addKendoWindow("#divReassignTicket", "Reassign Ticket", "1000px", 150, 120);
addKendoWindow("#divUpdateFeedback", "Edit Feedback", "1000px", 340, 180);
addKendoWindow("#divReasonForTicketAssignToDealer", "Reason for assign ticket to Dealer", "460px", 150, 120);
addKendoWindow("#divReasonForTicketReAssignToDealer", "Reason for Re-assign ticket to Dealer", "460px", 150, 120);
//addKendoWindow("#divReasonForTicketReAssignToDealer", "Reason for Re-assign ticket to Dealer", "1000px", 100, 80);
$("#divAddCustomer").parent().addClass("Cust_Window");
$("#divAddCustomerForExistingVehicle").parent().addClass("Cust_Window");
$("#divReassignTicket").parent().addClass("ReAssign_Window");
$('#textBoxDescription').on('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
onGoogleSearch();
});
function refreshtab() {
_assignedTo = 'dealer';
$.ajax({
type: "POST",
url: "/TicketAdministration_Dealer/TicketAdministrationDealer_GetTicketHistory/",
data: { assignedToType: _assignedTo },
success: function (data) {
// console.log(data);
if (data) {
$("#divDealerOpenCloseTickets").html("");
$("#divDealerOpenCloseTickets").html(data);
$("#divMapDetail").removeClass("display_none");
}
},
error: function (data) {
console.log(data);
}
});
}
//=================================================Calling Method of Here API
function GetDataHerefromAPI(method, url) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
if ("withCredentials" in xhr) {
xhr.open(method, url, false);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function drawSticeMapForDelaerTicketAdministration(id, width, height) {
$("#" + id).attr("src", "");
//$("#" + id).attr("src", "https://maps.googleapis.com/maps/api/staticmap?center=26.9124,75.7873&zoom=12&size=" + width + "x" + height + "&key=" + MAP_KEY)
$("#" + id).attr("src", "https://image.maps.ls.hereapi.com/mia/1.6/mapview?apiKey=DW3-YCFFZtJzlAQpTfVPoXADcZpEeZe3t8h6ganVsqo&c=26.9124,75.7873&" + width + "x" + height + "&key=" + MAP_KEY)
}