//*** hsmap.js ***
//verze 3.2.0 20.3.2008

testMAP=1;
sour="";
delka=0;
plocha=0;
dim=0;
zvetseni = 2;
service = "";
imgext = "";
mapWidth = 0;
mapHeight = 0;
user = "";
editLyr = "";
editRec = -1;
etopo = 0;
queryTopo = 2;
currBut = -1;
lastBut = "";
imgext = "";
spendlik = "";
spendliky = "";
hist = new Array;
buttons = new Array();
wresult = "";
wleg = "";
otherPar = "";
pom = 0;
adjHeight = 108;
legHeight = 30;
document.onkeydown=myKey
window.onresize=changeSize
SCRF = 2.54001/72/100;
buffer = 100;
ttt=0;
db_en= "";
autoRedraw = 0;
autoRedraw1 = 0;
hs_log=false;

isNN=document.getElementById;
isIE=document.all;

function init(){
  butt(1);
  adjustExtent(fParse(imgext," "));
  if(typeof(document.refmap)!="undefined"){
    var par = document.refmap.childNodes;
    for(var i=0;i<par.length;i++){      
      if(par[i].name=='image') var image = par[i].value;
      if(par[i].name=='imgext') var ext = par[i].value;
    }
    document.refmap.setDim(2,1);
    document.refmap.newMap(image, ext, document.refmap.width, document.refmap.height); 
  }  
  setTimeout("setSize()",500);
  //setSize();
}

function openfindwin(theURL){
  document.mapserv.target = "";
  wresult = okno(theURL, "wres");
}

function elm(name){
  if(document.getElementById) return document.getElementById(name);
  else if(document.all) return document.all[name];
  else return document.layers[name];
}

function bugReport(s){
  if(confirm(s_server_err)) okno(s, "err");
}

function clearpin(){
  spendlik = "";
  spendliky = "";
  otherPar = "";
  refreshmap();
}

function clearSelection(){
  otherPar = "&savequery=0";
  spendlik = "";
  spendliky = "";
  refreshmap();
  otherPar = "";
}

function lyrs(){
  v = '';
  if(document.mapserv.layer){
    if((document.mapserv.layer.name=='layer')&&(document.mapserv.layer.checked))v = document.mapserv.layer.value;
    else for(i=0;i<document.mapserv.layer.length;i++)
      if(document.mapserv.layer[i].checked) v += document.mapserv.layer[i].value+" "; 
    v = "&layers="+v;
  }
  return v;
}

function myCheck(t){
  if((t!="")&&(t.checked)){
    lyr = document.mapserv.layer;
    for(i=0;i<lyr.length;i++){
      if(t.className==lyr[i].className)
        lyr[i].checked=false;
    }
    t.checked =true;
  }
  if(autoRedraw > 0){
    clearTimeout(ttt);
    ttt = setTimeout("refreshmap()",autoRedraw);   
  } 
}

function qlyr(){
  if(typeof(document.mapserv.qlayer)!="undefined")
    for(i=0;i<document.mapserv.qlayer.length;i++){
      if(document.mapserv.qlayer[i].checked) return document.mapserv.qlayer[i].value;
    }
  return "";
}

function refreshmap(){
  clearTimeout(ttt);
  d = new Date();
  s = service+'&mode=map&mapsize='+mapWidth+' '+mapHeight;
  if(spendlik!=""){
    if(spendlik=="center"){
      pom = fParse(imgext, " ")
      spendlik = ((pom[0]+pom[2])/2) + " " + ((pom[1]+pom[3])/2);
    }
    s += "&map_pin_feature_points="+spendlik;
    s += "&map_pins_feature_points="+spendliky;
  }
  pom =lyrs();
  s += pom+'&x='+d.getTime()+otherPar+'&mapext='+imgext;
  writescale();
  if(hs_log) console.log(s);
  document.hsmap.newMap(s, imgext, mapWidth, mapHeight);
  if(hist.length>9){
    for(i=1;i<hist.length;i++)hist[i-1]=hist[i];
    hist.length--;
  }
  hist[hist.length]=s;
  hlaska("");
  if(autoRedraw1>0) ttt=setTimeout("refreshmap()", autoRedraw1);
  if(document.refmap) document.refmap.setRect(imgext);
}

