Object.prototype.attachEvent = function (sEvent, fnHandler, bUseCapture) {
    this.addEventListener(sEvent.indexOf('on') == 0 ? sEvent.replace('on', '') : sEvent, fnHandler, bUseCapture);
}

function pop_up(id, width, height, toolbar){
  if(id == "" || id == null) {
    return;
  }       
  if (width == "" || width == null || height == "" || height == null) {
    width = 800;
    height = 600;
  }
  if(toolbar=="") toolbar="no";
  wx = (screen.width-width)/2;
  wy = (screen.height-height)/2;
  wnd=window.open(id,"_blank", "width="+width+",height="+height+",status=no,resizable=1,scrollbars=1,toolbar="+toolbar+",menubar=no, left="+wx+",top="+wy);
}

function close_self(){
  if(window.opener){
    window.opener.location.reload();    
  }
  window.close();
}
function close_control(location){
  if(window.opener){
    window.opener.location=location;    
  }
  window.close();
}

opened=1;

function down(){
  if(opened){
    document.all['toolbal'].style.left=document.all['toolbal'].clientWidth-50;
    opened=0;
  }else{
    document.all['toolbal'].style.left=0;
    opened=1;
  }
}

function ret_selected(element){
  url="";
  title="";
  form=element.form;
  try{
    elements=form.elements;
    for(i=0;i<elements.length;i++){
      if(elements[i].checked){
        url=elements[i].value;
        title=elements.elements[url].value;
      }
    }
    if(url!=""){
      window.opener.navigator_call_back(url,title);
      window.close();
    }else{
      logging("No page selected!");
      return false;
    }
  }catch(e){
    logging("Error ret_selected:"+e.message);
  }
}

function navigator_call_back(url,title){
  try{
    form=window.document.forms[0];
    form["url"].value=url;
    form["navigator_but"].value=title;
  }catch(e){
    logging("Error navigator_call_back:"+e.message);
  }
}

function switch_system(){
  if(document.all.system.style.display==""||document.all.system.style.display=="none"){
    document.all.system.style.display="block";
  }else{
    document.all.system.style.display="none";
  }
}


clean_a=false;
clean_img=false;
clean_colors=true;
clean_aligns=false;

// хорошие теги
goodTags0=["body","a","p","br","strong","b","em","i","tt","code","pre","ul","ol","li","img","table","tbody","thead","tfoot","caption","tr","td","th","col","colgroup","h1","h2","h3","h4","h5","h6","small","big","sub","sup","div"];

// теги, которые canHaveHTML() и могут быть пустыми.
canEmptyTags0=["td","th"];

goodAttributes0=[];
// хорошие атрибуты (допустимы у всех тегов)
goodAttributes0[""] = ["href", "target", "name", "title", "alt", "src", "id", "bgColor", "color"];

// дополнительные допустимые атрибуты для отдельных тегов
goodAttributes0["img"] = ["width", "height", "border", "align"];
goodAttributes0["table"] = ["cellSpacing", "cellPadding", "border", "width %"]; // width % - на будущее - сделаю, чтоб только процентные меры принимать, остальные посылать...
goodAttributes0["td"] = ["colSpan", "rowSpan"];
goodAttributes0["tr td col colgroup"] = ["noWrap", "align", "vAlign", "width %"];
goodAttributes0["a area"] = ["href", "name"];
goodAttributes0["br"] = ["clear"];

// однозначно убиваемые псевдо-атрибуты (отсутствуют в коллекции attributes)
mustDieAttributes=["x:str","x:num","x:fmla","o:p"]; // внимание - в 6-ом MSIE убийство несуществующих атрибутов у тега TABLE ведет к краху браузера

// хорошие классы (не убиваем)
goodClasses0=["important","noindent","note","h1","h2","h3","h4","h5","h6"];

goodTags=[];
for(i in goodTags0){
  goodTags[goodTags0[i]]=true
}
canEmptyTags=[];
for(i in canEmptyTags0){
  canEmptyTags[canEmptyTags0[i]]=true
}

goodAttributes=[];
for(i in goodAttributes0){
  var splitted=i.split(" ");
  for(ii in splitted){
    if(!goodAttributes[splitted[ii]]) goodAttributes[splitted[ii]]=[];
    for(j in goodAttributes0[i]){
      goodAttributes[splitted[ii]][goodAttributes0[i][j]]=true;
    }               
  }
}

goodClasses=[];
for(i in goodClasses0){
  goodClasses[goodClasses0[i]]=true;
}
function cleanObject(o){
  try{
    if(o.innerHTML=='')return false;
    var s="";
    var myAttributes=[];
    var i;
    if(o.outerHTML.substr(0,2)=="<?"){
      o.removeNode(false);
      //o.parentNode.replaceChild(o.firstChild, o)
      return
    }
    var tag=o.tagName.toLowerCase();
    // удаляем плохие, заказные и пустые теги
    if(!goodTags[tag] || (self.clean_a && tag=="a") || (self.clean_img && tag=="img") || (o.canHaveHTML && o.innerHTML=="" && !canEmptyTags[tag])){
      try{
        o.removeNode(false)
        //o.parentNode.replaceChild(o.firstChild, o)
      }catch(e){
        logging("Error cleanObject#1: "+e.message);
      }
      return;
    }
    var a=o.attributes;
    if(!a) return;
    for(i in a){ // хм...
       if(""+a[i]!="null"){ // странно, но просто if(a[i]) не прокатывает
         myAttributes[i]=a[i]
       }
    }
    // киляем плохие атрибуты и плохие классы
    for(i in myAttributes){
       //i=i.toLowerCase()
       if((!goodAttributes[""][i] &&(!goodAttributes[tag] || !goodAttributes[tag][i] || i=="class" || i=="className"))||
          (self.clean_colors && (i=="bgColor" || i=="color"))||
          (self.clean_aligns && (i=="align" || i=="vAlign"))){               
            if(i=="class"){
              i="className";
            }
            if(i!="className" || !goodClasses[o.className]){
              o.removeAttribute(i);
            }
       }       
    }
    // в 6-ом MSIE не киляем непонятных атрибутов у таблиц. см. выше.
    if(o.tagName.toLowerCase()!="table"){
            for(i in mustDieAttributes){
                    o.removeAttribute(mustDieAttributes[i])
            }
    }
    o.style.cssText=""
  }catch(e){
    logging("Error cleanObject#1: "+e.message);
  }
}


function cleanTree(o,mustClean){
  try{
    var c=o.children
    var i
    if(c){
            for(i=c.length-1;i>=0;i--){
                    cleanTree(c[i],true)
            }
    }    
    if(mustClean) cleanObject(o)
  }catch(e){
    logging("Error cleanTree: "+e.message);    
  }
}
//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;


function initRTE(imgPath, incPath, css) {
        //set browser vars
        var ua = navigator.userAgent.toLowerCase();
        isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
        isGecko = (ua.indexOf("gecko") != -1);
        isSafari = (ua.indexOf("safari") != -1);
        isKonqueror = (ua.indexOf("konqueror") != -1);
        //check to see if designMode mode is available
        if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
                isRichText = true;
        }
        if (!isIE) document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT | Event.MOUSEDOWN | Event.MOUSEUP);
        //document.onmouseover = raiseButton;
        //document.onmouseout  = normalButton;
        //document.onmousedown = lowerButton;
        //document.onmouseup   = raiseButton;
        //set paths vars
        imagesPath = imgPath;
        includesPath = incPath;
        cssFile = css;
        if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');
        //for testing standard textarea, uncomment the following line
        //isRichText = false;
}

function writeRichText(rte, html, width, height, buttons, readOnly) {
        if (isRichText) {
                if (allRTEs.length > 0) allRTEs += ";";
                allRTEs += rte;
                writeRTE(rte, html, width, height, buttons, readOnly);
        } else {
                writeDefault(rte, html, width, height, buttons, readOnly);
        }
}

function writeDefault(rte, html, width, height, buttons, readOnly) {
        if (!readOnly) {
                document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
        } else {
                document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
        }
}

function raiseButton(e) {
        if (isIE) {
                var el = window.event.srcElement;
        } else {
                var el= e.target;
        }
        
        className = el.className;
        if (className == 'rteImage' || className == 'rteImageLowered') {
                el.className = 'rteImageRaised';
        }
}

function normalButton(e) {
        if (isIE) {
                var el = window.event.srcElement;
        } else {
                var el= e.target;
        }
        
        className = el.className;
        if (className == 'rteImageRaised' || className == 'rteImageLowered') {
                el.className = 'rteImage';
        }
}

function lowerButton(e) {
        if (isIE) {
                var el = window.event.srcElement;
        } else {
                var el= e.target;
        }
        
        className = el.className;
        if (className == 'rteImage' || className == 'rteImageRaised') {
                el.className = 'rteImageLowered';
        }
}

