

var importXML;
var doAlert=true;
function loadXML(x, editer) {
 if (x==false) doAlert=false;
 if (window.ActiveXObject || window.XMLHttpRequest) {
  importXML = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLDOM");
  importXML.async=true;
  if (x!=null && x!=false) {
   importXML.onreadystatechange = function () {if (importXML.readyState == 4) getcitydetails(x,editer);};
   try {
    importXML.load("citydata.php?id="+x);
   } catch (e) {
    importXML.open("GET","citydata.php?id="+x,true);
    importXML.send(null);
   }
  } else {
   importXML.onreadystatechange = function () {if (importXML.readyState == 4) getmessage();};
   try {
    importXML.load("maildata.php");
   } catch (e) {
    importXML.open("GET","maildata.php",true);
    importXML.send(null);
   }
  }
 }
 
 else if (document.implementation && document.implementation.createDocument) {
  importXML=document.implementation.createDocument("","",null);
  importXML.onload = (x != null) ? function(){getcitydetails(x,editer);} : getmessage;
  importXML.async=true;
  if (x != null && x!=false)
   importXML.load("citydata.php?id="+x);
  else
   importXML.load("maildata.php");
 }
 else{}
}

function getcitydetails(x,editer) {
 if (window.XMLHttpRequest)
  try {importXML = importXML.responseXML;} catch(e){}
 try {
  y = importXML.getElementsByTagName("details")[0].childNodes[0].nodeValue;
  citydetails(x,y,editer);
 } catch (e) {}
}

function getmessage() {
 alertnow=false;
 try {
  if (window.XMLHttpRequest)
   try {importXML = importXML.responseXML;} catch(e){}
  numofmails = importXML.getElementsByTagName("mails")[0].childNodes[0].nodeValue;
  if (numofmails>parseInt(document.getElementById('mail').innerHTML)) alertnow=true;
  document.getElementById('mail').innerHTML = numofmails;
  document.getElementById('mailImager').style.display = (numofmails>0) ? 'inline' : 'none';
  if (alertnow && doAlert!=false) {
   mailImage = "./images/thumb.php?width=50&height=70&id="+importXML.getElementsByTagName("mailImage")[0].childNodes[0].nodeValue;
   mailSubject = '<a href=\"message.php?id=' + importXML.getElementsByTagName("mailId")[0].childNodes[0].nodeValue;
   mailSubject += '\" target=main>"' + importXML.getElementsByTagName("mailSubject")[0].childNodes[0].nodeValue + '"</a>';
   parent.alerter('התקבלה הודעה חדשה', mailSubject, mailImage);
   document.focus();
   parent.notify();
  }
  numReq = importXML.getElementsByTagName("userR")[0].childNodes[0].nodeValue;
  if (numReq>0) {
   show('userReq');
   document.getElementById('userReq').innerHTML = "&nbsp;<a class=blue href=mail.php?sent=2 style='color:#AA8822' target=main>בקשות חברות (<span style='color:darkorange'>"+numReq+"</span>)</a>&nbsp;";
  }
  else if (document.getElementById('userReq').innerHTML != "") {
   document.getElementById('userReq').innerHTML = "";
   hide('userReq');
  }
  numviewers = importXML.getElementsByTagName("numviewers")[0].childNodes[0].nodeValue;
  top.getIt('viewers').innerHTML = numviewers;
  numfriends = importXML.getElementsByTagName("numfriends")[0].childNodes[0].nodeValue;
  top.getIt('friends').innerHTML = numfriends;
  action = importXML.getElementsByTagName("message")[0].childNodes[0].nodeValue;
  name   = importXML.getElementsByTagName("name")[0].childNodes[0].nodeValue;
  try {
   if (parent.mainindex.messanger.document.statusmsgform.myid.value <= 10001) {
    numuserupdates = importXML.getElementsByTagName("userupdates")[0].childNodes[0].nodeValue;
    document.getElementById('userupdates').innerHTML = numuserupdates;

    lastForum = importXML.getElementsByTagName("lastForum")[0].childNodes[0].nodeValue;
    document.getElementById('newPost').style.display = (lastForum==1) ? "" : "none";
    if (lastForum==1)
     document.focus();
   }
  } catch(e){}
 if (action!=0) {
  parent.instM(action,name);
 }
 } catch(e) {} //try all
 doAlert=true;
}


<!--
var tmr;
var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);

thisOne = new Object();

function menuTo(link) {
  top.mainindex.main.location.href = link;
  top.hide('menu1');
  top.hide('menu2');
  top.hide('menu3');
}

function putIt(e, id, w, obj, w2) {
  menuP = (ie5) ? 6 : 4;
  getIt(id).style.left = -137-menuP+obj.offsetLeft+obj.offsetWidth;
  show(id);
}

function fadeIt(sel, h) {
  clearInterval(tmr);
  if ( parseInt( getIt(sel).style.height )  > 6 ) 
    fadeOut(sel);
  else
    fadeIn(sel, h);
  }

function fadeIn(valg, h) {
  valgt = valg;
  fade_In(valgt, h);
  show(valg);
  tmr=setInterval("fade_In(valgt, " + h + ")",10);
}

function fadeOut(valg){
  clearInterval(tmr);
  valgt=valg;
  tmr=setInterval("fade_Out(valgt)",10);
 }

function fadeOutNow(mio){
  clearInterval(tmr);
  thisOne = getIt(mio);
  thisOne.style.height=0;
}

function fade_In(mio, h){
  thisOne = getIt(mio);
  height  = Math.min(20, h - parseInt(thisOne.style.height));
  if (height>0)
    thisOne.style.height = parseInt(thisOne.style.height)+height;
  else
   clearInterval(tmr);
}

function fade_Out(mio){
  thisOne = getIt(mio);
  height  = Math.min(20, parseInt(thisOne.style.height)-1);
  if (height > 0)
	 thisOne.style.height = parseInt(thisOne.style.height)-height;
  else
   endIt(mio);
}

function endIt(mio) {
 hide(mio);
 clearInterval(tmr);
 if (mio=='SA')
  fadeIn('CA', 190);
 else if (mio=='CA')
  fadeIn('SA', 233)
}

function countryTo(mio) {
 thisOne = getIt(mio);
 if ((thisOne.style.height==190 && mio=='CA') ||
     (thisOne.style.height==233 && mio=='SA'))
  return;
 if (mio=='SA') {
  getIt('SABut').style.background='#ffeaea';
  getIt('CABut').style.background='#fafaff';
  fadeOut('CA');
 }
 else {
  getIt('CABut').style.background='#ffeaea';
  getIt('SABut').style.background='#fafaff';
  fadeOut('SA');
 }
}

function show(id){
if(ns4){document.layers[id].visibility = "show";}
else {getIt(id).style.visibility = "visible";
      getIt(id).style.display = "block";}
}

function hide(id){
if(ns4){document.layers[id].visibility = "hide";}
else { getIt(id).style.visibility = "hidden";
       getIt(id).style.display = "none";}
}

function getIt(id) {
  if(ns4)
   return document.layers[id];
  if(ie4 || ie5)
   return document.all[id];
  if(ns6)
   return document.getElementById(id);
}

var tmr1;
var Opacity = 0;
var myobj;
function fadeInAlpha(valg1){
 Opacity = parseInt(valg1.style.opacity) * 100;
 clearInterval(tmr1);
 myobj=valg1;
 tmr1=setInterval("fade_InAlpha(myobj)",100);
}
 
function fadeOutAlpha(valg1){
 Opacity = parseInt(valg1.style.opacity) * 100;
 clearInterval(tmr1);
 myobj=valg1;
 tmr1=setInterval("fade_OutAlpha(myobj)",100);
}

function fade_OutAlpha(mio) {
 if (Opacity > 0) {
  Opacity -= 33;
  mio.style.filter = "alpha(style=0,opacity=" + Opacity + ")";
  mio.style.opacity = "."+Opacity;
 }
 else {
  clearInterval(tmr1);
 }
}

function fade_InAlpha(mio) {
 if (Opacity < 99) {
  Opacity += 33;
  mio.style.filter = "alpha(style=0,opacity=" + Opacity + ")";
  mio.style.opacity = "."+Opacity;
 }
 else {
  mio.style.filter = "";
  mio.style.opacity = "";
  clearInterval(tmr1);
 }
}

//-->

// Misc functions for TODOS.co.il website
// Includes Website Misc, Hebrew Keyboard initialize, IM, Map, Drag&Drop, and Gallery functions
// Built by Nir Soudry, 2007-8

// Website Misc start
var ie=document.all;
var nn6=getIt&&!document.all;

try {
 top.getIt('alertDiv').style.display='none';
 top.getIt('bigdiv').style.display='none';
}catch(e){}

document.onkeydown=function(e) {
 var kC  = (window.event) ? event.keyCode : e.keyCode;
 var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;
 if(kC==Esc) {
  try {
   top.getIt('alertDiv').style.display='none';
   top.getIt('bigdiv').style.display='none';
   getIt('pList').style.display='none';
  }catch(e){}
 }
}

function toggleT(id) { //for mainframe
 bol = (getIt(id+'Table').style.display=='none');
 getIt(id+'Table').style.display = (bol) ? '' : 'none';
 getIt(id+'Img').src = (bol) ? 'arr1.gif' : 'arr0.gif';
 bol = (bol) ? 1 : 0;
 parent.updater.location='sqlactions.php?toggleT='+id+'&go='+bol;
}

function toggleT_Ajax(url, id) { //for mainframe
 if (getIt(id+'Div').innerHTML=='') { //first time
  load(url, id+'Div');
  getIt(id+'Img').src = 'arr1.gif';
  parent.updater.location='sqlactions.php?toggleT='+id+'&go=1';
  return;
 }
 toggleT(id);
}

if (document.images) { //preload images
 preloadImage = new Image();
 imagesUrl = new Array("icon/stargreen.gif", "frowny.gif", "smiley.gif", "arr0.gif", "loadingblue.gif", "icon/left.png");
 for(i=0; i<imagesUrl.length; i++)
  preloadImage.src = imagesUrl[i];
}

function toggleId(id) {
 getIt(id).style.display = (getIt(id).style.display=="none") ? "" : "none";
}

function bg(obj, color) {
 obj.style.background = color;
}

function bgImg(obj, img) {
 obj.style.background = "url("+img+")";
}

function border(obj, color) {
 obj.style.borderColor = color;
}

function toGallery(galleryName) {
 id = parseInt(galleryName);
 type = galleryName.substring(galleryName.indexOf(id), galleryName.length);
 if (type=="users")
  link = "myalbum.php?id="+id;
 else
  link = "gallery.php?typeid="+id+"&type="+type;
 top.location = "http://todos.co.il/"+link;
}

function doStars(rank, id) {
 document.write("<span class=name>ציון</span>&nbsp;<span id=ranktext"+id+">");
 var src="";
 for (x=1; x<=5; x++) {
  if (rank>4.7) src='stargreen.gif';
   else if (x-0.3 <= rank) src='starred.gif';
    else if (x-0.7 <= rank) src='starhalf.gif';
     else src='starempty.gif';

  document.write("<img width=12 alt='דרגו ("+x+"/5)' onclick='setStars("+x+","+id+");' class=hand onmouseover='showStars("+x+","+id+");' onmouseout='showStars("+rank+","+id+");' src='icon/"+src+"' id='star"+x+"-"+id+"'>");
 }
}

function doTable(id,rem,gal,hostel,details,minihostels,like,map) { //write options table on top left of citydetails
 if (gal>0) gal="<strong>"+gal+"</strong>";
 if (rem>0) rem="<strong>"+rem+"</strong>";
 wrt = "<table class=doTable cellspacing=0 cellpadding=0><tr>";
 /*
 if (minihostels)
  wrt+= "<td class=hand nowrap onclick=\"reserve("+id+");\"><a href=javascript:; style='color:#3B8B17'><img src='icon/book.png' height=20 width=20><br>הזמינו מקום</a></td>";
 if (details)
  wrt+= "<td class=hand nowrap onclick=\"details("+id+",0);\"><a href=javascript:;><img src='icon/3.gif' height=20 width=20><br>פרטים נוספים</a></td>";
 wrt += "<td class=hand nowrap onclick=\"openIFrame("+id+",'remarks');\"><a href=javascript:;><img src='icon/1.gif' height=20 width=20><br>הערות("+rem+")</a></td>";
 wrt += "<td nowrap class=hand onclick='gallery("+id+")'><a href=javascript:;><img src='icon/2.gif' height=20><br>גלריות(<span id=numcitydetails"+id+">"+gal+"</span>)</a></td>";
 wrt += "<td id=update"+id+" nowrap style='padding-left:0px'><a href=\"javascript:Edit('"+id+"'";
 if (hostel) wrt+=",true";
 wrt+=");\"><img src='update.jpg' height=20 width=20><br>עדכנו פרטים</a></td></tr></table>";
 */
 if (like)
  wrt += '<td nowrap><fb:like ref="cd'+id+'" href="http://todos.co.il/like.php?cdid='+id+'" layout="button_count"></fb:like></td>';
 wrt += "<td nowrap>";
 if (minihostels)
  wrt += "<td nowrap><span class=likeRed><a target=_blank href='http://www.minihostels.com/reservation/hostel/"+minihostels+"/aid/605' class=like><span class=l1>&nbsp;</span><b class=bo>הזמינו מקום עכשיו</b><span class=l2>&nbsp;</span></a></span></td>";
 wrt += "<td nowrap><a href=javascript:; onclick='gallery("+id+")' class=like><span class=l1>&nbsp;</span><b class=bb>תמונות ("+gal+")</b><span class=l2>&nbsp;</span></a></td>";
 wrt += "<td><a href=javascript:; onclick=\"openIFrame("+id+",'remarks');\" class=like><span class=l1>&nbsp;</span><b class=bc>הערות ("+rem+")</b><span class=l2>&nbsp;</span></a></td>";
 if (details)
  wrt += "<td><a href=javascript:; onclick=\"details("+id+",0);\" class=like><span class=l1>&nbsp;</span><b class=bi>מידע נוסף</b><span class=l2>&nbsp;</span></a></td>";
 if (map)
  wrt += "<td><a href=javascript:; onclick=\"streetMap("+id+");\" class=like><span class=l1>&nbsp;</span><b class=bi>מפה</b><span class=l2>&nbsp;</span></a></td>";
 //wrt += "</td>";
 wrt += "<td id=update"+id+"><a class=like href=\"javascript:Edit('"+id+"'";
 if (hostel) wrt+=",true";
 wrt += ");\"><span class=l1>&nbsp;</span><b class=bu>עדכנו פרטים</b><span class=l2>&nbsp;</span></a></td>";
 wrt += "</tr></table>";
 
 document.write(wrt);
}

