var isEnableMoving = false;
var isEnableScaling = true;
var moveObject = null, move_sx, move_sy;
var setObject = null;
var widthMap,heightMap;
var widthObjectLoader;
var heightObjectLoader;
var scale;
var scaleObject = null;
var mainImage = null;
var backImage = null;
var isShowFullBlock = false;
var curLayerId; //слой, на котором выбран объект
var curGraphId; //ИД выбранного объекта
var curFullPagesContanerId;     //ИД контейнера последней нажатой кнопки вперед или назад на FullBlock
var url_server = location.protocol+'//'+location.host+'/';

var initMinimap = true;
var initCreate = true;
var createMode = false;

var initW, initH;

var wasDrag = false;

function initData()
{
    $(document.documentElement).keyup(function (event) {
        if(createMode && event.keyCode == 27){
            resetVector();
        }
    });

    initW = $(window).width()-10;
    initH = $(window).height()-10;

    if(!-[1,]){//хитрое определение IE
        //для IE надо увеличить высоту на ширину полосы прокрутки
        initH = initH+15;
    }

    $("#dynamic_map").width(initW);
    $("#dynamic_map").height(initH);
    $("#dynamic_map").css("left", 5);
    $("#dynamic_map").css("top", 5);
    $("#selected_div").width(initW);
    $("#selected_div").height(initH);
    $("#selected_div").css("left", 0);
    $("#selected_div").css("top", 0);
    $("#selected_div").hide();
    $("#create_div").width(initW);
    $("#create_div").height(initH);
    $("#create_div").css("left", 0);
    $("#create_div").css("top", 0);
    $("#create_div").hide();
    $("#toolbar_div").css("left", 10);
    $("#toolbar_div").css("top", 10);
    $("#workset_div").css("left", 215);
    $("#workset_div").css("top", 10);

    $("#copyright").css("left", initW-240);
    $("#copyright").css("top", initH-30);

    $("#search_div").css("left", initW-525);
    if(initW > 1000){
        $("#search_div").css("top", 10);
    }
    else{
        $("#search_div").css("top", 50);
    }


    $("#zoom_in_div").css("left", 15);
    $("#zoom_in_div").css("top", 50);
    $("#scale_slider").css("left", 23);
    $("#scale_slider").css("top", 90);
    $("#scale_slider").height(100);
    $("#zoom_out_div").css("left", 15);
    $("#zoom_out_div").css("top", 200);


    $("#search_result_block").dialog( {autoOpen: false, width: 350, height: 'auto', position: [initW - 390, 70]} );
    $("#full_block").dialog( {autoOpen: false, width: 600, height: 400, position: [initW/2 - 300, 100]} );
    $("#preview_block").dialog( {autoOpen: false, width: 400, height: 'auto'} );
    $("#msg").dialog( {autoOpen: false, draggable: false, resizable: false, width: 'auto', height: 'auto'} );
    $("#minimap_block").dialog( {resizable: false, autoOpen: false, width: widthMiniMap+30, height: heightMiniMap+40, position: [initW - (widthMiniMap+60), initH - (heightMiniMap+70)]} );
    $("#minimap_block").dialog({
       close: function(event, ui) {
            if($('#minimap_button').attr('checked')){
                $('#minimap_button').removeAttr('checked')
                $('#minimap_button').button( "refresh" );
            }
       }
    });
    $('#minimap_button').button( "refresh" );

    $("#layers_block").dialog( {autoOpen: false, width: widthLegend+30, height: heightLegend+40, position: [50, 50]} );
    $("#layers_block").dialog({
       close: function(event, ui) {
            if($('#layers_button').attr('checked')){
                $('#layers_button').removeAttr('checked')
                $('#layers_button').button( "refresh" );
            }
       }
    });
    $('#layers_button').button( "refresh" );

    $("#help_block").dialog( {autoOpen: false, width: initW - 200, height: initH - 200} );
    $("#help_block").dialog({
       close: function(event, ui) {
            if($('#help_button').attr('checked')){
                $('#help_button').removeAttr('checked')
                $('#help_button').button( "refresh" );
            }
       }
    });
    $('#help_button').button( "refresh" );


    $('#dynamic_map').click(function(e) {
         if(createMode == true){
             var x = e.pageX - this.offsetLeft;
             var y = e.pageY - this.offsetTop;
             addPoint(x, y);
         }
         else{
             var x = e.pageX - this.offsetLeft;
             var y = e.pageY - this.offsetTop;
             reloadGraphic(x, y);
         }
     });

   $('#dynamic_map').dblclick(function(e) {
         if(createMode == true){
             finish();
         }
     });


   $('#dynamic_map').mousemove(function(e) {
         if(createMode == true && wasDrag == false){
             var x = e.pageX - this.offsetLeft;
             var y = e.pageY - this.offsetTop;
             if(this.offsetLeft > 5)
                alert(e.pageX+" "+this.offsetLeft);
             movePoint(x, y);
         }
     });

    $('#create_point').click(function() {
        setContourType(0);    
    });
    $('#create_line').click(function() {
        setContourType(1);
    });
    $('#create_polygon').click(function() {
        setContourType(2);    
    });
    $('#contour_type').buttonset();


    $('#create_continue').button();
    $('#create_continue').click(function() {
        $.getJSON(url_server +"ActionServlet?action=wl_tiles&mode=create_form",
          function(data){
              var createForm = document.getElementById("create_form");
              if(!createForm)
                  return;

              $("#form_table").remove();

              var tbl = document.createElement('table');
              tbl.id = 'form_table';
              var table = document.createElement('tbody');
              tbl.appendChild(table);

              for(var i = 0; i < data.fields.length; i++)
              {
                  var tr = createEditRow(data.fields[i])
                  table.appendChild(tr);
              }
              $("#create_form").append(tbl);

              $('#step1').hide();
              $('#step3').hide();
              $('#step2').show();
          });
    });


    $('#create_finish').button();
    $('#create_finish').click(function() {
        var req_url = url_server +"ActionServlet?action=wl_tiles&mode=create";
        $(':input[id^=field_]').each(function(i,e){
            req_url += '&' + e.id + '=' + encodeURIComponent(e.value);
        });

        req_url += pointsToString() + '&w='+w+'&h='+h+'&cx='+getMapX()+'&cy='+getMapY()+'&scale='+scales[currentScale];

        $.getJSON(req_url,
          function(data){
              var kod = document.getElementById("create_kod");
              var mess = document.getElementById("create_mess");
              if(!kod || !mess)
                  return;
              kod.style.color = field_name_color;
              if(data.kod){
                  mess.innerHTML = okCreateMessage;
                  kod.innerHTML = data.kod;
                  $('#step1').hide();
                  $('#step2').hide();
                  $('#step3').show();
              }
              else{
                  mess.innerHTML = errorCreateMessage;
                  kod.innerHTML = data.error;
                  $('#step1').hide();
                  $('#step2').hide();
                  $('#step3').show();
              }
          });
    });

    $('#create_close').button();
    $('#create_close').click(function() {
        createMode = false;
        resetVector();
        $('#create_div').hide();
        $("#help_create_block").dialog("close");
        $('#create_button').attr('checked', false)
        $('#create_button').button( "refresh" );

    });

    $('#create_cancel').button();
    $('#create_cancel').click(function() {
        $('#dialog-confirm').dialog("open");
    });

    $("#scale_slider").slider({ orientation: 'vertical' });
    $("#scale_slider").slider( "option", "min", minScale );
    $("#scale_slider").slider( "option", "max", maxScale );
    $("#scale_slider").slider( "option", "step", 1 );
    $("#scale_slider").slider( "option", "value", maxScale-currentScale );

    $("#scale_slider").bind( "slide", function(event, ui) {
        if(currentScale != maxScale-ui.value)
        {
            currentScale = maxScale-ui.value;
            setCurrentScale(false);
        }
    });

    $("#msg").ajaxError(function(e, xhr, settings, exception){
        jQuery('#search_result_block').hideLoading();
        $("#search_result_block").dialog( "option", "draggable", true );
        $("#search_result_block").dialog( "option", "resizable", true );
        jQuery('#full_block').hideLoading();
        $("#full_block").dialog( "option", "draggable", true );
        $("#full_block").dialog( "option", "resizable", true );
        jQuery('#preview_block').hideLoading();
        $("#preview_block").dialog( "option", "draggable", true );
        $("#preview_block").dialog( "option", "resizable", true );
        $(this).dialog("open");
    });

var switchCreateToMeasure = false;

    $( "#dialog-confirm" ).dialog({
        autoOpen: false,
        resizable: false,
        height:200,
        modal: true,
        buttons: {
            "Нет": function() {
                $(this).dialog( "close" );
                $('#create_button').attr('checked', true)
                $('#create_button').button( "refresh" );
            },
            "Да": function() {
                createMode = false;
                resetVector();
                $(this).dialog( "close" );
                $('#create_div').hide();
                $("#help_create_block").dialog("close");
                $('#create_button').attr('checked', false)
                $('#create_button').button( "refresh" );
                if(switchCreateToMeasure){
                    setMeasureMode(true);
                    switchCreateToMeasure = false;
                }
            }
        },
        closeOnEscape: false
    });
    $( 'a.ui-dialog-titlebar-close', $('#ui-dialog-title-dialog-confirm').parent() ).remove();

    $("#help_create_block").dialog( {
        autoOpen: false,
        width: 480,
        height: 'auto',
        position: [initW - 520, 70],
        closeOnEscape: false
        });
    $( 'a.ui-dialog-titlebar-close', $('#ui-dialog-title-help_create_block').parent() ).remove();

    $("#workset_select").change(function() {
        cur_ws = $("#workset_select").val();
        $("#layers_block").load(legend_pages[cur_ws]);
        drawMap(lastPaintedDiv);
    });

      $('#measure_button').button({text: false, icons: {primary: 'ui-icon-arrowthick-2-e-w'}});
        $('#measure_button').click(function() {
            if($('#create_button').attr('checked')){
                switchCreateToMeasure = true;
                $('#dialog-confirm').dialog("open");
                return;
            }
            if(!$('#measure_button').attr('checked')){
                resetMeasureMode(false);
            }
            else{
                setMeasureMode(false);
            }
          });


      $('#create_button').button({text: false, icons: {primary: 'ui-icon-pencil'}});
      $('#layers_button').button({text: false, icons: {primary: 'ui-icon-script'}});
      $('#help_button').button({text: false, icons: {primary: 'ui-icon-help'}});


      $('#zoom_in_button').button({text: false, icons: {primary: 'ui-icon-zoomin'}});
      $('#zoom_in_button').click(function() {
            changeScale(1);
      });
      $('#zoom_out_button').button({text: false, icons: {primary: 'ui-icon-zoomout'}});
      $('#zoom_out_button').click(function() {
            changeScale(-1);
      });

      $('#selected_button').button({text: false, icons: {primary: 'ui-icon-home'}});
      $('#selected_button').click(function() {
        if(!initSelect){
            if(showSelected){
                $('#selected_div').hide();
                showSelected = false;
            }
            else{
                $('#selected_div').show();
                showSelected = true;
            }
        }
      });
      $('#minimap_button').button({text: false, icons: {primary: 'ui-icon-image'}});
      $('#minimap_button').click(function() {
            if($('#minimap_button').attr('checked')){
                if(initMinimap){
                    var url = url_server + 'ActionServlet?action=wl_mini_map_component_xml&command=get_mini_map&width='+widthMiniMap+'&height='+heightMiniMap;
                    if(mini_map_image)
                        url += '&mini_map_image='+mini_map_image;
                    $.getJSON(url, function(data){
                        $("#minimap_block").append(addMiniMap(data));
                        $('#minimap_block').click(function(e) {
				            var x = e.pageX - $("#minimap_block").offset().left;
				            var y = e.pageY - $("#minimap_block").offset().top;
                            updateMapByMinimap(x, y);
                        });

                        createMinimapRect();
                        $("#minimap_block").dialog( "option", "height", 'auto' );
                        $("#minimap_block").dialog("open");
                    });
                    initMinimap = false;
                }
                else{
                    setMinimapPosition();
                    $("#minimap_block").dialog("open");
                }
            }
            else
                $("#minimap_block").dialog("close");
        });


      $('#layers_button').click(function() {
            if($('#layers_button').attr('checked')){
                $("#layers_block").load(legend_pages[cur_ws]);
                $("#layers_block").dialog("open");
            }
            else
                $("#layers_block").dialog("close");
        });

      $('#help_button').click(function() {
            if($('#help_button').attr('checked')){
                $("#help_block").load(helpPage);
                $("#help_block").dialog("open");
            }
            else
                $("#help_block").dialog("close");
        });
        

      $('#create_button').click(function() {
            if($('#measure_button').attr('checked')){
                resetMeasureMode(true);
            }
            if(!$('#create_button').attr('checked')){
                $('#dialog-confirm').dialog("open");
            }
            else{
                if(initCreate){
                    initVector("create_div", initW, initH, 50, scales[currentScale], 2);
                    initCreate = false;
                }
                setVectorScale(scales[currentScale]);
                createMode = true;
                $('#create_div').show();
                $('#step1').show();
                $('#step2').hide();
                $('#step3').hide();
                $("#help_create_block").dialog("open");
            }
        });
      //$('#loader_button').button({text: false, icons: {primary: 'ui-icon-folder-open'}});
      $('#search_button').button({text: false, icons: {primary: 'ui-icon-search'}});
      $('#search_button').click(function() {
            startSearch();
        });
      $(':radio').click(function() {
            if(!$('#create_button').attr('checked')){
                if(createMode){
                    $('#dialog-confirm').dialog("open");
                }
            }
      });

    $('#login_error').hide();
    $("#login").dialog( {modal: true, autoOpen: false, width: 400, height: 'auto', closeOnEscape: false} );
    $( 'a.ui-dialog-titlebar-close', $('#ui-dialog-title-login').parent() ).remove();



      $('#guest_button').button();
      $('#guest_button').click(function() {
            login(guestLogin, guestPass, guestMM);

      });
      $('#admin_button').button();
      $('#admin_button').click(function() {
            $("#wellcome").hide();
            $("#login_div").show();
            $("#j_gee_username").focus();
      });
      $('#admin_login').button();
      $('#admin_login').click(function() {
            adminLogin();
      });

    $.getJSON(url_server +"ActionServlet?action=wl_tiles&mode=login",
      function(data){
        if(data.login){
            loginForm(data.login.mms);
        }
        else{
            initApp();
        }
      });

  }

