var ie = document.all;
var ns6 = document.getElementById && !document.all;
var opera=(window.opera);
var ie7 = (ie && document.implementation != null && document.compatMode != null && window.XMLHttpRequest != null);
var ie6 = ie && !ie7;
var BrowserStartTime = 0;



function trim(string)
{
  return string.replace(/(^\s+)|(\s+$)/g, "");
}

function RightBackground(src)
{
  if (ie && !ie7 && !opera && !ns6)
    return "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader (src='"+src+"');";
  else
    return  "background: url('"+src+"');";
}

if (opera)
{
  var browserleftcorrection=-5;
  var browserwidthcorrection=-3;
  var browsertopcorrection=-2;
}
else
if (ns6)
{
  var browserleftcorrection=-5;
  var browserwidthcorrection=-3;
  var browsertopcorrection=-5;
}
else
{
  var browserleftcorrection=-5;
  var browserwidthcorrection=0;
  var browsertopcorrection=0;
}


function iecompattest()
{
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}


function clearbrowseredge(dropmenuobj,obj, whichedge){
  var edgeoffset='';
  if (whichedge=="rightedge"){
    var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
    dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
    if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
      edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth
  }
  else{
    var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
    dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
    if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
      edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
  }
  return edgeoffset
}


function getpageoffset(offset)
{
  if (offset=='left')
  {
    var offset=ie && !window.opera ? iecompattest().scrollLeft : window.pageXOffset;
    return offset;
  }
  else
  {
    offset=ie && !window.opera ? iecompattest().scrollTop : window.pageYOffset;
    return offset;
  }
}

function getposOffset(what, offsettype)
{
  var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
  var parentEl=what.offsetParent;
  while (parentEl!=null)
  {
    totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
    parentEl=parentEl.offsetParent;
  }
  return totaloffset;
}


function getpageheight()
{
  return (ie && !window.opera) ? iecompattest().clientHeight : window.innerHeight;
}

function createCookie(name,value,days)
{
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++)
  {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return "";
}

function eraseCookie(name)
{
  createCookie(name,"",-1);
}

var debugwin = null;

function writedebug(msg)
{
  if (!debugwin) debugwin = document.getElementById('debugwin');
  debugwin.innerHTML+='<br>['+msg+']';
}

if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){
        return i;
      }
    }
    return -1;
  }
}

String.prototype.urlencode = function()
{
  var enc = (encodeURI(this).replace(/&/g, "%26")).replace(/=/g, "%3D");
  return enc;
}

function isInteger (s)
{
  var i;
  if (!s.length) return false;
  for (i = 0; i < s.length; i++)
  {
    var c = s.charAt(i);
    if (!isDigit(c)) return false;
  }
  return true;
}

function isDigit (c)
{
  return ((c >= "0") && (c <= "9"))
}

