var timeStart = new Date();

var isDown=false;
var mapLoaded=false;
var posX=0; 
var posY=0;
var cur_tool = "zoomin";
var map_link_pre = 'http://www.topplan.ru';
var points_cnt = 0;
var points = new Array();
var userpnts = new Array();


  function show_user_pnt(pnt_id){
      $('#usr_pnt_edit').hide();
      $('#usr_pnt_view').show();
      $('#v_point_name').html(userpnts[pnt_id].name);
      if (userpnts[pnt_id].addr) {
        $('#v_point_addr').html(userpnts[pnt_id].addr);
      } else {
        $('#v_point_addr').html('Ручная привязка');
      }
      $('#v_point_memo').html(userpnts[pnt_id].memo);
      $('#v_point_id').html(pnt_id);
      obj_xx = userpnts[pnt_id].getX();
      obj_yy = userpnts[pnt_id].getY();
      $("#cx_d").val(parseInt(obj_xx));
      $("#cy_d").val(parseInt(obj_yy));
      setTimeout("redraw_map()", 1);
  } 
  function edit_user_pnt(pnt_id){
      $('#usr_pnt_view').hide();
      $('#usr_pnt_edit').show();
      $('#e_point_name').val(userpnts[pnt_id].name);
      if (userpnts[pnt_id].addr) {
        $('#e_point_addr').html(userpnts[pnt_id].addr);
      } else {
        $('#e_point_addr').html('Ручная привязка');
      }
      $('#e_point_memo').val(userpnts[pnt_id].memo);
      $('#e_point_id').html(pnt_id);
      $('#u_pnt'+pnt_id).css("border","solid 2px red");
  } 
  function edit_user_pnt_cancel(){
      $('#usr_pnt_view').hide();
      $('#usr_pnt_edit').hide();
      var i = $('#e_point_id').html();
      if (i) {
        $('#u_pnt'+i).remove();
        userpnts[i].restorepointpos();
        userpnts[i].put();
      }
  } 
  function edit_user_pnt_set_xy(xdig,ydig,addr){
      var i = $('#e_point_id').html();
      if (i) {
        $("#map_addrlist_popup").hide();
        $('#u_pnt'+i).remove();
        userpnts[i].setpointpos(xdig,ydig);
        userpnts[i].setaddr(addr);
        edit_user_pnt(i);
        userpnts[i].put();
        $("#cx_d").val(parseInt(xdig));
        $("#cy_d").val(parseInt(ydig));
        setTimeout("redraw_map()", 1);
      }
  } 


  function do_addr_search() {
    var street = $('#map_addr_edit').val();
    if (street.length > 2) {
      var region = $('#db_d').val();
      var link_txt  = '';
      $.post("/route.php", 
        { region:region, street: street, house:'', block:''},
        function(data){
          $.each(data, function(i, val) {
            if (val.id != 0) {
              if (data.length == 1) {
                var xy_arr = val.id.split(',',2)  
                edit_user_pnt_set_xy(xy_arr[0],xy_arr[1],val.nm);
              }
              if (val.dis) {
                link_txt = link_txt + '<a href=\"javascript:;\" onclick="edit_user_pnt_set_xy('+val.id+',\''+val.nm+'\');">'+val.dis+' '+val.nm+'</a><br>';
              } else {
                link_txt = link_txt + '<a href=\"javascript:;\" onclick="edit_user_pnt_set_xy('+val.id+',\''+val.nm+'\');">'+val.nm+'</a><br>';
              }
            } else {
              link_txt = 'Искомая комбинация на карте не встречается<br>';
            }
          });
          $('#map_addr_find_result').html('Результаты поиска:<br>' + link_txt);
        }
        ,"json" 
      );
    }
  }

  function get_user_auth(){
      var region = $('#db_d').val();
      var r = false;
      $.ajax({
         async: false,
         cache: false,
         type: "POST",
         url: "/map_usr_pnt.php",
         data: {region:region,action : 'getauth'},
         success: function(msg){
           if (msg=='ok') {
             r = true;
           }
         }
       });
      return r
  } 

  function edit_user_pnt_save(){
      var region = $('#db_d').val();
      var pnt_id = $('#e_point_id').html()
      userpnts[pnt_id].setparams( $('#e_point_name').val(),$('#e_point_addr').html(),$('#e_point_memo').val(),userpnts[pnt_id].bdid);
      var up = userpnts[pnt_id];

          $('#usr_pnt_view').hide();
          $('#usr_pnt_edit').hide();
          $('#u_pnt'+pnt_id).css("border","");

      $.post("/map_usr_pnt.php", 
        { region:region, action:'save',name:up.name, addr:up.addr, memo:up.memo,id:up.bdid,x:up.xdig,y:up.ydig},
        function(data){
          display_usr_pnt_list()
        }
        ,"html" 
      );
  } 
  function edit_user_pnt_delete(){
      var region = $('#db_d').val();
      var pnt_id = $('#e_point_id').html()
      var up = userpnts[pnt_id];
      $.post("/map_usr_pnt.php", 
        { region:region,action:'delete',id:up.bdid},
        function(data){
          userpnts.splice(pnt_id,1);
          $('#usr_pnt_view').hide();
          $('#usr_pnt_edit').hide();
          $("#u_pnt"+pnt_id).remove();
          display_usr_pnt_list()
        }
        ,"html" 
      );
  } 

  function display_usr_pnt_list(){

      var link_txt = '';
      $.each(userpnts, function(i, val) {
          link_txt = link_txt + '<div class=\"map_point_list\">' + (i+1) + '. <a href=\"javascript:;\"  onclick="show_user_pnt('+i+');">'+val.name+'</a></div>';
      });
      if (link_txt!='') {
        $('#user_points_list').html('<div id=\"usr_pnt_list\"><b>Список точек:</b><br>'+link_txt+'</div>');
        
      } else {
        $('#user_points_list').html('<div id=\"usr_pnt_list\">Нет точек</div>');
      }
      
  } 
  function load_usr_pnt_list(){
      var region = $('#db_d').val();
      var link_txt = '';
      $.post("/map_usr_pnt.php", 
        { region:region,action : 'list'},
        function(data){
          $.each(data, function(i, val) {
            if (val != ''){
              var j = userpnts.length;
              userpnts.push(new user_point(val.x,val.y,j));
              userpnts[j].put();
              userpnts[j].setparams(val.nm,val.addr,val.memo,val.id);
            }
          });
        }
        ,"json" 
      );
  } 

  function routeByPnt(pnts) {
    set_cursor('wait');
    var route = pnts[1].xdig + ',' + pnts[1].ydig + ',';
    var p_cnt = pnts.length-2;
 
    for (i=1; i<p_cnt;i++) {
      route = route + pnts[2+(p_cnt-i)].xdig + ',' + pnts[2+(p_cnt-i)].ydig + ',';
    }

    route = route + pnts[2].xdig + ',' + pnts[2].ydig;
    var region = $('#db_d').val();
    
    $('#close_route_btn').show();
    $('#result_list_id').html('Маршрут:<br><br>');
    $.post("/map_tj.php", 
      { addroute: route, db : region },
      function(data){
        $.each(data, function(i, val) {
          if (val.nm !== 'undefined') {
            if (i == (data.length - 1)) {
              $('#result_list_id').append('<b>' + val.nm+'</b><br>');
            } else {
              $('#result_list_id').append(val.nm+'<br>');
            }
          }
        });
        //alert(data[data.length-2].lxdig);

        var map_params = data[data.length-2];
        lxdig = map_params.lxdig;
        bydig = map_params.bydig;
        rxdig = map_params.rxdig;
        tydig = map_params.tydig;
        //ss = ww;
        var idroute = map_params.idroute;

        cx_dig = Math.floor(((rxdig - lxdig)/2) + (1*lxdig));
        cy_dig = Math.floor(((tydig - bydig)/2) + (1*bydig));

        sc_dig = Math.max( ((tydig - bydig)/400),((rxdig - lxdig)/600) );

       $("#cx_d").val(cx_dig);
       $("#cy_d").val(cy_dig);
       $("#sc_d").val(sc_dig);
       $("#idroute").val(idroute);
       if (typeof left_col_show == 'function') {
         left_col_show();
       }
       redraw_map();
       //tool_click('move');
      }
      ,"json" 
    );
  }

