﻿// JScript File
var eMap;                      // элемент imgMap
var eMapDiv;                   // элемент imgPanel
var distDataID;                // текущие координаты
var inDataID;                  // скрытое поле inData1

var agt = navigator.userAgent.toLowerCase();
var browserIE = ((agt.indexOf('msie')!=-1) && (agt.indexOf('opera')==-1));
var browserGecko = (agt.indexOf('gecko')!=-1);
var browserOpera = (agt.indexOf('opera')!=-1);
delete agt;

var eventClientX = 0;
var eventClientY = 0;
var eventClientX0 = 0;
var eventClientY0 = 0;
var eventX = 0;
var eventY = 0;

var dragmode = false;            // указывает включен ли режим перемещения рисунка карты
var draggable = false;           // указывает инициировано ли событие перемещения рисунка
var zoommode = false;
var bookmarkmode = false;
var eventInitButton = 0;       // клавиша мышки, вызвавшая событие
var imgMap = "";               // имя элемента imgMap в HTML
var ExprX_ClientID = "";       // имя элемента ExprX в HTML
var ExprY_ClientID = "";       // имя элемента ExprY в HTML
var FX_ClientID = "";          // имя элемента FX в HTML
var FY_ClientID = "";          // имя элемента FY в HTML
var eBuf;                      // фейк-imgMap на время загрузки нового рисунка
var eCircle;                   // рисунок круга для поиска
var MapDivId;                  // имя элемента imgPanel
var divWait;                   // имя элемента divWait в HTML
var scaleInfoID;               // имя элемента scaleInfo (информация о текущем масштабе)
var defaultMapCursor = 'default';
var MapCursor = defaultMapCursor;
var topDiv = null;             // div, закрывающий собой всю страницу
var enabledSelectElements = null;
var hiddenSelectElements = null;
var eSize = "";                // размеры элемента imgPanel
var changingSize = false;      // указывает инициировано ли событие изменения размеров рисунка карты

var rulermode=false;           // указывает включен ли режим измерения расстояния на карте
var rulerDiv=null;             // div на который наносятся точки
var idCount=0;                 // счетчик точек при измерении расстояния
var length=0;                  // длина пути на карте
var distancePoints = null;     // массив точек
var delta = (browserGecko)?5:4;       // поправка для вывода информации (точки пути)
var sessionId;
var closePic = (browserGecko) ? 
                        '\xA0<span onclick="javascript: clearDistance();" class="closeDivStyleGecko">x</span>':
                        '\xA0<span onclick="javascript: clearDistance();" class="closeDivStyleIE">x</span>';
var ctlLinkSheetID = "";       // id элемента, содержащего имя листа карты 
var ctlLinkObjectID = "";      // id элемента, содержащего номер объекта в листе карты
var CoordInfoID;               // id элемента отображающего текущие координаты
var mapCommand = "cmDefault";           // имя текущей команды карты

/*Секция тултипов*/
var ToolTips = '';
var infoPoints = "";
var sepPoint = "%%";
var sepMember = "|*";
var defaultToolTipBgColor = "FFFFCC";  // Цвет фона тултипа по умолчанию
var defaultToolTipFontSize = 12;       // Размер шрифта тултипа по умолчанию
var defaultToolTipDopusk = 6;          // В радиусе значения допуска от точки будет появляться тултип
var timerID = null;                    // ID таймера
var updateTimerID = null;
var MapAutoUpdatePeriod;
var ddlMapAutoUpdateID;

var UNDEF = "undefined";
var bmDiv = null;


var preonclick = null;
var preonmousedown = null;
var preonmousemove = null;

var preonclicksad = null;
var preonmousedownsad = null;
var preonmousemovesad = null;

var catArr = new Array();       // массив содержащий в индексах id категрии, а в элементах - тип категории (catArr[5]='Organization')
var putobjectmode = false;      // режим создания объектов
var ddlCategoriesId             // переменная для хранения id ddlCategories
var hfCategoryId                // переменная для хранения id hfCategory
var hfPhoneId;                  // переменная для хранения id hfPhone
var hfEmailId;                  // переменная для хранения id hfEmail
var admSectionId                // административный div (для логинов)
var orgSectionId;               // переменная для хранения id слоя для ввода и редактирования данных организаций
var appSectionId;               // переменная для хранения id слоя для ввода и редактирования данных жилья
var custSectionId;              // переменная для хранения id слоя для ввода и редактирования данных собственных данных пользователя
var commonSectionId;            // переменная для хранения id слоя для ввода и редактирования общих данных
var phoneContainerId;           // переменная для хранения id таблицы с телефонами
var emailContainerId;           // переменная для хранения id таблицы с email'ами
var editObjectBehaviour;        // строка, содержащая значение атрибута BehaviorID элемента окна редактирования св-в объекта
var hfEditObjectModeId;         // переменная для хранения id hfEditObjectMode. Используется в обработчике кнопки ok диалогового окна на сервере для того, чтобы отличать режимы создания и редактирования
var emptyREpattern = "^\\s*$";  // Шаблон рег. выражения для проверки пустого поля
var intREpattern = "^[0-9]+$";  // Шаблон рег. выражения для проверки целых значений
var floatREpattern = "^[0-9]+[,\\.]?[0-9]*$";   // Шаблон рег. выражения для вещественых значений
var urlREpattern = "^(https?://)?([\\w-]+\\.)+[\\w-]+(:\\d+)?(/[0-9a-zA-Zа-яА-Я \\+\\[\\]\\(\\){}./?%\\-&=!<>~;,'#\"]*)?$"; // Шаблон рег. выражения для url
var bmAnimId = null;            // Переменная для хранения id закладки которую нужно после загрузки рисунка карты выделить
var mapUrlParam = null;
var InfoTooltipPrm = null;      //Переменая для хранения инфо о тултипе, который отображается при выделении объекта
var ShowCenter = 0;
var MapObjectKey;               //Переменная для хранения id выбанного объекта для расстановки в MapObjects.ascx

var prm;

var ERROR_MSG = 'Во время выполнения операции произошла ошибка!';

function TtOptions(){
    this.X;
    this.Y;
    this.Text;
    this.DataBase;
    this.EditAddr;
    this.Del;
    this.AddOrg;
    this.AddRealty;    
    this.AddCust;
    this.EditTt;
}

function showpan(arg)
{
    window.open('Panorama.aspx?dataid='+arg,'panWindow','width=640,height=610,toolbar=0,resizable=1');
    hideToolTip();
}

function showimg(arg)
{
    window.open('Image.aspx?dataid='+arg,'panWindow','width=660,height=640,toolbar=0,resizable=1');
    hideToolTip();
}

function showcam(arg)
{
    window.open('ipcam.aspx?dataid='+arg,'panWindow','width=380,height=370,toolbar=0,resizable=1');
    hideToolTip();
}

function initMap()
{
    if (eMap==null) eMap = getElement(imgMap);
    eMap.onclick = mapClickDefault;
    eMap.onmousedown = mapMouseDownDefault;
    eMap.onmousemove = mapMouseMoveDefault;
    eMap.onload = eMapOnLoad;
    setMapCursor(defaultMapCursor);
    document.onmouseup = evtMouseUp;

    if (changingSize) eMap.style.visibility = 'hidden';
    restoreDistance();
    restoreBookmarks();
    eMapDiv = getElement(MapDivId);
    if (eMapDiv != null) eMapDiv.onload="javascript: eMapDiv.style.cursor = MapCursor; if (changingSize) eMap.style.visibility = 'hidden';";
    eBuf = document.createElement('img');
    eBuf.id = 'eBuffer';
    eBuf.style.visibility='hidden';
    if (!browserIE && eMapDiv != null) eMapDiv.appendChild(eBuf);
    
    eCircle = document.createElement('img');
    eCircle.id = 'eCircle';
    eCircle.src = 'MapView/img/map/circle.gif';
    
    setScaleInfo("FirstLoad");
    clearStatus();
    toolTip_Init();
    InfoTooltip_Init();
    var timer = getElement(ddlMapAutoUpdateID);
    if (timer != null)
    {
        MapAutoUpdatePeriod = timer.value;
        resetAutoUpdateTimer();
    }
    var kuk = getCookie(sessionId);
    if (kuk != null && kuk.length != 0)
      {
        var btn = getElement(kuk);
        if (btn == null) return;
        btn.style.border = '1px inset';
        mapCommand = "cmObjectInfo";
        setMapAction();
      }
    if (ShowCenter)
    {
        displayCenter('CenterPoint', 10, hidePoint);
        ShowCenter = 0;
    }   
    try
    {
        showMapPanel();        
    }
    catch(e) { }
}

function displayCenter(id, k, cb){
    var cpEl = getElement(id);
    if (cpEl){
        var eMapDivXY = uiFindPos(eMapDiv);
        var mapDivSz = objSize(eMapDiv);
        var cpElSz = objSize(cpEl);
        cpEl.style.display = '';
        objectMoveTo(cpEl, eMapDivXY[0] + mapDivSz[0]/2 - cpElSz[0]/2, eMapDivXY[1] + mapDivSz[1]/2 - cpElSz[1]/2);
        animBm(cpEl.id, k, cpEl.style.backgroundColor, cpEl.style.zIndex, cb);
    }
}

function hidePoint(id) {
    var cpEl = getElement(id);
    if (cpEl) {
        cpEl.style.display = 'none';
    }
}

function InfoTooltip_Init()
{
    if (InfoTooltipPrm) {
        var eMapXY = uiFindPos(eMap);       
        InfoTooltipPrm.X += eMapXY[0];
        InfoTooltipPrm.Y += eMapXY[1];
        showInfoTooltip(InfoTooltipPrm, 0, 0, '200px');
    }
    else {
        closeInfoTooltip();
    }
}

function toolTip_Init()
{
    if (typeof(ToolTips) == 'undefined')
       return;
    infoPoints = ToolTips.split(sepPoint);
    
    var ttD = getElement('toolTipDiv');
    if (ttD != null)
    // Если HTML-элемент для отображения тултипа уже создан - обновляем его содержимое
    {
        var cx = ttD.getAttribute("coordX");
        var cy = ttD.getAttribute("coordY");
        if (cx == null || cy == null) return false;        
        cx = coordToPixY(cx);
        cy = coordToPixX(cy);
        var docScroll = uiGetScrollXY();
        var eMapXY = uiFindPos(eMap);
        var clientX = cx + eMapXY[0] - docScroll[0];
        var clientY = cy + eMapXY[1] - docScroll[1];
        
        if (ttD.style.visibility == "visible") mapMouseMoveInfo(cx, cy, clientX, clientY);
    }
    else
    // иначе создаем его
    {
        toolTipDiv = document.createElement('div');
        toolTipDiv.id = 'toolTipDiv';
        toolTipDiv.className = 'toolTipDiv';
        document.body.appendChild(toolTipDiv);

        funcMouseOver = "javascript: if (timerID == null) return; window.clearTimeout(timerID); timerID = null;";

        toolTipDiv.innerHTML =
            '<table border="0" align="left" cellpadding="2" cellspacing="0" bgcolor="#'+defaultToolTipBgColor+'" ' +
                  'style="width:200px;"'+
                  'onmouseover="' + funcMouseOver + '"' +
                  '>' + 
            '<tr valign="top">' +
            '<td colspan="3" id="TTtext"></td>' +
            '</tr>' +

            '<tr valign="top" height="15px">'+

            '<td width="40px">'+
            '<img src="../MapView/img/map/T-Backward.gif" border="0" hspace="1" vspace="1" style="cursor:pointer" onclick="javascript: switchToolTipItem(-1);">' +
            '&nbsp;' +
            '<img src="../MapView/img/map/T-Forward.gif"  border="0" hspace="1" vspace="1" style="cursor:pointer" onclick="javascript: switchToolTipItem(+1);">' +
            '</td>' +

            '<td width="150px"><div align="center" id="TTnumber"></div></td>' +

            '<td width="10px" nowrap><img src="../MapView/img/map/T-Close.gif" border="0" align="right" style="cursor:pointer" onclick="javascript: hideToolTip();"></td>' +

            '</tr>' +

            '</table>';
    }
}

function evtMouseUp(e)
{
    if (dragmode && eMap.onmousemove == mapMouseMoveDrag)
    { 
        if (browserGecko) { if (e.target == eMap || e.target == rulerDiv) { return false; } }
        else { if (event.srcElement == eMap || event.srcElement == rulerDiv) { return false; } }
        eMap.onclick();
    }
}