function getDocHeight()
{
  var D = document;
  return Math.max(
    Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
    Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
    Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

var http_requests= new Array(1);
http_requests[0] = false;

function AjaxRequest(parameters,dest,loadbox,tries,RequestSeed)
{
  if (!RequestSeed)
  {
    var currentDate = new Date();
    RequestSeed = (currentDate.valueOf()-BrowserStartTime)-2147483159;
    parameters += "&REQUESTSEED="+RequestSeed;
  }

  var url="/ajax.php";
  var i=0;
  while (http_requests[i]) i++;
  http_requests[i]=[]
  http_requests[i].dest=dest;
  http_requests[i].requestseed = RequestSeed;
  http_requests[i].params=parameters;
  if (loadbox)
    http_requests[i].loadbox=loadbox;
  else
    http_requests[i].loadbox=false;

  if (tries)
    http_requests[i].tries=tries;
  else
    http_requests[i].tries=0;
  http_requests[i].tries++;
  //if (console && console.log) console.log('Request '+RequestSeed+',Try '+http_requests[i].tries);
  if (tries===true)
    http_requests[i].tries=99;
  if (window.XMLHttpRequest)
  { // Mozilla, Safari,...
    http_requests[i].request = new XMLHttpRequest();
    if (http_requests[i].request.overrideMimeType)
    {
      http_requests[i].request.overrideMimeType('text/html');
    }
  }
  else
  if (window.ActiveXObject)
  { // IE
    try
    {
      http_requests[i].request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        http_requests[i].request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        if (http_requests[i].loadbox) hidebox(http_requests[i].loadbox);
      }
    }
  }
  if (!http_requests[i].request)
  {
    alert('Cannot create XMLHTTP instance! You might not be able to use this site, please contact your computer administrator!');
    hidebox(http_requests[i].loadbox);
    return false;
  }

  http_requests[i].request.open('POST',url,true);
  http_requests[i].request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_requests[i].request.setRequestHeader("Content-length", parameters.length);
  //http_requests[i].request.setRequestHeader("Connection", "close");
  http_requests[i].request.setRequestHeader("Connection", "keep-alive");
  http_requests[i].request.send(parameters);
  http_requests[i].request.onreadystatechange = alertContents;
  var exec = "";
  var boxret = "";
  if (http_requests[i].tries<4)
    exec="AjaxRequest('"+http_requests[i].params+"','"+http_requests[i].dest.replace(/'/g,'\\\'')+"',"+http_requests[i].loadbox+","+(http_requests[i].tries)+","+RequestSeed+")";
  else
  if (http_requests[i].loadbox)
    exec="boxerror("+http_requests[i].loadbox; //+");if (console && console.log) console.log('Request Timeout!');";

  if (http_requests[i].loadbox)
    boxret = "boxretry("+http_requests[i].loadbox+","+(http_requests[i].tries+1)+");";
  else
    boxret = "";
  //if (console && console.log) console.log(boxret+"http_requests["+i+"].request.abort();http_requests["+i+"]=null;"+exec);
  http_requests[i].timer=setTimeout(boxret+"http_requests["+i+"].request.abort();http_requests["+i+"]=null;"+exec,12000);
  return true;
}

//http_requests[0].request.abort();http_requests[0]=null;AjaxRequest('&action=getfiltercontent&category=12&filter=make&section=main&query=cars-bikes-vehicles&mainaction=&state[]=2&city[]=182&city[]=164&country=1&pricefrom=0&priceto=0&yearfrom=0&yearto=0&mileagefrom=0&mileageto=0&location=0&REQUESTSEED=-2147464859','set_filter_content('make',text);',false,1,-2147464859);

function alertContents()
{
  var j=0;
  for (j=0;j<http_requests.length;j++)
  {
    if (http_requests[j]!=null)
    {
      if (http_requests[j].request.readyState == 4)
      {
        clearTimeout(http_requests[j].timer);
        if (http_requests[j].request && http_requests[j].request.status == 200 && http_requests[j].request.responseText!='STILLPROCESSING')
        {
          var text = http_requests[j].request.responseText;
          eval(http_requests[j].dest);
          if (http_requests[j].loadbox) hidebox(http_requests[j].loadbox);
        }
        else        
        if (http_requests[j].request.status!==0)
        {
          //if (console && console.log) console.log("Ready state 4, status:"+http_requests[j].request.status);
          if (http_requests[j].tries<4)
          {
            if (http_requests[j].loadbox)
              boxretry(http_requests[j].loadbox,+http_requests[j].tries+1);
            //if (console && console.log) console.log('Setting Timeout (10sec)');
            setTimeout("AjaxRequest('"+http_requests[j].params+"','"+http_requests[j].dest+"',"+http_requests[j].loadbox+","+(http_requests[j].tries)+","+http_requests[j].requestseed+")",10000);
          }
          else
          {
            if (http_requests[j].loadbox)
              boxerror(http_requests[j].loadbox);
          }
        }
        http_requests[j].request.abort();
        http_requests[j].request = null;
        http_requests[j] = null;
      }
    }
  }
}

var currentDate = new Date();
BrowserStartTime = currentDate.valueOf();


var UploadLoadBox = false;

function dumpProps(obj, parent,level) {
  // Go through all the properties of the passed-in object
  if (!level) return '';
  level--;
  for (var i in obj) {
    // if a parent (2nd parameter) was passed in, then use that to
    // build the message. Message includes i (the object's property name)
    // then the object's property value on a new line
    var n = '!';
    var obji = '!';
    if (!i) n = 'ERROR';
    else
      n = i;
    if (!obj[i]) obji = 'ERROR'
    else
      obji = obj[i];

    if (parent) {
      var msg = parent + "." + n + " = " + obji;
    } else {
      var msg = n + " = " + obji;
    }
    // Display the message. If the user clicks "OK", then continue. If they
    // click "CANCEL" then quit this level of recursion
    if (!confirm(msg)) {
      return;
    }
    // If this property (i) is an object, then recursively process the object
    //console.log(msg);
    if (typeof obji == "object") {
      if (parent) {
        dumpProps(obji, parent + "." + n,level);
      } else {
        dumpProps(obji,'',level);
      }
    }
  }
}

function upload_file(obj)
{
  var theForm = document.getElementById('upload_form');
  UploadLoadBox = showloadbox(obj,false,'Uploading file , Please wait...<br><img src="/img/smallloader.gif">');
  theForm.submit();
  theForm.reset();
}

function upload_complete(exec)
{
  if (UploadLoadBox) hidebox(UploadLoadBox);
  UploadLoadBox = false;
  eval(exec);
}

var LoadImage = new Image();
LoadImage.src = "/img/design/2ndloader.gif";

function showloadbox(obj,small)
{
  var i=1;
  while  (document.getElementById("loadbox"+i) && document.getElementById("loadbox"+i).style.visibility=="visible") i++;
  if (!document.getElementById("loadbox"+i)) createloadbox(i);
  var loadbox=document.getElementById("loadbox"+i);
  loadbox.style.height="auto";
  loadbox.style.width="auto";
  if (small)
  {
    loadbox.className="loadboxsmall";
    var height=15*small;
    var width=15*small;
    loadbox.innerHTML='<img src="/img/mediumloader.gif" style="width:'+width+'px;height:'+height+'px;">';
    loadbox.issmall = small;
  }
  else
  {
    loadbox.className="loadbox";
    var height = 60;
    loadbox.innerHTML='Loading...<br><img src="/img/design/2ndloader.gif" width="24" height="24">';
    var width = 235;
    loadbox.issmall = false;
  }

  var X = 0;
  var Y = 0;
  if (obj)
  {
    X = getposOffset(obj, "left")+Math.floor(obj.offsetWidth / 2)-((width + (small ? 0 : 20))/2);
    Y = getposOffset(obj, "top")+Math.floor(obj.offsetHeight / 2)-((height + (small ? 0 : 20))/2);
  }
  else
  {
    X = Math.floor((document.body.scrollWidth-width)/2);
    Y = ((document.body.scrollTop) + (Math.floor(document.body.clientHeight - height) / 3));
  }

  loadbox.style.width = width+"px";
  loadbox.style.height = height+"px";
  loadbox.style.left=X+"px"
  loadbox.style.top=Y+"px";
  loadbox.style.visibility="visible";
  loadbox.appear=true;
  loadbox.style.opacity="0.1";


  if (ie)
    loadbox.style.filter="alpha(opacity=1)";

  setTimeout("inctrans("+i+")",50);
  return i;
}

function boxerror(i)
{
  hidebox(i);
  MakeConfirmation('<img src="/img/error.gif" style="float:left;"> Request Timeout! Please try again in a few seconds!',300,100,'','OK');
}

function boxstate(i)
{

}

function boxretry(i,time)
{
  var box=document.getElementById("loadbox"+i);
  if (!box || box.issmall) return;
  box.innerHTML='Proccessing...<br><img src="/img/design/2ndloader.gif" width="24" height="24">';
}


function inctrans(i)
{
  var obj=document.getElementById("loadbox"+i);
  var objstyle=obj.style;
  if (objstyle.opacity<1 && obj.appear)
  {
    objstyle.opacity=Math.abs(objstyle.opacity)+0.2;
    if (ie) objstyle.filter="alpha(opacity="+Math.floor(Math.abs(objstyle.opacity)*100)+")";
    setTimeout("inctrans("+i+");",60);
  }
}

function dectrans(i)
{
  var obj=document.getElementById("loadbox"+i);
  var objstyle=obj.style;
  if (objstyle.opacity>0.1)
  {
    objstyle.opacity=Math.abs(objstyle.opacity)-0.2;
    if (ie) objstyle.filter="alpha(opacity="+Math.floor(Math.abs(objstyle.opacity)*100)+")";
    setTimeout("dectrans("+i+");",60);
  }
  else
  {
    objstyle.visibility="hidden";
    objstyle.left="-500px";
  }
}


function hidebox(ID){
  var box=document.getElementById("loadbox"+ID);
  box.appear=false;
  setTimeout("dectrans("+ID+");",10);
}

function createloadbox(ID){
  var divblock=document.createElement("div");
  divblock.setAttribute("id", "loadbox"+ID);
  divblock.className="loadbox";
  document.body.appendChild(divblock);
}


//----------------------------------------------WINDOW ENGINE------------------------------------------------------------------------------------------

var Windows = new Array();
var nowinleft = true;
var NextWinID = 1;

var GreyScreen = [];
GreyScreen.obj = null;
GreyScreen.fadein = false;
GreyScreen.fadeout = false;
GreyScreen.opacity = 0;

var WIN_NOCLOSE     = 1;
var WIN_STARTHIDDEN = 1 << 1;
var WIN_STRETCH     = 1 << 2;
var WIN_TRIM        = 1 << 3;
var WIN_MODAL       = 1 << 4;
var WIN_STATUSBAR   = 1 << 5;
var WIN_INLOADSTATE = 1 << 6;
var WIN_SCROLLBARS  = 1 << 7;
var WIN_REFRESH     = 1 << 8;
var WIN_OPENONCE    = 1 << 9;

function ShowWinBox(wincontents, obj,width,height,header,flags,post_str)
{
  var id = Windows.length;
  var FullWidth = 0;
  var FullHeight = 0;
  // Get Width and Weight of the Window Content Area
  //if (document.body.scrollWidth < document.body.offsetWidth)
  //  FullWidth = document.body.offsetWidth;
  //else
  FullWidth = document.body.scrollWidth;

  if (document.body.scrollHeight < document.body.offsetHeight)
    FullHeight = document.body.offsetHeight;
  else
    FullHeight = document.body.scrollHeight;

  var top = 0;

  if (window.pageYOffset)
    top = window.pageYOffset;
  else
  if (document.documentElement)
    top = document.documentElement.scrollTop;
  else
    top = document.body.scrollTop;

  var FHeight = 0;
  if (window.innerHeight) FHeight = window.innerHeight;
  else
  if (document.documentElement) FHeight = document.documentElement.clientHeight;
  else
    FHeight = document.body.clientHeight;

  // Calculate X and Y Relative to Object
  var X = 0;
  var Y = 0;
  if (obj)
  {
    X = getposOffset(obj, "left");
    Y = getposOffset(obj, "top");
  }
  else
  {
    X = Math.floor((FullWidth-width-40)/2);
    if (height)
      Y = (top + Math.floor((FHeight - height) / 2));
    else
      Y = top + 50;
    if (Y < 10) Y = 10;
  }

  if (!width) width='500';

  // Create VirtualWindow Instance
  Windows[id] = new MakeWindow();
  Windows[id].Init(NextWinID++,wincontents, X, Y, width, height, header, flags, post_str);
  if (post_str)
  {
    AjaxRequest(post_str,'FadeWindowContent(text,'+Windows[id].Id+');',showloadbox(Windows[id].Win,true));
  }
  return Windows[id].Id;

}


function MakeWindow()
{
  this.Id = null;
  this.Win = null;
  this.Order = Infinity;
  this.Minimized = null;
  this.Width = null;
  this.Height = null;
  this.Flags = null;
  this.StatusBar = null;
  this.Content = null;
  this.Request = null
}

function ShowAlphaObj(obj)
{
  //if (!ie) FadeOut(obj,true,false,false,';');
  //else
  obj.style.visibility = "visible";
}

function HideAlphaObj(obj)
{
  //if (!ie) FadeOut(obj,false,true,false,false,';');
  // else
  obj.style.visibility = "hidden";
}


MakeWindow.prototype.Init = function(id, wincontents, x, y, width, height, header, flags, post_str)
{
  this.Id = id;
  this.Win = document.createElement("div");
  this.Win.setAttribute("id", "winbox"+id);
  document.body.appendChild(this.Win);
  this.Win.className="winbox";
  this.Win.innerHTML = '';
  this.Win.id = "winbox"+id;
  this.Order = Infinity;
  this.Minimized = false;
  this.Width = width;
  this.Height = height;
  this.Flags = flags;
  this.Request = (post_str ? post_str : false);

  intwidth = width;
  height +='px';
  width += 'px';

  this.Win.style.left = x + "px";
  this.Win.style.top = y +"px";

  var close='<div class="window_closebtn" style="float:right;" title="Close" onMouseOver="HoldDrag();ShowAlphaObj(document.getElementById(\'window'+id+'_closebtn\'));" onMouseOut="ReleaseDrag();HideAlphaObj(document.getElementById(\'window'+id+'_closebtn\'));"><div id="window'+id+'_closebtn" class="window_closebtn_lit" onclick="CloseWindow('+id+');"></div></div>';
  if (flags & WIN_NOCLOSE)
    close='';

  var sb = '';
  if (flags & WIN_STATUSBAR)
    sb = '_sb';

  var refresh='';
  if (flags & WIN_REFRESH)
    refresh = '<div class="window_refreshbtn" style="float:right;" title="Refresh" onMouseOver="HoldDrag();ShowAlphaObj(document.getElementById(\'window'+id+'_refreshbtn\'));" onMouseOut="ReleaseDrag();HideAlphaObj(document.getElementById(\'window'+id+'_refreshbtn\'));"><div id="window'+id+'_refreshbtn" class="window_refreshbtn_lit" onclick="ReloadWindow('+id+');"></div></div>';

  if (wincontents!='')
    wincontents = wincontents.replace(/#thiswin#/g,id);

  this.Win.innerHTML = '<table cellspasing="0" cellpadding="0" class="floatwin" onmousedown="FocusWindow('+id+');ReStretch('+id+');return true;">'
  +'<tr id="windrag'+id+'" class="windrag">'
  +'<td class="wincorner_tl"></td>'
  +'<td class="wincorner_tm"><table cellpadding=0 cellspacing=0 width="100%";><tr><td class="winlogo"></td><td class="winheader"><div id="winheader_'+id+'">'+header+'</div></td><td style="text-align:right;">'+close+refresh+'</td></tr></table></td>'
  +'<td class="wincorner_tr"></td>'
  +'</tr>'
  +'<tr>'
  +'<td class="wincorner_ml"></td>'
  +'<td style="vertical-align:top;" class="wincorner_mm"><div class="wincontent" onMouseDown="ReOrganizeWindows('+id+')" style="width:'+width+'; height:'+height+';" id="wincontent'+id+'"></div></td>'
  +'<td class="wincorner_mr"></td>'
  +'</tr>'
  +'<tr>'
  +'<td class="wincorner_bl'+sb+'"></td>'
  +'<td class="wincorner_bm'+sb+'"><div id="winstatusbar'+id+'" class="winstatusbar'+sb+'"></div></td>'
  +'<td class="wincorner_br'+sb+'"></td>'
  +'</tr></table>';





  Drag.init(document.getElementById("windrag"+id),this.Win,false,false,'ResizeGreyScreen();',-15,false,-10);
  ReleaseDrag();
  this.Content = document.getElementById("wincontent"+id);
  this.StatusBar = document.getElementById("winstatusbar"+id);

  if (flags & WIN_STARTHIDDEN)
  {
    this.Content.style.opacity = 0;
    if (ie) this.Content.style.filter = "alpha(opacity=0)";
    this.Content.style.visibility = "hidden";
  }

  if ((flags & WIN_STATUSBAR) && (flags & WIN_INLOADSTATE))
  {
    this.StatusBar.innerHTML = '<img src="/img/tinyloader.gif" style="vertical-align:middle;"> Loading...';
  }

  FocusWindow(id,ie);
  this.Content.innerHTML = wincontents;
  FadeOut(this.Win,true,false,false,'FocusWindow('+id+');');

  if (flags & WIN_MODAL)
    setTimeout("ShowGreyScreen("+id+");",50);

  if (flags & WIN_SCROLLBARS)
  {
    this.Content.style.overflowY = 'scroll';
  }
  else
  if ((flags & WIN_TRIM) && wincontents != '')
  {
    this.Content.style.overflow = 'visible';
    this.Content.style.height = 'auto';
    this.Height = this.Content.offsetHeight;
  //this.Content.style.height = this.Height+'px';
  //this.Content.style.overflow = 'hidden';
  }
  else
  if (flags & WIN_STRETCH)
  {
    if (this.Content.ScrollHeight > this.Height)
      this.Content.style.height = this.Content.ScrollHeight;
    this.Height = this.Content.offsetHeight;
  }

}

function FocusWindow(id,iebug)
{
  ReOrganizeWindows(id);
  var theWin = GetWindowById(id);
  if (!theWin) return;
  for (var i = 0; i < (Windows.length) ; i++)
    if (Windows[i].Win) Windows[i].Win.className="winbox_grey";
  if (iebug)
    theWin.Win.className = "winbox_active_ie";
  else
    theWin.Win.className = "winbox_active";
}

function SetWindowHeader(id,header)
{
  var tmp = null
  if (tmp = document.getElementById('winheader_'+id))
    tmp.innerHTML = header;
}

function GetWindowById(id)
{
  var i = 0;
  while (Windows[i] && Windows[i].Id != id)  i++;
  if (Windows[i])
    return Windows[i];
  else
    return false;
}

function GetWinBoxById(id)
{
  var win;
  if (win = document.getElementById("wincontent"+id))
    return win;
  else
    return false;
}

function GetWindowIndexById(id)
{
  var i = 0;
  while (Windows[i] && Windows[i].Id != id)  i++;
  if (Windows[i])
    return i;
  else
    return false;
}

function CloseWindow(id)
{
  var thewin = false;

  if (thewin = GetWindowById(id))
  {
    if (ie)
      thewin.Win.className = "winbox_active_ie";
    FadeOut(thewin.Win,false,true,false,false,"DestroyWindow("+id+")");
  }
}

function ReloadWindow(id,post_str)
{
  var thewin = false;
  if (thewin = GetWindowById(id) && (post_str || thewin.Request))
  {
    post_str = (post_str ? post_str : thewin.Request);
    AjaxRequest(post_str,'FadeWindowContent(text,'+thewin.Id+');',showloadbox(thewin.Win,true));
    thewin.Request = post_str;
  }
  FocusWindow(id);
}

function DestroyWindow(id)
{
  var thewin = null;
  var i = 0;
  i = GetWindowIndexById(id);
  if (i === false) return false;
  thewin = Windows[i];
  thewin.Win.style.display = "none";
  document.body.removeChild(thewin.Win);
  thewin.Win = null;
  thewin = null;
  Windows[i] = null;
  for (var j = i; j < (Windows.length - 1) ; j++)
    Windows[j] = Windows[j+1];
  Windows.pop();
  if (Windows.length)
    FocusWindow(Windows[Windows.length-1].Id);
  HideGreyScreen();
  ReleaseDrag();
}

function ReOrganizeWindows(tofront)
{
  var thewin = null;
  if (!tofront)
    tofront = false;
  else
  {
    tofront = GetWindowIndexById(tofront);
    thewin = Windows[tofront];
    for (var i = tofront; i < (Windows.length - 1) ; i++)
      Windows[i] = Windows[i+1];
    Windows[Windows.length-1] = thewin;
  }

  for (var i = 0; i < (Windows.length) ; i++)
    if (Windows[i].Win) Windows[i].Win.style.zIndex = 22 + i * 2;
}

function ShowGreyScreen(id)
{
  if (!GreyScreen.obj) GreyScreen.obj = document.getElementById('greyscreen');

  //if (ie) GreyScreen.obj.style.filter = "alpha(opacity="+GreyScreen.opacity+")";
  GreyScreen.obj.style.display = "";
  GreyScreen.obj.style.visibility = "visible";
  GreyScreen.fadein = true;
  GreyScreen.fadeout = false;
  ResizeGreyScreen();
  setTimeout("FadeInGreyScreen()",20);
  var thewinid = GetWindowIndexById(id);
  if (thewinid)
    GreyScreen.obj.style.zIndex = 21+thewinid*2;
  else
    GreyScreen.obj.style.zIndex = 20;
}

function HideGreyScreen()
{
  if (GreyScreen.obj)
  {
    var i = Windows.length-1 ;
    var NoWindowLeft = true;
    while ((i > -1) && !(Windows[i].Flags & WIN_MODAL)) i--;

    if (i > -1)
    {
      var FirstModalId = Windows[i].Id;
      while ((i > 0) && (Windows[i-1].Id > FirstModalId)) i--;
    }

    if (i > -1)
    {
      NoWindowLeft = false;
      GreyScreen.obj.style.zIndex = 21+i*2;
    }

    if (GreyScreen.obj.style.display != "none" && !GreyScreen.fadeout && NoWindowLeft)
    {
      GreyScreen.opacity = 40;
      if (ie) GreyScreen.obj.style.filter = "alpha(opacity="+GreyScreen.opacity+")";
      GreyScreen.obj.style.opacity = GreyScreen.opacity/100;
      GreyScreen.fadein = false;
      GreyScreen.fadeout = true;
      setTimeout("FadeOutGreyScreen()",20);
    }
  }
}

function FadeInGreyScreen()
{
  if (GreyScreen.fadein && GreyScreen.opacity < 40)
  {
    GreyScreen.opacity += 20;
    GreyScreen.obj.style.opacity = GreyScreen.opacity/100;
    if (ie) GreyScreen.obj.style.filter = "alpha(opacity="+GreyScreen.opacity+")";
    setTimeout("FadeInGreyScreen()",40);
  }
  else
    GreyScreen.fadein = false;
}

function FadeOutGreyScreen()
{
  if (GreyScreen.fadeout && GreyScreen.opacity > 10)
  {
    GreyScreen.opacity -= 20;
    GreyScreen.obj.style.opacity = GreyScreen.opacity/100;
    if (ie) GreyScreen.obj.style.filter = "alpha(opacity="+GreyScreen.opacity+")";
    setTimeout("FadeOutGreyScreen()",40);
  }
  else
  {
    GreyScreen.fadeout = false;
    if (!GreyScreen.fadein)
    {
      GreyScreen.obj.style.display = "none";
      GreyScreen.obj.style.visibility = "hidden";
    }
  }
}

function ResizeGreyScreen()
{
  if (GreyScreen.obj)
  {
    var FullWidth=document.body.scrollWidth;
    var FullHeight=0;
    /*if (document.body.scrollHeight<document.body.offsetHeight)
      FullHeight=document.body.offsetHeight;
    else
      FullHeight=document.body.scrollHeight;

    if (document.documentElement.clientHeight && (document.documentElement.clientHeight > FullHeight))
      FullHeight = document.documentElement.clientHeight;*/

    //var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
    //alert('h1:'+document.body.scrollHeight+'|'+document.body.offsetHeight);
    //document.title = getDocHeight();
    GreyScreen.obj.style.height = '0px';
    GreyScreen.obj.style.width=FullWidth+"px";
    GreyScreen.obj.style.height=getDocHeight()+"px";
  }
}

function FadeWindowContent(text,id,exec)
{
  if (!exec) exec ='';
  text = text.replace(/#thiswin#/g,id);

  FadeOut(GetWindowById(id).Content,true,true,text,'FocusWindow('+id+');','ReStretch('+id+');'+exec)//,'ReStretch('+id+');');
//FocusWindow('+id+');
}

function SetWindowContent(text,id)
{
  text = text.replace(/#thiswin#/g,id);
  GetWindowById(id).Content.innerHTML=text;
  FocusWindow(id);
  ReStretch(id);
}

function FadeStatusBar(text,id)
{
  if (!text) text = '&nbsp;';
  FadeOut(GetWindowById(id).StatusBar,true,true,text);
}

function SetStatusBar(text,id)
{
  GetWindowById(id).StatusBar.innerHTML=text;
}

function ReStretch(id)
{
  var thewin = GetWindowById(id);
  if (thewin.Content.innerHTML=='') return false;

  if (thewin.StrechTimer)
    clearTimeout(thewin.StrechTimer);

  thewin.Height = thewin.Content.offsetHeight;
  thewin.Content.style.height = thewin.Height+"px";
  thewin.Content.style.overflow = "hidden";

  if (thewin.Flags & WIN_STRETCH)
  {
    if (thewin.Content.scrollHeight > thewin.Height)
      thewin.StrechTimer = setTimeout('StrechOut('+id+')',10);
    else
      thewin.StrechTimer = setTimeout('StrechIn('+id+')',10);
  }

  if ((thewin.Flags & WIN_TRIM))
  {
    if (thewin.Content.scrollHeight > thewin.Height)
      thewin.StrechTimer = setTimeout('StrechOut('+id+',true)',5);
    else
      thewin.StrechTimer = setTimeout('StrechIn('+id+',true)',5);
  }
}

function StrechOut(id,auto)
{
  if (!auto) auto = false;
  var thewin = GetWindowById(id);
  thewin.Height+= 15;
  thewin.Content.style.height = thewin.Height+"px";
  thewin.Content.scrollTop = 0;
  if (thewin.Content.scrollHeight > thewin.Height)
  {
    thewin.StrechTimer = setTimeout('StrechOut('+id+','+auto+')',5);
  }
  else
  {
    thewin.Height = parseInt(thewin.Content.scrollHeight);
    thewin.Content.style.height = thewin.Height+"px";
    if (auto)
    {
    //thewin.Content.style.overflow = "visible";
    //thewin.Content.style.height = "auto";
    }
    ResizeGreyScreen();
    clearTimeout(thewin.StrechTimer);
    setTimeout('StrechIn('+id+')',5);
  }
}

function StrechIn(id,target,auto)
{
  if (!auto) auto = false;
  var thewin = GetWindowById(id);
  thewin.Height-= 15;
  thewin.Content.style.height = thewin.Height+"px";
  if (thewin.Content.scrollHeight <= thewin.Height)
  {
    thewin.StrechTimer = setTimeout('StrechIn('+id+','+auto+')',5);
  }
  else
  {
    thewin.Height = parseInt(thewin.Content.scrollHeight);
    thewin.Content.style.height = thewin.Height+"px";
    if (auto)
    {
    //thewin.Content.style.overflow = "visible";
    //thewin.Content.style.height = "auto";
    }
    ResizeGreyScreen();
    thewin.Content.scrollTop = 0;
    clearTimeout(thewin.StrechTimer);
  }
}

//----------------------------------------------------------------------------------------------------------------------------------

//---------------------------------------------- DRAG ENGINE --------------------------------------------------------------------------------

var HoldTheDrag = false

function HoldDrag()
{
  HoldTheDrag = true;
}

function ReleaseDrag()
{
  HoldTheDrag = false;
}

var Drag = {

  obj : null,

  init : function(o, oRoot,onDragStart,onDrag ,onDragEnd, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
  {
    o.onmousedown	= Drag.start;

    o.hmode			= bSwapHorzRef ? false : true ;
    o.vmode			= bSwapVertRef ? false : true ;

    o.root = oRoot && oRoot != null ? oRoot : o ;
    o.dragcollide = Drag.dragcollide;

    o.onDragStart = onDragStart;
    o.onDragEnd = onDragEnd;
    o.onDrag = onDrag;

    if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
    if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
    if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
    if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

    o.minX	= (minX !== false && minX !== undefined) ? minX : null;
    o.minY	= (minY !== false && minX !== undefined) ? minY : null;
    o.maxX	= (maxX !== false && minX !== undefined) ? maxX : null;
    o.maxY	= (maxY !== false && minX !== undefined) ? maxY : null;

    o.lastnx = parseInt(o.root.style.left);
    o.lastny = parseInt(o.root.style.top);

    o.xMapper = fXMapper ? fXMapper : null;
    o.yMapper = fYMapper ? fYMapper : null;

    o.root.onDragStart	= new Function();
    o.root.onDragEnd	= new Function();
    o.root.onDrag		= new Function();
  },

  start : function(e)
  {
    if (HoldTheDrag) return false;
    var o = Drag.obj = this;
    e = Drag.fixE(e);
    var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
    var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
    o.root.onDragStart(x, y);

    if (Drag.obj.onDragStart) eval(Drag.obj.onDragStart);

    o.lastMouseX	= e.clientX;
    o.lastMouseY	= e.clientY;

    if (o.hmode) {
      if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
      if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
    } else {
      if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
      if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
    }

    if (o.vmode) {
      if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
      if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
    } else {
      if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
      if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
    }

    document.onmousemove	= Drag.drag;
    document.onmouseup		= Drag.end;
    

    return false;
  },

  /*dragcollide : function (o2,left,width)
  {
    var o = this;
    /*if (left)
    {
      if (o.lastnx+width > o2.lastnx)
        return o2.lasnx-width;
    }
    else
      if (o2.lastnx+width > o.lastnx)
        return o2.lasnx+width;
    return o.lastnx;
  },*/
  
  drag : function(e)
  {
    e = Drag.fixE(e);
    var o = Drag.obj;

    var ey	= e.clientY;
    var ex	= e.clientX;
    var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
    var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
    var nx, ny;

    if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
    if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
    if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
    if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

    nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
    ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));
    o.lastnx = nx;
    o.lasny = ny;

    if (o.xMapper)	nx =o.xMapper(y);
    else if (o.yMapper)	ny = o.yMapper(x);

    if (o.onDrag) eval(o.onDrag);

    o.root.style[o.hmode ? "left" : "right"] = nx + "px";
    o.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
    
    //if (ie) Drag.obj.root.style.filter="alpha(opacity=70)";

    o.lastMouseX	= ex;
    o.lastMouseY	= ey;

    o.root.onDrag(nx, ny);

    return false;
  },

  end : function()
  {
    document.onmousemove = null;
    document.onmouseup   = null;
    if (Drag.obj.onDragEnd) eval(Drag.obj.onDragEnd);

    /*Drag.obj.root.style.opacity=null;
        if (ie) Drag.obj.root.style.filter=null;*/

    Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
      parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));

    Drag.obj = null;

  },

  fixE : function(e)
  {
    if (typeof e == 'undefined') e = window.event;
    if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
    if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
    return e;
  }
};
//-----------------------------------------------------------------------------------------------------------------------

//-----------------------------------------------

function attEvt_ie(obj, event, func)
{
  obj.attachEvent('on' + event, func);
}

function attEvt_moz(obj, event, func)
{
  obj.addEventListener(event, func, false);
}
if (ie)
  attEvt = attEvt_ie;
else
  attEvt = attEvt_moz;

function createMethodRef(object, methodName, arg2)
{
  return function()
  {
    return object[methodName].apply(object, [arg2, arguments]);
  }
}

function ImgPreloader()
{
  this.ImgObj=false;
  this.AfterAction='';

  this.ImgLoad=OnImgLoad;
  this.PreloadImg=ImgPreload;

  function OnImgLoad()
  {
    //document.images[document.images.length]=this.ImgObj;
    eval(this.AfterAction);
  }

  function ImgPreload(src,exec)
  {
    this.AfterAction=exec;
    this.ImgObj= new Image();
    this.ImgObj.src=src;
    if (this.ImgObj.complete==false)
      attEvt(this.ImgObj,'load',createMethodRef(this,'ImgLoad'));
    else eval(exec);
  }
}

//----------------------------------------------
//var HYPEROBJECT = null;

function MakeConfirmation(conf_text,width,height,yesexec,yes,noexec,no)
{
  var nobutton='';
  if (no) nobutton=' <input class="simplebutton_dim" onmouseover="this.className=\'simplebutton_lit\'" onmouseout="this.className=\'simplebutton_dim\'" type=button id="button" value="'+no+'" onclick="'+noexec+';CloseWindow(#thiswin#);">';
  var id = ShowWinBox('',false,width,height,'Dialog',(WIN_NOCLOSE | WIN_TRIM | WIN_MODAL));
  var temptext = '<form name="winform_#thiswin#" id="winform_#thiswin#" action="" onsubmit="return false;"><table width="100%" cellpadding=0 cellspacing=0 style="margin-bottom:10px;"><tr><td><div width="100%" style="font-size:12px;margin:10px 10px 5px 10px;" >'+conf_text+'</div></td></tr><tr><td><div width="100%" align="center"><input id="yesbutton_#thiswin#" class="simplebutton_dim" onmouseover="this.className=\'simplebutton_lit\'" onmouseout="this.className=\'simplebutton_dim\'" type=submit value="'+yes+'" onclick="'+yesexec+';CloseWindow(#thiswin#);">'+nobutton+'</div></td></tr></table></form>';
  SetWindowContent(temptext, id);
  //SetWindowContent('',id);
  ReStretch(id);
  document.getElementById('yesbutton_'+id).focus();
  return id;
}

function notice(notice_text)
{
  //return alert(notice_text);
  MakeConfirmation('<img src="/img/info.gif" style="float:left;margin-right:10px;">'+notice_text,400,200,'','OK');
}

function getWinForm(winid)
{
  var theForm = document.forms['winform_'+winid];
  if (!theForm)
  {
    alert('Cannot find form in window #'+winid);
    return false;
  }
  else
    return theForm;
}

function ShowPic(obj,name,src,width,height)
{
  var loadbox=showloadbox(obj,true);
  var ImgPrel = new ImgPreloader();
  ImgPrel.PreloadImg(src,'showpic2(false,"'+name+'","'+src+'",'+width+','+height+');hidebox('+loadbox+')');
}


function showpic2(obj,name,src,width,height)
{
  var id = ShowWinBox('<a href="" onclick="CloseWindow(#thiswin#);return false;" title="[click to close]"><img class="image" width="'+width+'" height="'+height+'" src="'+src+'"></a>',false,width,height,name,WIN_MODAL);
//SetWindowContent(,id);
}

///--------------------- Fader -------------------------


FadeObjects= new Array();

function FadeOut(obj,fin,fout,text,exec2,exec1)
{
  var i=0;
  if (!fin) fin = false;
  if (!fout) fout = false;
  if (!text) text = false;
  if (!obj) return;
  var FOLen = FadeObjects.length-1;
  while (FOLen>-1 && (!FadeObjects[FOLen] || FadeObjects[FOLen].obj!=obj)) FOLen--;
  if (FOLen>-1)
  {
    i = FOLen;
  }
  else
  {
    while (FadeObjects[i] || FadeObjects[i]!=null) i++;
  }
  if (!FadeObjects[i] || FadeObjects[i]==null)
  {
    FadeObjects[i]=[];
    FadeObjects[i].obj=obj;
  }
  else
  if ((FadeObjects[i].fadein==fin) && (FadeObjects[i].fadeout==fout) && (FadeObjects[i].text==text) && (FadeObjects[i].exec2==exec2) && (FadeObjects[i].exec1==exec1))
  {
    return false;
  }

  if (((!fin && fout && FadeObjects[i].obj.style.visibility == 'hidden') || (fin && !fout && (!FadeObjects[i].obj.style.visibility || FadeObjects[i].obj.style.visibility == 'visible'))) && !FadeObjects[i].timer)
  {
    FadeObjects[i] = null;
    return false;
  }
  FadeObjects[i].opacity = 0;
  FadeObjects[i].fadein=fin;
  FadeObjects[i].fadeout=fout;
  FadeObjects[i].text=text;
  if (exec2)
    FadeObjects[i].exec2=exec2;
  else
    FadeObjects[i].exec2=false;

  if (exec1)
    FadeObjects[i].exec1=exec1;
  else
    FadeObjects[i].exec1=false;

  if (fout)
  {
    if (!obj.style.opacity || obj.style.opacity == null || obj.style.opacity === '')
    {
      obj.style.opacity = 1;
      FadeObjects[i].opacity = 100;
      if (ie) obj.style.filter = "alpha(opacity=100)";
      FadeObjects[i].obj.style.visibility="";
      delete FadeObjects[i].obj.style.visibility;
    }
  }
  else if(fin)
  {
    if (!obj.style.opacity || obj.style.opacity == null || obj.style.opacity === '' || FadeObjects[i].obj.style.visibility=='hidden')
    {
      obj.style.opacity=0;
      FadeObjects[i].opacity = 0;
      if (ie) obj.style.filter="alpha(opacity=0)";
      FadeObjects[i].obj.style.visibility="";
      delete FadeObjects[i].obj.style.visibility;
    }
  }

  if (fout && obj.style.opacity > 0)
  {
    FadeObjects[i].opacity = parseInt(obj.style.opacity*100);
    if (FadeObjects[i].timer!=null)
      clearTimeout(FadeObjects[i].timer);
    FadeObjects[i].timer=setTimeout("fadeoutobj("+i+");",10);//*100;
  }
  else
  if (fin)
  {
    FadeObjects[i].opacity = parseInt(obj.style.opacity*100);
    if (FadeObjects[i].timer!=null)
      clearTimeout(FadeObjects[i].timer);
    if (text!=false)
      obj.innerHTML=text;
    FadeIn(i);
  }
}

function FadeIn(i)
{
  FadeObjects[i].obj.style.visibility="";
  delete FadeObjects[i].obj.style.visibility;
  if (FadeObjects[i].exec1) eval(FadeObjects[i].exec1);
  if (FadeObjects[i].timer!=null)  clearTimeout(FadeObjects[i].timer);
  FadeObjects[i].timer=setTimeout("fadeinobj("+i+");",10);
}

function KillFadeObject(i)
{
  FadeObjects[i] = null;
}

function fadeinobj(i)
{
  var obj = FadeObjects[i].obj;
  var objstyle = obj.style;
  if (FadeObjects[i].opacity <= 100)
  {
    objstyle.opacity = FadeObjects[i].opacity/100;
    if (ie) objstyle.filter="alpha(opacity="+FadeObjects[i].opacity+")";
    FadeObjects[i].opacity += 20;
    FadeObjects[i].timer=setTimeout("fadeinobj("+i+");",30);
  }
  else
  {
    FadeObjects[i].opacity = 0;
    if (ie)
    {
      objstyle.filter = null;
      delete objstyle.filter;
    }
    objstyle.opacity = 1;
    delete objstyle.opacity;
    if (FadeObjects[i].exec2) eval(FadeObjects[i].exec2);
    clearTimeout(FadeObjects[i].timer)
    KillFadeObject(i);
  }
}

function fadeoutobj(i)
{
  var obj=FadeObjects[i].obj;
  var objstyle=obj.style;
  if (FadeObjects[i].opacity > 0)
  {
    objstyle.opacity = FadeObjects[i].opacity/100;
    if (ie) objstyle.filter="alpha(opacity="+FadeObjects[i].opacity+")";
    FadeObjects[i].opacity -= 20;
    FadeObjects[i].timer=setTimeout("fadeoutobj("+i+");",30);
  }
  else
  {
    FadeObjects[i].opacity = 0;
    objstyle.opacity = 0;
    if (ie) objstyle.filter="alpha(opacity=0)";
    if (FadeObjects[i].fadein && FadeObjects[i].fadeout)
    {
      if (FadeObjects[i].text!=false)
        FadeObjects[i].obj.innerHTML=FadeObjects[i].text;

      if (FadeObjects[i].exec1) eval(FadeObjects[i].exec1);
      FadeObjects[i].fadeout=false;
      FadeObjects[i].timer=setTimeout("fadeinobj("+i+");",30);
    }
    else
    {
      clearTimeout(FadeObjects[i].timer);
      objstyle.visibility="hidden";
      if (ie)
      {
        objstyle.filter = null;
        delete objstyle.filter;
      }
      //objstyle.opacity = 1;
      delete objstyle.opacity;
      if (FadeObjects[i].exec1) eval(FadeObjects[i].exec1);
      KillFadeObject(i);
    }
  }
}
//----------------------------------------INFO BOX--------------------------------------------------

var InfoBox= new Array();
var InfoBoxLeftPosCorr=-13;//------------------------------------
var InfoBoxTopPosCorr=2; //----------------------
var InfoBoxTimerID=false;
var prevobj=false;

function getinfobox(obj,addclosers)
{
  var i=1;
  while (InfoBox[i] && InfoBox[i].obj!=obj) i++;
  if (!InfoBox[i] || !InfoBox[i].block)
  {
    InfoBox[i]=[];
    //InfoBox[i].obj=obj;
    var divblock=document.createElement("div");
    divblock.setAttribute("id", "infobox"+i);
    document.body.appendChild(divblock);
    divblock.className='infobox';
    InfoBox[i].block=divblock;
    InfoBox[i].block.style.visibility = 'hidden';
    addclosers = addclosers ? 'onmouseover="StopInfoBoxHide('+i+');" onmouseout="InfoBoxTimeout('+i+')"' : '';
    InfoBox[i].block.innerHTML='<div id="infobox'+i+'content" class="infoboxcontent" '+addclosers+'></div>';//
    InfoBox[i].contentbox=document.getElementById("infobox"+i+"content");
    InfoBox[i].toleft=false;  //------------
    InfoBox[i].toup=false;  //--------------
  }
  return i;
}

function ShowInfoBox(boxcontent,obj,width,height,toleft,topcorr,donthideall,leftcorr)
{
  var i=getinfobox(obj,donthideall);
  if (!donthideall)
    HideAllBoxes();
  if (!topcorr) topcorr = 0;
  if (!leftcorr) leftcorr = 0;
  if (InfoBox[i].obj!=obj)
  {
    //prevobj=i;
    InfoBox[i].obj=obj;
    if (!toleft) toleft = false;
    boxcontent = boxcontent.replace(/#thisbox#/g,i);
    InfoBox[i].contentbox.innerHTML = boxcontent;
    var x = getposOffset(obj, "left")-browserleftcorrection;
    var y = getposOffset(obj, "top")-4;
    y+=topcorr;
    x+=leftcorr;
    if (width)
      InfoBox[i].contentbox.style.width = width+"px";
    else
      width = InfoBox[i].contentbox.offsetWidth;
    if (height)
      InfoBox[i].contentbox.style.height = height+"px";
    else
      height = InfoBox[i].contentbox.offsetHeight;

    //var Width = //InfoBox[i].contentbox.offsetWidth;
    //var Height = //InfoBox[i].contentbox.offsetHeight;

    if (((x-23+browserleftcorrection-width)<0) || !toleft)
      InfoBox[i].toleft=false;
    else
      InfoBox[i].toleft=(InfoBox[i].toleft || true);

    if ((y-height+13)<0)
      InfoBox[i].toup=false;
    else
      InfoBox[i].toup=(InfoBox[i].toup && true);
    //InfoBox[i].speed=Math.floor(Math.sqrt(Width+Height)*0.3);
    if (InfoBox[i].toleft)
    {
      InfoBox[i].block.style.left=x+InfoBoxLeftPosCorr-width+"px";
    }
    else
    {
      InfoBox[i].block.style.left=x-5-InfoBoxLeftPosCorr+obj.offsetWidth+"px";
    }
    if (InfoBox[i].toup)
    {
      InfoBox[i].block.style.top=y+8+InfoBoxTopPosCorr+"px";
    }
    else
    {
      InfoBox[i].block.style.top=y-3+InfoBoxTopPosCorr+"px";
    }
    if (boxcontent!='')
      InfoBox[i].content=boxcontent;
    InfoBox[i].width=width;
    InfoBox[i].height=height;
    InfoBox[i].leftcorr=x+browserleftcorrection-InfoBoxLeftPosCorr;
    InfoBox[i].upcorr=y+21+InfoBoxTopPosCorr;
    //FadeOut(InfoBox[i].block, true, false);
    InfoBox[i].block.style.visibility = '';
    return i;
  }
  else
  {
    InfoBox[i].block.style.visibility = '';
    //FadeOut(InfoBox[i].block, true, false);
    return i;
  }
}

function GetBoxByObj(obj)
{
  var i=1;
  while (InfoBox[i] && InfoBox[i].obj!=obj) i++;
  if (!InfoBox[i] || !InfoBox[i].block) return false;
  else return i;
}


function SetInfoBoxText(obj,text)
{
  var i=1;
  if (i=GetBoxByObj(obj))
  {
    if (InfoBox[i].contentbox.innerHTML!='')
      InfoBox[i].contentbox.innerHTML=text;
    else
      InfoBox[i].content=text;
  }
}

function SetInfoBoxText2(i,text)
{
  if (InfoBox[i].contentbox.innerHTML!='')
    InfoBox[i].contentbox.innerHTML=text;
  else
    InfoBox[i].content=text;
}

function StopInfoBoxHide(i)
{
  if (InfoBox[i].hidetimer) clearTimeout(InfoBox[i].hidetimer);
  //FadeOut(InfoBox[i].block, true, false);
  InfoBox[i].block.style.visibility = '';
}

function HideInfoBox(i)
{
  InfoBox[i].block.style.visibility = 'hidden';
//FadeOut(InfoBox[i].block, false, true);
}

function HideAllBoxes()
{
  for (var i=0;i<InfoBox.length;i++)
    if (InfoBox[i] && InfoBox[i].showing) HideInfoBox(i);
}


function InfoBoxTimeout2(obj)
{
  var i = null;
  if (i=GetBoxByObj(obj))
    InfoBox[i].hidetimer=setTimeout("HideInfoBox("+i+")",100);
}


function InfoBoxTimeout(i)
{
  InfoBox[i].hidetimer=setTimeout("HideInfoBox("+i+")",200);
}


function ShowHideSection(winid,section,notlast)
{
  var start = null;
  if (!notlast)
    start = 'e';
  else
    start = 'm';
  Section = document.getElementById(section);
  var img = document.getElementById(section+'_img');

  if (Section.style.display == 'none')
  {
    Section.style.display = 'block';
    img.src = '/img/sec_o'+start+'.gif';
  }
  else
  {
    Section.style.display = 'none';
    img.src = '/img/sec_c'+start+'.gif';
  }
  if (winid) ReStretch(winid);
}

var MSIE = navigator.userAgent.indexOf('MSIE')>=0?true:false;
var navigatorVersion = navigator.appVersion.replace(/.*?MSIE (\d\.\d).*/g,'$1')/1;

var namedColors = new Array('Alice Blue','Antique White','Aqua','Aquamarine','Azure','Beige','Bisque','Black','Blanched Almond','Blue','Blue Violet','Brown',
  'Burly Wood','Cadet Blue','Chartreuse','Chocolate','Coral','Cornflower Blue','Cornsilk','Crimson','Cyan','Dark Blue','Dark Cyan','Dark Golden Rod','Dark Gray',
  'Dark Green','Dark Khaki','Dark Magenta','Dark OliveGreen','Dark Orange','Dark Orchid','Dark Red','Dark Salmon','Dark Sea Green','Dark Slate Blue','Dark Slate Gray',
  'Dark Turquoise','Dark Violet','Deep Pink','Deep Sky Blue','Dim Gray','Dodger Blue','Feldspar','Fire Brick','Floral White','Forest Green','Fuchsia','Gainsboro',
  'Ghost White','Gold','Golden Rod','Gray','Green','Green Yellow','Honey Dew','Hot Pink','Indian Red','Indigo','Ivory','Khaki','Lavender','Lavender Blush',
  'Lawn Green','Lemon Chiffon','Light Blue','Light Coral','Light Cyan','Light Golden Rod Yellow','Light Grey','Light Green','Light Pink','Light Salmon','Light Sea Green',
  'Light Sky Blue','Light Slate Blue','Light Slate Gray','Light Steel Blue','Light Yellow','Lime','Lime Green','Linen','Magenta','Maroon','Medium Aqua Marine',
  'Medium Blue','Medium Orchid','Medium Purple','Medium Sea Green','Medium Slate Blue','Medium Spring Green','Medium Turquoise','Medium Violet Red','Midnight Blue',
  'Mint Cream','Misty Rose','Moccasin','Navajo White','Navy','Old Lace','Olive','Olive Drab','Orange','Orange Red','Orchid','Pale Golden Rod','Pale Green',
  'Pale Turquoise','Pale Violet Red','Papaya Whip','Peach Puff','Peru','Pink','Plum','Powder Blue','Purple','Red','Rosy Brown','Royal Blue','Saddle Brown',
  'Salmon','Sandy Brown','Sea Green','Sea Shell','Sienna','Silver','Sky Blue','Slate Blue','Slate Gray','Snow','Spring Green','Steel Blue','Tan','Teal','Thistle',
  'Tomato','Turquoise','Violet','Violet Red','Wheat','White','White Smoke','Yellow','Yellow Green');

var namedColorRGB = new Array('#F0F8FF','#FAEBD7','#00FFFF','#7FFFD4','#F0FFFF','#F5F5DC','#FFE4C4','#000000','#FFEBCD','#0000FF','#8A2BE2','#A52A2A','#DEB887',
  '#5F9EA0','#7FFF00','#D2691E','#FF7F50','#6495ED','#FFF8DC','#DC143C','#00FFFF','#00008B','#008B8B','#B8860B','#A9A9A9','#006400','#BDB76B','#8B008B',
  '#556B2F','#FF8C00','#9932CC','#8B0000','#E9967A','#8FBC8F','#483D8B','#2F4F4F','#00CED1','#9400D3','#FF1493','#00BFFF','#696969','#1E90FF','#D19275',
  '#B22222','#FFFAF0','#228B22','#FF00FF','#DCDCDC','#F8F8FF','#FFD700','#DAA520','#808080','#008000','#ADFF2F','#F0FFF0','#FF69B4','#CD5C5C','#4B0082',
  '#FFFFF0','#F0E68C','#E6E6FA','#FFF0F5','#7CFC00','#FFFACD','#ADD8E6','#F08080','#E0FFFF','#FAFAD2','#D3D3D3','#90EE90','#FFB6C1','#FFA07A','#20B2AA',
  '#87CEFA','#8470FF','#778899','#B0C4DE','#FFFFE0','#00FF00','#32CD32','#FAF0E6','#FF00FF','#800000','#66CDAA','#0000CD','#BA55D3','#9370D8','#3CB371',
  '#7B68EE','#00FA9A','#48D1CC','#C71585','#191970','#F5FFFA','#FFE4E1','#FFE4B5','#FFDEAD','#000080','#FDF5E6','#808000','#6B8E23','#FFA500','#FF4500',
  '#DA70D6','#EEE8AA','#98FB98','#AFEEEE','#D87093','#FFEFD5','#FFDAB9','#CD853F','#FFC0CB','#DDA0DD','#B0E0E6','#800080','#FF0000','#BC8F8F','#4169E1',
  '#8B4513','#FA8072','#F4A460','#2E8B57','#FFF5EE','#A0522D','#C0C0C0','#87CEEB','#6A5ACD','#708090','#FFFAFA','#00FF7F','#4682B4','#D2B48C','#008080',
  '#D8BFD8','#FF6347','#40E0D0','#EE82EE','#D02090','#F5DEB3','#FFFFFF','#F5F5F5','#FFFF00','#9ACD32');


var color_picker_div = false;
var color_picker_active_input = false;

function colorPickerGetTopPos(inputObj)
{

  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null){
    returnValue += inputObj.offsetTop;
  }
  return returnValue;
}

function colorPickerGetLeftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
  return returnValue;
}