function checkLyr(){
  if(autoRedraw) refreshmap();
}

function writescale(){
  if(!document.mapserv.scale) return;
  pom = fParse(imgext, " ");
  theScale = Math.round((pom[2] - pom[0])/mapWidth/SCRF);
  gray(theScale);
  theScale=theScale.toString();
  pos = 3;
  while(pos<theScale.length){
    theScale=theScale.substr(0,theScale.length-pos)+" "+theScale.substr(theScale.length-pos);
    pos +=4;
  }
  document.mapserv.scale.value = theScale;
}

function setscale(){
  if(typeof(elm('scale'))=="undefined") return;
  pom = fParse(imgext, " ");

  cx = (pom[2] + pom[0])/2.0;
  cy = (pom[3] + pom[1])/2.0;
  mer = document.mapserv.scale.value;
  while(mer.indexOf(" ") > -1) mer = mer.replace(" ", "");
  mer = Number(mer);
  if(!isNaN(mer)){
    sirka = mer * mapWidth * SCRF/2.0;
    adjustExtent([(cx-sirka), cy-1,(cx+sirka),cy+1]);
    refreshmap();
  }
}

function lastMap(){
  if(hist.length<2)return;
  s = hist[hist.length-2];
  pom = s.split("&");
  pom = pom[pom.length-1].split("=");
  imgext = pom[1];
  if(typeof(document.refmap)!="undefined") document.refmap.setRect(imgext);
  writescale();
  document.hsmap.newMap(s, imgext, mapWidth, mapHeight);
  hist.length--;
}

function Button(name,topo,prepocet,cAction,mAction){
  this.name=name;
  this.topo=topo;
  this.prepocet=prepocet;
  this.clickAction=cAction;
  this.mapAction=mAction;
}

function addButton(name,picture,alt,topo,prepocet,cAction,mAction){
  last = buttons.length;
  buttons[last] = new Button(name,topo,prepocet,cAction,mAction);
  document.write("<a href=\"javascript:butt("+last+");\" class='abut' id='b_"+last+"'><img src='"+picture+"' width=18 height=18 alt='"+alt+"'></a>");
}

function getButtonByName(n){
  for(i=0;i<buttons.length;i++) if(buttons[i].name==n) return i;
  return -1;
}

function butt(par){
  if (par!=currBut)lastBut=currBut;
  with (document){
    if(buttons[par].clickAction!=null) if(!buttons[par].clickAction()) return;
    if(currBut>-1) elm("b_"+currBut).className="abut";
    currBut = par;
    mapserv.target = "";
    document.hsmap.setDim(buttons[par].topo, buttons[par].prepocet);
    elm("b_"+currBut).className="abutsel"; 
  }
}

function fromApplet(name, d, s, del, pl){
  sour = s;
  //delka = del;
  //plocha = pl;
  dim = d;
  k = currBut;
  // change the extent according to reference map
  if(name=="refmap"){
    if(dim==1){
      xy = fParse(s, ",");
      zoomtopoint(xy[0], xy[1], 1);
    }else{
       adjustExtent(fParse(s, " "));
       refreshmap();
    }
    return;
  }
  buttons[currBut].mapAction();
}  

function mZoomIn(){
  rozsah = fParse(imgext," ");
  if(dim==1){
    xy = fParse(sour, ","); 
    zoomtopoint(xy[0], xy[1], zvetseni);
  }
  else{
    //rozsah = fParse(imgext," ");
    pom = fParse(sour, " ");
    adjustExtent(pom);
    refreshmap();
  }
}

function mZoomOut(){
  if(dim==1){
    xy = fParse(sour, ","); 
    zoomtopoint(xy[0], xy[1], 1/zvetseni);
  }
  else{
    rozsah = fParse(imgext," ");
    pom = fParse(sour, " ");
    mer = Math.max(Math.abs((pom[2]-pom[0])/(rozsah[2]-rozsah[0])),
          Math.abs((pom[3]-pom[1])/(rozsah[3]-rozsah[1])));
    zoomtopoint((pom[0]+pom[2])/2, (pom[1]+pom[3])/2, mer);
  }
}