function eMapOnLoad()
{
    HideWaitDiv(divWait);
    if (eMap == null) return;
    if (eSize != '')
    {
        setsize(MapDivId, eSize);
        setsize(imgMap, eSize);
        if (rulerDiv != null) setsize(rulerDiv.id, eSize);
        if (bmDiv != null) setsize(bmDiv.id, eSize);
        eMap.style.visibility = 'visible';
        eSize = '';
    }
    
    eBufHide();
    
    objectMoveTo(eMap, 0, 0);
    objectMoveTo(rulerDiv, 0, 0);
    objectMoveTo(bmDiv, 0, 0);
    setMapCursor("auto");
    setMapCursor(MapCursor);
    redrawDistance();
    redrawBookmarks();
    redrawSearchArea();
    resetAutoUpdateTimer();
    if (getElement("bmListDiv") != null)
    {
        var cnt = getElement("bmListDiv").getAttribute("objCnt");
        if (cnt != null)
        {
            var obj1 = getElement("bmLi_"+cnt);
            if (obj1 != null) obj1.style.background = "#D1DDF1";
            var obj2 = getElement("bmLiT_"+cnt);
            if (obj2 != null) obj2.style.background = "#D1DDF1";
        }
    }    
    toolTip_Init();
    InfoTooltip_Init();
    if (bmAnimId){    
        var el = getElement(bmAnimId);
        if (el) animBm(bmAnimId, 10, el.style.backgroundColor, el.style.zIndex);
        bmAnimId = null;
    }    
    
    if (mapCommand == "cmFindRecord")
       { WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$Body$MapPanel1$btFindRecord", "", true, "", "", false, true)); }
    else if (mapCommand == "cmObjectInfo")
       { if (eBuf.src != eMap.src) WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$Body$MapPanel1$btObject", "", true, "", "", false, true)); }
}

function animBm(id, k, origColor, origZIndex, cbFunc) {
    var el = getElement(id);
    if (el && el.style.display!='none'){  
        el.style.backgroundColor = ((k%2) == 0) ? '#ff0000' : origColor;
        el.style.zIndex = 190;
        k--;
        if (k>0 || k<0)
            setTimeout("animBm('"+id+"',"+k+",'"+origColor+"','"+origZIndex+"',"+cbFunc+")", 250);
        else
        {
            el.style.backgroundColor = origColor;
            el.style.zIndex = origZIndex;
            if (cbFunc)
                cbFunc(id);
        }
    }
    else if (el){
        el.style.backgroundColor = origColor;
        el.style.zIndex = origZIndex;
        if (cbFunc)
            cbFunc(id);               
    }
}

function TestViewStateSize()         // Определить размер ViewState
{
    var buff = document.forms[0]["__VIEWSTATE"].value;
    alert("View state is " + buff.length + " bytes");
}

function eBufShow()
{
    if (!dragmode || eBuf == null) return false;
    eBuf.src = eMap.src;
    eBuf.style.width    = eMap.style.width;
    eBuf.style.height   = eMap.style.height;
    eBuf.style.top      = eMap.style.top;
    eBuf.style.left     = eMap.style.left;
    eBuf.style.position = eMap.style.position;
    eBuf.style.cursor   = eMap.style.cursor;
    if (browserIE && dragmode)
        { if (eMapDiv != null) eMapDiv.appendChild(eBuf); }
    else
        { eBuf.style.visibility = 'visible'; }
}

function eBufHide()
{
    if (!dragmode || eBuf == null) return;
    if (browserIE)
        { if (eMapDiv != null)
             if (eBuf.parentNode == eMapDiv) eMapDiv.removeChild(eBuf); }
    else
        { eBuf.style.visibility = 'hidden'; }
}

function ShowWaitDiv(id)                               
{
    var waitDiv = getElement(id);
    if (waitDiv == null || eMapDiv == null || eMap.alt != '' || waitDiv.style.visibility == 'visible') return;     

    waitDiv.style.left=(parseInt(eMapDiv.style.width)*0.5-parseInt(waitDiv.style.width)*0.5)+'px';
    if (waitDiv.style.height != '')
        waitDiv.style.top=(parseInt(eMapDiv.style.height)*0.5-parseInt(waitDiv.style.height)*0.5)+'px';
    else
        waitDiv.style.top=(parseInt(eMapDiv.style.height)*0.5-7)+'px';

    //waitDiv.style.top  = (parseInt(eMapDiv.style.height)-27)+'px';
    //waitDiv.style.left = 8 +'px';   
    
    //setMapCursor('wait');
    waitDiv.style.visibility='visible';
/*
    var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight; // Определение текущих размеров клиентской области
    var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    var delta = (browserGecko)?16:0; // Поправка для Gecko
    waitDiv.style.height = _docHeight + delta + 'px';
    waitDiv.style.width = _docWidth + delta + 'px';    
    waitDiv.style.left = 0;
    waitDiv.style.top = 0;
    document.body.appendChild(waitDiv);*/
}

function HideWaitDiv(id)                               
{
    var waitDiv = getElement(id);
    if (waitDiv == null || waitDiv.style.visibility == 'hidden') return;
    waitDiv.style.visibility='hidden';
}

function CreateTopDiv() // Создание вспомогательного DIV, закрывающего собой всю клиентскую область
{
    topDiv = document.createElement('div');
    topDiv.className = 'div_top';

    var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight; // Определение текущих размеров клиентской области
    var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    var delta = (browserGecko)?16:0; // Поправка для Gecko

    topDiv.style.height = _docHeight + delta + 'px';
    topDiv.style.width = _docWidth + delta + 'px';
    if (browserIE) disableSelect(); // Скрыть элементы SELECT
    document.body.appendChild(topDiv);
}

function DestroyTopDiv()  // Удаление вспомогательного DIV
{
    if (browserIE) enableSelect();
    document.body.removeChild(topDiv);
    topDiv = null;
}

/* Деактивация SELECT'ов*/
function disableSelect()
{
    var selectElements = document.getElementsByTagName('SELECT');
    enabledSelectElements = new Array();
    var i=0;
    for (var k = 0 ; k < selectElements.length; k++)
        if (!selectElements[k].getAttribute('disabled'))   // Если SELECT активен заносим его в массив и деактивируем.
            {
              enabledSelectElements[i] = selectElements[k];
              enabledSelectElements[i].setAttribute('disabled', 'disabled');
              i++;
            }
}

function enableSelect()
{
    if (enabledSelectElements == null) return;
    for (var i = 0 ; i < enabledSelectElements.length; i++)
        enabledSelectElements[i].removeAttribute('disabled');
    enabledSelectElements = null;
}

/*Скрытие SELECT'ов*/
function hideSelectElements()
{
    if (hiddenSelectElements != null) return;   // Если массив не пуст  - выход из функции
    
    var selectElements = document.getElementsByTagName('SELECT');
    hiddenSelectElements = new Array();
    var i=0;
    for (var k = 0 ; k < selectElements.length; k++)
        if (selectElements[k].style.visibility != 'hidden')   // Если SELECT активен заносим его в массив и деактивируем.
            {
              hiddenSelectElements[i] = selectElements[k];
              hiddenSelectElements[i].style.visibility = 'hidden';
              i++;
            }
}

function showSelectElements()
{
    if (hiddenSelectElements == null) return;
    for (var i = 0 ; i < hiddenSelectElements.length; i++)
        hiddenSelectElements[i].style.visibility = 'visible';
    hiddenSelectElements = null;
}

function getElement(ID)
{
    if (ID == null) return null;
    var element = null;
    if (document && document.getElementById) 
        element = document.getElementById(ID);
    return element;
}

function showRulerCancel(args)
{
     param = args.split(';');
     if (param.length < 2) return;
     var elem = document.getElementById(param[0]);
     if (elem == null) return;
     elem.style.visibility = param[1];
}

function setMapCursor(cursor)
{
    if (eMap == null) return;
    eMap.style.cursor = cursor;
    if (rulerDiv != null) rulerDiv.style.cursor = cursor;
    if (eMapDiv != null) eMapDiv.style.cursor = cursor;
    if (bmDiv != null) bmDiv.style.cursor = cursor;
    
    var sAD = getElement('sADCircleImg');
    if (sAD != null) sAD.style.cursor = cursor;
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint != null) cPoint.style.cursor = cursor;
}

function mouseout(e) 
{
   self.status="";
}

function mouseclick(e)
{
   if (browserIE)
   {
      x = event.x;
      y = event.y;
   } 
}

function buildUrl(result, context)
{
    //setMapCursor(MapCursor); 
    HideWaitDiv(divWait);
    var parts = result.split(';');
    var pnUrl = getElement('pnUrl');
    var txtMapUrl = getElement('txtMapUrl');
    var txtLogoUrl = getElement('txtLogoUrl');
    if (pnUrl && txtMapUrl && txtLogoUrl)
    {
        pnUrl.style.display = '';
        txtMapUrl.value = parts[0];
        txtLogoUrl.value = '<a href="' + parts[0] + '" target="_blank"><img style="border:none" src="' + parts[1] + '" alt="map31.ru" title="Показать на карте" /></a>';
    }
}

function hidePnUrl()
{
    document.getElementById('pnUrl').style.display='none';
    document.getElementById('txtMapUrl').value='';
    document.getElementById('txtLogoUrl').value='';
}

function showmap(result, context)
{
    if (result.length == 0) 
    {
       HideWaitDiv(divWait);
       setMapCursor(MapCursor);     
       resetAutoUpdateTimer();
       return;
    }
    if (result.indexOf("NeedRefresh") > -1)
    {
       HideWaitDiv(divWait);
       setMapCursor(MapCursor);       
       var msg = "Время сессии работы с картой истекло. Для продолжения работы необходимо ";
       msg += "обновить страницу. Обновить страницу сейчас?";
       if (confirm(msg))
          location.reload(true);
    }
    parts = result.split(';');
    if (parts == null || parts.length < 2) 
    {
        HideWaitDiv(divWait);
        setMapCursor(MapCursor);    
        resetAutoUpdateTimer();
        return;
    }

    var eMap = document.getElementById(parts[0]);
    
    if (eMap != null)
    {
        if (parts[1].lastIndexOf("mapdrawing") >= 0)
        { 
           if (!changingSize)
           {
               eBufShow();
               eMap.src = parts[1];
               eMap.alt = "";
           }
           else
              eMap.style.visibility = 'hidden';
        }
        else
        {
           eMap.style.visibility='visible';
           setMapCursor(MapCursor);
           HideWaitDiv(divWait);
        }
    }
    if (parts.length == 2) 
       return;
    var limit = parts.length; 
    for (var i=2; i<limit; i+=3)
    {		
        switch (parts[i]) {
             case 'TTInfo':             
                 if (parts[i+1] == "empty")
                 {
                    InfoTooltipPrm = null;
                    break;
                 }
                 var objPrm = parts[i+1].split("%%");
                 InfoTooltipPrm = new TtOptions();
                 InfoTooltipPrm.X = parseInt(objPrm[0]);
                 InfoTooltipPrm.Y = parseInt(objPrm[1]);
                 InfoTooltipPrm.DataBase = (objPrm[2] == "0") ? false : true;
                 InfoTooltipPrm.Text = decodeMarkup(parts[i+2]);
                 InfoTooltipPrm.EditAddr = (objPrm[3] == "0") ? false : true;
                 InfoTooltipPrm.Del = (objPrm[4] == "0") ? false : true;
                 InfoTooltipPrm.AddOrg = (objPrm[5] == "0") ? false : true;
                 InfoTooltipPrm.AddRealty = (objPrm[6] == "0") ? false : true;
                 InfoTooltipPrm.AddCust = (objPrm[7] == "0") ? false : true;
                 InfoTooltipPrm.EditTt = (objPrm[8] == "0") ? false : true;                 
                 break;
             case 'Image':
                 showimage(parts[i+1], parts[i+2]);    
                 break;
             case 'Size':
                 eSize = parts[i+2];
                 if (eMap == null)
                    break;
                 eMap.src = parts[1];
                 eMap.alt = "";
                 changingSize = false;
                 break;
             case 'Button':
                 setbutton(parts[i+1], parts[i+2]);
                 break;
             case 'tbScale':
                 var scale = parts[i+2].split('#');
                 setScale(parts[i+1], scale[0]);
                 setScaleInfo(scale[1], scale[2], scale[3]);
                 break;
             case 'ScaInf':
                 var scale = parts[i+2].split('#');
                 setScaleInfo(scale[0], scale[1], scale[2]);
                 break;
             case 'Mouse':
                 selfStatus(parts[i+1], parts[i+2]);
                 break;
             case 'Cursor':
                 setCursor(parts[i+1], parts[i+2]);
                 break;
             case 'MouseMove':
                 getElement(parts[i+1]);
                 showCoord(parts[i+1], parts[i+2]);
                 break;
             case 'Visible':
                 var eElement = document.getElementById(parts[i+1]); 
                 if (eElement == null) break;
                 eElement.style.visibility = parts[i+2];
                 break;
             case 'Hidden':
                 if (parts[i+1] == 'ClearLinkData')
                 {
                    var Elem = getElement(ctlLinkSheetID);
                    if (Elem != null)  Elem.value = "";
                    Elem = getElement(ctlLinkObjectID);
                    if (Elem != null)  Elem.value = "";
                    break;
                 }
                 var ehidd = getElement(parts[i+1]);
                 if (ehidd != null)
                 {
                    ehidd.value = parts[i+2];
                 }
                 break;
             case 'btRestore':
                $find(parts[i+1])._onClick();
                break;
             case 'ToolTip':
                ToolTips = parts[i+2];
                break;
             case 'Print':
                showPrintPanel(parts[i+1], parts[i+2]);
                break;
             case 'PrintScale':
                updatePrintPanel(parts[i+1], parts[i+2]);
                break;
             case 'AutoUpdate':
                setAutoUpdateTimer(parts[i+1], parts[i+2]);
                break;
             case 'Bookmark':
                bmAnimId = "pointBmDiv_"+parts[i+1];
                break;
             case 'userMsg':
                if (parts[i+1] && parts[i+1]!='' && parts[i+1]!='undefined')
                    alert(parts[i+1] + "\r\n\r\n" + parts[i+2]);
                else
                    alert(parts[i+2]);
                break;
             case 'AreaStat':
                updateMarkup('AreaStatSlot', (parts[i+2]), true);
                break; 
             case 'AddrSearch':
                getElement('AddrTextSlot').innerHTML = parts[i+1];
                updateMarkup('AddrSearchSlot', parts[i+2], true);
                break;
             case 'MapObj':
                if (parts[i+1] && parts[i+1] != '') {
                    resetMapActions(false);
                    mapCommand = "cmDefault";
                    updateMarkup(parts[i+1], parts[i+2], true);
                }
                break;
          }
    }
    if (eMap == null)
        return;
    eMap.style.visibility='visible';
    if (browserGecko) eMap.focus();    // focus в IE вызывает мерцание картинки и "синдром старого рисунка". под Opera страничка заполняется фрагментами черной рамки вокруг рисунка.
}

function updatePrintPanel(controlId, txt)
{
    if (typeof(controlId) === 'undefined' || typeof(txt) === 'undefined')
       return;
    var elem = getElement(controlId);
    if (typeof(elem) === 'undefined')
       return;
    elem.innerHTML = txt; 
}

function showPrintPanel(behaviorId, clientData)
{
    if (typeof(behaviorId) === 'undefined' || typeof(clientData) === 'undefined')
       return;
    
    cldata = clientData.split('?');
    
    var clientId = cldata[0];
    var ratio = parseFloat(cldata[1]); 

    //alert(clientId + "r = " + cldata[1]);

    var eData = getElement(inData1ID); // выбранные точки : eData.value='mapPrint;'+top+';'+left+';'+bottom+';'+right;
    var eW = getElement(clientId + "_lbClipWidth");
    var eH = getElement(clientId + "_lbClipHeight");
    var eFS = getElement(clientId + "_lbFileSize");
    coord = eData.value.split(';');
    if (coord.length < 5)
       return; 
    var W = parseInt(coord[4]) - parseInt(coord[2]);
    var H = parseInt(coord[3]) - parseInt(coord[1]);
    eW.innerHTML = W;
    eH.innerHTML = H;
    eFS.innerHTML = parseInt((W * H * ratio * ratio + 1078) / 1000);
    $find(behaviorId)._doOpen();
}

function decodeMarkup(encMarkup)
{
    var re = new RegExp("\\|\\{\\|","g");
    var markup = encMarkup.replace(re, "<");
    re = new RegExp("\\|\\}\\|", "g");
    markup = markup.replace(re, ">");
    re = new RegExp("\\|cp\\|", "g");
    markup = markup.replace(re, ";");    
    return markup;
}

function showimage(clientId, imgname)
{
   if (clientId == null || clientId.length == 0 || imgname == null) 
      return;      
   var eImage = document.getElementById(clientId);
   if (eImage == null) return;
   eImage.src = imgname;
}

function setsize(clientId, size)
{
   if (clientId == null || clientId.length == 0 || size == null) 
      return;
   var eImage = document.getElementById(clientId);
   if (eImage == null) return;
   WH = size.split('x');
   eImage.style.width = WH[0]+'px';
   eImage.style.height = WH[1]+'px';
}

function setbutton(clientId, enable)
{
   if (clientId == null || clientId.length == 0 || enable == null) 
      return;
   var eButton = document.getElementById(clientId);
   if (eButton == null) return;
   if (enable == 'True')
      eButton.disabled=false;
   else if (enable == 'False')
      eButton.disabled=true;
   else if (enable == 'none')
      eButton.style.display='none';
   else
      eButton.style.display='';
   
   
}

function setScale(clientId, index)
{
   if (clientId == null || clientId.length == 0 || index == null)
      return;
   tbScale = getElement(clientId);
   if (tbScale == null) return;
   $find(ssBehaviorID).set_Value(index);
}

function setScaleInfo(scale, pixels, ratio)
{
   if (scale.length == 0) return;
   
   scaleInfo = getElement(scaleInfoID);
   if (scaleInfo == null) return;
   
   if (scale == "Default")
   {
        if (scaleInfo.getAttribute("MapScale") == null)
            { scaleInfo.innerHTML = '<span class="coordInfoText">-------</span>'; return; }
        attrib = scaleInfo.getAttribute("MapScale").split('#');
        if (attrib.length < 3) return;
        scale  = attrib[0];
        pixels = attrib[1];
        ratio  = attrib[2];
   }
   
   if (scale == "FirstLoad")
   {
        if (scaleInfo.getAttribute("MapViewScale") == null)
            { scaleInfo.innerHTML = '<span class="coordInfoText">-------</span>'; return; }
        attrib = scaleInfo.getAttribute("MapViewScale").split('#');
        if (attrib.length < 3) return;
        scale  = attrib[0];
        pixels = attrib[1];
        ratio  = attrib[2];
   }

   if (scale == "")
        { scaleInfo.innerHTML = '<span class="coordInfoText">-------</span>'; return; }

   var scaleF = formatting(scale, "");
   scaleInfo.innerHTML = '<span class="coordInfoText">&nbsp;1 : ' + scaleF + '</span>';
   
   if (pixels == "")
        { scaleLineInfo.innerHTML = ''; scaleLine.style.width = '0px'; return; }

    var scaleLine = getElement(scaleLineID);
    var scaleLineInfo = getElement(scaleLineInfoID);

    var unit = "m";
    if (ratio >= 1000) { ratio = ratio / 1000; unit = "km"; }

    result = replaceSymbols(ratio + " " + unit);
    scaleLineInfo.innerHTML = '<span class="scaleLineInfoText">' + result + '</span>';
    scaleLine.style.width = parseInt(pixels)+'px';
}

function replaceSymbols(stroka)
{
    if (stroka.length == 0) return;
    var limit = stroka.length;
    var result = '';
    for (var i=0; i<limit; i++)
    {
        symb = stroka.substr(i, 1);
        if (symb != ' ') result += '<img src="mapview/img/map/symbols/s_'+symb+'.gif" alt="'+symb+'" align="texttop" height="9">';
        else result += symb;
    }
    return result;
}

function setCursor(clientId, css)
{
   if (clientId == null || clientId.length == 0 || css == null) 
      return;
   var eControl = document.getElementById(clientId);
   if (eControl == null) return;
   eControl.style.cursor = css;
}

function showBorder(eButton, context)
{
    if (eButton == null) return;    
    var btnCommand = eButton.getAttribute("mapCommand");
    if (btnCommand == null) btnCommand = "cmDefault";
    setMapCursor(defaultMapCursor);
    var index = eButton.style.borderStyle.indexOf('inset');
    resetMapActions(true);    
    mapCommand = btnCommand;
    if (setMapAction()) {
       if (btnCommand == "cmMapMove") { setMapCursor('move'); }
       /*if (btnCommand == "cmDefault" || btnCommand  == "cmMapScaleUp" || btnCommand == "cmMapScaleDown") 
       {
           setMapCursor('crosshair');
       }*/        
       if (btnCommand == "cmObjectInfo") { setCookie(sessionId, eButton.id, 24); }        
       eButton.style.border = '1px inset';
       eButton.style.borderStyle = 'inset';            
    }
    else {
        mapCommand = "cmDefault";
        MapCursor = defaultMapCursor;
    }        
    if (topDiv!=null) DestroyTopDiv();
    return;
}

function showRuler(result, context)
{
    if (result == null) return;
    controls = result.split(';');
    if (controls.length < 1) return;    
    var eButton = getElement(controls[0]);
    if (eButton == null) return;
    var btnCommand = eButton.getAttribute("mapCommand");
    if (btnCommand == null) btnCommand == "cmDefault";
    
    var newborder_style = 'none';
    var index = eButton.style.border.indexOf('inset');
    resetMapActions();
    
    if (index < 0)
      {
        newborder_style = '1px inset';
        rulermode=true;
        mapCommand = btnCommand;
        setMapAction();
      }
    else mapCommand = "cmDefault";

    eButton.style.border = newborder_style;
    if (controls.length == 1) return;
    
    var eCancel = getElement(controls[1]);
    if (eCancel == null)
       return;
       
    if (controls[2] == 'Visible')
        eCancel.style.visibility = controls[3];
    
    if (topDiv!=null) DestroyTopDiv();
    
    if (eMap == null)
       eMap = getElement(controls[4]);
    if (!browserOpera) eMap.focus();
}

function showBorderAreaSearch(result, context)
{
    /*if (result == null) return;
    controls = result.split(';');
    if (controls.length < 1) return;
    
    var eButton = document.getElementById(controls[0]);*/
    var eButton = result;
    if (eButton == null) return;
    var btnCommand = eButton.getAttribute("mapCommand");
    if (btnCommand == null) btnCommand == "cmDefault";
    
    //if (mapCommand == "cmSelectAreaCircle" && btnCommand == "cmAreaSeek") { if (topDiv!=null) DestroyTopDiv(); return; }
    //if (mapCommand == "cmAreaSeek" && btnCommand == "cmSelectAreaCircle") { if (topDiv!=null) DestroyTopDiv(); return; }
    
    var newborder_style = 'none';
    var index = eButton.style.borderStyle.indexOf('inset');
    resetMapActions();
    
    if (index != -1)
    {
        MapCursor = defaultMapCursor;
        if (mapCommand == 'cmAreaSeek') {
            eButton.style.border = '1px solid #c0c0c0';
            eButton.style.borderStyle = 'solid';
        }
        mapCommand = 'cmDefault';
    }
    else
    {
        MapCursor = defaultMapCursor;
        newborder_style = '1px inset';
        
        if ( btnCommand == 'cmAreaSeek' ||
             btnCommand == 'cmSelectAreaCircle' )
        {
           mapCommand = btnCommand;           
           /*if (controls[1] != null)
               enableMapAreaSearchMode(controls);
           
           if (controls[1] != null && controls[1] == 'O')
           {
               eMap.onmousedown = mapMouseDownDefault;
               eMap.onclick = mapClickDefault;
           }*/
           eButton.style.border = '1px inset';
           eButton.style.borderStyle = 'inset';           
           enableMapAreaSearchMode();
        }        
        /*if ( btnCommand == 'cmSelectAreaCircle' )
        {
           var elems = document.getElementsByTagName('input');
           for (var i = 0; i < elems.length; i++)
           {
               var btnCommand = elems[i].getAttribute('mapCommand');
               if (btnCommand == null)
                   continue;
               if (btnCommand == 'cmSelectAreaCircle')
                  { var index = elems[i].id.indexOf('btMVSelectCircle');
                    if (index != -1) elems[i].style.border = '1px inset #c0c0c0'; }
           }
        }*/
    }
    
    if (topDiv!=null) DestroyTopDiv();
    return;
}

function formatting(number_val, unit)
{
    Result = '';
    var number = new String(number_val);
    var Unit = new String(unit);
    var i = 0;
    var len = 0;
    var index = -1;
    var fpoint;
    while(number.charAt(i) != "")
    {
        if (number.charAt(i) == '.')
           index = i;
        len++; i++;
    }
    if (len == 0) return Result;
    fpoint = index;
    if (index == -1) index = len;
    var remainder = parseInt(index%3);
    var count = parseInt(index/3);
    var start = remainder;
    Result = number.substring(0, remainder);
    for (k = 0; k < count; k++)
    {
        Result += ' ' + number.substr(start, 3);
        start += 3;
    }
    if (fpoint >= 0)   // дробная часть
        Result += number.substr(fpoint, 3);
    return Result + ' ' + Unit;
}

function showCoord(coord, expression)
{
    if (draggable && dragmode) return;

    var eDataX=document.getElementById(ExprX_ClientID);
    var eDataY=document.getElementById(ExprY_ClientID);
    var eFx=document.getElementById(FX_ClientID);
    var eFy=document.getElementById(FY_ClientID);
    var eDist=getElement(distDataID);                                               // 18/05/07
    if (eDataX == null || eDataY == null || eFx == null || eFy == null)
       return;
    if(coord == null || coord == '')
    {
       eFx.value = "";
       return;
    }
    cXY = coord.split('?');
    exprXY = expression.split('?');
    if (cXY.length != 2 || exprXY.length < 2 )
    {
       eFx.value = "";
       return;
    }
    eFx.value = cXY[0];
    eFy.value = cXY[1];
    eDataX.value = exprXY[0];
    eDataY.value = exprXY[1];
    eDist.value = exprXY[2];                                                          // 18/05/07
}

function radianToDegrees(radians)
{
   var degrees = parseFloat(radians) * 180.0 / Math.PI;
   var iDegrees = parseInt(degrees);
   var minutes = (degrees - parseFloat(iDegrees)) * 60.0;
   var iMinutes = parseInt(minutes);
   var seconds = (minutes - parseFloat(iMinutes)) * 60.0;
   if ((seconds + 0.001) > 60.0)
   {
      seconds = 0;
      iMinutes += 1;
   }
   var seconds1 = parseInt(seconds);
   //var rem = (seconds - seconds1).toString(10);
   //var rem = rem.substring(1,4);
   if (iMinutes >= 60)
   {
      iMinutes = 0;
      iDegrees += 1;
   }
   
   iDegrees = iDegrees%360;
   Result = "";
   if (iDegrees < 10)
       Result = "00";  
   else if (iDegrees < 100)    
       Result = "0";  
   Result = Result + iDegrees.toString(10) + "° ";
   
   if (iMinutes < 10)
       Result = Result + "0";
   Result = Result + iMinutes + "' ";
   if (seconds < 10)
       Result = Result + "0";
   Result = Result + parseInt(seconds) + "''";         
   
   return Result;
}

function MouseMoveGeo(x, y) 
{
   var eParm = document.getElementById(GeoNames[3]); 
   var eData = document.getElementById(GeoNames[2]);
   var eSize = document.getElementById(GeoNames[0]);
   var eStep = document.getElementById(GeoNames[1]);
   // число столбцов, строк
   max = eSize.value.split('#'); if (max.length != 2) return;
   if(max[0] == 0 || max[1] == 0) return;
   // сетка значений координат по рядам          
   var Rows = eData.value.split('$');
   if (Rows == null || Rows.length == 0) return;
   // шаг сетки по горизонтали/вертикали
   step = eStep.value.split('#'); if (step.length != 2) return;
   if(step[0] == 0 || step[1] == 0) return;
   // положение точки в сетке
   var coll = parseInt(x)/parseInt(step[0]); var row = parseInt(y)/parseInt(step[1]);
   var coll = parseInt(coll); row = parseInt(row);
   var coll2 = coll+1; if (coll == parseInt(max[0])) coll2 = coll-1;
   var row2 = row +1; if (row == parseInt(max[1])) row2 = row-1;
   // пары координат в ряду row сетки
   var Colls = Rows[row].split('#');
   if (Colls == null || Colls.length == 0) return;
   // координаты соседних точек
   var BL11 = Colls[coll].split(','); var BL12 = Colls[coll2].split(','); 
   // пары координат в ряду row2 сетки
   Colls = Rows[row2].split('#'); 
   var BL21 = Colls[coll].split(','); var BL22 = Colls[coll2].split(',');            
   // расстояния 
   var dx = x - parseInt(coll) * parseInt(step[0]); 
   var dy = y - parseInt(row) * parseInt(step[1]); 
   var d11 = dx * dx + dy * dy; d11 = Math.sqrt(parseFloat(d11)); 
            
   dx = parseInt(coll2) * parseInt(step[0]) - x; 
   dy = y - parseInt(row) * parseInt(step[1]); 
   var d12 = dx * dx + dy * dy; d12 = Math.sqrt(parseFloat(d12)); 

   dx = x - parseInt(coll) * parseInt(step[0]); 
   dy = y - parseInt(row2) * parseInt(step[1]); 
   var d21 = dx * dx + dy * dy; d21 = Math.sqrt(parseFloat(d21)); 

   dx = parseInt(coll2) * parseInt(step[0]) - x; 
   dy = y - parseInt(row2) * parseInt(step[1]); 
   var d22 = dx * dx + dy * dy; d22 = Math.sqrt(parseFloat(d22)); 

   // весовые коэффициенты
   var w = 0.0; var Sum_wL = 0.0; var Sum_wB = 0.0; var SumBW = 0.0; var SumLW = 0.0;
   
   if (d11 > 0.0001) 
   {
      w = 1 / parseFloat(d11); 
      Sum_wL += w; SumLW += parseFloat(BL11[1]) * w; 
      Sum_wB += w; SumBW += parseFloat(BL11[0]) * w;
   }
   if (d12 > 0.0001) 
   {
      w = 1 / parseFloat(d12); 
      Sum_wB += w; SumBW += parseFloat(BL12[0]) * w; 
      Sum_wL += w; SumLW += parseFloat(BL12[1]) * w;
   }
   if (d21 > 0.0001) 
   {  
      w = 1 / d21; 
      Sum_wL += w; SumLW += parseFloat(BL21[1]) * w; 
      Sum_wB += w; SumBW += parseFloat(BL21[0]) * w;
   } 
   if(d22 > 0.0001) 
   {
      w = 1 / d22; 
      Sum_wL += w; SumLW += parseFloat(BL22[1]) * w; 
      Sum_wB += w; SumBW += parseFloat(BL22[0]) * w;
   } 
   if (Sum_wB <= 0 || Sum_wL <= 0) return; 
   var L = SumLW / Sum_wL; var B = SumBW / Sum_wB; 
   selfStatus('B = ' + radianToDegrees(B), 'L = ' + radianToDegrees(L));
}

function objectMoveTo(obj, cX, cY)
{
    if (obj==null) return;
    if (isNaN(cX)) return;
    if (isNaN(cY)) return;
    
    obj.style.left = parseInt(cX) + 'px';
    obj.style.top  = parseInt(cY) + 'px';
}

function objectShiftOn(obj, cX, cY)
{
    if (obj==null) return;
    
    var x0 = parseInt(obj.style.left);
    var y0 = parseInt(obj.style.top);
    if (isNaN(x0)) x0 = 0;
    if (isNaN(y0)) y0 = 0;
    
    obj.style.left = x0 + parseInt(cX) + 'px';
    obj.style.top  = y0 + parseInt(cY) + 'px';
}

function enableRulerMode()
{
    setPreMode();
    eMap.onclick = mapClickDefault;
    eMap.onmousedown = mapMouseDownDefault;
    eMap.onmousemove = mapMouseMoveDefault;

    var sAD = getElement('sADCircleImg');
    if (sAD != null)
    { setPreModeSAD();
      sAD.onmouseup = mapClickDefault;
      sAD.onmousedown = mapMouseDownDefault;
      sAD.onmousemove = mapMouseMoveDefault; }

    if (rulerDiv != null) return true;
    distancePoints = new Array();
    distancePoints[0] = sessionId;
    rulerDiv = document.createElement('div');
    rulerDiv.id='rulerDiv';
    rulerDiv.className = 'rulerDivStyle';
    if (getElement(MapDivId) == null) return true;
    getElement(MapDivId).appendChild(rulerDiv);
    objectMoveTo(rulerDiv, 0, 0);
    rulerDiv.style.width  = eMap.style.width;
    rulerDiv.style.height = eMap.style.height;
    rulerDiv.setAttribute('onclick', 'javascript: eMap.onclick(event);');
    rulerDiv.setAttribute('onmousemove', 'javascript: eMap.onmousemove(event);');
    rulerDiv.setAttribute('onmousedown', 'javascript: eMap.onmousedown(event);');
    return true;
}

function disableRulerMode()
{
    restorePreMode();
    restorePreModeSAD();
}

function restoreDistance()
{
    var dc = getCookie('distPoints');
    if (dc == null) return;
    dc = dc.split(',');
    if (dc[0] != sessionId) { delCookie('distPoints'); return; }
    
    for (i=1; i<dc.length; i++)
      { XY = coordToPix(dc[i]).split(';');
        distanceClick(XY[0],XY[1]); }
}

function redrawDistance()
{
    if (rulerDiv == null || distancePoints == null) return;
    
    var x1=0; var y1=0;
    var pre_point = null;
    var newX = 0; var newY = 0;
    
    for (i=1; i<distancePoints.length; i++)
      {
        XY = coordToPix(distancePoints[i]).split(';');
        newX = XY[0]-delta;
        newY = XY[1]-delta;
        objectMoveTo(getElement('pointDiv_'+i), newX, newY);
        
        pre_point = getElement('pointDiv_'+(i-1));
        if (pre_point == null)
            { x1=XY[0]-delta; y1=XY[1]-delta; }
        else
            { x1=parseInt(pre_point.style.left)+delta; y1=parseInt(pre_point.style.top)+delta; }
            
        var line = getElement('distanceLine_' + i);
        if (line != null) { rulerDiv.removeChild(line); line = null; }
        
        drawLine(x1, y1, XY[0], XY[1], i);
      }
}

function clearDistance()
{
    distancePoints = null;
    idCount = 0;
    length = 0;

    if (rulerDiv != null && getElement(MapDivId) != null)
        { getElement(MapDivId).removeChild(rulerDiv); rulerDiv = null; }
    delCookie('distPoints');
}

function distanceClick(coordX,coordY)
{
    if (eMap == null) eMap = getElement(imgMap);
    if (rulerDiv == null) enableRulerMode();
    idCount++;
    setDistancePoint(idCount, coordX, coordY);
}

function setDistancePoint(idCount,cX,cY)
{
    var pointDiv = document.createElement('div');
    pointDiv.id='pointDiv_'+idCount;
    pointDiv.className = 'pointDivStyle';
    var delta_x = cX-delta;
    var delta_y = cY-delta;
    var x1=0; var y1=0;
    var pre_point = getElement('pointDiv_'+(idCount-1));    
    if (pre_point == null || typeof(pre_point) == 'undefined')
        {x1=cX; y1=cY;}
    else
        {x1=parseInt(pre_point.style.left)+delta; y1=parseInt(pre_point.style.top)+delta;}
    if (rulerDiv == null) return;
    rulerDiv.appendChild(pointDiv);
    objectMoveTo(pointDiv, delta_x, delta_y);
    drawLine(x1, y1, cX, cY, idCount);
    distancePoints[idCount] = pixToCoord(pointDiv.id);
    pointDiv.innerHTML = '';
    pointDiv.setAttribute('onclick', 'javascript: event.stopPropagation();');
    pointDiv.setAttribute('onmousemove', 'javascript: event.stopPropagation();');
    pointDiv.setAttribute('onmousedown', 'javascript: event.stopPropagation();');
    if (testCookie('distPoints', distancePoints, 24))
        setCookie('distPoints', distancePoints, 24);

    var lengthDiv = document.createElement('div');
    lengthDiv.id='lengthDiv_'+idCount;
    lengthDiv.className = (browserGecko)? 'lengthDivStyleGecko' : 'lengthDivStyleIE';
    if (getElement('lengthDiv_'+(idCount-1)) != null)
        {
            obj = getElement('lengthDiv_'+(idCount-1));
            symb = (browserOpera)?"\xA0" : "&";
            ind = obj.innerHTML.lastIndexOf(symb);
            obj.innerHTML = obj.innerHTML.substring(0, ind);
        }
    pointDiv.appendChild(lengthDiv);
    delta_x = 2*delta+1;
    delta_y = -(2*delta+6);
    objectMoveTo(lengthDiv, delta_x, delta_y);
    len = getLength(distancePoints[idCount], distancePoints[idCount-1]);
    lengthDiv.innerHTML = '<span style="color:Gray; font-size:90%">'+idCount+'.</span>&nbsp;'+len+closePic;
    lengthDiv.setAttribute('onclick', 'javascript: event.stopPropagation();');
    lengthDiv.setAttribute('onmousemove', 'javascript: event.stopPropagation();');
    lengthDiv.setAttribute('onmousedown', 'javascript: event.stopPropagation();');
}

function drawLine(x1, y1, x2, y2, count)
{
    var lw=2;
    if (browserIE)
    {
        x1 = parseInt(x1); y1 = parseInt(y1);
        x2 = parseInt(x2); y2 = parseInt(y2);

        var line=document.createElement('hr');
        line.className = 'distanceLine';
        line.id = 'distanceLine_' + count;
        
        var fx=true, fy=true;

        if (x1>x2) {fx=false; t=x1; x1=x2; x2=t;}
        if (y1>y2) {fy=false; t=y1; y1=y2; y2=t;}
        var dx = 2, dy = 2;
        x1+=dx; y1+=dy; x2+=dx; y2+=dy;

        var w=x2-x1; var h=y2-y1; 
        var c=Math.sqrt((w*w)+(h*h));

        objectMoveTo(line, x1-dx,y1-dy);
        line.style.width = c;

        var cs=(fx ? w:-w)/c;
        var sn=(fy ? h:-h)/c;

        var filter='';

        filter+="progid:DXImageTransform.Microsoft.Alpha(opacity=80) ";

        filter+="progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand'," + 
                "FilterType='bilinear'"+",M11="+(cs)+",M12="+(-sn)+",M21="+(sn)+",M22="+(cs)+")";

        line.style.filter=filter;
        rulerDiv.appendChild(line);
    }

    else if(browserOpera || browserGecko)
    {
        var x1 = parseInt(x1); var y1 = parseInt(y1);
        var x2 = parseInt(x2); var y2 = parseInt(y2);
        
        var line=document.createElement('canvas');
        rulerDiv.appendChild(line);
        line.className = 'distanceLine';
        line.id = 'distanceLine_' + count;

        var t;
        var fx=true; var fy=true;

        if(x1>x2) {fx=false; t=x1; x1=x2; x2=t;}
        if(y1>y2) {fy=false; t=y1; y1=y2; y2=t;}

        var dx = 0; var dy = 0;
        x1+=dx; y1+=dy; x2+=dx; y2+=dy;

        var w=x2-x1; var h=y2-y1;
        objectMoveTo(line, x1-dx,y1-dy);

        line.width=w;
        line.height=h;

        var ctx= line.getContext('2d');
        ctx.lineWidth=lw;
        ctx.strokeStyle='#FF0000';
        ctx.globalAlpha=0.80;

        ctx.beginPath();
        ctx.moveTo(fx ? dx:w-dx, fy ? dy:h-dy);
        ctx.lineTo(fx ? w-dx:dx, fy ? h-dy:dy);
        ctx.stroke();
    }
    else
    {
        return;
    }
}

function getLength(pointId1, pointId0)
{
    if (pointId0.indexOf(';') == -1) return '0&nbsp;м';
    if (pointId1 == null) return length;
    var coord0 = pointId0.split(';');
    var x0 = parseFloat(coord0[0]);
    var y0 = parseFloat(coord0[1]);
    var coord1 = pointId1.split(';');
    var x1 = parseFloat(coord1[0]);
    var y1 = parseFloat(coord1[1]);
    length += Math.round(Math.sqrt( Math.pow((x1-x0),2) + Math.pow((y1-y0),2) )); // посчитанное расстояние в метрах
        
    var len = length; var unit = "м";
    if (length > 1000)  { len = length / 1000; unit = "км"; }
    len = formatting(len, unit);
    while (len.indexOf(' ') != -1) len = len.replace(' ', '\xA0');

    return len;
}

function pixToCoord(obj_id)
{
    if (obj_id == null || obj_id.length == 0 || getElement(obj_id) == null) return;
    if (getElement(distDataID) == null) return;
    var DistData = getElement(distDataID).value.split('#');
    var eDataX=parseFloat(DistData[0]);
    var eDataY=parseFloat(DistData[1]);
    var eFx=parseFloat(DistData[2]);
    var eFy=parseFloat(DistData[3]);
    var coordX = parseInt(getElement(obj_id).style.left) + delta;
    var coordY = parseInt(getElement(obj_id).style.top)  + delta;

    var x = eDataX + eFx * coordY;
    var y = eDataY + eFy * coordX;
    return str=x+';'+y;
}

function coordToPix(point)
{
    if (point == null || point.length == 0) return;
    if (getElement(distDataID) == null) return;
    var coord = point.split(';');
    var x = coord[0]; var y = coord[1];

    var distData = getElement(distDataID).value.split('#');
    var eDataX=parseFloat(distData[0]);
    var eDataY=parseFloat(distData[1]);
    var eFx=parseFloat(distData[2]);
    var eFy=parseFloat(distData[3]);

    var cY = (x-eDataX) / eFx;
    var cX = (y-eDataY) / eFy;
    return str=Math.round(cX)+';'+Math.round(cY);
}

function setCookie(name,value,time)
{
    var k = getCookieString(name,value,time);
    if (k) {
        document.cookie = k;
     } 
}

function testCookie(name,value,time)
{
    var cn = getCookie(name);
    var currL = 0;
    if (cn)
        currL = (name+'='+encodeURIComponent(getCookie(name))).length;
    var totL = document.cookie.length;
    var newL = (name+'='+encodeURIComponent(value)).length;
    if ((totL - currL + newL) >= (4096-160)) // запас 160 байт для HttpOnly cookie
        return false;
    document.cookie = getCookieString(name,value,time);
    return true;
}

function getCookieString(name,value,time)
{
    if (value==null || value=='' || typeof(time) == 'undefined') 
        return null;    
    var kukie = name+'='+encodeURIComponent(value)+';path=/';
    var expire = new Date();
    expire.setTime(expire.getTime()+time*3600000);
    kukie += ';expires='+expire.toGMTString();
    return kukie;
}

function getCookie(name)
{
    var kukie = document.cookie;
    var index = kukie.indexOf(name+'=');
    if (index == -1){return null;}
    index = kukie.indexOf('=',index)+1;
    var endstr = kukie.indexOf(';',index);
    if (endstr == -1) { endstr = kukie.length; }
    return decodeURIComponent(kukie.substring(index,endstr).replace(new RegExp("\\+","ig") , "%20"));
}

function delCookie(name)
{
    var expire = new Date();
    expire.setTime(expire.getTime()-3600000*24*365);
    document.cookie = name+'='+'value=;expires='+expire.toGMTString()+';path=/';
}

function selfStatus(coordX, coordY)
{
     if (getElement(coordInfoID) == null) return;
     getElement(coordInfoID).innerHTML = "<span class='scaleText'>" + coordX + "&nbsp;&nbsp;&nbsp;" + coordY+ "</span>";
}

function clearStatus()
{
    if (getElement(coordInfoID) == null)
        return;
    var resource = getElement('ctl00_Body_hfRes');   // строки ресурсов
    var strs = ["Текущие координаты", "", "", "", "", ""];
    if (resource != null)
    {
       var strs1 = resource.value.split(';');
       if (strs1.length >= 6)
          strs = strs1;
    }
    getElement(coordInfoID).innerHTML = "<span class='scaleText'>"+strs[0]+"</span>";
}

function mapMouseMoveInfo(x, y, clientX, clientY)
{
    if (isNaN(x) || isNaN(y), isNaN(clientX), isNaN(clientY)) return;
    
    var xP = 0;                // координата X точки из списка
    var yP = 0;                // координата Y точки из списка
    var xy;                    // координаты точки
    var rec;                   // данные точки
    var number = 0;            // количество активных объектов
    var toolTipMassive = "";
    var fontSize;              // размер шрифта (2)
    var color;                 // цвет фона (3)
    var urlText;               // инфо об объекте (4+5)
    
    var ttD = getElement('toolTipDiv');
    if (ttD == null) return false;
    
    for (var i = 0; i < (infoPoints.length-1); i++)
    {
        // Координаты точки из списка
        xy = infoPoints[i].split(sepMember);
 
        xP = parseInt(xy[0]);
        yP = parseInt(xy[1]);
        // Если координаты точки в пределах заданного числа пикселей от положения курсора мышки
        if ( xP < (x - defaultToolTipDopusk) ) continue;
        if ( xP > (x + defaultToolTipDopusk) ) continue;
        if ( yP < (y - defaultToolTipDopusk) ) continue;
        if ( yP > (y + defaultToolTipDopusk) ) continue;

        rec = infoPoints[i].split(sepMember);
        number++;
        color = '#' + (rec[3]=="" ? defaultToolTipBgColor : rec[3]);
        fontSize = rec[2]=="" ? defaultToolTipFontSize : rec[2];
        index = rec[4].lastIndexOf("{br}");
        while (index >= 1)
        {
            rec[4] = rec[4].substr(0, index) + "<br/>" + rec[4].substr(index+4);
            index = rec[4].lastIndexOf("{br}");
        }
        var keyword = rec[5].substring(0, 11);
        if (rec[5] == "") { urlText = rec[4]; }     // простой текст
        else if (rec[5] != "" && keyword != "javascript:")    // ссылка
                {
                   urlText = '<a href="' + rec[5] + '" target="_blank" ' +
                             'class="toolTipDivText">' + rec[4] + '</a>';
                }
        else if (rec[5] != "" && keyword == "javascript:")   // скрипт
                { 
                   var onclickText = rec[5] + "('"+rec[6]+"');";
                   urlText = '<span onclick="'+ onclickText +'" class="toolTipDivText">' + rec[4] + '</span>';
                   if (rec[7]){
                       urlText += '<br /><a href="' + rec[7] + '" target="_blank">Дополнительная информация</a>';
                   }
                }
        
        toolTipMassive += sepMember +
                          '<div align="justify" style="background-color: '+color+
                          '; width: 100%; font-size: ' + fontSize +'px" align="justify">' +
                          urlText + '</div>';
    }
    
    if (toolTipMassive.length > 0)
    {
        ttD.setAttribute("toolTipMassive", toolTipMassive);
        ttD.setAttribute("coordX", pixToCoordX(x));
        ttD.setAttribute("coordY", pixToCoordY(y));
        showToolTip(clientX, clientY);
    }
    // Если отображать нечего то в случае если тултип виден - скрываем его
    else if (ttD.style.visibility == "visible" && timerID == null) { timerID = window.setTimeout("fadeOutToolTip()", 1000); }
}

function showToolTip(cX, cY)
{
    var ttD = getElement('toolTipDiv');
    if (ttD == null) return false;
    
    var activeObjects = ttD.getAttribute("toolTipMassive");
    if (activeObjects == null) return;
    
    activeObjects = activeObjects.split(sepMember);
    var count = activeObjects.length - 1;
    var index = 1;   // Отображаем первый элемент списка

    var delta = (browserIE)?2:4;
    var docScroll = uiGetScrollXY();
    cX = cX + delta + docScroll[0];
    cY = cY + delta + docScroll[1];
    objectMoveTo(ttD, cX, cY);
    
    var eMapXY = uiFindPos(eMap);
    var w = parseInt(eMap.style.width);
    var tabl = cX + 202;
    var ram  = eMapXY[0] + w;
    if (tabl > ram)
      { objectShiftOn(ttD, -207, 0); }
    
    
    var ttNumber = getElement('TTnumber');
    if (ttNumber != null)
          ttNumber.innerHTML = '';
    if (count > 1)
        { ttNumber.innerHTML = index + ' / ' + count;
          ttD.setAttribute("activeObjectIndex", index); }
    
    var ttText = getElement('TTtext');
    if (ttText != null)
          ttText.innerHTML = activeObjects[index] + '<hr width="100%" size="1">';
    
    ttD.style.opacity = 1;
    ttD.style.visibility = 'visible';
    timerID = null;
}

function switchToolTipItem(dir)
{
    var ttD = getElement('toolTipDiv');
    if (ttD == null) return false;
    
    var activeObjects = ttD.getAttribute("toolTipMassive");
    if (activeObjects == null) return;
    
    activeObjects = activeObjects.split(sepMember);
    var count = activeObjects.length - 1;
    var index = parseInt(ttD.getAttribute("activeObjectIndex"));

    if (dir == '-1' && index > 1)
    {
        var ttNumber = getElement('TTnumber');
        if (ttNumber == null) return false;
        
        ttNumber.innerHTML = '';
        if (count > 1)
        {
            var newIndex = index - 1;
            ttNumber.innerHTML = newIndex + ' / ' + count;
            ttD.setAttribute("activeObjectIndex", newIndex);
        }

        var ttText = getElement('TTtext');
        if (ttText == null) return false;
        ttText.innerHTML = activeObjects[newIndex] + '<hr width="100%" size="1">';
    }

    if (dir == '+1' && index < count)
    {
        var ttNumber = getElement('TTnumber');
        if (ttNumber == null) return false;
        
        ttNumber.innerHTML = '';
        if (count > 1)
        {
            var newIndex = index + 1;
            ttNumber.innerHTML = newIndex + ' / ' + count;
            ttD.setAttribute("activeObjectIndex", newIndex);
        }
        
        var ttText = getElement('TTtext');
        if (ttText == null) return false;
        ttText.innerHTML = activeObjects[newIndex] + '<hr width="100%" size="1">';
    }
}

function hideToolTip()
{
    var ttD = getElement('toolTipDiv');
    if (ttD == null) return false;
    ttD.style.visibility = 'hidden';
}

function fadeOutToolTip()
{
    if (timerID == null) return;
    var ttD = getElement('toolTipDiv');
    if (ttD != null) fadeOut(ttD, 50, 0.2);
    timerID = null;
}

function fadeOut(obj, fadeTimeDelta, fadeOpacityDelta)
{
    if (obj == null || isNaN(fadeTimeDelta) || isNaN(fadeOpacityDelta)) return;
    var originalOpacity = typeof(obj.style.opacity) == 'number' ? obj.style.opacity : 1;
    var opacity = originalOpacity;
    var count = opacity/fadeOpacityDelta;
    var str="";
    
    for (i=1; i <= count; i++)
    {
        opacity = originalOpacity - (i*fadeOpacityDelta);
        window.setTimeout('setOpacity("'+obj.id+'", '+opacity+')', fadeTimeDelta * i);
    }

    window.setTimeout('hideToolTip()', fadeTimeDelta * (i+1));
    window.setTimeout('setOpacity("'+obj.id+'", '+originalOpacity+')', fadeTimeDelta * (i+2));
}

function setOpacity(objID, opacity)
{
    if (getElement(objID) == null || isNaN(opacity)) return;
    
    var objStyle = getElement(objID).style;
    if (browserIE && typeof(objStyle.filter) == 'string')
        objStyle.filter = 'alpha(opacity='+opacity*100+');';
    else objStyle.opacity = opacity;
}

function enableMapPrintMode()
{
    var sAD = getElement('selectedAreaDiv');
    if (sAD != null) return true;
    sAD = document.createElement('div');
    sAD.id = 'selectedAreaDiv';
    sAD.className = 'selectedAreaDiv';
    sAD.onmouseup = mapClickSelectArea;
    sAD.onmousemove = mapMouseMoveSelectArea;
    MapDiv = getElement(MapDivId);
    if (MapDiv != null) MapDiv.appendChild(sAD);
    setPreMode();
    eMap.onmousedown = mapMouseDownSelectArea;
    eMap.onclick = mapClickSelectArea;
    return true;
}

function disableMapPrintMode()
{
    var sAD = getElement('selectedAreaDiv');
    if (sAD == null) return;
    MapDiv = getElement(MapDivId);
    if (MapDiv != null) MapDiv.removeChild(sAD);
    sAD = null;
    restorePreMode();
}

function enableMapAreaSearchMode(params)
{
    var sAD = document.createElement('div');
    sAD.id = 'selectAreaDiv';
    sAD.className = 'selectedAreaDiv';
    /*sAD.style.position = "absolute";
    sAD.style.filter = "alpha(opacity=20)";
    sAD.style.opacity=0.20;
    sAD.style.visibility = "hidden";
    sAD.style.cursor = defaultMapCursor;*/
    
    //sAD.innerHTML = '<img id="sADCircleImg" border="0" hspace="1" vspace="1">';
    MapDiv = getElement(MapDivId);
    if (MapDiv != null) MapDiv.appendChild(sAD);
    setPreMode();
    eMap.onmousedown = mapMouseDownAreaSearch;
    eMap.onclick = mapClickAreaSearch;
    /*sAD.setAttribute('params', params);
    sAD = getElement('sADCircleImg');
    if (eCircle != null) {sAD.src = eCircle.src;}
    else {sAD.src = 'MapView/img/map/circle.gif';}*/
    sAD.onmousedown = mapMouseDownAreaSearch;
    sAD.onmouseup = mapClickAreaSearch;
}

function disableMapAreaSearchMode()
{
    var sAD = getElement('selectAreaDiv');
    if (sAD == null) return;
    var MapDiv = getElement(MapDivId);
    if (MapDiv != null) MapDiv.removeChild(sAD);
    sAD = null;
    deleteAreaSearchCenterPoint();
}

function hideAreaDiv(objID)
{
    var obj = getElement(objID);

    if (obj == null) return;

    obj.style.visibility = 'hidden';
    obj.style.height = '0px';
    obj.style.width = '0px';

    eventClientX0 = 0; eventClientX = 0; eventX = 0;
    eventClientY0 = 0; eventClientY = 0; eventY = 0;
}

function enableFindRecordMode()
{
    eMap.onclick = mapClickFindRecord;
    return true;
}

function enableObjectInfo()
{
    eMap.onclick = mapClickObjectInfo;
    return true;
}

function uiFindPos(obj)
{
	if (obj == null) return;
	
	var curleft = 0;
	var curtop = 0;
	
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function uiGetScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function uiGetEventXY(obj, clientX, clientY)
{
    if (obj == null) return;
    
    var mPosX = 0; var mPosY = 0;
    
//    if (browserGecko) {
    if (isNaN(clientX) || isNaN(clientY)) return;
    var objXY = uiFindPos(obj);    // Положение объекта на странице
    var sXY = uiGetScrollXY();     // Скроллинг страницы
    mPosX = clientX - objXY[0] + sXY[0];
    mPosY = clientY - objXY[1] + sXY[1];
//    } else { mPosX=event.x; mPosY=event.y; }
    
    return [ mPosX, mPosY ];
}

function objSize(obj)
{
	if (obj == null) return;	
	return [obj ? (obj.offsetWidth || obj.style.pixelWidth || 0) : 0, obj ? (obj.offsetHeight || obj.style.pixelHeight || 0) : 0];
}

function setPreMode()
{
    if (eMap == null) return;
    
    if (eMap.onclick != null) preonclick = eMap.onclick;
    if (eMap.onmousedown != null) preonmousedown = eMap.onmousedown;
    if (eMap.onmousemove != null) preonmousemove = eMap.onmousemove;
}

function restorePreMode()
{
    if (eMap == null) return;
    
    if (preonclick != null && preonclick != eMap.onclick) { eMap.onclick = preonclick; preonclick = null; }
      else { eMap.onclick = mapClickDefault; }      
    if (preonmousedown != null && preonmousedown != eMap.onmousedown) { eMap.onmousedown = preonmousedown; preonmousedown = null; }
      else { eMap.onmousedown = mapMouseDownDefault; }
    if (preonmousemove != null && preonmousemove != eMap.onmousemove) { eMap.onmousemove = preonmousemove; preonmousemove = null; }
      else { eMap.onmousemove = mapMouseMoveDefault; }
}

function setPreModeSAD()
{
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return;
    
    if (sAD.onmouseup != null) preonclicksad = sAD.onmouseup;
    if (sAD.onmousedown != null) preonmousedownsad = sAD.onmousedown;
    if (sAD.onmousemove != null) preonmousemovesad = sAD.onmousemove;
}

function restorePreModeSAD()
{
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return;
    
    if (preonclicksad != null && preonclicksad != sAD.onmouseup) { sAD.onmouseup = preonclicksad; preonclicksad = null; }
      else { sAD.onmouseup = mapClickDefault; }
    if (preonmousedownsad != sAD.onmousedown) { sAD.onmousedown = preonmousedownsad; preonmousedownsad = null; }
      else { sAD.onmousedown = mapMouseDownDefault; }
    if (preonmousemovesad != sAD.onmousemove) { sAD.onmousemove = preonmousemovesad; preonmousemovesad = null; }
      else { sAD.onmousemove = mapMouseMoveDefault; }
}

function enablePutObjectMode()
{
    setPreMode();
    eMap.onclick = mapClickDefault;
    eMap.onmousedown = mapMouseDownDefault;
    eMap.onmousemove = mapMouseMoveDefault; 
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return true;
    setPreModeSAD();
    sAD.onmouseup = mapClickDefault;
    sAD.onmousedown = mapMouseDownDefault;
    
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint == null) return true;
    cPoint.onmouseup = mapClickDefault;
    cPoint.onmousedown = mapMouseDownDefault;           
    return true;
}

function disablePutObjectMode()
{
    restorePreMode();
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return;
    restorePreModeSAD();
    sAD.onmouseup = mapClickAreaSearch;
    sAD.onmousedown = mapMouseDownAreaSearch;
    
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint == null) return;
    cPoint.onmouseup = mapClickAreaSearch;
    cPoint.onmousedown = mapMouseDownAreaSearch;
}