function setMeasureMode(updateButton){
      if(initCreate){
          initVector("create_div", initW, initH, 50, scales[currentScale], 2);
          initCreate = false;
      }
      else{
          setContourType(2);
          setVectorScale(scales[currentScale]);
      }
      createMode = true;
      $('#create_div').show();
      if(updateButton){
          $('#measure_button').attr('checked', true)
          $('#measure_button').button( "refresh" );
      }
}

function resetMeasureMode(updateButton){
    createMode = false;
    resetVector();
    $('#create_div').hide();
    if(updateButton){
        $('#measure_button').attr('checked', false)
        $('#measure_button').button( "refresh" );
    }
}


function loginForm(mms)
{
    commonLoginForm(mms);

    $("#login_div").hide();
    $("#wellcome").show();
    $("#login").dialog("open");
    $("#j_gee_username").focus();
}

function initApp(){

    if(undoredo){
        unoredo.reset();
    }

    $.getJSON(url_server +"ActionServlet?action=wl_tiles&mode=ws",
      function(data){
          var worksetSelect = document.getElementById("workset_select");
          if(!worksetSelect)
              return;

          if(data.cur_ws){
            cur_ws = parseInt(data.cur_ws);
          }

          for(var i = 0; i < data.ws.length; i++)
          {
              var option = document.createElement('option');
              option.setAttribute("value", i);
              option.defaultSelected = i == cur_ws;
              option.selected = i == cur_ws;
              option.appendChild(document.createTextNode(data.ws[i].name))
              worksetSelect.appendChild(option);
          }


      });

      $.getJSON(url_server +"ActionServlet?action=wl_search_component_xml&command=get_search_aspects",
        function(data){
            initSearchAspects(data);
        });

      $.getJSON(url_server +"ActionServlet?action=wl_tiles&mode=initpos",
        function(data){
            if(data.x){
                initDynamicMap(data.x, data.y);
            }
            else if(data.layerName){
                initDynamicMap(-100000, -100000);
                setGraphic(0, 0, data.graphId, 0, data.layerName);
            }
            else{
                initDynamicMap(initCenterX, initCenterY);
            }
        });
}

