var map, popup, Tashkent;

var subLayersTypeIdDiv = null;

function showSubLayers(typeId)
{
    div = document.getElementById("subLayers" + typeId);
    if (! div || div.style.display == "inline") {
        return;
    }
    if (subLayersTypeIdDiv && subLayersTypeIdDiv != typeId) {
        document.getElementById("subLayers" + subLayersTypeIdDiv).style.display = "none";
    }
    subLayersTypeIdDiv = typeId;
    div.style.display = "inline";
    var coords = getCoords(document.getElementById("layerTd" + typeId));
    div.style.top = coords["top"] + "px";
}

function closeSubLayers(typeId)
{
    if (! typeId) {
        typeId = subLayersTypeIdDiv;
        if (! typeId) {
            return;
        }
    }
    var div = document.getElementById("subLayers" + typeId);
    if (! div || div.style.display == "none") {
        return true;
    }
    if (MgUz.mousePositionX > 450) {
        div.style.display = "none";
        return true;
    }
    var top = getCoords(document.getElementById("layerTd" + typeId)).top;
    if (MgUz.mousePositionY < top) {
        div.style.display = "none";
        return true;
    }
    var height = getCoords(div).height;
    if (MgUz.mousePositionY > top + height) {
        div.style.display = "none";
        return true;
    }
    return false;
}

function addNaviControls() {
    Tashkent.events.unregister("loadend", null, addNaviControls);
    map.addControl(new OpenLayers.PanZoomBar());
    map.addControl(new OpenLayers.Control.OverviewMap());
}

function init() {
    map = new OpenLayers.Map(
        'tashmap',
        {controls: [
            new OpenLayers.Control.Navigation(),
            controlLayers //,
            //new OpenLayers.Control.MousePosition()
        ]}
    );
    Tashkent = new OpenLayers.Layer.Grid(
        "Tashkent WMS",
        "http://wms.mg.uz/",
        {layers: 'basic', format: 'png'}
    );
    //Tashkent.transitionEffect = 'resize';
    if ("msie" == OpenLayers.Util.getBrowserName()) {
        Tashkent.events.register("loadend", null, addNaviControls);
    } else {
        map.addControl(new OpenLayers.PanZoomBar());
        map.addControl(new OpenLayers.Control.OverviewMap());
    }
    map.addLayer(Tashkent);
}

function publicationRenderer(uri, func, data)
{
    MgUz.loadShow();
    if (! data) {
        data = {};
    }
    JsHttpRequest.query(
        uri,
        data,
        function(result, errors) {
            func(result, errors);
            MgUz.loadHide();
            new Ya.share({
    'element': 'ya_share1',
    'elementStyle': {
        'type': 'button',
        'linkIcon': true,
        'border': false,
        'quickServices': ['yaru', 'vkontakte', 'facebook', 'twitter', 'odnoklassniki', 'friendfeed', 'moimir', 'lj']
    },
    'popupStyle': {
        'copyPasteField': true
    },
    'description': document.getElementsByTagName('meta')[1].content
 });

            return false;
        },
        false
    );
}

function contentPageLoad(uri, data)
{
    uri = "/ajax" + uri;
    var func = function(result, errors) {
        if (result["content"]) {
            document.getElementById("publicationsBlock").innerHTML = result["content"];
        }
    };
    publicationRenderer(uri, func, data);
}

function publicationsBlockRenderer(groupId)
{
    var uri = "/ajax/publish/";
    if (groupId) {
        uri += "group" + groupId + ".html";
    }
    func = function(result, errors) {
        if (result["content"]) {
            document.getElementById("publicationsBlock").innerHTML = result["content"];
        }
    };
    publicationRenderer(uri, func);
}

var XbbJsIsLoad = false;

function xbbJsLoad()
{
    if (! XbbJsIsLoad) {
        var script = document.createElement("script");
        script.src = "/files/bbcode/xbb.js.php";
        script.type = "text/javascript";
        document.getElementsByTagName("head").item(0).appendChild(script);
        XbbJsIsLoad = true;
    }
    if (typeof XBB == "undefined") {
        setTimeout("xbbJsLoad()", 10);
    } else {
        XBB.textarea_id = "comment_text"; // идентификатор textarea
        XBB.area_width = "550px";
        XBB.area_height = "400px";
        XBB.state = "plain"; // 'plain' or 'highlight'
        XBB.lang = "ru_utf8"; // локализация
    }
}

var publicationPoint = null;

function publicationTextRenderer(publcationId, point_x, point_y)
{
    xbbJsLoad();
    var uri = "/ajax/publish/doc/text" + publcationId + ".html";
    func = function(result, errors) {
        if (result["content"]) {
            document.getElementById("publicationsBlock").innerHTML = result["content"];
        }
        XBB.init();
    };
    publicationRenderer(uri, func);
    MgUz.addPublicationPoint({x: point_x, y: point_y});
}

function getCoords(element) {
    var left = element.offsetLeft;
    var top = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
        left += parent.offsetLeft - parent.scrollLeft;
        top += parent.offsetTop - parent.scrollTop
    }
    return {
        left: left,
        top: top,
        width: element.offsetWidth,
        height: element.offsetHeight
    };
}