function bEdit(){
  if (editLyr==""){alert(s_etheme); return false;}
  resetRecno();
  return true;
}

function mQuery(){
  if(dim==1) openInfoWin("&imgxy="+sour);
  else openInfoWin("&imgbox="+sour);
}

function mLength(){
  //hlaska(s_length+": "+delka);
}

function mArea(){
  //hlaska("  " + s_area+": "+plocha +"  "+s_perim+": "+delka);
}

function bEN(){
  openEN("");
  return true;
}

function mEN(){
  if(dim==1) openEN("&imgxy="+sour);
  else openEN("&imgbox="+sour);
}

function mPan(){
  xy = fParse(sour, ",");
  zoomtopoint(xy[0], xy[1], 1);
}

function mSelect(){
  if(dim==1) pdotaz("&mode=nquery&selmode=xor&imgxy="+sour, false, false);
  else pdotaz("&mode=nquery&selmode=add&imgbox="+sour, false, false);
}

function mPin(){
  wresult = okno("/mapserv/php/pin.php", "wres");
  wresult.focus();
  return true;
}

function mProfil(){
  var w = window.open("/mapserv/php/profil_inp.php", "profil",'width=800,height=300,toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no');  
  w.focus();
}

function move(fx, fy){
  r = iParse(imgext, " ");
  dx = (r[2]-r[0])*fx*0.8;
  dy = (r[3]-r[1])*fy*0.8;
  s = (r[0]+dx)+" "+(r[1]+dy)+" "+(r[2]+dx)+" "+(r[3]+dy);
  imgext = s;
  refreshmap();
}

function openInfoWin(s){
  wresult = okno("", "wres");
  wresult.focus();
  wresult.document.write(s_wait);
  pom =service+"&mode=nquery"+s+"&imgext="+imgext
    +"&mapsize="+mapWidth+" "+mapHeight
    +otherPar+"&qlayer="+qlyr()+"&lyrs="+lyrs();
  wresult = okno(pom, "wres");
  wresult.focus();
}

function openEN(s){
  if(s!=""){
    s=service+"&mode=nquery"+s+"&imgext="+imgext+"&mapsize="+mapWidth+" "+mapHeight
    +"&qlayer=parc&layer=parc&answer=ID";  
    //alert(s);
    s = document.hsmap.getURLPage(s);
    if(s=="") {
      alert("Nic nenalezeno");
      return;
    }  
    else{
      parc=s.split(",");
      s = "&akce=findids";
      for(i=0;i<parc.length;i++) if(parc[i]!="") s += "&id[]="+parc[i];
    }
  }
  var wresult = window.open( '', 'en'+window.name,"width=950,height=700,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhist=no");
  var a = wresult.testEN;
  if((a!=1)||(s!="")) wresult = window.open( '../../en2/hsen.php?dbname='+db_en+s, 'en'+window.name);
  wresult.focus();
}

function iParse(s, ch){
  var pole = s.split(ch);
  for(i=0;i<pole.length;i++)pole[i] = parseInt(pole[i]);
  return pole;
}

function fParse(s, ch){
  var pole = s.split(ch);
  for(i=0;i<pole.length;i++)pole[i] = parseFloat(pole[i]);
  return pole;
}


function adjustExtent(rozsah){
  cellsize = Math.max(Math.abs((rozsah[2]-rozsah[0])/(mapWidth-1)), Math.abs((rozsah[3]-rozsah[1])/(mapHeight-1)));
  var ox = Math.max(((mapWidth-1) - (rozsah[2] - rozsah[0])/cellsize)/2,0);
  var oy = Math.max(((mapHeight-1) - (rozsah[3] - rozsah[1])/cellsize)/2,0);
  rozsah[0] = rozsah[0] - ox*cellsize;
  rozsah[1] = rozsah[1] - oy*cellsize;
  rozsah[2] = rozsah[2] + ox*cellsize;
  rozsah[3] = rozsah[3] + oy*cellsize;
  imgext = rozsah[0]+' '+rozsah[1]+' '+rozsah[2]+' '+rozsah[3];
}

