<?php $__env->startSection('title'); ?> <?php echo e(Config::get('tripmanagement.title')); ?> <?php $__env->stopSection(); ?>
<?php $__env->startSection('body'); ?>

    <style type="text/css">
        .min-width-1000 {
            min-width: 1000px;
        }

        .route {
            padding-top: 20px;
            min-height: 200px;
            width: 100%;
        }

        .route .input-group {
            width: 100%;
        }

        .route .col-xs-3 {
            padding-right: 0px !important;
            padding-left: 0px !important;
        }

        .route .direction {
            width: 60px;
            background-color: inherit;
            border: none;
        }
    </style>
    
    <div class="row min-width-1000">
        <div class="col-xs-4">
            <div class="form-group">
                <label class="control-label"></label>
                <select class="form-control tripsList">
                    <option value="">Please select a trip</option>
                </select>
            </div>
        </div>
        <div class="col-xs-4">
            <div class="form-group">
                <label class="control-label"></label>
                <select class="form-control vehiclesList" id="vehiclesList">
                    <option value="">Please select a vehicle</option>
                </select>
            </div>
        </div>
    </div>
    <div class="row min-width-1000">
        <div class="col-md-12">
            <div class="img-thumbnail form-group route">
                -- no drop points to be loaded --
            </div>
        </div>
    </div>
    <style type="text/css">
        .controls {
            margin-bottom: 0px;
            padding-right: 110px;
            height: 30px;
            position: relative;
        }

        .controls .controlsWrapper {
            position: absolute;
            right: 0px;
        }

        .controls .segmentTitle {
            width: 100%;
            height: 100%;
        }

    </style>
    <div class="row min-width-1000">
        <div class="col-xs-8">
            <div class="form-group controls">
                <div class="controlsWrapper" id="controlsWrapper" style="display: none;">
                    <button class="btn btn-sm btn-info" id="edit" style="display: none;">Edit</button>
                    <button class="btn btn-sm btn-success" id="done" style="display: none;">Done</button>
                    <button class="btn btn-sm btn-danger" id="reset">Reset</button>
                </div>
                <div class="img-thumbnail segmentTitle" id="segmentTitle" style="display: none;"></div>
            </div>
            <div class="img-thumbnail form-group" id="map" style="width: 100% !important; height: 400px !important;">
            </div>
        </div>

        <style type="text/css">
            .tripSummary th, .segmentSummary th {
                width: 120px;
            }
        </style>
        <div class="col-xs-4">
            <div class="form-group" style="margin-top: 30px;">
                <div class="table-responsive">
                    <table class="table table-bordered table-condensed tripSummary" style="margin-bottom: 0px;">
                        <thead>
                        <tr>
                            <td colspan="2" class="text-center"><b>Trip Summary</b></td>
                        </tr>
                        <tr>
                            <th>Total Distance</th>
                            <td id="tripDistance">0 km</td>
                        </tr>
                        <tr>
                            <th>Total cost</th>
                            <td id="tripCost">-</td>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
            <div class="form-group">
                <label class="label label-success summary_title"></label>
            </div>
            <div class="form-group">
                <div class="table-responsive">
                    <table class="table table-bordered table-condensed segmentSummary">
                        <thead>
                            <tr>
                                <td class="text-center" colspan="2"><b>Segment Summary</b></td>
                            </tr>
                            <tr>
                                <th>From</th>
                                <td id="segmentFrom"></td>
                            </tr>
                            <tr>
                                <th>To</th>
                                <td id="segmentTo"></td>
                            </tr>
                            <tr>
                                <th>Distance</th>
                                <td>
                                    <label style="margin: 0px;"><input type="text" id="segmentDistance" data-original=""><span style="display: inline;" class="btn-primary btn-xs fa fa-undo undoSegmentDistance" id="undoSegmentDistance"></span></label>
                                </td>
                            </tr>
                            <tr>
                                <th>Suggestions</th>
                                <td>
                                    <select style="width: 100%;" class="suggestions" id="suggestions"></select>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <div class="form-group" style="margin-bottom: 5px">
                                        <label class="control-label">Cost</label>
                                        <select class="form-control costScinarios" id="costScinarios">
                                            <option value="">Select a cost scinario</option>
                                        </select>
                                    </div>
                                    <div class="form-group costCategoriesWrapper" id="costCategoriesWrapper" style="margin-bottom: 5px; display: none; width: 100%;">
                                        <select class="form-control costCategories" id="costCategories">
                                            <option value="">Select a category</option>
                                        </select>
                                    </div>
                                    <div class="form-group" style="margin-bottom: 10px;">
                                        <input type="text" class="form-control cost" id="cost">
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <h4>Additional Payments</h4>
                                    <div class="img-thumbnail" style="width: 100%">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="control-label">Direct deliveries</label>
                                            </div>
                                            <div class="col-md-6">
                                                <input type="text" class="form-control ap_direct_deliveries" id="ap_direct_deliveries">
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="control-label">Offloading charges</label>
                                            </div>
                                            <div class="col-md-6">
                                                <input type="text" class="form-control ap_offloading_charges" id="ap_offloading_charges">
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="control-label">Demurrages</label>
                                            </div>
                                            <div class="col-md-6">
                                                <input type="text" class="form-control ap_demurrages" id="ap_demurrages">
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="control-label">Other</label>
                                            </div>
                                            <div class="col-md-6">
                                                <input type="text" class="form-control ap_other" id="ap_other">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <h4>Deductions</h4>
                                    <div class="img-thumbnail" style="width: 100%">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="control-label">Document errors</label>
                                            </div>
                                            <div class="col-md-6">
                                                <input type="text" class="form-control d_document_errors" id="d_document_errors">
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="control-label">Other</label>
                                            </div>
                                            <div class="col-md-6">
                                                <input type="text" class="form-control d_other" id="d_other">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group" style="margin-bottom: 0px;">
                                        <button class="btn btn-sm btn-primary pull-left saveSegment" id="saveSegment">Save</button>
                                    </div>
                                </td>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>