function createEditRow(field)
{
    var trf = document.createElement('tr');
    var td1 = document.createElement('td');
    td1.align = 'left';
    td1.innerHTML = field.fieldName;
    td1.style.color = field_name_color;
    var td2 = document.createElement('td');
    td2.align = 'left';
    var input = document.createElement('input');
    input.size = 40;
    input.id = 'field_'+field.fieldId;
    td2.appendChild(input);
    trf.appendChild(td1);
    trf.appendChild(td2);
    return trf;
}


function addPreview(obj)
{
    var full_cont = document.createElement('table');
    full_cont.width = parseInt($( "#preview_block" ).width()) - 10;
    full_cont.id = "preview_content";
    var full_tbody = document.createElement('tbody');
    full_cont.appendChild(full_tbody);

    var grey = true;
    for(var j = 0; j < obj.root.length; j++)
    {
        var firstNode = obj.root[j].full_nodes[0];
        full_cont.style.marginTop = 5;
        full_cont.style.marginLeft = 5;
        if(firstNode.factName){
            for(var i=0; i<firstNode.facts.length; i++){
                var tr = createFactPreview(firstNode.facts[i], firstNode.factName, firstNode.factDscrId)
                if(grey)
                    tr.style.backgroundColor = '#efefef';
                grey = !grey;
                full_tbody.appendChild(tr);
            }
        }
    }
    return full_cont;
}

