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;
    }
    return true;
  }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 grap_initialization(){
  try{
    var closebut=getElement("close_window_input");
    if(closebut&&!window.opener){
      closebut.style.display="none";
    }
  }catch(e){
    logging("Error grap_initialization:"+e.message);
  }
}

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 currentopened = null;
function menu_initialization(){
  register_menu_handlers();
}
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_close_force;}
      }
    }
  }catch(e){
    logging("Error register_menu_handlers:"+e.message);
  }
}
function menu_find_parent_id(object){
  try{
    if(!object.id){
      if(object.parentNode){
        return menu_find_parent_id(object.parentNode);
      }else{
        return false;
      }
    }else{
      return object.id;
    }
  }catch(e){
    logging("Error menu_find_parent_id:"+e.message);
  }
}
function menu_get_sub(object){
  try{
    var id=new String(menu_find_parent_id(object)).substring(4);
    var submenu_id="sub_"+id;
    return getElement(submenu_id);
  }catch(e){
    logging("Error menu_get_sub:"+e.message);
  }
}
function menu_in_menu(object){
  try{
    while(object.parentNode){
      var id=object.id.substring(4);
      if(id){
        var itmmenu_id="itm_"+id;
        var submenu_id="sub_"+id;
        if(getElement(itmmenu_id)||getElement(submenu_id)){
           return submenu_id;
        }
      }    
      object=object.parentNode;
    }
    return false;
  }catch(e){
    logging("Error menu_in_menu:"+e.message);
  }
}

function menu_mousein(event){
  try{
        event   = event || window.event;
    var object  = event.target || event.srcElement;
    if(menu_in_menu(object)){
      var submenu=menu_get_sub(object);
      if(submenu){
        if(currentopened&&currentopened.id!=submenu.id){
          currentopened.style.display="none";
        }
        submenu.style.display="block";
        currentopened=submenu;
        submenutoclose=null;
      }
    }
    submenutoclose=null;
    return false;
    
  }catch(e){
    logging("Error menu_mousein:"+e.message);
  }
}

function menu_mouseout(event){
  try{
        event   = event || window.event;
    var object  = event.target || event.srcElement;
    var submenu;
    if(submenu=menu_get_sub(object)){
      setTimeout("menu_close_sub()",200);
      submenutoclose=submenu;
    }
    return false;
  }catch(e){
    logging("Error menu_mouseout:"+e.message);
  }
}

function menu_close_sub(id){
  try{
    if(submenutoclose){
      submenutoclose.style.display="none";
    }
  }catch(e){
    logging("Error menu_close_sub:"+e.message);
  }
}
function menu_close_force(event){
  try{
        event   = event || window.event;
    var object  = event.target || event.srcElement;
    var id      = menu_in_menu(object);
    var submenu = getElement(id);
    submenu.style.display="none";
  }catch(e){
    logging("Error menu_close_force:"+e.message);
  }
}
/*  TOOLBAR MENU FUNCTIONS */

