﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("SpatialTest");

SpatialTest.ViewerMap = function(element) {
    SpatialTest.ViewerMap.initializeBase(this, [element]);
    this._map = null;
    this._state = null;
    this._sessionId = "456789";
    this._items = [];
    this._first = null;
    this._second = null;
    this._searchInputId = null;
    this._seachbuttonid = null;
    this._notFound = null;
    this._geo = null;
    this.cFirst;
    this.cSecond;
    this._e = new Sys.EventHandlerList();
    this.gmapDivId =  null;
    this.mapPartDivHidden = null;
    this._scrollLeftWidth = null;
    this._scrollTopWidth = null;
    this._mapHeight = null;
    this._mapWidth = null;
    this.autoCenter = true;
}

SpatialTest.ViewerMap.prototype = {
    initialize: function() {
        SpatialTest.ViewerMap.callBaseMethod(this, 'initialize');

        if (this._searchInputId != null) {
            $addHandler($get(this._searchInputId), "keydown", Function.createDelegate(this, this._searchInputClick));
            $addHandler($get(this._seachbuttonid), "click", Function.createDelegate(this, this._searchButtonClick));
        }
        this._setupMap();
        document.body.onunload = GUnload;

        // Add custom initialization here
    },
    dispose: function() {
        //Add custom dispose actions here
        SpatialTest.ViewerMap.callBaseMethod(this, 'dispose');
    },
    drawCircle: function(container) {
        if ($(container).val().length > 0) {
            var items = $(container).val().split('|');
            this._searchAddExt(new GLatLng(items[1], items[2]), new GLatLng(items[4], items[5]), new GLatLng(items[6], items[7]), items[8]);
        }
    },
    //VG search yvyky handlina
    _searchInputClick: function(event) {

        if (event.keyCode != 13)
            return;
        var address = $('#' + this._searchInputId).val()
        var geocoder = new GClientGeocoder();
        if (geocoder) {
            geocoder.getLatLng(address, Function.createDelegate(this, this._searchAd))
        };
        event.preventDefault();
        return false;
    },
    _searchButtonClick: function(event) {

        var address = $('#' + this._searchInputId).val()
        var geocoder = new GClientGeocoder();
        if (geocoder) {
            geocoder.getLatLng(address, Function.createDelegate(this, this._searchAd))
        };
        event.preventDefault();
        return false;
    },
    _searchAd: function(point) {

        var address = $('#' + this._searchInputId).val()
        if (!point) {
            //showInformation(this, address + " " + this._notFound, false);
        } else {
            var zoom = this._map.getZoom();
            if (parseInt(zoom) < 6)
                zoom = 6;

            this._map.setCenter(point, zoom);
            if (this._mapPartDivHidden) {
                var temp = this._map.fromContainerPixelToLatLng(new GPoint(this._scrollLeftWidth, this._scrollTopWidth))
                this._map.setCenter(temp, zoom);
            }
            var point2 = new GLatLng(point.lat() + 0.3, point.lng());
            this._toolbar.add_searchReady(Function.createDelegate(this, this._onFigureCompleted));
            this._toolbar._clearFigures();
            this._toolbar._drawingCircle = true;
            this._toolbar._drawPoly(point, point2);
        }
        return false;
    },
    _searchAddExt: function(point, point2, point3, zoom) {
        var address = $('#' + this._searchInputId).val()

        if (!point) {
            //showInformation(this, address + " " + this._notFound, false);
        } else {
            this._map.setZoom(zoom);
            this._toolbar._clearFigures();
            this._toolbar._drawingCircle = true;
            this._toolbar._drawPoly(point, point2);
            this._toolbar.FixDrawingCircle();
            this._map.setCenter(point, zoom);
        }
        return false;
    },
    
    saveLocation: function(obj) {
        if (this._toolbar.line == undefined || this._toolbar.line.getVertexCount() == 2) {
            if (this._toolbar._drawingCircle) {

                var fig = this._toolbar.getFigure();
                if (fig != null && fig.figure == 'circle') {
                    var map_zoom = this._map.getZoom();
                    var map_center = this._map.getCenter();
                    obj.value = 'circle|' + fig.first.lat() + '|' + fig.first.lng() + '|' + fig.second.distanceFrom(fig.first) + '|' + fig.second.lat() + '|' + fig.second.lng() + '|' + map_center.lat() + '|' + map_center.lng() + '|' + map_zoom;
                    this._first = fig.first;
                    this._second = fig.second;
                    this._toolbar._drawingCircle = true;
                    if (this._toolbar.line != undefined)
                        this._toolbar._fixCss(this._toolbar_drawingRect, this._toolbar._drawingCircle);
                }
            }
            else {

                obj.value = '';
                this._first = null;
                this._second = null;
            }

        }
        else {
            this.reset(obj);
        }

    },
    reset: function(obj) {
        obj.value = '';
    },
    clear: function() {
        this._toolbar.stopDrawingCircle();
        this._first = null;
        this._second = null;
        this._toolbar._drawingCircle = false;
        this._toolbar._fixCss(this._toolbar_drawingRect, this._toolbar._drawingCircle);
        this._toolbar.remove_searchReady(Function.createDelegate(this, this._onFigureCompleted));
    },
    doSearch: function(search) {

        var geocoder = new GClientGeocoder();
        if (geocoder) {
            geocoder.getLatLng(search, Function.createDelegate(this, this._searchAdd)
            );
        }
        return false;

    },
    _updateMapSize: function(gmapDivId, ishidden, scrollLeft, scrollTop) {
        this._gmapDivId = gmapDivId;
        this._mapPartDivHidden = ishidden;
        this._scrollLeftWidth = scrollLeft;
        this._scrollTopWidth = scrollTop;

        var temp = this._map.fromContainerPixelToLatLng(new GPoint(this._scrollLeftWidth, this._scrollTopWidth))
        var zoom = this._map.getZoom();
        if (this._map != null)
            this._map.setCenter(temp, zoom);
    },
    _setupMap: function() {
        this._state = new SpatialTest.StateManager("gmap");
        this._state.validate(this._sessionId);
        if (GBrowserIsCompatible()) {
            if(this._mapHeight == null)
                this._mapHeight = 225;
            if(this._mapWidth == null)
                this._mapWidth = 600;
            this._map = new GMap2(this.get_element(),
            {
                size: new GSize(this._mapWidth, this._mapHeight)
            });
            
            var menu = new GMenuMapTypeControl();
            //this._map.addControl(menu, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(525, 15)));
            this._map.addControl(new GSmallZoomControl3D());
            
            this._map.disableScrollWheelZoom();

            this._map.setCenter(new GLatLng(this._state.getValue("lat", 55.128649), this._state.getValue("lng", 24.32373)),
            this._state.getValue("z", 7), this._getMapType(this._state.getValue("t", "Map")));
            if(this.autoCenter)
                $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", Function.createDelegate(this, this.setCenterCoordsByLocation))

            GEvent.bind(this._map, "moveend", this, this._mapMoveEnd);
            GEvent.bind(this._map, "maptypechanged", this, this._mapTypeChanged);
            GEvent.bind(this._map, "click", this, this._mapClick);
            this._toolbar = new ToolbarControl(this._map, 40, 13);
            this._toolbar.add_figureCompleted(Function.createDelegate(this, this._onFigureCompleted));
            this._toolbar.add_figureRemoved(Function.createDelegate(this, this._onFigureRemoved));
            this._toolbar.add_figureChanged(Function.createDelegate(this, this._onFigureChanged));
            this._map.addControl(this._toolbar);
        }
    },
    setCenterCoordsByLocation: function(data) {
        var point = new GLatLng(data["geoplugin_latitude"], data["geoplugin_longitude"]);
        this._map.setCenter(point, 7);
    },
    add_searchReady: function(handler) {
        this._e.addHandler('searchReady', handler);
    },
    remove_searchReady: function(handler) {
        this._e.removeHandler('searchReady', handler);
    },
    _raiseSearchReady: function() {
        var handler = this._e.getHandler('searchReady');
        if (handler) {
            handler(this);
        }

    },
    _onFigureCompleted: function(control) {
        var fig = control.getFigure();
        if (fig != null) this._raiseSearchReady();

    },
    _onFigureRemoved: function() {
    },
    _onFigureChanged: function() {
        this._raiseSearchReady();
    },
    _mapClick: function(overlay, latlng, overlaylatlng) {
        if (overlay == null) {
            /*console.log(latlng);
            var marker = new GMarker(new GLatLng(latlng.lat(), latlng.lng()), { draggable: true });
            marker.value = items.length;
            items.push(marker);
            GEvent.addListener(marker, "click", function(latlng) {
            marker.openInfoWindowHtml(createEditHtml(marker.value));
            });
            GEvent.addListener(marker, "dragstart", function(latlng) {
            marker.closeInfoWindow();
            });
            map.addOverlay(marker);
            marker.openInfoWindowHtml(createEditHtml(marker.value));*/
        }
    },
    _mapMoveEnd: function() {
        var center = this._map.getCenter();
        this._state.setValue("lat", center.lat());
        this._state.setValue("lng", center.lng());
        this._state.setValue("z", this._map.getZoom());
    },
    _mapTypeChanged: function() {
        this._state.setValue("t", this._map.getCurrentMapType().getName());
    },
    _getMapType: function(type) {
        switch (type) {
            case "Terrain":
                return G_PHYSICAL_MAP;
            case "Hybrid":
                return G_HYBRID_MAP;
            case "Satellite":
                return G_SATELLITE_MAP;
            case "Map":
            default:
                return G_NORMAL_MAP;
        }
    },
    _onMethodComplete: function(result, context) {
        this._clearMarkers();
        this._createMarkers(result);
    },
    _onMethodFailed: function(result, context) {
        this._clearMarkers();
    },
    _clearMarkers: function() {
        var list = this._markers;
        if (list == null)
            return;
        for (var i = 0; i < list.length; i++) {
            this._map.removeOverlay(list[i]);
        }
    },
    _createMarkers: function(list) {
        this._markers = [];
        var that = this;
        for (var i = 0; i < list.length; i++) {
            var dat = list[i];
            var marker = new GMarker(new GLatLng(dat.Lat * 1, dat.Long * 1));
            marker.data = dat;
            marker.value = i;
            marker.bindInfoWindowHtml(this._createEditHtml(marker));
            this._markers.push(marker);
            this._map.addOverlay(marker);
        }
    },
    _createEditHtml: function(marker) {
        var index = marker.value;
        var baloonText = '<h2>Vertybės peržiūrėjimas</h2><div style="width: 300px;">' +
            'Pavadinimas: <span>' + marker.data.Text + '</span><br/> ' +
            'Metai: <span>' + marker.data.Year + '</span><br/></div>';
        return baloonText;
    },
    set_notFound: function(value) {
        this._notFound = value;
    },
    get_notFound: function() {
        return this._notFound;
    },
    set_autoCenter: function(value) {
        this.autoCenter = value;
    },
    get_autoCenter: function(value) {
        return this.autoCenter;
    },
    set_mapHeight: function(value) {
        this._mapHeight = value;
    },
    get_mapHeight: function() {
        return this._mapHeight;
    },
    set_mapWidth: function(value) {
        this._mapWidth = value;
    },
    get_mapWidth: function() {
        return this._mapWidth;
    },
    set_searchInputId: function(value) {
        this._searchInputId = value;
    },
    get_searchInputId: function() {
        return this._searchInputId;
    },
    set_seachbuttonid: function(value) {
        this._seachbuttonid = value;
    },
    get_seachbuttonid: function() {
        return this._seachbuttonid;
    }
}

