var tid;
var closetimeout;closetimeout=200; //Timeout to close open menu window
var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 &&
                parseFloat(navigator.appVersion) >= 4) ? 1 : 0;
var isMinIE4 = (document.all) ? 1 : 0;
var isMinIE5 = (isMinIE4 && navigator.appVersion.indexOf("5.") >= 0) ? 1 : 0;
var isNS6    = (navigator.appName.indexOf("Netscape") >=0 && parseFloat(navigator.appVersion) >= 5) ? 1 : 0;

var activemenu = -1;

var datasearch = Array();
var sdatasearch = Array();


var canopen; //The bit to show, that pop-up can be oppenned
canopen = false;

function show(what,action) {
 if (canopen) {
   obj = 'menu'+ what;
   if (action=="hide") {
      layer = (document.getElementById)? document.getElementById(obj) : document.all[obj];
      if (layer && layer.style) {
        layer.style.visibility = "hidden";
      }
      activemenu = -1;
   }
   if (action=="show") {
      clearTimeout(tid);
      if (activemenu>-1) {
        show(activemenu,'hide');
      }
      obj = 'menu'+what;
      layer = (document.getElementById)? document.getElementById(obj) : document.all[obj];
      if (layer && layer.style) {
        layer.style.visibility = "visible";
      }
      activemenu = what;
   }
 }
}