function createFactPreview(fact, factName, factDscrId)
{
    var tr = document.createElement('tr');
    tr.className = 'previewRow';
    var th = document.createElement('th');
    th.colSpan = '1';
    th.align = 'left';
    th.style.color = field_name_color; 
    th.innerHTML = getAlias(factName);
    tr.appendChild(th);

    var th_a = document.createElement('th');
    if(fact.f_title.substr(0, 2) == '<a' || fact.f_title.substr(0, 2) == '<A'){
    //гиперссылка в описании - оставляем ее
        th_a.innerHTML = fact.f_title;
    }
    else{
        th_a.colSpan = '2';
        th_a.align = 'left';
        var a = document.createElement('a');
        a.style.cursor = 'pointer';
        a.onclick = new Function('viewFullObject(' + factDscrId + ', '+fact.f_value+')');
        a.innerHTML = fact.f_title;
        th_a.appendChild(a);
    }
    tr.appendChild(th_a);
    th = document.createElement('th');
    th.colSpan = '1';
    th.align = 'left';
    a = document.createElement('a');
    a.onclick = new Function('setGraphic(' + factDscrId + ', 0, 0, '+fact.f_value+')');
    a.innerHTML = 'Показать на карте';
    a.className = 'gr_button';
    th.appendChild(a);
    tr.appendChild(th);
    return tr;
}