var addingPoint = {

    isActive: false,

    pointControl: null,

    pointLayer: null,

    userPoints: null,

    editPointId: 0,

    buttonClick: function()
    {
        this.isActive = ! this.isActive;
        if (this.isActive) {
            if (! this.pointLayer) {
                this.pointLayer = new OpenLayers.Layer.Vector("Point Layer");
                map.addLayer(this.pointLayer);
                this.pointControl = new OpenLayers.Control.DrawFeature(this.pointLayer, OpenLayers.Handler.Point);
                map.addControl(this.pointControl);
            }
            this.pointControl.featureAdded = this.pointAdd;
            this.pointControl.activate();
            document.getElementById("addingPointFormDiv").style.display = "inline";
            document.getElementById("addingPointButtonImg").src = "/files/OpenLayers/theme/mg/img/draw_point_on.png";
            if (this.editPointId) {
                document.getElementById("editPointFormDiv_" + this.editPointId).style.display = "none";
                this.editPointId = 0;
            }
        } else {
            this.pointControl.deactivate();
            document.getElementById("addingPointFormDiv").style.display = "none";
            document.getElementById("addingPointButtonImg").src = "/files/OpenLayers/theme/mg/img/draw_point_off.png";
        }
        return false;
    },

    pointAdd: function()
    {
        var features = this.layer.features;
        if (features.length > 1) {
            this.layer.destroyFeatures([features[0]]);
        }
        document.forms.addingPointForm.point_x.value = features[0].geometry.x;
        document.forms.addingPointForm.point_y.value = features[0].geometry.y;
    },

    pointEdit: function()
    {
        var features = this.layer.features;
        if (features.length > 1) {
            this.layer.destroyFeatures([features[0]]);
        }
        eval("var form = document.forms.editPointForm_" + addingPoint.editPointId);
        form.point_x.value = features[0].geometry.x;
        form.point_y.value = features[0].geometry.y;
    },

    formSubmit: function()
    {
        var x = parseFloat(document.forms.addingPointForm.point_x.value);
        var y = parseFloat(document.forms.addingPointForm.point_y.value);
        if (! x || ! y) {
            alert("Некорректно указаны координаты: x=" + x + ", y=" + y);
            return false;
        }
        var name = document.forms.addingPointForm.name.value;
        if (! name) {
            alert("Не указано название объекта");
            return false;
        }
	var group = document.forms.addingPointForm.group.value;

        var description = document.forms.addingPointForm.description.value;
        var public = document.forms.addingPointForm.public.checked;
        MgUz.loadShow();
        JsHttpRequest.query(
            "/scripts/ajax/save/point",
            {
                x: x,
                y: y,
                name: name,
		group: group,
                description: description,
                public: public ? 1 : 0
            },
            function(result, errors)
            {
                if (result["message"]) {
                    var message = "<font color='green'>" + result["message"] + "</font>";
                    document.getElementById("addingPointResultMessage").innerHTML = message;
                }
                if (result["point_id"]) {
                    addingPoint.userPoints.dataToMarker(
                        new OpenLayers.Geometry.Point(x, y),
                        "/files/mg.uz/publish.gif",
                        name,
                        description
                    );
                    document.forms.addingPointForm.point_x.value = "";
                    document.forms.addingPointForm.point_y.value = "";
                    document.forms.addingPointForm.name.value = "";
                    document.forms.addingPointForm.description.value = "";
                    var features = addingPoint.pointLayer.features;
                    if (features.length) {
                        addingPoint.pointLayer.destroyFeatures([features[0]]);
                    }
                }
                MgUz.loadHide();
                return false;
            },
            true
        );
        return false;
    },

    deletePoint: function(point_id)
    {
        MgUz.loadShow();
        JsHttpRequest.query(
            "/scripts/ajax/delete/point",
            {id: point_id},
            function(result, errors)
            {
                if (1 == result["error_code"]) {
                    alert(result["message"]);
                } else {
                    var message = "<td colspan='2' align='left'><font color='red'>" + result["message"] + "</font></td>";
                    document.getElementById("editPointTr_" + point_id).innerHTML = message;
                }
                MgUz.loadHide();
                return false;
            },
            true
        );
        return false;
    },

    editPointActivate: function(point_id, point_x, point_y)
    {
        if (this.editPointId) {
            document.getElementById("editPointFormDiv_" + this.editPointId).style.display = "none";
        }
        if (this.editPointId == point_id) {
            this.editPointId = 0;
            return false;
        }
        this.editPointId = point_id;
        document.getElementById("editPointFormDiv_" + point_id).style.display = "inline";
        if (point_x && point_y) {
            map.setCenter(new OpenLayers.LonLat(point_x, point_y), 10);
        }
        if (this.isActive) {
            this.buttonClick();
        }
        if (! this.pointLayer) {
            this.pointLayer = new OpenLayers.Layer.Vector("Point Layer");
            map.addLayer(this.pointLayer);
            this.pointControl = new OpenLayers.Control.DrawFeature(this.pointLayer, OpenLayers.Handler.Point);
            map.addControl(this.pointControl);
        }
        this.pointControl.featureAdded = this.pointEdit;
        this.pointControl.activate();
        return false;
    },


    editFormSubmit: function(form)
    {
        var point_id = form.point_id.value;
        var x = parseFloat(form.point_x.value);
        var y = parseFloat(form.point_y.value);
        if (! x || ! y) {
            alert("Некорректно указаны координаты: x=" + x + ", y=" + y);
            return false;
        }
        var name = form.name.value;
        if (! name) {
            alert("Не указано название объекта");
            return false;
        }
	var group = form.group.value;
        if (! group) {
            alert("Не выбрана группа");
            return false;
        }
        var description = form.description.value;
        var public = form.public.checked;
        MgUz.loadShow();
        JsHttpRequest.query(
            "/scripts/ajax/save/point",
            {
                id: point_id,
                x : x,
                y : y,
                name: name,
		group: group,
                description: description,
                public: public ? 1 : 0
            },
            function(result, errors)
            {
                if (result["message"]) {
                    document.getElementById("editPointMessageSpan_" + point_id).innerHTML = result["message"];
                }
                MgUz.loadHide();
                return false;
            },
            true
        );
        return false;
    }
};

