﻿var routestepGraphs = [];
var addRouteGraphicLine = [];
var routeUniqueId;

var routePoints = [];
var beginAddPoints = false;
var turnSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 7, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 1), new dojo.Color([255, 255, 0, 0.5]));
var startSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 15, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 1), new dojo.Color([0, 255, 0, 0.5]));
var stopSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 15, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 1), new dojo.Color([255, 0, 0, 0.5]));
var middleSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 15, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 1), new dojo.Color([0, 0, 255, 0.5]));

function addRoutePoint(uniqueId) {

    routePoints.push(uniqueId);
    $('#accordion').accordion('activate', 4);

    var point = terra.map.graphManager.graphList[uniqueId];

    if (point.isDrivePoint == true) { return; }
    point.isDrivePoint = true;

    //html = "<li class='ui-state-default' id='" + uniqueId + "'>" + point.description + "<div class='uniq_div' style='display:none'>" + uniqueId + "</div> <a title='Αφαίρεση' onclick='removeFromRoutePoints(\"" + uniqueId + "\",false);' href='#'><span style='display:inline' class='ui-icon ui-icon-close'></span></a></li>";
    html = "<li class='ui-state-default ui-corner-all' id='" + uniqueId + "'><div class='descDiv' style='display:inline;'>" + point.description + "</div> <div title='Αφαίρεση' style='display:inline;cursor:pointer;margin-left:15px' onclick='removeFromRoutePoints(\"" + uniqueId + "\",false);' href='#'>X</div></li>";

    $('#routePoints').append(html);
    $("#routePoints").sortable('refresh');


    //    var turnSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 7, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 1), new dojo.Color([255, 255, 255, 0.5]));
    //    var turnPointGraphic;
    //    var symbol;
    //    if (routePoints.length == 1) {
    //        symbol = startSymbol
    //    } else {
    //        symbol = stopSymbol
    //    }
    //    var turnPointGeom = new esri.geometry.Point(xC, yC, new esri.SpatialReference({ wkid: 2100 })); ;
    //    //if (isWGS84 == true) {
    //    //    turnPointGeom = esri.geometry.geographicToWebMercator(turnPointGeom);
    //    // }
    //    turnPointGraphic = new esri.Graphic(turnPointGeom, symbol);
    //    addRouteGraphic(turnPointGraphic);
    //    if (routePoints.length == 2) {findRoute();}

}

function updateRouteDesc(uni, desc) {

    //check if marker is in route
    $("#routePoints li").each(function() {
        var tmpUniqueId = $(this).attr('id');
        if (tmpUniqueId == uni) {
            $(this).find('.descDiv').html(desc);
            return;
        }
    });

}


function removeFromRoutePoints(uniqueId) {

    var point = terra.map.graphManager.graphList[uniqueId];

    point.isDrivePoint = false;
    $('#routePoints').find('#' + uniqueId).remove();
    $("#routePoints").sortable('refresh');

}

function clearRoute() {

    clearRouteGraphs();

    beginAddPoints = false;
    routePoints = new Array();

    if (routeUniqueId) {
        try {
            terra.map.graphManager.removeGr(routeUniqueId);
            routeUniqueId = null;
        } catch (e) {

        }
    }

    $('#routeFindResults').html('');

}

function clearRouteGraphs() {

    $.each(routestepGraphs, function() {
        map.graphics.remove(this);

    });
    routestepGraphs = new Array();

    $.each(addRouteGraphicLine, function() {
        map.graphics.remove(this);

    });

    addRouteGraphicLine = new Array();

}

function addRouteGraphic(graph) {
    map.graphics.add(graph);
    routestepGraphs.push(graph);
}

function addRouteGraphicL(graph) {
    map.graphics.add(graph);
    addRouteGraphicLine.push(graph);
}

function getRouteStops() {

    var routeStops = [];
    $("#routePoints li").each(function() {

        var uniqueId = $(this).attr('id');
        var point = terra.map.graphManager.graphList[uniqueId];

        routeStops.push({ "x": point.geometry.x, "y": point.geometry.y, "stopName": point.description, "stopId": uniqueId });

    });

    return routeStops;

}