//--------------------------Mouse Wheel Block--------------------

var waiterID;
var scaleKoef;   //коэфициент масштабирования
var divWidth;    //первоначальная ширина картинки., она же ширина div
var divHeight
var imgWidth;    //текущая ширина картинки
var pic;
var divImg;

function startWaiter()
{
    waiterID = setTimeout("timerHandle()",300);
}

function stopWaiter()
{
    if(waiterID)
        clearTimeout(waiterID);
}

function timerHandle()
{
    scaleKoef = divWidth / imgWidth;
    var realScale = parseInt($("#scale_map").value);
    realScale *= scaleKoef;
    $("#scale_map").value = Math.round(realScale);
    setTimeout("scaleImage(pic)",100);

}

// Event handler for mouse wheel event.
function handle(delta,event)
    {
        stopWaiter();

        if(!isEnableScaling)
            return;

        if(event.srcElement)
            pic = event.srcElement;
        else
           pic = event.target;

        for(var elem = pic.parentNode; elem.tagName != "DIV" && elem.tagName != "div"; elem = elem.parentNode);
        divImg = elem;

        divWidth = parseInt(divImg.style.width);
        var imgWidthOld;
        var x = parseInt(divImg.style.left);

        divHeight = parseInt(divImg.style.height);
        var imgHeight;
        var imgHeightOld;
        var y = parseInt(divImg.style.top);

        imgWidthOld = parseInt(pic.width);
        imgHeightOld = parseInt(pic.height);

        var imgWidthAdd = (imgWidthOld*1.2)-imgWidthOld;
        var imgHeightAdd = (((imgWidthOld + imgWidthAdd)*imgHeightOld)/imgWidthOld) - imgHeightOld

        var xOffset;
        var yOffset;

        if(delta > 0)
    	{
            pic.width = imgWidthOld + imgWidthAdd;
            pic.height = imgHeightOld + parseInt(imgHeightAdd);

            imgWidth = parseInt(pic.width);
            imgHeight = parseInt(pic.height);

            xOffset = (imgWidth - imgWidthOld)/2;
            yOffset = (imgHeight - imgHeightOld)/2;

            divImg.style.left = x - xOffset;
            divImg.style.top = y - yOffset;
        }
        else if(delta < 0)
        {
            pic.width = imgWidthOld - imgWidthAdd;
            pic.height = imgHeightOld - parseInt(imgHeightAdd);

            imgWidth = parseInt(pic.width);
            imgHeight = parseInt(pic.height);

            xOffset = (imgWidthOld - imgWidth)/2;
            yOffset = (imgHeightOld - imgHeight)/2;

            divImg.style.left = x + xOffset;
            divImg.style.top = y + yOffset;
        }

        startWaiter();
    }

function WheelEvent_Zoom(event)
{
    var delta = 0;
    if (!event) /* For IE. */
        event = window.event;
    if (event.wheelDelta)
    {
        /* IE/Opera. */
        delta = event.wheelDelta/120;
        /** In Opera 9, delta differs in sign as compared to IE.
        */
        /*if (window.opera)
        delta = -delta;*/
    }
    else if (event.detail)
    {
        delta = -event.detail/3;
    }

    if (delta)
    {
	changeScale(delta);
    }

    if (event.preventDefault)
        event.preventDefault();
	event.returnValue = false;
}