var MgUz = {

    gallery: null,

    orgPoints: null,

    isLoad: false,

    roadLayer: null,

    selectedPointLayer: null,

    layers: {},

    imageUuid: function(uuid)
    {
        if ("panorama" == uuid) {
            return;
        }
        JsHttpRequest.query("/scripts/ajax/image/info", {uuid: uuid}, MgUz.openImgDiv, false);
    },

    setGallery: function(data)
    {
        var url = "/scripts/gallery/" + data[0] + ".xml";
        var iframe = document.getElementById("galleryIframe");
        if (typeof(iframe.contentWindow.setFlashUrl) != "undefined") {
            iframe.contentWindow.setFlashUrl(url, data[1]);
        }
    },

    closeImgDiv: function()
    {
        if (document.getElementById("galleryImgDiv")) {
            document.getElementById("galleryImgDiv").style.display = "none";
        }
        return false;
    },

    openImgDiv: function(result, errors)
    {
        if (! result) {
            return;
        }
        var coords = getCoords(document.getElementById("galleryIframe"));
        var imgDiv = document.getElementById("galleryImgDiv");
        if (! imgDiv) {
            imgDiv = document.createElement("div");
            imgDiv.setAttribute("id", "galleryImgDiv");
            imgDiv.style.position = "absolute";
            imgDiv.style.backgroundColor = "white";
            imgDiv.style.border = "#61a57e 1px solid";
            imgDiv.style.top  = (coords["top"] + 45) + "px";
            imgDiv.style.zIndex = "2000";
            imgDiv.innerHTML = "<div align='right'><a href='javascript:void(0)' onclick='return MgUz.closeImgDiv()'>"
                             + "<img alt='Закрыть' width='17' height='17' border='0' wspace='3' "
                             + "src='/files/OpenLayers/theme/default/img/close.gif' /></a></div>"
                             + "<div align='center' id='galleryImg'></div>";
            document.getElementById("tashmap").parentNode.appendChild(imgDiv);
        }
//        var width = result["width"] < 600 ? parseInt(result["width"]) : 600;
        var width = parseInt(result["width"]);

        var left = coords["left"] + parseInt((coords["width"] - width)/2) - 3;
        imgDiv.style.width = (width + 6) + "px";
        imgDiv.style.left = left + "px";
        var source = result["source"] ? result["source"] : result["source_link"];
        if (result["source_link"]) {
            source = "<a href='" + result["source_link"] + "' target='_blank'>" + source + "</a>";
        }
        var description = "<strong>" + result["name"] + "</strong>";
        if (source) {
            description += "<br />Источник: " + source;
        }
        var html = "";
        if (result["group_name"]) {
            html += "<p align='left'>&nbsp;Галерея \"<strong><a href='/gallery/"
                  + result["group_uuid"] + ".html' onclick=\"return MgUz.galleryJsLoad('"
                  + result["group_uuid"] + "')\">" + result["group_name"] + "</a></strong>\"</p>";
        }
        html += "<img style='border:#61a57e 1px solid' align='center' width='"
              + width + "' height='" + result["height"] + "' src='/scripts/image/mw"+width+"/"
              + result["uuid"] + ".img' /><p>" + description + "</p>";
        document.getElementById("galleryImg").innerHTML = html;
        imgDiv.style.display = "";
    },

    addPublicationPoint: function(data)
    {
        if (! data["x"] || ! data["y"]) {
            return;
        }
        point_x = parseFloat(data["x"]);
        point_y = parseFloat(data["y"]);
        if (null == publicationPoint) {
            publicationPoint = new OpenLayers.Layer.Markers("Точка публикации");
            if (map) {
                map.addLayer(publicationPoint);
            }
        }
        var newCenter = new OpenLayers.LonLat(point_x, point_y);
        var marker = new OpenLayers.Marker(
            newCenter,
            new OpenLayers.Icon("/files/mg.uz/publish.gif", new OpenLayers.Size(25, 25))
        );
        publicationPoint.addMarker(marker);
        if (map) {
            map.setCenter(newCenter, 10);
        } else {
            lon = point_x;
            lat = point_y;
            zoom = 10;
        }
    },

    addOrgPoint: function(data)
    {
        if (data["x"] && data["y"]) {
            point_x = parseFloat(data["x"]);
            point_y = parseFloat(data["y"]);
            if (null == this.orgPoints) {
                this.orgPoints = new OpenLayers.Layer.Markers("Выбранные организации");
                if (map) {
                    map.addLayer(this.orgPoints);
                }
            }
            var newCenter = new OpenLayers.LonLat(point_x, point_y);
            var marker = new OpenLayers.Marker(
                newCenter,
                new OpenLayers.Icon("/files/mg.uz/publish.gif", new OpenLayers.Size(25, 25))
            );
            this.orgPoints.addMarker(marker);
            if (map) {
                map.setCenter(newCenter, 10);
            } else {
                lon = point_x;
                lat = point_y;
                zoom = 10;
            }
        }
        if (data["url"]) {
            contentPageLoad(data["url"]);
            var coords = getCoords(document.getElementById("mapTable"));
            window.scrollTo(0, coords["top"]);
        }
        return false;
    },

    galleryJsLoad: function(uuid, func)
    {
        if ((typeof MgUz.galleryJsLoadData == "undefined") || ! MgUz.galleryJsLoadData) {
            var script = document.createElement("script");
            script.src = "/files/mg.uz/gallery.js";
            script.type = "text/javascript";
            document.getElementsByTagName("head").item(0).appendChild(script);
        }
        if (uuid) {
            MgUz.galleryJsLoadData = [uuid, func];
        }
        if (! MgUz.gallery) {
            setTimeout("MgUz.galleryJsLoad()", 10);
        } else if (MgUz.galleryJsLoadData[1]) {
            MgUz.galleryJsLoadData[1](MgUz.galleryJsLoadData[0]);
        } else {
            this.closeImgDiv();
            MgUz.gallery.dataLoad(MgUz.galleryJsLoadData[0]);
            contentPageLoad("/gallery/" + MgUz.galleryJsLoadData[0] + ".html");
        }
        return false;
    },

    layerGalleryClick: function(uuid)
    {
        var checkbox = document.getElementById("layer_gallery");
        if (checkbox.checked) {
            MgUz.closeImgDiv();
            MgUz.gallery.dataLoad(uuid);
            MgUz.gallery.layer.setVisibility(true);
        } else {
            MgUz.gallery.layer.setVisibility(false);
        }
    },

    orgTypeLoad: function(typeId, logo)
    {
        contentPageLoad("/trade/orgs/cat" + typeId + ".html");
        if (document.getElementById("layer_" + typeId)) {
            document.getElementById("layer_" + typeId).checked = true;
        } else {
            if (! logo) {
                logo = "/files/blobs/object.gif";
            }
            setMarkerLayer(typeId, "", logo);
        }
        if (map) {
            redrawLayers();
            map.setCenter(new OpenLayers.LonLat(69.265, 41.285), 5);
        }
        return false;
    },

    getElementComputedStyle: function(elem, prop)
    {
        if (typeof elem != "object") {
            elem = document.getElementById(elem);
        }
        // external stylesheet for Mozilla, Opera 7+ and Safari 1.3+
        if (document.defaultView && document.defaultView.getComputedStyle) {
            if (prop.match(/[A-Z]/)) {
                prop = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
            }
            return document.defaultView.getComputedStyle(elem, "").getPropertyValue(prop);
        }
        // external stylesheet for Explorer and Opera 9
        if (elem.currentStyle) {
            var i;
            while ((i=prop.indexOf("-"))!=-1) {
                prop = prop.substr(0, i) + prop.substr(i+1,1).toUpperCase() + prop.substr(i+2);
            }
            return elem.currentStyle[prop];
        }
        return "";
    },

    mousePageXY: function(e)
    {
        var x = 0, y = 0;
        if (!e) {
            e = window.event;
        }
        if (e.pageX || e.pageY) {
            x = e.pageX;
            y = e.pageY;
        } else if (e.clientX || e.clientY) {
            x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
            y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
        }
        return {"x": x, "y": y};
    },

    loadShow: function()
    {
        MgUz.isLoad = true;
        var progressbar = document.getElementById("progressbar");
        progressbar.style.left = (MgUz.mousePositionX + 15) + "px";
        progressbar.style.top = (MgUz.mousePositionY + 15) + "px";
        progressbar.style.display = "";
    },

    loadHide: function()
    {
        MgUz.isLoad = false;
        document.getElementById("progressbar").style.display = "none";
    },

    searchSubmit: function()
    {
        var geoForm = document.forms.geoSearch;
        var srch = geoForm.srch.value;
        if (! srch) {
            alert("Не задана строка поиска");
            return false;
        }
        var district = geoForm.district.options[geoForm.district.selectedIndex].value;
        var lrs = geoForm.lrs.options[geoForm.lrs.selectedIndex].value;
        var uri = "/ajax/search/";
        var func = function(result, errors) {
                if (result["content"]) {
                    document.getElementById("publicationsBlock").innerHTML = result["content"];
                }
            };
        var data = {srch: srch, district: district, lrs: lrs}
        publicationRenderer(uri, func, data);
        return false;
    },

    roadShow: function(geometry)
    {
        if (! this.roadLayer) {
            this.roadLayer = new OpenLayers.Layer.Vector("Найденная улица");
            map.addLayer(this.roadLayer);
        }
        if (this.roadLayer.features.length > 0) {
            this.roadLayer.destroyFeatures();
        }
        var feature = new OpenLayers.Feature.Vector(geometry, {});
        feature.style = OpenLayers.Feature.Vector.style.select;
        feature.style.cursor = "";
        this.roadLayer.addFeatures([feature]);
        var bounds = geometry.getBounds();
        var zoom = map.getZoomForExtent(bounds, false);
        map.setCenter(bounds.getCenterLonLat(), zoom);
        return false;
    },

    pointShow: function(data)
    {
        if (! this.selectedPointLayer) {
            this.selectedPointLayer = new OpenLayers.Layer.Markers("Точка на карте");
            map.addLayer(this.selectedPointLayer);
        }
        if (this.selectedPointLayer.markers.length > 0) {
            this.selectedPointLayer.clearMarkers();
        }
        if (! data["x"] || ! data["y"]) {
            return;
        }
        point_x = parseFloat(data["x"]);
        point_y = parseFloat(data["y"]);
        var newCenter = new OpenLayers.LonLat(point_x, point_y);
        var marker = new OpenLayers.Marker(
            newCenter,
            new OpenLayers.Icon("/files/mg.uz/publish.gif", new OpenLayers.Size(25, 25))
        );
        this.selectedPointLayer.addMarker(marker);
        if (map) {
            map.setCenter(newCenter, 10);
        } else {
            lon = point_x;
            lat = point_y;
            zoom = 10;
        }
        return false;
    },

    loadLayer: function(uuid) {
        if (! this.layers[uuid]) {
            MgUz.loadShow();
            this.layers[uuid] = {};
            this.layers[uuid].layer = new OpenLayers.Layer.PointsLayer(
                "Точечные объекты",
                {popupSize: new OpenLayers.Size(150, 130)}
            );
            if (map) {
                map.addLayer(this.layers[uuid].layer);
            }
            JsHttpRequest.query(
                "/scripts/ajax/points/layer",
                {uuid: uuid},
                function(result, errors)
                {
                    var i;
                    if (result["layer"]) {
                        var uuid = result["layer"]["uuid"];
                        MgUz.layers[uuid]["parent_uuid"] = result["layer"]["parent_uuid"];
                        MgUz.layers[uuid]["icon_uuid"] = result["layer"]["icon_uuid"];
                        MgUz.layers[uuid]["name"] = result["layer"]["name"];
                        if (result["points"]) {
                            var icon = "/files/mg.uz/publish.gif";
                            if (result["layer"]["icon_uuid"]) {
                                icon = "/scripts/image/" + result["layer"]["icon_uuid"] + ".img";
                            }
                            var point;
                            for (i = 0; i < result["points"].length; ++i) {
                                point = result["points"][i];
                                MgUz.layers[uuid].layer.dataToMarker(
                                    new OpenLayers.Geometry.Point(point["x"], point["y"]),
                                    icon,
                                    point["name"],
                                    point["description"]
                                );
                            }
                        }
                        if (result["children"]) {
                            MgUz.layers[uuid]["children"] = result["children"];
                            var checked = document.getElementById(uuid) ? document.getElementById(uuid).checked : true;
                            var chUuid;
                            for (i = 0; i < result["children"].length; ++i) {
                                chUuid = result["children"][i]["uuid"];
                                if (document.getElementById(chUuid)) {
                                    document.getElementById(chUuid).checked = checked;
                                }
                                MgUz.loadLayer(chUuid);
                            }
                        }
                    }
                    MgUz.loadHide();
                    return false;
                },
                false
            );
        }
        var checked = document.getElementById(uuid) ? document.getElementById(uuid).checked : true;
        if (checked) {
            this.layers[uuid].layer.setVisibility(true);
        } else {
            this.layers[uuid].layer.setVisibility(false);
        }
        if (this.layers[uuid]["children"]) {
            var chUuid;
            for (var i = 0; i < this.layers[uuid]["children"].length; ++i) {
                chUuid = this.layers[uuid]["children"][i]["uuid"];
                if (document.getElementById(chUuid)) {
                    document.getElementById(chUuid).checked = checked;
                }
                this.loadLayer(chUuid);
            }
        }
        return false;
    },

    hideLayer: function(uuid) {
        if (! this.layers[uuid])
	{
            return false;
	}
	    map.removeLayer(this.layers[uuid].layer);
	    return false;
    },

    loadUserMap: function(loginEncode, uuid) {
        contentPageLoad("/usermap/" + loginEncode + ".html");
        this.loadLayer(uuid);
        return false;
    }
};