SpatialTest.ViewerMap.registerClass('SpatialTest.ViewerMap', Sys.UI.Control);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

/*function createEditHtml(index) {
marker = items[index];

var baloonText = '<h2>Vertybės redagavimas</h2><div style="width: 300px;">' +
'Pavadinimas: <input type="text" id="title" value="textas"/><br/> ' +
'Metai: <input type="text" id="years" value="1940"/><br/>' +
'<input type="button" onclick="saveClick(this)" name="save" marker="' + index + '" value="Išsaugoti"/>' +
'<input type="button" onclick="cancelClick(this)" name="cancel" marker="' + index + '"  value="Atšaukti" /></div>';
return baloonText;
}

var _webRequest = null;

function saveClick(el) {
var index = el.getAttribute("marker");
marker = items[index];
var params = {
markerId: 0,
text: $get('title', el.parentNode).value,
year: $get('years', el.parentNode).value,
lng: marker.getLatLng().lng(),
lat: marker.getLatLng().lat()
};

if (_webRequest) {
// abort the previous web service call if we 
// are issuing a new one and the previous one is 
// active.
_webRequest.get_executor().abort();
_webRequest = null;
}


_webRequest = Sys.Net.WebServiceProxy.invoke('/spatialtest/services/MarkerService.asmx', 'UpdateMarker', false, params,
onMethodComplete, onMethodFailed, index);
marker.closeInfoWindow();
}

function onMethodComplete(result, eventArgs) {
//alert('Method Completed');
//alert(result);
}

function onMethodFailed(result, eventArgs) {
//alert('Method Failed');
}

function cancelClick(el) {
//alert("cancelClick " + el.name);
//alert("cancel - " + el.getAttribute("marker"));
//console.log(el.getAttribute("marker"))
marker = items[el.getAttribute("marker")];
//console.log(marker.value);
marker.closeInfoWindow();
}
*/