function moveGraphic(obj, dx, dy)
{
    if((parseInt(dx) == 0) && (parseInt(dy) == 0))
        return;

    centerX -= dx*sc[currentScale];
    centerY -= dy*sc[currentScale];

    if(lastPaintedDiv == "#divImg")
        drawMap("#divImg2");
    else
        drawMap("#divImg");

    var temp;
    temp = $("#divImg2").css("zIndex");
    $("#divImg2").css("zIndex", $("#divImg").css("zIndex"));
    $("#divImg").css("zIndex", temp);

    obj.style.top = "0px";
    obj.style.left = "0px";
    translateGO(dx, dy, scales[currentScale]);
    translateObjects(dx, dy);
    if(lastPaintedDiv == "#divImg"){
       $("#divImg2").css('top', 0);
       $("#divImg2").css('left', 0);
    }
    else{
       $("#divImg").css('top', 0);
       $("#divImg").css('left', 0);
    }

    setMinimapPosition();
}

var lastPaintedDiv;

function drawMap(divCont){
    lastPaintedDiv = divCont;
    currentImagesHash = new Hashtable();

	var minX = parseInt(centerX/sc[currentScale] - w/2);
	var minY = parseInt(centerY/sc[currentScale] - h/2);
	var maxX = parseInt(centerX/sc[currentScale] + w/2);
	var maxY = parseInt(centerY/sc[currentScale] + h/2);

      var n = parseInt(minX/256);
      var dx = (minX-n*256);
      var m = parseInt(minY/256);
      var dy = (minY-m*256);

      var minN = parseInt(minX/256);
      var minM = parseInt(minY/256);
      var maxN = parseInt(maxX/256);
      var maxM = parseInt(maxY/256);

      var countY = 0;
      for(var i=minM; i<maxM+1; i++){
          var countX = 0;
	    for(var j=minN; j<maxN+1; j++){
		 getImageByCoord(divCont, j, i, countX, countY, dx, dy);
             countX++;
	    }
          countY++;
      }
	if(lastImagesHash){
		var values = lastImagesHash.values();
            for(var i in values){
                $("#tempDiv").append(values[i]);
            }
	}
	lastImagesHash = currentImagesHash;
}

var lastImagesHash;
var currentImagesHash;

var add_sel = true;
var sel_img;
var sel_scale;
var sel_w;
var sel_h;
var sel_x = 8875;
var sel_y = 23889;

function getImageByCoord(divCont, x, y, countX, countY, dx, dy){
    if(x < 0 || y < 0 || x > xTMax[currentScale] || y > yTMax[currentScale])
	  return;
    var id = "ws"+cur_ws+"x"+x+"y"+y+"z"+currentScale;
    var img = imagesHash.get(id);
    if(!img){
      var img = document.createElement('img');
	  img.id = id;
	  img.name = id;
	  var sb = tiles_path+"/"+ws[cur_ws]+"/z"+scales[currentScale]+"/";
        var xDir = parseInt(x/1024);
	  var yDir = parseInt(y/1024);
	  sb+= xDir;
	  sb+= "/x";
	  sb+= x;
	  sb+= '/';
	  sb+= yDir;
	  sb+= "/y";
	  sb+= y;
	  sb+= ".jpg";
	  imagesHash.put(id, img);
      img.style.position = 'absolute';
      img.style.left = ""+(countX*256-dx)+"px";
      img.style.top = ""+(countY*256-dy)+"px";
      $(divCont).append(img);
      $("img[name='"+id+"']").load(function(){
          $(this).show();
      });
      $("img[name='"+id+"']").hide();
      img.src = sb;
    }
    else{
        img.style.position = 'absolute';
        img.style.left = ""+(countX*256-dx)+"px";
        img.style.top = ""+(countY*256-dy)+"px";
        $(divCont).append(img);
    }

    currentImagesHash.put(id, img);
    if(lastImagesHash)
 	  lastImagesHash.remove(id);

}


