﻿var currentEditMarker;
var isoMapEditor = {

    "mapSettings": { "ID": null, "CenterPoint": { "X": "", "Y": "" }, "NorthEastPoint": { "X": "", "Y": "" }, "SouthWestPoint": { "X": "", "Y": "" }, "ZoomFactor": null },
    "ajaxStore": "AjaxStore.aspx",
    "epiReturnPointID": null,
    "addedPoints": [],
    "currentMapPicker": null,
    "isEditingMarker": false,
    "simpleEditCategories": [],
    "clearView": function() {
        window.returnValue = "none";
        window.close();

    },



    "returnView": function() {
        var returnStr = '';

        for (var i = 0; i < markers.length; i++) {
            var title = typeof (markers[i].title) == 'undefined' ? '' : markers[i].title;
            returnStr += '[' + markers[i].getLatLng() + ',' + title + ']';

        }
        window.returnValue = returnStr + ":" + map.getCenter() + ":" + map.getZoom();
        window.close();
    },
    "saveView": function (latitude, longitude, onlylatlng) {
        if (onlylatlng) {
            window.returnValue = latitude + ":" + longitude + ":" + map.getZoom();
            window.close();

        }
        else {
        iso.trace("Map empty", JSON.stringify(isoMapEditor.mapSettings));

        isoMapEditor.mapSettings = isoMapEditor.setMapKeyPoints(isoMapEditor.mapSettings);

        iso.trace("Map coords set", JSON.stringify(isoMapEditor.mapSettings));

        $.ajax({
            type: "POST",
            url: isoMapEditor.ajaxStore,
            data: "callType=saveView&mapSettings=" + JSON.stringify(isoMapEditor.mapSettings),
            success: function(response) {

                iso.trace("Map ajax success", response);

                isoMapEditor.mapSettings = JSON.parse(response);

                iso.trace("Map ID", isoMapEditor.mapSettings.ID);
                iso.trace("epiReturnPointID", isoMapEditor.epiReturnPointID);
                //isoMapEditor.savePoints();
                var returnStr;
                returnStr = (isoMapEditor.mapSettings.ID != null) ? isoMapEditor.mapSettings.ID : 'none';
                returnStr += (isoMapEditor.epiReturnPointID != null) ? ":" + isoMapEditor.epiReturnPointID : '';
                window.returnValue = returnStr;


                iso.trace("Return string", returnStr);
                window.close();

            }
        });


        }
        //iso.trace("Map after save", JSON.stringify(isoMapEditor.mapSettings));

    },

    "setMapKeyPoints": function(obj) {

        var bounds = map.getBounds();

        obj.CenterPoint.X = map.getCenter().x.toString();
        obj.CenterPoint.Y = map.getCenter().y.toString();
        obj.NorthEastPoint.X = bounds.getNorthEast().x.toString();
        obj.NorthEastPoint.Y = bounds.getNorthEast().y.toString();
        obj.SouthWestPoint.X = bounds.getSouthWest().x.toString();
        obj.SouthWestPoint.Y = bounds.getSouthWest().y.toString();

        obj.ZoomFactor = map.getZoom();

        return obj;
    },

    "addPoint": function(latitude, longitude, title, category, text, iconID, iconURL, cbFunction, mapSettingsID) {
        var internalPoint = { "IconID": iconID, "IconURL": iconURL, "InfoTitle": title, "InfoText": text, "CategoryID": category, "ID": null, "X": longitude, "Y": latitude, "mapSettingsID": mapSettingsID };


        if (!isoMapEditor.validateNewPoint(internalPoint))
            return;


        isoMapEditor.addedPoints.push(internalPoint);

        var markerOptions;
        if (iconURL != null && iconURL != "") {
            var letteredIcon = new GIcon(baseIcon);
            letteredIcon.image = iconURL;
            letteredIcon.iconSize = new GSize(30, 30);

            markerOptions = { icon: letteredIcon };
        }
        else {
        }

        var point = new GLatLng(latitude, longitude);
        map.addOverlay(new GMarker(point, markerOptions));



        iso.trace("Send new point", JSON.stringify(internalPoint));
        $.ajax({
            type: "POST",
            url: isoMapEditor.ajaxStore,
            data: "callType=addPoint&point=" + JSON.stringify(internalPoint),
            success: function(response) {
                iso.trace("Ajax response to add call", response);

                if (cbFunction != null) {
                    iso.trace("Nu ska vi köra callback-metoden:", cbFunction);
                    eval(cbFunction + '(' + response + ')');
                }
                else
                    iso.trace("Callbackfunktionen var", cbFunction);

            }
        });
    },

    "validateNewPoint": function(newPoint) {
        if (newPoint.InfoTitle == '') {
            alert('- Please provide a title and save again.');
            return false;
        }

        return true;
    },

    "updPoint": function(index, latitude, longitude, title, category, text, iconID, iconURL, mapSettingsID) {
        alert(iconURL);
        iso.trace("ikon", mapPointList[index].IconURL);
        mapPointList[index].X = longitude;
        mapPointList[index].Y = latitude;


        mapPointList[index].InfoTitle = title;
        mapPointList[index].InfoText = text;
        mapPointList[index].CategoryID = category;
        mapPointList[index].mapSettingsID = mapSettingsID;

        mapPointList[index].IconURL = iconURL;
        var markerOptions;
        if (mapPointList[index].IconURL != null && mapPointList[index].IconURL != '') {
            var letteredIcon = new GIcon(baseIcon);
            letteredIcon.image = mapPointList[index].IconURL;
            letteredIcon.iconSize = new GSize(30, 30);
            markerOptions = { icon: letteredIcon };
        }

        var point = new GLatLng(latitude, longitude);
        map.addOverlay(new GMarker(point, markerOptions));

        //var internalPoint = {"IconID":iconID,"IconURL":iconURL,"InfoTitle":title,"InfoText":text,"CategoryID":category,"ID":null,"X":longitude,"Y":latitude};
        //isoMapEditor.addedPoints.push(internalPoint);

        iso.trace("Before upd", JSON.stringify(mapPointList[index]));
        $.ajax({
            type: "POST",
            url: isoMapEditor.ajaxStore,
            data: "callType=addPoint&point=" + JSON.stringify(mapPointList[index]),
            success: function(response) {
                iso.trace("Ajax response to upd call", response);

                $('#editMarker').hide();
                $('#otherMarker').show();

                isoMapEditor.isEditingMarker = false;


            }
        });
    },

    "savePoints": function() {
        iso.trace("Before save ponits", JSON.stringify(isoMapEditor.addedPoints));
        $.ajax({
            type: "POST",
            url: isoMapEditor.ajaxStore,
            data: "callType=addPoints&pointList=" + JSON.stringify(isoMapEditor.addedPoints),
            success: function(response) {
                iso.trace("Ajax response to add call", response);

                window.returnValue = (isoMapEditor.mapSettings.ID != null) ? isoMapEditor.mapSettings.ID : 'none';
                window.close();
            }
        });
    },

    "removePoint": function(index) {
        if (confirm("Vill du verkligen ta bort kartnålen \"" + mapPointList[index].InfoTitle + "\"")) {
            iso.trace("Remove point", mapPointList[index].ID);
            $.ajax({
                type: "POST",
                url: isoMapEditor.ajaxStore,
                data: "callType=removePoint&mapPointID=" + mapPointList[index].ID,
                success: function(response) {

                    iso.trace("Remove point response", response);

                    if (response == 'success')
                        currentEditMarker.remove();

                }
            });

        }

    },

    "editPoint": function(index) {

    },

    "displayEditPanel": function(index) {
        if (!isoMapEditor.isEditingMarker) {
            iso.trace("edit index", index);
            iso.trace("edit obj", JSON.stringify(mapPointList[index]));

            $('#editMarker').show();
            $('#otherMarker').hide();

            grab('txtEditTitle').value = mapPointList[index].InfoTitle;
            alert(mapPointList[index].IconURL);
            grab(iconID2).value = mapPointList[index].IconURL;
            //         grab('txtEditInfoText').value = mapPointList[index].InfoText;
            grab('txtEditId').value = mapPointList[index].ID;
            grab('txtEditPointIndex').value = index;

            //           $('#txtEditCategory').val(mapPointList[index].CategoryID);

            var point = new GLatLng(mapPointList[index].Y, mapPointList[index].X);
            isoMapEditor.currentMapPicker.setPoint(point);

            isoMapEditor.isEditingMarker = true;

            currentEditMarker.remove();

            document.getElementById('txtLat').value = mapPointList[index].Y;
            document.getElementById('txtLong').value = mapPointList[index].X;

            //            if ($.inArray(mapPointList[index].CategoryName, isoMapEditor.simpleEditCategories) > -1)
            //                $('#txtEditCategory').attr('disabled', 'disabled');
            //            else
            //                $('#txtEditCategory').removeAttr('disabled');

        }
        else
            alert('Your are currently editing another map point. You need to save or cancel the current marker before you can proceeed!');
    }
}