function enableDragMode()
{
    setPreMode();
    eMap.onclick = mapClickDefault;
    eMap.onmousedown = mapMouseDownDefault;
    eMap.onmousemove = mapMouseMoveDefault;
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return true;
    setPreModeSAD();
    sAD.onmousedown = eMap.onmousedown;
    sAD.onmouseup = eMap.onclick;
    
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint == null) return true;
    cPoint.onmousedown = eMap.onmousedown;
    cPoint.onmouseup = eMap.onclick;
    return true;
}

function disableDragMode()
{
    restorePreMode();
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return;
    restorePreModeSAD();
    sAD.onmouseup = mapClickAreaSearch;
    sAD.onmousedown = mapMouseDownAreaSearch;
    
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint == null) return;
    cPoint.onmouseup = mapClickAreaSearch;
    cPoint.onmousedown = mapMouseDownAreaSearch;
}

function enableZoomMode()
{
    setPreMode();
    eMap.onclick = mapClickDefault;
    eMap.onmousedown = mapMouseDownDefault;
    eMap.onmousemove = mapMouseMoveDefault;
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return true;
    setPreModeSAD();
    sAD.onmouseup = mapClickDefault;
    sAD.onmousedown = mapMouseDownDefault;
    
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint == null) return true;
    cPoint.onmouseup = mapClickDefault;
    cPoint.onmousedown = mapMouseDownDefault;
    return true;
}