function route_point(x,y,id) {
    this.xdig = x;
    this.ydig = y;
    this.id = id;

    this.setpointpos = function(new_x,new_y) {
      this.xdig = new_x;
      this.ydig = new_y;
    }

    this.put = function() {
      var cxd  = parseInt($("#cx_d").val()); 
      var cyd  = parseInt($("#cy_d").val());
      var scd  = parseFloat($("#sc_d").val());
      var mapw = parseInt($("#map_w").val());
      var maph = parseInt($("#map_h").val());

      var Xpx = parseInt((mapw/2) + (( this.xdig - cxd)/scd))-16; 
      var Ypx = parseInt((maph/2) + (( this.ydig - cyd)/scd))-(-5); 
      var atmpic = '/images/map/map_route_'+this.id+'.gif';
      $('#points_place').append("<img id='r_pnt"+this.id+"' class='routepnt' style='position:absolute; z-index:5; left:"+Xpx+"px;bottom:"+Ypx+"px;' src='" + atmpic + "'>");
      var img_pos_x = findPosX(document.getElementById("im_container"));
      var img_pos_y = findPosY(document.getElementById("im_container"));
      var pnt_n = this.id;
        $('#r_pnt'+pnt_n).bind('drag',function( event ){
          $( this ).css({
            top: event.offsetY-img_pos_y,
            left: event.offsetX-img_pos_x
          });
        })
        .bind('dragend',function( event ){
          var scroll = Math.max(document.documentElement.scrollTop,document.body.scrollTop );  // !!! NB !!! only for G.chrome copatibility
          var posX2 = event.offsetX - img_pos_x + (16*1) ;
          var posY2 = event.offsetY - img_pos_y + (35*1) ;
          var mapw = parseInt($("#map_w").val());
          var maph = parseInt($("#map_h").val());
          var cx_dig = $("#cx_d").val();
          var cy_dig = $("#cy_d").val();
          var sc_dig = $("#sc_d").val();

          var Xdig = parseInt((posX2 - (mapw/2))*sc_dig); 
          var Ydig = parseInt(((maph-posY2) - (maph/2))*sc_dig); 
          Xdig = parseInt(-Xdig - cx_dig)*(-1);
          Ydig = parseInt(-Ydig - cy_dig)*(-1);

          points[pnt_n].setpointpos(Xdig,Ydig);
          if (points_cnt > 1) {
            routeByPnt(points); 
          }
        });
    }
}