function initDynamicMap(initX, initY)
{
    w = parseInt($("#dynamic_map").width());
    h = parseInt($("#dynamic_map").height());

    numX = parseInt(w/256+1);
    numY = parseInt(h/256+1);

    centerX = getImageX(initY);
    centerY = getImageY(initX);

    var mapContainer = $("#dr");

    var divImg = document.createElement('div');
    divImg.style.position = "absolute";
    divImg.style.left = "0px";
    divImg.style.top = "0px";
    divImg.style.width = w;
    divImg.style.height = h;
    divImg.style.zIndex = "5";
    divImg.style.backgroundColor = "#ffffff";
    divImg.id = "divImg";
    mapContainer.append(divImg);

    /*if (window.addEventListener)
        divImg.addEventListener('DOMMouseScroll', WheelEvent_Zoom, false);
    divImg.onmousewheel = WheelEvent_Zoom;*/

    var divImg2 = document.createElement('div');
    divImg2.style.position = "absolute";
    divImg2.style.left = "0px";
    divImg2.style.top = "0px";
    divImg2.style.width = w;
    divImg2.style.height = h;
    divImg2.style.zIndex = "4";
    divImg2.style.backgroundColor = "#ffffff";
    divImg2.id = "divImg2";
    mapContainer.append(divImg2);

    if (window.addEventListener)
        document.getElementById("dr").addEventListener('DOMMouseScroll', WheelEvent_Zoom, false);
    document.getElementById("dr").onmousewheel = WheelEvent_Zoom;

    var tempDiv = document.createElement('div');
    tempDiv.style.position = 'absolute';
    tempDiv.style.left = '0px';
    tempDiv.style.top = '0px';
    tempDiv.style.width = w;
    tempDiv.style.height = h;
    tempDiv.style.zIndex = '3';
    tempDiv.style.backgroundColor = '#ffffff';
    tempDiv.id = "tempDiv";
    mapContainer.append(tempDiv);

    $("#tempDiv").hide();

    drawMap("#divImg");

    $("#dr").draggable({
        start: function(event, ui)
        {
            wasDrag = true;
            $("#dr").css( "cursor", "move" );
        },
        stop: function(event, ui)
        {
            $("#dr").css( "cursor", "default" );
            moveGraphic(event.target, ui.position.left, ui.position.top);
            wasDrag = false;
        }
    });
}

// изменение масштаба колесом мыши
function changeScale(delta){
        currentScale -= delta;
	  if(currentScale < minScale)
		currentScale = minScale;
	  if(currentScale > maxScale)
		currentScale = maxScale;
        setCurrentScale(true);
}

function setCurrentScale(marker){
    if(marker){
        $("#scale_slider").slider( "option", "value", maxScale-currentScale);
    }
    var k = sel_scale/scales[currentScale];
    var w = sel_w*k;
    var h = sel_h*k;
    drawMap(lastPaintedDiv);
    setMinimapPosition();
    if(!initSelect){
        scaleGO(scales[currentScale]);
    }
    scaleObjects(scales[currentScale], initW, initH);
}


var imagesHash = new Hashtable();
var w;
var h;
var numX;
var numY;
var centerX;
var centerY;
var deltaX;
var deltaY;

function getMapX(){
    return boundMaxX - centerY/(7200.0/(scales[minScale]*2.54));
}
function getMapY(){
    return boundMinY + centerX/(7200.0/(scales[minScale]*2.54));
}

function getImageX(y){
    return (y-boundMinY)*(7200.0/(scales[minScale]*2.54));
}

function getImageY(x){
    return (boundMaxX-x)*(7200.0/(scales[minScale]*2.54));
}

function getPointX(y){
    return initW/2 + (getImageX(y) - centerX);
}

function getPointY(x){
    return initH/2 + (getImageY(x) - centerY);
}

function initImg(img, x, y){
    var sb = "tiles/z500/";
    var xDir = parseInt(x/1024);
    var yDir = parseInt(y/1024);
    sb+= xDir;
    sb+= "/x";
    sb+= x;
    sb+= '/';
    sb+= yDir;
    sb+= "/y";
    sb+= y;
    sb+= ".jpg";
    img.setAttribute("src", sb);
    var id = "x"+x+"y"+y;
    img.id = id;
    imagesHash.put(id, img);
}

var initSelect = true;
var showSelected = false;

function setGraphic(fd, layerId, graphId, factId, layerName)
{
    if(!factId)
        factId = 0;
    if(!layerName)
        layerName = "undefined";
    var url = url_server + 'ActionServlet?action=wl_tiles&mode=find&factId='+factId+'&fd='+fd+'&layerId='+layerId+'&graphId='+graphId+'&layerName='+layerName +'&w='+w+'&h='+h + '&scale='+scales[currentScale]+'&tiles=true';
    $.getJSON(url, function(data){
        centerX = getImageX(parseInt(data.y));
        centerY = getImageY(parseInt(data.x));
        showGraphicSelection(data.go, data.area);
        setScale(data.scale);
    });

}

