<?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 id="segmentDistance"></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" style="margin-bottom: 10px;">
                                    <input type="text" class="form-control cost" id="cost">
                                </div>
                                <div class="form-group" style="margin-bottom: 0px;">
                                    <button class="btn btn-sm btn-primary pull-left saveSegment" id="saveSegment">Save
                                        cost scinario
                                    </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
                });
            }
        }

        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);
                        });

                        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;
                    }
                }
            }
            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 calculateTotalDistance() {
            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;
                    }
                }
            }
            total = total / 1000;

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


            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');
            }

            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;
            }


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

        function getSegmentDistance(index) {
            index = +index;
            var total = 0;
            var cost = '0.00';
            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;
                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 = 0;
            if (typeof(index) == 'number' && index < collection.length) {
                scinario_id = collection[index].scinario_id;
                startTitle = collection[index].start.getTitle();
                endTitle = collection[index].end.getTitle();

                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;

            }


            document.getElementById('segmentFrom').innerHTML = startTitle;
            document.getElementById('segmentTo').innerHTML = endTitle;
            document.getElementById('segmentDistance').innerHTML = total + ' km';


            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;
                }
            }

        }

        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').innerHTML = '0 km';

                    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 = '';

                }
            }
        }

        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();
                });
            });

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

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

            $('.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');

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


                    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 * cpkm;

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

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

                            }
                        }

                    } else {

                        if (auto_calculate == 1) { // || auto_calculate == null
                            var totalDistance = getTotalDistance();

                            var totalTripCost = totalDistance * cpkm;

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

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


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

            $('.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(),
                                scinario: $('.costScinarios').val()
                            };

                            saveSegment(data, index);

                        }

                    } else {

                        var trip_data = {
                            'trip_id': $('.tripsList option:selected').val(),
                            'transporter_vehicle_id': $('.vehiclesList option:selected').val(),
                            'scinario_id': $('.costScinarios').val(),
                            'cost': $('.cost').val(),
                            'segments': [],
                            'total_distance': $('#tripDistance').text()
                        };
                        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,
                            };

                            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);
                                } else {
                                    if (index != undefined) {
                                        collection[index].cost = trip_data.cost;
                                    }
                                }
                            }
                        }
                        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;
                                    }
                                }
                            }
                        }
                        calculateTotalDistance();
                        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>';
                    var dom = '';
                    if (e != undefined && typeof(e) == 'object' && Object.keys(e).length > 0) {
                        $.each(e, function (i, k) {
                            if (k.selected == 1) {
                                dom += '<option value="' + k.id + '" selected>Trip #' + k.id + '</option>';
                            } else {
                                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-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;

                                    $.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>';
                                        } 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);
                                    } else if (costResult.hasOwnProperty('placeholder')) {
                                        $('.cost').val('').attr('placeholder', costResult.placeholder);
                                    }
                                }

                                $('.summary_title').html(e.label);
                            }, '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);
                }, 'json');
            }

        });

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