MgUz.User = {

    login: '',

    access: [],

    mapInfo: [],

    isAccess: function(access) {
        var is = false;
        for (var i = 0; i < this.access.length; ++i) {
            if (access == this.access[i]) {
                is = true;
            }
        }
        return is;
    },

    addPointClick: function() {
        var formDiv = document.getElementById("addingPointFormDiv");
        if (! this.isAccess("map_draw")) {
            alert("Добавлять точки могут только зарегистрированные пользователи после авторизации");
            if (formDiv) {
                formDiv.style.display = "none";
            }
            return false;
        }
        if (formDiv) {
            addingPoint.buttonClick();
            return false;
        }
        MgUz.loadShow();
        JsHttpRequest.query(
            "/ajax/add/point/form",
            {},
            function(result, errors)
            {
                var td = document.getElementById("mapHelpTd");
                if (result["content"]) {
                    td.innerHTML = result["content"] + td.innerHTML;
                    addingPoint.buttonClick();
                }
                MgUz.loadHide();
                return false;
            },
            false
        );
        return false;
    },

    authorization: function() {
        var frm = document.forms.authorizationForm;
        if (! frm) {
            return true;
        }
        var login = frm.user.value;
        var passw = frm.pass.value;
        if (! login || ! passw) {
            alert("Введите логин и пароль");
            return false;
        }
        MgUz.loadShow();
        var save = frm.sessionSave.checked ? 1 : 0;
        JsHttpRequest.query(
            "/scripts/ajax/authorization",
            {user: login, pass: passw, sessionSave: save},
            function(result, errors)
            {
                if (result["login"] && result["login"] != MgUz.User.login) {
                    MgUz.User.login = result["login"];
                    MgUz.User.access = result["access"];
                    document.getElementById("layerPersonal").disabled = false;
                    MgUz.User.authorizationFormLoad();
                } else {
                    MgUz.loadHide();
                }
                if (result["mapInfo"]) {
                    MgUz.User.mapInfo = result["mapInfo"];
                    if (MgUz.User.mapInfo["iconUuid"]) {
                        var img = document.getElementById("layerPersonalImg");
                        img.src = "/scripts/image/" + MgUz.User.mapInfo["iconUuid"] + ".img";
                        if (MgUz.User.mapInfo["iconWidth"]) {
                            img.width = MgUz.User.mapInfo["iconWidth"];
                        }
                        if (MgUz.User.mapInfo["iconHeight"]) {
                            img.height = MgUz.User.mapInfo["iconHeight"];
                        }
                    }
                }
                return false;
            },
            false
        );
        return false;
    },

    authorizationFormLoad: function() {
        JsHttpRequest.query(
            "/ajax/authorization/form",
            {},
            function(result, errors)
            {
                if (result["content"]) {
                    document.getElementById("loginTd").innerHTML = result["content"];
                }
                MgUz.loadHide();
                return false;
            },
            false
        );
    },

    layerLoad: function() {
        if (! this.isAccess("map_draw")) {
            return;
        }
        if (! addingPoint.userPoints) {
            MgUz.loadShow();
            addingPoint.userPoints = new OpenLayers.Layer.PointsLayer(
                "Пользовательские объекты",
                {popupSize: new OpenLayers.Size(150, 130)}
            );
            if (map) {
                map.addLayer(addingPoint.userPoints);
            }
            JsHttpRequest.query(
                "/scripts/ajax/user/points",
                {},
                function(result, errors)
                {
                    if (result["mapInfo"]) {
                        MgUz.User.mapInfo = result["mapInfo"];
                    }
                    if (result["points"]) {
                        var icon = "/files/mg.uz/publish.gif";
                        if (MgUz.User.mapInfo["iconUuid"]) {
                            icon = "/scripts/image/" + MgUz.User.mapInfo["iconUuid"] + ".img";
                        }
                        var point;
                        for (var i = 0; i < result["points"].length; ++i) {
                            point = result["points"][i];
                            addingPoint.userPoints.dataToMarker(
                                new OpenLayers.Geometry.Point(point["x"], point["y"]),
                                icon,
                                point["name"],
                                point["description"]
                            );
                        }
                    }
                    MgUz.loadHide();
                    return false;
                },
                false
            );
        }
        if (! document.getElementById("layerPersonal").checked) {
            addingPoint.userPoints.setVisibility(false);
            return;
        }
        addingPoint.userPoints.setVisibility(true);
    }
};