function zoomWRect(s, buf){
  v = fParse(s, " ");
  if(buf < 0) buf = buffer;
  v[0] = v[0] - buf;
  v[1] = v[1] - buf;
  v[2] = v[2] + buf;
  v[3] = v[3] + buf;
  adjustExtent(v);
  window.focus();
  refreshmap();
}

function zoomtopoint(mapx, mapy, factor){
  rozsah = fParse(imgext," ");
  dx = (rozsah[2]-rozsah[0]);
  dy = (rozsah[3]-rozsah[1]);
  dx = dx/factor/2;
  dy = dy/factor/2;
  rozsah[0] = mapx - dx;
  rozsah[1] = mapy - dy;
  rozsah[2] = mapx + dx;
  rozsah[3] = mapy + dy;
  imgext = rozsah[0]+' '+rozsah[1]+' '+rozsah[2]+' '+rozsah[3];
  refreshmap();
}

function zoomtocenter(factor){
  rozsah = fParse(imgext," ");
  zoomtopoint((rozsah[0]+rozsah[2])/2, (rozsah[1]+rozsah[3])/2, factor);
}

function zoomall(allext){
  adjustExtent(fParse(allext, ' '));
  refreshmap();
}

function shpedit(){
  thefile = elm('base').href+"../php/edit.php?lyrname="+editLyr+"&recno="+editRec+"&project="+project;
  if(editRec>-1) thefile += "&geom=1";
  wresult = okno(thefile, "wres");
}

/*function vyberedit(){
  s = "";
  for (i=0; i<document.mapserv.layer.length; i++){
    s += document.mapserv.layer[i].value+",";
  }
  s = s.substr(0,s.length-1);
  thefile = document.all.base.href+"../php/vrstvy.php?lyrs="+s;
  s = service.split("=");
  thefile += "&map="+s[1];
  wresult=okno(thefile, "wres");
}*/

function okno(myURL, name){
  return window.open(myURL, name, "width=375,height=420,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhist=no");
}

function myKey(){
  document.hsmap.klic(event.keyCode);
}

function setSize(){
  if(window.innerWidth){
    mapWidth = window.innerWidth-elm("rpanel").width.replace(/px/,'');
    mapHeight = window.innerHeight-adjHeight;
  }   
  else {
    mapWidth = document.body.clientWidth-elm("rpanel").width.replace(/px/,'');
    mapHeight = document.body.clientHeight-adjHeight;
  }  
  if(mapWidth<350)mapWidth=350;
  if(mapHeight<100)mapHeight=100;
  document.hsmap.width = mapWidth;
  document.hsmap.height = mapHeight;
  adjustExtent(fParse(imgext, " "));
  if(typeof(document.refmap)!="undefined") rmh = document.refmap.height; else rmh=0;
  elm("legenda").style.height = mapHeight + legHeight - rmh;
  document.hsmap.newMap("", imgext, mapWidth, mapHeight);
  refreshmap();
}

function changeSize(){
  clearTimeout(ttt);
  ttt = setTimeout("setSize()",400);
}

function legenda(){
  pom =service+"&mode=legend&mapext="+imgext
    +'&mapsize='+mapWidth+' '+mapHeight+"&layers="+lyrs();
  var wleg = window.open(pom, 'leg', "width=336,height=420,toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,copyhist=no");
  wleg.focus();
}

function elyr(){
  with(document.mapserv){
    pom = elyrs.options[elyrs.selectedIndex].value;
    pom = pom.split(",");
    editLyr = pom[0];
    bi = getButtonByName("e");
    buttons[bi].topo = parseInt(pom[1]);
    for (i=0; i<layer.length; i++){
      layer[i].style.borderStyle="none";
      if(layer[i].value == editLyr){
        layer[i].style.borderStyle="solid";
        layer[i].style.borderWidth=2;
        layer[i].style.borderColor="#FF0000";
        layer[i].style.outlineColor="#FF0000";
        layer[i].checked=true;
      }
    }
    if(editLyr==""){
      if(currBut==bi) butt(1);
      //all["b_"+bi].style.display="none"; 
    } 
    else {
      butt(bi);
      //all["b_"+bi].style.display="block"; 
    }  
  }
}