function reserve(id) {
 window.open(document.getElementById('mini'+id).href);
}

function skypeMapTo (where,ratio) { //Check for Skype-add-in which changes the map place.
 sf = getIt('skypeFinder').innerHTML;
 if (sf != "972-2-6665554") {
  mapTo(where,ratio);
 }
 else {
  setTimeout("skypeMapTo('"+where+"',"+ratio+")",400);
 }
}
function locC(id,detailer) { // location=location.php
 detailer = (detailer==undefined) ? "" : "&detailer="+detailer;
 document.location="location.php?id="+id+detailer;
}
function locsC(id) { // location=locations.php
 document.location="locations.php?country="+id;
}
function locuC(id) { // location=userdetails.php
 document.location="userdetails.php?id="+id;
}
function go2(where) { //scroll page
 try {
  winW = (nn6) ? window.innerWidth : document.body.offsetWidth;
  selectedPosY = getIt(where).offsetTop - 20;
  document.body.scrollTop = selectedPosY;
 } catch(e) {}
}

function alerter(title,text,image) { // nice alert()
 if (nn6) {winW = window.innerWidth; winH = window.innerHeight;}
 if (ie)  {winW = document.body.offsetWidth; winH = document.body.offsetHeight;}
 getIt('alertTitle').innerHTML = title;
 getIt('alertText').innerHTML  = text;
 getIt('alertImage').innerHTML = "<img src='"+image+"'>";
 getIt('alertDiv').style.top = winH/2 - 200;
 getIt('alertDiv').style.left = winW/2 - (getIt('alertDiv').offsetWidth / 2);
 getIt('alertDiv').style.display = 'block';
 getIt('alertDiv').style.left = winW/2 - (getIt('alertDiv').offsetWidth / 2);
}

function magnify(width, height, x, desc, caller, dater, edit, desc2){ //magnify image (int, int, filename in ./images, string, framename)
 try {parent.parent.getIt('alertDiv').style.display='none';}
 catch(e){}
 hide('thumb');
 show('loading');
 if (nn6) {winW = window.innerWidth; winH = window.innerHeight;}
 if (ie)  {winW = document.body.offsetWidth; winH = document.body.offsetHeight;}
 if (winH-40<height) {width = width / (height / (winH-45)); height=winH-45;}
 if (winW-100<width) {height=height / (width / (winW-100)); width=winW-100;}
 width =Math.round(width);
 height=Math.round(height);
 getIt('bigdiv').style.left = (winW)/2 - width/2;
 getIt('bigdiv').style.top = 5;
 getIt('thumb').style.height = height;
 getIt('thumb').style.width  = width;
 getIt('bigdiv').style.width = width+15;
 getIt('bigdiv').style.height = height+25;
 backnext="קישור ישיר: <a href='photo.php?id="+x+"' class=lightNoU target=_new>לתמונה</a>&nbsp;";
 if (x.indexOf("users")!=-1 || x.indexOf("city")!=-1 || x.indexOf("citydetails")!=-1)
  backnext+="| <a href='gallery.php?id="+x+"' class=lightNoU target=_top>לגלריה</a>&nbsp;";
 photonxt="";
 if (caller!=undefined && caller!='') {
  caller = (caller!='main')? "mainindex.main.frames['"+caller+"']" : "mainindex.main";
  backnext+="<a href='javascript:;' onclick=\""+caller+".goBack();\">הקודם</a>";
  backnext+=" <a href='javascript:;' onclick=\""+caller+".goNext();\">הבא</a>&nbsp;";
  photonxt="class=hand onclick=\""+caller+".goNext();\"";
 }
 dater = (dater==undefined && dater!='') ? "" : "&"+dater;
 getIt('bigDivBacknext').innerHTML = backnext;
 if (desc ==undefined) desc="";
 if (desc2==undefined) desc2="";
 getIt('bigDivDesc').innerHTML = desc + " " + desc2;
 if (edit==1)
  getIt('bigDivDesc').innerHTML = "<img title='עדכון תיאור' align=absmiddle height=12 src='icon/pencil.gif' class=hand onclick=\"editDesc('"+x+"', '"+desc+"')\"> " + getIt('bigDivDesc').innerHTML;
 getIt('thumb').innerHTML = "<img "+photonxt+" src='./thumb.php?id="+x+"&width="+width+"&height="+height+dater+"' onload=\"hide('loading');show('thumb');\">";
 show('bigdiv');
}

function changeInputs() { //set class=text for 'input type=text'
 els = document.getElementsByTagName('input');
 elsLen = els.length;
 for (i=0; i<elsLen; i++) {
  if (els[i].getAttribute('type')) {
  if ((els[i].getAttribute('type') == "text") || (els[i].getAttribute('type') == "password"))
  els[i].className = 'text';
  }
 }
}

window.onload = function(){changeInputs();}

function flashVer() { // return flash version
 for(i=10; i>0; i--){
	try {
   var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
	 return "flash="+i;
	}
	catch(e){}
 }
 if (navigator.plugins != null && navigator.plugins.length > 0) {
  var flashPlugin = navigator.plugins['Shockwave Flash'];
  if (typeof flashPlugin == 'object')
   for (i=10; i>0; i--)
    if (flashPlugin.description.indexOf(i+'.') != -1)
     return "flash="+i;
 }
 return 0;
}

// Website Misc end
///////////////////
// Mikledet start
function goMik () { //toggle heb value
if (document.searchForm.heb.value == '1') {
  document.searchForm.heb.value = '0';
  getIt('keySetter').innerHTML="EN";
  getIt('keyShowTR').style.display = "none";
  top.showKey(false);
 }
 else {
  getIt('keyShowTR').style.display = "";
  document.searchForm.heb.value = '1';
  getIt('keySetter').innerHTML="HE";
 }
}

function in_array (s,a) {
 for(var k in a) if(a[k]==s) return 1; return 0;
}

document.onkeypress = function(e){return checkMik(e)};
var exclude = [37,38,39,40,8,9,13,32,35,36,45,62,63,126,33,64,35,36,37,94,60,38,42,40,41,95,43,123,125,124,58,34];
function checkMik(e){ //check if heb is wanted
 try {heb = top.mainindex.document.searchForm.heb.value;}
 catch (e2) {heb=0;}
 elem  = (nn6) ? e.target : event.srcElement;
 coder = (nn6) ? e.charCode  : event.keyCode;
 coder2= (nn6) ? e.keyCode : 0;
if (heb=='1' && !in_array(coder, exclude) && coder2==0)
 if (elem.type == 'text' || elem.tagName == 'TEXTAREA') {
  getCaretPositions(elem);
  elem.id = elem.name;
  keyb_change(elem.id, true);
  if (nn6)
   return translate(e);
  else
   return translate(event);
 }
}

function showKey(fold) { //toggle show/hide keyboard
 if (nn6) {winW = window.innerWidth; winH = window.innerHeight;}
 if (ie)  {winW = document.body.offsetWidth; winH = document.body.offsetHeight;}
 if ((top.mainindex.getIt('keyShow').innerHTML=="הצג מקלדת") && (fold!=false)) {
  if (getIt('keyboard').innerHTML=="") keyb_change('KeyID', true);
  getIt('KeyIDDiv').style.top = (winH) - 145 - 5 - 25 + "px";
  getIt('KeyIDDiv').style.left= (winW)/2 - 442/2  + "px";
  getIt('keyboard').style.visibility='visible';
  getIt('KeyIDDiv').style.display='block';
  top.mainindex.getIt('keyShow').innerHTML = "הסתר מקלדת";
 }
 else {
  getIt('KeyIDDiv').style.display='none';
  getIt('keyboard').style.visibility='hidden';
  top.mainindex.getIt('keyShow').innerHTML = "הצג מקלדת";
 }
}
// Mikledet end
///////////////
// IM start
var xIval="";
var activeid="";

function beep() {}
function notify() {}

function instM(id, name) { //Set IM Div (friend's id, friend's name)
 if (id==activeid) return;
 try {
  if (id == top.mainindex.messanger.document.statusmsgform.myid.value)
   return;
 } catch (e) {}
 if (!mainindex.main.checkLogged(6)) return;
 clearInterval(xIval);
 if (nn6) {winW = window.innerWidth; winH = window.innerHeight;}
 if (ie)  {winW = document.body.offsetWidth; winH = document.body.offsetHeight;}
 obj = getIt('messageDiv');
 obj.style.display='none';
 getIt('messageTitle').innerHTML="&nbsp;<img src='icon/imsgg.gif' align=absmiddle> "+name+"&nbsp;";
 getIt('messageImg').innerHTML="<img src='u/"+id+"/width=35&cutheight=28'>";
 document.messageForm.friend.value=id;
 obj.style.top=winH-238;
 obj.style.display='block';
 document.messageForm.mytext.focus();
 loadIM(id);
 xIval = setInterval('loadIM('+id+')', 1000);
 activeid=id;
}

function clearMsg() { //Unset IM Div
 clearInterval(xIval);
 getIt('messageDiv').style.display='none';
 activeid="";
}