/* 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 get_rte_object(){

}
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) {
  try{
    window.insert_image_into=rte;
    wnd=pop_up('images','750','600');
  }catch(e){
    logging("Error AddImage:"+e.message);
  }
}

function file_insert(path){
  try{
    alert(path);
  }catch(e){
    logging("Error file_insert:"+e.message);
  }
}

function image_delete(object,id){
  try{
    var url=getHost()+"image_delete?"+"file_id="+id;
    aGet(url);
    var image_container=object.parentNode.parentNode;
    var images_container=object.parentNode.parentNode.parentNode;
    images_container.removeChild(image_container);
  }catch(e){
    logging("Error file_insert:"+e.message);
  }
}

/*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(button){
  try{
    for(i=0;i<document.forms.length;i++){
      var elements=document.forms[i].elements;
      var formname=document.forms[i].id;
      j=0;
      while(elements[j]){
        place=document.getElementById('input_'+formname+'_'+elements[j].name);
        if(place&&place.className=="placeholder"){
          updateRTE(elements[j].name);
          place.value=elements[j].value;          
        }
        j++;
      }
    }
    button.form.submit();
    button.disabled=1;
    return false;
  }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;
  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.
  if(!target.getAttribute)return;///  
  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.url=url;
    req.onreadystatechange = processReqChange;
    req.send(null);
  }catch(e){
    logging(e.message+'\n in loadXMLDoc');
  }
}

//////
function processReqChange(){
  try{
    if(req.readyState == 4) {
      // only if "OK"
      if(req.status == 200){
        //logging("Response:"+req.responseText);
        eval(onCompleteEval+"('"+escape(req.responseText)+"',req);");
        if(sendbutton){
          sendbutton.disabled=false;
          sendbutton=null;
        }
      }else{
        logging("Не удалось получить данные:\n" + 'Status text:'+req.statusText+'\n'+'Status code:'+req.status);
      }
    }
  }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 stat');
  }
}

function requestdata(sender,url){
  if(sender.disabled==false&&!sendbutton){
    sendbutton=sender;
    sendbutton.disabled=true;
    loadXMLDoc(url);
  }
  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(getElement('wrap')&&getElement('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{
        event   = event || window.event;
    var object  = event.target || event.srcElement;
    var keyCode = event.keyCode;
    if(event.ctrlKey){
      if(object.tagName!="INPUT"&&object.tagName!="TEXTAREA"){
        var link=null;
        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){
    logging("Error NavigateThrough:"+e.message);
  }
}


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();
  }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,0,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,0,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{
    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 getHost(){
  var url=new URL(new String(document.location));
  return "http://"+url.getHost()+"/";
}
function setTransparent(object,alpha){
  try{
    object.style.filter="Alpha(opacity="+alpha+")";
    object.style.opacity=alpha/100;
    object.style.KhtmlOpacity=alpha/100;

  }catch(e){
    logging("Error setTransparent:"+e.message);
  }
}

document.getElementsByClassName = function(className) {
  var children = document.getElementsByTagName('*') || document.all;
  var elements = new Array();
  
  for(var i = 0; i <children.length; i++) {
    var child = children[i];
    var classNames = child.className.split(' ');
    for(var j = 0; j <classNames.length; j++) {
      if(classNames[j] == className) {
        elements.push(child);
        break;
      }
    }
  }
  return elements;
}

function getElementsByClass(className){
  try{
    return document.getElementsByClassName(className);
  }catch(e){
    logging("Error getElementsByClass:"+e.message);
  }
}

if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/){
    var len = this.length;
    var from = Number(arguments[1]) || 0;
    from = (from <0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from <0)
      from += len;

    for (; from <len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
function getElement(id){
  try{
    return document.getElementById(id);
  }catch(e){
    logging("Error setTransparent:"+e.message);
  }
}


document.addEvent=function (obj, evType, fn, useCapture) {
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  }else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  }else{
    alert("Handler could not be attached");
  }
}

function addEvent(obj, evType, fn, useCapture){
  try{
    return document.addEvent(obj, evType, fn, useCapture);
  }catch(e){
    logging("Error addEvent:"+e.message);
  }
}

document.removeEvent=function (obj, evType, fn, useCapture){
  if(obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  }else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  }else{
    alert("Handler could not be removed");
  }
}

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;
}


if(typeof(HTMLElement) != 'undefined') HTMLElement.prototype.swapNode = function (node) {
  var nextSibling = this.nextSibling;
  var parentNode = this.parentNode;
  node.parentNode.replaceChild(this, node);
  parentNode.insertBefore(node, nextSibling);
}

var guidelines=new Array();
var guidedraging=null;
var saved_onselectstart=null;

function guid_initialization(){
  addEvent(document,"mousemove", guide_mousemove);
  addEvent(document,"mouseup", guide_mouseup);
}

function guideline(orientation){
  this.data_id=0;
  this.text="";
  this.orientation=orientation;
  this.setPosition=guide_setPosition;
  this.setAttached=guide_setAttached;
  this.setId      =guide_setId;
  this.asString   =guide_asString;
  this.attached   =true;
  this.x          =0;
  this.y          =0;
  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(data_id){
  try{
    this.data_id=data_id;
  }catch(e){
    logging("Error guide_setAttached:"+e.message);
  }
}
function guide_setAttached(value){
  try{
    this.attached=value;
    this.ancor.className=value?"guide_ancor_down":"guide_ancor_up";
  }catch(e){
    logging("Error guide_setAttached:"+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";
        this.x                  =this.position;
      }else{
        if(position>40){
          this.div.style.top      =this.position-40;
          this.div.style.left     =0;
          this.indicator.innerHTML=position-40+"px";
          this.y                  =position;
        }
      }
    }
  }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;
  }catch(e){
    logging("Error guide_mousedown:"+e.message);
  }
}
function guide_ancor_click(eobject){
  try{
    if(!eobject){object=event.srcElement;}else{object=eobject.srcElement;}   
    object.guide.setAttached(!object.guide.attached);
    workspace_change_guideline(object.guide);
    return false;
  }catch(e){
    logging("Error guide_ancor_click:"+e.message);
  }
}
function guide_deleter_click(eobject){
  try{
    if(!eobject){object=event.srcElement;}else{object=eobject.srcElement;}   
    var guide=object.guide;
    workspace_delete(guide);
    guidelines.splice(guide.id);
    document.body.removeChild(guide.div);
    return false;
  }catch(e){
    logging("Error guide_deleter_click:"+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 guide_mousemove:"+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(x,y,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);
    /// Info
    var info=create( "div", { id: "guide_info_"+guide.id,"class":"guide_info"});
    guide.info=info;
    guide.info.guide=guide;
    guide.info.onmousedown=guide_mousedown;
    guide.div.appendChild(info);
    /// Position 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;
    info.appendChild(indicator);
    /// Ancor
    var ancor=create( "div", { id: "guide_ancor_"+guide.id,"class":"guide_ancor_down"});
    guide.ancor=ancor;
    guide.ancor.guide=guide;
    guide.ancor.onclick=guide_ancor_click;
    info.appendChild(ancor);
    /// Deleter
    var deleter=create( "div", { id: "guide_deleter_"+guide.id,"class":"guide_deleter"});
    guide.deleter=deleter;
    guide.deleter.guide=guide;
    guide.deleter.onclick=guide_deleter_click;
    info.appendChild(deleter);
    /// Setting a position
    guide.setPosition(orientation?x:y);
    return guide;
  }catch(e){
    logging("Error add_guideline:"+e.message);
  }
}
 
/// Сортирует 
function getMaxZindex(elements){
  try{
    var zmax=0;
    for(var el=0;el<elements.length;el++){
      if(elements[el].div.style.zIndex>zmax){
        zmax=elements[el].div.style.zIndex;
      }
    }
    return zmax;
  }catch(e){
    logging("getMaxZindex:\n"+e.message);    
  }
}
function getMaxZindexElement(elements){
    var zmaxe=0;
    for(var el=0;el<elements.length;el++){
      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{
    addEvent(document,"mousemove", tooltip_onmousemove);
    addEvent(document,"mouseup", 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);
  }
}
  
/**
 * reflection.js v1.6
 *
 * Contributors: Cow http://cow.neondragon.net
 *               Gfx http://www.jroller.com/page/gfx/
 *               Sitharus http://www.sitharus.com
 *               Andreas Linde http://www.andreaslinde.de
 *               Tralala, coder @ http://www.vbulletin.org
 *
 * Freely distributable under MIT-style license.
 */
 