function countRoutePoints() {

    var routeStops = 0;
    $("#routePoints li").each(function() {
        routeStops += 1;
    });
    return routeStops;
}

function findRoute() {

    //var param = routePoints[0].x + "$" + routePoints[0].y + "$" + routePoints[1].x + "$" + routePoints[1].y;   // 4206761$478838$4196855 ;//$.compactJSON(routePoints)


    $('#routeFindResults').html('Παρακαλώ περιμένετε … ');

    //getRoute(string stops, bool bestRoute, bool preserveFirst, bool preserveLast)

    var countStops = countRoutePoints();

    if (countStops < 2) {

        $("#dialogMissingPoints").dialog({
            autoOpen: false,
            bgiframe: true,
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                }
            }
        });

        $("#dialogMissingPoints").dialog('open');

        return;
    }

    var stops = getRouteStops();

    map.infoWindow.hide();

    //var selected = $('#chkFindBestRoute').attr('checked');
    //$('#chkPreserveFirstStop').attr('disabled', 'disabled');
    //$('#chkPreserveLastStop').attr('disabled', 'disabled');

    var bestRoute = $('#chkFindBestRoute').attr('checked');
    var preserveFirst = $('#chkPreserveFirstStop').attr('checked');
    var preserveLast = $('#chkPreserveLastStop').attr('checked');

    $.ajax({
        type: "POST",
        url: "webservice.asmx/getRoute",
        dataType: "xml",
        data:
		            {
		                "routeStopsJSON": $.toJSON(stops),
		                "bestRoute": bestRoute,
		                "preserveFirst": preserveFirst,
		                "preserveLast": preserveLast
		            },
        success: function(xml) {

            var data = $.evalJSON($(xml).find("string").text());


            if (data.routeSteps.length == 0) {
                alert('Δεν βρέθηκε καμία διαδρομή');
                $('#routeFindResults').html('');
                return;
            }

            clearRoute();

            $('#routeResultsDisplay').show('fast');
            $('#routeParameters').hide();

            var routeExtent = new esri.geometry.Extent(
                    data.routeExtent.pointMin.x,
                    data.routeExtent.pointMin.y,
                    data.routeExtent.pointMax.x,
                    data.routeExtent.pointMax.y,
                    new esri.SpatialReference({ wkid: 2100 }));

            //if (isWGS84 == true) {
            //    routeExtent = esri.geometry.geographicToWebMercator(routeExtent);
            //}


            //Create route lines
            var lineSymb = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 255, 0.5]), 5);
            var routePath = new Array();
            $.each(data.routePoints, function() {

                var line = new esri.geometry.Point(this.x, this.y, new esri.SpatialReference({ wkid: 2100 }));

                //if (isWGS84 == true) {
                //    line = esri.geometry.geographicToWebMercator(line);
                //}

                routePath.push(line);

            });

            var geom = new esri.geometry.Polyline();
            geom.setSpatialReference(new esri.SpatialReference({ wkid: 2100 }));
            geom.addPath(routePath);

            routeUniqueId = guid();

            //////////////////////////////////////////////////////////////////////////////////////////
            // WARNING the html must contain the word route in order not to diplay the infowindow();//
            //////////////////////////////////////////////////////////////////////////////////////////
            terra.map.graphManager.addNewGr(false, routeUniqueId, 3, 'Route', 'route', geom);
            ////////////////////////////////////////////////////////////////////////////////////////

            var turnPointInfo = new esri.InfoTemplate('Βήμα: ${count}', '${name}<br/>${nextprevius}');
            var stepList = '';

            var routeDuration = 0;
            var routeLength = 0;

            var i = 0;
            for (var l = 0; l < data.routeSteps.length; l++) {

                var cStep = data.routeSteps[l];

                //this means routeStep
                //alert(this.stepDescriptionGR);

                var symb = turnSymbol;

                var uid = cStep.stepPointCoord.stopId;
                var name = cStep.stepPointCoord.stopName;
                var color = '';

                if (name != null) {
                    cStep.stepDescriptionGR = cStep.stepDescriptionGR.replace(name, '<b>' + name + '</b>');
                }

                if (i == 0) {
                    symb = startSymbol;
                    color = 'green';
                } else if (i == (data.routeSteps.length - 1)) {
                    symb = stopSymbol;
                    color = 'red';
                } else {
                    if (uid != null) {
                        color = 'blue';
                        symb = middleSymbol;
                    }
                }

                var nextHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Επόμενο' onclick='showRouteStep(" + (i + 1) + ");' href='#'><span class='ui-icon ui-icon-circle-arrow-e'></span></a></div></td>";
                var lastHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Προορισμός' onclick='showRouteStep(" + (data.routeSteps.length - 1) + ");' href='#'><span class='ui-icon ui-icon-seek-end'></span></a></div></td>";
                var prevHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Προηγούμενο' onclick='showRouteStep(" + (i - 1) + ");' href='#'><span class='ui-icon ui-icon-circle-arrow-w'></span></a></div></td>";
                var firstHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Αφετηρία' onclick='showRouteStep(" + (0) + ");' href='#'><span class='ui-icon ui-icon-seek-first'></span></a></div></td>";

                var navHTML = "<br/><br/><div id='popupcommands'><table><tr>";

                if (i == 0)
                    navHTML += "<br/>" + nextHTML + "   " + lastHTML;
                else if (i == (data.routeSteps.length - 1))
                    navHTML += "<br/>" + firstHTML + "   " + prevHTML;
                else
                    navHTML += "<br/>" + firstHTML + "   " + prevHTML + "   " + nextHTML + "   " + lastHTML;

                navHTML += "</tr></table></div>";

                var turnGeom = new esri.geometry.Point(cStep.stepPointCoord.x, cStep.stepPointCoord.y, new esri.SpatialReference({ wkid: 2100 }));

                //if (isWGS84 == true) {
                //    turnGeom = esri.geometry.geographicToWebMercator(turnGeom);
                //}

                var x = cStep.stepPointCoord.x;
                var y = cStep.stepPointCoord.y;

                var extraContent = '';

                //extraContent += "<br/><br/><a href='#' onclick='addNewCorrection(" + x + "," + y + ",true,false);'>Αναφορά λάθους σε αυτό το σημείο</a>";
                //extraContent += "<div style='color:gray;font-size:10px;font-family:verdana;'>(μπορείτε να καταχωρίσετε και άλλα σημεία χρησιμοποιώντας το αριστερό μενού)</div>";

                navHTML += extraContent;

                var turnPontGraphic = new esri.Graphic(turnGeom, symb, { name: cStep.stepDescriptionGR, nextprevius: navHTML, count: i }, turnPointInfo);
                addRouteGraphic(turnPontGraphic);

                //var backcolor = '#FFFFCC';
                //  if ((i % 2) == 1) { backcolor = '#CCCCCC'; }

                var listHTML = "<a href='#' style='font-size:9pt;color:" + color + "' onclick='showRouteStep(" + i + ");return false;'>" + (i + 1) + ". " + cStep.stepDescriptionGR + "</a><br/>";
                stepList += listHTML;

                routeDuration += cStep.stepTime;
                routeLength += cStep.stepDistance;

                i++;

            }

            var htmlTotal = '';

            routeDuration += " ";
            routeLength += " ";

            var routeD = '';
            var Char;
            for (i = 0; i < routeDuration.length; i++) {
                Char = routeDuration.charAt(i);
                if (Char == '.') {
                    break
                }
                else {
                    routeD += Char;
                }
            }

            var routeL = '';
            for (i = 0; i < routeLength.length; i++) {
                Char = routeLength.charAt(i);
                if (Char == '.') {
                    routeL += "." + routeLength.charAt(i + 1);
                    break;
                }
                else {
                    routeL += Char;
                }
            }

            setTimeout(function() { map.setExtent(geom.getExtent()); }, 5);

            htmlTotal += 'Συνολικός χρόνος :<b>' + routeD + ' λεπτά</b>';
            htmlTotal += '<br/>Συνολική απόσταση :<b>' + routeL + ' χλμ.</b>';

            $('#routeFindResultsTotal').html(htmlTotal);
            $('#routeFindResults').html(stepList);

            $('#addRouteByPoint').hide();
            $('#clearRouteBtn').show('fast');

        }
    });

}