function user_point(x,y,id) {
    this.xdig = x;
    this.ydig = y;
    this.id = id;
    this.name = '';
    this.addr = '';
    this.memo = '';
    this.bdid = '';
    this.oldxdig = x;
    this.oldydig = y;
    this.oldaddr = '';

    this.setpointpos = function(new_x,new_y) {
      this.oldxdig = this.xdig;
      this.oldydig = this.ydig;
      this.xdig = new_x;
      this.ydig = new_y;
    }
    this.restorepointpos = function() {
      this.xdig = this.oldxdig;
      this.ydig = this.oldydig;
      this.addr = this.oldaddr;
    }
    this.getbdid = function() {
      return this.bdid;
    }
    this.getX = function() {
      return this.xdig;
    }
    this.getY = function() {
      return this.ydig;
    }
    this.setparams = function(name,addr,memo,bdid) {
      this.name = name;
      this.addr = addr;
      this.memo = memo;
      this.bdid = bdid;
    }
    this.setaddr = function(addr) {
      this.oldaddr = this.addr;
      this.addr = addr;
    }

    this.put = function() {
      var cxd  = parseInt($("#cx_d").val()); 
      var cyd  = parseInt($("#cy_d").val());
      var scd  = parseFloat($("#sc_d").val());
      var mapw = parseInt($("#map_w").val());
      var maph = parseInt($("#map_h").val());

      var Xpx = parseInt((mapw/2) + (( this.xdig - cxd)/scd))-14; 
      var Ypx = parseInt((maph/2) + (( this.ydig - cyd)/scd))-(-3); 
      $('#points_place').append("<div id='u_pnt"+this.id+"' class='userpnt' style='left:"+Xpx+"px;bottom:"+Ypx+"px;'>"+(this.id+1)+"</div>");
      var img_pos_x = findPosX(document.getElementById("im_container"));
      var img_pos_y = findPosY(document.getElementById("im_container"));
      var pnt_n = this.id;
      $('#u_pnt'+pnt_n).bind('drag',function( event ){
        $( this ).css({
          top: event.offsetY-img_pos_y,
          left: event.offsetX-img_pos_x
        });
      })
      .bind('dragend',function( event ){
        var scroll = Math.max(document.documentElement.scrollTop,document.body.scrollTop );  // !!! NB !!! only for G.chrome copatibility
        var posX2 = event.offsetX - img_pos_x + (14*1) ;
        var posY2 = event.offsetY - img_pos_y + (33*1) ;
        var mapw = parseInt($("#map_w").val());
        var maph = parseInt($("#map_h").val());
        var cx_dig = $("#cx_d").val();
        var cy_dig = $("#cy_d").val();
        var sc_dig = $("#sc_d").val();

        var Xdig = parseInt((posX2 - (mapw/2))*sc_dig); 
        var Ydig = parseInt(((maph-posY2) - (maph/2))*sc_dig); 
        Xdig = parseInt(-Xdig - cx_dig)*(-1);
        Ydig = parseInt(-Ydig - cy_dig)*(-1);
        userpnts[pnt_n].setpointpos(Xdig,Ydig);
        userpnts[pnt_n].setaddr('');
        if($('#usr_pnt_edit').css('display')=='none') {
          edit_user_pnt(pnt_n);
        } else {
          if ($('#e_point_id').html() != pnt_n) {        //не эту точку
            edit_user_pnt_cancel();
            edit_user_pnt(pnt_n);
          }
        }
      });

      if($('#usr_pnt_edit').css('display')!='none') {  //если редактируем
        if ($('#e_point_id').html() == pnt_n) {        //именно эту точку
          $('#u_pnt'+pnt_n).css("border","solid 2px red");
        }
      }

    }
}
function scroll_to_map(){
  destination = $("#zoomin").offset().top;
  $("body").animate({ scrollTop: destination}, 1100 );
  return false;
}
     