<?php $__env->stopSection(); ?>
<?php $__env->startSection('script'); ?>

    <script type="text/javascript">
        var map;
        var marker;
        var markers = [];//collection of marker instances
        var markerOptions = [];//details of individual markers ; position , title etc
        var directionsService;
        var collection = [];

        mapEnvironment('reset');

        function initMap(callback) {

            map = null;
            marker = null;
            markers = [];
            markerOptions = [];
            directionsService = null
            collection = [];

            var center = {lat: 7.641309304668609, lng: 80.6396484375};
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 8,
                center: center,
                streetViewControl: false
            });

            directionsService = new google.maps.DirectionsService();

            if (callback != undefined && typeof(callback) == 'function') {
                callback();
            }
        }

        // function addMarkerOptions(latlng, title, identifier_id, is_startingLocation){
        // 	markerOptions.push({position: latlng, title: title, identifier_id: identifier_id, is_startingLocation: is_startingLocation});
        // }

        // function addMarkers(){
        // 	markers = [];
        // 	for(var i = 0; i < markerOptions.length; i++){
        // 		markers.push(new google.maps.Marker(markerOptions[i]));
        // 	}
        // 	coupleMarkers();
        // }

        // function coupleMarkers(){
        // 	collection = [];
        // 	var size = markers.length;
        // 	for(var i = 0; i < markers.length; i++){
        // 		if((i+1) < size){
        // 			collection.push({
        // 				start: markers[i],
        // 				end: markers[i+1],
        // 				renderer: {},
        // 				polyline: {},
        // 				waypoints: []
        // 			});
        // 		}
        // 	}
        // }

        function addCouples(couple) {

            if (couple != undefined && typeof(couple) == 'object' && couple.hasOwnProperty('start') && couple.hasOwnProperty('end')) {

                var start = couple.start;
                var end = couple.end;

                var waypoints = JSON.parse(couple.waypoints);
                for (var i = 0; i < waypoints.length; i++) {
                    waypoints[i].stopover = false;
                }

                var cost = couple.cost;

                var start_latlng = JSON.parse(start.coordinates, function (k, v) {
                    return (typeof v === "object" || isNaN(v)) ? v : parseFloat(v);
                });
                var end_latlng = JSON.parse(end.coordinates, function (k, v) {
                    return (typeof v === "object" || isNaN(v)) ? v : parseFloat(v);
                });

                var startMarker = new google.maps.Marker({
                    position: start_latlng,
                    title: start.name,
                    identifier_id: start.id,
                    is_startingLocation: start.is_starting
                });

                var endMarker = new google.maps.Marker({
                    position: end_latlng,
                    title: end.name,
                    identifier_id: end.id,
                    is_startingLocation: end.is_starting
                });

                collection.push({
                    start: startMarker,
                    end: endMarker,
                    renderer: {},
                    polyline: {},
                    waypoints: waypoints,
                    cost: cost,
                    scinario_id: couple.scinario_id,
                    per_km_category: couple.per_km_category,
                    distance: couple.distance
                });
            }
        }

        function drawRoute() {
            loadRenderers(function () {

            });
        }

        function loadRenderers(callback) {
            var index = 0;
            for (var counter = 0; counter < collection.length; counter++) {

                var waypoints = collection[counter].waypoints || [];
                for (var i = 0; i < collection[counter].waypoints.length; i++) {
                    collection[counter].waypoints[i].stopover = false;
                }


                collection[counter].start.setMap(map);
                collection[counter].end.setMap(map);

                var routeSettings = {
                    origin: collection[counter].start.getPosition(),
                    destination: collection[counter].end.getPosition(),
                    waypoints: waypoints,
                    travelMode: 'DRIVING',
                    provideRouteAlternatives: false
                };

                directionsService.route(routeSettings, function (response, status) {
                    if (status === 'OK') {
                        var directionsRenderer = new google.maps.DirectionsRenderer({
                            draggable: true,
                            suppressMarkers: true,
                            directions: response,
                            // suppressPolylines: true,
                            segmentPosition: index,
                            polylineOptions: {zIndex: 9999, strokeColor: '#6EA0C9', strokeWeight: 6}
                        });

                        directionsRenderer.addListener('directions_changed', function () {
                            var directions = collection[this.segmentPosition].renderer.getDirections();

                            collection[this.segmentPosition].polyline.setMap(null);
                            collection[this.segmentPosition].polyline.setPath([]);

                            var steps = directions.routes[0].legs[0].steps;
                            for (var step = 0; step < steps.length; step++) {
                                var nextSegment = steps[step].path;
                                for (k = 0; k < nextSegment.length; k++) {
                                    collection[this.segmentPosition].polyline.getPath().push(nextSegment[k]);
                                }
                            }

                            calculateTotalDistance();
                            calculateSegmentDistance(this.segmentPosition);
                        });


                        var polylineOptions = {
                            strokeColor: "#000",
                            strokeOpacity: 0.7,
                            strokeWeight: 6,
                            clickable: true,
                            segmentPosition: index,
                            map: map
                        }

                        if (collection[index].hasOwnProperty('cost') && collection[index].cost > 0) {
                            polylineOptions.strokeColor = '#29a540';
                        }

                        var directions = directionsRenderer.getDirections();
                        var polyline = new google.maps.Polyline(polylineOptions);
                        var steps = directions.routes[0].legs[0].steps;
                        for (var step = 0; step < steps.length; step++) {
                            var nextSegment = steps[step].path;
                            for (k = 0; k < nextSegment.length; k++) {
                                polyline.getPath().push(nextSegment[k]);
                            }
                        }

                        polyline.addListener('click', function () {
                            mapEnvironment('polyClick', this.segmentPosition);
                            calculateSegmentDistance(this.segmentPosition);
                            loadSuggestions(this.segmentPosition);
                        });

                        collection[index].renderer = directionsRenderer;
                        collection[index].polyline = polyline;

                    }
                    if ((index + 1) == collection.length) {

                        calculateTotalDistance();

                        if (callback != undefined && typeof(callback) == 'function') {
                            callback();
                        }
                    }
                    index++;
                });

            }
        }

        function getTotalDistance() {
            var total = 0;
            var cost = 0;
            for (var counter = 0; counter < collection.length; counter++) {
                // var directions = collection[counter].renderer.getDirections();
                // if (directions != undefined) {
                //     var route = directions.routes[0];
                //     for (var i = 0; i < route.legs.length; i++) {
                //         total += route.legs[i].distance.value;
                //     }
                // }

                if(+collection[counter].distance > 0){
                    total += (+collection[counter].distance * 1000);
                }else{
                    var directions = collection[counter].renderer.getDirections();
                    if (directions != undefined) {
                        var route = directions.routes[0];
                        for (var i = 0; i < route.legs.length; i++) {
                            total += route.legs[i].distance.value;
                        }
                    }
                }
            }
            total = total / 1000;



            for (var counter = 0; counter < collection.length; counter++) {
                if (+collection[counter].cost > 0) {
                    cost += +collection[counter].cost;
                } else {
                    cost = 0;
                    break;
                }
            }

            return total;
        }

        function updateTotalDistance(){
            var total = 0;
            for (var counter = 0; counter < collection.length; counter++) {
                if(+collection[counter].distance > 0){
                    total += (+collection[counter].distance * 1000);
                }else{
                    var directions = collection[counter].renderer.getDirections();
                    if (directions != undefined) {
                        var route = directions.routes[0];
                        for (var i = 0; i < route.legs.length; i++) {
                            total += route.legs[i].distance.value;
                        }
                    }
                }
            }
            total = total / 1000;


            document.getElementById('tripDistance').innerHTML = total + ' km';

            //-----------------
            var selectedCostScinario = document.getElementById('costScinarios');
            var affects_per_trip = null;
            var auto_calculate = null;
            var rate = null;
            if (selectedCostScinario.selectedIndex != -1 && selectedCostScinario.options[selectedCostScinario.selectedIndex].value != '') {
                affects_per_trip = selectedCostScinario.options[selectedCostScinario.selectedIndex].getAttribute('data-apt');
                auto_calculate = selectedCostScinario.options[selectedCostScinario.selectedIndex].getAttribute('data-ac');

                if(auto_calculate == 1){
                    var selectedCostCategory = document.getElementById('costCategories');
                    if(selectedCostCategory.selectedIndex != -1 && selectedCostCategory.options[selectedCostCategory.selectedIndex].value != ''){
                        rate = selectedCostCategory.options[selectedCostCategory.selectedIndex].getAttribute('data-rate');
                    }
                }
            }


            //------------------------------------------------- on key up : cost & totalCost


            var cost = 0;
            var totalCost = 0;
            if(affects_per_trip == 1){
                if(auto_calculate == 1){
                    //trip wise auto calculate
                    cost = total * rate;
                    totalCost = total * rate;
                }else if(auto_calculate == 0){
                    //trip wise fixed

                }

            }else if(affects_per_trip == 0){
                var index = $('.saveSegment').val();
                if(index != ''){
                    if(auto_calculate == 1){
                        //segment wise auto calculate

                        var distance = +collection[index].distance > 0 ? collection[index].distance : getSegmentDistance(index);
                        cost = distance * rate;


                        //total trip cost
                        for (var counter = 0; counter < collection.length; counter++) {
                            if(counter != index){
                                if (+collection[counter].cost > 0) {
                                    totalCost += +collection[counter].cost;
                                } else {
                                    totalCost = 0;
                                    break;
                                }
                            }else{
                                totalCost += cost;
                            }
                            
                        }
                    }else if(auto_calculate == 0){
                        //segment wise fixed
                        cost = +collection[index].cost;

                        for (var counter = 0; counter < collection.length; counter++) {
                            if(counter != index){
                                if (+collection[counter].cost > 0) {
                                    totalCost += +collection[counter].cost;
                                } else {
                                    totalCost = 0;
                                    break;
                                }
                            }else{
                                totalCost += cost;
                            }
                            
                        }

                    }
                }
            }

            document.getElementById('cost').value = cost.toFixed(2);
            document.getElementById('tripCost').innerHTML = totalCost.toFixed(2);
        }

        function calculateTotalDistance() {
            var total = 0;
            var cost = 0;
            var totalTripCost = 0;
            for (var counter = 0; counter < collection.length; counter++) {
                if(+collection[counter].distance > 0){
                    total += (+collection[counter].distance * 1000);
                }else{
                    var directions = collection[counter].renderer.getDirections();
                    if (directions != undefined) {
                        var route = directions.routes[0];
                        for (var i = 0; i < route.legs.length; i++) {
                            total += route.legs[i].distance.value;
                        }
                    }
                }
            }
            total = total / 1000;




            var selectedCostScinario = document.getElementById('costScinarios');

            var affects_per_trip = null;
            var auto_calculate = null;
            if (selectedCostScinario.selectedIndex != -1) {
                affects_per_trip = selectedCostScinario.options[selectedCostScinario.selectedIndex].getAttribute('data-apt');
                auto_calculate = selectedCostScinario.options[selectedCostScinario.selectedIndex].getAttribute('data-ac');
            }

            // if(affects_per_trip == 0){
            //     for (var counter = 0; counter < collection.length; counter++) {
            //         if (+collection[counter].cost > 0) {
            //             cost += +collection[counter].cost;
            //         } else {
            //             cost = 0;
            //             break;
            //         }
            //     }
            // }
            

            //old code for cost calculation. Since new per_km_categories introduced, we have to reimplement it
            // var selectedVehicle = document.getElementById('vehiclesList');
            // var vehicle_trip_cost = null;
            // var cpkm = null;
            // if (selectedVehicle.selectedIndex != -1) {
            //     vehicle_trip_cost = selectedVehicle.options[selectedVehicle.selectedIndex].getAttribute('data-cost');
            //     cpkm = selectedVehicle.options[selectedVehicle.selectedIndex].getAttribute('data-cpkm');
            // }

            // if (affects_per_trip == 1) {
            //     if (auto_calculate == 1) {
            //         document.getElementById('cost').disabled = true;
            //         cost = cpkm * total;
            //     } else {
            //         document.getElementById('cost').disabled = false;
            //         cost = vehicle_trip_cost;
            //     }
            //     document.getElementById('cost').value = cost;
            // }

            
            var selectedCostCategory = document.getElementById('costCategories');
            //todo disable cost textbox like above

            if (auto_calculate == 1) {
                document.getElementById('cost').disabled = true;
            } else {
                document.getElementById('cost').disabled = false;
            }
            
            if (affects_per_trip == 1 && auto_calculate == 1) {
                if(selectedCostCategory.selectedIndex != -1){
                    var costCategory = selectedCostCategory.options[selectedCostCategory.selectedIndex];

                    if(costCategory.value != ''){
                        var rate = costCategory.getAttribute('data-rate');
                        cost = total * rate;
                    }
                }
                totalTripCost = cost;
                
            }else if(affects_per_trip == 1 && auto_calculate == 0){

                var selectedVehicle = document.getElementById('vehiclesList');
                if (selectedVehicle.selectedIndex != -1){
                    var vehicle_trip_cost = selectedVehicle.options[selectedVehicle.selectedIndex].getAttribute('data-cost');
                    cost = vehicle_trip_cost;
                }
                totalTripCost = cost;
                
            }else if(affects_per_trip == 0 && auto_calculate == 1){
                //segment auto calculate
                var costCategory = selectedCostCategory.options[selectedCostCategory.selectedIndex];
                var index = $('.saveSegment').val();
                if(costCategory.value != '' && index != ''){
                    var rate = costCategory.getAttribute('data-rate');
                    cost = getSegmentDistance(index) * rate;
                }
                
            }else if(affects_per_trip == 0 && auto_calculate == 0){
                //segment fixed cost added
                var index = $('.saveSegment').val();
                if(index != ''){
                    cost = collection[index].cost;
                }
            }
            document.getElementById('cost').value = cost;


            //this variable is used to track if costs are allocated trip-wise or segment-wise
            //so we can preload the total trip cost by using tihs
            var vehicleScinarioID = $('.vehiclesList option:selected').data('scinario_id');
            if(vehicleScinarioID == 0){
                //costs are saved segment wise
                totalTripCost = 0;
                for (var counter = 0; counter < collection.length; counter++) {
                    if (+collection[counter].cost > 0) {
                        totalTripCost += +collection[counter].cost;
                    } else {
                        totalTripCost = 0;
                        break;
                    }
                }


            }else{
                //tripwise
                //already calculated? and already working?

            }

            // console.log(affects_per_trip, auto_calculate);
            // console.log(collection);
            




            document.getElementById('tripDistance').innerHTML = total + ' km';
            document.getElementById('tripCost').innerHTML = totalTripCost;
        }

        function getSegmentOriginalDistance(index){
            index = +index;
            var total = 0;
            if (typeof(index) == 'number' && index < collection.length) {

                var directions = collection[index].renderer.getDirections();
                if (directions != undefined) {
                    var route = directions.routes[0];
                    for (var i = 0; i < route.legs.length; i++) {
                        total += route.legs[i].distance.value;
                    }
                }
                
                total = total / 1000;
            }
            return total;
        }

        function loadSuggestions(index){
            index = +index;
            
            
            if (typeof(index) == 'number' && index < collection.length) {
                var sid = collection[index].start.identifier_id;
                var eid = collection[index].end.identifier_id;

                // $('meta[name="_token"]').attr('content');
                var _token = document.querySelector("[name=_token]") != null ? document.querySelector("[name=_token]").content : '';

                var http = new XMLHttpRequest();
                var url = "<?php echo e(url('/tripmanagement/loadSuggestions')); ?>";
                var params = '_token='+ _token +'&sid='+ sid +'&eid='+eid;
                http.open("POST", url, true);

                //Send the proper header information along with the request
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

                http.onreadystatechange = function() {//Call a function when the state changes.
                    if(http.readyState == 4 && http.status == 200) {
                        var dom = '';
                        var responseObject = JSON.parse(http.responseText);
                        for(var i = 0; i < Object.keys(responseObject).length; i++){
                            if(responseObject[i].hasOwnProperty('distance')){
                                var distance = responseObject[i].distance;
                                dom += '<option>'+ distance +'</option>';
                            }
                        }
                        document.getElementById('suggestions').innerHTML = dom;
                    }
                }
                http.send(params);
            }

        }

        function getSegmentDistance(index) {
            index = +index;
            var total = 0;
            var cost = '0.00';

            if (typeof(index) == 'number' && index < collection.length) {

                if(+collection[index].distance > 0){
                    total = (+collection[index].distance * 1000);
                }else{
                    var directions = collection[index].renderer.getDirections();
                    if (directions != undefined) {
                        var route = directions.routes[0];
                        for (var i = 0; i < route.legs.length; i++) {
                            total += route.legs[i].distance.value;
                        }
                    }
                }
                total = total / 1000;
                cost = collection[index].cost;
            }
            return total;
        }

        function calculateSegmentDistance(index) {
            index = +index;
            var total = 0;
            var startTitle = '-';
            var endTitle = '-';
            var cost = '0.00';
            var scinario_id = "";
            var per_km_category = "";
            
            if (typeof(index) == 'number' && index < collection.length) {
                scinario_id = collection[index].scinario_id;
                startTitle = collection[index].start.getTitle();
                endTitle = collection[index].end.getTitle();
                per_km_category = collection[index].per_km_category;



                var directions = collection[index].renderer.getDirections();
                if (directions != undefined) {
                    var route = directions.routes[0];
                    for (var i = 0; i < route.legs.length; i++) {
                        total += route.legs[i].distance.value;
                    }
                }
                total = total / 1000;
                cost = collection[index].cost;

                var distance = +collection[index].distance;
                if(distance > 0){
                    total = distance;
                    document.getElementById('segmentDistance').value = distance;
                    document.getElementById('segmentDistance').setAttribute('data-original', distance);
                }else{
                    document.getElementById('segmentDistance').value = total;
                    document.getElementById('segmentDistance').setAttribute('data-original', total);
                }
            }


            document.getElementById('segmentFrom').innerHTML = startTitle;
            document.getElementById('segmentTo').innerHTML = endTitle;


            
            


            //pre selecting cost scinario
            document.getElementById('costScinarios').value = scinario_id;


            var selectedCostScinario = document.getElementById('costScinarios');

            var affects_per_trip = null;
            var auto_calculate = null;
            if (selectedCostScinario.selectedIndex != -1) {
                affects_per_trip = selectedCostScinario.options[selectedCostScinario.selectedIndex].getAttribute('data-apt');
                auto_calculate = selectedCostScinario.options[selectedCostScinario.selectedIndex].getAttribute('data-ac');
            }


            // var selectedVehicle = document.getElementById('vehiclesList');

            // var vehicle_trip_cost = null;
            // var cpkm = null;
            // if (selectedVehicle.selectedIndex != -1) {
            //     vehicle_trip_cost = selectedVehicle.options[selectedVehicle.selectedIndex].getAttribute('data-cost');
            //     cpkm = selectedVehicle.options[selectedVehicle.selectedIndex].getAttribute('data-cpkm');
            // }

            // document.getElementById('cost').value = '';


            // if (affects_per_trip != null && affects_per_trip == 0) {
            //     if (auto_calculate != null && auto_calculate == 1) {
            //         document.getElementById('cost').disabled = true;
            //         var segmentCost = total * cpkm;
            //         document.getElementById('cost').value = segmentCost.toFixed(2);
            //     } else {
            //         document.getElementById('cost').value = cost;
            //         document.getElementById('cost').disabled = false;
            //     }

            // } else {

            //     if (auto_calculate != null && auto_calculate == 0) {
            //         document.getElementById('cost').disabled = true;
            //         document.getElementById('cost').value = vehicle_trip_cost;
            //     } else {
            //         document.getElementById('cost').disabled = false;
            //     }
            // }


            //todo : auto select costCategory
            document.getElementById('costCategories').value = per_km_category;

            var selectedVehicle = document.getElementById('vehiclesList');
            var vehicle_trip_cost = null;


            var selectedCostCategory = document.getElementById('costCategories');
            


            if (selectedVehicle.selectedIndex != -1) {
                vehicle_trip_cost = selectedVehicle.options[selectedVehicle.selectedIndex].getAttribute('data-cost');
            }



            document.getElementById('cost').value = '';

            if (affects_per_trip != null && affects_per_trip == 0) {

                
                if (auto_calculate != null && auto_calculate == 1) {
                    //segment autocalculate


                    //the following code order in this condition block has to be maintained 
                    //on segment click, we have to pre select the relevent cost category
                    //since we are already in auto calculate section :
                    document.getElementById('costCategoriesWrapper').style.display = "inline-block";
                    
                    var costCategory = selectedCostCategory.options[selectedCostCategory.selectedIndex];
                    
                    if(costCategory.selectedIndex != -1){


                        var rate = costCategory.getAttribute('data-rate');
                            
                        document.getElementById('cost').disabled = true;
                        var segmentCost = total * rate;
                        document.getElementById('cost').value = segmentCost.toFixed(2);    
                        

                        

                        
                    }else{

                        document.getElementById('cost').value = ''
                    }

                    
                } else {
                    document.getElementById('cost').value = cost;
                    document.getElementById('cost').disabled = false;
                    document.getElementById('costCategoriesWrapper').style.display = "none";
                    document.getElementById('costCategories').value = '';
                }

            } else {
                //trip
                if (auto_calculate != null && auto_calculate == 0) {
                    document.getElementById('cost').disabled = true;
                    document.getElementById('costCategoriesWrapper').style.display = "none";
                    document.getElementById('costCategories').value = '';
                    document.getElementById('cost').value = vehicle_trip_cost;
                } else {
                    document.getElementById('cost').disabled = false;
                }
            }





        }

        function mapEnvironment(method, index) {
            index = +index;
            if (typeof(method) == 'string') {
                if (method == 'polyClick' && typeof(index) == 'number' && index < collection.length) {

                    document.getElementById('controlsWrapper').style.display = "inline-block";
                    document.getElementById('segmentTitle').style.display = "inline-block";
                    document.getElementById('segmentTitle').innerHTML = collection[index].start.getTitle() + ' - ' + collection[index].end.getTitle();

                    document.getElementById('edit').style.display = "inline-block";
                    // document.getElementById('saveSegment').style.display = "inline-block";
                    document.getElementById('done').style.display = "none";

                    document.getElementById('edit').value = index;
                    document.getElementById('reset').value = index;
                    document.getElementById('done').value = index;

                    document.getElementById('saveSegment').value = index;

                    highlightSegment(index);

                } else if (method == 'edit') {

                    for (var i = 0; i < collection.length; i++) {
                        collection[i].renderer.setMap(null);

                        if (collection[i].hasOwnProperty('cost') && collection[i].cost > 0) {
                            collection[i].polyline.setOptions({strokeColor: "#29a540"});
                        }
                        collection[i].polyline.setMap(map);

                    }
                    collection[index].polyline.setMap(null);
                    collection[index].renderer.setMap(map);

                    document.getElementById('edit').style.display = "none";
                    document.getElementById('done').style.display = "inline-block";
                } else if (method == 'done') {

                    for (var i = 0; i < collection.length; i++) {
                        collection[i].renderer.setMap(null);
                        collection[i].polyline.setMap(map);
                    }

                    document.getElementById('done').style.display = "none";
                    document.getElementById('edit').style.display = "inline-block";
                } else if (method == 'reset') {



                    document.getElementById('controlsWrapper').style.display = "none";
                    document.getElementById('segmentTitle').style.display = "none";
                    document.getElementById('segmentTitle').innerHTML = '';

                    document.getElementById('edit').style.display = "none";
                    // document.getElementById('saveSegment').style.display = "none";
                    document.getElementById('done').style.display = "none";

                    document.getElementById('segmentFrom').innerHTML = '';
                    document.getElementById('segmentTo').innerHTML = '';
                    // document.getElementById('cost').value = '';
                    document.getElementById('tripCost').innerHTML = '-';
                    document.getElementById('segmentDistance').value = '0';
                    // document.getElementById('segmentDistance').dataset.original = 0;
                    document.getElementById('segmentDistance').setAttribute('data-original', 0);

                    document.getElementById('tripDistance').innerHTML = '0 km';

                    document.getElementById('edit').value = "";
                    document.getElementById('reset').value = "";
                    document.getElementById('done').value = "";
                    document.getElementById('saveSegment').value = "";
                    document.getElementById('cost').value = '';

                    document.getElementById('ap_direct_deliveries').value = "";
                    document.getElementById('ap_offloading_charges').value = "";
                    document.getElementById('ap_demurrages').value = "";
                    document.getElementById('ap_other').value = "";
                    document.getElementById('d_document_errors').value = "";
                    document.getElementById('d_other').value = "";

                }
            }
        }

        function resetSegment(index) {
            collection[index].waypoints = [];

            collection[index].renderer.setMap(null);
            collection[index].polyline.setMap(null);
            collection[index].polyline.setPath([]);
            collection[index].renderer = null;
            collection[index].polyline = null;


            var routeSettings = {
                origin: collection[index].start.getPosition(),
                destination: collection[index].end.getPosition(),
                travelMode: 'DRIVING',
                provideRouteAlternatives: false
            };


            directionsService.route(routeSettings, function (response, status) {
                if (status === 'OK') {
                    var directionsRenderer = new google.maps.DirectionsRenderer({
                        draggable: true,
                        suppressMarkers: true,
                        directions: response,
                        segmentPosition: index,
                        polylineOptions: {zIndex: 9999, strokeColor: '#6EA0C9', strokeWeight: 6}
                    });

                    directionsRenderer.addListener('directions_changed', function () {

                        var directions = collection[this.segmentPosition].renderer.getDirections();

                        collection[index].polyline.setMap(null);
                        collection[index].polyline.setPath([]);

                        var steps = directions.routes[0].legs[0].steps;
                        for (var step = 0; step < steps.length; step++) {
                            var nextSegment = steps[step].path;
                            for (k = 0; k < nextSegment.length; k++) {
                                collection[this.segmentPosition].polyline.getPath().push(nextSegment[k]);
                            }
                        }

                        calculateTotalDistance();
                        calculateSegmentDistance(this.segmentPosition);
                    });

                    var polylineOptions = {
                        strokeColor: "#000",
                        strokeOpacity: 0.7,
                        strokeWeight: 6,
                        clickable: true,
                        segmentPosition: index,
                        map: map
                    }

                    if (collection[index].hasOwnProperty('cost') && +collection[index].cost > 0) {
                            polylineOptions.strokeColor = '#29a540';
                    }

                    var directions = directionsRenderer.getDirections();
                    var polyline = new google.maps.Polyline(polylineOptions);
                    var steps = directions.routes[0].legs[0].steps;
                    for (var step = 0; step < steps.length; step++) {
                        var nextSegment = steps[step].path;
                        for (k = 0; k < nextSegment.length; k++) {
                            polyline.getPath().push(nextSegment[k]);
                        }
                    }

                    polyline.addListener('click', function () {
                        calculateSegmentDistance(this.segmentPosition);
                        mapEnvironment('polyClick', this.segmentPosition);
                    });

                    collection[index].renderer = directionsRenderer;
                    collection[index].polyline = polyline;
                }

                mapEnvironment('polyClick', index);
                calculateSegmentDistance(index);
            });

        }


        function highlightSegment(index) {

            if (typeof(index) == 'number' && index < collection.length) {
                for (var i = 0; i < collection.length; i++) {
                    collection[i].renderer.setMap(null);

                    if (collection[i].hasOwnProperty('cost') && +collection[i].cost > 0) {
                        collection[i].polyline.setOptions({strokeColor: "#29a540", zIndex: ((i + 1) * 10)});
                    } else {
                        collection[i].polyline.setOptions({strokeColor: "#000", zIndex: ((i + 1) * 10)});
                    }
                    collection[i].polyline.setMap(map);
                }
                collection[index].polyline.setOptions({strokeColor: "#FF0000", zIndex: ((i + 2) * 10)});
            }
        }

        document.getElementById('edit').addEventListener("click", function () {
            mapEnvironment('edit', this.value);
        });

        document.getElementById('done').addEventListener("click", function () {
            mapEnvironment('done', this.value);
        });

        document.getElementById('reset').addEventListener("click", function () {
            var index = this.value;
            resetSegment(index);
        });

    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBxs5MnILDCN8Qz01-5fHUGKBQ85B34gHE"></script>

    <script type="text/javascript">

        $(function () {
            var _token = $('meta[name="_token"]').attr('content');

            $(document).ajaxStart(function () {
                $('button, .btn').data('loading-text', '...');
                $('button, .btn').button('loading');
            }).ajaxStop(function () {
                $('button, .btn').button('reset');
            });

            

            initMap();
            loadTripsList(function () {
                loadVehicles(function () {
                    loadDropPoints();
                });
            });

            $('#segmentDistance').keyup(function(){

                var index = $('.saveSegment').val();
                if(index != '' && $.isDouble($(this).val())){

                    $(this).data('original', $(this).val());
                    collection[index].distance = $(this).val();

                    
                    
                }else{
                    $(this).val($(this).data('original'));
                    if(index != ''){
                        collection[index].distance = $(this).data('original');
                    }
                }
                updateTotalDistance();
            });

            $('.tripsList').change(function () {
                mapEnvironment('reset');
                loadVehicles(function () {
                    loadDropPoints();
                });
            });

            $('.vehiclesList').change(function () {
                mapEnvironment('reset');
                loadDropPoints();
            });

            $('.undoSegmentDistance').click(function(){
                var index = $('.saveSegment').val();
                if(index != ''){
                    var distance = getSegmentOriginalDistance(index);
                    collection[index].distance = distance;
                    $('#segmentDistance').val(distance);
                    updateTotalDistance();
                }
            });

            $('.costCategories').change(function(){
                if($(this).val() != ''){

                    var affects_per_trip = $('option:selected', $('.costScinarios')).data('apt');
                    var auto_calculate = $('option:selected', $('.costScinarios')).data('ac');
                    var vehicle_cost = $('.vehiclesList option:selected').data('cost');
                    
                    var rate = $('option:selected', $(this)).data('rate');


                    if (affects_per_trip == 0) {

                        var index = $('.saveSegment').val();

                        $('.cost').val('');
                        $('.cost').attr('placeholder', 'Please select a segment first');


                        if (index != '') {
                            index = +index;
                            if (typeof(index) == 'number' && index < collection.length) {

                                if (auto_calculate == 1) {
                                    var distance = getSegmentDistance(index);
                                    var totalCost = distance * rate;

                                    $('.cost').val(totalCost.toFixed(2));
                                } else {

                                    $('.cost').val(collection[index].cost);
                                }

                            }
                        }


                    }else{

                        if (auto_calculate == 1) {
                            var totalDistance = getTotalDistance();
                            var totalCost = rate * totalDistance;
                            $('.cost').val(totalCost.toFixed(2));

                        }else {
                            $('.cost').val(vehicle_cost);
                        }
                    }

                    
                }else{
                    $('.cost').val('');
                }
            });

            $('.costScinarios').change(function () {
                if ($(this).val() != '') {
                    var affects_per_trip = $('option:selected', $(this)).data('apt');
                    var auto_calculate = $('option:selected', $(this)).data('ac');
                    var vehicle_cost = $('.vehiclesList option:selected').data('cost');
                    var cpkm = $('.vehiclesList option:selected').data('cpkm');
                    var per_km_category = $('.vehiclesList option:selected').data('per_km_category');

                    //check

                    if (auto_calculate == 1) {
                        $('.cost').prop('disabled', true);
                        $('.costCategoriesWrapper').show();
                    } else {
                        $('.cost').prop('disabled', false);
                        $('.costCategoriesWrapper').hide();
                    }

                    $('.costCategories').val('');

                    if (affects_per_trip == 0) {

                        var index = $('.saveSegment').val();

                        $('.cost').val('');
                        $('.cost').attr('placeholder', 'Please select a segment first');


                        if (index != '') {
                            index = +index;
                            if (typeof(index) == 'number' && index < collection.length) {

                                if (auto_calculate == 1) {

                                    if($('.costCategories option:selected').val() != ''){

                                        // var distance = getSegmentDistance(index);
                                        // var totalCost = distance * cpkm;
                                        // $('.cost').val(totalCost.toFixed(2));

                                        //to be figured out!!
                                    }else{
                                        $('.cost').val('');
                                    }


                                    
                                } else {

                                    $('.cost').val(collection[index].cost);
                                }

                            }
                        }
                        
                    } else {
                        //trip auto calculate
                        
                        if (auto_calculate == 1) { // || auto_calculate == null
                            $('.costCategories').val(per_km_category);

                            if($('.costCategories option:selected').val() != ''){
                                var rate = $('.costCategories option:selected').data('rate');
                                var totalDistance = getTotalDistance();
                                var totalTripCost = totalDistance * rate;
                                $('.cost').val(totalTripCost.toFixed(2));
                            }else{
                                $('.cost').val('');
                            }


                            // var totalDistance = getTotalDistance();
                            
                            // var totalTripCost = totalDistance * cpkm;

                            // $('.cost').val(totalTripCost.toFixed(2));

                        } else {
                            $('.cost').val(vehicle_cost);
                        }
                    }


                } else {
                    $('.cost').val('');
                    $('.cost').prop('disabled', true);
                    $('.costCategoriesWrapper').hide();
                }
            });

            $('.saveSegment').click(function () {
                var index = $(this).val();
                if ($.isDouble($('.cost').val())) {

                    if (index != '' && $('.costScinarios option:selected').data('apt') == 0) {

                        index = +index;
                        if (typeof(index) == 'number' && index < collection.length) {

                            var start = collection[index].start.identifier_id;
                            var end = collection[index].end.identifier_id;
                            var startType = collection[index].start.is_startingLocation;
                            var endType = collection[index].end.is_startingLocation;

                            directions = collection[index].renderer.getDirections();
                            var waypoints = []; //clearing global variable
                            if (directions != undefined) {
                                if (Object.keys(directions.routes[0].legs[0].via_waypoints).length > 0) {
                                    var points = directions.routes[0].legs[0].via_waypoints;
                                    for (var i = 0; i < points.length; i++) {
                                        waypoints.push({location: {lat: points[i].lat(), lng: points[i].lng()}});
                                    }
                                }
                            }

                            var data = {
                                trip_id: $('.tripsList option:selected').val(),
                                transporter_vehicle_id: $('.vehiclesList option:selected').val(),
                                start: {id: start, type: startType},
                                end: {id: end, type: endType},
                                waypoints: waypoints,
                                cost: $('.cost').val(),
                                distance: $('#segmentDistance').val(),
                                scinario: $('.costScinarios').val(),
                                per_km_category: $('.costCategories').val(),
                                ap_direct_deliveries : +$('.ap_direct_deliveries').val(),
                                ap_offloading_charges : +$('.ap_offloading_charges').val(),
                                ap_demurrages : +$('.ap_demurrages').val(),
                                ap_other : +$('.ap_other').val(),
                                d_document_errors : +$('.d_document_errors').val(),
                                d_other : +$('.d_other').val()
                            };

                            if(+$('#segmentDistance').val() > 0){
                                saveSegment(data, index);
                            }else{
                                notify.error('<b>Invalid distance</b>');
                            }
                        }

                    } else {

                        var trip_data = {
                            'trip_id': $('.tripsList option:selected').val(),
                            'transporter_vehicle_id': $('.vehiclesList option:selected').val(),
                            'scinario_id': $('.costScinarios').val(),
                            'cost': $('.cost').val(),
                            'per_km_category': $('.costCategories').val(),
                            'segments': [],
                            'total_distance': $('#tripDistance').text(),
                            'ap_direct_deliveries' : +$('.ap_direct_deliveries').val(),
                            'ap_offloading_charges' : +$('.ap_offloading_charges').val(),
                            'ap_demurrages' : +$('.ap_demurrages').val(),
                            'ap_other' : +$('.ap_other').val(),
                            'd_document_errors' : +$('.d_document_errors').val(),
                            'd_other' : +$('.d_other').val()
                        };

                        for (var index = 0; index < collection.length; index++) {

                            var start = collection[index].start.identifier_id;
                            var end = collection[index].end.identifier_id;
                            var startType = collection[index].start.is_startingLocation;
                            var endType = collection[index].end.is_startingLocation;

                            directions = collection[index].renderer.getDirections();
                            var waypoints = []; //clearing global variable
                            if (directions != undefined) {
                                if (Object.keys(directions.routes[0].legs[0].via_waypoints).length > 0) {
                                    var points = directions.routes[0].legs[0].via_waypoints;
                                    for (var i = 0; i < points.length; i++) {
                                        waypoints.push({location: {lat: points[i].lat(), lng: points[i].lng()}});
                                    }
                                }
                            }

                            var data = {
                                start: {id: start, type: startType},
                                end: {id: end, type: endType},
                                waypoints: waypoints,
                                distance: +collection[index].distance > 0 ? +collection[index].distance : getSegmentDistance(index)
                            };

                            trip_data.segments.push(data);
                        }
                        saveTrip(trip_data);

                    }
                } else {
                    $.notify.error('<b>Invalid cost</b>');
                }

            });

            function saveTrip(trip_data) {
                $.post("<?php echo e(url('/tripmanagement/saveTrip')); ?>", {_token: _token, data: trip_data}, function (e) {
                    $.highlightOrThrow(e, function (response) {
                        if (typeof(e) == 'object' && e.hasOwnProperty('response') && typeof(e.response) == 'object') {
                            var response = e.response;
                            if (response.hasOwnProperty('affects_per_trip') && response.hasOwnProperty('cost')) {
                                if (response.affects_per_trip == 1) {
                                    $('.vehiclesList option:selected').attr('data-cost', trip_data.cost);
                                    $('.vehiclesList option:selected').data('cost', trip_data.cost);
                                    $('.vehiclesList option:selected').data('scinario_id', trip_data.scinario_id);
                                    $('.vehiclesList option:selected').data('per_km_category', trip_data.per_km_category);
                                    for(var i = 0; i < collection.length; i++){
                                        collection[i].cost = 0;
                                        collection[i].scinario_id = "";
                                        collection[i].per_km_category = "";
                                    }
                                } else {
                                    if (index != undefined) {
                                        collection[index].cost = trip_data.cost;
                                        $('.vehiclesList option:selected').data('scinario_id', '');
                                    }
                                }
                            }
                        }
                        calculateTotalDistance();
                        loadSummaryTitle();
                    });
                }, 'json');
            }

            function saveSegment(data, index) {
                $.post("<?php echo e(url('/tripmanagement/saveSegment')); ?>", {_token: _token, data: data}, function (e) {
                    $.highlightOrThrow(e, function (response) {
                        if (typeof(e) == 'object' && e.hasOwnProperty('response') && typeof(e.response) == 'object') {
                            var response = e.response;
                            if (response.hasOwnProperty('affects_per_trip') && response.hasOwnProperty('cost')) {
                                if (response.affects_per_trip == 1) {
                                    $('.vehiclesList option:selected').data('cost', data.cost);

                                } else {
                                    if (index != undefined) {
                                        collection[index].cost = data.cost;
                                        collection[index].scinario_id = data.scinario;
                                        collection[index].per_km_category = data.per_km_category;
                                    }
                                }
                                $('.vehiclesList option:selected').data('scinario_id', '');
                                $('.vehiclesList option:selected').data('per_km_category', '');
                            }
                        }
                        calculateTotalDistance();
                        // calculateSegmentDistance();
                        loadSummaryTitle();
                    });
                }, 'json');
            }

            function loadTripsList(callback) {
                var $select = $('.tripsList');
                $.post("<?php echo e(url('/tripmanagement/loadTripsList')); ?>", {_token: _token}, function (e) {
                    var dom = '<option value="">Please select a trip</option>';
                    if (e != undefined && typeof(e) == 'object' && Object.keys(e).length > 0) {
                        $.each(e, function (i, k) {
                            dom += '<option value="' + k.id + '">Trip #' + k.id + '</option>';
                        });
                    }
                    $select.html(dom);
                    if (callback != undefined && typeof(callback) == 'function') {
                        callback();
                    }
                }, 'json');
            }

            function loadVehicles(callback) {
                var $select = $('.vehiclesList');
                var trip_id = $('.tripsList option:selected').val();
                $.post("<?php echo e(url('/tripmanagement/loadVehicles')); ?>", {_token: _token, trip_id: trip_id}, function (e) {
                    var dom = '';
                    if (e != undefined && typeof(e) == 'object' && Object.keys(e).length > 0) {
                        $.each(e, function (i, k) {
                            dom += '<option value="' + k.id + '" data-cost="' + k.cost + '" data-scinario_id="'+ k.scinario_id +'" data-per_km_category="'+ k.per_km_category +'" data-cpkm="' + k.cpkm + '">' + k.name + ' - ' + k.number + '</option>';
                        });
                    }
                    $select.html(dom);
                    if (callback != undefined && typeof(callback) == 'function') {
                        callback();
                    }
                }, 'json');
            }

            function loadDropPoints(callback) {
                markerOptions = [];
                collection = [];
                var $thumbnail = $('.route');

                $thumbnail.html('-- no drop points to be loaded --');
                var data = {
                    trip_id: $('.tripsList option:selected').val(),
                    vehicle_id: $('.vehiclesList option:selected').val()
                };
                initMap(function () {

                    if (data.trip_id != undefined && data.trip_id != null && data.trip_id != '') {
                        if (data.vehicle_id != undefined && data.vehicle_id != null && data.vehicle_id != '') {
                            var dom = '';
                            $.post("<?php echo e(url('/tripmanagement/loadDropPoints')); ?>", {
                                _token: _token,
                                data: data
                            }, function (e) {
                                if (e != undefined && typeof(e) == 'object' && Object.keys(e).length > 0 && e.hasOwnProperty('locations') && e.hasOwnProperty('couples') && typeof(e.locations) == 'object' && Object.keys(e.locations).length > 0) {
                                    var couples = e.couples;
                                    var locations = e.locations;
                                    var costResult = e.costResult;
                                    var scinariosList = e.scinariosList;
                                    var per_km_categories = e.per_km_categories;

                                    $.each(couples, function (i, couple) {
                                        addCouples(couple);
                                    });
                                    drawRoute();

                                    $.each(locations, function (i, k) {

                                        if (i == 0) {
                                            dom += '<div class="col-xs-3">';
                                            dom += '	<div class="form-group">';
                                            dom += '		<div class="input-group">'
                                            dom += '			<input type="text" class="form-control" disabled value="' + k.name + '" />'
                                            dom += '		</div>';
                                            dom += '	</div>';
                                            dom += '</div>';
                                        } else {

                                            dom += '<div class="col-xs-3">';
                                            dom += '	<div class="form-group">';
                                            dom += '		<div class="input-group">'
                                            dom += '			<span class="input-group-addon direction"><i class="fa fa-long-arrow-right fa-lg"></i></span>';
                                            dom += '			<input type="text" class="form-control" disabled value="' + k.name + '" />'
                                            dom += '		</div>';
                                            dom += '	</div>';
                                            dom += '</div>';
                                        }


                                    });

                                    $thumbnail.html(dom);

                                } else {
                                    $thumbnail.html('-- no drop points to be loaded --');
                                    initMap();
                                }
                                if (callback != undefined && typeof(callback) == 'function') {
                                    callback();
                                }

                                if (scinariosList != undefined && typeof(scinariosList) == 'object' && Object.keys(scinariosList).length > 0) {
                                    var selectDOM = '<option value="">Please select a cost scinario.</option>';
                                    $.each(scinariosList, function (i, scinario) {
                                        if (scinario.selected == 1) {
                                            selectDOM += '<option value="' + scinario.id + '" data-apt="' + scinario.affects_per_trip + '" data-ac="' + scinario.auto_calculate + '" selected>' + scinario.scinario + '</option>';

                                            if(scinario.auto_calculate == 1){
                                                $('.costCategoriesWrapper').show();
                                            }else{
                                                $('.costCategoriesWrapper').hide();
                                            }

                                        } else {
                                            selectDOM += '<option value="' + scinario.id + '" data-apt="' + scinario.affects_per_trip + '" data-ac="' + scinario.auto_calculate + '">' + scinario.scinario + '</option>';
                                        }
                                    });
                                    $('.costScinarios').html(selectDOM);
                                }

                                if (typeof(costResult) == 'object' && Object.keys(costResult).length > 0) {
                                    if (costResult.hasOwnProperty('cost')) {
                                        // $('.cost').val(costResult.cost);
                                        //check : commented for no reason . same functionality done in calculateTotalDistance
                                    } else if (costResult.hasOwnProperty('placeholder')) {
                                        $('.cost').val('').attr('placeholder', costResult.placeholder);
                                    }
                                }


                                if(typeof(per_km_categories) == 'object' && Object.keys(per_km_categories).length > 0){
                                    var selectDOM = '<option value="">Please select a cost category.</option>';
                                    $.each(per_km_categories, function (i, category) {

                                        if (category.selected == 1) {
                                            selectDOM += '<option value="' + category.id + '" data-category="' + category.category + '" data-slug="' + category.slug + '" data-rate="'+ category[category.slug] +'" selected>' + category.category + '</option>';

                                        } else {
                                            selectDOM += '<option value="' + category.id + '" data-category="' + category.category + '" data-slug="' + category.slug + '" data-rate="'+ category[category.slug] +'">' + category.category + '</option>';

                                        }
                                    });
                                    $('.costCategories').html(selectDOM);
                                }

                                if(e.label != undefined && e.label.length > 0){
                                    $('.summary_title').html(e.label);
                                }else{
                                    $('.summary_title').html('');
                                }



                                loadSummaryTitle();
                            }, 'json');
                        }
                    }

                });
            }


            function loadSummaryTitle() {
                var data = {
                    trip_id: $('.tripsList option:selected').val(),
                    vehicle_id: $('.vehiclesList option:selected').val()
                };
                $.post("<?php echo e(url('tripmanagement/loadSummaryTitle')); ?>", {_token: _token, data: data}, function (e) {
                    $('.summary_title').html(e.label);
                    $('#tripCost').html((+e.tripCost).toFixed(2));

                    if(e.hasOwnProperty('cost_scinario')){
                        $('.ap_direct_deliveries').val(+e.cost_scinario.ap_direct_deliveries > 0 ? e.cost_scinario.ap_direct_deliveries : '');
                        $('.ap_offloading_charges').val(+e.cost_scinario.ap_offloading_charges > 0 ? e.cost_scinario.ap_offloading_charges : '');
                        $('.ap_demurrages').val(+e.cost_scinario.ap_demurrages > 0 ? e.cost_scinario.ap_demurrages : '');
                        $('.ap_other').val(+e.cost_scinario.ap_other > 0 ? e.cost_scinario.ap_other : '');
                        $('.d_document_errors').val(+e.cost_scinario.d_document_errors > 0 ? e.cost_scinario.d_document_errors : '');
                        $('.d_other').val(+e.cost_scinario.d_other > 0 ? e.cost_scinario.d_other : '');
                    }


                }, 'json');
            }

        });

    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>