function hlaska(s){
  elm('hlaska').innerHTML = s;
}

function printMap(mypath){
  theURL = "../php/mapprint.php?path="+mypath;
  w = okno(theURL, "wres");
  w.focus();
}

function uklid(){
  if((wresult!="")&& (!(wresult.closed)))wresult.close();
  if((wleg!="")&& (!(wleg.closed)))wleg.close();
}

/*
function skup(t){
  pom = t.checked;
  lyr = mapserv.layer;
  for(i=0;i<lyr.length;i++){
      if(t.id==lyr[i].className)
        lyr[i].checked=pom;
      else  
      if((pom==true)&&(lyr[i].id!=""))lyr[i].checked=false;
  }
  if(pom==true){
    for(i=0;i<elm('prep').length;i++)elm('prep')[i].checked=false;
  }
  t.checked = pom;
}
*/

function flatNodes(epom, nodename){
  var newList = new Array();
  if(epom.hasChildNodes()){
    for(var i=0; i<epom.childNodes.length; i++){
      if(epom.childNodes[i].nodeName==nodename) newList.push(epom.childNodes[i]);
      else {
        pom = flatNodes(epom.childNodes[i], nodename);
        for(var j=0; j<pom.length; j++) newList.push(pom[j]);
      }
    }
  }
  return newList;
}

function skup(t){
  pom = t.checked;
  lyr = document.mapserv.layer;
  for(i=0;i<lyr.length;i++){
      if(t.id==lyr[i].id)
        lyr[i].checked=pom;
      else  
      if((pom==true)&&(lyr[i].id!=""))lyr[i].checked=false;
  }
  /*if(pom==true){
    for(i=0;i<document.mapserv.prep.length;i++)document.mapserv.prep[i].checked=false;
  }
  t.checked = pom;*/
}

function rozbal(jmeno, o, c){
  obj = elm(jmeno);
  obj1 = elm(jmeno+'i');
  if(obj.style.display=="none"){
    obj.style.display="block";
    obj1.src = c;
  }
  else{
    obj.style.display="none";
    obj1.src = o;
  }
}

function dotaz(qstr, zoomto, highlight){
  q = service + "&mode=itemnquery&savequery=1&answer=mapext&" + qstr;
  if(q.length>1800){
    alert("Výběr je příliš velký!");
    return false;
  }
  rect = ("."+document.hsmap.getURLPage(q)).substr(1);
  //alert(s);
  if(rect=="") {
    alert('nic nenalezeno');
  }
  else if(zoomto==true){
    //alert(s);
    zoomWRect(rect, buffer);
  }
  else refreshmap();
  return rect;  
}

function pdotaz(s, zoomto, highlight){
  var q =service+"&mode=nquery"+s+"&imgext="+imgext
    +"&mapsize="+mapWidth+" "+mapHeight
    +otherPar+"&qlayer="+qlyr()+"&savequery=1&answer=mapext&lyrs="+lyrs(); 
  if(hs_log) console.log('QUERY:'+q);
  var s = document.hsmap.getURLPage(q);
  if(hs_log) console.log('RESPONSE:'+s); 
  if(s=="") {
    alert('nic nenalezeno');
  }
  else{
    if(zoomto==true) zoomWRect(s, buffer);
    else refreshmap();
  }
}

function gray(theScale){
  lb = document.all.lab;
  if(lb){
    for(i=0;i<lb.length;i++) {
      pom = lb[i].id.split(",");
      if(((pom[0]!="")&&(theScale<parseInt(pom[0])))||((pom[1]!="")&&(theScale>parseInt(pom[1])))){
        if(lb[i].href!="")lb[i].className="LyrLabelURLG";
        else lb[i].className="LyrLabelG";
      }
      else{
        if(lb[i].href!="") lb[i].className="LyrLabelURL";
        else lb[i].className="LyrLabel";
      }
    }
  }
}

function zoomSelected(){
  q =service+"&mode=selnquery"+"&mapsize="+mapWidth+" "+mapHeight
    +otherPar+"&qlayer="+qlyr()+"&answer=mapext&lyrs="+lyrs();  
  s = document.hsmap.getURLPage(q);
  //alert(s);
  if(s=="") {
    alert('nic nenalezeno');
  }
  else{
    //alert(s);
    zoomWRect(s, buffer);
    refreshmap();
  }
}