var Reflection = {
        defaultHeight : 0.5,
        defaultOpacity: 0.5,
        
        add: function(image, options) {
                Reflection.remove(image);
                
                doptions = { "height" : Reflection.defaultHeight, "opacity" : Reflection.defaultOpacity }
                if (options) {
                        for (var i in doptions) {
                                if (!options[i]) {
                                        options[i] = doptions[i];
                                }
                        }
                } else {
                        options = doptions;
                }
        
                try {
                        var d = document.createElement('div');
                        var p = image;
                        
                        var classes = p.className.split(' ');
                        var newClasses = '';
                        for (j=0;j<classes.length;j++) {
                                if (classes[j] != "reflect") {
                                        if (newClasses) {
                                                newClasses += ' '
                                        }
                                        
                                        newClasses += classes[j];
                                }
                        }

                        var reflectionHeight = Math.floor(p.height*options['height']);
                        var divHeight = Math.floor(p.height*(1+options['height']));
                        
                        var reflectionWidth = p.width;
                        
                        if (document.all && !window.opera) {
                                /* Copy original image's classes & styles to div */
                                d.className = newClasses;
                                p.className = 'reflected';
                                
                                d.style.cssText = p.style.cssText;
                                p.style.cssText = 'vertical-align: bottom';
                        
                                var reflection = document.createElement('img');
                                reflection.src = p.src;
                                reflection.style.width = reflectionWidth+'px';
                                
                                reflection.style.marginBottom = "-"+(p.height-reflectionHeight)+'px';
                                reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(options['opacity']*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(options['height']*100)+')';
                                
                                d.style.width = reflectionWidth+'px';
                                d.style.height = divHeight+'px';
                                p.parentNode.replaceChild(d, p);
                                
                                d.appendChild(p);
                                d.appendChild(reflection);
                        } else {
                                var canvas = document.createElement('canvas');
                                if (canvas.getContext) {
                                        /* Copy original image's classes & styles to div */
                                        d.className = newClasses;
                                        p.className = 'reflected';
                                        
                                        d.style.cssText = p.style.cssText;
                                        p.style.cssText = 'vertical-align: bottom';
                        
                                        var context = canvas.getContext("2d");
                                
                                        canvas.style.height = reflectionHeight+'px';
                                        canvas.style.width = reflectionWidth+'px';
                                        canvas.height = reflectionHeight;
                                        canvas.width = reflectionWidth;
                                        
                                        d.style.width = reflectionWidth+'px';
                                        d.style.height = divHeight+'px';
                                        p.parentNode.replaceChild(d, p);
                                        
                                        d.appendChild(p);
                                        d.appendChild(canvas);
                                        
                                        context.save();
                                        
                                        context.translate(0,image.height-1);
                                        context.scale(1,-1);
                                        
                                        context.drawImage(image, 0, 0, reflectionWidth, image.height);
        
                                        context.restore();
                                        
                                        context.globalCompositeOperation = "destination-out";
                                        var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
                                        
                                        gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
                                        gradient.addColorStop(0, "rgba(255, 255, 255, "+(1-options['opacity'])+")");
                
                                        context.fillStyle = gradient;
                                        if (navigator.appVersion.indexOf('WebKit') != -1) {
                                                context.fill();
                                        } else {
                                                context.fillRect(0, 0, reflectionWidth, reflectionHeight*2);
                                        }
                                }
                        }
                } catch (e) {
            }
        },
        
        remove : function(image) {
                if (image.className == "reflected") {
                        image.className = image.parentNode.className;
                        image.parentNode.parentNode.replaceChild(image, image.parentNode);
                }
        }
}

function refl_initialization() {
        var rimages = document.getElementsByClassName('reflect');
        for (i=0;i<rimages.length;i++) {
                var rheight = null;
                var ropacity = null;
                
                var classes = rimages[i].className.split(' ');
                for (j=0;j<classes.length;j++) {
                        if (classes[j].indexOf("rheight") == 0) {
                                var rheight = classes[j].substring(7)/100;
                        } else if (classes[j].indexOf("ropacity") == 0) {
                                var ropacity = classes[j].substring(8)/100;
                        }
                }
                
                Reflection.add(rimages[i], { height: rheight, opacity : ropacity});
        }
}
  
/* URL class for JavaScript
 * Copyright (C) 2003 Johan Kдnngеrd, <johan AT kanngard DOT net>
 * http://dev.kanngard.net/
 *	
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * The GPL is located at: http://www.gnu.org/licenses/gpl.txt
 */

/* Creates a new URL object with the specified url String. */
function URL(url){
	if(url.length==0) eval('throw "Invalid URL ['+url+'];');
	this.url=url;
	this.port=-1;
	this.query=(this.url.indexOf('?')>=0)?this.url.substring(this.url.indexOf('?')+1):'';
	if(this.query.indexOf('#')>=0) this.query=this.query.substring(0,this.query.indexOf('#'));
	this.protocol='';
	this.host='';
	var protocolSepIndex=this.url.indexOf('://');
	if(protocolSepIndex>=0){
		this.protocol=this.url.substring(0,protocolSepIndex).toLowerCase();
		this.host=this.url.substring(protocolSepIndex+3);
		if(this.host.indexOf('/')>=0) this.host=this.host.substring(0,this.host.indexOf('/'));
		var atIndex=this.host.indexOf('@');
		if(atIndex>=0){
			var credentials=this.host.substring(0,atIndex);
			var colonIndex=credentials.indexOf(':');
			if(colonIndex>=0){
				this.username=credentials.substring(0,colonIndex);
				this.password=credentials.substring(colonIndex);
			}else{
				this.username=credentials;
			}
			this.host=this.host.substring(atIndex+1);
		}
		var portColonIndex=this.host.indexOf(':');
		if(portColonIndex>=0){
			this.port=this.host.substring(portColonIndex);
			this.host=this.host.substring(0,portColonIndex);
		}
		this.file=this.url.substring(protocolSepIndex+3);
		this.file=this.file.substring(this.file.indexOf('/'));
	}else{
		this.file=this.url;
	}
	if(this.file.indexOf('?')>=0) this.file=this.file.substring(0, this.file.indexOf('?'));
	var refSepIndex=url.indexOf('#');
	if(refSepIndex>=0){
		this.file=this.file.substring(0,refSepIndex);
		this.reference=this.url.substring(this.url.indexOf('#'));
	}else{
		this.reference='';
	}
	this.path=this.file;
	if(this.query.length>0) this.file+='?'+this.query;
	if(this.reference.length>0) this.file+='#'+this.reference;

	this.getPort=getPort;
	this.getQuery=getQuery;
	this.getProtocol=getProtocol;
	this.getHost=getHost;
	this.getUserName=getUserName;
	this.getPassword=getPassword;
	this.getFile=getFile;
	this.getReference=getReference;
	this.getPath=getPath;
	this.getArgumentValue=getArgumentValue;
	this.getArgumentValues=getArgumentValues;
	this.toString=toString;

	/* Returns the port part of this URL, i.e. '8080' in the url 'http://server:8080/' */
	function getPort(){
		return this.port;
	}

	/* Returns the query part of this URL, i.e. 'Open' in the url 'http://server/?Open' */
	function getQuery(){
		return this.query;
	}

	/* Returns the protocol of this URL, i.e. 'http' in the url 'http://server/' */
	function getProtocol(){
		return this.protocol;
	}

	/* Returns the host name of this URL, i.e. 'server.com' in the url 'http://server.com/' */
	function getHost(){
		return this.host;
	}

	/* Returns the user name part of this URL, i.e. 'joe' in the url 'http://joe@server.com/' */
	function getUserName(){
		return this.username;
	}

	/* Returns the password part of this url, i.e. 'secret' in the url 'http://joe:secret@server.com/' */
	function getPassword(){
		return this.password;
	}

	/* Returns the file part of this url, i.e. everything after the host name. */
	function getFile(){
		return this.file;
	}

	/* Returns the reference of this url, i.e. 'bookmark' in the url 'http://server/file.html#bookmark' */
	function getReference(){
		return this.reference;
	}

	/* Returns the file path of this url, i.e. '/dir/file.html' in the url 'http://server/dir/file.html' */
	function getPath(){
		return this.path;
	}

	/* Returns the FIRST matching value to the specified key in the query.
	   If the url has a non-value argument, like 'Open' in '?Open&bla=12', this method
	   returns the same as the key: 'Open'...
	   The url must be correctly encoded, ampersands must encoded as &amp;
	   I.e. returns 'value' if the key is 'key' in the url 'http://server/?Open&amp;key=value' */
	function getArgumentValue(key){
		var a=this.getArgumentValues();
		if(a.length<1) return '';
		for(i=0;i<a.length;i++){
			if(a[i][0]==key) return a[i][1];
		}
		return '';
	}

	/* Returns all key / value pairs in the query as a two dimensional array */
	function getArgumentValues(){
		var a=new Array();
		var b=this.query.split('&amp;');
		var c='';
		if(b.length<1) return a;
		for(i=0;i<b.length;i++){
			c=b[i].split('=');
			a[i]=new Array(c[0],((c.length==1)?c[0]:c[1]));
		}
		return a;
	}

	/* Returns a String representation of this url */
	function toString(){
		return this.url;
	}
}

var currentVoteId=false;
function vote_showResults(id){
  try{
    currentVoteId=id;
    aGet(getURL("voting_stat?")+"&id="+id,"vote_showResultRecived");
  }catch(e){
    logging("Error vote_showResults:"+e.message);
  }
}

function vote_showAllResults(){
  try{

  }catch(e){
    logging("Error vote_showAllResults:"+e.message);
  }
}

function vote_showResultRecived(content,xmlObject){
  try{
    if(currentVoteId){
      var target=getElement("vote_container");
      target.innerHTML=xmlObject.responseText;
      currentVoteId=false;
    }
  }catch(e){
    logging("Error vote_showResultRecived:"+e.message);
  }
}
function vote_submit(button){
  try{
    var form=button.form;
    var id  =form.voting_id.value;
    var kind=form.voting_kind.value;
    var error="";
    currentVoteId=id;
    query=form_to_string(form);
    aGet(getURL("voting_show?")+query,"vote_showResultRecived");
    return false;
  }catch(e){
    logging("Error vote_submit:"+e.message);
    return false;
  }
}

function vote_show(id){
  try{
    aGet(getURL("voting_show?")+"&id="+id,"vote_showRecived");
    currentVoteId=id;
  }catch(e){
    logging("Error vote_show:"+e.message);
  }
}

function vote_showRecived(content,xmlObject){
  try{
    if(currentVoteId){
      var target=getElement("vote_container");
      target.innerHTML=xmlObject.responseText;
      currentVoteId=false;
    }
  }catch(e){
    logging("Error vote_showRecived:"+e.message);
  }
}

function captchaReload(image){
  try{
    image.src="/captcha?rand="+Math.floor(Math.random()*500);
  }catch(e){
    logging("Error captchaReload:"+e.message);
  }
}

function chat_initialize(){
  try{
    
    setTimeout("chat_timer();",2000);
  }catch(e){
    logging("Error chat_initialize:"+e.message);
  } 
}
function chat_post(){
  try{
    chat_status("Отправка");
    var message=getElement("chat_mess");
    var button=getElement("chat_send");
    aGet(getHost()+"chat_post?"+"message="+message.value,"chat_post_posted");
    message.value="";
  }catch(e){
    logging("Error chat_post:"+e.message);
  } 
}
function chat_post_posted(content,xmlObject){
  try{
    chat_status(xmlObject.responseText);
  }catch(e){
    logging("Error chat_load_posts:"+e.message);
  } 
}
function chat_load_posts(){
  try{
    chat_status("Загрузка собщений");
    aGet(getHost()+"chat_messages?","chat_load_posts_loaded");
  }catch(e){
    logging("Error chat_load_posts:"+e.message);
  } 
}
function chat_load_posts_loaded(content,xmlObject){
  try{
    var chat_messages_div=getElement("chat_messages");
    chat_status("Сообщения загружены");
    chat_messages.innerHTML=xmlObject.responseText;
  }catch(e){
    logging("Error chat_load_posts_loaded:"+e.message);
  } 
}
function chat_load_online(){
  try{
    chat_status("Загрузка пользователей");
    aGet(getHost()+"chat_online?","chat_load_online_loaded");
  }catch(e){
    logging("Error chat_load_online:"+e.message);
  } 
}
function chat_load_online_loaded(content,xmlObject){
  try{
    var online_div=getElement("chat_online");
    online_div.innerHTML=xmlObject.responseText;
    chat_status("");
    chat_load_posts();
  }catch(e){
    logging("Error chat_load_online_loaded:"+e.message);
  } 
}

function chat_status(status){
  try{
    var status_div=getElement("chat_status");
    status_div.innerHTML=status;
  }catch(e){
    logging("Error chat_status:"+e.message);
  } 
}
function chat_timer(){
  try{
    chat_load_online();     
    setTimeout("chat_timer();",2000);
  }catch(e){
    logging("Error chat_timer:"+e.message);
  } 
}
function chat_message_user(object){
  try{
    var username=object.innerHTML;
    var message=getElement("chat_mess");
    message.value=message.value+" "+username+":";
  }catch(e){
    logging("Error chat_timer:"+e.message);
  } 
}

var banners=new Array();
function Banner(){
  /// Функции предпросмотра
  this.previewAsGraph=banner_preview_as_graph;
  this.previewAsText =banner_preview_as_text;
  this.previewAsFlash=banner_preview_as_flash;
  /// Функции отрисовки банера
  this.asGraph=banner_as_graph;
  this.asText =banner_as_text;
  this.asFlash=banner_as_flash;
  return this;
}

function banner_preview_as_graph(){
  try{
     document.write("<div id='banner_container'><a href='"+this.link+"' target='"+(this.blank==1?"_blank":"")+"'><img width='"+this.width+"' height='"+this.height+"' alt='"+this.title+"' src='/"+this.path+"'></a></div>");
  }catch(e){
    logging("Error banner_preview_as_graph:"+e.message);
  }
}

function banner_preview_as_text(){
  try{

  }catch(e){
    logging("Error banner_preview_as_text:"+e.message);
  }
}

function banner_preview_as_flash(){
  try{

  }catch(e){
    logging("Error banner_preview_as_flash:"+e.message);
  }
}
function banner_as_graph(){
  try{
    document.write("<div id='banner_container'><a href='"+this.link+"' onclick='banner_click("+this.id+")' target='"+(this.blank==1?"_blank":"_self")+"'><img width='"+this.width+"' height='"+this.height+"' alt='"+this.title+"' src='/"+this.path+"'></a></div>");
  }catch(e){
    logging("Error banner_as_graph:"+e.message);
  }
}

function banner_as_text(){
  try{

  }catch(e){
    logging("Error banner_as_text:"+e.message);
  }
}

function banner_as_flash(){
  try{

  }catch(e){
    logging("Error banner_as_flash:"+e.message);
  }
}
function banner_click(id){
  try{
    var banner=banners[id];
    new Image().src=banner.click;
  }catch(e){
    logging("Error banner_as_flash:"+e.message);
  }
}

function default_submit(button){
  try{
    var submit=getElement(button.form.name+"_submit");
    button.disabled=true;
    CheckContent(button);
    button.form.submit();
    return false;
  }catch(e){
    logging("Error default_submit:"+e.message);
    return false;
  } 
}

function form_input_to_string(input){
  try{
    var string="";
    switch(input.type){
      case "text"      : {string=input.value;                               break;}
      case "textarea"  : {string=input.value;                               break;}
      case "radio"     : {string=input.checked?input.value:"";              break;}
      case "checkbox"  : {string=input.checked;                             break;}
      case "hidden"    : {string=input.value;                               break;}
      case "select-one": {string=input.options[input.selectedIndex].value;  break;}
    }
    if(string!=""){
      string=input.name+"="+string;
    }
    return string;
  }catch(e){
    logging("Error form_input_to_string:"+e.message);
    return false;
  } 
}

function form_to_string(form){
  try{
    var elements=form.elements;
    var query   ="";
    for(var i=0;i<elements.length;i++){
      var value=form_input_to_string(elements[i]);
      if(value!=""){
        query+="&"+value;
      }
    }
    return query;
  }catch(e){
    logging("Error form_to_string:"+e.message);
  } 
}

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);
this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:
function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{
_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};
deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};
if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);
deconcept.unloadSet=true;}}
if(!document.getElementById&&document.all){
document.getElementById=function(id){return document.all[id];};}
var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