function writeRTE(rte, html, width, height, buttons, readOnly) {
        if (readOnly) buttons = false;
        
        //adjust minimum table widths
        if (isIE) {
                if (buttons && (width <600)) width = 600;
                var tablewidth = width;
        } else {
                if (buttons && (width <500)) width = 500;
                var tablewidth = width + 4;
        }
        
        if (buttons == true) {
                document.writeln('<div class="rteBack" id="Buttons1_' + rte + '>'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'bold.gif" alt="Bold" onClick="FormatText(\'' + rte + '\', \'bold\', \'\')" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'italic.gif" alt="Italic" onClick="FormatText(\'' + rte + '\', \'italic\', \'\')" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'underline.gif" alt="Underline" onClick="FormatText(\'' + rte + '\', \'underline\', \'\')" />'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" >'+
                                   '<img class="rteImage"   src="' + imagesPath + 'left_just.gif" alt="Align Left" onClick="FormatText(\'' + rte + '\', \'justifyleft\', \'\')" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'centre.gif" alt="Center" onClick="FormatText(\'' + rte + '\', \'justifycenter\', \'\')" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'right_just.gif" alt="Align Right" onClick="FormatText(\'' + rte + '\', \'justifyright\', \'\')" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'justifyfull.gif" alt="Justify Full" onclick="FormatText(\'' + rte + '\', \'justifyfull\', \'\')" />'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'clear.gif" alt="Clean up code" onClick="FormatText(\'' + rte + '\', \'cleanup\', \'\')" />'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'numbered_list.gif" alt="Ordered List" onClick="FormatText(\'' + rte + '\', \'insertorderedlist\', \'\')" />'+
                                   '<img class="rteImage"   src="' + imagesPath + 'list.gif" alt="Unordered List" onClick="FormatText(\'' + rte + '\', \'insertunorderedlist\', \'\')" />'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" />'+
                                   
                                   '<img class="rteImage" src="' + imagesPath + 'outdent.gif" alt="Outdent" onClick="FormatText(\'' + rte + '\', \'outdent\', \'\')" />'+
                                   '<img class="rteImage" src="' + imagesPath + 'indent.gif" alt="Indent" onClick="FormatText(\'' + rte + '\', \'indent\', \'\')" />'+
                                   
                                   '<div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" alt="Text Color" onClick="FormatText(\'' + rte + '\', \'forecolor\', \'\')"></div>'+
                                   '<div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" alt="Background Color" onClick="FormatText(\'' + rte + '\', \'hilitecolor\', \'\')"></div>'+
                                   
                                   '<img class="rteImage" src="' + imagesPath + 'format_sub.gif" alt="Undo" onClick="FormatText(\'' + rte + '\', \'subscript\')">'+
                                   '<img class="rteImage" src="' + imagesPath + 'format_sup.gif" alt="Redo" onClick="FormatText(\'' + rte + '\', \'superscript\')">'+
                                   
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" >'+
                                   '<img class="rteImage" src="/grape/buttons/hyperlink.gif" alt="Insert Link" onClick="FormatText(\'' + rte + '\', \'createlink\')">'+
                                   '<img class="rteImage" src="/grape/buttons/images.gif" alt="Add Image" onClick="AddImage(\'' + rte + '\')">'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif">'+
                                   '<img class="rteImage" src="/grape/buttons/cut.gif" alt="Cut" onClick="FormatText(\'' + rte + '\', \'cut\')">'+
                                   '<img class="rteImage" src="/grape/buttons/copy.gif" alt="Copy" onClick="FormatText(\'' + rte + '\', \'copy\')">'+
                                   '<img class="rteImage" src="/grape/buttons/paste.gif" alt="Paste" onClick="FormatText(\'' + rte + '\', \'paste\')">'+
                                   '<img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" >'+
                                   '<img class="rteImage" src="/grape/buttons/undo.gif" alt="Undo" onClick="FormatText(\'' + rte + '\', \'undo\')">'+
                                   '<img class="rteImage" src="/grape/buttons/redo.gif" alt="Redo" onClick="FormatText(\'' + rte + '\', \'redo\')">'+
                                   '<select class="formatSelect" id="formatblock_' + rte + '" onchange="Select(\'' + rte + '\', this.id);" >'+
                                   '  <option value=""       >Style</option>'+
                                   '  <option value="p"      >Paragraph</option>'+
                                   '  <option value="h1"     >Heading 1</option>'+
                                   '  <option value="h2"     >Heading 2</option>'+
                                   '  <option value="h3"     >Heading 3</option>'+
                                   '  <option value="h4"     >Heading 4</option>'+
                                   '  <option value="h5"     >Heading 5</option>'+
                                   '  <option value="h6"     >Heading 6</option>'+
                                   '  <option value="address">Address  </option>'+
                                   '  <option value="pre">Formatted</option>'+
                                   '</select>'+
                               '</div>');
        }
        document.writeln('<iframe id="' + rte + '" name="' + rte + '" width="' + width + 'px" height="' + height + 'px"></iframe>');
        if (!readOnly) document.writeln('<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;View Source');
        document.writeln('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>');
        document.writeln('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">');
        document.getElementById('hdn' + rte).value = html;
        enableDesignMode(rte, html, readOnly);
}

function enableDesignMode(rte, html, readOnly) {
        var frameHtml = "<html id=\"" + rte + "\">\n";
        frameHtml += "<head>\n";
        //to reference your stylesheet, set href property below to your stylesheet path and uncomment
        if(cssFile.length > 0) {
          frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
        }
        frameHtml += "<style>\n";
        frameHtml += "body{\n";
        frameHtml += "  background: #FFFFFF;\n";
        frameHtml += "  margin: 0px;\n";
        frameHtml += "  padding: 0px;\n";
        frameHtml += "}\n";
        frameHtml += "p{\n";
        frameHtml += "  margin: 0px;\n";
        frameHtml += "  padding: 0px;\n";
        frameHtml += "  padding-bottom: 3px;\n";
        frameHtml += "}\n";
        frameHtml += "</style>\n";
        frameHtml += "</head>\n";
        frameHtml += "<body>\n";
        frameHtml += html + "\n";
        frameHtml += "</body>\n";
        frameHtml += "</html>";
        
        if (document.all) {
                var oRTE = frames[rte].document;
                oRTE.open();
                oRTE.write(frameHtml);
                oRTE.close();
                if (!readOnly) oRTE.designMode = "On";
        } else {
                try {
                        if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
                        try {
                                var oRTE = document.getElementById(rte).contentWindow.document;
                                oRTE.open();
                                oRTE.write(frameHtml);
                                oRTE.close();
                                if (isGecko && !readOnly) {
                                        //attach a keyboard handler for gecko browsers to make keyboard shortcuts work
                                        oRTE.addEventListener("keypress", kb_handler, true);
                                }
                        } catch (e) {
                           logging("Error enableDesignMode: Error preloading content:"+e.message);    
                        }
                } catch (e) {
                        //gecko may take some time to enable design mode.
                        //Keep looping until able to set.
                        if (isGecko) {
                                setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
                        } else {
                                return false;
                        }
                }
        }
}

function updateRTEs() {
        var vRTEs = allRTEs.split(";");
        for (var i = 0; i <vRTEs.length; i++) {
                updateRTE(vRTEs[i]);
        }
}

function updateRTE(rte) {
        if (!isRichText) return;
        
        //set message value
        var oHdnMessage = document.getElementById('hdn' + rte);
        var oRTE = document.getElementById(rte);
        var readOnly = false;
        
        //check for readOnly mode
        if (document.all) {
                if (frames[rte].document.designMode != "On") readOnly = true;
        } else {
                if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
        }
        
        if (isRichText && !readOnly) {
                //if viewing source, switch back to design view
                if (document.getElementById("chkSrc" + rte).checked) {
                        document.getElementById("chkSrc" + rte).checked = false;
                        toggleHTMLSrc(rte);
                }
                
                if (oHdnMessage.value == null) oHdnMessage.value = "";
                if (document.all) {
                        oHdnMessage.value = frames[rte].document.body.innerHTML;
                } else {
                        oHdnMessage.value = oRTE.contentWindow.document.body.innerHTML;
                }
                
                //if there is no content (other than formatting) set value to nothing
                if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == "" 
                        && oHdnMessage.value.toLowerCase().search("<hr") == -1
                        && oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = "";
                //fix for gecko
                if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = "";
        }
}

function toggleHTMLSrc(rte) {
        //contributed by Bob Hutzel (thanks Bob!)
        var oRTE;
        if (document.all) {
                oRTE = frames[rte].document;
        } else {
                oRTE = document.getElementById(rte).contentWindow.document;
        }
        
        if (document.getElementById("chkSrc" + rte).checked) {
                //document.getElementById("Buttons1_" + rte).style.visibility = "hidden";
                if (document.all) {
                        oRTE.body.innerText = oRTE.body.innerHTML;
                } else {
                        var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
                        oRTE.body.innerHTML = "";
                        oRTE.body.appendChild(htmlSrc);
                }
        } else {
                ///document.getElementById("Buttons1_" + rte).style.visibility = "visible";
                if (document.all) {
                        //fix for IE
                        var output = escape(oRTE.body.innerText);
                        output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
                        output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
                        
                        oRTE.body.innerHTML = unescape(output);
                } else {
                        var htmlSrc = oRTE.body.ownerDocument.createRange();
                        cleanTree(htmlSrc,true);
                        htmlSrc.selectNodeContents(oRTE.body);
                        oRTE.body.innerHTML = htmlSrc.toString();
                }
        }
}

//Function to format text in the text box
function FormatText(rte, command, option) {
        var oRTE;
        if (document.all) {
                oRTE = frames[rte];
                
                //get current selected range
                var selection = oRTE.document.selection; 
                if (selection != null) {
                        rng = selection.createRange();
                }
        } else {
                oRTE = document.getElementById(rte).contentWindow;
                
                //get currently selected range
                var selection = oRTE.getSelection();
                rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
        }
        
        try {
                if (command == "cleanup"){
                  cleanTree(oRTE.document.body,true);
                  return true;
                }
                if ((command == "forecolor") || (command == "hilitecolor")) {
                        //save current values
                        parent.command = command;
                        currentRTE = rte;
                        
                        //position and show color palette
                        buttonElement = document.getElementById(command + '_' + rte);
                        // Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
                        document.getElementById('cp' + rte).style.left = getOffsetLeft(buttonElement, 4) + "px";
                        document.getElementById('cp' + rte).style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight + 4) + "px";
                        if (document.getElementById('cp' + rte).style.visibility == "hidden") {
                                document.getElementById('cp' + rte).style.visibility = "visible";
                                document.getElementById('cp' + rte).style.display = "inline";
                        } else {
                                document.getElementById('cp' + rte).style.visibility = "hidden";
                                document.getElementById('cp' + rte).style.display = "none";
                        }
                } else if (command == "createlink") {
                        var szURL = prompt("Enter a URL:", "");
                        try {
                                //ignore error for blank urls
                                oRTE.document.execCommand("Unlink", false, null);
                                oRTE.document.execCommand("CreateLink", false, szURL);
                        } catch (e) {
                                //do nothing
                        }
                } else {
                        oRTE.focus();
                        oRTE.document.execCommand(command, false, option);
                        oRTE.focus();
                }
        } catch (e) {
           logging("Error enableDesignMode:"+e.message);    
        }
}

//Function to set color
function setColor(color) {
        var rte = currentRTE;
        var oRTE;
        if (document.all) {
                oRTE = frames[rte];
        } else {
                oRTE = document.getElementById(rte).contentWindow;
        }
        
        var parentCommand = parent.command;
        if (document.all) {
                //retrieve selected range
                var sel = oRTE.document.selection; 
                if (parentCommand == "hilitecolor") parentCommand = "backcolor";
                if (sel != null) {
                        var newRng = sel.createRange();
                        newRng = rng;
                        newRng.select();
                }
        }
        oRTE.focus();
        oRTE.document.execCommand(parentCommand, false, color);
        oRTE.focus();
        document.getElementById('cp' + rte).style.visibility = "hidden";
        document.getElementById('cp' + rte).style.display = "none";
}

//function to perform spell check
function checkspell() {
        try {
                var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
                tmpis.CheckAllLinkedDocuments(document);
        }
        catch(exception) {
                if(exception.number==-2146827859) {
                        if (confirm("ieSpell not detected.  Click Ok to go to download page."))
                                window.open("http://www.iespell.com/download.php","DownLoad");
                } else {
                    logging("Error checkspell:"+e.message);    
                }
        }
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
function getOffsetTop(elm, parents_up) {
        var mOffsetTop = elm.offsetTop;
        var mOffsetParent = elm.offsetParent;
        
        if(!parents_up) {
                parents_up = 10000; // arbitrary big number
        }
        while(parents_up>0 && mOffsetParent) {
                mOffsetTop += mOffsetParent.offsetTop;
                mOffsetParent = mOffsetParent.offsetParent;
                parents_up--;
        }
        
        return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
function getOffsetLeft(elm, parents_up) {
        var mOffsetLeft = elm.offsetLeft;
        var mOffsetParent = elm.offsetParent;
        
        if(!parents_up) {
                parents_up = 10000; // arbitrary big number
        }
        while(parents_up>0 && mOffsetParent) {
                mOffsetLeft += mOffsetParent.offsetLeft;
                mOffsetParent = mOffsetParent.offsetParent;
                parents_up--;
        }
        
        return mOffsetLeft;
}

function Select(rte, selectname) {
        var oRTE;
        if (document.all) {
                oRTE = frames[rte];
                
                //get current selected range
                var selection = oRTE.document.selection; 
                if (selection != null) {
                        rng = selection.createRange();
                }
        } else {
                oRTE = document.getElementById(rte).contentWindow;
                
                //get currently selected range
                var selection = oRTE.getSelection();
                rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
        }
        
        var idx = document.getElementById(selectname).selectedIndex;
        // First one is always a label
        if (idx != 0) {
                var selected = document.getElementById(selectname).options[idx].value;
                var cmd = selectname.replace('_' + rte, '');
                oRTE.focus();
                oRTE.document.execCommand(cmd, false, '<'+selected+'>');
                oRTE.focus();
                document.getElementById(selectname).selectedIndex = 0;
        }
}

function kb_handler(evt) {
        var rte = evt.target.id;
        
        //contributed by Anti Veeranna (thanks Anti!)
        if (evt.ctrlKey) {
                var key = String.fromCharCode(evt.charCode).toLowerCase();
                var cmd = '';
                switch (key) {
                        case 'b': cmd = "bold"; break;
                        case 'i': cmd = "italic"; break;
                        case 'u': cmd = "underline"; break;
                };

                if (cmd) {
                        FormatText(rte, cmd, true);
                        //evt.target.ownerDocument.execCommand(cmd, false, true);
                        // stop the event bubble
                        evt.preventDefault();
                        evt.stopPropagation();
                }
        }
}

function docChanged (evt) {}

function stripHTML(oldString) {
        var newString = oldString.replace(/(<([^>]+)>)/ig,"");
        
        //replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
        
        //trim string
        newString = trim(newString);
        
        return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
        
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
        
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
        
        // Note that there are two spaces in the string - look for multiple spaces within the string
   while (retValue.indexOf("  ") != -1) {
                // Again, there are two spaces in each of the strings
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}

/*  TOOLBAR MENU FUNCTIONS */

var tohide=new Array();
var tofade=new Array();
var selected_menu="";


function menu_initialization(){
  register_menu_handlers();
  if(typeof(HTMLElement) != 'undefined') HTMLElement.prototype.contains = function(el) {
    var p = el.parentNode;
    while(p && p != this && p != document.documentElement) p = p.parentNode;
    return p === this;
  }
}

function register_menu_handlers(){
  try{
    var all;
    if(document.all){
      all=document.all;
    }else{
      all=document.getElementsByTagName("*");
    }
    
    for(var i=0;i<all.length;i++){
      if(all[i].id){
        if(all[i].id.indexOf("itm_")==0){
          all[i].onmouseover=menu_mousein;
        }
        if(all[i].id.indexOf("sub_")==0){
          all[i].onmouseout  =menu_mouseout;
          all[i].onclick     =menu_mouseout;
        }
      }
    }
  }catch(e){
    logging("Error register_menu_handlers:"+e.message);
  }
}

function menu_mousein(eevent){
  try{
    if(eevent)event=eevent;
    var id=event.toElement.id.substring(4);
    if(id){
      var itmmenu_id="itm_"+id;
      var submenu_id="sub_"+id;
      if(selected_menu!=""&&selected_menu!=id){
        tohide.push("sub_"+selected_menu);
        toolbar_hide_sub_force();
      }
      var submenu=document.getElementById(submenu_id);
      var itmmenu=document.getElementById(itmmenu_id);
      if(submenu){submenu.style.display="block";}  
      selected_menu=id;
    }
  }catch(e){
    logging("Error menu_mousein:"+e.message);
  }
}

function menu_mouseout(eevent){
  try{
    if(eevent)event=eevent;
    if(event.fromElement){
      var id=event.fromElement.id.substring(4);
      if(document.getElementById("sub_"+id)){
        itm=document.getElementById("itm_"+id);
        if(itm&&!itm.contains(event.toElement)){
          tohide.push("sub_"+id);
          setTimeout(toolbar_hide_sub_force, 100);
        }
      }
    }else{
      el=event.srcElement;
      while(el) {
        if(el.id.indexOf("sub_")==0)
          break;
        el = el.parentNode;
      }
      if(el){
        tohide.push(el.id);
        setTimeout(toolbar_hide_sub_force, 100);
      }
    }
  }catch(e){
    logging("Error menu_mouseout:"+e.message);
  }
}

function toolbar_hide_sub_force(){
  try{
    if(tohide.length>0){
      var id=tohide.pop();
      //tlog("toolbar_hide_sub_force:"+id);
      var submenu=document.getElementById (id);
      if(submenu){
        submenu.style.display="none";
      }
    }
  }catch(e){
    logging("Error toolbar_hide_sub_force:"+e.message);
  }
}
/*  TOOLBAR MENU FUNCTIONS */

/*
(C) www.dhtmlgoodies.com, September 2005

Version 1.2, November 8th - 2005 - Added <iframe> background in IE
Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.       

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

*/
var languageCode = 'en';        // Possible values:     en,ge,no        
                                                        // en = english, ge = german, no = norwegian
                                                        
var calendar_offsetTop = 0;             // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendar_offsetLeft = 0;    // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendarDiv = false;

var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;


switch(languageCode){
        case "en":      /* English */
                var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
                var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
                var weekString = 'Week';
                var todayString = 'Today is';
                break;
        case "ge":      /* German */
                var monthArray = ['Jдnner','Februar','Mдrz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
                var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
                var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];     
                var weekString = 'Woche';
                var todayString = 'Heute';
                
                break;
        case "no":      /* Norwegian */
                var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
                var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
                var dayArray = ['Man','Tir','Ons','Tor','Fre','L&oslash;r','S&oslash;n'];       
                var weekString = 'Uke';
                var todayString = 'Dagen i dag er';
                break;  
        case "nl":      /* Dutch */
                var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
                var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
                var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
                var weekString = 'Week';
                var todayString = 'Vandaag';
                break;          
}



var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
var currentMonth;
var currentYear;
var calendarContentDiv;
var returnDateTo;
var returnFormat;
var activeSelectBoxMonth;
var activeSelectBoxYear;
var iframeObj = false;

var returnDateToYear;
var returnDateToMonth;
var returnDateToDay;

var inputYear;
var inputMonth;
var inputDay;

var hours="00";
var minutes="00";
var seconds="00";


var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)
function cancelCalendarEvent()
{
        return false;
}
function isLeapYear(inputYear)
{
        if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
        return false;   
        
}
var activeSelectBoxMonth = false;

function highlightMonthYear()
{
        if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
        
        if(this.className=='monthYearActive'){
                this.className='';      
        }else{
                this.className = 'monthYearActive';
                activeSelectBoxMonth = this;
        }
}

function showMonthDropDown()
{
        if(document.getElementById('monthDropDown').style.display=='block'){
                document.getElementById('monthDropDown').style.display='none';  
        }else{
                document.getElementById('monthDropDown').style.display='block';         
                document.getElementById('yearDropDown').style.display='none';
        }
}

function showYearDropDown()
{
        if(document.getElementById('yearDropDown').style.display=='block'){
                document.getElementById('yearDropDown').style.display='none';   
        }else{
                document.getElementById('yearDropDown').style.display='block';  
                document.getElementById('monthDropDown').style.display='none';  
        }               

}

function selectMonth()
{
        document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
        currentMonth = this.id.replace(/[^\d]/g,'');

        document.getElementById('monthDropDown').style.display='none';
        for(var no=0;no<monthArray.length;no++){
                document.getElementById('monthDiv_'+no).style.color=''; 
        }
        this.style.color = selectBoxHighlightColor;
        activeSelectBoxMonth = this;
        writeCalendarContent();
        
}

function selectYear()
{
        document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
        currentYear = this.innerHTML.replace(/[^\d]/g,'');
        document.getElementById('yearDropDown').style.display='none';
        if(activeSelectBoxYear){
                activeSelectBoxYear.style.color='';
        }
        activeSelectBoxYear=this;
        this.style.color = selectBoxHighlightColor;
        writeCalendarContent();
        
}

function switchMonth()
{
        if(this.src.indexOf('left')>=0){
                currentMonth=currentMonth-1;;
                if(currentMonth<0){
                        currentMonth=11;
                        currentYear=currentYear-1;
                }
        }else{
                currentMonth=currentMonth+1;;
                if(currentMonth>11){
                        currentMonth=0;
                        currentYear=currentYear/1+1;
                }       
        }       
        
        writeCalendarContent(); 
        
        
}

function createMonthDiv(){
        var div = document.createElement('DIV');
        div.className='monthYearPicker';
        div.id = 'monthPicker';
        
        for(var no=0;no<monthArray.length;no++){
                var subDiv = document.createElement('DIV');
                subDiv.innerHTML = monthArray[no];
                subDiv.onmouseover = highlightMonthYear;
                subDiv.onmouseout = highlightMonthYear;
                subDiv.onclick = selectMonth;
                subDiv.id = 'monthDiv_' + no;
                subDiv.style.width = '56px';
                subDiv.onselectstart = cancelCalendarEvent;             
                div.appendChild(subDiv);
                if(currentMonth && currentMonth==no){
                        subDiv.style.color = selectBoxHighlightColor;
                        activeSelectBoxMonth = subDiv;
                }                               
                
        }       
        return div;
        
}

function changeSelectBoxYear()
{

        var yearItems = this.parentNode.getElementsByTagName('DIV');
        if(this.innerHTML.indexOf('-')>=0){
                var startYear = yearItems[1].innerHTML/1 -1;
                if(activeSelectBoxYear){
                        activeSelectBoxYear.style.color='';
                }
        }else{
                var startYear = yearItems[1].innerHTML/1 +1;
                if(activeSelectBoxYear){
                        activeSelectBoxYear.style.color='';

                }                       
        }

        for(var no=1;no<yearItems.length-1;no++){
                yearItems[no].innerHTML = startYear+no-1;       
                yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);    
                
        }               
        if(activeSelectBoxYear){
                activeSelectBoxYear.style.color='';
                if(document.getElementById('yearDiv'+currentYear)){
                        activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
                        activeSelectBoxYear.style.color=selectBoxHighlightColor;;
                }
        }
}

function updateYearDiv()
{
        var div = document.getElementById('yearDropDown');
        var yearItems = div.getElementsByTagName('DIV');
        for(var no=1;no<yearItems.length-1;no++){
                yearItems[no].innerHTML = currentYear/1 -6 + no;        
                if(currentYear==(currentYear/1 -6 + no)){
                        yearItems[no].style.color = selectBoxHighlightColor;
                        activeSelectBoxYear = yearItems[no];                            
                }else{
                        yearItems[no].style.color = '';
                }
        }               
}

function updateMonthDiv()
{
        for(no=0;no<12;no++){
                document.getElementById('monthDiv_' + no).style.color = '';
        }               
        document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
        activeSelectBoxMonth =  document.getElementById('monthDiv_' + currentMonth);
}

function createYearDiv()
{

        if(!document.getElementById('yearDropDown')){
                var div = document.createElement('DIV');
                div.className='monthYearPicker';
        }else{
                var div = document.getElementById('yearDropDown');
                var subDivs = div.getElementsByTagName('DIV');
                for(var no=0;no<subDivs.length;no++){
                        subDivs[no].parentNode.removeChild(subDivs[no]);        
                }       
        }       
        
        
        var d = new Date();
        if(currentYear){
                d.setFullYear(currentYear);     
        }

        var startYear = d.getFullYear()/1 - 5;

        
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = '&nbsp;&nbsp;- ';
        subDiv.onclick = changeSelectBoxYear;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = highlightMonthYear; 
        subDiv.onselectstart = cancelCalendarEvent;                     
        div.appendChild(subDiv);
        
        for(var no=startYear;no<(startYear+10);no++){
                var subDiv = document.createElement('DIV');
                subDiv.innerHTML = no;
                subDiv.onmouseover = highlightMonthYear;
                subDiv.onmouseout = highlightMonthYear;         
                subDiv.onclick = selectYear;            
                subDiv.id = 'yearDiv' + no;     
                subDiv.onselectstart = cancelCalendarEvent;     
                div.appendChild(subDiv);
                if(currentYear && currentYear==no){
                        subDiv.style.color = selectBoxHighlightColor;
                        activeSelectBoxYear = subDiv;
                }                       
        }
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = '&nbsp;&nbsp;+ ';
        subDiv.onclick = changeSelectBoxYear;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = highlightMonthYear;         
        subDiv.onselectstart = cancelCalendarEvent;                     
        div.appendChild(subDiv);                

        
        return div;
}

function highlightSelect()
{
        if(this.className=='selectBox'){
                this.className = 'selectBoxOver';       
                this.getElementsByTagName('IMG')[0].src = '/grape/calendar/down_over.gif';
        }else{
                this.className = 'selectBox';   
                this.getElementsByTagName('IMG')[0].src = '/grape/calendar/down.gif';                    
        }
        
}

function highlightArrow()
{
        if(this.src.indexOf('over')>=0){
                if(this.src.indexOf('left')>=0)this.src = '/grape/calendar/left.gif';    
                if(this.src.indexOf('right')>=0)this.src = '/grape/calendar/right.gif';                          
        }else{
                if(this.src.indexOf('left')>=0)this.src = '/grape/calendar/left_over.gif';       
                if(this.src.indexOf('right')>=0)this.src = '/grape/calendar/right_over.gif';     
        }
}

function highlightClose()
{
        if(this.src.indexOf('over')>=0){
                this.src = '/grape/calendar/close.gif';
        }else{
                this.src = '/grape/calendar/close_over.gif';     
        }       

}

function closeCalendar(){

        document.getElementById('yearDropDown').style.display='none';
        document.getElementById('monthDropDown').style.display='none';
                
        calendarDiv.style.display='none';
        if(iframeObj)iframeObj.style.display='none';
        if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
        if(activeSelectBoxYear)activeSelectBoxYear.className='';
        

}

function writeTopBar()
{

        var topBar = document.createElement('DIV');
        topBar.className = 'topBar';
        topBar.id = 'topBar';
        calendarDiv.appendChild(topBar);
        
        // Left arrow
        var leftDiv = document.createElement('DIV');
        leftDiv.style.marginRight = '1px';
        var img = document.createElement('IMG');
        img.src = '/grape/calendar/left.gif';
        img.onmouseover = highlightArrow;
        img.onclick = switchMonth;
        img.onmouseout = highlightArrow;
        leftDiv.appendChild(img);       
        topBar.appendChild(leftDiv);
        if(Opera)leftDiv.style.width = '16px';
        
        // Right arrow
        var rightDiv = document.createElement('DIV');
        rightDiv.style.marginRight = '1px';
        var img = document.createElement('IMG');
        img.src = '/grape/calendar/right.gif';
        img.onclick = switchMonth;
        img.onmouseover = highlightArrow;
        img.onmouseout = highlightArrow;
        rightDiv.appendChild(img);
        if(Opera)rightDiv.style.width = '16px';
        topBar.appendChild(rightDiv);           

                        
        // Month selector
        var monthDiv = document.createElement('DIV');
        monthDiv.id = 'monthSelect';
        monthDiv.onmouseover = highlightSelect;
        monthDiv.onmouseout = highlightSelect;
        monthDiv.onclick = showMonthDropDown;
        var span = document.createElement('SPAN');              
        span.innerHTML = monthArray[currentMonth];
        span.id = 'calendar_month_txt';
        monthDiv.appendChild(span);

        var img = document.createElement('IMG');
        img.src = '/grape/calendar/down.gif';
        img.style.position = 'absolute';
        img.style.right = '0px';
        monthDiv.appendChild(img);
        monthDiv.className = 'selectBox';
        if(Opera){
                img.style.cssText = 'float:right;position:relative';
                img.style.position = 'relative';
                img.style.styleFloat = 'right';
        }
        topBar.appendChild(monthDiv);

        var monthPicker = createMonthDiv();
        monthPicker.style.left = '37px';
        monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
        monthPicker.style.width ='60px';
        monthPicker.id = 'monthDropDown';
        
        calendarDiv.appendChild(monthPicker);
                        
        // Year selector
        var yearDiv = document.createElement('DIV');
        yearDiv.onmouseover = highlightSelect;
        yearDiv.onmouseout = highlightSelect;
        yearDiv.onclick = showYearDropDown;
        var span = document.createElement('SPAN');              
        span.innerHTML = currentYear;
        span.id = 'calendar_year_txt';
        yearDiv.appendChild(span);
        topBar.appendChild(yearDiv);
        
        var img = document.createElement('IMG');
        img.src = '/grape/calendar/down.gif';
        yearDiv.appendChild(img);
        yearDiv.className = 'selectBox';
        
        if(Opera){
                yearDiv.style.width = '50px';
                img.style.cssText = 'float:right';
                img.style.position = 'relative';
                img.style.styleFloat = 'right';
        }       
        
        var yearPicker = createYearDiv();
        yearPicker.style.left = '113px';
        yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
        yearPicker.style.width = '35px';
        yearPicker.id = 'yearDropDown';
        calendarDiv.appendChild(yearPicker);
        
                
        var img = document.createElement('IMG');
        img.src = '/grape/calendar/close.gif';
        img.style.styleFloat = 'right';
        img.onmouseover = highlightClose;
        img.onmouseout = highlightClose;
        img.onclick = closeCalendar;
        topBar.appendChild(img);
        if(!document.all){
                img.style.position = 'absolute';
                img.style.right = '2px';
        }
        
        

}

function writeCalendarContent()
{
        var calendarContentDivExists = true;
        if(!calendarContentDiv){
                calendarContentDiv = document.createElement('DIV');
                calendarDiv.appendChild(calendarContentDiv);
                calendarContentDivExists = false;
        }
        
        var d = new Date();             
        d.setMonth(currentMonth);
        d.setFullYear(currentYear);             
        d.setDate(0);           


        document.getElementById('calendar_year_txt').innerHTML = currentYear;
        document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
        
        var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
        if(existingTable.length>0){
                calendarContentDiv.removeChild(existingTable[0]);
        }
        
        var calTable = document.createElement('TABLE');
        calTable.cellSpacing = '0';
        calendarContentDiv.appendChild(calTable);
        var calTBody = document.createElement('TBODY');
        calTable.appendChild(calTBody);
        var row = calTBody.insertRow(-1);
        var cell = row.insertCell(-1);
        cell.innerHTML = weekString;
        cell.style.backgroundColor = selectBoxRolloverBgColor;
        
        for(var no=0;no<dayArray.length;no++){
                var cell = row.insertCell(-1);
                cell.innerHTML = dayArray[no]; 
        }
        
        var row = calTBody.insertRow(-1);
        var cell = row.insertCell(-1);
        cell.style.backgroundColor = selectBoxRolloverBgColor;
        var week = getWeek(currentYear,currentMonth,1);
        cell.innerHTML = week;          // Week
        for(var no=0;no<d.getDay();no++){
                var cell = row.insertCell(-1);
                cell.innerHTML = '&nbsp;';
        }

        var colCounter = d.getDay();
        var daysInMonth = daysInMonthArray[currentMonth];
        if(daysInMonth==28){
                if(isLeapYear(currentYear))daysInMonth=29;
        }
        
        for(var no=1;no<=daysInMonth;no++){
                d.setDate(no-1);
                if(colCounter>0 && colCounter%7==0){
                        var row = calTBody.insertRow(-1);
                        var cell = row.insertCell(-1);
                        var week = getWeek(currentYear,currentMonth,no);
                        cell.innerHTML = week;          // Week 
                        cell.style.backgroundColor = selectBoxRolloverBgColor;                  
                }
                var cell = row.insertCell(-1);
                if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
                        cell.style.color = '#FF0000';   
                }
                cell.innerHTML = no;
                cell.onclick = pickDate;
                colCounter++;
        }
        
        
        if(!document.all){
                if(calendarContentDiv.offsetHeight)
                        document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
                else{
                        document.getElementById('topBar').style.top = '';
                        document.getElementById('topBar').style.bottom = '0px';
                }
                        
        }
        
        if(iframeObj){
                if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
        }
                
        
}

function resizeIframe()
{
        iframeObj.style.width = calendarDiv.offsetWidth + 'px';
        iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;      
        
        
}

function pickDate()
{
        var month = currentMonth/1 +1;
        if(month<10)month = '0' + month;
        var day = this.innerHTML;
        if(day/1<10)day = '0' + day;
        if(returnFormat){
                returnFormat = returnFormat.replace('dd',day);
                returnFormat = returnFormat.replace('mm',month);
                returnFormat = returnFormat.replace('yyyy',currentYear);

                returnFormat = returnFormat.replace('hh',hours);
                returnFormat = returnFormat.replace('ii',minutes);
                returnFormat = returnFormat.replace('ss',seconds);

                returnDateTo.value = returnFormat;
        }else{
                for(var no=0;no<returnDateToYear.options.length;no++){
                        if(returnDateToYear.options[no].value==currentYear){
                                returnDateToYear.selectedIndex=no;
                                break;
                        }                               
                }
                for(var no=0;no<returnDateToMonth.options.length;no++){
                        if(returnDateToMonth.options[no].value==month){
                                returnDateToMonth.selectedIndex=no;
                                break;
                        }                               
                }
                for(var no=0;no<returnDateToDay.options.length;no++){
                        if(returnDateToDay.options[no].value==day){
                                returnDateToDay.selectedIndex=no;
                                break;
                        }                               
                }
                
                
        }
        closeCalendar();
        
}

// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add
function getWeek(year,month,day){
        day = day/1;
        year = year /1;
    month = month/1 + 1; //use 1-12
    var a = Math.floor((14-(month))/12);
    var y = year+4800-a;
    var m = (month)+(12*a)-3;
    var jd = day + Math.floor(((153*m)+2)/5) + 
                 (365*y) + Math.floor(y/4) - Math.floor(y/100) + 
                 Math.floor(y/400) - 32045;      // (gregorian calendar)
    var d4 = (jd+31741-(jd%7))%146097%36524%1461;
    var L = Math.floor(d4/1460);
    var d1 = ((d4-L)%365)+L;
    NumberOfWeek = Math.floor(d1/7) + 1;
    return NumberOfWeek;        
}

function writeBottomBar()
{
        var d = new Date();
        var topBar = document.createElement('DIV');
        topBar.id = 'topBar';
        topBar.className = 'todaysDate';
        topBar.innerHTML = todayString + ': ' + d.getDate() + '.' + monthArrayShort[d.getMonth()] + '. ' +  d.getFullYear() ;
        calendarDiv.appendChild(topBar);        
        
        
                
}
function getTopPos(inputObj)
{
        
  var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
  return returnValue + calendar_offsetTop;
}

function getleftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
  return returnValue + calendar_offsetLeft;
}

function positionCalendar(inputObj)
{
        calendarDiv.style.left = getleftPos(inputObj) + 'px';
        calendarDiv.style.top = getTopPos(inputObj) + 'px';
        if(iframeObj){
                iframeObj.style.left = calendarDiv.style.left;
                iframeObj.style.top =  calendarDiv.style.top;
        }
                
}
        
function initCalendar()
{
        if(MSIE){
                iframeObj = document.createElement('IFRAME');
                iframeObj.style.position = 'absolute';
                iframeObj.border='0px';
                iframeObj.style.border = '0px';
                iframeObj.style.backgroundColor = '#FF0000';
                document.body.appendChild(iframeObj);
        }
                
        calendarDiv = document.createElement('DIV');    
        calendarDiv.id = 'calendarDiv';
        calendarDiv.style.zIndex = 1000;
        
        document.body.appendChild(calendarDiv);
        writeBottomBar();
        writeTopBar();
        

        
        if(!currentYear){
                var d = new Date();
                currentMonth = d.getMonth();
                currentYear = d.getFullYear();
        }
        writeCalendarContent(); 


                
}


function displayCalendar(inputField,format,buttonObj)
{
        if(inputField.value.length==format.length){
                var monthPos = format.indexOf('mm');
                currentMonth = inputField.value.substr(monthPos,2)/1 -1;        
                var yearPos = format.indexOf('yyyy');
                currentYear = inputField.value.substr(yearPos,4);               
                var dayPos = format.indexOf('dd');
                tmpDay = inputField.value.substr(dayPos,2);     
                var hourPos = format.indexOf('hh');
                hours = inputField.value.substr(hourPos,2);
                var minPos = format.indexOf('ii');
                minutes = inputField.value.substr(minPos,2);
                var secPos = format.indexOf('ss');
                seconds = inputField.value.substr(secPos,2);
                
        }else{
                var d = new Date();
                currentMonth = d.getMonth();
                currentYear = d.getFullYear();
                tmpDay = 1;
        }
        
        inputYear = currentYear;
        inputMonth = currentMonth;
        inputDay = tmpDay/1;
        
        if(!calendarDiv){
           initCalendar();                 
        }else{
           writeCalendarContent();
        }                       
        returnFormat = format;
        returnDateTo = inputField;
        positionCalendar(buttonObj);
        calendarDiv.style.visibility = 'visible';       
        calendarDiv.style.display = 'block';    
        if(iframeObj){
                iframeObj.style.display = '';
                iframeObj.style.height = '140px';
                iframeObj.style.width = '195px';
        }
        updateYearDiv();
        updateMonthDiv();
        
}

function displayCalendarSelectBox(yearInput,monthInput,dayInput,buttonObj)
{
        currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
        currentYear = yearInput.options[yearInput.selectedIndex].value;

        inputYear = yearInput.options[yearInput.selectedIndex].value;
        inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
        inputDay = dayInput.options[dayInput.selectedIndex].value/1;
                        
        if(!calendarDiv){
                initCalendar();                 
        }else{
                writeCalendarContent();
        }               

        returnDateToYear = yearInput;
        returnDateToMonth = monthInput;
        returnDateToDay = dayInput;
        
        returnFormat = false;
        returnDateTo = false;
        positionCalendar(buttonObj);
        calendarDiv.style.visibility = 'visible';       
        calendarDiv.style.display = 'block';
        if(iframeObj){
                iframeObj.style.display = '';
                iframeObj.style.height = calendarDiv.offsetHeight + 'px';
                iframeObj.style.width = calendarDiv.offsetWidth + 'px'; 
        }
        updateYearDiv();
        updateMonthDiv();
                
}

/* ADCONTENT  BEGIN*/

goHide=false;
adcontent_opened=null;

function adco_initialization(){
  register_adcontent_handlers();
}
function register_adcontent_handlers(){
  try{
    var all;
    if(document.all){
      all=document.all;
    }else{
      all=document.getElementsByTagName("*");
    }    
    for(var i=0;i<all.length;i++){
      if(all[i].id){
        if(all[i].id.indexOf("adcontent_link_")==0||all[i].id.indexOf("adcontent_menu_")==0){
          all[i].onmouseover=adcontent_menu_mousein;
          all[i].onmouseout=adcontent_menu_mouseout;
        }
      }
    }
  }catch(e){
    logging("Error register_adcontent_handlers:"+e.message);
  }
}

function adcontent_menu_mousein(eventobj){
  try{
    
    var evt;if(!window.event){evt=eventobj;evt.srcElement=this;}else{evt=window.event;}
    if(!evt.srcElement)return;
    
    var id=evt.srcElement.id.substring(15);
    var menu=document.getElementById("adcontent_menu_"+id);
    if(menu){
      menu.style.display='inline';
      /// Если перепрыгнули из одного меню в другое - то убираем открытое
      if(adcontent_opened&&adcontent_opened.id!="adcontent_menu_"+id){
        goHide=true;
        adcontent_hide();
      }
      adcontent_opened=menu;
      
    }
    /// Если это переходы внутри открытого меню, не скрываем.
    if(adcontent_opened&&adcontent_opened.contains(evt.srcElement)){
      goHide=false;
    }
  }catch(e){
    logging("Error adcontent_menu_mousein:"+e.message);
  }
}

function adcontent_menu_mouseout(eventobj){
  try{
    var evt;if(!window.event){evt=eventobj;evt.srcElement=this;}else{evt=window.event;}
    if(!evt.srcElement)return; /// У фоксы бывают вызовы и без this хз что это значит %)
    var id=evt.srcElement.id.substring(15); /// ИД элемента (линка||меню)
    var menu=document.getElementById("adcontent_menu_"+id);/// Выход из меню?
    if(menu&&menu.style.display=="none")return; /// Если тупой Фаерфокс вызвал событие для невидимого меню.
    if(menu){/// Мы покинули меню 
      goHide=true;
      setTimeout("adcontent_hide();",100);
      return;
    }    
    if(adcontent_opened&&!adcontent_opened.contains(evt.srcElement)){/// Меню открыто и элемент не в нём
      goHide=true;
      setTimeout("adcontent_hide();",100);
      return;
    }
  }catch(e){
    logging("Error adcontent_menu_mouseout:"+e.message);
  }
}
function adcontent_hide(){
  try{
    if(goHide){
      if(adcontent_opened){
        adcontent_opened.style.display='none';
        adcontent_opened=null;
        goHide=false;
      }
    }
  }catch(e){
    logging("Error adcontent_hide:"+e.message);
  }
} 

/* ADCONTENT  END*/

/*Cookie*/
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if(begin == -1) {
    begin = dc.indexOf(prefix);
    if(begin != 0)
      return null;
  }else 
    begin += 2;

  var end = document.cookie.indexOf(";", begin);
  if (end == -1)end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/// IMAGES UPLOADERS
function image_insert(imagePath){
  try{
    var rte =window.opener.insert_image_into;
    var oRTE=window.opener.document.getElementById(rte);
    if (window.opener.document.all) {
      oRTE = window.opener.frames[rte];
      //get current selected range
      var selection = oRTE.document.selection; 
      if (selection != null) {rng = selection.createRange();}
    }else{
      oRTE = window.opener.document.getElementById(rte).contentWindow;
      //get currently selected range
      var selection = oRTE.getSelection();
      rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
    }
    if((imagePath != null) && (imagePath != "")) {
      oRTE.focus();
      oRTE.document.execCommand('InsertImage', false, imagePath);
      oRTE.focus();
    }
  }catch(e){
    logging("Error image_insert:"+e.message);
  }
}
function image_copy(path){    
   logging(path);
}
var editor_id="";
function AddImage(rte) {
  window.insert_image_into=rte;
  wnd=pop_up('images','750','600');
}

/*ORDERING*/
function get_ordering(form){
  text="";
  try{
    order=1;
    dc=document.getElementById("DragContainer");
    for(i=0;i<DragContainer.childNodes.length;i++){
       text=text+DragContainer.childNodes[i].id+";";
    }     
    document.all['order_list'].value=text;
    return true;
  }catch(e){
    logging("Error get_ordering:"+e.message);
    return false;
  }   
}


function CheckContent(form){
  try{
    for(i=0;i<document.forms.length;i++){
      elements=document.forms[i].elements;
      j=0;
      while(elements[j]){
        try{
          updateRTE(elements[j].name);
          place=document.getElementById('placeholder_for_'+elements[j].name);
          elements[j].name
          place.value=elements[j].value;
          
        }catch(e){
        }
        j++;
      }
    }
    return true;
  }catch(e){
    logging("Error CheckContent:"+e.message);
    return false;
  } 
}

// 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 iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;

// Demo 0 variables
var DragDrops   = [];
var curTarget   = null;
var lastTarget  = null;
var dragHelper  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

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].setAttribute('DragObj', cDrag);
    }
  }
}

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
  };
}