$(document).ready(function() {

 $("#map_login_btn").click( function(){
   var um = $("#map_login_u").val();
   var pw = $("#map_login_p").val();
   $("#map_login_btn").css('background-color','#eee');

   $.post("/map_usr_pnt.php", 
     { email:um, password:pw,action : 'logon'},
     function(data){
       $("#map_login_btn").css('background-color','#aaa');
       if (data=='loginok') {
         left_col_show();
         load_usr_pnt_list()
         $("#login_label").hide();
         $("#logout_label").show();
         $('#map_login_popup').hide();
         $("#map_login_u").val('');
         $("#map_login_p").val('');
         $("#point").show();
         $("#pnt_add_new_btn").show();
         display_usr_pnt_list()
       } else {
         alert(data);
       }
     }
     ,"html" 
   );
 });

 $("#map_register_btn").click( function(){
   var em = $("#map_register_e").val();
   var pw = $("#map_register_p").val();
   $("#map_register_btn").css('background-color','#eee');

   $.post("/map_usr_pnt.php", 
     { email:em, password:pw, action : 'registeruser'},
     function(data){
       $("#map_register_btn").css('background-color','#aaa');
       if (data=='loginok') {
         left_col_show();
         load_usr_pnt_list()
         $("#login_label").hide();
         $("#logout_label").show();
         $('#map_login_popup').hide();
         $("#map_register_e").val('');
         $("#map_register_p").val('');
         $("#point").show();
         $("#pnt_add_new_btn").show();
         $("#login_popup_content").show();
         $("#register_popup_content").hide();
         display_usr_pnt_list()
       } else {
         alert(data);
       }
     }
     ,"html" 
   );
 });
 $("#pnt_add_new_btn").click( function(){

    var cx_dig = $("#cx_d").val();
    var cy_dig = $("#cy_d").val();

    if($('#usr_pnt_edit').css('display')!='none') {
      var i = $('#e_point_id').html();
        edit_user_pnt_save();
    }
    var i = userpnts.length;
    userpnts.push(new user_point(cx_dig,cy_dig,i));
    userpnts[i].put();
    userpnts[i].setparams('Новая точка ','','',0);
    edit_user_pnt(i);
    display_usr_pnt_list();
    $("#map_addrlist_popup").show();
 });

 $("#map_login_popup_close_btn2").click( function(){
   $('#map_login_popup').hide();
 });
 $("#map_login_popup_close_btn").click( function(){
   $('#map_login_popup').hide();
 });

 $("#login_label").click( function(){
   $('#map_login_popup').show();
 });

 $("#logout_label").click( function(){
   $.post("/index.phtml?page=lk&logout=1&ajlogin=1&submit=1", 
     { username:''},
     function(data){
       //alert(data);
         $("#login_label").show();
         $("#logout_label").hide();
         $("#point").hide();
         $("#pnt_add_new_btn").hide();
         $('#usr_pnt_view').hide();
         $('#usr_pnt_edit').hide();
         userpnts = [];
         display_usr_pnt_list()
         left_col_hide();
     }
     ,"html" 
   );
 });

 $("#map_addrlist_popup_close_btn").click( function(){
   $("#map_addrlist_popup").hide();
 });

 $("#pnt_edit_addr_btn").click( function(){
   $("#map_addrlist_popup").show();
 });

 $("#map_addr_find_btn").click( function(){
   do_addr_search();
 });

 $("#pnt_edit").click( function(){
  edit_user_pnt($('#v_point_id').html());
 });

 $("#pnt_edit_cancel").click( function(){
  edit_user_pnt_cancel();
 });

 $("#pnt_edit_save").click( function(){
  edit_user_pnt_save();
 });

 $("#pnt_edit_delete").click( function(){
  edit_user_pnt_delete();
 });

 $("#region_title").click( function(){
   $("#region_title").hide();
   $("#region_list").show();
 });



 $("#register_link_sw").click( function(){
   $("#login_popup_content").hide();
   $("#register_popup_content").show();
 });
 $("#login_link_sw").click( function(){
   $("#login_popup_content").show();
   $("#register_popup_content").hide();
 });


 $("#close_route_btn").click( function(){

   $("#close_route_btn").hide();
   $("#idroute").val('');
   points_cnt = 0;
   points = new Array();
   $('#result_list_id').html('');
   if (typeof left_col_hide == 'function') {
     left_col_hide();
   }
   redraw_map()

 });

$('#im_container').mousewheel(function(event, delta) {
  if(mapLoaded == true) {  
    var new_scale = 0;
    var cur_sc = $("#sc_d").val();

    if (delta > 0) 
         new_scale = cur_sc / 3;
    else if (delta < 0)
         new_scale = cur_sc * 3;
    var xy = getEventDigCoord(event);
    $("#cx_d").val(xy['X']);
    $("#cy_d").val(xy['Y']);
    $("#sc_d").val(new_scale);
    redraw_map();
   }
  timeStart = new Date();
  return false; // prevent default
});


$(".loading_image").ajaxStart(function(){
   $(this).html('<img src="/atmmap/images/loading.gif" border="0" alt="loading...">');;
});

$(".loading_image").ajaxComplete(function(event,request, settings){
  $(this).html("");
});


});