function contact_form_send(button){
  try{
    var form=button.form;
    var query=form_to_string(form);
    aGet(getURL("contact_form?")+query,"contact_form_sent");
    button.disabled=1;
    return false;
  }catch(e){
    logging("Error contact_form_send:"+e.message);
  }
}
function contact_form_sent(content,xml){
  try{
    
    var contact_form_container=getElement("contact_form_container");
    contact_form_container.innerHTML=xml.responseText;
  }catch(e){
    logging("Error contact_form_sent:"+e.message);
  }
}

function avatarInsert(button){
  try{
    button.disabled=true;
    button.form.submit();
    return false;
  }catch(e){
    logging("Error avatarInsert:"+e.message);
  }
}

function avatarDelete(button){
  try{
    var form=button.form;


  
  }catch(e){
    logging("Error avatarInsert:"+e.message);
  }
}

function onDateChange(kind,name,input){
  try{
    var form=input.form;
    var vday  =form.elements[name+"_day"].value;
    var vmonth=form.elements[name+"_month"].options[form.elements[name+"_month"].selectedIndex].value;
    var vyear =form.elements[name+"_year"].value;
    form.elements[name].value=vyear+"-"+vmonth+"-"+vday;
  }catch(e){
    logging("Error onDateDayChange:"+e.message);
  }
}