function disableZoomMode()
{
    restorePreMode();
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return;
    restorePreModeSAD();
    
    var cPoint = getElement('areaSearchCenterPoint');
    if (cPoint == null) return;
    cPoint.onmouseup = mapClickAreaSearch;
    cPoint.onmousedown = mapMouseDownAreaSearch;
}

function setAutoUpdateTimer(objID, timeValue)
{
    if (isNaN(timeValue))
    {
        var time = getElement(objID);
        if (time == null) return;
        MapAutoUpdatePeriod = time.value;
    }
    else MapAutoUpdatePeriod = timeValue;
    
    resetAutoUpdateTimer();
}

function resetAutoUpdateTimer()
{
    if (MapAutoUpdatePeriod > 0)
    {
      if (updateTimerID != null)
      {
        try
        { window.clearTimeout(updateTimerID); }
        catch(exception)
        { }
      }
      updateTimerID = window.setTimeout("updateImage()", MapAutoUpdatePeriod*1000);
    }
    else
    {
      try
      { window.clearTimeout(updateTimerID); }
      catch(exception)
      { }
      updateTimerID = null;
    }
}

function updateImage()
{
    var eData=getElement(inData1ID);
    if (eData == null)
        return;
    eData.value='mapUpdate;';
    ShowWaitDiv(divWait);
    updateTimerID = null;
    callbackFunction();
    return false;
}