var ajax=Array();
function load(url, target) {
 getIt(target).innerHTML = "<div style='background:white'><img src='icon/loadinggreen.gif'></div>";
 if (window.ActiveXObject || window.XMLHttpRequest) {
   ajax[target]=(window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
   ajax[target].onreadystatechange = function () {
     if (ajax[target].readyState == 4) loadExec(target);
   };
 }
 else if (document.implementation && document.implementation.createDocument) {
   ajax[target]=document.implementation.createDocument("","",null);
   ajax[target].onload=function(){loadExec(target)};
 }
 else {return;}

 try{ajax[target].async=true;}catch(e){}
 try {
  ajax[target].load(url);
 } catch (e) {
  ajax[target].open("GET",url,true);
  ajax[target].send(null);
 }
}

function loadExec(target) {
 getIt(target).innerHTML =
  (ajax[target].readyState==4 && ajax[target].status==200) ? ajax[target].responseText : "";
  //if (ajax[target].responseText==undefined)  alert(ajax[target]);
 ajax[target]=null;
}

 var xmlDocIM;
function loadIM(id) { //load xml chat history (friend's id)
 if (window.ActiveXObject || window.XMLHttpRequest) {
   xmlDocIM=(window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLDOM");
   xmlDocIM.onreadystatechange = function () {
    try {
     if (xmlDocIM.readyState == 4) getIMmessage(id);
    } catch(e) {}
   };
 }
 else if (document.implementation && document.implementation.createDocument) {
   xmlDocIM=document.implementation.createDocument("","",null);
   xmlDocIM.onload=function(){getIMmessage(id)};
 }
 else {
  getIt("innerMessage").innerHTML = "<center><br><br><b>הדפדפן שלך לא תומך באופציה זו.</b></center>";
  return;
 }

 xmlDocIM.async=true;
 try {
  xmlDocIM.load("imdata.php?friend="+id);
 } catch (e) {
  xmlDocIM.open("GET","imdata.php?friend="+id,true);
  xmlDocIM.send(null);
 }
}

function getIMmessage(id) { // Do IM
 if (window.XMLHttpRequest)
  try {xmlDocIM = xmlDocIM.responseXML;} catch(e){}
 try{
  text = xmlDocIM.getElementsByTagName("text")[0].childNodes[0].nodeValue;
  lastup = xmlDocIM.getElementsByTagName("lastup")[0].childNodes[0].nodeValue;
 } catch(e) {
  text = "<center><span style='color:red'><br><br><b>קיימים קשיים ביצירת התקשורת.<br><br>מנסה שוב...</b></span>";
  lastup = "connErr";
 }
 innerObj = getIt("innerMessage");
 if (document.messageForm.lastup.value != lastup) {
  innerObj.innerHTML = text;
  document.messageForm.lastup.value = lastup;
  beep();
  setTimeout("innerObj.scrollTop=innerObj.scrollHeight",40);
 }
}

function sendmsgimg() {
 if (getIt("innerMessage").innerHTML.indexOf("שולח...")==-1 &&
     getIt("innerMessage").innerHTML.indexOf("רק חברים יכולים ליצור קשר בדרך זו")==-1)
     {
  getIt("innerMessage").innerHTML+="<span class=light><img src='icon/grayAjax.gif'> שולח...</span>";
  getIt("innerMessage").scrollTop = getIt("innerMessage").scrollHeight+20;
 }
}
// IM end
////////////
// Map start
function markback(id) { //Put arrow on map
 xy = (true) ? getIt('area'+id).coords : getIt('area'+id).xy;
 xy = xy.split(',');
 aLeft= parseInt(xy[0]);
 aTop = parseInt(xy[1]);
 aWidth = parseInt(xy[2]) - parseInt(xy[0]);
 aHeight= parseInt(xy[3]) - parseInt(xy[1]);

 if      (getIt('mapDiv').scrollTop > aTop)   return;
 else if (getIt('mapDiv').scrollTop  + parseInt(getIt('mapDiv').style.height) < aTop)  return;
 else if (getIt('mapDiv').scrollLeft > aLeft) return;
 else if (getIt('mapDiv').scrollLeft + parseInt(getIt('mapDiv').style.width)  < aLeft) return;

 else { // in map limit
  aTop += 20 + 6  - getIt('mapDiv').scrollTop;  // 25,20 = image x,y
  aLeft+= 25 - 12 - getIt('mapDiv').scrollLeft; // 12 half img width
  getIt('markbackArrow').style.top = document.body.scrollTop + aTop +(aHeight / 2);
  getIt('markbackArrow').style.left= document.body.scrollLeft + aLeft+(aWidth / 2);
  show('markbackArrow');
 }
}

function unmarkback() { //Remove arrow
 try {
  hide('markbackArrow');
 } catch(e) {}
}

var tCountry = undefined, tRatio = undefined;
function toggleMap(country, ratio) { //toggle show/hide map
 try {
  if (country != undefined) {
   tCountry = country;
   tRatio   = ratio;
  }
  if (getIt('mapTR').style.display=='none') {
   getIt('mapTR').style.display = '';
   getIt('mapbotTR').style.display = '';
   if (tCountry != undefined)
    mapTo(tCountry, tRatio);
   getIt('mapXBut').value = "_";
  }
  else {
   getIt('mapTR').style.display = 'none';
   getIt('mapbotTR').style.display = 'none';
   getIt('mapXBut').value = " ";
  }
 }
 catch(e) {}
}

function tipkb(ev) { //tooltip for keyboard botton
 try {
  doTooltipAsIs(ev,"בלחיצה על 'מקלדת עברית',<br>כל טקסט שיכתב על ידכם באתר, יכתב בעברית<br>ללא קשר לשפה במחשב.");
 }
 catch(e){}
}

function markit(id,city,ev) { //mark text + do tooltip onmouseover map
 try {
  pos  = getIt('area'+id).href.indexOf("_");
  pos2 = getIt('area'+id).href.indexOf("il/");
  country = getIt('area'+id).href.substring(pos2+3, pos).replace("-"," ");
  doTooltipAsIs(ev,"<img src='flags/"+country+"'> "+city);
  getIt('city_'+id).className = 'locsSelected';
 }
 catch(e){}
}

function unmark(id) { // remove mark + tooltip onmouseout map
 try{
  hideTip();
  getIt('city_'+id).className = 'locs';
 }
 catch(e){}
}

function mapTo(where, ratio) { // move map to specific country
switch (where){
 case 'Argentina':toTop=700; toLeft = 220; break;
 case 'Chile':    toTop=700; toLeft = 150; break;
 case 'Brazil':   toTop=300; toLeft = 510; break;
 case 'Bolivia':  toTop=390; toLeft = 225; break;
 case 'Peru':     toTop=210; toLeft = 000; break;
 case 'Colombia': toTop=000; toLeft = 040; break;
 case 'Ecuador':  toTop=200; toLeft = 000; break;
 case 'Venezuela':toTop=000; toLeft = 140; break;
 case 'Uruguay':  toTop=760; toLeft = 400; break;
 case 'Paraguay': toTop=570; toLeft = 350; break;

 case 'Panama':      toTop=1050;toLeft = 810; break;
 case 'Costa Rica':  toTop=920; toLeft = 545; break;
 case 'Nicaragua':   toTop=630; toLeft = 485; break;
 case 'Honduras':    toTop=460; toLeft = 335; break;
 case 'Belize':      toTop=290; toLeft = 315; break;
 case 'El Salvador': toTop=620; toLeft = 240; break;
 case 'Guatemala':   toTop=325; toLeft = 070; break;
 case 'Mexico':      toTop=035; toLeft = 160; break;

 default:         toTop=0;   toLeft = 0;
}
 toTop*=ratio; toLeft*=ratio;
 getIt('mapDiv').scrollTop = toTop;
 getIt('mapDiv').scrollLeft = toLeft;
}

var t;
function moveIt(whereTo) { //set timer of map scroller
 t = setInterval("moveItTimed('"+whereTo+"')",150);
}

function stopMove() { //unset timer of map scroller
 clearInterval(t);
}

function moveItTimed(whereTo) { //move map 15px
 y = getIt('mapDiv').scrollTop;
 x = getIt('mapDiv').scrollLeft;
 if ((whereTo=='down') || (whereTo=='up'))
  getIt('mapDiv').scrollTop = (whereTo=='down') ? y+15 : y-15;
 else if ((whereTo=='right') || (whereTo=='left'))
  getIt('mapDiv').scrollLeft = (whereTo=='right') ? x+15 : x-15;
}

function setLocationsWidth() {
 winW = (nn6) ? window.innerWidth : document.body.offsetWidth;
 width = winW - parseInt(getIt('mapDiv').style.width) - 78;
 try {
  getIt('citiesDiv').style.width = width;
  getIt('pediaDiv').style.width = width;
  getIt('usefulDiv').style.width = width;
 }
 catch(e){}
}
// Map end
/////////////////
//Drap&Drop start
var isdrag=false;
var ddx,ddy;
var dobj, fobj;

function movemouseMove(e) { // move object
 if (isdrag) {
  dobj.style.left = nn6 ? tx + e.clientX - ddx : tx + event.clientX - ddx;
  dobj.style.top  = nn6 ? ty + e.clientY - ddy : ty + event.clientY - ddy;
  return false;
 }
}

function movemouseScroll(e) { // move object
 if (isdrag) {
  dobj.scrollLeft = nn6 ? tx - e.clientX + ddx : tx - event.clientX + ddx;
  dobj.scrollTop  = nn6 ? ty - e.clientY + ddy : ty - event.clientY + ddy;
  return false;
 }
}

function movemouseResize(e) { // resize object
 if (isdrag) {
  try {
   dobj.style.width  = nn6 ? Math.max(0, tx+e.clientX-ddx) : Math.max(0, tx+event.clientX-ddx);
   dobj.style.height = nn6 ? Math.max(1, ty+e.clientY-ddy) : Math.max(1, ty+event.clientY-ddy);
   getIt('mapTable').style.width = '';
  } catch(e){}
  return false;
 }
}

function selectmouse(e) { // onmousedown - decide move/resize and set values for action
 var topelement = nn6 ? "HTML" : "BODY";
 fobj = nn6 ? e.target : event.srcElement;
 while (fobj.tagName != topelement && fobj.className != "mapDiv" && fobj.className != "moveMsg" &&
        fobj.className != "moveMe" && fobj.className != "ddarrow") {
  fobj = nn6 ? fobj.parentNode : fobj.parentElement;
 }
 if (fobj.className=="mapDiv") { // scroll object
  isdrag = true;
  dobj = fobj;
  tx = parseInt(dobj.scrollLeft+0,10);
  ty = parseInt(dobj.scrollTop+0,10);
  ddx = nn6 ? e.clientX : event.clientX;
  ddy = nn6 ? e.clientY : event.clientY;
  dobj.style.filter='Alpha(opacity=50)';
  dobj.style.opacity='.5';
  document.onmousemove=movemouseScroll;
  return false;
 }
 else if ((fobj.className=="moveMe") || (fobj.className=="moveMsg")) { // move object
  isdrag = true;
  dobj = (fobj.className=="moveMe") ? fobj : getIt('messageDiv');
  tx = parseInt(dobj.style.left,10);
  ty = parseInt(dobj.style.top, 10);
  ddx = nn6 ? e.clientX : event.clientX;
  ddy = nn6 ? e.clientY : event.clientY;
  document.onmousemove=movemouseMove;
  return false;
 }
 else if (fobj.className=="ddarrow") { // resize object
  isdrag = true;
  dobj = getIt('mapDiv');
  tx = parseInt(dobj.style.width+0,10);
  ty = parseInt(dobj.style.height+0,10);
  ddx = nn6 ? e.clientX : event.clientX;
  ddy = nn6 ? e.clientY : event.clientY;
  document.onmousemove=movemouseResize;
  return false;
 }
}

function stopdrag() { //onmouseup
 isdrag=false;
 if (dobj) {
  dobj.style.filter='';
  dobj.style.opacity='';
 }
 try {
  if (fobj.className=="ddarrow")
   setLocationsWidth();
 }catch(e){}
 document.onmousemove=function(ev){try{if(tipFollowMouse)trackMouse(ev);}catch(e){}};
}

document.onmousedown=selectmouse;
document.onmouseup=stopdrag;
// Drag&Drop end
// Gallery start
 var galDiv = undefined;
 var galWid, galScr;
 var pager = 1;
 var scrollTmr;
 function scrollGallery(page) {
  galWid = parseInt(galDiv.style.width);
  galScr = parseInt(galDiv.scrollWidth);
  var scrollTo = Math.max(0, galScr - page * galWid);
  if (scrollTo==0) pager = Math.ceil(galScr / galWid);
  else if (scrollTo >= galScr) pager = 1;
  else pager = page;
  getIt('right').style.visibility = (pager>=2) ? '' : 'hidden';
  getIt('left').style.visibility  = (scrollTo>0) ? '' : 'hidden';
  scrollTmr = setInterval("scrollTo(galDiv, galScr-pager*galWid)", 30);
  setTimeout("clearInterval(scrollTmr); loadImages()",1000);
  return false;
 }

 function scrollTo(mio, scroll){
  current = parseInt(mio.scrollLeft) - scroll;
  width = Math.min(30, Math.abs(current));
  if (current > 0) {
    mio.scrollLeft = parseInt(mio.scrollLeft) - width;
  } else if (current < 0) {
    mio.scrollLeft = parseInt(mio.scrollLeft) + width;
  } else {
   clearInterval(scrollTmr);
   loadImages();
  }
 }

 function testImageX(img) {
  if(document.documentElement["getBoundingClientRect"]){
   bound=img.getBoundingClientRect();
   if (bound.right<0)
   return;
  }
  img.src=img.getAttribute('thumb');
  img.removeAttribute('thumb');
 }

 function loadImages() {
  var imgs=document.getElementsByTagName('IMG');
  for(var x=0;x<imgs.length;++x) {
   if(imgs[x].getAttribute('thumb'))
    testImageX(imgs[x]);
  }
 }

 function initNav() {
  galWid = parseInt(galDiv.style.width);
  galScr = parseInt(galDiv.scrollWidth);
  if (galScr > galWid) {
   getIt('leftnav').innerHTML = "<span onclick='scrollGallery(pager+1)' id=left class=hand><img onmouseover=\"this.src='icon/left2.png'\" onmouseout=\"this.src='icon/left.png'\" src='icon/left.png'></span>";
   getIt('rightnav').innerHTML = "<span onclick='scrollGallery(pager-1)' id=right style='visibility:hidden' class=hand><img onmouseover=\"this.src='icon/right2.png'\" onmouseout=\"this.src='icon/right.png'\" src='icon/right.png'></span>";
  }
 }

var cpvobj=null;
function hPVTO(height) {
 var ch;
 if (cpvobj==null) return;
 ch=20+cpvobj.offsetHeight;
 cpvobj.style.height=ch;
 if (ch>=160) cpvobj=null;
 setTimeout(hPVTO,10);
}

function hPV(id, url) {
 var obj=getIt("PV"+id);
 if (obj.style.display=="") {obj.style.display="none"; return false;}
 if (cpvobj!=null) cpvobj.style.height=160;
 cpvobj=obj;
 obj.style.display="";
 obj.style.height=25;
 obj.style.width="99%";
 obj.style.border="1px solid green";
 obj.style.overflow="hidden";
 obj.innerHTML='<iframe id='+id+' align=center frameborder=0 width=100% height=100% src="'+url+'"></iframe>';
 setTimeout(hPVTO,10);
 return false;
}
// Gallery end

var what = Array ("name", "engname", "price", "mail", "doubleprice", "address", "phone");
var edited=0;
var isOpened = Array();
var isHostel = Array();
var changedMade=false;

function topUsers() {
top.alerter(
'ניקוד באתר','על כל תרומה של משתמש לאתר, הוא יקבל ניקוד על-פי הערכים הבאים:<br><br>1. הוספת אתר חדש - 5 נקודות<br>2. עדכון מידע באתר קיים - 3 נקודות<br>3. הוספת בלוג - 2 נקודות<br>4. כל מידע אחר (הוספת תמונה, דירוג אתרים, הודעה בפורום) - נקודה אחת<br><br>חמשת המשתמשים שתרמו באופן הניכר ביותר, בצורה כזו או אחרת לקהילת המטיילים של טודוס, <br>יוצגו בדף הראשי כתורמים ביותר, והסמל הזה יופיע לצד שמם: <img src=icon/topusers.png><br><br>על פי מערכת הניקוד הזו, תוכלו לדעת מי המשתמשים שתרמו לקהילה. אולי טיפ שלהם יעזור גם בטיול שלכם...','./images/thumb.php?id=0&height=50');
}

function checkPass() {
 if (document.update.passworder.value.length<5) {
  alert("סיסמה קצרה מדי - מינימום חמישה תווים.\nMinimun of 5 chars for password");
  return false;
  document.update.passworder.focus();
 }
 return true;
}

function selectChange() { //select onchange - add citydetails
 document.getElementById('addDiv').style.display='inline';
 selector = document.getElementById('addSelect');
 document.getElementById('details1').style.display = (selector.selectedIndex==0) ? 'inline': 'none';
 document.getElementById('addTitle').innerHTML=selector.options[selector.selectedIndex].text;
 switch (selector.selectedIndex){
  case 0: price="מחיר בחדר משותף"; dprice="מחיר בחדר זוגי"; break;
  case 1: price="מחיר ממוצע לאדם"; dprice=false;            break;
  case 2: price="מחיר"; dprice=false; break;
  case 3: case 4: price="מחיר"; dprice="ציוד נדרש"; break;
  default: price="מחיר"; dprice="מחיר כפול";
 }
 document.getElementById('addPrice').innerHTML = price;
 if (dprice) {
  document.getElementById('addDPrice').innerHTML=dprice;
  document.getElementById('addDPriceTX').style.visibility='visible';
 } else {
  document.getElementById('addDPrice').innerHTML="";
  document.getElementById('addDPriceTX').style.visibility='hidden';
 }
 try {document.body.scrollTop = document.body.scrollHeight;}
 catch(e) {}
}

function changes() {
 changedMade=true;
 document.getElementById('submitTR').style.display='inline';
}
function changesSaved() {
 changedMade=false;
 document.getElementById('submitTR').style.display='none';
}

function toggleAddCD() {
 if (document.getElementById('addDiv').style.display=='none') {
  if (parent.checkLogged(7)) selectChange();
 }
 else document.getElementById('addDiv').style.display='none';
}

function checkDontwarry() {
 stMsg="";
 if (document.update.dontwarryHidden.value.indexOf("<"+document.update.dontwarryMail.value+">")!=-1)
  stMsg = "האימייל כבר קיים ברשימה\n";
 filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
 if (!filter.test(document.update.dontwarryMail.value)) stMsg += "כתובת האימייל לא תקינה\n";
 if (stMsg!="") {alert(stMsg); return false;}
 return true;
}

function toggleUpdate(id) {
 document.getElementById('updateTR'+id).style.display = (document.getElementById('updateTR'+id).style.display=='none') ? "block" : "none";
}

function addDontwarry() {
 if (!checkDontwarry()) return;
 namer = document.update.dontwarryName.value.replace("'","");
 namer = namer.replace('"',''); namer = namer.replace(";","");
 namer = namer.replace(",","-");
 document.update.dontwarryHidden.value += namer + " <" + document.update.dontwarryMail.value + ">,";
 document.getElementById('dontwarryText').innerHTML+="<span id='" + document.update.dontwarryMail.value + "'><img title='הסר' hspace=5 height=12 class=hand src='clear.gif' onclick='removeDontwarry(\"" + document.update.dontwarryMail.value + "\");'> <span dir=rtl>" + namer + "</span> <span dir=ltr>&lt;" + document.update.dontwarryMail.value + "&gt;</span><br></span>";
 document.update.dontwarryMail.value = "";
 document.update.dontwarryName.value = "";
 changes();
}

function removeDontwarry(id) {
 temp = document.update.dontwarryHidden.value;
 temp = temp.substring(0,temp.length-1);
 temp = temp.split(",");
 newTemp="";
 for (i=0; i<temp.length; i++) {
  if (temp[i].indexOf("<"+id+">")==-1) newTemp+=temp[i]+",";
 }
 document.update.dontwarryHidden.value = newTemp;
 document.getElementById('dontwarryText').removeChild(document.getElementById(id));
 changes();
}

function changeSex(){
 document.getElementById('seximg').src='sex'+document.update.sex[document.update.sex.selectedIndex].value+'.gif';
}

function report(id) {
 top.alerter("דיווח על תוכן לא מתאים", "כאן תוכלו לדווח על תוכן לא מתאים:<form action='sqlactions.php' method=post target=updater onsubmit='if (this.reportText.value.length==0) {alert(\"לא ניתן לשלוח הודעה ריקה\"); return false;}'><input type=hidden value='"+id+"' name=id><b>מדוע התוכן אינו מתאים?<br>&nbsp;&nbsp;<select name=reportSelect><option value='תוכן לא נכון'>תוכן לא נכון</option><option value='תוכן מוגן בזכויות יוצרים'>תוכן מוגן בזכויות יוצרים</option><option value='תמונה לא מתאימה'>תמונה לא מתאימה</option><option value='תוכן מטריד'>תוכן מטריד</option></select><br>טקסט חופשי:</b><br>&nbsp;&nbsp;<input size=40 name=reportText class=text><br><input type=submit value='שלח הודעה'></form>", "./images/thumb.php?id=1&height=40");
}

function reportAlbum(id, type) {
 parent.parent.alerter("דיווח על תמונה לא מתאימה", "<form action='sqlactions.php' method=post target=updater><input type=hidden value='"+id+"' name=id><input type=hidden value='"+type+"' name=type><b>מדוע התמונה אינה מתאימה?<br>&nbsp;&nbsp;<select name=reportAlbum><option value='תמונה מטרידה'>תמונה מטרידה</option><option value='תמונה מוגנת בזכויות יוצרים'>תמונה מוגנת בזכויות יוצרים</option></select><br>התמונה הלא מתאימה:</b><br>&nbsp;&nbsp;<input size=40 name=reportText class=text><br><input type=submit value='שלח הודעה'></form>", "./images/thumb.php?id=1&height=40");
}

function reportVideo(video) {
 parent.parent.alerter("דיווח על וידאו לא מתאים", "<form action='sqlactions.php' method=post target=updater><input type=hidden value='"+video+"' name=video><b>מדוע הוידאו לא מתאים?<br>&nbsp;&nbsp;<select name=reportVideo><option value='וידאו מטריד'>וידאו מטריד</option><option value='וידאו מוגן בזכויות יוצרים'>וידאו מוכן בזכויות יוצרים</option></select></b><br>&nbsp;&nbsp;<input size=40 name=reportText class=text><br><input type=submit value='שלח הודעה'></form>", "./images/thumb.php?id=1&height=40");
}

function editDesc(id, desc) {
 parent.parent.alerter("שינוי תיאור", "<form action='sqlactions.php' method=post target=updater name=editForm><b>תיאור התמונה:</b><input type=hidden value='"+id+"' name=editGalPic>&nbsp;<input size=40 name=picText class=text value=\""+desc+"\"><br><input type=submit value='שנה תיאור'></form>", "thumb.php?id=1&height=40");
}

function setStars(x,id) {
 if (!checkLogged(4)) return;
 parent.updater.location = "sqlactions.php?stars=" + x + "&id=" + id;
}

function showStars(x,id) {
for (i=1; i<=5; i++) {
 if (x>4.7) src='stargreen.gif';
  else if (i-0.3 <= x) src='starred.gif';
   else if (i-0.7 <= x) src='starhalf.gif';
    else src='starempty.gif';
 document.getElementById("star"+i+"-"+id).src = 'icon/'+src;
 }
document.getElementById('rank'+id).innerHTML = "(" + x.toFixed(1) + ")";
}

function openIFrame(x, filename) {
 height = (filename=='rankers') ? 75 : 135;
 temp = "<a href='javascript:clearDetails(" + x + ");'><img src='icon/leftarrowcyan.png' hspace=2>סגירת פרטים</a><br>";
 temp +=  "<iframe ALLOWTRANSPARENCY='true' src='"+filename+".php?id=" +x + "' frameborder=0 width=100% height="+height+" SCROLLING=yes></iframe>";
 document.getElementById("details"+x).innerHTML = temp;
 document.getElementById("detailstable"+x).style.borderBottom = "2px solid #DDDDFF";
}

function gallery(x,type) {
 if (typeof type=='undefined') type='citydetails';
 temp = "<a href=\"javascript:clearDetails('"+x+"');\"><img src='icon/leftarrowcyan.png' hspace=2>סגירת גלריה</a><br>";
 temp+= "<iframe name=gal"+x+" ALLOWTRANSPARENCY='true' src='gallery.php?typeid="+x+"&type="+type+"' frameborder=0 width=100% height=160 SCROLLING=no></iframe>";
 document.getElementById("details"+x).innerHTML = temp;
 document.getElementById("detailstable"+x).style.borderBottom = "2px solid #DDDDFF";
 isOpened[x]=0;
}

function streetMap(x) {
 if (typeof type=='undefined') type='citydetails';
 temp = "<a href=\"javascript:clearDetails('"+x+"');\"><img src='icon/leftarrowcyan.png' hspace=2>סגירת מפה</a><br>";
 temp+= "<iframe ALLOWTRANSPARENCY='true' src='streetMap.php?id="+x+"' frameborder=0 width=100% height=300 SCROLLING=no></iframe>";
 document.getElementById("details"+x).innerHTML = temp;
 document.getElementById("detailstable"+x).style.borderBottom = "2px solid #DDDDFF";
 isOpened[x]=0;
}

function weather(x,i) {
 temp = "<iframe src='weather.php?id="+x+"&all="+i+"' id=weatherFrame frameborder=0 width=100% height=240 SCROLLING=YES></iframe>";
 document.getElementById("topcityIframe").innerHTML = temp;
 cityMenu("topcityIframe");
 document.getElementById("uploadGal").style.display='none';
}

function cityMap(x) {
 temp = "<iframe src='streetMap.php?city="+x+"' id=streetFrame frameborder=0 width=100% height=300 SCROLLING=NO></iframe>";
 document.getElementById("topcityIframe").innerHTML = temp;
 cityMenu("topcityIframe");
 document.getElementById("uploadGal").style.display='none';
}

function transport(x) {
 temp = "<iframe src='transport.php?id="+x+"' id=transportFrame frameborder=0 width=100% height=240 SCROLLING=YES></iframe>";
 document.getElementById("topcityIframe").innerHTML = temp;
 cityMenu("topcityIframe");
 document.getElementById("uploadGal").style.display='none';
}

function cityGallery(x) {
 temp = "<iframe src='gallery.php?typeid="+x+"&type=city' id=cgal"+x+" name=cgal"+x+" frameborder=0 width=100% height=235 SCROLLING=NO></iframe>";
 document.getElementById("topcityIframe").innerHTML = temp;
 cityMenu("topcityIframe");
 document.getElementById("uploadGal").style.display='';
}

function cityMenu(id) {
 cityMenuArray = new Array("text","pedia","topcityIframe");
 for (i=0; i<cityMenuArray.length; i++)
  document.getElementById(cityMenuArray[i]).style.display = (cityMenuArray[i]==id) ? '' : 'none';
 if (id!="topcityIframe")
  document.getElementById("uploadGal").style.display='none';
}

function checkboxreturn(x) { if (x==edited || x==1) return true; else return false; }

var detailsarrayheb = new Array("מים חמים", "אינטרנט בתשלום", "אינטרנט חינם", "בריכת שחיה", "מסעדה", "באר", "שרותי כביסה", "שרותי תיירות", "לוקרים", "מטבח", "ארוחת בוקר", "א.בוקר בתשלום", "טלויזיה", "שמירת חפצים", "דוברי אנגלית", "דוברי עברית", "<font color=orange><b>רשת HI</b></font>");

function citydetails(x,details,editer) {
 if (editer != 0) {
  citydetailsEdit(x, details);
  return;
 }
 document.getElementById("details"+x).innerHTML = "<img src='loadingblue.gif'>";
 tempdetails=new Array();
 temp = "<a href='javascript:clearDetails(" + x + ");'><img src='icon/leftarrowcyan.png' hspace=2>סגירת פרטים</a><br>";
 temp += "<table><tr><td class=value>";
 for (i=0; i<detailsarrayheb.length; i++) {
  if (details.indexOf(i+10) != -1) tempdetails.push(detailsarrayheb[i]);
 }
 for (i=0; i<tempdetails.length; i++) {
  temp += "<li>" + tempdetails[i] + "</li>";
  if ((i == Math.floor(tempdetails.length / 2)) && (i>1)) temp+="</td><td valign=top class=value>"
 }
 if (tempdetails.length == 0) temp+="אין פרטים נוספים על המקום";
 temp += "</td></tr></table>";
 document.getElementById("details"+x).innerHTML = temp;
 document.getElementById("detailstable"+x).style.borderBottom = "2px solid #DDDDFF";
}

function citydetailsEdit(x, details) {
 temp="";
 if (x!=1) temp = "<a href='javascript:clearDetails(" + x + ");'><img src='icon/leftarrowcyan.png' hspace=2>סגירת פרטים</a><br>";
 temp += "<table><tr>";
 for (i=0; i<detailsarrayheb.length; i++) {
 y = i+10;
 if (details.indexOf(i+10) != -1) checked="checked"; else checked="";
   temp +=  "<td><label onfocus='blur()' class=value onclick='return checkboxreturn("+x+")' for='checkbox[" + x + "," + i + "]'><input type=checkbox " + checked + " id='checkbox[" + x + "," + i + "]' name='checkbox-"+x+'-'+y+"' class=checkbox value=" + y + "> " + detailsarrayheb[i] + "</label></td>";
   if ((i+1) % 7 == 0) temp += "</tr><tr>";
 }
 temp += "</tr></table>";
 if (x==1) document.getElementById("details"+x).innerHTML = temp;
 else {
  document.getElementById("details"+x).innerHTML = temp;
  document.getElementById("detailstable"+x).style.borderBottom = "2px solid #DDDDFF";
 }
}

function clearDetails(x) {
 document.getElementById("details"+x).innerHTML = " ";
 document.getElementById("detailstable"+x).style.borderBottom = "2px dashed #DDDDFF";
 isOpened[x]=0;
}

function flag(idname) {
 flager = (((document.getElementById("flag"+idname).value)==1) ? 0 : 1);
 document.getElementById("flag"+idname).value=flager;
 document.getElementById("flag"+idname).src = "icon/flag"+flager+".gif";
 parent.updater.location="sqlactions.php?id="+idname+"&flag="+flager;
}

function unread(idname) {
 flager = (document.getElementById("unread"+idname).border==1) ? 0 : 1;
 document.getElementById("unread"+idname).border=flager;
 document.getElementById("unread"+idname).src = "icon/read"+flager+".gif";
 document.getElementById("item"+idname).style.fontWeight = (flager==0) ? 'bold' : '';
 document.getElementById("item"+idname).style.backgroundColor = (flager==0) ? '#EEEEFF' : '#FAFAFF';
 parent.updater.location="sqlactions.php?id="+idname+"&unread="+flager;
}

function delItem(idname, sent) {
 if (confirm('האם למחוק את ההודעה?'))
  parent.updater.location='sqlactions.php?sent='+sent+'&cbhide='+idname+'-';
}

function Edit(i,doDetails) {
 isHostel[i] = (doDetails) ? true : false;
 if (edited>0) {
   if (approveEdit(edited)) {setTimeout('Editor('+i+')', 200);}
 } else {setTimeout('Editor('+i+')', 200);}
}

function editCity() {
 document.getElementById('citydescription').innerHTML = '<textarea class=textarea rows=5 cols=90 name=description>' + document.getElementById('citydescription').innerHTML + '</textarea>';
 //document.getElementById('citywebsite').innerHTML = '<input dir=ltr class=text size=30 name=website value="' + document.getElementById('citywebsite').innerHTML + '">';
 document.getElementById('cityname').innerHTML = '<input class=text size=12 name=cityname value="' + document.getElementById('cityname').innerHTML + '">';
 //document.getElementById('cityengname').innerHTML = '<input dir=ltr class=text size=12 name=cityengname value="' + document.getElementById('cityengname').innerHTML + '">';
 document.getElementById('editCityButton').style.display = 'none';
 document.getElementById('editCityButtonSub').style.display = 'block';
}

function checkLogged(msg) {
 try {var logged = top.mainindex.messanger.document.statusmsgform.myid.value;}
 catch (e) {
  try {var logged = top.mainindex.messanger.document.statusmsgform.myid.value;}
  catch (e) {}
 }
 if (logged==0) {
  switch(msg) {
   case 1:  message = "לעדכן את הפרטים"; break;
   case 2:  message = "להעלות תמונות"; break;
   case 3:  message = "לכתוב בפורום"; break;
   case 4:  message = "לדרג"; break;
   case 5:  message = "להוסיף/לעדכן הערות"; break;
   case 6:  message = "לשלוח הודעה מיידית"; break;
   case 7:  message = "להוסיף אתר"; break;
   case 8:  message = "להוסיף כתבות"; break;
   case 9:  message = "לשלוח הודעה"; break;
  default: message="";
  }
  if (message!="") top.alerter("תקלה", "<nobr><big>על מנת "+message+" יש להתחבר/<a href=register.php target=main>להרשם.<br>ההרשמה חינם</a><br>משתמשי פייסבוק? לחצו על <img src='icon/loginFB.png'> מצד ימין להתחברות מהירה</big>", "./images/thumb.php?id=1&height=40");
  return false;
 }
 else return true;
}

function Editor(i) {
 if (!checkLogged(1)) return;
 for (j=0; j<what.length; j++) {
  if ((what[j] == "price") || (what[j] == "doubleprice")) sizer="size=8";
  else if ((what[j] == "name") || (what[j] == "engname")) sizer="size=25";
  else sizer="size=23";
  if (what[j] == "phone") document.getElementById('phone'+i).innerHTML = document.getElementById('hidPhone'+i).value; //anti skype add-in
  try {document.getElementById(what[j]+i).innerHTML = '<input class=text id='+what[j]+' name='+what[j]+' '+sizer+' value="' + document.getElementById(what[j]+i).innerHTML + '">';
  } catch(e) {}
}

 document.getElementById('description'+i).readOnly = false;
 document.getElementById('description'+i).className = 'textarea';
 web=document.getElementById('websiter'+i).innerHTML.replace("http://todos.co.il","");
 web=document.getElementById('websiter'+i).innerHTML.replace("http://www.todos.co.il","");
 document.getElementById('website'+i).innerHTML = '<input dir=ltr class=text size=23 id=website name=website value="' + web + '">';

 document.getElementById('update'+i).innerHTML = '<table cellpadding=0 cellspacing=0><tr align=center><td nowrap><a class=redlink href="javascript:Submiter('+i+');"><img src="approve.gif" height=20><br><b>אשרו עדכון</b></a>&nbsp</td><td><a href="javascript:resetFrom('+i+')" class=redlink><img src="approve0.gif" height=20><br><b>בטלו</b></a></td></tr></table>';

 if (isHostel[i]) openDetails(i,1);
 edited=i;
}

function resetFrom(i) {
 document['form'+i].reset();
 approveEdit(i);
}

function Submiter(i) {
 if (!checkLogged(1)) {
  resetFrom(i);
  return;
 }
 document['form'+i].submit();
 document.getElementById('update'+i).innerHTML = '<nobr><a onclick="Submiter('+i+');"><img src="loadingblue.gif" height=20 width=20><br><font color=blue><b>&nbspמעדכן...&nbsp</b></a>';
}

function AddCD() {
 if (!checkLogged(7)) return;
 if (!document['addform'].name.value) {alert('אין שם למיקום\nNo Name');return;}
 document['addform'].submit();
 document.getElementById('addtd').innerHTML = "<a onclick='AddCD()'><img src='loadinggreen.gif' height=20 width=20><br><font color=darkgreen><b>מוסיף...</b></a>";
}

function approveEdit(i) {
 document.getElementById('hidPhone'+i).value = document.getElementById('phone').value; //anti skype add-in
 document.getElementById('engname').value+=" ";
 for (j=0; j<what.length; j++) {
  try{document.getElementById(what[j]+i).innerHTML = document.getElementById(what[j]).value;}
  catch(e){}
 }
  document.getElementById('description'+i).readOnly = true;
  document.getElementById('description'+i).className = 'loctextarea';
  web = document.getElementById('website').value;
  if ((web.substr(0,7) != "http://") && (web.length>0)) {web="http://"+web;}
  document.getElementById('website'+i).innerHTML = '<a id=websiter'+i+' href="'+web+'" target=_blank>'+web+'</a>';
 if (document.getElementById('details'+i).innerHTML.indexOf("span") != -1) loadXML(i, 0);

 edited=0;
 if (isHostel[i]) openDetails(i,0);
// document.getElementById('update'+i).innerHTML = '<nobr><a href="javascript:Edit('+i+','+isHostel[i]+');"><img src=update.jpg height=20 width=20><br>עדכנו פרטים</a>';
 document.getElementById('update'+i).innerHTML = "<a class=like href=\"javascript:Edit("+i+","+isHostel[i]+");\"><span class=l1>&nbsp;</span><b class=bu>עדכנו פרטים</b><span class=l2>&nbsp;</span></a>";
 
 return true;
}

function details(x) {
 if (edited!=x) {
  try {
   if (isOpened[x]==1) {clearDetails(x);}
   else {openDetails(x, 0);}
  }
  catch(err) {
   openDetails(x, 0);
  }
 }
}

function openDetails(x, editer) {
 isOpened[x]=1;
 if (edited!=x) loadXML(x, editer);
}


/* JavaScript Virtual Keyboard (slim variant), version 2.6
 *
 * (C) 2006-2007 Dmitriy Khudorozhkov (mailto:kh_dmitry2001@mail.ru)
 *
 * This software is provided "as-is", without any express or implied warranty.
 * In no event will the author be held liable for any damages arising from the
 * use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 *
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 *
 * 3. This notice may not be removed or altered from any source distribution.
 */

function VKeyboard(container_id, callback_ref, create_arrows, create_updown,
                   create_nav_keys, create_numpad, font_name, font_size,
                   font_color, dead_color, bg_color, key_color,
                   sel_item_color, border_color, inactive_border_color,
                   inactive_key_color, lang_sel_brd_color, show_click,
                   click_font_color, click_bg_color, click_border_color,
                   do_embed, do_gap, start_layout_index)
{
  return this._construct(container_id, callback_ref, create_arrows, create_updown,
                         create_nav_keys, create_numpad, font_name, font_size,
                         font_color, dead_color, bg_color, key_color,
                         sel_item_color, border_color, inactive_border_color,
                         inactive_key_color, lang_sel_brd_color, show_click,
                         click_font_color, click_bg_color, click_border_color,
                         do_embed, do_gap, start_layout_index);
}

VKeyboard.kbArray = [];

VKeyboard.prototype = {

  _get_event_source: function(event)
  {
    var e = event || window.event;
    return e.srcElement || e.target;
  },

  _setup_event: function(elem, eventType, handler)
  {
    return (elem.attachEvent ? elem.attachEvent("on" + eventType, handler) : ((elem.addEventListener) ? elem.addEventListener(eventType, handler, false) : null));
  },

  _detach_event: function(elem, eventType, handler)
  {
    return (elem.detachEvent ? elem.detachEvent("on" + eventType, handler) : ((elem.removeEventListener) ? elem.removeEventListener(eventType, handler, false) : null));
  },

  _start_flash: function(in_el)
  {
    function getColor(str, posOne, posTwo)
    {
      if(/rgb\((\d+),\s(\d+),\s(\d+)\)/.exec(str)) // try to detect Mozilla-style rgb value.
      {
        switch(posOne)
        {
          case 1: return parseInt(RegExp.$1, 10);
          case 2: return parseInt(RegExp.$2, 10);
          case 3: return parseInt(RegExp.$3, 10);
          default: return 0;
        }
      }
      else // standard (#xxxxxx or #xxx) way
        return str.length == 4 ? parseInt(str.substr(posOne, 1) + str.substr(posOne, 1), 16) : parseInt(str.substr(posTwo, 2), 16);
    }

    function getR(color_string)
    { return getColor(color_string, 1, 1); }

    function getG(color_string)
    { return getColor(color_string, 2, 3); }

    function getB(color_string)
    { return getColor(color_string, 3, 5); }

    var el = in_el.time ? in_el : (in_el.company && in_el.company.time ? in_el.company : null);

    if(el)
    {
      el.time = 0;
      clearInterval(el.timer);
    }

    var vkb = this;
    var ftc = vkb.fontcolor, bgc = vkb.keycolor, brc = vkb.bordercolor;

    // Special fixes for simple/dead/modifier keys:

    if(in_el.dead)
      ftc = vkb.deadcolor;

    if(((in_el.innerHTML == "Shift") && vkb.Shift) || ((in_el.innerHTML == "Caps") && vkb.Caps) || ((in_el.innerHTML == "AltGr") && vkb.AltGr))
      bgc = vkb.lic;

    // Extract base color values:
    var fr = getR(ftc), fg = getG(ftc), fb = getB(ftc);
    var kr = getR(bgc), kg = getG(bgc), kb = getB(bgc);
    var br = getR(brc), bg = getG(brc), bb = getB(brc);

    // Extract flash color values:
    var f_r = getR(vkb.cfc), f_g = getG(vkb.cfc), f_b = getB(vkb.cfc);
    var k_r = getR(vkb.cbg), k_g = getG(vkb.cbg), k_b = getB(vkb.cbg);
    var b_r = getR(vkb.cbr), b_g = getG(vkb.cbr), b_b = getB(vkb.cbr);

    var _shift_colors = function()
    {
      function dec2hex(dec)
      {
        var hexChars = "0123456789ABCDEF";
        var a = dec % 16;
        var b = (dec - a) / 16;

        return hexChars.charAt(b) + hexChars.charAt(a) + "";
      }

      in_el.time = !in_el.time ? 10 : (in_el.time - 1);

      function calc_color(start, end)
      { return (end - (in_el.time / 10) * (end - start)); }

      var t_f_r = calc_color(f_r, fr), t_f_g = calc_color(f_g, fg), t_f_b = calc_color(f_b, fb);
      var t_k_r = calc_color(k_r, kr), t_k_g = calc_color(k_g, kg), t_k_b = calc_color(k_b, kb);
      var t_b_r = calc_color(b_r, br), t_b_g = calc_color(b_g, bg), t_b_b = calc_color(b_b, bb);

      function setStyles(style)
      {
        style.color = "#" + dec2hex(t_f_r) + dec2hex(t_f_g) + dec2hex(t_f_b);
        style.borderColor = "#" + dec2hex(t_b_r) + dec2hex(t_b_g) + dec2hex(t_b_b);
        style.backgroundColor = "#" + dec2hex(t_k_r) + dec2hex(t_k_g) + dec2hex(t_k_b);
      }

      var first = (in_el == vkb.mod[4]) ? false : true, is = in_el.style, cs = in_el.company ? in_el.company.style : null;

      if(cs && first)
        setStyles(cs);

      setStyles(is);

      if(cs)
      {
        if(!first)
        {
          setStyles(cs);
          is.borderBottomColor = "#" + dec2hex(t_k_r) + dec2hex(t_k_g) + dec2hex(t_k_b);
        }
        else
          cs.borderBottomColor = "#" + dec2hex(t_k_r) + dec2hex(t_k_g) + dec2hex(t_k_b);
      }

      if(!in_el.time)
      {
        clearInterval(in_el.timer);
        return;
      }
    };

    _shift_colors();

    in_el.timer = window.setInterval(_shift_colors, 50);
  },

  _setup_style: function(obj, top, left, width, height, position, text_align, line_height, font_size, font_weight, padding_left, padding_right)
  {
    var os = obj.style;

    if(top)    os.top = top;
    if(left)   os.left = left;
    if(width)  os.width = width;
    if(height) os.height = height;

    if(position) os.position = position;

    if(text_align)  os.textAlign  = text_align;
    if(line_height) os.lineHeight = line_height;
    if(font_size)   os.fontSize   = font_size;

    os.fontWeight = font_weight || "bold";

    if(padding_left)  os.paddingLeft  = padding_left;
    if(padding_right) os.paddingRight = padding_right;
  },

  _setup_key: function(parent, id, top, left, width, height, text_align, line_height, font_size, font_weight, padding_left, padding_right)
  {
    var _id = this.Cntr.id + id;
    var exists = document.getElementById(_id);

    var key = exists ? exists.parentNode : document.createElement("DIV");
    this._setup_style(key, top, left, width, height, "absolute");

    var key_sub = exists || document.createElement("DIV");
    key.appendChild(key_sub); parent.appendChild(key);

    this._setup_style(key_sub, "", "", "", line_height, "relative", text_align, line_height, font_size, font_weight, padding_left, padding_right);
    key_sub.id = _id;

    return key_sub;
  },

  _findX: function(obj)
  { return (obj && obj.parentNode) ? parseFloat(obj.parentNode.offsetLeft) : 0; },

  _findY: function(obj)
  { return (obj && obj.parentNode) ? parseFloat(obj.parentNode.offsetTop) : 0; },

  _findW: function(obj)
  { return (obj && obj.parentNode) ? parseFloat(obj.parentNode.offsetWidth) : 0; },

  _findH: function(obj)
  { return (obj && obj.parentNode) ? parseFloat(obj.parentNode.offsetHeight) : 0; },

  _construct: function(container_id, callback_ref, create_arrows, create_updown, create_nav_keys, create_numpad,
                       font_name, font_size, font_color, dead_color, bg_color, key_color, sel_item_color,
                       border_color, inactive_border_color, inactive_key_color, lang_sel_brd_color,
                       show_click, click_font_color, click_bg_color, click_border_color, do_embed,
                       do_gap, start_layout_index)
  {
    var exists  = (this.Cntr != undefined), ct = exists ? this.Cntr : document.getElementById(container_id);
    var changed = (font_size && (font_size != this.fontsize));

    this._Callback = ((typeof(callback_ref) == "function") && ((callback_ref.length == 1) || (callback_ref.length == 2))) ? callback_ref : (this._Callback || null);

    var ff = font_name || this.fontname || "";
    var fs = font_size || this.fontsize || "14px";

    var fc = font_color   || this.fontcolor   || "#000";
    var dc = dead_color   || this.deadcolor   || "#F00";
    var bg = bg_color     || this.bgcolor     || "#FFF";
    var kc = key_color    || this.keycolor    || "#FFF";
    var bc = border_color || this.bordercolor || "#777";

    this.fontname = ff, this.fontsize = fs, this.fontcolor = fc;
    this.bgcolor = bg,  this.keycolor = kc, this.deadcolor = dc, this.bordercolor = bc;

    this.lic = sel_item_color        || this.lic || "#DDD";
    this.ibc = inactive_border_color || this.ibc || "#CCC";
    this.ikc = inactive_key_color    || this.ikc || "#FFF";
    this.lsc = lang_sel_brd_color    || this.lsc || "#F77";

    this.cfc = click_font_color   || this.cfc || "#CC3300";
    this.cbg = click_bg_color     || this.cbg || "#FF9966";
    this.cbr = click_border_color || this.cbr || "#CC3300";

    this.sc = (show_click == undefined) ? ((this.sc == undefined) ? false : this.sc) : show_click;
    this.gap = (do_gap != undefined) ? (do_gap ? 1 : -1) : (this.gap || 1);

    if(!exists)
    {
      this.Cntr = ct;
      this.Caps = this.Shift = this.AltGr = false;

      this.DeadAction = []; this.DeadAction[0] = this.DeadAction[1] = null;
      this.keys = [], this.mod = [], this.pad = [];

      VKeyboard.kbArray[container_id] = this;
    }

    var kb = exists ? ct.childNodes[0] : document.createElement("DIV");

    if(!exists)
    {
      ct.appendChild(kb);
      ct.style.display = "block";
      ct.style.zIndex  = 999;

      if(do_embed) ct.style.visibility = "hidden"; 
        ct.style.position = "absolute";
        var initX = 0, initY = 25, ct_ = ct;
        if(ct_.offsetParent)
        {
          while (ct_.offsetParent)
          {
            initX += ct_.offsetLeft;
            initY += ct_.offsetTop;

            ct_ = ct_.offsetParent;
          }
        }
        else if (ct_.x)
        {
          initX += ct_.x;
          initY += ct_.y;
        }

	if (navigator.appName=="Netscape") {
	 winW = window.innerWidth; winH = window.innerHeight;}
	if (navigator.appName.indexOf("Microsoft")!=-1) {
	 winW = document.body.offsetWidth; winH = document.body.offsetHeight;}
   	  ct.style.left = (winW)/2 - 442/2 + "px";
      ct.style.top = (winH) - 145 + "px";

      kb.style.position = "relative";
      kb.style.top      = "0px", kb.style.left = "0px";
    }

    kb.style.border = "1px solid " + bc;

    var kb_main = exists ? kb.childNodes[0] : document.createElement("DIV"), ks = kb_main.style;
    if(!exists)
    {
      kb.appendChild(kb_main);

      ks.position = "relative";
      ks.width    = "1px";
      ks.cursor   = "default";
    }

    // Disable content selection:
    this._setup_event(kb_main, "selectstart", function(event) { return false; });
    this._setup_event(kb_main, "mousedown",   function(event) { if(event.preventDefault) event.preventDefault(); return false; });

    ks.fontFamily = ff, ks.backgroundColor = bg;

    if(!exists || changed)
    {
      var mag = parseFloat(fs) / 14.0, cell = Math.floor(25.0 * mag), dcell = 2 * cell, gap = this.gap;
      var cp = String(cell) + "px", cx = String(cell - (do_gap ? 0 : 2.0)) + "px", lh = String(cell - 2.0) + "px";

      var prevX = 0, prevY = gap, prevW = 0, prevH = 0;

      // Convenience strings:
      var c = "center", n = "normal", r = "right", l = "left", e = "&nbsp;", pad = String(4 * mag) + "px";

      // Number row:

      var key;
      for(var i = 0; i < 13; i++)
      {
        this.keys[i] = key = this._setup_key(kb_main, "___key" + String(i), prevY + "px", (prevX + prevW + gap) + "px", cp, cp, c, lh, fs);

        prevX = this._findX(key), prevW = this._findW(key);
      }

      prevY = this._findY(key);
      prevH = this._findH(key); // universal key height

      var kb_kbp = this._setup_key(kb_main, "___kbp", prevY + "px", (prevX + prevW + gap) + "px", (2.96 * cell) + "px", cp, r, lh, fs, n, "", pad);
      kb_kbp.innerHTML = "BackSpace";
      this.mod[0] = kb_kbp;

      // Top row:

      var kb_tab = this._setup_key(kb_main, "___tab", (prevY + prevH + gap) + "px", gap + "px", (1.48 * cell + gap) + "px", cp, l, lh, fs, n, pad);
      kb_tab.innerHTML = "Tab";
      this.mod[1] = kb_tab;

      prevX = this._findX(kb_tab), prevW = this._findW(kb_tab), prevY = this._findY(kb_tab);

      for(; i < 26; i++)
      {
        this.keys[i] = key = this._setup_key(kb_main, "___key" + String(i), prevY + "px", (prevX + prevW + gap) + "px", cp, cp, c, lh, fs);

        prevX = this._findX(key), prevW = this._findW(key);
      }

      this.kbpH = this._findX(kb_kbp) + this._findW(kb_kbp);

      // Home row:

      var kb_caps = this._setup_key(kb_main, "___caps", (prevY + prevH + gap) + "px", gap + "px", dcell + "px", cp, l, lh, fs, n, pad);
      kb_caps.innerHTML = "Caps";
      this.mod[2] = kb_caps;

      prevX = this._findX(kb_caps), prevW = this._findW(kb_caps), prevY = this._findY(kb_caps);

      for(; i < 38; i++)
      {
        this.keys[i] = key = this._setup_key(kb_main, "___key" + String(i), prevY + "px", (prevX + prevW + gap) + "px", cp, cp, c, lh, fs);

        prevX = this._findX(key), prevW = this._findW(key);
      }

      prevY = this._findY(key);
      var s = prevX + prevW + gap;

      var kb_enter = this._setup_key(kb_main, "___enter_l", prevY + "px", s + "px", (this.kbpH - s) + "px", cp, r, lh, fs, n, "", pad);
      kb_enter.innerHTML = "Enter";
      this.mod[3] = kb_enter;

      s = this._findX(this.keys[25]) + this._findW(this.keys[25]) + gap;

      var kb_enter_top = this._setup_key(kb_main, "___enter_top", this._findY(kb_tab) + "px", s + "px", (this.kbpH - s) + "px", cx, c, cx);
      kb_enter_top.innerHTML = e;
      kb_enter_top.subst = "Enter";
      this.mod[4] = kb_enter_top;

      kb_enter_top.company = kb_enter;
      kb_enter.company = kb_enter_top;

      // Bottom row:

      var kb_shift = this._setup_key(kb_main, "___shift", (prevY + prevH + gap) + "px", gap + "px", (2.52 * cell) + "px", cp, l, lh, fs, n, pad);
      kb_shift.innerHTML = "Shift";
      this.mod[5] = kb_shift;

      prevX = this._findX(kb_shift), prevW = this._findW(kb_shift), prevY = this._findY(kb_shift);

      for(; i < 48; i++)
      {
        this.keys[i] = key = this._setup_key(kb_main, "___key" + String(i), prevY + "px", (prevX + prevW + gap) + "px", cp, cp, c, lh, fs);

        prevX = this._findX(key), prevW = this._findW(key);
      }

      prevY = this._findY(key);

      var kb_shift_r = this._setup_key(kb_main, "___shift_r", prevY + "px", (prevX + prevW + gap) + "px", (this._findX(kb_kbp) + this._findW(kb_kbp) - prevX - prevW - gap) + "px", cp, r, lh, fs, n, "", pad);
      kb_shift_r.innerHTML = "Shift";
      this.mod[6] = kb_shift_r;

      // Language selector:

      var vcell = String(1.32 * cell) + "px";

      var kb_lang = this._setup_key(kb_main, "___lang", (prevY + prevH + gap) + "px", gap + "px", vcell, cp, l, lh, fs, n, pad);
      this.mod[7] = kb_lang;

      prevY = this._findY(kb_lang);

      ks.height = (prevY + prevH + gap) + "px";

      prevY += "px";

      var kb_res_1 = this._setup_key(kb_main, "___res_1", prevY, (this._findX(kb_lang) + this._findW(kb_lang) + gap) + "px", vcell, cp, c, lh, fs);
      kb_res_1.innerHTML = e;
      this.mod[8] = kb_res_1;

      var kb_res_2 = this._setup_key(kb_main, "___res_2", prevY, (this._findX(kb_res_1) + this._findW(kb_res_1) + gap) + "px", vcell, cp, c, lh, fs);
      kb_res_2.innerHTML = e;
      this.mod[9] = kb_res_2;

      var kb_space = this._setup_key(kb_main, "___space", prevY, (this._findX(kb_res_2) + this._findW(kb_res_2) + gap) + "px", (6.28 * cell) + "px", cp, c, lh, fs);
      this.mod[10] = kb_space;

      var kb_alt_gr = this._setup_key(kb_main, "___alt_gr", prevY, (this._findX(kb_space) + this._findW(kb_space) + gap) + "px", vcell, cp, c, lh, parseFloat(fs) * 0.786, n);
      kb_alt_gr.innerHTML = "AltGr";
      this.mod[11] = kb_alt_gr;

      var kb_res_3 = this._setup_key(kb_main, "___res_3", prevY, (this._findX(kb_alt_gr) + this._findW(kb_alt_gr) + gap) + "px", vcell, cp, c, lh, fs);
      kb_res_3.innerHTML = e;
      this.mod[12] = kb_res_3;

      var kb_res_4 = this._setup_key(kb_main, "___res_4", prevY, (this._findX(kb_res_3) + this._findW(kb_res_3) + gap) + "px", vcell, cp, c, lh, fs);
      kb_res_4.innerHTML = e;
      this.mod[13] = kb_res_4;

      var w = this.kbpH + gap;

      kb.style.width = ks.width = w + "px";
    }

    this._refresh_layout(this.avail_langs[start_layout_index || 0][0]);

    return this;
  },
  
  _set_key_state: function(key, on, textcolor, bordercolor, bgcolor)
  {
    if(key)
    {
      var ks = key.style;
      if(ks)
      {
        if(textcolor) ks.color = textcolor;
        if(bordercolor) ks.border = "1px solid " + bordercolor;
        if(bgcolor) ks.backgroundColor = bgcolor;
      }

      this._detach_event(key, 'mousedown', this._generic_callback_proc);

      if(on)
        this._setup_event(key, 'mousedown', this._generic_callback_proc);
    }
  },

  _refresh_layout: function(layout)
  {
    if(!layout) layout = this.mod[7].innerHTML;

    var fc = this.fontcolor, kc = this.keycolor, ikc = this.ikc;
    var ibc = this.ibc, bc = this.bordercolor, lic = this.lic;

    var arr_type = this.AltGr ? (this.Shift ? "alt_gr_shift" : "alt_gr") : (this.Shift ? "shift" : (this.Caps ? "caps" : "normal"));

    var nkeys = this.keys.length;

    var norm_arr  = this[layout + "_normal"];
    var caps_arr  = this[layout + "_caps"];
    var shift_arr = this[layout + "_shift"];
    var alt_arr   = this[layout + "_alt_gr"];

    var alt_shift_arr = this[layout + "_alt_gr_shift"];

    var dead_arr = this[this.DeadAction[1]] || null;

    var bcaps  = (caps_arr  && (caps_arr.length  == nkeys));
    var bshift = (shift_arr && (shift_arr.length == nkeys));
    var balt   = (alt_arr   && (alt_arr.length   == nkeys));
    var baltsh = (balt      && alt_shift_arr && (alt_shift_arr.length == nkeys));

    var caps = this.mod[2], shift = this.mod[5], shift_r = this.mod[6], alt_gr = this.mod[11];

    if(bshift)
    {
      this._set_key_state(shift, true, fc, bc, this.Shift ? lic : kc);
      this._set_key_state(shift_r, true, fc, bc, this.Shift ? lic : kc);
    }
    else
    {
      this._set_key_state(shift, false, ibc, ibc, ikc);
      this._set_key_state(shift_r, false, ibc, ibc, ikc);

      if(arr_type == "shift")
      {
        arr_type = "normal";
        this.Shift = false;
      }
    }

    if(balt)
    {
      this._set_key_state(alt_gr, true, fc, bc, this.AltGr ? lic : kc);

      if(this.AltGr)
      {
        if(baltsh)
        {
          this._set_key_state(shift, true, fc, bc);
          this._set_key_state(shift_r, true, fc, bc);
        }
        else
        {
          this._set_key_state(shift, false, ibc, ibc, ikc);
          this._set_key_state(shift_r, false, ibc, ibc, ikc);

          arr_type = "alt_gr";
          this.Shift = false;
        }
      }
    }
    else
    {
      this._set_key_state(alt_gr, false, ibc, ibc, ikc);

      if(arr_type == "alt_gr")
      {
        arr_type = "normal";
        this.AltGr = false;
      }
      else if(arr_type == "alt_gr_shift")
      {
        arr_type = "normal";
        this.AltGr = false, this.Shift = false;

        shift.style.backgroundColor = kc, shift_r.style.backgroundColor = kc;
      }
    }

    if(this.Shift && !baltsh)
      this._set_key_state(alt_gr, false, ibc, ibc, ikc);

    if(bcaps && !this.AltGr)
      this._set_key_state(caps, true, fc, bc, this.Caps ? lic : kc);
    else
    {
      this._set_key_state(caps, false, ibc, ibc, ikc);

      this.Caps = false;
      if(arr_type == "caps") arr_type = "normal";
    }

    var arr_cur = this[layout + "_" + arr_type];

    var i = nkeys;
    while(--i >= 0)
    {
      var key = this.keys[i], key_val = arr_cur[i]; if(!key_val) key_val = "";

      if(typeof(key_val) == "object")
      {
        key.innerHTML = key_val[0], key.dead = key_val[1];

        this._set_key_state(key, true, this.deadcolor, bc, (this.DeadAction[0] == key_val[0] ? lic : kc));
      }
      else
      {
        key.dead = null;

        var block = false;

        if(key_val != "")
        {
          if(dead_arr)
          {
            for(var j = 0, l = dead_arr.length; j < l; j++) { var dk = dead_arr[j]; if(dk[0] == key_val) { key_val = dk[1]; break;}};

            if(j == l) block = true;
          }

          key.innerHTML = key_val;

          if(block)
            this._set_key_state(key, false, ibc, ibc, ikc);
          else
            this._set_key_state(key, true, fc, bc, kc);
        }
        else
        {
          key.innerHTML = "&nbsp;";
          this._set_key_state(key, false, ibc, ibc, ikc);
        }
      }
    }

    i = this.mod.length;
    while(--i >= 0)
    {
      var key = this.mod[i];

      switch(i)
      {
        case 2: case 5: case 6: case 11:
          break;

        case 7:
          key.innerHTML = layout;

          this._detach_event(key, 'mousedown', this._handle_lang_menu);

          if(this.DeadAction[1])
            this._set_key_state(key, false, ibc, ibc, ikc);
          else
          {
            var many = (this.avail_langs.length > 1);

            this._set_key_state(key, false, fc, many ? this.lsc : ibc, many ? kc : ikc);
            if(many)
              this._setup_event(key, 'mousedown', this._handle_lang_menu);
          }
          break;

        case 10:
          key.innerHTML = this.DeadAction[1] ? this.DeadAction[0] : "&nbsp;";

        default:
          if((this.DeadAction[1] && (i != 10)) || ((i == 8) || (i == 9) || (i == 12) || (i ==13)))
            this._set_key_state(key, false, ibc, ibc, ikc);
          else
            this._set_key_state(key, true, fc, bc, kc);

          var ks = key.style;
          switch(i)
          {
            case 4: ks.borderBottomColor = kc; break;

            case 8: case 9: case 12: case 13: ks.borderColor = ibc; break;
          }
      }
    }

    i = this.pad.length;
    while(--i >= 0)
    {
      key = this.pad[i];

      if(this.DeadAction[1])
        this._set_key_state(key, false, ibc, ibc, ikc);
      else
        this._set_key_state(key, true, fc, bc, kc);
    }
  },

  _handle_lang_menu: function(event)
  {
   },

  _generic_callback_proc: function(event)
  {
    var in_el = VKeyboard.prototype._get_event_source(event);
    var container_id = in_el.id.substring(0, in_el.id.indexOf("___"));
    var vkb = VKeyboard.kbArray[container_id];

    var val = in_el.subst || in_el.innerHTML;
    if(!val) return;

    switch(val)
    {
      case "Caps": case "Shift": case "AltGr":

        vkb[val] = !vkb[val];
        vkb._refresh_layout();

        if(vkb.sc) vkb._start_flash(in_el);
        return;

      case "Tab":    val = "\t"; break;
      case "&nbsp;": val = " ";  break;
      case "&quot;": val = "\""; break;
      case "&lt;":   val = "<";  break;
      case "&gt;":   val = ">";  break;
      case "&amp;":  val = "&";  break;
    }

    if(vkb.sc) vkb._start_flash(in_el);

    if(in_el.dead)
    {
      if(in_el.dead == vkb.DeadAction[1])
      { val = ""; vkb.DeadAction[0] = vkb.DeadAction[1] = null; }
      else
      { vkb.DeadAction[0] = val; vkb.DeadAction[1] = in_el.dead; }

      vkb._refresh_layout();
      return;
    }
    else
    {
	  var r;
      if(vkb.DeadAction[1]) { vkb.DeadAction[0] = vkb.DeadAction[1] = null; r = true; }

      if(vkb.AltGr || vkb.Shift || r)
      {
        vkb.AltGr = false; vkb.Shift = false;
        vkb._refresh_layout();
      }
    }

    if(vkb._Callback) vkb._Callback(val, vkb.Cntr.id);
    if (text.id=="state") doNow(); /////////////////auto suggestion///////////////
  },

  SetParameters: function()
  {
    var l = arguments.length;
    if(!l || (l % 2 != 0)) return false;

    var p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16;

    while(--l > 0)
    {
      var value = arguments[l];

      switch(arguments[--l])
      {
        case "callback":
          p0 = ((typeof(value) == "function") && ((value.length == 1) || (value.length == 2))) ? value : this._Callback;
          break;

        case "font-name":  p1 = value; break;
        case "font-size":  p2 = value; break;
        case "font-color": p3 = value; break;
        case "dead-color": p4 = value; break;
        case "base-color": p5 = value; break;
        case "key-color":  p6 = value; break;

        case "selection-color": p7 = value; break;
        case "border-color":    p8 = value; break;

        case "inactive-border-color": p9  = value; break;
        case "inactive-key-color":    p10 = value; break;
        case "lang-cell-color":       p11 = value; break;

        case "show-click": p12 = value; break;

        case "click-font-color":   p13 = value; break;
        case "click-key-color":    p14 = value; break;
        case "click-border-color": p15 = value; break;

        case "layout": p16 = value; break;

        default: break;
      }
    }

    this._construct(this.Cntr.id, p0, 0, 0, 0, (this.pad.length != 0), p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, this.gap, p16);

    return true;
  },

  Show: function(value)
  {
    var ct = this.Cntr.style;

    ct.display = ((value == undefined) || (value == true)) ? "block" : ((value == false) ? "none" : ct.display);
  },

  // Layout info:

  avail_langs: [["He", "&#x05E2;&#x05D1;&#x05E8;&#x05D9;&#x05EA;"]],

  He_normal: ["&#x003B;", "&#x0031;", "&#x0032;", "&#x0033;", "&#x0034;", "&#x0035;", "&#x0036;", "&#x0037;", "&#x0038;", "&#x0039;", "&#x0030;", "&#x002D;", "&#x003D;",
              "&#x002F;", "&#x0027;", "&#x05E7;", "&#x05E8;", "&#x05D0;", "&#x05D8;", "&#x05D5;", "&#x05DF;", "&#x05DD;", "&#x05E4;", "&#x005D;", "&#x005B;", "&#x005C;",
              "&#x05E9;", "&#x05D3;", "&#x05D2;", "&#x05DB;", "&#x05E2;", "&#x05D9;", "&#x05D7;", "&#x05DC;", "&#x05DA;", "&#x05E3;", "&#x002C;",,
              "&#x05D6;", "&#x05E1;", "&#x05D1;", "&#x05D4;", "&#x05E0;", "&#x05DE;", "&#x05E6;", "&#x05EA;", "&#x05E5;", "&#x002E;"],

  He_shift: ["&#x007E;", "&#x0021;", "&#x0040;", "&#x0023;", "&#x0024;", "&#x0025;", "&#x005E;", "&#x0026;", "&#x002A;", "&#x0028;", "&#x0029;", "&#x005F;", "&#x002B;",
             "&#x0051;", "&#x0057;", "&#x0045;", "&#x0052;", "&#x0054;", "&#x0059;", "&#x0055;", "&#x0049;", "&#x004F;", "&#x0050;", "&#x007B;", "&#x007D;", "&#x007C;",
             "&#x0041;", "&#x0053;", "&#x0044;", "&#x0046;", "&#x0047;", "&#x0048;", "&#x004A;", "&#x004B;", "&#x004C;", "&#x003A;", "&#x0022;",,
             "&#x005A;", "&#x0058;", "&#x0043;", "&#x0056;", "&#x0042;", "&#x004E;", "&#x004D;", "&#x003C;", "&#x003E;", "&#x003F;"],

  He_caps:  ["&#x003B;", "&#x0031;", "&#x0032;", "&#x0033;", "&#x0034;", "&#x0035;", "&#x0036;", "&#x0037;", "&#x0038;", "&#x0039;", "&#x0030;", "&#x002D;", "&#x003D;",
             "&#x0051;", "&#x0057;", "&#x0045;", "&#x0052;", "&#x0054;", "&#x0059;", "&#x0055;", "&#x0049;", "&#x004F;", "&#x0050;", "&#x007B;", "&#x007D;", "&#x007C;",
             "&#x0041;", "&#x0053;", "&#x0044;", "&#x0046;", "&#x0047;", "&#x0048;", "&#x004A;", "&#x004B;", "&#x004C;", "&#x003A;", "&#x0022;",,
             "&#x005A;", "&#x0058;", "&#x0043;", "&#x0056;", "&#x0042;", "&#x004E;", "&#x004D;", "&#x002C;", "&#x002E;", "&#x002F;"]
};


<!--
   function trim (str) { return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");};

   var opened = false, vkb = null, text = null, insertionS = 0, insertionE = 0;

   var userstr = navigator.userAgent.toLowerCase();
   var safari = (userstr.indexOf('applewebkit') != -1);
   var gecko  = (userstr.indexOf('gecko') != -1) && !safari;
   var standr = gecko || window.opera || safari;
   var nn6=document.getElementById&&!document.all;
   var textfieldIdvar=null;

   function keyb_change(textfieldId, openNow)
   { textfieldIdvar=textfieldId;
     opened = (openNow) ? true : false;

     if(opened && !vkb)
     {
       // Note: all parameters, starting with 3rd, in the following
       // expression are optional; their values are equal to the
       // default parameter values for the VKeyboard object.
       // The only exception is 18th parameter (flash switch),
       // which is false by default.

       vkb = new VKeyboard("keyboard",    // container's id
                           keyb_callback, // reference to the callback function
                           false,          // create the arrow keys or not? (this and the following params are optional)
                           false,          // create up and down arrow keys?
                           false,         // reserved
                           false,          // create the numpad or not?
                           "",            // font name ("" == system default)
                           "12px",        // font size in px
                           "#33A",        // font color
                           "#F00",        // font color for the dead keys
                           "#FFF",        // keyboard base background color
                           "#FFF",        // keys' background color
                           "#DDD",        // background color of switched/selected item
                           "#888",        // border color
                           "#CCC",        // border/font color of "inactive" key (key with no value/disabled)
                           "#FFF",        // background color of "inactive" key (key with no value/disabled)
                           "#F77",        // border color of the language selector's cell
                           true,          // show key flash on click? (false by default)
                           "#CC3300",     // font color during flash
                           "#FF9966",     // key background color during flash
                           "#CC3300",     // key border color during flash
                           true,         // display = (f) block / (t) none
                           true,          // use 1-pixel gap between the keys?
                           0);            // index(0-based) of the initial layout
     }
     else
       vkb.Show(opened);

     if (textfieldIdvar=='wysiwygnewhebtext1')
      text = document.getElementById("wysiwygnewhebtext1").contentWindow.document.body;
     else text = document.getElementById(textfieldId);
   }

   // Advanced callback function:
   //
   function keyb_callback(ch)
   {
     if (textfieldIdvar=='wysiwygnewhebtext1') var val = text.innerText;
     else var val = text.value;

     switch(ch)
     {
       case "BackSpace":
         if(val.length)
         {
           var span = null;

           if(document.selection)
             span = document.selection.createRange().duplicate();

           if(span && span.text.length > 0)
           {
             span.text = "";
             getCaretPositions(text);
           }
           else
             deleteAtCaret(text);
         }

         break;

       default:
         insertAtCaret(text, (ch == "Enter" ? (window.opera ? '\r\n' : '\n') : ch));
     }
   }

   // This function retrieves the position (in chars, relative to
   // the start of the text) of the edit cursor (caret), or, if
   // text is selected in the TEXTAREA, the start and end positions
   // of the selection.
   //
   function getCaretPositions(ctrl)
   {
     var CaretPosS = -1, CaretPosE = 0;

     // Mozilla way:
     if(ctrl.selectionStart || (ctrl.selectionStart == '0'))
     {
       CaretPosS = ctrl.selectionStart;
       CaretPosE = ctrl.selectionEnd;

       insertionS = CaretPosS == -1 ? CaretPosE : CaretPosS;
       insertionE = CaretPosE;
     }
     // IE way:
     else if(document.selection)// && ctrl.createTextRange
     {
       var start = end = 0;
       try
       {
         start = Math.abs(document.selection.createRange().moveStart("character", -10000000)); // start

         if (start > 0)
         {
           try
           {
             var endReal = Math.abs(ctrl.createTextRange().moveEnd("character", -10000000));

             var r = document.body.createTextRange();
             r.moveToElementText(ctrl);
             var sTest = Math.abs(r.moveStart("character", -10000000));
             var eTest = Math.abs(r.moveEnd("character", -10000000));

             if ((ctrl.tagName.toLowerCase() != 'input') && (eTest - endReal == sTest))
               start -= sTest;
           }
           catch(err) {}
         }
       }
       catch (e) {}

       try
       {
         end = Math.abs(document.selection.createRange().moveEnd("character", -10000000)); // end
         if(end > 0)
         {
           try
           {
             var endReal = Math.abs(ctrl.createTextRange().moveEnd("character", -10000000));

             var r = document.body.createTextRange();
             r.moveToElementText(ctrl);
             var sTest = Math.abs(r.moveStart("character", -10000000));
             var eTest = Math.abs(r.moveEnd("character", -10000000));

             if ((ctrl.tagName.toLowerCase() != 'input') && (eTest - endReal == sTest))
              end -= sTest;
           }
           catch(err) {}
         }
       }
       catch (e) {}

       insertionS = start;
       insertionE = end;
     }
   }

   function setRange(ctrl, start, end)
   {
     if(ctrl.setSelectionRange) // Standard way (Mozilla, Opera, Safari ...)
     {
       ctrl.setSelectionRange(start, end);
     }
     else // MS IE
     {
       var range;

       try
       {
         range = ctrl.createTextRange();
       }
       catch(e)
       {
         try
         {
           range = document.body.createTextRange();
           range.moveToElementText(ctrl);
         }
         catch(e)
         {
           range = null;
         }
       }

       if(!range) return;

       range.collapse(true);
       range.moveStart("character", start);
       range.moveEnd("character", end - start);
       range.select();
     }

     insertionS = start;
     insertionE = end;
   }

   function deleteSelection(ctrl)
   {
     if(insertionS == insertionE) return;

     if (textfieldIdvar=='wysiwygnewhebtext1') {
      var tmp = (document.selection && !window.opera) ? ctrl.innerText.replace(/\r/g,"") : ctrl.innerText;
      ctrl.innerText = tmp.substring(0, insertionS) + tmp.substring(insertionE, tmp.length);
     } else {
      var tmp = (document.selection && !window.opera) ? ctrl.value.replace(/\r/g,"") : ctrl.value;
      ctrl.value = tmp.substring(0, insertionS) + tmp.substring(insertionE, tmp.length);
     }

     setRange(ctrl, insertionS, insertionS);
   }

   function deleteAtCaret(ctrl)
   {
     // if(insertionE < insertionS) insertionE = insertionS;
     if(insertionS != insertionE)
     {
       deleteSelection(ctrl);
       return;
     }

     if(insertionS == insertionE)
       insertionS = insertionS - 1;

     if (textfieldIdvar=='wysiwygnewhebtext1') {
      var tmp = (document.selection && !window.opera) ? ctrl.innerText.replace(/\r/g,"") : ctrl.innerText;
      ctrl.innerText = tmp.substring(0, insertionS) + tmp.substring(insertionE, tmp.length);
     } else {
      var tmp = (document.selection && !window.opera) ? ctrl.value.replace(/\r/g,"") : ctrl.value;
      ctrl.value = tmp.substring(0, insertionS) + tmp.substring(insertionE, tmp.length);
     }

     setRange(ctrl, insertionS, insertionS);
   }

   // This function inserts text at the caret position:
   //
   function insertAtCaret(ctrl, val)
   {
     if(insertionS != insertionE) deleteSelection(ctrl);

     if(gecko && document.createEvent && !window.opera)
     {
       var e = document.createEvent("KeyboardEvent");

       if(e.initKeyEvent && ctrl.dispatchEvent)
       {
         e.initKeyEvent("keypress",        // in DOMString typeArg,
                        false,             // in boolean canBubbleArg,
                        true,              // in boolean cancelableArg,
                        null,              // in nsIDOMAbstractView viewArg, specifies UIEvent.view. This value may be null;
                        false,             // in boolean ctrlKeyArg,
                        false,             // in boolean altKeyArg,
                        false,             // in boolean shiftKeyArg,
                        false,             // in boolean metaKeyArg,
                        null,              // key code;
                        val.charCodeAt(0));// char code.

         ctrl.dispatchEvent(e);
       }
     }
     else
     {
      if (textfieldIdvar=='wysiwygnewhebtext1') {
       ctrl.innerHTML = ctrl.innerHTML.replace("<P>&nbsp;</P>","");
       var tmp = (document.selection && !window.opera) ? ctrl.innerText.replace(/\r/g,"") : ctrl.innerText;
      if ((tmp.substring(insertionS, tmp.length))=="") {
       ctrl.innerHTML+=val;
       setRange(ctrl, tmp.length+1, tmp.length+1);
      } else
        ctrl.innerText = tmp.substring(0, insertionS) + val + tmp.substring(insertionS, tmp.length);
      } else {
       var tmp = (document.selection && !window.opera) ? ctrl.value.replace(/\r/g,"") : ctrl.value;
       ctrl.value = tmp.substring(0, insertionS) + val + tmp.substring(insertionS, tmp.length);
      }
     }

     setRange(ctrl, insertionS + val.length, insertionS + val.length);
   }

   // Translator function:

   var pressedC = false;

   function translate(event) {
     if(!vkb || !opened) return true;

     var arr_type = vkb.AltGr ? (vkb.Shift ? "alt_gr_shift" : "alt_gr") : (vkb.Shift ? "shift" : (vkb.Caps ? "caps" : "normal"));
     var lang_array = vkb[vkb.mod[7].innerHTML + "_" + arr_type];

     if(!lang_array) return true;

     if(!event) event = window.event;

     var key = event.which ? event.which : event.keyCode;

     switch(event.type)
     {
       case "keydown":
       
         switch(key)
         {
           case 20: // Caps

             if(!pressedC)
             {
               vkb.Caps = !vkb.Caps;
               vkb._refresh_layout();

               pressedC = true;
               return true;
             }
             break;

           case 18: // Alt(Gr)

             vkb.AltGr = true;
             vkb._refresh_layout();

             return true;
             break;

           case 16: // Shift

              vkb.Shift = true;
              vkb._refresh_layout();
              return true;

             break;

           default:
              if(event.initKeyEvent)
             {
               var code = String.fromCharCode(key).toUpperCase().charCodeAt(0);

               if((code < 48) || (code > 222)) return true;

               var keymap = [192,49,50,51,52,53,54,55,56,57,48,189,187, // ~ to =
                             81,87,69,82,84,89,85,73,79,80,219,221,220, // q to \
                             65,83,68,70,71,72,74,75,76,186,222,,       // a to '
                             90,88,67,86,66,78,77,188,190,191];         // z to /

               if(navigator.product && (navigator.product.toLowerCase() == 'gecko'))
               {
                 keymap[11] = 109;
                 keymap[12] = 61;
                 keymap[36] = 59;
               }

               for(i = 0; i < keymap.length; i++)
               {
                 if(keymap[i] == code)
                   break;
               }

               if((i > keymap.length) || !lang_array[i])
               {
                 event.returnValue = false;
                 if(event.preventDefault) event.preventDefault();

                 return false;
               }

               code = parseInt(String(lang_array[i]).substr(3, 4), 16);

               var e = document.createEvent("KeyboardEvent");

               e.initKeyEvent("keypress",       //  in DOMString typeArg,
                              false,            //  in boolean canBubbleArg,
                              true,             //  in boolean cancelableArg,
                              null,             //  in nsIDOMAbstractView viewArg,  Specifies UIEvent.view. This value may be null.
                              false,            //  in boolean ctrlKeyArg,
                              false,            //  in boolean altKeyArg,
                              false,            //  in boolean shiftKeyArg,
                              false,            //  in boolean metaKeyArg,
                              code, null);      //  key code.

               text.dispatchEvent(e);
               
               event.returnValue = false;
               if(event.preventDefault) event.preventDefault();

               insertAtCaret(text, String.fromCharCode(code));
             }

             return true;
         }

         break;

       case "keyup":

         switch(key)
         {
           case 13: // Enter

           case 9: // Tab

             break;

           case 20: // Caps

             pressedC = false;
             break;

           case 18: // Alt(Gr)

             vkb.AltGr = false;
             vkb._refresh_layout();

             return true;
             break;

           case 16: // Shift

             vkb.Shift = false;
             vkb._refresh_layout();

             return true;
             break;
         }

         break;

       case "keypress":

         switch(key)
         {
           case 13: // Enter

           case 32: // Space
            return true;
            break;

           default: // all other keys

             if((key < 33) || (key > 222)) return true; // || !(document.all || window.opera)

             var code = String.fromCharCode(key).toUpperCase().charCodeAt(0);

             var keymap = [96,49,50,51,52,53,54,55,56,57,48,45,61, // ` to =
                           81,87,69,82,84,89,85,73,79,80,91,93,92, // q to \
                           65,83,68,70,71,72,74,75,76,59,39,,      // a to '
                           90,88,67,86,66,78,77,44,46,47];         // z to /

             var keymap_sh = [126,33,64,35,36,37,94,38,42,40,41,95,43,   // ~ to +
                              81,87,69,82,84,89,85,73,79,80,123,125,124, // q to |
                              65,83,68,70,71,72,74,75,76,58,34,,         // a to "
                              90,88,67,86,66,78,77,60,62,63];            // z to ?

             var map = vkb.Shift ? keymap_sh : keymap;

             for(i = 0; i < map.length; i++)
               if(map[i] == code)
                 break;

             if((i > map.length) || !lang_array[i]) { event.returnValue = false; return false; }

             code = parseInt(String(lang_array[i]).substr(3, 4), 16)

             if (!window.opera && !nn6) event.keyCode = code;

             // cancel default behaviour:
             event.returnValue = false;
             insertAtCaret(text, String.fromCharCode(code));
         }

       return false;
     }

     return true;
   }

 //-->


function toogleWeather(id) {
 wObj = getIt("weather_"+id);
 if (wObj.style.display=='none') {
  wObj.style.display='';
  if (wObj.innerHTML=='') {
   wObj.innerHTML = "<center><img src=loadingblue.gif></center>";
   fillWeather(id);
  }
 }
 else
  wObj.style.display='none';
}

var weatherXML;
function fillWeather(id) {
 if (window.ActiveXObject || window.XMLHttpRequest) {
   weatherXML=(window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLDOM");
   weatherXML.onreadystatechange = function () {if (weatherXML.readyState == 4) putWeather(id);};
 }
 else if (document.implementation && document.implementation.createDocument) {
  weatherXML=document.implementation.createDocument("","",null);
  weatherXML.onload=function(){putWeather(id);};
 }
 else
  return;

 weatherXML.async=true;

 try {
  weatherXML.load("smallweatherxml.php?id="+id);
 } catch (e) {
  weatherXML.open("GET","smallweatherxml.php?id="+id,true);
  weatherXML.send(null);
 }
}

function putWeather(id) {
 if (window.XMLHttpRequest)
  try {weatherXML = weatherXML.responseXML;} catch(e){}
 try {
  text = weatherXML.getElementsByTagName("texter")[0].childNodes[0].nodeValue;
  getIt("weather_"+id).innerHTML = text;
  getIt("weather_"+id).style.display="";
 }
 catch(e) {alert(e);}
}