function cancelColorPickerEvent(){
  return false;
}

function createNamedColors(inputObj){
  for(var no=0;no<namedColors.length;no++){
    var color = namedColorRGB[no];
    var div = document.createElement('DIV');
    div.style.backgroundColor=color;
    div.innerHTML = '<span></span>';
    div.className='colorSquare';
    div.title = namedColors[no];
    div.onclick = chooseColor;
    div.setAttribute('rgbColor',color);
    div.setAttribute('nameColor',namedColors[no]);
    inputObj.appendChild(div);
  }
}


function chooseColor()
{
  var color = this.getAttribute('rgbColor');
  var obj = color_picker_active_input;
  eval(color_picker_exec);
  FadeOut(color_picker_div,false,true);
}


function showColorPicker(inputObj,exec)
{
  if(!color_picker_div){
    color_picker_div = document.createElement('DIV');
    color_picker_div.className = 'colorPicker';
    document.body.appendChild(color_picker_div);
    createNamedColors(color_picker_div);
  }
  color_picker_div.style.left = colorPickerGetLeftPos(inputObj) + 'px';
  color_picker_div.style.top = colorPickerGetTopPos(inputObj) + inputObj.offsetHeight + 2 + 'px';
  FadeOut(color_picker_div,true,false);
  color_picker_exec = exec;
  color_picker_active_input = inputObj;
}