function div_show(div,action) {
 if (canopen) {
   obj = div;
   if (action=="hide") {
      layer = (document.getElementById)? document.getElementById(obj) : document.all[obj];
      if (layer && layer.style) {
        layer.style.visibility = "hidden";     
      }
   }
   if (action=="show") {
      layer = (document.getElementById)? document.getElementById(obj) : document.all[obj];
      if (layer && layer.style) {
        layer.style.visibility = "visible";       
      }
   }
 }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function update_div(div,html) {
//   alert(html);
   var layer = (document.getElementById)? document.getElementById(div) : document.all[div];
   if(layer && layer.innerHTML) {
     layer.innerHTML = html;
   }
}

function get_div_html(div) {
   var layer = (document.getElementById)? document.getElementById(div) : document.all[div];
   if(layer && layer.innerHTML) {
     return layer.innerHTML;
   }
}

function xaction(commands) {
   try {
     eval(commands);
   } catch (e) {
     alert('error');
     alert(commands);
   }
}


function query_form(in_kiev) {
  var kiev_tpl='<a href="javascript:void(query_form(0));"><img src="i/cm1.gif" width="146" height="37" border="0"></a><a href="javascript:void(query_form(1));"><img src="i/cm2s.gif" width="69" height="37" border="0"></a>';
  var outkiev_tpl='<a href="javascript:void(query_form(0));"><img src="i/cm1s.gif" width="146" height="37" border="0"></a><a href="javascript:void(query_form(1));"><img src="i/cm2.gif" width="69" height="37" border="0"></a>';

  var kiev_tpl2='&#149; <a href="javascript:void(getDistricts(1,true));" class="ts">Поиск по району</a>&nbsp; &#149; <a href="javascript:void(getSmallDistricts(1,true));" class="ts">Поиск по микрорайону</a>&nbsp; &#149; <a href="javascript:void(getStreetsFilter());" class="ts">Поиск по улице</a>';
  var outkiev_tpl2='&#149; <a href="javascript:void(getDirects(1,true));" class="ts">Поиск по направлению</a>&nbsp; &#149; <a href="javascript:void(getAreas(1,true));" class="ts">Поиск по району</a>&nbsp; &#149; <a href="javascript:void(getVillagesFilter());" class="ts">Поиск по населенному пункту</a>';

  if (in_kiev) {
    update_div('content1',kiev_tpl);
    update_div('content2',kiev_tpl2);
  } else {
    update_div('content1',outkiev_tpl);
    update_div('content2',outkiev_tpl2);
  }
}

function getDistricts(p,clear_required) {
  if (clear_required) clear_datasearch();
  document.forms['query'].stype.value='_mainplaces';

  update_div('content3','&nbsp;');
  div_show('loading','show');
  sajax_do_call('getDistricts',Array(p,xaction));
}

function getSmallDistricts(p,clear_required) {
  if (clear_required) clear_datasearch();
  document.forms['query'].stype.value='_places';
  update_div('content3','&nbsp;');
  div_show('loading','show');
  sajax_do_call('getSmallDistricts',Array(p,xaction));
}

function getDirects(p,clear_required) {
  if (clear_required) clear_datasearch();
  document.forms['query'].stype.value='_streets!_directs';
  update_div('content3','&nbsp;');
  div_show('loading','show');
  sajax_do_call('getDirects',Array(p,xaction));
}

function getAreas(p,clear_required) {
  if (clear_required) clear_datasearch();
  document.forms['query'].stype.value='_places';
  update_div('content3','&nbsp;');
  div_show('loading','show');
  sajax_do_call('getAreas',Array(p,xaction));
}

function getStreetsFilter() {
  clear_datasearch();
  update_div('content3','&nbsp;');
  update_div('content4','&nbsp;');
  update_div('content5','&nbsp;');
  div_show('loading','show');
  sajax_do_call('getStreetsFilter',Array(xaction));
}

function getVillagesFilter() {
  clear_datasearch();
  update_div('content3','&nbsp;');
  update_div('content4','&nbsp;');
  update_div('content5','&nbsp;');
  div_show('loading','show');
  sajax_do_call('getVillagesFilter',Array(xaction));
}


function getStreets(filter, p, clear_required) {
  if (clear_required) clear_datasearch();
  document.forms['query'].stype.value='_streets';
  div_show('loading','show');
  sajax_do_call('getStreets',Array(filter, p,xaction));
}

function getVillages(filter, p, clear_required) {
  if (clear_required) clear_datasearch();
  document.forms['query'].stype.value='_streets';
  div_show('loading','show');
  sajax_do_call('getVillages',Array(filter, p,xaction));
}


function clear_datasearch() {
  datasearch = Array();  
  sdatasearch = Array();  
  refreshlist();
}

function add_datasearch(str,val) {
  add_unique_to_array(str,datasearch);
  add_unique_to_array(val,sdatasearch);
  refreshlist();
}

function delete_datasearch(i) {
  if (datasearch.length==1) {
    clear_datasearch();
  }else{
    datasearch.splice(i,1);
    sdatasearch.splice(i,1);
    refreshlist();
  }
}


function refreshlist() {
  var tpl = '<div class="container ts"><nobr>{info}</nobr><div class="rsd"><a href="javascript:delete_datasearch({id});"><img src="i/r.gif" border="0"></a></div></div>';
  var html='';
  var f = document.forms['query'];
  f.data.value='';
  if (datasearch.length==0) {
     update_div('content6','&nbsp;');
  }else{
    for (var i=0;i<datasearch.length;i++) {
      f.data.value = f.data.value+': '+datasearch[i];
      f.sdata.value = f.sdata.value+': '+sdatasearch[i];
      var ttpl = tpl.replace('{info}',datasearch[i]);
      ttpl = ttpl.replace('{id}',i);
      html=html+ttpl;
    }
    update_div('content6',html);
  }
}

function make_list(in_arr, in_arr_keys, query, page, pages) {
  var html='<div style="position:absolute;top:2px;left:0px;width:183px;height:108px;overflow:hidden;">';
  for (i=0;i<Math.min(in_arr.length,7);i++) {
    html=html+'<nobr><a href="javascript:void(add_datasearch(\''+in_arr[i]+'\',\''+in_arr_keys[i]+'\'));" class="ts"><img src="i/a.gif" border="0">'+unescape(in_arr[i])+'</a></nobr>';
    if (i<6) html=html+'<br>';
  }
  html=html+'</div>';
  if (in_arr.length>7) {
     html=html+'<div style="position:absolute;top:2px;left:184px;width:183px;height:108px;overflow:hidden;">';
     for (i=7;i<Math.min(in_arr.length,14);i++) {
       html=html+'<nobr><a href="javascript:void(add_datasearch(\''+in_arr[i]+'\', \''+in_arr_keys[i]+'\'));" class="ts"><img src="i/a.gif" border="0">'+unescape(in_arr[i])+'</a></nobr>';
       if (i<13) html=html+'<br>';
     }
     html=html+'</div>';
  }
  update_div('content4',html);

  html='';
  if (page>1) {
    html='<a href="javascript:void('+query.replace('{p}',(page-1))+');"><img src="i/al.gif" width="13" height="12" border="0"></a>';
  }
  if (page<pages) {
    html=html+'<a href="javascript:void('+query.replace('{p}',(page+1))+');"><img src="i/ar.gif" width="13" height="12" border="0"></a>';
  }
  if (!html) html='<img src="i/1.gif" width="1" height="1">';

  update_div('content5',html);
  div_show('loading','hide');
}

function make_filter(in_arr1, in_arr2, query) {
   // A &#149; Б ...
   //<a href="javascript:void();" class="ts">A</a>
   var html = '';
   for (i=0;i<in_arr1.length;i++) {
     if (html) html = html + '<img src="i/fd.gif" width="6" height="9">';
     html = html + '<a href="javascript:void('+query.replace('{F}',in_arr2[i])+');" class="ts">'+in_arr1[i]+'</a>';
   }
   update_div('content3',html);
   div_show('loading','hide');
}




//Function to work with arrays
function in_array(str,arr) {
 res = -1;
 for (var i=0;i<arr.length;i++) {
   if (arr[i]==str) {
     res = i;
     i=arr.length;
   }
 }
 return res;
}

function del_from_array(str,arr) {
 res = -1;
 newarr = Array();
 for (var i=0;i<arr.length;i++) {
   if (arr[i]!=str) newarr.push(arr[i]);
 }
 return newarr;
}

function add_to_array(str,arr) {
  lastid=arr.length;
  arr[lastid]=str;
  return lastid;
}

function add_unique_to_array(str,arr) {
  if (in_array(str,arr)==-1) {
     arr.push(str);
     lastid=arr.length-1;
     return lastid;
  }else{
     return -1;
  }
}

function add_to_top_array(str,arr) {
  lastid=arr.length;
  for (i=lastid; i>0;i--) {
    arr[i]=arr[i-1];
  }
  arr[0]=str;
  return lastid;
}


function add_unique_to_top_array(str,arr) {
  var m;
  if (in_array(str,arr)==-1) {
     m = add_to_top_array(str,arr);
     return m;
  }else{
     return -1;
  }
}


var p_x = 100;
var p_y = 100;
defaultWidth  = 600;
defaultHeight = 600;
var AutoClose = true;
if (parseInt(navigator.appVersion.charAt(0))>=4){
var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+p_x+',top='+p_y;
var optIE='scrollbars=no,width=150,height=100,left='+p_x+',top='+p_y;
function loadPhoto(imageURL,imageTitle){
if (isNN){imgWin=window.open('about:blank','',optNN);}
if (isIE){imgWin=window.open('about:blank','',optIE);}
with (imgWin.document){
writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
writeln('width=100-(document.body.clientWidth-document.images[0].width);');
writeln('height=100-(document.body.clientHeight-document.images[0].height);');
writeln('window.resizeTo(width,height);}');writeln('if (isNN){');
writeln('window.innerWidth=document.images["img"].width;');writeln('window.innerHeight=document.images["img"].height;}}');
writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
if (!AutoClose) writeln('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
else writeln('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
writeln('<img name="img" src='+imageURL+' style="display:block"></body></html>');
close();		
}}


var levels = new Array('house', 'street', 'district', 'locality', 'area', 'province');
var levels_precision = new Array(17, 16, 12, 11, 7, 6);
var min_possible_level = 0;

function get_level(kind) {
  for (var i=0; i<levels.length; i++) {
     if (levels[i]==kind) {
        return i;
     }
  }
  return -1;
}

 function start_map (query) {
 var map = new YMaps.Map(document.getElementById("YMapsID"));
 var geocoder = new YMaps.Geocoder(query);
 map.addOverlay(geocoder);

 YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
   if (this.length()) {                      
       var i_to_be_used = -1;
       var current_level = -1;
       var is_dublicate = true;
       while (is_dublicate && (min_possible_level<6)) {
         current_level = -1;
         for (var i=0; i<this.length(); i++) {
            if (get_level(this.get(i).kind)>=min_possible_level) {
               if ((current_level==-1) || (current_level>get_level(this.get(i).kind))) {
                 i_to_be_used=i;
                 current_level=get_level(this.get(i).kind);
                 is_dublicate = false;
               } else if ((current_level==-1) || (current_level==get_level(this.get(i).kind))) {
                 is_dublicate = true;
               }
            }
         }
         if (is_dublicate) {
           if (min_possible_level<current_level) {
             min_possible_level = current_level+1;
           }else{
             min_possible_level = 6;
           }
         }
       }
       map.addOverlay(this.get(i_to_be_used));
       map.setCenter(this.get(i_to_be_used).getGeoPoint(), levels_precision[0+get_level(this.get(i_to_be_used).kind)]);
   }else {
        update_div('YMapsID','<div style="line-height: 400px;" align="center">&nbsp;</div>')
   }
}); 
YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (error) {
        update_div('YMapsID','<div style="line-height: 400px;" align="center">&nbsp;</div>')
});
}