//pro data v SHP
function parcely(seznam){
  rect = dotaz('qlayers=parc,defbody&qitem=ID&qstring=/'+seznam+'/', true, true);
  seznam += "a";
  if((seznam.indexOf("|")>-1)&&(rect)!=""){
    sp = seznam.split("|");
    pocet = sp.length;
    rect = rect.split(" ");
    if(parseInt(pocet)!=parseInt(rect[4])) alert('Pozor! Nalezeno pouze '+rect[4]+" z "+pocet+" parcel. ");
  }
  //alert (seznam);
}

/*
//pro data v DB
function parcely(seznam){
  rect = dotaz('qlayers=parc,defbody&qitem=id&qstring=id IN ('+seznam+')', true, true);
  seznam += "a";
  if((seznam.indexOf(",")>-1)&&(rect)!=""){
    sp = seznam.split(",");
    pocet = sp.length;
    rect = rect.split(" ");
    if(parseInt(pocet)!=parseInt(rect[4])) alert('Pozor! Nalezeno pouze '+rect[4]+" z "+pocet+" parcel. ");
  }
  //alert (seznam);
}
*/
function wmswin(){
  var w = window.open("", "wmswin", "width=500,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhist=no");
  if(w.test!=1){
    var w = window.open("../php/wms_add.php?project="+project,"wmswin");
  }
  w.focus();
}

function usrwms(action, l){
  window.location = service+"&mapext="+imgext+lyrs()+"&mode=wms&action="+action+"&wmslyr="+l;
}

function showURL(css){
  s = service+'&mapsize='+mapWidth+' '+mapHeight;
  if(spendlik!=""){
    s += "&map_pin_feature_points="+spendlik;
    s += "&map_pins_feature_points="+spendliky;
  }
  pom =lyrs();
  s += pom+otherPar+'&mapext='+imgext;
  w = okno("","wres");
  w.focus();
  w.document.write("<html><head><link rel=\'stylesheet\' type=\'text/css\' href=\'"+css+".css\'></head><body>");
  w.document.write("<b>URL aplikace:</b><br><a href=\'"+s+"\'>"+s+"</a><hr><b>URL mapy:</b><br><a href=\'"+s+"&mode=map\'>"+s+"&mode=map</a></body></html>");
  w.document.close();
}

function reshape(layer, recno){
  window.focus();
  var b=getButtonByName("e");
  if(b<0)return false;
  if(document.mapserv.elyrs){
    for(var i=0;i<document.mapserv.elyrs.options.length;i++){
      var pom=document.mapserv.elyrs.options[i].value.split(",");
      if(pom[0]==layer){
        document.mapserv.elyrs.selectedIndex=i;
        elyr();
        break;
      }
    }
  }
  butt(b);
  document.mapserv.elyrs.options[document.mapserv.elyrs.selectedIndex].text += " #"+recno;  
  editRec = recno;
}

function resetRecno(){
  if(editRec>-1){
    with(document.mapserv){ 
      for(var i=0;i<elyrs.options.length;i++)
        if(elyrs.options[i].text.indexOf("#")>0) elyrs.options[i].text=elyrs.options[i].text.substr(0,elyrs.options[i].text.indexOf("#")-1);
    }
    editRec = -1;
    butt(getButtonByName("q"));  
  }
}

function showStatus(m){
  var s = '';
  delka = 0;
  plocha = 0;
  if(m.delka>0){
    delka = m.delka;
    if(m.delka>5000) s = ' | '+Math.round(m.delka)/1000+' km';
    else s = ' | '+Math.round(m.delka)+' m';
    if(m.plocha>0){
      plocha = m.plocha;
      if(m.plocha>10000) s += ' | '+Math.round(m.plocha/100)/100+' ha';
      else if(m.plocha>1000) s += ' | '+Math.round(m.plocha)+' m2';
      else s += ' | '+Math.round(m.plocha*100)/100+' m2';
    }
  }
  hlaska(Math.round(m.x)+' '+Math.round(m.y)+s);
}