document.onmousemove = function(e)
{
    var mCur = MgUz.mousePageXY(e);
    MgUz.mousePositionX = mCur.x;
    MgUz.mousePositionY = mCur.y;
    if (MgUz.isLoad) {
        MgUz.loadShow();
    }
    closeSubLayers();
};

//layers control

var addingLayer = {

    isActive: false,

    pointControl: null,

    pointLayer: null,

    userPoints: null,

    editPointId: 0,

    buttonClick: function()
    {
        this.isActive = ! this.isActive;
        if (this.isActive) {
            if (! this.pointLayer) {
                this.pointLayer = new OpenLayers.Layer.Vector("Point Layer");
                map.addLayer(this.pointLayer);
                this.pointControl = new OpenLayers.Control.DrawFeature(this.pointLayer, OpenLayers.Handler.Point);
                map.addControl(this.pointControl);
            }
            this.pointControl.featureAdded = this.pointAdd;
            this.pointControl.activate();
            document.getElementById("addingPointFormDiv").style.display = "inline";
            document.getElementById("addingPointButtonImg").src = "/files/OpenLayers/theme/mg/img/draw_point_on.png";
            if (this.editPointId) {
                document.getElementById("editPointFormDiv_" + this.editPointId).style.display = "none";
                this.editPointId = 0;
            }
        } else {
            this.pointControl.deactivate();
            document.getElementById("addingPointFormDiv").style.display = "none";
            document.getElementById("addingPointButtonImg").src = "/files/OpenLayers/theme/mg/img/draw_point_off.png";
        }
        return false;
    },

    pointAdd: function()
    {
        var features = this.layer.features;
        if (features.length > 1) {
            this.layer.destroyFeatures([features[0]]);
        }
        document.forms.addingPointForm.point_x.value = features[0].geometry.x;
        document.forms.addingPointForm.point_y.value = features[0].geometry.y;
    },

    pointEdit: function()
    {
        var features = this.layer.features;
        if (features.length > 1) {
            this.layer.destroyFeatures([features[0]]);
        }
        eval("var form = document.forms.editPointForm_" + addingPoint.editPointId);
        form.point_x.value = features[0].geometry.x;
        form.point_y.value = features[0].geometry.y;
    },

    formSubmit: function()
    {
        var x = parseFloat(document.forms.addingPointForm.point_x.value);
        var y = parseFloat(document.forms.addingPointForm.point_y.value);
        if (! x || ! y) {
            alert("Некорректно указаны координаты: x=" + x + ", y=" + y);
            return false;
        }
        var name = document.forms.addingPointForm.name.value;
        if (! name) {
            alert("Не указано название объекта");
            return false;
        }
        var description = document.forms.addingPointForm.description.value;
        var public = document.forms.addingPointForm.public.checked;
        MgUz.loadShow();
        JsHttpRequest.query(
            "/scripts/ajax/save/point",
            {
                x: x,
                y: y,
                name: name,
                description: description,
                public: public ? 1 : 0
            },
            function(result, errors)
            {
                if (result["message"]) {
                    var message = "<font color='green'>" + result["message"] + "</font>";
                    document.getElementById("addingPointResultMessage").innerHTML = message;
                }
                if (result["point_id"]) {
                    addingPoint.userPoints.dataToMarker(
                        new OpenLayers.Geometry.Point(x, y),
                        "/files/mg.uz/publish.gif",
                        name,
                        description
                    );
                    document.forms.addingPointForm.point_x.value = "";
                    document.forms.addingPointForm.point_y.value = "";
                    document.forms.addingPointForm.name.value = "";
                    document.forms.addingPointForm.description.value = "";
                    var features = addingPoint.pointLayer.features;
                    if (features.length) {
                        addingPoint.pointLayer.destroyFeatures([features[0]]);
                    }
                }
                MgUz.loadHide();
                return false;
            },
            true
        );
        return false;
    },

    deletePoint: function(point_id)
    {
        MgUz.loadShow();
        JsHttpRequest.query(
            "/scripts/ajax/delete/point",
            {id: point_id},
            function(result, errors)
            {
                if (1 == result["error_code"]) {
                    alert(result["message"]);
                } else {
                    var message = "<td colspan='2' align='left'><font color='red'>" + result["message"] + "</font></td>";
                    document.getElementById("editPointTr_" + point_id).innerHTML = message;
                }
                MgUz.loadHide();
                return false;
            },
            true
        );
        return false;
    },

    editPointActivate: function(point_id, point_x, point_y)
    {
        if (this.editPointId) {
            document.getElementById("editPointFormDiv_" + this.editPointId).style.display = "none";
        }
        if (this.editPointId == point_id) {
            this.editPointId = 0;
            return false;
        }
        this.editPointId = point_id;
        document.getElementById("editPointFormDiv_" + point_id).style.display = "inline";
        if (point_x && point_y) {
            map.setCenter(new OpenLayers.LonLat(point_x, point_y), 10);
        }
        if (this.isActive) {
            this.buttonClick();
        }
        if (! this.pointLayer) {
            this.pointLayer = new OpenLayers.Layer.Vector("Point Layer");
            map.addLayer(this.pointLayer);
            this.pointControl = new OpenLayers.Control.DrawFeature(this.pointLayer, OpenLayers.Handler.Point);
            map.addControl(this.pointControl);
        }
        this.pointControl.featureAdded = this.pointEdit;
        this.pointControl.activate();
        return false;
    },


    editFormSubmit: function(form)
    {
        var point_id = form.point_id.value;
        var x = parseFloat(form.point_x.value);
        var y = parseFloat(form.point_y.value);
        if (! x || ! y) {
            alert("Некорректно указаны координаты: x=" + x + ", y=" + y);
            return false;
        }
        var name = form.name.value;
        if (! name) {
            alert("Не указано название объекта");
            return false;
        }
        var description = form.description.value;
        var public = form.public.checked;
        MgUz.loadShow();
        JsHttpRequest.query(
            "/scripts/ajax/save/point",
            {
                id: point_id,
                x : x,
                y : y,
                name: name,
                description: description,
                public: public ? 1 : 0
            },
            function(result, errors)
            {
                if (result["message"]) {
                    document.getElementById("editPointMessageSpan_" + point_id).innerHTML = result["message"];
                }
                MgUz.loadHide();
                return false;
            },
            true
        );
        return false;
    }
};

