﻿
if (!terra.map.graphManager) terra.map.graphManager = {};
if (!terra.map.graphManagerObject) terra.map.graphManagerObject = function() { };

terra.map.graphManager = {

    uniqueId: null,
    savedGraphics: null,
    savedDivId: 'savedGraphicsDiv',
    drivingDiv: 'drivingPoints',
    graphList: { 0: "" },
    pointCounter: 1,

    getNewCounter: function() {
        return this.pointCounter++;
    },

    addNewGr: function(isSaved, uniqueId, type, description, html, geometry) {

        if (uniqueId in this.graphList) {

            this.showGr(uniqueId);

        } else {

            var newGr = new terra.map.graphManagerObject();
            newGr.uniqueId = uniqueId;
            newGr.type = type;
            newGr.description = description;
            newGr.html = html;
            newGr.isSaved = isSaved;
            newGr.geometry = geometry;

            this.graphList[uniqueId] = newGr;

            map.graphics.add(newGr.getGraphic());

            this.showGr(uniqueId);


        }

    },

    showGr: function(uniqueId) {

        var cS = this.graphList[uniqueId];
        
        var isroutegraph = new RegExp("route");
        if (!cS.html.match(isroutegraph)) {
            cS.openInfoWindow();
        }



    },

    removeGr: function(uniqueId) {

        if (this.graphList[uniqueId].isDrivePoint == true) {
            removeFromRoutePoints(uniqueId);
        }

        if (this.graphList[uniqueId].isDriveTime == true) {
            this.selectForDriveTime(uniqueId, false);
        }

        map.graphics.remove(this.graphList[uniqueId].getGraphic());
        map.infoWindow.hide();
        delete this.graphList[uniqueId];

    },

    saveGr: function(uniqueId) {

        var obj = this.graphList[uniqueId];

        $.ajax({
            type: "POST",
            url: "webservice.asmx/saveMarker",
            dataType: "xml",
            data:
		    {
		        "uid": obj.uniqueId,
		        "typeId": obj.type,
		        "esriType": obj.geometry.type,
		        "desc": obj.description,
		        "longDesc": obj.html,
		        "geomData": $.toJSON(obj.geometry.toJson()),
		        "email": false

		    },
            success: function(xml) {

                var data = $.evalJSON($(xml).find("string").text());

                if (data.resType == 1) {

                    //alert(data.message); 

                    terra.map.graphManager.removeGr(uniqueId);
                    terra.map.graphManager.getSavedGraphics(uniqueId);

                    $('#accordion').accordion('activate', 3);

                    //terra.map.graphManager.graphList[uniqueId].isSaved = true;

                }
                else {
                    alert(data.message);
                }

            }

        });

    },

    deleteGr: function(uniqueId) {

        terra.map.graphManager.uniqueId = uniqueId;

        $("#dialogDelete").dialog(
		{

		    autoOpen: false,
		    bgiframe: true,
		    resizable: false,
		    height: 140,
		    modal: true,
		    overlay: {
		        backgroundColor: '#000',
		        opacity: 0.5
		    },

		    buttons: {
		        'Διαγραφή': function() {

		            terra.map.graphManager.executeDelete();
		            $(this).dialog('close');

		        },
		        'Άκυρο': function() {
		            $(this).dialog('close');
		        }
		    }

		});

        $("#dialogDelete").dialog('open');

    },

    sendEmail: function(uid) {

        terra.map.graphManager.uniqueId = uid;
        var obj = this.graphList[terra.map.graphManager.uniqueId];

        $("#dialogSendEmail").dialog(
		{

		    autoOpen: false,
		    bgiframe: true,
		    resizable: false,
		    height: 340,
		    width: 400,
		    modal: true,
		    overlay: {
		        backgroundColor: '#000',
		        opacity: 0.5
		    },

		    buttons: {

		        'Αποστολή': function() {

		            var sender = $('#dialogSendEmail_Sender').val();
		            var recipients = $('#dialogSendEmail_Recipients').val();
		            var subject = $('#dialogSendEmail_Subject').val();
		            var comments = $('#dialogSendEmail_Comments').val();

		            terra.map.graphManager.executeSendEmail(terra.map.graphManager.uniqueId, sender, recipients, subject, comments);

		        },
		        'Άκυρο': function() {
		            $(this).dialog('close');
		        }
		    }

		});

        $('#dialogSendEmail_Subject').val(obj.description);
        $("#dialogSendEmail").dialog('open');

    },

    executeSendEmail: function(uid, sender, recipients, subject, comments) {

        var obj = this.graphList[uid];

        $.ajax({
            type: "POST",
            url: "webservice.asmx/sendEmail",
            dataType: "xml",
            data:
		                    {
		                        "fromEmail": sender,
		                        "mailList": recipients,
		                        "subject": subject,
		                        "comments": comments,
		                        "typeId": obj.type,
		                        "esriType": obj.geometry.type,
		                        "desc": obj.description,
		                        "longDesc": obj.html,
		                        "geomData": $.toJSON(obj.geometry.toJson())

		                    },

            success: function(xml) {
                var data = $.evalJSON($(xml).find("string").text());
                terra.map.graphManager.mailSendStatus(data);

            }

        });

    },
	
	 mailSendStatus_problem: function(data) {

        if (data.resType == 1) {

           // $("#dialogSendEmail").dialog('close');

            $("#dialogSendProblemSuccess").dialog(
        	{
        	    autoOpen: false,
        	    bgiframe: true,
        	    resizable: true,
        	    height: 340,
        	    width: 400,
        	    modal: true,
        	    overlay: {
        	        backgroundColor: '#000',
        	        opacity: 0.5
        	    },
        	    buttons: {
        	        'Ok': function() {
        	            $(this).dialog('close');
        	        }
        	    }
        	});

            $("#dialogSendProblemSuccess").dialog('open');
            return;



        }
        else {
            alert(data.message);
        }

    },
  mailSendStatus_contact: function(data) {

        if (data.resType == 1) {

            $("#dialogSendEmail").dialog('close');

            $("#dialogSendContactSuccess").dialog(
        	{
        	    autoOpen: false,
        	    bgiframe: true,
        	    resizable: true,
        	    height: 340,
        	    width: 400,
        	    modal: true,
        	    overlay: {
        	        backgroundColor: '#000',
        	        opacity: 0.5
        	    },
        	    buttons: {
        	        'Ok': function() {
        	            $(this).dialog('close');
        	        }
        	    }
        	});

            $("#dialogSendContactSuccess").dialog('open');
            return;



        }
        else {
            alert(data.message);
        }

    },
    mailSendStatus: function(data) {

        if (data.resType == 1) {

            $("#dialogSendEmail").dialog('close');

            $("#dialogSendEmailSuccess").dialog(
        	{
        	    autoOpen: false,
        	    bgiframe: true,
        	    resizable: true,
        	    height: 340,
        	    width: 400,
        	    modal: true,
        	    overlay: {
        	        backgroundColor: '#000',
        	        opacity: 0.5
        	    },
        	    buttons: {
        	        'Ok': function() {
        	            $(this).dialog('close');
        	        }
        	    }
        	});

            $("#dialogSendEmailSuccess").dialog('open');
            return;



        }
        else {
            alert(data.message);
        }

    },

    executeDelete: function() {

        var obj = this.graphList[terra.map.graphManager.uniqueId];

        $.ajax({
            type: "POST",
            url: "webservice.asmx/deleteMarker",
            dataType: "xml",
            data:
		            {
		                "uid": obj.uniqueId
		            },
            success: function(xml) {

                var data = $.evalJSON($(xml).find("string").text());

                if (data.resType == 1) {
                    //
                    terra.map.graphManager.getSavedGraphics();
                    terra.map.graphManager.removeGr(terra.map.graphManager.uniqueId);
                    //alert(data.message);
                }
                else {
                    alert(data.message);
                }

            }

        });

    },

    populateDrivingPoints: function() {

        var html = '<table>';
        for (var key in this.graphList) {

            var objM = this.graphList[key];
            if (objM.type == 1) {

                if (objM.isDriveTime == true) {

                    html += "<tr>";
                    html += "<td><a href='#' onclick='terra.map.graphManager.showGr(\"" + objM.uniqueId + "\")'>" + objM.description + "</a></td>";
                    html += "<td><a title='Αφαίρεση' onclick='terra.map.graphManager.selectForDriveTime(\"" + objM.uniqueId + "\",false);' href='#'><span class='ui-icon ui-icon-close'></span></a></td>";
                    html += "</tr>";
                    //html + = "<input id='chk_" + objM.uniqueId + "' type='checkbox' " + selected + " onclick='terra.map.graphManager.selectForDriveTime(\"" + objM.uniqueId + "\",$(this).attr(\"checked\"),true, null)' /> 
                }

            }

        }

        html += '</table>';
        $('#' + terra.map.graphManager.drivingDiv).html(html);
        $('#accordion').accordion('activate', 4);

    },

    selectForDriveTime: function(uniqueId, enable) {

        this.graphList[uniqueId].isDriveTime = enable;
        this.populateDrivingPoints();

    },

    // selectForDriveTime: function(uniqueId, enable, searchOnMap, i) {
    //        if (enable == true) {
    //            if (searchOnMap == true) {
    //                terra.map.graphManager.showGr(uniqueId);
    //                $('#chk_' + uniqueId).attr('checked', true);
    //                terra.map.graphManager.graphList[uniqueId].isDriveTime = true;
    //            } else {
    //                terra.map.graphManager.showSavedGraphic(i);
    //                $('#chk_' + uniqueId).attr('checked', true);
    //                var uid = terra.map.graphManager.savedGraphics[i].uniqueId;
    //                terra.map.graphManager.graphList[uid].isDriveTime = true;
    //            }
    //        } else {
    //            //$('#chk_' + uniqueId).attr('checked', false);
    //            terra.map.graphManager.graphList[uniqueId].isDriveTime = false;
    //        }
    // },

    getDrivingTimesGraphs: function() {

        var gList = [];
        for (var key in this.graphList) {
            var objM = this.graphList[key];
            if (objM.type == 1 && objM.isDriveTime == true) {
                gList.push({ 'graph': objM.graphic, 'desc': objM.description, 'longDesc': 'Drive time zone ' + objM.description });
            }
        }
        return gList;

    },

    getStreetGeometry: function(uniqueId) {

        var obj = this.graphList[uniqueId];

        $.ajax({
            type: "POST",
            url: "webservice.asmx/getStreetGeometry",
            dataType: "xml",
            data:
		            {
		                "x": obj.geometry.x,
		                "y": obj.geometry.y
		            },
            success: function(xml) {

                var data = $.evalJSON($(xml).find("string").text());

                if (data.length > 0) {

                    //
                    var geomJSON = $.evalJSON(data[0].addFormated);
                    var geom = esri.geometry.fromJson(geomJSON);
                    terra.map.graphManager.addNewGr(false, guid(), 3, data[0].addStreet, data[0].addStreet, geom);

                    //alert(data.message);
                }
                else {
                    //alert(data.message);
                }

            }
        });

    },
    createBuffer: function(uniqueId) {

        terra.map.graphManager.uniqueId = uniqueId;

        $("#dialogBuffer").dialog(
		{

		    autoOpen: false,
		    bgiframe: true,
		    resizable: false,
		    height: 140,
		    modal: true,
		    overlay: {
		        backgroundColor: '#000',
		        opacity: 0.5
		    },
		    buttons: {

		        'Δημιουργία': function() {

		            var radius = $('#dialogBuffer_txtRadius').val();

		            if (radius.match(/^\d+$/)) {
		                $(this).dialog('close');
		                terra.map.graphManager.executeBuffer();
		            } else {
		                alert('Invalid number');
		            }

		        },
		        'Άκυρο': function() {
		            $(this).dialog('close');
		        }
		    }

		});

        $("#dialogBuffer").dialog('open');

    },

    renameMarker: function(uniqueId) {

        terra.map.graphManager.uniqueId = uniqueId;


        $("#dialogRename").dialog(
		{

		    autoOpen: false,
		    bgiframe: true,
		    resizable: true,
		    height: 330,
		    width: 400,
		    modal: true,
		    overlay: {
		        backgroundColor: '#000',
		        opacity: 0.5
		    },
		    buttons: {

		        'Αλλαγή': function() {

		            var desc = $('#dialogRename_title').val();
		            var longdesc = $('#dialogRename_description').val();
		            var obj = terra.map.graphManager.graphList[terra.map.graphManager.uniqueId];

		            if (obj.isSaved == true) {
		                $.ajax({
		                    type: "POST",
		                    url: "webservice.asmx/updateMarker",
		                    dataType: "xml",
		                    data:
		                    {
		                        "uid": obj.uniqueId,
		                        "desc": desc,
		                        "longDesc": longdesc
		                    },
		                    success: function(xml) {

		                        var data = $.evalJSON($(xml).find("string").text());

		                        if (data.resType == 1) {

		                            //
		                            var obj = terra.map.graphManager.graphList[terra.map.graphManager.uniqueId];
		                            obj.description = $('#dialogRename_title').val();
		                            obj.html = $('#dialogRename_description').val();
		                            obj.graphic.setInfoTemplate(obj.getInfoWindow());
		                            map.infoWindow.hide();
		                            $("#dialogRename").dialog('close');

		                            terra.map.graphManager.showGr(obj.uniqueId);
		                            terra.map.graphManager.getSavedGraphics(null);

		                            updateRouteDesc(obj.uniqueId, obj.description);


		                        }
		                        else {
		                            alert(data.message);
		                        }

		                    }

		                });

		            } else {

		                var obj = terra.map.graphManager.graphList[terra.map.graphManager.uniqueId];
		                obj.description = $('#dialogRename_title').val();
		                obj.html = $('#dialogRename_description').val();
		                obj.graphic.setInfoTemplate(obj.getInfoWindow());
		                map.infoWindow.hide();
		                $("#dialogRename").dialog('close');

		                terra.map.graphManager.showGr(obj.uniqueId);

		                updateRouteDesc(obj.uniqueId, obj.description);

		            }


		        },
		        'Άκυρο': function() {
		            $(this).dialog('close');
		        }
		    }

		});

        var obj = terra.map.graphManager.graphList[terra.map.graphManager.uniqueId];

        $('#dialogRename_title').val(obj.description);
        $('#dialogRename_description').val(obj.html);

        $("#dialogRename").dialog('open');

    },
    executeBuffer: function() {

        var obj = this.graphList[terra.map.graphManager.uniqueId];

        //    function getBuffer(geometry, foundfeatures) {

        var params = new esri.tasks.BufferParameters();

        params.features = [obj.graphic];

        params.distances = [$('#dialogBuffer_txtRadius').val()];
        params.unit = esri.tasks.BufferParameters.UNIT_METER;
        params.bufferSpatialReference = new esri.SpatialReference({ wkid: 2100 });

        gsvc.buffer(params, terra.map.graphManager.fillBuffer);




    },

    fillBuffer: function(buffer) {

        var radius = $('#dialogBuffer_txtRadius').val();
        var obj = terra.map.graphManager.graphList[terra.map.graphManager.uniqueId];

        terra.map.graphManager.addNewGr(false, guid(), 2, radius + 'm buffer από ' + obj.description, radius + 'm buffer από ' + obj.html, buffer[0].geometry)

    },

    getSavedGraphics: function(uniqueId) {

        $('#' + this.savedDivId).html('loading ...');

        $.ajax({
            type: "GET",
            url: "webservice.asmx/selectMarkers",
            dataType: "xml",
            success: function(xml) {

                var data = $.evalJSON($(xml).find("string").text());

                terra.map.graphManager.savedGraphics = data;

                var html = '';

                for (var i = 0; i < data.length; i++) {
                    html += "<br/><a href='#' onclick='terra.map.graphManager.showSavedGraphic(" + i + ")'>" + data[i].desc + "</a>";
                }

                $('#' + terra.map.graphManager.savedDivId).html(html);

                if (uniqueId != null) {
                    terra.map.graphManager.showSavedGraphicFromUniqueId(uniqueId);
                }

                //terra.map.graphManager.populateDrivingPoints();

            }

        });

    },

    getEmailGraphics: function(uniqueId) {

        $('#' + this.savedDivId).html('loading ...');

        $.ajax({
            type: "GET",
            url: "webservice.asmx/selectEmailMarkers",
            dataType: "xml",
            data:
		                    {
		                        "uniqueId": uniqueId
		                    },
            success: function(xml) {

                var data = $.evalJSON($(xml).find("string").text());

                if (data.length == 1) {

                    var geomJSON = $.evalJSON(data[0].geomData);
                    var geom = esri.geometry.fromJson(geomJSON);

                    terra.map.graphManager.addNewGr(true, data[0].uniqueId, data[0].typeID, data[0].desc, data[0].longDesc, geom);

                }
            }

        });

    },
    showSavedGraphic: function(i) {

        var geomJSON = $.evalJSON(this.savedGraphics[i].geomData);
        var geom = esri.geometry.fromJson(geomJSON);

        this.addNewGr(true, this.savedGraphics[i].uniqueId, this.savedGraphics[i].typeID, this.savedGraphics[i].desc, this.savedGraphics[i].longDesc, geom);

    },

    showSavedGraphicFromUniqueId: function(uniqueId) {

        var thisGraph;

        for (var i = 0; i < this.savedGraphics.length; i++) {
            if (this.savedGraphics[i].uniqueId == uniqueId) {
                thisGraph = this.savedGraphics[i];
                break;
            }
        }

        var geomJSON = $.evalJSON(thisGraph.geomData);
        var geom = esri.geometry.fromJson(geomJSON);

        this.addNewGr(true, this.savedGraphics[i].uniqueId, this.savedGraphics[i].typeID, this.savedGraphics[i].desc, this.savedGraphics[i].longDesc, geom);

    },

    executeQuery: function(uid) {

        var geom = this.graphList[uid].geometry;
        terra.map.layers.initQuerySERVICE(geom);

    }

}