var deleting_reply=false; 
function reply_delete(object,id){
  try{
    deleting_reply=id;
    aGet(object.href+"?","reply_deleted");
  }catch(e){
    logging("Error reply_delete:"+e.message);
  }
  return false;
}
function reply_deleted(content,xml){
  try{
    if(deleting_reply){
      id                = deleting_reply;
      var reply_title   = getElement("reply_title_"+id);
      var reply_text    = getElement("reply_text_"+id);
      var reply_buttons = getElement("reply_buttons_"+id);
      reply_title.parentNode.removeChild(reply_title);
      reply_text.parentNode.removeChild(reply_text);
      reply_buttons.parentNode.removeChild(reply_buttons);
      deleting_reply=false;
    }else{
      alert("'"+xml.responseText+"'");
    }
  }catch(e){
    logging("Error reply_deleted:"+e.message);
  }
}

var loading_tree_node=false;

function tree_view_onclick(id){
  try{
    if(!loading_tree_node){
      var parent_node=getElement("tree_node_"+id);
      var child_container=getElement("tree_node_childs_"+id);      
      if(!parent_node.loaded){
        child_container.className="tree_view_child_container_loading";
        parent_node.className="in_tree_view_loading";
        aGet(getURL("tree_view?execute=1&parent_id="+id),"tree_view_loaded");
        loading_tree_node=id;
      }else{        
        if(parent_node.className=="in_tree_view_loaded_full_opened"){
            child_container.className="tree_view_child_container_unloaded";
          parent_node.className="in_tree_view_loaded_full_closed";
        }else{
          if(parent_node.className=="in_tree_view_loaded_full_closed"){
            child_container.className="tree_view_child_container_loaded";
            parent_node.className="in_tree_view_loaded_full_opened";
          }
        }
      }
    }
  }catch(e){
    logging("Error tree_view_onclick:"+e.message);  
  }
}