var dragObject  = null;
var mouseOffset = null;

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 getPosition(e){
        var left = 0;
        var top  = 0;

        while (e.offsetParent){
                left += e.offsetLeft;
                top  += e.offsetTop;
                e     = e.offsetParent;
        }

        left += e.offsetLeft;
        top  += e.offsetTop;

        return {x:left, y:top};
}

function mouseUp(){
        dragObject = null;
}

function makeDraggable(item){
        if(!item) return;
        item.onmousedown = function(ev){
                dragObject  = this;
                mouseOffset = getMouseOffset(this, ev);
                return false;
        }
}
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);
  // mouseOut event - fires if the item the mouse is on has changed
  if(lastTarget && (target!==lastTarget)){
    // reset the classname for the target element
    var origClass = lastTarget.getAttribute('origClass');
    if(origClass) lastTarget.className = origClass;
  }

  //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 = target.getAttribute('DragObj');

  // if the mouse was moved over an element that is draggable
  if(dragObj!=null){

    // mouseOver event - Change the item's class if necessary
    if(target!=lastTarget){
      var oClass = target.getAttribute('overClass');
      if(oClass){
        target.setAttribute('origClass', target.className);
        target.className = oClass;
      }
    }

    // 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]);

      // Make a copy of the current item and put it in our drag helper.
      dragHelper.appendChild(curTarget.cloneNode(true));
      dragHelper.style.display = 'block';

      // set the class on our helper DIV if necessary
      var dragClass = curTarget.getAttribute('dragClass');
      if(dragClass){
              dragHelper.firstChild.className = dragClass;
      }

      // disable dragging from our helper DIV (it's already being dragged)
      dragHelper.firstChild.removeAttribute('DragObj');

      //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';
      // loop through each possible drop container
      for(var i=0; i<dragConts.length; i++){
        with(dragConts[i]){
          var pos = getPosition(dragConts[i]);
          //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));
            setAttribute('startLeft',   pos.x);
            setAttribute('startTop',    pos.y);
          }
        }
      }
    }
  }
  // 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;
    dragHelper.style.left = mousePos.x - mouseOffset.x;
    var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
    var activeCont = null;
    var xPos = mousePos.x - mouseOffset.x + (parseInt( curTarget.getAttribute('startWidth') )  /2);
    ///
    var yPos = mousePos.y - mouseOffset.y + (parseInt( curTarget.getAttribute('startHeight') ) /2);

    // check each drop container to see if our target object is "inside" the container
    for(var i=0; i<dragConts.length; i++){
      with(dragConts[i]){
        if(((getAttribute('startLeft'))                               <xPos) &&
          ((getAttribute('startTop'))                                <yPos) &&
          ((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
          ((getAttribute('startTop')  + 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];
            // exit the for loop
            break;
        }
      }
    }
    // Our target object is in one of our containers.  Check to see where our div belongs
    if(activeCont){
      // beforeNode will hold the first node AFTER where our div belongs
      var beforeNode = null;

      // 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]                              &&
            ((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
            ((getAttribute('startTop')  + 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);
        }
      }

      // make our drag item visible
      if(curTarget.style.display!=''){
        curTarget.style.display  = '';
      }
    }else{
      // our drag item is not in a container, so hide it.
      if(curTarget.style.display!='none'){
              curTarget.style.display  = 'none';
      }
    }
  }
  // track the current mouse state so we can compare against it next time
  lMouseState = iMouseDown;
  // mouseMove target
  lastTarget  = target;
  // track the current mouse state so we can compare against it next time
  lMouseState = iMouseDown;
  // this helps prevent items on the page from being highlighted while dragging
  if(curTarget||dragObj!=null){
      return false;
  }
}

function mouseUp(ev){
  if(curTarget){
    // hide our helper object - it is no longer needed
    dragHelper.style.display = 'none';

    // if the drag item is invisible put it back where it was before moving it
    if(curTarget.style.display == 'none'){
      if(rootSibling){
        rootParent.insertBefore(curTarget, rootSibling);
      }else{
        rootParent.appendChild(curTarget);
      }
    }

    // make sure the drag item is visible
    curTarget.style.display = '';
  }
  if(curTarget){
    var fname=curTarget.getAttribute('onDropCall');
    if(fname){
      eval(fname+"(curTarget);");
    }
  }
  curTarget  = null;
  iMouseDown = false;
}

function mouseDown(){iMouseDown = true;if(lastTarget){return false;}}

function drag_initialization(){
  // Create our helper object that will show the item while dragging
  document.onmousemove = mouseMove;
  if(document.getElementById('DragContainer')){
    document.onmousedown = mouseDown;
    document.onmouseup   = mouseUp;
    dragHelper = document.createElement('DIV');
    dragHelper.style.cssText = 'position:absolute;display:none;';
    CreateDragContainer(document.getElementById('DragContainer'));
    document.body.appendChild(dragHelper);
  }
}

function tool_initialization(){
  
}
 
function upload_delete(url,name){
  var preview=document.getElementById('grape_upload_'+name);
  preview.parentNode.removeChild(preview);
  aGet(url+'/attribute?'+name+'=');
}
  
var remove_stack=new Array();
function anim_initialization(){

}
function aremove(object){
  remove_stack[remove_stack.length()]=object;

}
function aremoveListener(){
  for(var i=0;i<remove_stack.length();i++){
  
  }
}
   
var req;
var sendbutton=null;
var onCompleteEval="";
//////
function getHttpRequest(url){
  try{
    var req;
    if(window.XMLHttpRequest) {
      req = new XMLHttpRequest();
      req.open("GET", url, true);
    }else if (window.ActiveXObject) {
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if(req){
        req.open("GET", url, true);
        req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");            
        req.setRequestHeader("Content-Type","text/xml");
        req.setRequestHeader("Charset","windows-1251");
      }
    }
    req.onreadystatechange = processReqChange;
    return req;
  }catch(e){
    logging("Error getHttpRequest:"+e.message);
  }
}
function postHttpRequest(url){
  try{
    var req;
    if(window.XMLHttpRequest) {
      req = new XMLHttpRequest();
      req.open("POST", url, true);
    }else if (window.ActiveXObject) {
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if(req){
        req.open("POST", url, true);
        req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");            
        req.setRequestHeader("Content-Type","text/xml");
        req.setRequestHeader("Charset","windows-1251");
      }
    }
    req.onreadystatechange = processReqChange;
    return req;
  }catch(e){
    logging("Error postHttpRequest:"+e.message);
  }
}

function aGet(url,onComplete){
  try{
    logging("Request:"+url);
    url=url+'&hash'+Math.random();
    req=getHttpRequest(url);
    req.send(null);
    if(onComplete){onCompleteEval=onComplete;}
  }catch(e){
    logging("Error aGet:"+e.message);
  }
}
function aPost(url,data){
  try{
    data=data+'&hash'+Math.random();
    req=postHttpRequest(url);
    req.send(data);
    if(onComplete){onCompleteEval=onComplete;}
  }catch(e){
    logging("Error aPost:"+e.message);
  }
}

function loadXMLDoc(url){
  try{
    url=url+'&hash'+Math.random();
    req=getHttpRequest(url);
    req.onreadystatechange = processReqChange;
    req.send(null);
  }catch(e){
    logging(e.message+'\n in loadXMLDoc');
  }
}

//////
function processReqChange(){
  try{
    ab = window.setTimeout("req.abort();", 5000);
    if(req.readyState == 4) {
      clearTimeout(ab);
      // only if "OK"
      if(req.status == 200){
        logging("Response:"+req.responseText);
        eval(onCompleteEval+"('"+escape(req.responseText)+"');");
      }else{
        logging("Не удалось получить данные:\n" + 'Status text:'+req.statusText+'\n'+'Status code:'+req.status);
      }
      if(sendbutton){
        sendbutton.disabled=false;
        sendbutton=null;
      }
    }
  }catch(e){
    logging(e.message+'\n in processReqChange');
  }
}

function stat(n){
  try{
    switch (n) {
      case 0: return "не инициализирован"; break;        
      case 1: return "загрузка...";        break;      
      case 2: return "загружено";          break;      
      case 3: return "в процессе...";      break;        
      case 4: return "готово";             break;      
      default:return "неизвестное состояние";  
    }  
  }catch(e){
    logging(e.message+'\n in loadXMLDoc');
  }
}

function requestdata(sender,url){
  if(sender.disabled==false&&!sendbutton){
    sendbutton=sender;
    sendbutton.disabled=true;
    loadXMLDoc(url);
  }
  return false;
}

   
/*
// 2005-03-21
// Copyright (c) Art. Lebedev | http://www.artlebedev.ru/
// Author - Vladimir Tokmakov
*/

function tabs_initialization(){
  var i, j, k, eDD, iMax_height, iDT_height, aeDL_child, sDD_inner_HTML
  var bFirst_tab = true
  var aeDl = document.getElementsByTagName( "DL" )

  for( i = 0 ; i <aeDl.length ; i++ ){
    if( aeDl[i].className == "tabsheets" && aeDl[i].offsetHeight == 99 ){ // Ґб«Ё г ­ б ®ва Ў®в « CSS, в® ¬Ґ­пҐ¬ ўлб®вг г tabsheet-®ў
      aeDL_child = aeDl[i].childNodes
      iMax_height = 0
      for( j = 0 ; j <aeDL_child.length ; j++ ){
        if( aeDL_child[j].nodeName == "DT" ){
          iDT_height = aeDL_child[j].offsetHeight
          aeDL_child[j].unselectable = true
          aeDL_child[j].onmousedown = Switch_sheet
          eDD = aeDL_child[j]
          while( eDD.nextSibling ){
            eDD = eDD.nextSibling
            if( eDD.nodeName == "DD" ){
              if( eDD.offsetHeight > iMax_height ){
                iMax_height = eDD.offsetHeight
              }
              if( !bFirst_tab ){
                eDD.className = "inactive"
              }else{
                aeDL_child[j].className = "active"
              }
              bFirst_tab = false
              break
            }
          }
        }
      }
      aeDl[i].style.height = (iMax_height + iDT_height) * 1 + "px"
      for( j = 0 ; j <aeDL_child.length ; j++ ){
        if( aeDL_child[j].nodeName == "DD" ){
          aeDL_child[j].style.height = iMax_height + "px"
        }
      }
    }
    return true
  }
}

function Switch_sheet( e ){
  var eTab = e ? e.target : window.event.srcElement
  if( eTab.nodeType == 3){
    eTab = eTab.parentNode
  }
  var eSheet = eTab
  while( eSheet.nextSibling ){
    eSheet = eSheet.nextSibling
    if( eSheet.nodeName == "DD" ){
      break
    }
  }
  if( eSheet.className == "inactive" ){
    eTab.className = "on" 
    var aeDL_child = eTab.parentNode.childNodes
    for( var i = 0 ; i <aeDL_child.length ; i++ ){
      if( aeDL_child[i].nodeName == "DT" && aeDL_child[i].className != "on" ){
        aeDL_child[i].className = ""
      }else if( aeDL_child[i].nodeName == "DD" ){
        aeDL_child[i].className = "inactive"
      }
    }
    eSheet.className = "active"
    eTab.className = "active"
  }
  return false
}

function foot_initialization(){
  setFooter();
  window.onresize=setFooter;
}
function getWindowHeight(){
  var windowHeight = 0;
  if (typeof(window.innerHeight) == 'number') {
          windowHeight = window.innerHeight;
  }
  else {
          if (document.documentElement && document.documentElement.clientHeight) {
                  windowHeight = document.documentElement.clientHeight;
          }
          else {
                  if (document.body && document.body.clientHeight) {
                          windowHeight = document.body.clientHeight;
                  }
          }
  }
  return windowHeight;
}

function setFooter(){
  try{
    if (document.getElementById&&document.getElementById('wrap')&&document.getElementById('footer')){
      var windowHeight = getWindowHeight();
      var contentHeight = document.getElementById('wrap').offsetHeight;
      var footerElement = document.getElementById('footer');
      var footerHeight  = footerElement.offsetHeight;
      /*if (windowHeight > 0) {
        if (windowHeight - (contentHeight + footerHeight) >= 0) {
          footerElement.style.top = contentHeight - footerHeight + 'px';
        }
        else {
          footerElement.style.top = '0px';
        }
      }*/
      //if(contentHeight>windowHeight){
        footerElement.style.top=contentHeight - footerHeight+'px';
      //}else{
        //footerElement.style.top=windowHeight - footerHeight+'px';
      //}    
      //window.status=windowHeight +'-'+ contentHeight +'-'+ footerHeight;
    }
  }catch(e){
  
  }
}



function navi_initialization(){
  document.onkeydown = NavigateThrough;
}

function NavigateThrough(event){  
  try{
    var keyCode = window.event.keyCode;
    if(window.event.ctrlKey){
      switch (keyCode){
        case 0x25:
          link = document.getElementById ('PrevLink');
          break;
        case 0x27:
          link = document.getElementById ('NextLink');
          break;
      }
      if (link && link.href) document.location = link.href;
    }
  }catch(e){
  
  }
}


var workspace_visibility=true;
var workspace_log=true;
var currentObject=null;
function wosp_initialization(){
  try{
    workspace_visibility=getCookie("workspace_visibility")=="true"?true:false;
    workspace_log=getCookie("workspace_log")=="true"?true:false;
    workspace_create_log();
    workspace_init();
  }catch(e){  
    logging("Error wosp_initialization :"+e.message);
  }
}
function workspace_add_tooltip(page_id,user_id,initText){
  try{
    var tooltip=add_tooltip(200,200,initText);
    tooltip.page_id=page_id;
    tooltip.user_id=user_id;
    currentObject=tooltip;
    aGet(getURL("workspace_add_tooltip?")+tooltip.asString(),"workspace_added");
    return false;
  }catch(e){  
    logging("Error workspace_add_tooltip:"+e.message);
  }
}
function workspace_added(data_id){
  try{
    if(currentObject){
      currentObject.setId(data_id);
      currentObject=null;
    }
  }catch(e){  
    logging("Error workspace_add_tooltip:"+e.message);
  }
}
function workspace_add_guideline_hor(page_id,user_id){
  try{
    var guideline=add_guideline(100,false);  
    guideline.page_id=page_id;
    guideline.user_id=user_id;
    currentObject=guideline;
    aGet(getURL("workspace_add_guideline_hor?")+guideline.asString(),"workspace_added");
  }catch(e){  
    logging("Error workspace_add_guideline_hor:"+e.message);
  }
}
function workspace_add_guideline_ver(page_id,user_id){
  try{
    var guideline=add_guideline(100,true);
    guideline.page_id=page_id;
    guideline.user_id=user_id;
    currentObject=guideline;
    aGet(getURL("workspace_add_guideline_ver?")+guideline.asString(),"workspace_added");
  }catch(e){  
    logging("Error workspace_add_guideline_ver :"+e.message);
  }
}

function workspace_change_guideline(guideline){
  try{
    aGet(getURL("workspace_edit?")+guideline.asString());
  }catch(e){  
    logging("Error workspace_change_guideline :"+e.message);
  }
}

function workspace_change_tooltip(tooltip){
  try{
    aGet(getURL("workspace_edit?")+tooltip.asString());
  }catch(e){  
    logging("Error workspace_change_guideline :"+e.message);
  }
}
function workspace_delete(object){
  try{
    logging(object.data_id);
    aGet(getURL("workspace_delete?")+object.asString());
  }catch(e){  
    logging("Error workspace_delete :"+e.message);
  }
}

function workspace_hide(){
  try{
    workspace_visibility=!workspace_visibility;
    setCookie("workspace_visibility",workspace_visibility);
    var i=0;
    for(i in tooltips){
      tooltips[i].div.style.visibility=workspace_visibility?"visible":"hidden";
    }
    for(i in guidelines){
      guidelines[i].div.style.visibility=workspace_visibility?"visible":"hidden";
    }
  }catch(e){  
    logging("Error workspace_hide :"+e.message);
  }
}
function workspace_logging(){
  try{
    workspace_log=!workspace_log; 
    setCookie("workspace_log",workspace_log);
    workspace_create_log();
  }catch(e){  
    logging("Error workspace_logging:"+e.message);
  }
}
function workspace_create_log(){
  try{
    var logg=document.getElementById('logging');
    if(!logg){
      logg=create("div",{id:"logging","class":"logging"});
      logg.innerText="Logiing place:";
      document.body.appendChild(logg);
    }
    logg.style.visibility=workspace_log?"visible":"hidden";
  }catch(e){  
    logging("Error workspace_create_log:"+e.message);
  }
}

function logging(text){
  try{
    logg=document.getElementById('logging');
    if(logg){
      logg.innerHTML=tagsToText(text)+"<br>"+logg.innerHTML;
    }else{
      alert(text);
    }
  }catch(e){  
    alert(text+"\n"+e.message);
  }
}

function noSelection(){return false;}

function create( name, attributes ) {
  try{
    var el = document.createElement( name );
    if ( typeof attributes == 'object' ) {
      for ( var i in attributes ) {
        el.setAttribute( i, attributes[i] );  
        if ( i.toLowerCase() == 'class' ) {
          el.className = attributes[i];  // for IE compatibility
  
        }
        if ( i.toLowerCase() == 'style' ) {
          el.style.cssText = attributes[i]; // for IE compatibility
        }
      }
    }
    for ( var i = 2; i<arguments.length; i++ ) {
      var val = arguments[i];
      if ( typeof val == 'string' ) { val = document.createTextNode( val ) };
      el.appendChild( val );
    }
    return el;
  }catch(e){
    logging("Error create:"+e.message);
  }
}

/// “¤ «пҐв ўбҐе ¤ҐвҐ©
function removeChilds(object){
  while(object.childNodes[0]){
    object.removeChild(object.childNodes[0]);
  }
}

function toHtml(string){

}
function toText(string){

}
function tagsToText(string){
  var result=new String(string);
  result=result.replace(/\</g,"&lt;");
  result=result.replace(/\>/g,"&gt;");
  return result;
}
function getURL(action){
  try{
    var base=new String(document.location);
    if(base.substring(base.length-1)=="/"){
      return base+action;
    }else{
      return base+"/"+action;
    }
  }catch(e){
    logging("Error getURL:"+e.message);
  }
}

function setTransparent(object,alpha){
  try{
    object.style.filter="Alpha(opacity="+alpha+")";
  }catch(e){
    logging("Error setTransparent:"+e.message);
  }
}

var guidelines=new Array();
var guidedraging=null;
var saved_onselectstart=null;

function guideline(orientation){
  this.data_id=0;
  this.text="";
  this.orientation=orientation;
  this.setPosition=guide_setPosition;
  this.setId      =guide_setId;
  this.asString   =guide_asString;
  this.attached   =false;
  this.zIndex     =0;
  return this;
}
function guide_asString(){
  try{
    return "kind=guideline&x="+this.x+"&y="+this.y+"&attached="+this.attached+"&data_id="+this.data_id+"&page_id="+this.page_id+"&user_id="+this.user_id+"&text="+this.text+"&orientation="+this.orientation+"&position="+this.position+"&zIndex="+this.zIndex;
  }catch(e){
    logging("Error guide_asString:"+e.message);
  }
}
function guide_setId(id){
  this.data_id=id;
}
function guide_setPosition(position){
  try{    
    if(this.orientation){
      this.position=position+document.documentElement.scrollLeft;
    }else{
      this.position=position+document.documentElement.scrollTop;
    }
    if(position>0){
      if(this.orientation){
        this.div.style.left=this.position;
        this.div.style.top =0;
        this.indicator.innerHTML=position+"px";
      }else{
        if(position>40){
          this.div.style.top =this.position-40;
          this.div.style.left=0;
          this.indicator.innerHTML=position-40+"px";
        }
      }
    }
  }catch(e){
    logging("Error guide_setId:"+e.message);
  }
}

function guide_mousedown(object){
  try{
    if(!object){
      object=event.srcElement;
    }else{
      object=object.srcElement;
    }
    guide=object.guide;
    guidedraging=guide;
    saved_onselectstart=document.body.onselectstart;
    document.body.onselectstart=noSelection;
    zordering(guidelines,guidedraging.id);
    guidedraging.zIndex=guidedraging.div.style.zIndex;
    logging(guidedraging.zIndex);
  }catch(e){
    logging("Error:"+e.message);
  }
}

function guide_mousemove(event){
  try{
    if(guidedraging){
      var div=document.getElementById('guide_'+guidedraging.id);
      var indicator=document.getElementById('guide_indicator_'+guidedraging.id);
      var npos=guidedraging.orientation?event.clientX:event.clientY;
      var maxp=guidedraging.orientation?document.body.clientWidth:document.body.clientHeight;
      if((npos>3)&&((maxp-npos)>3)){
        guidedraging.setPosition(npos-4);
      }
    }
  }catch(e){
    logging("Error:"+e.message);
  }
}

function guide_mouseup(event){
  try{
    if(guidedraging){
      workspace_change_guideline(guidedraging);
      guidedraging=null;
      document.body.onselectstart=saved_onselectstart;
    }
  }catch(e){
    logging("Error:"+e.message);
  }
}

function add_guideline(pos,orientation){
  try{
    var guide=new guideline(orientation);
    guide.id=guidelines.length;
    guidelines[guidelines.length]=guide;
    var className=orientation?"guidelinev":"guidelineh";
    /// Guide
    guide.div=create( "div", { id: "guide_"+guide.id,"class":className});
    guide.div.onmousedown=guide_mousedown;
    guide.div.guide=guide;
    document.body.appendChild(guide.div);
    /// Indicator
    var indicator=create( "div", { id: "guide_indicator_"+guide.id,"class":"guide_indicator"});
    guide.indicator=indicator;
    guide.indicator.guide=guide;
    guide.indicator.onmousedown=guide_mousedown;
    guide.div.appendChild(indicator);
    /// Information
    /// Setting a position
    guide.setPosition(pos);
    return guide;
  }catch(e){
    logging("Error add_guideline:"+e.message);
  }
}
 
/// Сортирует 
function getMaxZindex(elements){
  try{
    var zmax=0;
    for(el in elements){
      if(elements[el].div.style.zIndex>zmax){
        zmax=elements[el].div.style.zIndex;
      }
    }
    return zmax;
  }catch(e){
    logging("getMaxZindex:"+e.message);    
  }
}
function getMaxZindexElement(elements){
    var zmaxe=0;
    for(el in elements){
      if(elements[el].div.style.zIndex>elements[zmaxe].div.style.zIndex){
        zmaxe=el;
      }
    }
    return zmaxe;
}
function initzindex(elements,element){
  try{
    elements[element].div.style.zIndex=getMaxZindex(elements)+1;
  }catch(e){
    logging("Initzindex error:"+e.message);    
  }
}
function zordering(elements,front){
  try{
    //var first=elements[front].div;
    //var maxe=getMaxZindexElement(elements);
    //logging(elements[front].div.style.zIndex+":"+elements[maxe].div.style.zIndex);
    //var zstore=elements[front].div.style.zIndex;
    //elements[front].div.style.zIndex=elements[maxe].div.style.zIndex;
    //elements[maxe].div.style.zIndex=zstore;
    elements[front].div.style.zIndex=getMaxZindex(elements)+1;
  }catch(e){
    logging("Zordering error:"+e.message);    
  }
}
 
var tooltips=new Array();
var dragedTooltip=null;

function toot_initialization(){
  try{
    document.attachEvent("onmousemove", tooltip_onmousemove);
    document.attachEvent("onmouseup", tooltip_onmouseup);  
  }catch(e){  
    logging("Error toot_initialization:"+e.message);
  }
}

function tooltip(x,y,text){
  try{
    this.text=text;
    this.x=x;
    this.y=y;  
    this.offsetX=0;
    this.offsetY=0;
    this.data_id=0;
    this.page_id=0;
    this.user_id=0;
    this.editing=false;
    this.setPosition=tooltip_setPosition;
    this.attached=false;
    this.setAttached=tooltip_setAttached;
    this.asString=tooltip_asString;
    this.setId=tooltip_setId;

    this.zIndex=0;
  }catch(e){  
    logging("Error tooltip constructor:"+e.message);
  }
}

function tooltip_asString(){
  try{
    return "kind=tooltip&x="+this.x+"&y="+this.y+"&attached="+this.attached+"&data_id="+this.data_id+"&page_id="+this.page_id+"&user_id="+this.user_id+"&text="+this.text+"&zIndex="+this.zIndex;
  }catch(e){  
    logging("Error tooltip_asString:"+e.message);
  }
}
function tooltip_setId(id){
  try{
    this.data_id=id;
    this.titleid.innerHTML="ID#"+id;

  }catch(e){  
    logging("Error tooltip_setId:"+e.message);
  }
}
function tooltip_setAttached(value){
  try{
    this.attached=value;
    this.att.className=this.attached?"tooltip_attached":"tooltip_attach";
  }catch(e){  
    logging("Error tooltip_setAttached:"+e.message);
  }
}
function tooltip_onmousedown(object){
  try{
    if(!object){object=event.srcElement;}else{object=object.srcElement;}   
    if(object.tooltip&&(object.className=="tooltip_title"||object.className=="tooltip_editor"||object.className=="tooltip_id")){
      dragedTooltip=object.tooltip;
      saved_onselectstart=document.body.onselectstart;
      dragedTooltip.offsetX=event.offsetX;
      dragedTooltip.offsetY=event.offsetY;
      zordering(tooltips,dragedTooltip.id);
      dragedTooltip.zIndex=dragedTooltip.div.style.zIndex;
      document.body.onselectstart=noSelection;
    }  
  }catch(e){  
    logging("Tooltip_onmousedown error:"+e.message);
  }
}

function tooltip_onmousemove(event){
  try{    
    if(dragedTooltip){
      dragedTooltip.setPosition(event.clientX-5,event.clientY-5);    
    }  
  }catch(e){  
    logging("Tooltip_onmousemove error:"+e.message);
  }
}

function tooltip_onmouseup(event){
  try{
    if(dragedTooltip){
      dragedTooltip.x=dragedTooltip.x-dragedTooltip.offsetX;
      dragedTooltip.y=dragedTooltip.y-dragedTooltip.offsetY;
      workspace_change_tooltip(dragedTooltip);
      dragedTooltip=null;
      document.body.onselectstart=saved_onselectstart;
    }  
  }catch(e){  
    logging("Tooltip_onmouseup error:"+e.message);
  }
}

function tooltip_setPosition(x,y){
  try{
    this.x=x;
    this.y=y;
    this.div.style.left=x-this.offsetX+document.documentElement.scrollLeft;//+4
    this.div.style.top=y-this.offsetY+document.documentElement.scrollTop-40;//+16    
  }catch(e){  
    logging("Tooltip_setPosition error:"+e.message);
  }
}

function tooltip_attach(object){
  try{
    if(!object){object=event.srcElement;}else{object=object.srcElement;}   
    object.tooltip.setAttached(!object.tooltip.attached);
    workspace_change_tooltip(object.tooltip);
    return false;
  }catch(e){  
    logging("Tooltip_attach error:"+e.message);
  }
}

function tooltip_delete(eobject){
  try{
    if(!eobject){object=event.srcElement;}else{object=eobject.srcElement;}   
    var tooltip=object.tooltip;
    workspace_delete(tooltip);
    tooltips.splice(tooltip.id);
    document.body.removeChild(tooltip.div);
    return false;
  }catch(e){  
    logging("Tooltip_delete error:"+e.message);
  }
}

function tooltip_editbut(eobject){
  try{
    var object;
    if(!eobject){object=event.srcElement;}else{object=eobject.srcElement;}   
    object.tooltip.editing=!object.tooltip.editing;
    object.className=object.tooltip.editing?"tooltip_editbut tooltip_editbut_inedit":"tooltip_editbut tooltip_editbut_outedit";
    if(object.tooltip.editing){
      object.tooltip.textarea.value=object.tooltip.text.replace(/\<br\>/g,"\n");
      object.tooltip.textarea.style.display="block";
      object.tooltip.editor.style.display="none";
    }else{
      object.tooltip.textarea.style.display="none";
      object.tooltip.editor.style.display="block";      
      object.tooltip.text=object.tooltip.textarea.value.replace(/\n/g,"<br>");
      object.tooltip.editor.innerHTML=object.tooltip.text;
      workspace_change_tooltip(object.tooltip);
    }
    return false;
  }catch(e){  
    logging("Tooltip_delete error:"+e.message);
  }
}

function add_tooltip(x,y,text){
  try{
    var tt=new tooltip(x,y,text);
    tt.id=tooltips.length;
    tooltips[tooltips.length]=tt;
    /// Main tooltip div    
    tt.div=create("div",{id:"tooltip_"+tt.id,"class":"tooltip"});
    tt.div.tooltip=tt;
    /// Tooltip title
    tt.title=create("div", {id:"tooltip_"+tt.id,"class":"tooltip_title"});
    tt.title.tooltip=tt;
    tt.title.onmousedown=tooltip_onmousedown;
    tt.div.appendChild(tt.title);
    /// Tooltip id
    tt.titleid=create("div", {id:"tooltip_"+tt.id,"class":"tooltip_id"});
    tt.titleid.tooltip=tt;
    tt.titleid.innerHTML="ID#unknown";
    tt.title.onmousedown=tooltip_onmousedown;
    tt.title.appendChild(tt.titleid);

    /// Tooltip editor
    tt.editco=create("div", {id:"tooltip_"+tt.id,"class":"tooltip_editcontainer"});
    tt.editco.tooltip=tt;
    tt.div.appendChild(tt.editco);
    /// Tooltip editor
    tt.editor=create("div", {id:"tooltip_"+tt.id,"class":"tooltip_editor"});
    tt.editor.tooltip=tt;
    tt.editor.innerHTML=text;
    tt.editor.onmousedown=tooltip_onmousedown;
    tt.editco.appendChild(tt.editor);
    /// Tooltip editor field
    tt.textarea=create("textarea",{id:"tooltip_"+tt.id,"class":"tooltip_textarea"});
    tt.textarea.tooltip=tt;
    tt.textarea.value=text;
    tt.textarea.style.display="none";
    tt.editco.appendChild(tt.textarea);
    /// Tooltip delete
    tt.del=create("a",{id:"tooltip_"+tt.id,"class":"tooltip_delete"});
    tt.del.tooltip=tt;
    tt.del.onclick=tooltip_delete;
    tt.title.appendChild(tt.del);  
    /// Tooltip attach
    tt.att=create("a",{id:"tooltip_"+tt.id,"class":"tooltip_attach"});
    tt.att.tooltip=tt;
    tt.att.onclick=tooltip_attach;
    tt.title.appendChild(tt.att);  
    /// Tooltip editbut
    tt.del=create("a",{id:"tooltip_"+tt.id,"class":"tooltip_editbut tooltip_editbut_outedit"});
    tt.del.tooltip=tt;
    tt.del.onclick=tooltip_editbut;
    tt.title.appendChild(tt.del);  
    //// Done !
    document.body.appendChild(tt.div);
    tt.setPosition(x,y);
    initzindex(tooltips,tt.id);
    return tt;
  }catch(e){  
    logging("Add_tooltip error:"+e.message);
  }
}
  
 
window.onload=initialization;

function initialization(){
  menu_initialization();
  drag_initialization();
  tool_initialization();
  tabs_initialization();
  anim_initialization();
  foot_initialization();
  adco_initialization();
  navi_initialization();
  toot_initialization();
  wosp_initialization();
}