function findRouteΜΜΜ() {

    //var param = routePoints[0].x + "$" + routePoints[0].y + "$" + routePoints[1].x + "$" + routePoints[1].y;   // 4206761$478838$4196855 ;//$.compactJSON(routePoints)


    $('#routeFindResults').html('Παρακαλώ περιμένετε … ');

    //getRoute(string stops, bool bestRoute, bool preserveFirst, bool preserveLast)

    var countStops = countRoutePoints();

    if (countStops != 2) {

        $("#dialogMissingPoints").dialog({
            autoOpen: false,
            bgiframe: true,
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                }
            }
        });

        $("#dialogMissingPoints").dialog('open');

        return;
    }

    var stops = getRouteStops();

    map.infoWindow.hide();

    //var selected = $('#chkFindBestRoute').attr('checked');
    //$('#chkPreserveFirstStop').attr('disabled', 'disabled');
    //$('#chkPreserveLastStop').attr('disabled', 'disabled');

    var bestRoute = $('#chkFindBestRoute').attr('checked');
    var preserveFirst = $('#chkPreserveFirstStop').attr('checked');
    var preserveLast = $('#chkPreserveLastStop').attr('checked');

    $.ajax({
        type: "POST",
        url: "webservice.asmx/getRouteMMM",
        dataType: "xml",
        data:
		            {
		                "routeStopsJSON": $.toJSON(stops),
		                "bestRoute": bestRoute,
		                "preserveFirst": preserveFirst,
		                "preserveLast": preserveLast
		            },
        success: function(xml) {

            var data = $.evalJSON($(xml).find("string").text());


            if (data.routeSteps.length == 0) {
                alert('Δεν βρέθηκε καμία διαδρομή');
                $('#routeFindResults').html('');
                return;
            }

            clearRoute();

            $('#routeResultsDisplay').show('fast');
            $('#routeParameters').hide();


            // routeUniqueId = guid();

            //////////////////////////////////////////////////////////////////////////////////////////
            // WARNING the html must contain the word route in order not to diplay the infowindow();//
            //////////////////////////////////////////////////////////////////////////////////////////
            // terra.map.graphManager.addNewGr(false, routeUniqueId, 3, 'Route', 'route', geom);
            ////////////////////////////////////////////////////////////////////////////////////////

            var turnPointInfo = new esri.InfoTemplate('Βήμα: ${count}', '${name}<br/>${nextprevius}');
            var stepList = '';

            var routeDuration = 0;
            var routeLength = 0;

            var i = 0;
            for (var l = 0; l < data.routeSteps.length; l++) {

                var cStep = data.routeSteps[l];

                //this means routeStep
                //alert(this.stepDescriptionGR);

                var symb = turnSymbol;

                var uid = cStep.stepPointCoord.stopId;
                var name = cStep.stepPointCoord.stopName;
                var color = '';

                if (name != null) {
                    cStep.stepDescriptionGR = cStep.stepDescriptionGR.replace(name, '<b>' + name + '</b>');
                }

                if (i == 0) {
                    symb = startSymbol;
                    color = 'green';
                } else if (i == (data.routeSteps.length - 1)) {
                    symb = stopSymbol;
                    color = 'red';
                } else {
                    if (uid != null) {
                        color = 'blue';
                        symb = middleSymbol;
                    }
                }

                var nextHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Επόμενο' onclick='showRouteStep(" + (i + 1) + ");' href='#'><span class='ui-icon ui-icon-circle-arrow-e'></span></a></div></td>";
                var lastHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Προορισμός' onclick='showRouteStep(" + (data.routeSteps.length - 1) + ");' href='#'><span class='ui-icon ui-icon-seek-end'></span></a></div></td>";
                var prevHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Προηγούμενο' onclick='showRouteStep(" + (i - 1) + ");' href='#'><span class='ui-icon ui-icon-circle-arrow-w'></span></a></div></td>";
                var firstHTML = "<td><div class='ui-state-default ui-corner-all'><a  title='Αφετηρία' onclick='showRouteStep(" + (0) + ");' href='#'><span class='ui-icon ui-icon-seek-first'></span></a></div></td>";

                var navHTML = "<br/><br/><div id='popupcommands'><table><tr>";

                if (i == 0)
                    navHTML += "<br/>" + nextHTML + "   " + lastHTML;
                else if (i == (data.routeSteps.length - 1))
                    navHTML += "<br/>" + firstHTML + "   " + prevHTML;
                else
                    navHTML += "<br/>" + firstHTML + "   " + prevHTML + "   " + nextHTML + "   " + lastHTML;

                navHTML += "</tr></table></div>";

                var turnGeom = new esri.geometry.Point(cStep.stepPointCoord.x, cStep.stepPointCoord.y, new esri.SpatialReference({ wkid: 2100 }));

                //if (isWGS84 == true) {
                //    turnGeom = esri.geometry.geographicToWebMercator(turnGeom);
                //}

                var x = cStep.stepPointCoord.x;
                var y = cStep.stepPointCoord.y;

                var extraContent = '';

                //extraContent += "<br/><br/><a href='#' onclick='addNewCorrection(" + x + "," + y + ",true,false);'>Αναφορά λάθους σε αυτό το σημείο</a>";
                //extraContent += "<div style='color:gray;font-size:10px;font-family:verdana;'>(μπορείτε να καταχωρίσετε και άλλα σημεία χρησιμοποιώντας το αριστερό μενού)</div>";

                navHTML += extraContent;

                var turnPontGraphic = new esri.Graphic(turnGeom, symb, { name: cStep.stepDescriptionGR, nextprevius: navHTML, count: i }, turnPointInfo);
                addRouteGraphic(turnPontGraphic);

                //var backcolor = '#FFFFCC';
                //  if ((i % 2) == 1) { backcolor = '#CCCCCC'; }

                var listHTML = "<a href='#' style='font-size:9pt;color:" + color + "' onclick='showRouteStep(" + i + ");return false;'>" + (i + 1) + ". " + cStep.stepDescriptionGR + "</a><br/><br/>";
                stepList += listHTML;

                routeDuration += cStep.stepTime;
                routeLength += cStep.stepDistance;

                i++;

            }

            var htmlTotal = '';

            routeDuration += " ";
            routeLength += " ";

            var routeD = '';
            var Char;
            for (i = 0; i < routeDuration.length; i++) {
                Char = routeDuration.charAt(i);
                if (Char == '.') {
                    break
                }
                else {
                    routeD += Char;
                }
            }

            var routeL = '';
            for (i = 0; i < routeLength.length; i++) {
                Char = routeLength.charAt(i);
                if (Char == '.') {
                    routeL += "." + routeLength.charAt(i + 1);
                    break;
                }
                else {
                    routeL += Char;
                }
            }

            // setTimeout(function() { map.setExtent(geom.getExtent()); }, 5);

            htmlTotal = data.routeComments;


            $('#routeFindResultsTotal').html(htmlTotal);
            $('#routeFindResults').html(stepList);

            $('#addRouteByPoint').hide();
            $('#clearRouteBtn').show('fast');

        }
    });

}
function showRouteStep(i) {

    var g = routestepGraphs[i];
    map.centerAt(g.geometry);

    map.infoWindow.hide();
    map.infoWindow.resize(350, 170);
    map.infoWindow.hide();

    map.infoWindow.setContent(g.getContent());
    map.infoWindow.setTitle(g.getTitle());
    map.infoWindow.show(map.toScreen(g.geometry), map.getInfoWindowAnchor(map.toScreen(g.geometry)));

    //map.infoWindow.show();

}