function tree_view_loaded(content,xml){
  try{
    if(loading_tree_node){
      var parent_node=getElement("tree_node_"+loading_tree_node);
      var child_container=getElement("tree_node_childs_"+loading_tree_node);
      ///
      if(xml.responseText!=""){
        child_container.innerHTML=xml.responseText;
        parent_node.className="in_tree_view_loaded_full_opened";
        child_container.className="tree_view_child_container_loaded";
      }else{
        parent_node.className="in_tree_view_loaded_empty";
        child_container.className="tree_view_child_container_unloaded";
      }
      ///
      parent_node.loaded=true;
      loading_tree_node=false;
    }
  }catch(e){
    logging("Error tree_view_loaded:"+e.message);  
  }
}
 
function favorite_insert(instance_id){
  try{
    alert(instance_id);
  }catch(e){
    logging("Error favorite_insert:"+e.message);
  }
}
 
function tbsh_initialization(){
  try{
    for(var i=0;i<getElementsByClass("tab_item").length;i++){
    
    }
  }catch(e){
    Logging("Error tbsh_initialization:"+e.message);
  }
}

function show_tab(object){
  try{
    var parent=object.parentNode;
    var tabs  =parent.childNodes;
    for(var i=0;i<tabs.length;i++ ){      
      if(object.id!=tabs[i].id){
        var content=getElement(tabs[i].id+"_con");
        tabs[i].className = "tab_item";
        if(content)content.style.display="none";    
      }else{
        object.className    = "tab_item_current";
        var content=getElement(object.id+"_con");
        if(content)content.style.display="block";    
      }
    }
    return false;
  }catch(e){
    Logging("Error show_tab:"+e.message);
  }
}
 