var MgUz = {

    gallery: null,

    orgPoints: null,

    isLoad: false,

    roadLayer: null,

    selectedPointLayer: null,

    layers: {},

    imageUuid: function(uuid)
    {
        if ("panorama" == uuid) {
            return;
        }
        JsHttpRequest.query("/scripts/ajax/image/info", {uuid: uuid}, MgUz.openImgDiv, false);
    },

    setGallery: function(data)
    {
        var url = "/scripts/gallery/" + data[0] + ".xml";
        var iframe = document.getElementById("galleryIframe");
        if (typeof(iframe.contentWindow.setFlashUrl) != "undefined") {
            iframe.contentWindow.setFlashUrl(url, data[1]);
        }
    },

    closeImgDiv: function()
    {
        if (document.getElementById("galleryImgDiv")) {
            document.getElementById("galleryImgDiv").style.display = "none";
        }
        return false;
    },

    openImgDiv: function(result, errors)
    {
        if (! result) {
            return;
        }
        var coords = getCoords(document.getElementById("galleryIframe"));
        var imgDiv = document.getElementById("galleryImgDiv");
        if (! imgDiv) {
            imgDiv = document.createElement("div");
            imgDiv.setAttribute("id", "galleryImgDiv");
            imgDiv.style.position = "absolute";
            imgDiv.style.backgroundColor = "white";
            imgDiv.style.border = "#61a57e 1px solid";
            imgDiv.style.top  = (coords["top"] + 45) + "px";
            imgDiv.style.zIndex = "2000";
            imgDiv.innerHTML = "<div align='right'><a href='javascript:void(0)' onclick='return MgUz.closeImgDiv()'>"
                             + "<img alt='Закрыть' width='17' height='17' border='0' wspace='3' "
                             + "src='/files/OpenLayers/theme/default/img/close.gif' /></a></div>"
                             + "<div align='center' id='galleryImg'></div>";
            document.getElementById("tashmap").parentNode.appendChild(imgDiv);
        }
//        var width = result["width"] < 600 ? parseInt(result["width"]) : 600;
        var width = parseInt(result["width"]);

        var left = coords["left"] + parseInt((coords["width"] - width)/2) - 3;
        imgDiv.style.width = (width + 6) + "px";
        imgDiv.style.left = left + "px";
        var source = result["source"] ? result["source"] : result["source_link"];
        if (result["source_link"]) {
            source = "<a href='" + result["source_link"] + "' target='_blank'>" + source + "</a>";
        }
        var description = "<strong>" + result["name"] + "</strong>";
        if (source) {
            description += "<br />Источник: " + source;
        }
        var html = "";
        if (result["group_name"]) {
            html += "<p align='left'>&nbsp;Галерея \"<strong><a href='/gallery/"
                  + result["group_uuid"] + ".html' onclick=\"return MgUz.galleryJsLoad('"
                  + result["group_uuid"] + "')\">" + result["group_name"] + "</a></strong>\"</p>";
        }
        html += "<img style='border:#61a57e 1px solid' align='center' width='"
              + width + "' height='" + result["height"] + "' src='/scripts/image/mw"+width+"/"
              + result["uuid"] + ".img' /><p>" + description + "</p>";
        document.getElementById("galleryImg").innerHTML = html;
        imgDiv.style.display = "";
    },

    addPublicationPoint: function(data)
    {
        if (! data["x"] || ! data["y"]) {
            return;
        }
        point_x = parseFloat(data["x"]);
        point_y = parseFloat(data["y"]);
        if (null == publicationPoint) {
            publicationPoint = new OpenLayers.Layer.Markers("Точка публикации");
            if (map) {
                map.addLayer(publicationPoint);
            }
        }
        var newCenter = new OpenLayers.LonLat(point_x, point_y);
        var marker = new OpenLayers.Marker(
            newCenter,
            new OpenLayers.Icon("/files/mg.uz/publish.gif", new OpenLayers.Size(25, 25))
        );
        publicationPoint.addMarker(marker);
        if (map) {
            map.setCenter(newCenter, 10);
        } else {
            lon = point_x;
            lat = point_y;
            zoom = 10;
        }
    },

    addOrgPoint: function(data)
    {
        if (data["x"] && data["y"]) {
            point_x = parseFloat(data["x"]);
            point_y = parseFloat(data["y"]);
            if (null == this.orgPoints) {
                this.orgPoints = new OpenLayers.Layer.Markers("Выбранные организации");
                if (map) {
                    map.addLayer(this.orgPoints);
                }
            }
            var newCenter = new OpenLayers.LonLat(point_x, point_y);
            var marker = new OpenLayers.Marker(
                newCenter,
                new OpenLayers.Icon("/files/mg.uz/publish.gif", new OpenLayers.Size(25, 25))
            );
            this.orgPoints.addMarker(marker);
            if (map) {
                map.setCenter(newCenter, 10);
            } else {
                lon = point_x;
                lat = point_y;
                zoom = 10;
            }
        }
        if (data["url"]) {
            contentPageLoad(data["url"]);
            var coords = getCoords(document.getElementById("mapTable"));
            window.scrollTo(0, coords["top"]);
        }
        return false;
    },

    galleryJsLoad: function(uuid, func)
    {
        if ((typeof MgUz.galleryJsLoadData == "undefined") || ! MgUz.galleryJsLoadData) {
            var script = document.createElement("script");
            script.src = "/files/mg.uz/gallery.js";
            script.type = "text/javascript";
            document.getElementsByTagName("head").item(0).appendChild(script);
        }
        if (uuid) {
            MgUz.galleryJsLoadData = [uuid, func];
        }
        if (! MgUz.gallery) {
            setTimeout("MgUz.galleryJsLoad()", 10);
        } else if (MgUz.galleryJsLoadData[1]) {
            MgUz.galleryJsLoadData[1](MgUz.galleryJsLoadData[0]);
        } else {
            this.closeImgDiv();
            MgUz.gallery.dataLoad(MgUz.galleryJsLoadData[0]);
            contentPageLoad("/gallery/" + MgUz.galleryJsLoadData[0] + ".html");
        }
        return false;
    },

    layerGalleryClick: function(uuid)
    {
        var checkbox = document.getElementById("layer_gallery");
        if (checkbox.checked) {
            MgUz.closeImgDiv();
            MgUz.gallery.dataLoad(uuid);
            MgUz.gallery.layer.setVisibility(true);
        } else {
            MgUz.gallery.layer.setVisibility(false);
        }
    },

    orgTypeLoad: function(typeId, logo)
    {
        contentPageLoad("/trade/orgs/cat" + typeId + ".html");
        if (document.getElementById("layer_" + typeId)) {
            document.getElementById("layer_" + typeId).checked = true;
        } else {
            if (! logo) {
                logo = "/files/blobs/object.gif";
            }
            setMarkerLayer(typeId, "", logo);
        }
        if (map) {
            redrawLayers();
            map.setCenter(new OpenLayers.LonLat(69.265, 41.285), 5);
        }
        return false;
    },

    getElementComputedStyle: function(elem, prop)
    {
        if (typeof elem != "object") {
            elem = document.getElementById(elem);
        }
        // external stylesheet for Mozilla, Opera 7+ and Safari 1.3+
        if (document.defaultView && document.defaultView.getComputedStyle) {
            if (prop.match(/[A-Z]/)) {
                prop = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
            }
            return document.defaultView.getComputedStyle(elem, "").getPropertyValue(prop);
        }
        // external stylesheet for Explorer and Opera 9
        if (elem.currentStyle) {
            var i;
            while ((i=prop.indexOf("-"))!=-1) {
                prop = prop.substr(0, i) + prop.substr(i+1,1).toUpperCase() + prop.substr(i+2);
            }
            return elem.currentStyle[prop];
        }
        return "";
    },

    mousePageXY: function(e)
    {
        var x = 0, y = 0;
        if (!e) {
            e = window.event;
        }
        if (e.pageX || e.pageY) {
            x = e.pageX;
            y = e.pageY;
        } else if (e.clientX || e.clientY) {
            x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
            y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
        }
        return {"x": x, "y": y};
    },

    loadShow: function()
    {
        MgUz.isLoad = true;
        var progressbar = document.getElementById("progressbar");
        progressbar.style.left = (MgUz.mousePositionX + 15) + "px";
        progressbar.style.top = (MgUz.mousePositionY + 15) + "px";
        progressbar.style.display = "";
    },

    loadHide: function()
    {
        MgUz.isLoad = false;
        document.getElementById("progressbar").style.display = "none";
    },

    searchSubmit: function()
    {
// alert('ddddddddd');
        var geoForm = document.forms.geoSearch;
        var srch = geoForm.srch.value;
        if (! srch) {
            alert("Не задана строка поиска");
            return false;
        }
        var district = geoForm.district.options[geoForm.district.selectedIndex].value;
        var lrs = geoForm.lrs.options[geoForm.lrs.selectedIndex].value;
        var uri = "/ajax/search/";
        var func = function(result, errors) {
// alert(result["content"]);
// alert(errors);
                if (result["content"]) {
                    document.getElementById("publicationsBlock").innerHTML = result["content"];
                }
            };
        var data = {srch: srch, district: district, lrs: lrs}
        publicationRenderer(uri, func, data);
        return false;
    },

    roadShow: function(geometry)
    {
        if (! this.roadLayer) {
            this.roadLayer = new OpenLayers.Layer.Vector("Найденная улица");
            map.addLayer(this.roadLayer);
        }
        if (this.roadLayer.features.length > 0) {
            this.roadLayer.destroyFeatures();
        }
        var feature = new OpenLayers.Feature.Vector(geometry, {});
        feature.style = OpenLayers.Feature.Vector.style.select;
        feature.style.cursor = "";
        this.roadLayer.addFeatures([feature]);
        var bounds = geometry.getBounds();
        var zoom = map.getZoomForExtent(bounds, false);
        map.setCenter(bounds.getCenterLonLat(), zoom);
        return false;
    },

    pointShow: function(data)
    {
        if (! this.selectedPointLayer) {
            this.selectedPointLayer = new OpenLayers.Layer.Markers("Точка на карте");
            map.addLayer(this.selectedPointLayer);
        }
        if (this.selectedPointLayer.markers.length > 0) {
            this.selectedPointLayer.clearMarkers();
        }
        if (! data["x"] || ! data["y"]) {
            return;
        }
        point_x = parseFloat(data["x"]);
        point_y = parseFloat(data["y"]);
        var newCenter = new OpenLayers.LonLat(point_x, point_y);
        var marker = new OpenLayers.Marker(
            newCenter,
            new OpenLayers.Icon("/files/mg.uz/publish.gif", new OpenLayers.Size(25, 25))
        );
        this.selectedPointLayer.addMarker(marker);
        if (map) {
            map.setCenter(newCenter, 10);
        } else {
            lon = point_x;
            lat = point_y;
            zoom = 10;
        }
        return false;
    },

    loadLayer: function(uuid) {
        if (! this.layers[uuid]) {
            MgUz.loadShow();
            this.layers[uuid] = {};
            this.layers[uuid].layer = new OpenLayers.Layer.PointsLayer(
                "Точечные объекты",
                {popupSize: new OpenLayers.Size(150, 130)}
            );
            if (map) {
                map.addLayer(this.layers[uuid].layer);
            }
            JsHttpRequest.query(
                "/scripts/ajax/points/layer",
                {uuid: uuid},
                function(result, errors)
                {
                    var i;
                    if (result["layer"]) {
                        var uuid = result["layer"]["uuid"];
                        MgUz.layers[uuid]["parent_uuid"] = result["layer"]["parent_uuid"];
                        MgUz.layers[uuid]["icon_uuid"] = result["layer"]["icon_uuid"];
                        MgUz.layers[uuid]["name"] = result["layer"]["name"];
                        if (result["points"]) {
                            var icon = "/files/mg.uz/publish.gif";
                            if (result["layer"]["icon_uuid"]) {
                                icon = "/scripts/image/" + result["layer"]["icon_uuid"] + ".img";
                            }
                            var point;
                            for (i = 0; i < result["points"].length; ++i) {
                                point = result["points"][i];
                                MgUz.layers[uuid].layer.dataToMarker(
                                    new OpenLayers.Geometry.Point(point["x"], point["y"]),
                                    icon,
                                    point["name"],
                                    point["description"]
                                );
                            }
                        }
                        if (result["children"]) {
                            MgUz.layers[uuid]["children"] = result["children"];
                            var checked = document.getElementById(uuid) ? document.getElementById(uuid).checked : true;
                            var chUuid;
                            for (i = 0; i < result["children"].length; ++i) {
                                chUuid = result["children"][i]["uuid"];
                                if (document.getElementById(chUuid)) {
                                    document.getElementById(chUuid).checked = checked;
                                }
                                MgUz.loadLayer(chUuid);
                            }
                        }
                    }
                    MgUz.loadHide();
                    return false;
                },
                false
            );
        }
        var checked = document.getElementById(uuid) ? document.getElementById(uuid).checked : true;
        if (checked) {
            this.layers[uuid].layer.setVisibility(true);
        } else {
            this.layers[uuid].layer.setVisibility(false);
        }
        if (this.layers[uuid]["children"]) {
            var chUuid;
            for (var i = 0; i < this.layers[uuid]["children"].length; ++i) {
                chUuid = this.layers[uuid]["children"][i]["uuid"];
                if (document.getElementById(chUuid)) {
                    document.getElementById(chUuid).checked = checked;
                }
                this.loadLayer(chUuid);
            }
        }
        return false;
    },

    loadUserMap: function(loginEncode, uuid) {
        contentPageLoad("/usermap/" + loginEncode + ".html");
        this.loadLayer(uuid);
        return false;
    }
};