// iMouseDown represents the current mouse button state: up or down
/*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var lastActiveCont = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;
var CurrentContainer = null;
var DragDrops   = [];
var curTarget   = null;
var lastTarget  = null;
var dragHelper  = null;
var dragBuffer  = null;
var resetCoords = null;
var dragShadow  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;
//var nImg        = new Image();



Number.prototype.NaN0=function(){
  return isNaN(this)?0:this;
}

function AddToDragContainer()
{
  var i = 0;
  while (i < DragDrops.length)
  {
    if (!DragDrops[i]) {
      i++;
      continue;
    }
    var k = DragDrops[i].length-1;
    while (k >= 0 && !document.getElementById(DragDrops[i][k].id))
    {
      DragDrops[i].pop();
      k--;
    }
    if (DragDrops[i].length==0) DragDrops[i] = null;
    i++;
  }

  for (var i=0; i<arguments.length; i++)
  {
    var cObj = arguments[i];
    var TempCont = null;
    var found = false;
    var cDrag = 0;
    var ContClass = cObj.getAttribute('contClass');

    for (var j = 0; j < DragDrops.length; j++)
    {
      TempCont = DragDrops[j];
      //writedebug('checking ('+(j+1)+'/'+DragDrops.length+') '+TempCont[0].getAttribute('contClass')+' == '+ContClass);
      if (!TempCont || TempCont[0].getAttribute('contClass') == ContClass)
      {
        cDrag = j;
        found = true;
        break;
      }
    }

    if (!found)
    {
      cDrag = DragDrops.length;
      DragDrops[cDrag] = [];
    //writedebug('nc:'+cDrag);
    }
    else
    {
      if (!DragDrops[cDrag]) DragDrops[cDrag] = [];
    //else
    //  if (!DragDrops[cDrag][0]) writedebug('Zdezdec!:'+cDrag);
    }

    TempCont = DragDrops[cDrag];

    /*var tempObj = []
    tempObj.offsetTop = cObj.offsetTop;
    tempObj.offsetLeft = cObj.offsetLeft;
    tempObj.offsetHeight = cObj.offsetHeight;
    tempObj.offsetWidth = cObj.offsetWidth;*/

    TempCont.push(cObj);
    cObj.setAttribute('DropObj', cDrag);

    for (var j=0; j<cObj.childNodes.length; j++)
    {
      // Firefox puts in lots of #text nodes...skip these
      if (cObj.childNodes[j].nodeName=='#text') continue;
      //cObj.childNodes[j].style.border="1px solid #55FF55";
      cObj.childNodes[j].onmousedown = mouseDown;      //attEvt(cObj.childNodes[j], 'mousedown', mouseDown);//*/createMethodRef(window,'alert','asdasder!!'))
      cObj.childNodes[j].setAttribute('DragObj', cDrag);
    }
  }
}