/* Перевод пикселей в координаты */
// С учетом координат верхнего левого угла отображаемой области
function pixToCoordX(x)
{
    if (isNaN(x) || getElement(distDataID) == null) return;
    
    var distData = getElement(distDataID).value.split('#');
    var eDataY=parseFloat(distData[1]);
    var eFy=parseFloat(distData[3]);
    var coordY = eDataY + eFy * x;
    return coordY;
}

// Без учета координат верхнего левого угла отображаемой области
function pixToCoordRelX(x)
{
    if (isNaN(x) || getElement(distDataID) == null) return;
    
    var distData = getElement(distDataID).value.split('#');
    var eFy=parseFloat(distData[3]);
    var coordY = eFy * x;
    return coordY;
}

// С учетом координат верхнего левого угла отображаемой области
function pixToCoordY(y)
{
    if (isNaN(y) || getElement(distDataID) == null) return;

    var distData = getElement(distDataID).value.split('#');
    var eDataX=parseFloat(distData[0]);
    var eFx=parseFloat(distData[2]);
    var coordX = eDataX + eFx * y;
    return coordX;
}

// Без учета координат верхнего левого угла отображаемой области
function pixToCoordRelY(y)
{
    if (isNaN(y) || getElement(distDataID) == null) return;

    var distData = getElement(distDataID).value.split('#');
    var eFx=parseFloat(distData[2]);
    var coordX = eFx * y;
    return coordX;
}