function findPosY(obj){
    var curtop = 0;
    while (obj){
        curtop += obj.offsetTop;
        obj = obj.offsetParent;
    }
    return curtop;
}

function findPosX(obj){
    var curleft = 0;
    while (obj){
        curleft += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    return curleft;
}

function getEventDigCoord(ev){
    var xy = new Array();

    var scroll = Math.max(document.documentElement.scrollTop,document.body.scrollTop );  // !!! NB !!! only for G.chrome copatibility
    var img_pos_x = findPosX(document.getElementById("im_container"));
    var img_pos_y = findPosY(document.getElementById("im_container"));
    var posX2 = ev.clientX - img_pos_x ;
    var posY2 = ev.clientY + (scroll*1) - img_pos_y  ;
    var mapw = parseInt($("#map_w").val());
    var maph = parseInt($("#map_h").val());
    var cx_dig = $("#cx_d").val();
    var cy_dig = $("#cy_d").val();
    var sc_dig = $("#sc_d").val();

    var Xdig = parseInt((posX2 - (mapw/2))*sc_dig); 
    var Ydig = parseInt(((maph-posY2) - (maph/2))*sc_dig); 
    Xdig = parseInt(-Xdig - cx_dig)*(-1);
    Ydig = parseInt(-Ydig - cy_dig)*(-1);
    xy['X']=Xdig;
    xy['Y']=Ydig;
    return xy;
}


function down(event){
  if(mapLoaded == true) {

    set_cursor(cur_tool);
    switch (cur_tool){
    case 'point':
          if($('#usr_pnt_edit').css('display')!='none') {
            var i = $('#e_point_id').html();
              edit_user_pnt_save();
          }
          var xy = getEventDigCoord(event);
          var i = userpnts.length;
          userpnts.push(new user_point(xy['X'],xy['Y'],i));
          userpnts[i].put();
          userpnts[i].setparams('Новая точка ','','',0);
          edit_user_pnt(i);
          display_usr_pnt_list();
    break;
    case 'route':
        if (points_cnt < 17) {
          points_cnt++;
          var xy = getEventDigCoord(event);
          points[points_cnt] =  new route_point(xy['X'],xy['Y'],points_cnt);
          points[points_cnt].put();
          if (points_cnt > 1) {
            routeByPnt(points); 
          }
        }
    break;
    case 'zoomin':
        isDown=true;
        var scroll = Math.max(document.documentElement.scrollTop,document.body.scrollTop );
        sel = document.getElementById("sel_area").style;
        sel.pixelTop  = event.clientY+(scroll*1); 
        sel.pixelLeft = event.clientX;            
        if ($.browser.mozilla) {
          $("#sel_area").css("top",event.clientY+(scroll*1));
          $("#sel_area").css("left",event.clientX);
        }
        sel.pixelHeight = 3;
        sel.pixelWidth  = 3;
        sel.display = "block";
    break;
    case 'move':
    	posX = event.clientX ;
        posY = event.clientY+(document.body.scrollTop*1); // !!! NB !!! for G.chrome only
        isDown=true;
        set_cursor('move2');
    break;
    case 'zoomout':
        isDown=true;
    break;

    }
  }
  return false

}

function up(event){
  if(mapLoaded == true) {
    var cx_dig = $("#cx_d").val(); 
    var cy_dig = $("#cy_d").val();
    var sc_dig = $("#sc_d").val();
    var img_w = $("#map_w").val();
    var img_h = $("#map_h").val();
    switch (cur_tool){
    case 'zoomin':
        if (isDown==true){
            isDown=false;
            var sel = document.getElementById("sel_area").style;
	        var img = document.getElementById("im_container");
            var img_pos_x = findPosX(img);
            var img_pos_y = findPosY(img);

            var sel_x_center =  sel.pixelLeft - img_pos_x + ($("#sel_area").width() / 2);  //
            var center_x = Math.ceil((cx_dig - ((img_w/2) * sc_dig)) + (sel_x_center * sc_dig));
            
            var sel_y_center = img_h - (sel.pixelTop - img_pos_y + ($("#sel_area").height() / 2)); //
            var center_y = Math.ceil((cy_dig - ((img_h/2) * sc_dig)) + (sel_y_center * sc_dig));

//        $("#debugbar").html(img_h + '/' + sel.pixelTop + '/' + img_pos_y + '/' + $("#sel_area").height());

            var sc_x = (sel.pixelWidth / img_w) * sc_dig; //
            var sc_y = (sel.pixelHeight / img_h) * sc_dig; //

            scale_to = Math.max( sc_x , sc_y );

            if (parseInt(sel.pixelWidth)  < 4) {
              if (parseInt(sel.pixelHeight)  < 4) {
                scale_to = sc_dig  / 3;
              }
            }

    	    var minsc = $("#maxs_d").val(); 
            if (scale_to < minsc)
	        scale_to = minsc;

            $("#cx_d").val(center_x);
            $("#cy_d").val(center_y);
            $("#sc_d").val(scale_to);
            sel.display = 'none';
            redraw_map();
        }
    break;
    case 'move':
        if (isDown==true){
            isDown=false;
            var im_cont = document.getElementById("im_container").style;
            var center_x = - Math.ceil((parseInt(im_cont.left) * sc_dig) - cx_dig);
            var center_y = Math.ceil(cy_dig - (parseInt(im_cont.top) * -sc_dig));
            $("#cx_d").val(center_x);
            $("#cy_d").val(center_y);
            redraw_map();
        }
    break;
    case 'zoomout':
        if (isDown==true){
            //alert(event.currentTarget.id);
            isDown=false;
            scale_to = sc_dig * 1.6;
            $("#sc_d").val(scale_to);
            redraw_map();
	    }  
    break;
    }
  }
  timeStart = new Date();
}
function redraw_map(){
    set_cursor('wait');
    mapLoaded=false;

    var db_name = $("#db_d").val();
    var cx_dig = $("#cx_d").val();
    var cy_dig = $("#cy_d").val();
    var sc_dig = parseFloat($("#sc_d").val());
    var img_w = $("#map_w").val();
    var img_h = $("#map_h").val();
 
    var minsc = $("#maxs_d").val();

    var mx_dig = $("#mxdig").val();
    var my_dig = $("#mydig").val();
    var mrk  = $("#marker").val();

    var maxx = $("#maxx_d").val();
    var minx = $("#minx_d").val();
    var maxy = $("#maxy_d").val();
    var miny = $("#miny_d").val();

    var idroute = $("#idroute").val();

	maxsc = Math.ceil(Math.min( (maxx - minx) / img_w , (maxy - miny) / img_h ));

	if (sc_dig > maxsc)
	    sc_dig = maxsc;

      	if (sc_dig < minsc)
            sc_dig = minsc;

	maxcxd = maxx - Math.ceil( (img_w/2) * sc_dig);
	mincxd = parseInt(minx) + Math.ceil( (img_w/2) * sc_dig);
	maxcyd = maxy - Math.ceil( (img_h/2) * sc_dig);
	mincyd = parseInt(miny) + Math.ceil( (img_h/2) * sc_dig);	

	if (cx_dig > maxcxd)
	    cx_dig = maxcxd;
	if (cx_dig < mincxd)
	    cx_dig = mincxd;

	if (cy_dig > maxcyd)
	    cy_dig = maxcyd;
	if (cy_dig < mincyd)
	    cy_dig = mincyd;

     document.getElementById('sc_marker').style.marginLeft = parseInt(322 - parseInt((sc_dig - minsc)/(maxsc - minsc) *320))+'px' ;  // !!! NB !!! conv. to %

     $("#cx_d").val(cx_dig);
     $("#cy_d").val(cy_dig);
     $("#sc_d").val(sc_dig);
      mapsrc =  '/map_tj.php?db='+db_name+'&sxpix='+img_w+'&sypix='+img_h+'&cxdig='+cx_dig+'&cydig='+cy_dig+'&scaledig='+sc_dig+'&mxdig='+mx_dig+'&mydig='+my_dig+'&marker='+mrk+'&idroute='+idroute+'&imagetype=gif';
    //mapsrc =  '/maps/'+db_name+'/img_'+img_w+'x'+img_h+'_cx'+cx_dig+'cy'+cy_dig+'s'+sc_dig+'.gif';
    document.getElementById('map_img').src  = mapsrc;
    //document.getElementById('map_link').href = map_link_pre+'/map/'+db_name+'/m'+mrk+'cx'+cx_dig+'cy'+cy_dig+'sd'+sc_dig+'mx'+mx_dig+'my'+my_dig;
    document.getElementById('map_link').href = '/index.phtml?page=map&db='+db_name+'&cxdig='+cx_dig+'&cydig='+cy_dig+'&scaledig='+sc_dig+'&mxdig='+mx_dig+'&mydig='+my_dig+'&marker='+mrk+'&idroute='+idroute;
    document.getElementById('map_link2').href = document.getElementById('map_link').href;

    $('#map_img_link_edit').val(map_link_pre+mapsrc);
    $('#map_html_link_edit').val('<a href="'+map_link_pre+'/map/'+db_name+'/m'+mrk+'cx'+cx_dig+'cy'+cy_dig+'sd'+sc_dig+'mx'+mx_dig+'my'+my_dig+'"><img src="'+map_link_pre+mapsrc+'" border=0></a>');
    var full_w = document.body.clientWidth - 40;
    var full_h = document.body.clientHeight - 100;
    document.getElementById('map_full_link').href = '/index.phtml?page=map&db='+db_name+'&widemap=1&cxdig='+cx_dig+'&cydig='+cy_dig+'&scaledig='+sc_dig+'&mxdig='+mx_dig+'&mydig='+my_dig+'&marker='+mrk+'&sxpix='+full_w+'&sypix='+full_h+'&idroute='+idroute;
    document.getElementById('map_full_link2').href = document.getElementById('map_full_link').href;
}
function move(event){
  if(mapLoaded == true) {  
    switch (cur_tool){
    case 'zoomin':
        if (isDown==true){
            var scroll = Math.max(document.documentElement.scrollTop,document.body.scrollTop );  // !!! NB !!! only for G.chrome copatibility
            if ((event.clientX > sel.pixelLeft ) && ((event.clientY+scroll) > sel.pixelTop));
              $("#sel_area").height((event.clientY+scroll) - sel.pixelTop-2);
              $("#sel_area").width(event.clientX - sel.pixelLeft-2);
        }
    break;
    case 'move':
        if (isDown==true){
            im_cont = document.getElementById("im_container").style;
            im_cont.left = parseInt(event.clientX - posX)+'px';
            im_cont.top  = parseInt((event.clientY+document.body.scrollTop) - posY)+'px';  // !!! NB !!! doc.sc.top don't work? but dont need
        }
    break;
    }
  }
}
function map_loaded(){
  var mimg_w = $("#map_w").val();
  var mimg_h = $("#map_h").val();
  $("#map_img").width(mimg_w*1).height(mimg_h*1);

  im_cont = document.getElementById("im_container").style;
  im_cont.left=0;
  im_cont.top=0;
  im_cont.marginLeft = parseInt(0)+'px';
  im_cont.marginTop  = parseInt(0)+'px';

  $("#points_place").html('');
  for (i=0; i<points_cnt;i++) {
    points[i+1].put();      
  }

  $.each(userpnts, function(i, val) {
    val.put();
  });
  display_usr_pnt_list();

  mapLoaded=true;
  set_cursor(cur_tool);
  var timeLoad = new Date();
  var loadTimeMs = (timeLoad.getTime() - timeStart.getTime());
  document.getElementById('ltms').innerHTML=loadTimeMs;
}

function tool_click(tool_name){
  document.getElementById(cur_tool).style.background = "none";
//    document.getElementById(cur_tool).className = '';
  document.getElementById(tool_name).style.background = "#900";
//    document.getElementById(tool_name).className = 'active';
    cur_tool = tool_name;
    set_cursor(tool_name);
}
function set_cursor(cur_name){ 
    im_frm = document.getElementById("im_frame").style;
    switch (cur_name){
    case 'zoomin':                             
        im_frm.cursor = ($.browser.opera)? 'crosshair' : 'url(/images/map/c_zoomin.cur), crosshair';
    break;
    case 'zoomout':
        im_frm.cursor = ($.browser.opera)? 'default' : 'url(/images/map/c_zoomout.cur), default';
    break;
    case 'move':
        im_frm.cursor = ($.browser.opera)? 'move' : 'url(/images/map/c_hand1.cur), move';
    break;
    case 'move2':
        im_frm.cursor = ($.browser.opera)? 'move' : 'url(/images/map/c_hand2.cur), move';
    break;
    case 'route':
        im_frm.cursor = ($.browser.opera)? 'crosshair' : 'url(/images/map/c_route.cur), move';
    break;
    case 'point':
        im_frm.cursor = ($.browser.opera)? 'crosshair' : 'url(/images/map/c_point.cur), move';
    break;
    case 'wait':
        im_frm.cursor = ($.browser.opera)? 'wait' : 'url(/images/map/c_wait.cur), wait';
    break;
    }
}
function show_obj (obj_xx,obj_yy){

     var min_sc = $("#maxs_d").val();
     $("#cx_d").val(parseInt(obj_xx));
     $("#cy_d").val(parseInt(obj_yy));
     $("#mxdig").val(parseInt(obj_xx));
     $("#mydig").val(parseInt(obj_yy));
     $("#marker").val('1027');
     $("#sc_d").val(min_sc);
     setTimeout("redraw_map()", 1);
}

function set_sc (sc_to){
     var min_sc = $("#maxs_d").val(); 
     var cur_sc = $("#sc_d").val();

     switch (sc_to) {
       case 'i': 
         new_scale = cur_sc - ((maxsc - min_sc)/7);
       break;
       case 'o': 
         new_scale = (1*cur_sc + ((maxsc - min_sc)/7));
       break;
       case 'wh_i': 
         new_scale = cur_sc / 3;
       break;
       case 'wh_o': 
         new_scale = cur_sc * 3;
       break;

       default:
         new_scale = parseFloat( (parseInt(sc_to)/7) * maxsc);
         new_scale = parseFloat( - min_sc -  new_scale)*(-1);
     }
// addon #1 begin
     var mimg_w = $("#map_w").val();
     var mimg_h = $("#map_h").val();
     var new_w = parseInt(mimg_w * (cur_sc/new_scale));
     var new_h = parseInt(mimg_h * (cur_sc/new_scale));
     var left_m = parseInt((mimg_w - new_w)/2);
     var  top_m = parseInt((mimg_h - new_h)/2);
 
     im_cont = document.getElementById("im_container").style;
     $("#map_img").width(new_w).height(new_h);
     im_cont.marginLeft = parseInt(left_m)+'px';
     im_cont.marginTop  = parseInt(top_m)+'px';
// addon #1 end

     $("#sc_d").val(new_scale);
     setTimeout("redraw_map()", 1);
}
function getClientWidth() {
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}
function getClientHeight(){
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