function CreateDragContainer(){
  /*
	Create a new "Container Instance" so that items from one "Set" can not
	be dragged into items from another "Set"
	*/
  var cDrag        = DragDrops.length;
  DragDrops[cDrag] = [];

  /*
	Each item passed to this function should be a "container".  Store each
	of these items in our current container
	*/
  for(var i=0; i<arguments.length; i++){
    var cObj = arguments[i];
    DragDrops[cDrag].push(cObj);
    cObj.setAttribute('DropObj', cDrag);

    /*
		Every top level item in these containers should be draggable.  Do this
		by setting the DragObj attribute on each item and then later checking
		this attribute in the mouseMove function
		*/
    for(var j=0; j<cObj.childNodes.length; j++){

      // Firefox puts in lots of #text nodes...skip these
      if(cObj.childNodes[j].nodeName=='#text') continue;
      cObj.childNodes[j].onmousedown = mouseDown;      //attEvt(cObj.childNodes[j], 'mousedown', mouseDown);//*/createMethodRef(window,'alert','asdasder!!'))
      cObj.childNodes[j].setAttribute('DragObj', cDrag);
    }
  }
}

function getPosition(e){
  var left = 0;
  var top  = 0;
  if (!e) return {
    x:0,
    y:0
  };
  while (e.offsetParent){
    left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
    top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
    e     = e.offsetParent;
  }

  left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
  top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

  return {
    x:left,
    y:top
  };
}