/* Перевод координат в пиксели */
// С учетом координат верхнего левого угла отображаемой области
function coordToPixX(x)
{
    if (isNaN(x) || getElement(distDataID) == null) return;

    var distData = getElement(distDataID).value.split('#');
    var eDataX=parseFloat(distData[0]);
    var eFx=parseFloat(distData[2]);
    var cY = (x-eDataX) / eFx;
    return Math.round(cY);
}

// Без учета координат верхнего левого угла отображаемой области
function coordToPixRelX(x)
{
    if (isNaN(x) || getElement(distDataID) == null) return;
    
    var distData = getElement(distDataID).value.split('#');
    var eFx=parseFloat(distData[2]);
    var cY = x / eFx;
    return Math.round(cY);
}

// С учетом координат верхнего левого угла отображаемой области
function coordToPixY(y)
{
    if (isNaN(y) || getElement(distDataID) == null) return;

    var distData = getElement(distDataID).value.split('#');
    var eDataY=parseFloat(distData[1]);
    var eFy=parseFloat(distData[3]);
    var cX = (y-eDataY) / eFy;
    return Math.round(cX);
}

// Без учета координат верхнего левого угла отображаемой области
function coordToPixRelY(y)
{
    if (isNaN(y) || getElement(distDataID) == null) return;
    
    var distData = getElement(distDataID).value.split('#');
    var eFy=parseFloat(distData[3]);
    var cX = y / eFy;
    return Math.round(cX);
}



function callbackFunctionShowmap(clientID, hiddenFieldID)
{
    var hf = getElement(hiddenFieldID);
    if (hf == null) return false;
    
    WebForm_DoCallback(clientID, hf.value, showmap, null, null, false);

    return false;
}