function fields_insert(button,container_id){
  try{
    var container=getElement(container_id);
    button.disabled=true;

  }catch(e){
    logging("Error favorite_insert:"+e.message);
  }
}

function fields_inserted(content,xml){
  try{

    button.disabled=false;
  }catch(e){
    logging("Error favorite_insert:"+e.message);
  }
}

var fields_now_loading=false;

function fields_get_values_list(select){
  try{    
    var form=select.form;
    if(!fields_now_loading){
      var field_name_id=select.options[select.selectedIndex].value;
      if(field_name_id!=-1){
        form.elements["field_value_id"].disabled=true;
        aGet(getHost()+"fields_values_list?kind=3&field_name_id="+field_name_id,"fields_recived_values_list");
        fields_now_loading=form;
      }else{
        form.elements["new_field_name"].disabled=false;
      }
    }
  }catch(e){
    logging("Error fields_get_values_list:"+e.message);
  }
}

function fields_recived_values_list(content,xml){
  try{
    if(fields_now_loading){
      var form=fields_now_loading;
      var select=form.elements["field_value_id"];
      form.elements["field_value_id"].disabled=true;
      for(var i=1;i<select.options.length;i++){select.options[i] = null;}/// Удаляем все кроме первой      
      // Записываем новые значения
      xml=xml.responseXML.documentElement;
      for(var i=0;i<xml.getElementsByTagName("field").length;i++){
        var field_id=xml.getElementsByTagName("field")[i].getAttribute("id");
        var field_value=xml.getElementsByTagName("field")[i].getAttribute("value");
        var field_count=xml.getElementsByTagName("field")[i].getAttribute("count");
        select.options[i+1] = new Option(field_value,field_id);
      }
      if(xml.getElementsByTagName("field").length>0){
        form.elements["field_value_id"].disabled=false;
      }
      fields_now_loading=false;
    }
  }catch(e){
    alert("Error fields_get_values_list:"+e.message);
  }
}