function mouseCoords(ev){
  if(ev.pageX || ev.pageY){
    return {
      x:ev.pageX,
      y:ev.pageY
    };
  }
  return {
    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:ev.clientY + document.body.scrollTop  - document.body.clientTop
  };
}


function getMouseOffset(target, ev){
  ev = ev || window.event;

  var docPos    = getPosition(target);
  var mousePos  = mouseCoords(ev);
  return {
    x:mousePos.x - docPos.x,
    y:mousePos.y - docPos.y
  };
}

function mouseMove(ev){

  ev         = ev || window.event;
  /*
	We are setting target to whatever item the mouse is currently on

	Firefox uses event.target here, MSIE uses event.srcElement
	*/
  var target   = ev.target || ev.srcElement;
  var mousePos = mouseCoords(ev);


  /*
		dragObj is the grouping our item is in (set from the createDragContainer function).
		if the item is not in a grouping we ignore it since it can't be dragged with this
		script.
		*/
  var dragObj = null;
  if (target.getAttribute)
    dragObj = target.getAttribute('DragObj');

  // if the mouse was moved over an element that is draggable
  if(dragObj!=null){

    // if the user is just starting to drag the element
    if(iMouseDown && !lMouseState){

      // mouseDown target
      curTarget     = target;

      // Record the mouse x and y offset for the element
      rootParent    = curTarget.parentNode;
      rootSibling   = curTarget.nextSibling;

      mouseOffset   = getMouseOffset(target, ev);


      // We remove anything that is in our dragHelper DIV so we can put a new item in it.
      for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);
      dragBuffer = null;
      resetCoords = false;


      // Make a copy of the current item and put it in our drag helper.
      //Buffer

      // disable dragging from our helper DIV (it's already being dragged)

      var DragFunc = curTarget.parentNode.getAttribute('dragFunc');
      if (DragFunc)
      {
        var dobj = curTarget;
        eval('dragBuffer = '+DragFunc);
        //alert(dragBuffer.html);
        dragHelper.innerHTML = dragBuffer.html;
        resetCoords = curTarget.parentNode.getAttribute('resetCoords');
        if (resetCoords)
        {
          mouseOffset.x = 0;
          mouseOffset.y = 0;
        }
      }
      else
      {
        dragHelper.appendChild(curTarget.cloneNode(true));
        dragHelper.firstChild.removeAttribute('DragObj');
        var DragClass = curTarget.parentNode.getAttribute('dragClass');
        if (DragClass)
        {
          dragHelper.firstChild.setAttribute('origClass',dragHelper.firstChild.className);
          dragHelper.firstChild.className = DragClass;
        }
      }
      dragHelper.style.display = '';
      dragHelper.style.position = 'absolute';
      lastActiveCont = curTarget.parentNode;
      /*
				Record the current position of all drag/drop targets related
				to the element.  We do this here so that we do not have to do
				it on the general mouse move event which fires when the mouse
				moves even 1 pixel.  If we don't do this here the script
				would run much slower.
				*/

      var dragConts = DragDrops[dragObj];

      /*
				first record the width/height of our drag item.  Then hide it since
				it is going to (potentially) be moved out of its parent.
				*/
      curTarget.setAttribute('startWidth',  parseInt(curTarget.offsetWidth));
      curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
      curTarget.style.display  = 'none';
      dragHelper.style.left = (mousePos.x - mouseOffset.x)+"px";

      // loop through each possible drop container
      for(var i=0; i<dragConts.length; i++){
        with(dragConts[i]){

          var pos = getPosition(dragConts[i]);
          //writedebug('container '+dragObj+'/'+i+' saved at X '+pos.x+', Y '+pos.y+', W '+offsetWidth+', H '+offsetHeight);
          /*
						save the width, height and position of each container.

						Even though we are saving the width and height of each
						container back to the container this is much faster because
						we are saving the number and do not have to run through
						any calculations again.  Also, offsetHeight and offsetWidth
						are both fairly slow.  You would never normally notice any
						performance hit from these two functions but our code is
						going to be running hundreds of times each second so every
						little bit helps!

						Note that the biggest performance gain here, by far, comes
						from not having to run through the getPosition function
						hundreds of times.
						*/
          setAttribute('startWidth',  parseInt(offsetWidth));
          setAttribute('startHeight', parseInt(offsetHeight));
          setAttribute('startLeft',   pos.x);
          setAttribute('startTop',    pos.y);
          }

        // loop through each child element of each container
        for(var j=0; j<dragConts[i].childNodes.length; j++){
          with(dragConts[i].childNodes[j]){
            if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;

            var pos = getPosition(dragConts[i].childNodes[j]);

            // save the width, height and position of each element
            setAttribute('startWidth',  parseInt(offsetWidth));
            setAttribute('startHeight', parseInt(offsetHeight));
            //writedebug('saved:'+scrLeft+' '+scrTop);
            setAttribute('startLeft',   pos.x) //-scrLeft);
            setAttribute('startTop',    pos.y)//-scrTop);
            }
        }
      }
      var gostarteval = rootParent.getAttribute('onDragStart');
      if (gostarteval) eval(gostarteval);
    }
  }

  // If we get in here we are dragging something
  if(curTarget){
    // move our helper div to wherever the mouse is (adjusted by mouseOffset)
    dragHelper.style.top  = (mousePos.y - mouseOffset.y)+"px";
    dragHelper.style.left = (mousePos.x - mouseOffset.x)+"px";

    var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
    if (!dragConts) writedebug('WTF:'+curTarget.getAttribute('DragObj')+' | '+DragDrops.length);
    var activeCont = null;

    var addX = resetCoords ? 0 : (parseInt(curTarget.getAttribute('startWidth')) /2);
    var addY = resetCoords ? 0 : (parseInt(curTarget.getAttribute('startHeight')) /2);

    var xPos = mousePos.x - mouseOffset.x + addX;
    var yPos = mousePos.y - mouseOffset.y + addY;

    // check each drop container to see if our target object is "inside" the container
    //for(var i=(dragConts.length-1); i<=0; i--){
    for(var i=(dragConts.length-1); i>=0; i--){
      with(dragConts[i]){
        if((parseInt(getAttribute('startLeft'))                                           < xPos) &&
          (parseInt(getAttribute('startTop'))                                            < yPos) &&
          ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
          ((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){

          /*
							our target is inside of our container so save the container into
							the activeCont variable and then exit the loop since we no longer
							need to check the rest of the containers
							*/
          activeCont = dragConts[i];
          CurrentContainer = activeCont;

          // exit the for loop
          break;
        }
        }
    }

    // Our target object is in one of our containers.  Check to see where our div belongs
    if(activeCont){
      if(activeCont!=curTarget.parentNode){

      }

      // beforeNode will hold the first node AFTER where our div belongs
      var beforeNode = null;
      var activeContObjFunc = activeCont.getAttribute('dragFunc');

      if (dragBuffer && activeContObjFunc && activeCont!=lastActiveCont)
      {
        if (curTarget.parentNode) curTarget.parentNode.removeChild(curTarget);
        var dobj = dragBuffer;
        var tmp = curTarget.getAttribute('DragObj');
        var dragBuffer2 = document.createElement('DIV');
        var curParent = activeCont;
        document.body.appendChild(dragBuffer2);
        eval('dragBuffer2.innerHTML = '+activeContObjFunc);
        curTarget = dragBuffer2.firstChild;
        curTarget.style.display="none";
        curTarget.onmousedown = mouseDown;
        curTarget.setAttribute('DragObj',tmp);
      }
      //if (activeCont.getAttribute('isDropTarget'))

      // loop through each child node (skipping text nodes).
      for(var i=activeCont.childNodes.length-1; i>=0; i--){
        with(activeCont.childNodes[i]){
          if(nodeName=='#text') continue;

          // if the current item is "After" the item being dragged
          if(curTarget != activeCont.childNodes[i]                                                  &&
            ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
            ((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){
            beforeNode = activeCont.childNodes[i];
          }
          }
      }

      // the item being dragged belongs before another item
      if(beforeNode){
        if(beforeNode!=curTarget.nextSibling){
          activeCont.insertBefore(curTarget, beforeNode);
        }

      // the item being dragged belongs at the end of the current container
      } else {
        if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
          activeCont.appendChild(curTarget);
        }
      }

      // the timeout is here because the container doesn't "immediately" resize
      setTimeout(function(){
        var contPos = getPosition(activeCont);
        activeCont.setAttribute('startWidth',  parseInt(activeCont.offsetWidth));
        activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
        activeCont.setAttribute('startLeft',   contPos.x);
        activeCont.setAttribute('startTop',    contPos.y);
        if (!curTarget) return false;
        var sometmp = getPosition(curTarget);
        dragShadow.style.left = (sometmp.x-1)+"px";
        dragShadow.style.top = (sometmp.y-1)+"px";
        dragShadow.style.width = (parseInt(curTarget.offsetWidth)-1)+"px";
        dragShadow.style.height = (parseInt(curTarget.offsetHeight)-1)+"px";

      }, 5);

      // make our drag item visible
      if(curTarget.style.display!=''){
        curTarget.style.display    = '';

        //curTarget.style.visibility = 'hidden';
        if (ie6)
          curTarget.style.visibility = 'hidden';
        else
        if (ie)
          curTarget.style.filter = "alpha(opacity=30)";
        else
          curTarget.style.opacity = "0.3";

        dragShadow.style.display = 'block';
      }
      lastActiveCont = activeCont;
    } else {

      // our drag item is not in a container, so hide it.
      if(curTarget.style.display!='none'){
        curTarget.style.display  = 'none';
        dragShadow.style.display = 'none';
      }
    }
  }

  // track the current mouse state so we can compare against it next time
  lMouseState = iMouseDown;

  // mouseMove target
  lastTarget  = target;

  if(dragObject){
    dragObject.style.position = 'absolute';
    dragObject.style.top      = (mousePos.y - mouseOffset.y)+"px";
  //dragObject.style.left     = (mousePos.x - mouseOffset.x)+"px";
  }

  // track the current mouse state so we can compare against it next time
  lMouseState = iMouseDown;

  // this prevents items on the page from being highlighted while dragging
  if(curTarget || dragObject) {
    return false;
  }
}

function mouseUp(ev)
{
  //writedebug('MouseUp');
  if(curTarget)
  {
    dragShadow.style.display = 'none';
    dragHelper.style.display = 'none';
    if (curTarget.style.display == 'none')
    {
      var activeContObjFunc = rootParent.getAttribute('dragFunc');
      if (dragBuffer && activeContObjFunc) // && activeCont!=lastActiveCont
      {
        //curTarget.parentNode.removeChild(curTarget);
        var dobj = dragBuffer;
        var tmp = curTarget.getAttribute('DragObj');
        var curParent = rootParent;
        var dragBuffer2 = document.createElement('DIV');
        document.body.appendChild(dragBuffer2);
        eval('dragBuffer2.innerHTML = '+activeContObjFunc);
        curTarget = dragBuffer2.firstChild;
        curTarget.style.display="none";
        curTarget.onmousedown = mouseDown;
        curTarget.setAttribute('DragObj',tmp);
      }
      if (rootSibling)
      {
        rootParent.insertBefore(curTarget, rootSibling);
      }
      else
      {
        rootParent.appendChild(curTarget);
      }
    }

    curTarget.style.display  = '';
    if (ie6)
      curTarget.style.visibility = 'visible';
    else
    if (ie)
      curTarget.style.filter = "";
    else
      curTarget.style.opacity = "";

    //curTarget.style.visibility = 'visible';
    if (CurrentContainer)
    {
      goendeval = CurrentContainer.getAttribute('onDragFinish');
      if (goendeval) eval(goendeval);
    }
  }
  curTarget  = null;
  if (dragObject)
  {
    ev = ev || window.event;
    var mousePos = mouseCoords(ev);
    var dT = dragObject.getAttribute('droptarget');
    if (dT)
    {
      var targObj = document.getElementById(dT);
      var objPos  = getPosition(targObj);
      if ((mousePos.x > objPos.x) && (mousePos.y > objPos.y) && (mousePos.x<(objPos.x+parseInt(targObj.offsetWidth))) && (mousePos.y<(objPos.y+parseInt(targObj.offsetHeight))))
      {
        var nSrc = targObj.getAttribute('newSrc');
        if (nSrc)
        {
          dragObject.src = nSrc;
          setTimeout(function()
          {
            if(!dragObject || !dragObject.parentNode) return;
            dragObject.parentNode.removeChild(dragObject);
            dragObject = null;
          }, parseInt(targObj.getAttribute('timeout')));
        }
        else
        {
          dragObject.parentNode.removeChild(dragObject);
        }
      }
    }
  }
  dragObject = null;
  iMouseDown = false;
  lMouseState = false;
  document.onmousemove = null;
  document.onmouseup  = null;
  return true;
}

function mouseDown(ev){
  ev         = ev || window.event;
  var target = ev.target || ev.srcElement;
  iMouseDown = true;
  document.onmousemove = mouseMove;
  document.onmouseup   = mouseUp;

  if(target.onmousedown || target.getAttribute('DragObj')){
    return false;
  }
//return false;
//return true;

}

function makeDraggable(item){
  if(!item) return;
  item.onmousedown = function(ev){
    dragObject  = this;
    mouseOffset = getMouseOffset(this, ev);
    return false;
  }
}

function makeClickable(item){
  if(!item) return;
  item.onmousedown = function(ev){
    document.getElementById('ClickImage').value = this.name;
  }
}

function addDropTarget(item, target){
  item.setAttribute('droptarget', target);
}

window.onload = function(){

  // Create our helper object that will show the item while dragging
  dragHelper = document.createElement('DIV');
  dragHelper.style.cssText = 'position:absolute;display:none;z-index:999';

  dragBuffer = document.createElement('DIV');
  dragBuffer.style.cssText = 'position:absolute;display:none;';


  dragShadow = document.createElement('DIV');
  dragShadow.style.cssText = 'position:absolute;display:none;border:1px dashed #AAAAAA;padding:0px;z-index:998';

  document.body.appendChild(dragBuffer);
  document.body.appendChild(dragHelper);
  document.body.appendChild(dragShadow);
}

function GetDragContainerElementIds(id)
{
  var theContainer = document.getElementById(id);
  if (!theContainer) return false;
  var TheArr = Array();
  var  i = 0;
  for(var j=0; j<theContainer.childNodes.length; j++)
  {
    // Firefox puts in lots of #text nodes...skip these
    if(theContainer.childNodes[j].nodeName=='#text') continue;
    TheArr[i] = theContainer.childNodes[j].id;
    i++;
  }
  return TheArr;
}

function GetDragContainerElementValues(id)
{
  var theContainer = document.getElementById(id);
  if (!theContainer) return false;
  var TheArr = Array();
  var  i = 0;
  for(var j=0; j<theContainer.childNodes.length; j++)
  {
    // Firefox puts in lots of #text nodes...skip these
    if(theContainer.childNodes[j].nodeName=='#text') continue;
    TheArr[i] = theContainer.childNodes[j].getAttribute('value');
    i++;
  }
  return TheArr;
}