/* Отобразить область поиска */
/* На входе значения в метрах */
function showSearchArea(cX, cY, r)
{
    if (isNaN(cX) || isNaN(cY) || isNaN(r)) return false;
    
    var sAD = getElement('sADCircleImg');
    if (sAD == null) return false;
    
    var centerX = coordToPixY(cX);
    var centerY = coordToPixX(cY);
    var radius = Math.abs(coordToPixRelX(r));
    var d = radius * 2;   // диаметр
    
    sAD.style.left   = (centerX - radius) + 'px';
    sAD.style.top    = (centerY - radius) + 'px';
    sAD.style.width  = d + 'px';
    sAD.style.height = d + 'px';
    
    var sADC = getElement('sADCircleImg');
    if (sADC != null)
    {
        sADC.style.width  = d + 'px';
        sADC.style.height = d + 'px';
    }
    
    setAreaSearchCenterPoint();
    if (sAD.style.visibility != 'visible') sAD.style.visibility = 'visible';
}

/* Отобразить область поиска */
/* На входе значения в пикселях */
function showSearchAreaPix(cX, cY, r)
{
    if (isNaN(cX) || isNaN(cY) || isNaN(r)) return false;
    
    var sAD = getElement('selectAreaDiv');
    if (sAD == null) return false;
    var d = r * 2;  // диаметр
    
    sAD.style.left   = (cX - r) + 'px';
    sAD.style.top    = (cY - r) + 'px';
    sAD.style.width  = d + 'px';
    sAD.style.height = d + 'px';
    
    var sADC = getElement('sADCircleImg');
    if (sADC != null)
    {
        sADC.style.width  = d + 'px';
        sADC.style.height = d + 'px';
    }

    setAreaSearchCenterPoint();
    if (sAD.style.visibility != 'visible') sAD.style.visibility = 'visible';
}

/* Отобразить область поиска */
/* На входе координаты центра (x, y) в пикселях, радиус r - в метрах */
function showSearchAreaRadiusPlane(x, y, r)
{
    if (isNaN(x) || isNaN(y) || isNaN(r)) return false;
    
    var sAD = getElement('selectAreaDiv');
    if (sAD == null) return false;
    
    r = Math.abs(coordToPixRelX(r));
    var d = r * 2;  // диаметр
    
    sAD.style.left   = (x - r) + 'px';
    sAD.style.top    = (y - r) + 'px';
    sAD.style.width  = d + 'px';
    sAD.style.height = d + 'px';
    
    var sADC = getElement('sADCircleImg');
    if (sADC != null)
    {
        sADC.style.width  = d + 'px';
        sADC.style.height = d + 'px';
    }
    
    setAreaSearchCenterPoint();
    
    var coordsPlane = sAD.getAttribute("coordsPlane");
    if (coordsPlane != null && coordsPlane.length != 0)
    {
        if (!browserIE) coordsPlane = coordsPlane.split(',');
        coordsPlane[2] = pixToCoordRelX(r);
        if (sAD.getAttribute("coordsPlane") != null) { sAD.removeAttribute("coordsPlane"); }
        sAD.setAttribute("coordsPlane", coordsPlane);
    }
    
    if (sAD.style.visibility != 'visible') sAD.style.visibility = 'visible';
    return false;
}

function redrawSearchArea()
{
    var sAD = getElement('selectAreaDiv');
    if (sAD == null || sAD.style.visibility != 'visible') return false;
    
    var cP = sAD.getAttribute("coordsPlane");                            // centerX, centerY, Radius (plane)
    if (cP == null) { hideAreaDiv(sAD.id); return false; }
    if (!browserIE) cP = cP.split(',');
    
    var centerX = coordToPixY(cP[0]);
    var centerY = coordToPixX(cP[1]);
    var radius  = Math.abs(coordToPixRelX(cP[2]));
    
    showSearchAreaPix(centerX,centerY,radius);
}

function setAreaSearchCenterPoint()
{
    var sAD = getElement('selectAreaDiv');
    if (sAD == null) return false;
    
    var coords = sAD.getAttribute("coords");                            // centerX, centerY, Radius
    if (coords == null) { hideAreaDiv(sAD.id); return false; }
    if (!browserIE) coords = coords.split(',');
    
    var delta = 3;       // поправка для вывода информации (точки пути)
    
    var prePoint = getElement('areaSearchCenterPoint');
    if (prePoint != null)
    {
        var cP = sAD.getAttribute("coordsPlane");                            // centerX, centerY, Radius (plane)
        if (cP == null) { hideAreaDiv(sAD.id); return false; }
        if (!browserIE) cP = cP.split(',');
        var xG = coordToPixY(cP[0]) - delta;
        var yG = coordToPixX(cP[1]) - delta;
        objectMoveTo(prePoint, xG, yG);
        return false;
    }
    
    var point = document.createElement('div');
    point.id='areaSearchCenterPoint';
    point.className = 'pointDivStyle';
    getElement(MapDivId).appendChild(point);
    point.onmouseup = mapClickAreaSearch;
    
    var xG = coords[0] - delta;
    var yG = coords[1] - delta;
    objectMoveTo(point, xG, yG);
}

function deleteAreaSearchCenterPoint()
{
    var MapDiv = getElement(MapDivId);
    var point = getElement('areaSearchCenterPoint');
    if (MapDiv != null && point != null) { MapDiv.removeChild(point); point=null; }
}

function showLabel(clientX, clientY, text)
{
    var labelDiv = getElement('labelDiv');
    
    if (labelDiv == null)
    {
        labelDiv = document.createElement('div');
        labelDiv.id='labelDiv';
        labelDiv.className = (browserGecko)? 'lengthDivStyleGecko' : 'lengthDivStyleIE';
        document.body.appendChild(labelDiv);
        
        labelDiv.setAttribute('onclick', 'javascript: event.stopPropagation();');
        labelDiv.setAttribute('onmousemove', 'javascript: event.stopPropagation();');
        labelDiv.setAttribute('onmousedown', 'javascript: event.stopPropagation();');
    }
    
    var sXY = uiGetScrollXY();       // Скроллинг страницы
    var delta_x = clientX + 8 + sXY[0];
    var delta_y = clientY - 23 + sXY[1];
    objectMoveTo(labelDiv, delta_x, delta_y);
    labelDiv.innerHTML = '&nbsp;<strong>'+text+'</strong>&nbsp;';
}

function hideLabel()
{
    var labelDiv = getElement('labelDiv');    
    if (labelDiv == null) return;
    
    document.body.removeChild(labelDiv);
    labelDiv == null
}

function stopProp()
{
    var evt = browserGecko?e:event;

    if (!browserIE) { evt.stopPropagation(); }
    else { evt.cancelBubble = true; }
}

function resetMapActions(resetDefAction)
{
    dragmode = false;
    zoommode = false;
    bookmarkmode = false;
    
    eMap.onclick = mapClickDefault;
    eMap.onmousedown = mapMouseDownDefault;
    eMap.onmousemove = mapMouseMoveDefault;
    eMap.onload = eMapOnLoad;
    document.onmouseup = evtMouseUp;
    
    hideBmInputDiv();
    hideBmOutputDiv();
    
    disableMapPrintMode();
    disableMapAreaSearchMode();
    disablePutObjectMode();
    
    var ttD = getElement('toolTipDiv');
    if (ttD != null) // Если HTML-элемент для отображения тултипа создан - скрываем его
      { if (ttD.style.visibility == "visible") ttD.style.visibility = "hidden"; }
    
    MapCursor = defaultMapCursor;
    setMapCursor(MapCursor);
    
    delCookie(sessionId);    
    //HideWaitDiv(divWait);
    var elems = document.getElementsByTagName('input');
    var newStyle = "1px solid #c0c0c0";
    
    for (var i = 0; i < elems.length; i++)
    {
     if (elems[i].getAttribute('mapAction') == 'true')
     {
        elems[i].style.border = 'none';
        elems[i].style.borderStyle = 'none';
        var btnCommand = elems[i].getAttribute('mapCommand');
        if (btnCommand == null)
            continue;        
        if (btnCommand == 'cmDefault' && !resetDefAction) {
            elems[i].style.border = '1px inset';
            elems[i].style.borderStyle = 'inset'; 
        }
        else if (btnCommand == 'cpMapBookmark')
          { var index = elems[i].id.indexOf('btBookmarkCreate');
            if (index != -1) elems[i].style.border = newStyle; }
        else if (btnCommand == 'cmAreaSeek')
          { elems[i].style.border = newStyle; }
        else if (btnCommand == 'cmMapPrint')
          { elems[i].style.border = newStyle; }
        else if (btnCommand == 'cmSelectAreaCircle')
          { var index = elems[i].id.indexOf('btMVSelectCircle');
            if (index != -1) elems[i].style.border = 'none'; }
     }
    }
}

function setMapAction()
{
    switch (mapCommand)
       {
         case 'cmMapScaleUp':    // масштабирование
             return enableZoomMode();
         case 'cmMapScaleDown':  // масштабирование
             return enableZoomMode();
         case 'cmMapBookmark':   // закладки
             return enableMapBookmarkMode();
         case 'cmMapPrint':      // режим печати
             return enableMapPrintMode();
         case 'cmMapMove':       // перемещения рисунка карты
             return enableDragMode();
         case 'cmMapRuler':      // измерение расстояния
             return enableRulerMode();
         case 'cmFindRecord':      // измерение расстояния
             return enableFindRecordMode();
         case 'cmObjectInfo':      
             return enableObjectInfo();
         case 'cmMapPutObject':     //режим расстановки объектов
            return enablePutObjectMode();
         case 'cmDefault':       // режим по умолчанию
             return true;
       }
}

function tooltipClick(args)
{
   if (args == null || args.length == 0)
       return;
   var parm = args.split('))');
   alert(parm[1]);
   //parm[1] - значение связанного поля (RN) по семантике;
   //при связи по объекту - parm[0] - LinkSheet, parm[1] - LinkObject  
}

// Запросить данные о связанных объектах карты
// result - xml-список таблиц со значениями полей по отобранным объектам карты   
function queryDataList(result, context)
{
    if (result == null || result.length == 0)
        return;
    var param = result.split('alert'); // сообщение об ошибке
    if (param.length == 2)
    {
       alert(param[1]);
       return;
    }
    alert(param[0]);
    // имя клиентской функции-обработчика списка данных 
    //tooltipClick2(param[0]);   
}

// ===========================================
// Вывод панели со ссылкой на текущую страницу
// ===========================================
var idPnUrl;
function BuildUrl(result, context)
{
    parts = result.split(';');
    if (parts == null || parts.length < 3) 
        return;
    
    // определим ID панели со ссылкой
    var Panel = getElement(parts[1]);
    if (Panel == null)
        return;
    // отобразим или спрячем панель
    if (Panel.style.display == 'block')
        Panel.style.display = 'none'
    else Panel.style.display = 'block';
    Panel.style.width = eMap.style.width;
    idPnUrl = parts[1]; // запомним ID панели
    
    // определим ID элемента в который запишем ссылку
    var Link = getElement(parts[2]);
    if (Link == null)
        return;
    Link.value = parts[0];
    Link.style.width = parseInt(eMap.style.width) - 10;
}
function HidePnUrl()
{
    var Panel = getElement(idPnUrl);
    if (Panel == null)
        return;
    Panel.style.display = 'none'; 
}
// ===========================================




//~Illyashenko
function updateMarkup(slotElemId, markup, isEncoded)
{
    var slot = getElement(slotElemId);
    if (slot)
    {
        if (isEncoded)
            slot.innerHTML = decodeMarkup(markup);
        else
            slot.innerHTML = markup;
    }
}

function changeSizeFromDDL(ddlSizeClientId, imgMapClientId)
{
    var eDDL = document.getElementById(ddlSizeClientId);
    var size = eDDL.value; 
    if (menus && !isMenuCollapsed() && mapSizeControlClientId) {
        var objImgMap = document.getElementById(imgMapClientId);
        var ddlW=parseInt(size.substring(0, size.indexOf('x')));
        var ddlH=parseInt(size.substring(size.indexOf('x')+1, size.length));
        var h = objImgMap.height; 
        var w = objImgMap.width; 
        if (h==null && w==null) {
            var wpx = objImgMap.style.width; 
            var hpx = objImgMap.style.height; 
            w = parseInt(wpx.substring(0, wpx.indexOf('px'))); 
            h = parseInt(hpx.substring(0, wpx.indexOf('px')));
        }
        if (ddlW>w) 
            changeSize(w+'x'+ddlH, eDDL.selectedIndex);
        else
            changeSize(size, eDDL.selectedIndex);
    }
    else
        changeSize(size, eDDL.selectedIndex)
}

function formatStringFloatValue(source)
{
    if (source.indexOf(",") > -1)
    {
        var re = /,/g;
        return source.replace(re, ".");
    }
    else
        return source;
}

function findElementsRecursive(element, tagNames, callbackFunction)
{
    if (!element) return;
    var childNodes = element.childNodes;
    for(var i=0; i<childNodes.length; i++)
    {
        for (var j=0; j<tagNames.length; j++)
        {
            if (childNodes[i].tagName && childNodes[i].tagName.toUpperCase() == tagNames[j])
            {
                callbackFunction(childNodes[i], tagNames[j]);
            }
        }
        findElementsRecursive(childNodes[i], tagNames, callbackFunction);
    }
    return;
}