function showGraphicSelection(go, area){
        if(initSelect){
            initGO("selected_div", initW, initH);
            initSelect = false;
            var selectedDiv = document.getElementById("selected_div")
            /*if (window.addEventListener)
                selectedDiv.addEventListener('DOMMouseScroll', WheelEvent_Zoom, false);
            selectedDiv.onmousewheel = WheelEvent_Zoom;*/
        }
        createGO(go, scales[currentScale], area);
        if(!showSelected){
            $('#selected_div').show();
            showSelected = true;
        }
        $('#selected_button').attr('checked', true);
        $('#selected_button').button( "refresh" );
}

function setScale(newScale)
{
    for(var i in scales){
        if(scales[i] > newScale){
            if(i != 0){
                var delta = scales[i-1] + (scales[i] - scales[i-1])/2;
                if(newScale > delta){
                    currentScale = i;
                }
                else{
                    currentScale = i-1;
                }
            }
            else{
                currentScale = 0;
            }
            setCurrentScale(true);
            return;
        }
    }
    currentScale = maxScale;
    setCurrentScale(true);
}



function reloadGraphic(x, y)
{
    url = url_server + 'ActionServlet?action=wl_tiles&mode=sel&w='+w+'&h='+h+'&x='+x+'&y='+y+'&cx='+getMapX()+'&cy='+getMapY()+'&scale='+scales[currentScale]+'&ws='+cur_ws;

    $("#preview_block").dialog("open");
    $("#preview_block").dialog( "option", "draggable", false );
    $("#preview_block").dialog( "option", "resizable", false );
    jQuery('#preview_block').showLoading();

    $.getJSON(url, function(data){
        jQuery('#preview_block').hideLoading();
        $("#preview_block").dialog( "option", "draggable", true );
        $("#preview_block").dialog( "option", "resizable", true );
        if(data.empty){
                $("#preview_content").detach();
                $("#preview_block").dialog( "option", "height", 'auto' );
        }
        else{
                $("#preview_content").detach();
                $("#preview_block").append(addPreview(data));
                updateButtons();

                var h = parseInt($( "#preview_content" ).height()) + 70;
                if(h > initH - 100){
                    h = initH - 100;
                }
                $("#preview_block").dialog({ height: h });
        }
    });
}

function addMiniMap(obj)
{
    var miniMapImg = new Image();
    miniMapImg.id = 'miniMap_img';
    miniMapImg.src = obj.html;

    var tbl = document.createElement('table');
    var table = document.createElement('tbody');
    tbl.appendChild(table);
    tbl.width = '100%';
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.valign = "center";
    td.align = "center";
    table.appendChild(tr);
    tr.appendChild(td);
    td.appendChild(miniMapImg);
    return tbl;
}

function createMinimapRect() {
    if($('#minimap_button').attr('checked')){
            var rectDiv = document.createElement('div');
            rectDiv.style.position = "absolute";
            rectDiv.style.backgroundColor = "#0000ff";
            rectDiv.id = "rectDiv";
            $("#minimap_block").append(rectDiv);
            setMinimapPosition();
            $("#rectDiv").fadeTo(0, 0.5);
    }
}

function setMinimapPosition(){
    var scaleKoef = parseInt(minimapScale/scales[currentScale]);
    var mw = parseInt(w/scaleKoef);
    var mh = parseInt(h/scaleKoef);
    var mx = parseInt(centerX*scales[0]/minimapScale-mw/2+17+minimapDx);
    var my = parseInt(centerY*scales[0]/minimapScale-mh/2+38+minimapDy);
    $("#rectDiv").width(mw);
    $("#rectDiv").height(mh);
    $("#rectDiv").css("left", mx);
    $("#rectDiv").css("top", my);
}

function updateMapByMinimap(x, y)
{
    var dx = $("#minimap_block").position().left;
    var dy = $("#minimap_block").position().top;

    var newCenterX = (x+dx-17-minimapDx)*(minimapScale/scales[0]);
    var newCenterY = (y+dy-38-minimapDy)*(minimapScale/scales[0]);

    var mapDx = (centerX-newCenterX)/sc[currentScale];
    var mapDy = (centerY-newCenterY)/sc[currentScale];
    translateGO(mapDx, mapDy, scales[currentScale]);
    centerX = newCenterX;
    centerY = newCenterY;

    drawMap(lastPaintedDiv);
    setMinimapPosition();
}

function pointsToString(){
    var str = '&cnt_type='+contourType+'&points=';
    for(var i=0; i<pointsCount; i++){
        var x = parseInt(polygon[i].attr("cx"));
        var y = parseInt(polygon[i].attr("cy"));
        str+= '_'+x+'_'+y;
    }
    return str;
}