function sele_initialization(){
  try{
    for(var i=0;i<getElementsByClass("editable_select").length;i++){
      var select = getElementsByClass("editable_select")[i];
      var parent = select.parentNode;
      var id     = select.id;
      addEvent(select,"mousedown",select_mosusedown);
      
      select.input=create( "input", { id: "guide_"+id,"class":"toolbar_input_select"});
      select.input.select=select;
      select.input.style.display  ="none";
      addEvent(select.input,"blur",select_input_blur);
      parent.appendChild(select.input);
    }  
  }catch(e){
    logging("Error sele_initialization:"+e.message);
  }
}

function select_mosusedown(e){
  try{
    var tg = (window.event) ? e.srcElement : e.target;
    var ev = e?e:window.event;
    if(tg.input){
      var input = tg.input;
      var select= tg;
      var parent= tg.parentNode;
      var width=tg.offsetWidth;
      clickX = (ev.x?ev.x:ev.pageX)-select.offsetLeft;
      clickY = (ev.y?ev.y:ev.pageY)-parent.offsetTop;
      if(select.disabled==true){
        select.disabled=false;
      }else{
        if(width-clickX>20&&clickY<22&&clickY>0){
          select.swapNode(input);
          select.input.value=tg.options[tg.selectedIndex].innerHTML;
          select.input.idval=tg.options[tg.selectedIndex].value;
          select.style.display="none";
          input.style.display="block";
          input.focus();
        }
      }
    }
    return true;
  }catch(e){
    logging("Error select_click:"+e.message);
  }
}

function select_input_blur(e){
  try{
    var tg = (window.event) ? e.srcElement : e.target;
    var ev = e?e:window.event;
    var value=tg.value;
    var input=tg;
    var select=tg.select;
    select.swapNode(input);
    input.style.display="none";
    select.style.display="block";
    select.focus();
    var found=0;
    for(var i=0;i<select.options.length;i++){
      if(select.options[i].innerHTML==value){
        found=true;
      }
    }
    if(!found){
      var newOption= new Option(value,value);
      select.options[select.options.length]=newOption;
      select.selectedIndex=select.options.length-1;
    }
  }catch(e){
    logging("Error select_input_blur:"+e.message);
  }
}


function child_group(select,field,url){
  try{
    var value=select.options[select.selectedIndex].value;
    var name =select.options[select.selectedIndex].innerHTML;
    if(value>0){
      document.location=url+"/group/"+field+"/"+name;
    }
  }catch(e){
    alert("Error child_group"+e.message);
  }
}

 
window.onload=initialization;

function initialization(){
  try{
    menu_initialization();
    drag_initialization();
    tool_initialization();
    anim_initialization();
    foot_initialization();
    adco_initialization();
    navi_initialization();
    guid_initialization();
    toot_initialization();
    wosp_initialization();
    refl_initialization();
    grap_initialization();
    sele_initialization();
  }catch(e){
    logging("Error initialization:"+e.message);
  }
}