//~Edit Object Properties Window
function clearDataCallback(foundElement, tagName)
{
    var upTagName = foundElement.tagName.toUpperCase();
    setValid(foundElement);
    if (upTagName == 'INPUT')
    {
        var attr = foundElement.getAttribute('type');
        if (attr) 
        {   
            if (attr == 'text')
                foundElement.value = '';
            else if (attr == 'checkbox')
                foundElement.checked = false;
        }    
    }
    else if (upTagName == 'TEXTAREA')
    {
        foundElement.value = '';
    }    
    else if (upTagName == 'SELECT')  
    {
        foundElement.selectedIndex = 0;
    }
}

function clearTableData(containerId)
{
    var container = findFirstElementByTagName(getElement(containerId), 'TBODY'); 
    // Условие .. > 1, т.к. необходимо оставить строку с заголовком таблицы
    while(container.childNodes.length > 1)
    {
        container.removeChild(container.childNodes[container.childNodes.length-1]);
    }
}
/*
function clearAllData()
{
    var orgDiv = getElement(orgSectionId);
    var appDiv = getElement(appSectionId);
    var commonDiv = getElement(commonSectionId);
    var tagNames = new Array('INPUT', 'TEXTAREA', 'SELECT');
    findElementsRecursive(orgDiv, tagNames, clearDataCallback);
    findElementsRecursive(appDiv, tagNames, clearDataCallback);
    findElementsRecursive(commonDiv, tagNames, clearDataCallback);
    clearTableData(phoneContainerId);
    clearTableData(emailContainerId);
    getElement(hfPhoneId).value = '';
    getElement(hfEmailId).value = '';
    orgDiv.style.display='none';
    appDiv.style.display='none';
    getElement(hfEditObjectModeId).value = '';    
}
*/
function addItem(descrElementId, valueElementId, containerElementId, hfItemId, rePattern, errorMsg)
{
    var hfItem = getElement(hfItemId);
    if (!hfItem)
    {
        alert(ERROR_MSG);
        return;
    }
	var descr = getElement(descrElementId).value;    
	var itemValue = getElement(valueElementId).value;    
    
    if (!validateText(itemValue, rePattern))
    {
        alert(errorMsg);
        return;
    }
    
    hfItem.value += "0|#;#|";
    
    var srcElement = findFirstElementByTagName(getElement(containerElementId), 'TBODY');
    
	var tr = document.createElement('tr');
	tr.onclick = rowClick;
	var tdDescr = document.createElement('td');
	var tdValue = document.createElement('td');
	
	var spanDescr = document.createElement('span');	
	var attr = document.createAttribute('class');
	attr.nodeValue = 'dataDescription';
	spanDescr.setAttributeNode(attr);
	spanDescr.innerHTML = descr;
	hfItem.value += descr + "|#;#|";
		
	var spanValue = document.createElement('span');
	attr = document.createAttribute('class');
	attr.nodeValue = 'dataValue';
	spanValue.setAttributeNode(attr);	
	spanValue.innerHTML = itemValue;
	hfItem.value += itemValue;
	
	tdDescr.appendChild(spanDescr);
    tdValue.appendChild(spanValue);
	tr.appendChild(tdDescr);
	tr.appendChild(tdValue);
	srcElement.appendChild(tr);	
    hfItem.value += "|#.#|";
}	

function clearSelection(element)
{
    var childNodes = element.childNodes;
    var attr;
    for(var i=0; i<childNodes.length; i++)
    {
        if (childNodes[i].tagName && childNodes[i].tagName.toUpperCase() == 'TR')
        {
            //attr = childNodes[i].getAttribute('class');
            if (childNodes[i].className) 
            {   
                if (childNodes[i].className == 'dataSelection')
                    childNodes[i].className = '';
            }
        }
    }    
}

function rowClick(e, sender)
{
    if (!sender)
    {
        var e = (e) ? e : ((window.event) ? window.event : null);
        if (e)
            sender = (e.srcElement) ? e.srcElement : e.target;
    }
    if (sender)
    {
        while(sender.tagName.toUpperCase() != 'TR' || sender.parentNode == null)
            sender = sender.parentNode;
        clearSelection(sender.parentNode);
        var tblContainer = sender.parentNode;
        
	    var attr = document.createAttribute('class');
	    attr.nodeValue = 'dataSelection';
	    sender.setAttributeNode(attr); 
	 }
}

function deleteItem(containerElementId, hfItemId)
{
    var hfItem = getElement(hfItemId);
    if (!hfItem)
    {
        alert(ERROR_MSG);
        return;
    }
    var srcElement = findFirstElementByTagName(getElement(containerElementId), 'TBODY');
    
	var allChildNodes = srcElement.childNodes;
	var childNodes = new Array();
	for(var i=0; i<allChildNodes.length; i++){
	    if (allChildNodes[i].nodeType == 1)
	        childNodes[childNodes.length] = allChildNodes[i];
	}
	var items;
    for(var i=0; i<childNodes.length; i++)
    {
            if (childNodes[i].className) 
            {
                if (childNodes[i].className == 'dataSelection')
                {
                    items = hfItem.value.split('|#.#|');
                    hfItem.value = '';
                    for(var j=0; j<items.length; j++)
                    {
                        if (j!=i-1 && items[j].length>0)
                            hfItem.value += items[j] + '|#.#|';
                    }
                    srcElement.removeChild(childNodes[i]);
                }
            }
    } 	   
}

function findFirstElementByTagName(container, tagName)
{
    if (container)
    {
	    var childNodes = container.childNodes;
	    for(var i=0; i<childNodes.length; i++)
	    {
		    if (childNodes[i].tagName && (childNodes[i].tagName.toUpperCase() == tagName.toUpperCase())) 
			    return childNodes[i];
	    }
	    return container;
	}
	return null;
}

var invalidInput;

function validateAllData()
{
    var orgDiv = getElement(orgSectionId);
    var appDiv = getElement(appSectionId);
    var custDiv = getElement(custSectionId);
    var commonDiv = getElement(commonSectionId);   
    
    var tagNames = new Array('INPUT', 'TEXTAREA');
    invalidInput = false;
    findElementsRecursive(orgDiv, tagNames, validateDataCallback);
    findElementsRecursive(appDiv, tagNames, validateDataCallback);
    findElementsRecursive(custDiv, tagNames, validateDataCallback)
    findElementsRecursive(commonDiv, tagNames, validateDataCallback); 
    return !invalidInput;
}

function validateDataCallback(foundElement, tagName)
{
    setValid(foundElement);
    var valueType = foundElement.getAttribute('valuetype');
    var allowEmpty = foundElement.getAttribute('allowempty');
    var minValue = foundElement.getAttribute('minvalue');
    var maxValue = foundElement.getAttribute('maxvalue');
    if (validateText(foundElement.value, emptyREpattern))
    {
        if (allowEmpty == "0")
        {
            setInvalid(foundElement, "Данное поле не может быть пустым");
            return;
        }
        else
            return;
    }
    if (valueType == "int")
    {
        if (!validateText(foundElement.value, intREpattern))
        {
            setInvalid(foundElement, "Данное поле может содержать только целые числа");
            return;
        }
        else
        {
            var intVal = parseInt(foundElement.value);
            if (minValue)
            {
                var intMinValue = parseInt(minValue);
                if (intVal < intMinValue)
                {
                    setInvalid(foundElement, "Введенное значение должно быть не меньше " + intMinValue);
                    return;
                }
            }
            if (maxValue)
            {
                var intMaxValue = parseFloat(maxValue);
                if (intVal > intMaxValue)
                {
                    setInvalid(foundElement, "Введенное значение должно быть не больше " + intMaxValue);
                    return;
                }            
            }
        }
    }
    else if (valueType == "float")
    {
        if (!validateText(foundElement.value, floatREpattern))
        {
            setInvalid(foundElement, "Данное поле может содержать только вещественные числа");
            return;
        }
        else
        {
            var floatVal = parseFloat(foundElement.value);
            if (minValue)
            {
                var floatMinValue = parseFloat(minValue);
                if (floatVal < floatMinValue)
                {
                    setInvalid(foundElement, "Введенное значение должно быть не меньше " + floatMinValue);
                    return;
                }
            }
            if (maxValue)
            {
                var floatMaxValue = parseFloat(maxValue);
                if (floatVal > floatMaxValue)
                {
                    setInvalid(foundElement, "Введенное значение должно быть не больше " + floatMaxValue);
                    return;
                }            
            }        
        }    
    }
    else if (valueType == "url")
    {
        if (!validateText(foundElement.value, urlREpattern))
        {
            setInvalid(foundElement, "Введенное значение должно быть корректным URL адресом.<br />Например: http://www.mycompany.com");
            return;            
        }
    }
}

function setInvalid(element, msg)
{
    invalidInput = true;
    element.style.backgroundColor = "lemonchiffon";
    element.onmouseover = function(e) { showInputTooltip(e?e:window.event, msg);return false; }
    element.onmouseout = function() { hideInputTooltip(); } 
    element.onchange = function() { this.style.backgroundColor=""; hideInputTooltip(); this.onmouseover = null; element.onmouseout = null; }
}

function setValid(element)
{
    element.style.backgroundColor = "";
    element.onmouseover = null;
    element.onmouseout = null;    
}

function validateText(text, pattern)
{
    var re = new RegExp(pattern);
	var matches = re.exec(text);
	if (!(matches != null && text == matches[0]))
	{
	    return false;
    }    
    return true;
}

function onKeyUp(e, sender)
{    
    var e = (e) ? e : ((window.event) ? window.event : null);
    if (e.keyCode == 27)
    {
        var modal = $find(editObjectBehaviour);
        if (modal)
            modal.hide();
        if (pnUrl)
            hidePnUrl();
    }
}
//~end Edit Object Properties Window
//~tooltip
var ttPoint;
var isTTClosed = true;
function showInfoTooltip(options, offsetX, offsetY, width, height) {
    var tR = document.getElementById('tRealty');
    if (tR) tR.style.display = 'none';
	var picOffset = 18;
	var tdiv = document.getElementById('tdiv');
	tdiv.style.display = '';
	if (arguments.length == 0)
	    return;
	if (options.DataBase)
	    document.getElementById('dbRecords').style.display = '';
	else
	    document.getElementById('dbRecords').style.display = 'none';
	if (options.EditAddr)
	    document.getElementById('editAddr').style.display = '';
	else
	    document.getElementById('editAddr').style.display = 'none';	    
	if (options.Del)
	    document.getElementById('delObj').style.display = '';
	else
	    document.getElementById('delObj').style.display = 'none';	
	if (options.AddOrg)
	    document.getElementById('addOrg').style.display = '';
	else
	    document.getElementById('addOrg').style.display = 'none';
	if (options.AddRealty)
	    document.getElementById('addRealty').style.display = '';
	else
	    document.getElementById('addRealty').style.display = 'none';	
	if (options.AddCust)
	    document.getElementById('addCust').style.display = '';
	else
	    document.getElementById('addCust').style.display = 'none';	
	if (options.EditTt)
	    document.getElementById('editTt').style.display = '';
	else
	    document.getElementById('editTt').style.display = 'none';	    	    	        		        	    
	if (width)
		tdiv.style.width = width;
	if (height)
		tdiv.style.height = height;
	var htmlCell = document.getElementById('sv_ttHTML');
	var attr = htmlCell.getAttribute('htmlContent');
	if (!attr || attr != options.Text){
	   htmlCell.setAttribute('htmlContent', options.Text);
	   htmlCell.innerHTML = options.Text;
	}		
	var imgPointer = document.getElementById('sv_ttPointer');
	imgPointer.style.left = '4px';
	var szTooltip = objSize(tdiv);	
	tdiv.style.left = options.X - offsetX - picOffset + 'px';
	tdiv.style.top = options.Y - offsetY - szTooltip[1] + 'px';
	isTTClosed = false;
	if (!ttPoint)
	    ttPoint = new Array();
	ttPoint[0] = options.X;
	ttPoint[1] = options.Y;
}

function getInfoTooltipPoint() {
    return ttPoint;
}

function hideInfoTooltip() {
	document.getElementById('tdiv').style.display = 'none';
	var tR = document.getElementById('tRealty');
        if (tR) tR.style.display = 'none';
}

function closeInfoTooltip() {
    ttPoint = null;
    isTTClosed = true;
    hideInfoTooltip();
}

function isInfoTooltipClosed() {
    return isTTClosed;
}

function shiftOnInfoTooltip(cX, cY)
{
    var tdiv = document.getElementById('tdiv');
    if (ttPoint) {
          ttPoint[0] += parseInt(cX);
          ttPoint[1] += parseInt(cY);
    }
    objectShiftOn(tdiv, cX, cY);
}
//~end Illyashenko tooltip