MgUz.User = {

    login: '',

    access: [],

    mapInfo: [],

    isAccess: function(access) {
        var is = false;
        for (var i = 0; i < this.access.length; ++i) {
            if (access == this.access[i]) {
                is = true;
            }
        }
        return is;
    },

    addPointClick: function() {
        var formDiv = document.getElementById("addingPointFormDiv");
        if (! this.isAccess("map_draw")) {
            alert("Добавлять точки могут только зарегистрированные пользователи после авторизации");
            if (formDiv) {
                formDiv.style.display = "none";
            }
            return false;
        }
        if (formDiv) {
            addingPoint.buttonClick();
            return false;
        }
        MgUz.loadShow();
        JsHttpRequest.query(
            "/ajax/add/point/form",
            {},
            function(result, errors)
            {
                var td = document.getElementById("mapHelpTd");
                if (result["content"]) {
                    td.innerHTML = result["content"] + td.innerHTML;
                    addingPoint.buttonClick();
                }
                MgUz.loadHide();
                return false;
            },
            false
        );
        return false;
    },

    authorization: function() {
        var frm = document.forms.authorizationForm;
        if (! frm) {
            return true;
        }
        var login = frm.user.value;
        var passw = frm.pass.value;
        if (! login || ! passw) {
            alert("Введите логин и пароль");
            return false;
        }
        MgUz.loadShow();
        var save = frm.sessionSave.checked ? 1 : 0;
        JsHttpRequest.query(
            "/scripts/ajax/authorization",
            {user: login, pass: passw, sessionSave: save},
            function(result, errors)
            {
                if (result["login"] && result["login"] != MgUz.User.login) {
                    MgUz.User.login = result["login"];
                    MgUz.User.access = result["access"];
                    document.getElementById("layerPersonal").disabled = false;
                    MgUz.User.authorizationFormLoad();
                } else {
                    MgUz.loadHide();
                }
                if (result["mapInfo"]) {
                    MgUz.User.mapInfo = result["mapInfo"];
                    if (MgUz.User.mapInfo["iconUuid"]) {
                        var img = document.getElementById("layerPersonalImg");
                        img.src = "/scripts/image/" + MgUz.User.mapInfo["iconUuid"] + ".img";
                        if (MgUz.User.mapInfo["iconWidth"]) {
                            img.width = MgUz.User.mapInfo["iconWidth"];
                        }
                        if (MgUz.User.mapInfo["iconHeight"]) {
                            img.height = MgUz.User.mapInfo["iconHeight"];
                        }
                    }
                }
                return false;
            },
            false
        );
        return false;
    },

    authorizationFormLoad: function() {
        JsHttpRequest.query(
            "/ajax/authorization/form",
            {},
            function(result, errors)
            {
                if (result["content"]) {
                    document.getElementById("loginTd").innerHTML = result["content"];
                }
                MgUz.loadHide();
                return false;
            },
            false
        );
    },

    layerLoad: function() {
        if (! this.isAccess("map_draw")) {
            return;
        }
        if (! addingPoint.userPoints) {
            MgUz.loadShow();
            addingPoint.userPoints = new OpenLayers.Layer.PointsLayer(
                "Пользовательские объекты",
                {popupSize: new OpenLayers.Size(150, 130)}
            );
            if (map) {
                map.addLayer(addingPoint.userPoints);
            }
            JsHttpRequest.query(
                "/scripts/ajax/user/points",
                {},
                function(result, errors)
                {
                    if (result["mapInfo"]) {
                        MgUz.User.mapInfo = result["mapInfo"];
                    }
                    if (result["points"]) {
                        var icon = "/files/mg.uz/publish.gif";
                        if (MgUz.User.mapInfo["iconUuid"]) {
                            icon = "/scripts/image/" + MgUz.User.mapInfo["iconUuid"] + ".img";
                        }
                        var point;
                        for (var i = 0; i < result["points"].length; ++i) {
                            point = result["points"][i];
                            addingPoint.userPoints.dataToMarker(
                                new OpenLayers.Geometry.Point(point["x"], point["y"]),
                                icon,
                                point["name"],
                                point["description"]
                            );
                        }
                    }
                    MgUz.loadHide();
                    return false;
                },
                false
            );
        }
        if (! document.getElementById("layerPersonal").checked) {
            addingPoint.userPoints.setVisibility(false);
            return;
        }
        addingPoint.userPoints.setVisibility(true);
    }
};

document.onmousemove = function(e)
{
    var mCur = MgUz.mousePageXY(e);
    MgUz.mousePositionX = mCur.x;
    MgUz.mousePositionY = mCur.y;
    if (MgUz.isLoad) {
        MgUz.loadShow();
    }
    closeSubLayers();
};