terra.map.graphManagerObject.prototype = {

    uniqueId: null,
    dbId: null,
    type: null,
    isSaved: null,
    isDriveTime: false,
    isDrivePoint: false,
    description: null,
    html: null,
    geometry: null,
    graphic: null,
    getCommands: function() {

        var ret = '<div id="popupcommands" style="margin-top:20px"><table><tr>';
        //'<li title=".ui-icon-trash" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-trash"/></li>';
        
        if (this.type == 1) {	
			ret += "<td><div class='ui-state-default ui-corner-all'><a title='Αποστολή αιτήματος προς το Δήμο' onclick='sendpReportContactForm(" + this.geometry.x + "," + this.geometry.y + ");' href='#'><span class='ui-icon ui-icon-pencil'></span></a></div></td>";
			ret += "<td><div class='ui-state-default ui-corner-all'><a title='Αλλαγή περιγραφής' onclick='terra.map.graphManager.renameMarker(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-comment'></span></a></div></td>";
            ret += "<td><div class='ui-state-default ui-corner-all'><a  title='Πρόσθεση στα σημεία διαδρομής'  onclick='addRoutePoint(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-flag'></span></a></div></td>";
           // ret += "<td><div class='ui-state-default ui-corner-all'><a  title='Add to Driving time' onclick='terra.map.graphManager.selectForDriveTime(\"" + this.uniqueId + "\",true);' href='#'><span class='ui-icon ui-icon-plus'></span></a></div></td>";
           // ret += "<td><div class='ui-state-default ui-corner-all'><a  title='Επιλογή οδού'  onclick='terra.map.graphManager.getStreetGeometry(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-arrowthickstop-1-s'></span></a></div></td>";
        
		}

        // if (this.type == 2 || this.type == 3) {
        //     ret += "<td><div class='ui-state-default ui-corner-all'><a  title='Query' onclick='terra.map.graphManager.executeQuery(\"" + this.uniqueId + "\",true);' href='#'><span class='ui-icon ui-icon-script'></span></a></div></td>";
        // }

        switch (this.type) {

            case (1): case (3): //Point (Address, Poi, DrawnPoint)
                {
                  //  ret += "<td><div class='ui-state-default ui-corner-all'><a title = 'Buffer' onclick='terra.map.graphManager.createBuffer(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-radio-on'></span></a></div></td>";
                    break;
                }

        }

        ret += "<td><div class='ui-state-default ui-corner-all'><a  title='Αποστολή με e-mail'  onclick='terra.map.graphManager.sendEmail(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-mail-closed'></span></a></div></td>";
        ret += "<td><div class='ui-state-default ui-corner-all'><a title='Αφαίρεση' onclick='terra.map.graphManager.removeGr(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-close'></span></a></div></td>";
	
        if (this.isSaved == true) {
         //   ret += "<td><div class='ui-state-default ui-corner-all'><a title = 'Διαγραφή' onclick='terra.map.graphManager.deleteGr(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-trash'></span></a></div><td>";
        } else {
         //   ret += "<td><div class='ui-state-default ui-corner-all'><a title = 'Αποθήκευση' onclick='terra.map.graphManager.saveGr(\"" + this.uniqueId + "\");' href='#'><span class='ui-icon ui-icon-disk'></span></a></div></td>";
        }

        ret += "</tr></table></div>";
        return ret;

    },
    getSymbol: function() {

        var symbol;

        switch (this.type) {

            case (1): //Point (Address, Poi, DrawnPoint)
                {
                    symbol = 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.9]));
                    break;
                }
            case (2): //Polygons
                {
                    symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol("dashdot", new dojo.Color([255, 0, 0]), 1), new dojo.Color([255, 255, 0, 0.25]));
                    break;
                }

            case (3): //Lines
                {
                    symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 255, 0.5]), 5);
                    break;
                }
        }

        return symbol;

    },

    getGraphic: function() {

        if (this.graphic == null) {
            this.graphic = new esri.Graphic(this.geometry, this.getSymbol(), null, this.getInfoWindow());
        }

        return this.graphic;

    },

    getInfoWindow: function() {
        return new esri.InfoTemplate(this.description, this.html + this.getCommands());
    },

    openInfoWindow: function() {

        map.infoWindow.hide();

        var g = this.graphic;

        if (this.type == 1) {

            setTimeout(function() { map.centerAt(g.geometry); }, 5);
            map.infoWindow.resize(300, 120);
            map.infoWindow.setContent(g.getContent());
            map.infoWindow.setTitle(g.getTitle());
            map.infoWindow.show(map.toScreen(g.geometry), map.getInfoWindowAnchor(map.toScreen(g.geometry)));

        } else {

            //setTimeout(function() { map.setExtent(g.geometry.getExtent()); }, 5);
            map.infoWindow.resize(300, 120);
            map.infoWindow.setContent(g.getContent());
            map.infoWindow.setTitle(g.getTitle());
            map.infoWindow.show(map.toScreen(g.geometry), map.getInfoWindowAnchor(map.toScreen(g.geometry)));

        }

    }

};

