function popup(id, width, height, toolbar ,menubar, status){return pop_up(id, width, height, toolbar,menubar, status);}
function pop_up(id, width, height, toolbar ,menubar, status){
  if(id == "" || id == null) {
    return;
  }       
  if (width == "" || width == null || height == "" || height == null) {
    width = 800;
    height = 600;
  }
  if(toolbar=="") toolbar="no";
  if(menubar=="") menubar="no";
  if(status=="") status="no";
  
  
  wx = (screen.width-width)/2;
  wy = (screen.height-height)/2;
  wnd=window.open(id,"_blank", "width="+width+",height="+height+",status="+status+",resizable=1,scrollbars=1,toolbar="+toolbar+",menubar="+menubar+", left="+wx+",top="+wy);
  return false;
}

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 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);
  }
}

function scrollTop(){
	var ScrollTop = document.body.scrollTop;
	if(ScrollTop == 0){
   if(window.pageYOffset)
     ScrollTop = window.pageYOffset;
   else
     ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	} 
	return ScrollTop;
}

//For debuging
function print_r(x,max,sep,l){ 
  l = l || 0; 
  max = max || 10; 
  sep = sep || ' '; 
  if (l > max) { return "[WARNING: Too much recursion]\n";} 
  var i, r = '', t = typeof x, tab = '';  
  if (x === null) { r += "(null)\n"; 
  }else if (t == 'object'){
    l++; 
    for(i=0;i<l;i++){ 
      tab+= sep;
    }
    if(x&&x.length){
      t='array';
    }
    r+='('+t+") :\n"; 
    for(i in x){ 
      try{ 
        r+=tab+'['+i+'] : '+print_r(x[i],max,sep,(l + 1));
      }catch(e){
        return "[ERROR: "+e+"]\n"; 
      }
    }
  }else{
    if(t =='string'){
      if(x==''){
        x='(empty)';
      }
    }
    r +='('+t+') '+x+"\n";
  }
  return r;
}


/*Browser detection*/
var isIE;var isGecko;var isSafari;var isKonqueror;

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);

function control_access_to_all(object,control){
  try{
    aGet(getURL("access_control?")+"control_id="+control+"&value=toall"+"&execute=1","control_access_processed");
    return false;
  }catch(e){
    logging("Error control_access_to_all:"+e.message);
  }
}
function control_access_click(object,control,role){
  try{
    aGet(getURL("access_control?")+"control_id="+control+"&role_id="+role+"&value="+(object.checked?"1":"0")+"&execute=1","control_access_processed");
  }catch(e){
    logging("Error control_access_click:"+e.message);
  }
}
function control_access_processed(content,xml){
  try{

  }catch(e){
    logging("Error control_access_click:"+e.message);
  }
}

//init variables
var isRichText = false;var rng;var currentRTE;var allRTEs = "";
var imagesPath;
var includesPath;var cssFile;var rteInitilized=false;

function initRTE(imgPath, incPath, css) {
  if(!rteInitilized){
    //set browser vars
    //check to see if designMode mode is available
    if (document.getElementById && (document.designMode)) {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>');
      //document.writeln('<script src="/grape/scripts/editarea.js"></  script>');
    }
        
    //for testing standard textarea, uncomment the following line
    //isRichText = false;
    rteInitilized=true;
  }
}

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 onpaste="alert(\'The text is being pasted\')" name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
  }else{document.writeln('<textarea onpaste="alert(\'The text is being pasted\')" 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;
  }  
  document.getElementById('hdn' + rte).value = html;
  enableDesignMode(rte, html, readOnly);
}

function enableDesignMode(rte, html, readOnly) {
  if(html=="stored_html")html=stored_html[rte];
  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";
  }

  if(isGecko){
    html=html!=""?html:"<br>";
  }
  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 += "  margin-bottom: 5px;\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);
          oRTE.addEventListener("paste", kb_paste, 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.
      stored_html[rte]=html;
      setTimeout("enableDesignMode('" + rte + "', 'stored_html', " + readOnly + ");", 100);
    }
  }
}

function kb_paste(evt){
  try{
  	var o=evt.target;
	  while((o.id+""==""||o.id+""=="undefined")&&o){o=o.parentNode;}
	  if(!o)alert("not found");
	  var rte = o.id;	  
	  var oRTE= document.getElementById(rte);
	  setTimeout("cleanup('" + rte + "');", 1000);
  }catch(e){
    alert("Error in kb_paste:"+e.message);
  }
}


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,inv) {
  //contributed by Bob Hutzel (thanks Bob!)
  var oRTE;
  var nchk = 'chkSrc' + rte;

	if(inv){getElement(nchk).checked=!getElement(nchk).checked;}

  if (document.all) {
    oRTE = frames[rte].document;
  } else {
    oRTE = document.getElementById(rte).contentWindow.document;
  }

  
  if (getElement(nchk).checked) {
    document.getElementById("buttons_" + rte).style.display = "none";
    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("buttons_" + rte).style.display = "block";
    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();
            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"){
      cleanup(rte);
      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 if(command == "image_insert") {
        AddImage(rte);
    }else{
      oRTE.focus();
      oRTE.document.execCommand(command, false, option);
      oRTE.focus();
    }
  } catch (e) {
     alert("Error enableDesignMode:"+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 formatSelect(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;
      case 's': cmd = "strike"; 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
}


function cleanup(rte){
  try{
    var RTEContent = document.all?document.frames[rte].document.body:getElement(rte).contentDocument.body;
    cleanup_tree(RTEContent);
  }catch(e){
    alert("Error in cleanup : "+e.message);
  }
}

good_tag = new Array("font","a","table","thead","tbody","tr","td","th","ul","ol","li","p","br","em","h1","h2","h3","h4","h5","h6","div","span","u","strong","b","s","i","img","#text");
good_atr = new Array("id","href","valign","align","class","src","alt","title","rowspan","colspan","width","className");
bad_class= new Array("MsoNormal");

function cleanup_tree(o){
  try{
    var i=0;
    while(i<o.childNodes.length){
      var child=o.childNodes[i];
      //alert(child.nodeName);
      if(good_tag.indexOf(new String(child.nodeName).toLowerCase())==-1){
        if(!document.all){
          o.removeChild(child);
        }else{
          //alert(child.nodeName+":"+child.className+":"+child.tagName);
          child.outerHTML=child.innerHTML;
        }
      }else{
        var a=0;
        if(child.attributes){
          while(a<child.attributes.length){
            var attribute = child.attributes[a];
            var name      = new String(attribute.name).toLowerCase();
            var value     = new String(attribute.value).toLowerCase();
            //alert(name+":"+a+":"+child.attributes.length);
            if(good_atr.indexOf(name)==-1){
            	if(!child.removeAttribute(name)){a++;}
            }else{
	            if(name=="class"&&bad_class.indexOf(value)==-1){
	              //alert("ClassName - "+value);
	            	if(!child.removeAttribute("class")&&!child.removeAttribute("className")){a++;}
	            }else{
		            a++;
	  	        }
	    	    }
          }
        }
        if(child.childNodes.length!=0){cleanup_tree(child);}
        i++;
      }
    }
  }catch(e){
    alert("Error in cleanup_tree : "+e.message);
  }
}

/*  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){
          if(submenu=menu_get_sub(all[i])){
          	all[i].onmouseover=menu_mousein;
          	submenu.menu_owner=all[i];
          }
        }
        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{
    object=object.parentNode;
    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){
          submenutoclose=currentopened;
          menu_close_sub();
        }
        if(submenu.childNodes.length){
          submenu.style.display="block";
        }
        if(!submenu.menu_owner.oldClass){
          submenu.menu_owner.oldClass=submenu.menu_owner.className;
          submenu.menu_owner.className=submenu.menu_owner.className+"_active";
        }
        currentopened=submenu;
        submenutoclose=null;
      }
    }
    submenutoclose=null;
    return false;
    
  }catch(e){
    logging("Error menu_mousein:"+e.message);
  }
}

function menu_mousein_sub(event){
  try{
  }catch(e){
    logging("Error menu_mousein_sub:"+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(){
  try{
    if(submenutoclose){
      submenutoclose.style.display="none";
      if(submenutoclose.menu_owner.oldClass){
        submenutoclose.menu_owner.className=submenutoclose.menu_owner.oldClass;
        submenutoclose.menu_owner.oldClass=false;
      }
    }
  }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);
    submenutoclose=submenu;
    menu_close_sub();
  }catch(e){
    logging("Error menu_close_force:"+e.message);
  }
}
/*  TOOLBAR MENU FUNCTIONS */

/*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,entity,id) {
  try{
    window.insert_image_into=rte;
    wnd=pop_up('/object.images/'+entity+'/'+id,'750','600');
    return false;
  }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()+"object.image_delete/"+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);
  }
}

function image_deleted(){
  try{

  }catch(e){
    alert("Error in image_deleted:"+e.message);
  }
}


function insert_element(kind,path,id){
  try{
    var rteID=window.opener.insert_image_into;
    var oRTE=window.opener.document.getElementById(rteID).contentWindow;
    switch(kind){
      case "image"     : {oRTE.document.execCommand('InsertImage', false, "/"+path);break;}
      case "link"      : {pasteHtml(oRTE,"{file kind=\"link\" id=\""+id+"\" name=\""+path+"\" }");break;}
      case "download"  : {var desc=prompt("Enter file description:", "");pasteHtml(oRTE,"{file kind=\"download\" id=\""+id+"\" name=\""+desc+"\" }");break;}
      case "video"     : {pasteHtml(oRTE,"{file kind=\"video\" id=\""+id+"\" name=\""+path+"\" }");break;}
      case "flash"     : {pasteHtml(oRTE,"{file kind=\"flash\" id=\""+id+"\" name=\""+path+"\" }");break;}
      case "icon"      : {pasteHtml(oRTE,"{file kind=\"icon\" id=\""+id+"\" name=\""+path+"\" }");break;}
    }
    return false;
  }catch(e){
    alert("Error insert_element:"+e.message);
  }
}

/*ORDERING*/
function get_ordering(form){
  text="";
  try{
    order=1;
    var DragContainer=getElement("DragContainer");
    var OrderList    =getElement("order_list");
    var button       =getElement(form.name+"_button");
    for(i=0;i<DragContainer.childNodes.length;i++){
       text=text+DragContainer.childNodes[i].id+";";
    }     
    OrderList.value=text;
    default_submit(form);
    return true;
  }catch(e){
    logging("Error get_ordering:"+e.message);
    return false;
  }   
}


function edit_initialization(){
  try{
    
  }catch(e){
    logging("Error edit_initialization:"+e.message);
  } 
}

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++;
      }
    }
    return false;
  }catch(e){
    logging("Error CheckContent:"+e.message);
    return false;
  } 
}

function pasteHtml(RTE,code){
  try{
    RTE.focus();
    if(isGecko){
      RTE.document.execCommand('inserthtml', false, code);
    }else{
      RTE.document.execCommand('paste', false, code);
    }
    oRTE.focus();
  }catch(e){
    logging("Error pasteHtml:"+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-document.body.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+"px";
    dragHelper.style.left = mousePos.x - mouseOffset.x+"px";
    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(((parseInt(getAttribute('startLeft')))                              <xPos) &&
          ((parseInt(getAttribute('startTop')))                                <yPos) &&
          ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
          ((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){
            //our target is inside of our container so save the container into
            //the activeCont variable and then exit the loop since we no longer
            //need to check the rest of the containers
            activeCont = dragConts[i];
            // 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]                              &&
            ((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
            ((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){
                    beforeNode = activeCont.childNodes[i];
          }
        }
      }

      // the item being dragged belongs before another item
      if(beforeNode){
        if(beforeNode!=curTarget.nextSibling){
                activeCont.insertBefore(curTarget, beforeNode);
        }

      // the item being dragged belongs at the end of the current container
      } else {
        if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
          activeCont.appendChild(curTarget);
        }
      }

      // 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){
  switchSelection();
  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(){
  switchSelection();
  iMouseDown = true;if(lastTarget){return false;}
}

function drag_initialization(){
  // Create our helper object that will show the item while dragging  
  if(document.getElementById('DragContainer')){
    addEvent(document, "mousemove", mouseMove);
    addEvent(document, "mousedown", mouseDown);
    addEvent(document, "mouseup", 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+'=');
}

  
/*  
        Animator.js 1.1.9
        
        This library is released under the BSD license:

        Copyright (c) 2006, Bernard Sumption. All rights reserved.
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        Redistributions of source code must retain the above copyright notice, this
        list of conditions and the following disclaimer. Redistributions in binary
        form must reproduce the above copyright notice, this list of conditions and
        the following disclaimer in the documentation and/or other materials
        provided with the distribution. Neither the name BernieCode nor
        the names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission. 
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
        ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
        ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
        LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
        OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
        DAMAGE.

*/


// Applies a sequence of numbers between 0 and 1 to a number of subjects
// construct - see setOptions for parameters
function Animator(options) {
        this.setOptions(options);
        var _this = this;
        this.timerDelegate = function(){_this.onTimerEvent()};
        this.subjects = [];
        this.target = 0;
        this.state = 0;
        this.lastTime = null;
};
Animator.prototype = {
        // apply defaults
        setOptions: function(options) {
                this.options = Animator.applyDefaults({
                        interval: 20,  // time between animation frames
                        duration: 400, // length of animation
                        onComplete: function(){},
                        onStep: function(){},
                        transition: Animator.tx.easeInOut
                }, options);
        },
        // animate from the current state to provided value
        seekTo: function(to) {
                this.seekFromTo(this.state, to);
        },
        // animate from the current state to provided value
        seekFromTo: function(from, to) {
                this.target = Math.max(0, Math.min(1, to));
                this.state = Math.max(0, Math.min(1, from));
                this.lastTime = new Date().getTime();
                if (!this.intervalId) {
                        this.intervalId = window.setInterval(this.timerDelegate, this.options.interval);
                }
        },
        // animate from the current state to provided value
        jumpTo: function(to) {
                this.target = this.state = Math.max(0, Math.min(1, to));
                this.propagate();
        },
        // seek to the opposite of the current target
        toggle: function() {
                this.seekTo(1 - this.target);
        },
        // add a function or an object with a method setState(state) that will be called with a number
        // between 0 and 1 on each frame of the animation
        addSubject: function(subject) {
                this.subjects[this.subjects.length] = subject;
                return this;
        },
        // remove all subjects
        clearSubjects: function() {
                this.subjects = [];
        },
        // forward the current state to the animation subjects
        propagate: function() {
                var value = this.options.transition(this.state);
                for (var i=0; i<this.subjects.length; i++) {
                        if (this.subjects[i].setState) {
                                this.subjects[i].setState(value);
                        } else {
                                this.subjects[i](value);
                        }
                }
        },
        // called once per frame to update the current state
        onTimerEvent: function() {
                var now = new Date().getTime();
                var timePassed = now - this.lastTime;
                this.lastTime = now;
                var movement = (timePassed / this.options.duration) * (this.state <this.target ? 1 : -1);
                if (Math.abs(movement) >= Math.abs(this.state - this.target)) {
                        this.state = this.target;
                } else {
                        this.state += movement;
                }
                
                try {
                        this.propagate();
                } finally {
                        this.options.onStep.call(this);
                        if (this.target == this.state) {
                                window.clearInterval(this.intervalId);
                                this.intervalId = null;
                                this.options.onComplete.call(this);
                        }
                }
        },
        // shortcuts
        play: function() {this.seekFromTo(0, 1)},
        reverse: function() {this.seekFromTo(1, 0)},
        // return a string describing this Animator, for debugging
        inspect: function() {
                var str = "#<Animator:\n";
                for (var i=0; i<this.subjects.length; i++) {
                        str += this.subjects[i].inspect();
                }
                str += ">";
                return str;
        }
}
// merge the properties of two objects
Animator.applyDefaults = function(defaults, prefs) {
        prefs = prefs || {};
        var prop, result = {};
        for (prop in defaults) result[prop] = prefs[prop] !== undefined ? prefs[prop] : defaults[prop];
        return result;
}
// make an array from any object
Animator.makeArray = function(o) {
        if (o == null) return [];
        if (!o.length) return [o];
        var result = [];
        for (var i=0; i<o.length; i++) result[i] = o[i];
        return result;
}
// convert a dash-delimited-property to a camelCaseProperty (c/o Prototype, thanks Sam!)
Animator.camelize = function(string) {
        var oStringList = string.split('-');
        if (oStringList.length == 1) return oStringList[0];
        
        var camelizedString = string.indexOf('-') == 0
                ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
                : oStringList[0];
        
        for (var i = 1, len = oStringList.length; i <len; i++) {
                var s = oStringList[i];
                camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
        }
        return camelizedString;
}
// syntactic sugar for creating CSSStyleSubjects
Animator.apply = function(el, style, options) {
        if (style instanceof Array) {
                return new Animator(options).addSubject(new CSSStyleSubject(el, style[0], style[1]));
        }
        return new Animator(options).addSubject(new CSSStyleSubject(el, style));
}
// make a transition function that gradually accelerates. pass a=1 for smooth
// gravitational acceleration, higher values for an exaggerated effect
Animator.makeEaseIn = function(a) {
        return function(state) {
                return Math.pow(state, a*2); 
        }
}
// as makeEaseIn but for deceleration
Animator.makeEaseOut = function(a) {
        return function(state) {
                return 1 - Math.pow(1 - state, a*2); 
        }
}
// make a transition function that, like an object with momentum being attracted to a point,
// goes past the target then returns
Animator.makeElastic = function(bounces) {
        return function(state) {
                state = Animator.tx.easeInOut(state);
                return ((1-Math.cos(state * Math.PI * bounces)) * (1 - state)) + state; 
        }
}
// make an Attack Decay Sustain Release envelope that starts and finishes on the same level
// 
Animator.makeADSR = function(attackEnd, decayEnd, sustainEnd, sustainLevel) {
        if (sustainLevel == null) sustainLevel = 0.5;
        return function(state) {
                if (state <attackEnd) {
                        return state / attackEnd;
                }
                if (state <decayEnd) {
                        return 1 - ((state - attackEnd) / (decayEnd - attackEnd) * (1 - sustainLevel));
                }
                if (state <sustainEnd) {
                        return sustainLevel;
                }
                return sustainLevel * (1 - ((state - sustainEnd) / (1 - sustainEnd)));
        }
}
// make a transition function that, like a ball falling to floor, reaches the target and/
// bounces back again
Animator.makeBounce = function(bounces) {
        var fn = Animator.makeElastic(bounces);
        return function(state) {
                state = fn(state); 
                return state <= 1 ? state : 2-state;
        }
}
 
// pre-made transition functions to use with the 'transition' option
Animator.tx = {
        easeInOut: function(pos){
                return ((-Math.cos(pos*Math.PI)/2) + 0.5);
        },
        linear: function(x) {
                return x;
        },
        easeIn: Animator.makeEaseIn(1.5),
        easeOut: Animator.makeEaseOut(1.5),
        strongEaseIn: Animator.makeEaseIn(2.5),
        strongEaseOut: Animator.makeEaseOut(2.5),
        elastic: Animator.makeElastic(1),
        veryElastic: Animator.makeElastic(3),
        bouncy: Animator.makeBounce(1),
        veryBouncy: Animator.makeBounce(3)
}

// animates a pixel-based style property between two integer values
function NumericalStyleSubject(els, property, from, to, units) {
        this.els = Animator.makeArray(els);
        if (property == 'opacity' && window.ActiveXObject) {
                this.property = 'filter';
        } else {
                this.property = Animator.camelize(property);
        }
        this.from = parseFloat(from);
        this.to = parseFloat(to);
        this.units = units != null ? units : 'px';
}
NumericalStyleSubject.prototype = {
        setState: function(state) {
                var style = this.getStyle(state);
                var visibility = (this.property == 'opacity' && state == 0) ? 'hidden' : '';
                var j=0;
                for (var i=0; i<this.els.length; i++) {
                        try {
                                this.els[i].style[this.property] = style;
                        } catch (e) {
                                // ignore fontWeight - intermediate numerical values cause exeptions in firefox
                                if (this.property != 'fontWeight') throw e;
                        }
                        if (j++ > 20) return;
                }
        },
        getStyle: function(state) {
                state = this.from + ((this.to - this.from) * state);
                if (this.property == 'filter') return "alpha(opacity=" + Math.round(state*100) + ")";
                if (this.property == 'opacity') return state;
                return Math.round(state) + this.units;
        },
        inspect: function() {
                return "\t" + this.property + "(" + this.from + this.units + " to " + this.to + this.units + ")\n";
        }
}

// animates a colour based style property between two hex values
function ColorStyleSubject(els, property, from, to) {
        this.els = Animator.makeArray(els);
        this.property = Animator.camelize(property);
        this.to = this.expandColor(to);
        this.from = this.expandColor(from);
        this.origFrom = from;
        this.origTo = to;
}

ColorStyleSubject.prototype = {
        // parse "#FFFF00" to [256, 256, 0]
        expandColor: function(color) {
                var hexColor, red, green, blue;
                hexColor = ColorStyleSubject.parseColor(color);
                if (hexColor) {
                        red = parseInt(hexColor.slice(1, 3), 16);
                        green = parseInt(hexColor.slice(3, 5), 16);
                        blue = parseInt(hexColor.slice(5, 7), 16);
                        return [red,green,blue]
                }
                if (window.DEBUG) {
                        alert("Invalid colour: '" + color + "'");
                }
        },
        getValueForState: function(color, state) {
                return Math.round(this.from[color] + ((this.to[color] - this.from[color]) * state));
        },
        setState: function(state) {
                var color = '#'
                                + ColorStyleSubject.toColorPart(this.getValueForState(0, state))
                                + ColorStyleSubject.toColorPart(this.getValueForState(1, state))
                                + ColorStyleSubject.toColorPart(this.getValueForState(2, state));
                for (var i=0; i<this.els.length; i++) {
                        this.els[i].style[this.property] = color;
                }
        },
        inspect: function() {
                return "\t" + this.property + "(" + this.origFrom + " to " + this.origTo + ")\n";
        }
}

// return a properly formatted 6-digit hex colour spec, or false
ColorStyleSubject.parseColor = function(string) {
        var color = '#', match;
        if(match = ColorStyleSubject.parseColor.rgbRe.exec(string)) {
                var part;
                for (var i=1; i<=3; i++) {
                        part = Math.max(0, Math.min(255, parseInt(match[i])));
                        color += ColorStyleSubject.toColorPart(part);
                }
                return color;
        }
        if (match = ColorStyleSubject.parseColor.hexRe.exec(string)) {
                if(match[1].length == 3) {
                        for (var i=0; i<3; i++) {
                                color += match[1].charAt(i) + match[1].charAt(i);
                        }
                        return color;
                }
                return '#' + match[1];
        }
        return false;
}
// convert a number to a 2 digit hex string
ColorStyleSubject.toColorPart = function(number) {
        if (number > 255) number = 255;
        var digits = number.toString(16);
        if (number <16) return '0' + digits;
        return digits;
}
ColorStyleSubject.parseColor.rgbRe = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
ColorStyleSubject.parseColor.hexRe = /^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

// Animates discrete styles, i.e. ones that do not scale but have discrete values
// that can't be interpolated
function DiscreteStyleSubject(els, property, from, to, threshold) {
        this.els = Animator.makeArray(els);
        this.property = Animator.camelize(property);
        this.from = from;
        this.to = to;
        this.threshold = threshold || 0.5;
}

DiscreteStyleSubject.prototype = {
        setState: function(state) {
                var j=0;
                for (var i=0; i<this.els.length; i++) {
                        this.els[i].style[this.property] = state <= this.threshold ? this.from : this.to; 
                }
        },
        inspect: function() {
                return "\t" + this.property + "(" + this.from + " to " + this.to + " @ " + this.threshold + ")\n";
        }
}

// animates between two styles defined using CSS.
// if style1 and style2 are present, animate between them, if only style1
// is present, animate between the element's current style and style1
function CSSStyleSubject(els, style1, style2) {
        els = Animator.makeArray(els);
        this.subjects = [];
        if (els.length == 0) return;
        var prop, toStyle, fromStyle;
        if (style2) {
                fromStyle = this.parseStyle(style1, els[0]);
                toStyle = this.parseStyle(style2, els[0]);
        } else {
                toStyle = this.parseStyle(style1, els[0]);
                fromStyle = {};
                for (prop in toStyle) {
                        fromStyle[prop] = CSSStyleSubject.getStyle(els[0], prop);
                }
        }
        // remove unchanging properties
        var prop;
        for (prop in fromStyle) {
                if (fromStyle[prop] == toStyle[prop]) {
                        delete fromStyle[prop];
                        delete toStyle[prop];
                }
        }
        // discover the type (numerical or colour) of each style
        var prop, units, match, type, from, to;
        for (prop in fromStyle) {
                var fromProp = String(fromStyle[prop]);
                var toProp = String(toStyle[prop]);
                if (toStyle[prop] == null) {
                        if (window.DEBUG) alert("No to style provided for '" + prop + '"');
                        continue;
                }
                
                if (from = ColorStyleSubject.parseColor(fromProp)) {
                        to = ColorStyleSubject.parseColor(toProp);
                        type = ColorStyleSubject;
                } else if (fromProp.match(CSSStyleSubject.numericalRe)
                                && toProp.match(CSSStyleSubject.numericalRe)) {
                        from = parseFloat(fromProp);
                        to = parseFloat(toProp);
                        type = NumericalStyleSubject;
                        match = CSSStyleSubject.numericalRe.exec(fromProp);
                        var reResult = CSSStyleSubject.numericalRe.exec(toProp);
                        if (match[1] != null) {
                                units = match[1];
                        } else if (reResult[1] != null) {
                                units = reResult[1];
                        } else {
                                units = reResult;
                        }
                } else if (fromProp.match(CSSStyleSubject.discreteRe)
                                && toProp.match(CSSStyleSubject.discreteRe)) {
                        from = fromProp;
                        to = toProp;
                        type = DiscreteStyleSubject;
                        units = 0;   // hack - how to get an animator option down to here
                } else {
                        if (window.DEBUG) {
                                alert("Unrecognised format for value of "
                                        + prop + ": '" + fromStyle[prop] + "'");
                        }
                        continue;
                }
                this.subjects[this.subjects.length] = new type(els, prop, from, to, units);
        }
}

CSSStyleSubject.prototype = {
        // parses "width: 400px; color: #FFBB2E" to {width: "400px", color: "#FFBB2E"}
        parseStyle: function(style, el) {
                var rtn = {};
                // if style is a rule set
                if (style.indexOf(":") != -1) {
                        var styles = style.split(";");
                        for (var i=0; i<styles.length; i++) {
                                var parts = CSSStyleSubject.ruleRe.exec(styles[i]);
                                if (parts) {
                                        rtn[parts[1]] = parts[2];
                                }
                        }
                }
                // else assume style is a class name
                else {
                        var prop, value, oldClass;
                        oldClass = el.className;
                        el.className = style;
                        for (var i=0; i<CSSStyleSubject.cssProperties.length; i++) {
                                prop = CSSStyleSubject.cssProperties[i];
                                value = CSSStyleSubject.getStyle(el, prop);
                                if (value != null) {
                                        rtn[prop] = value;
                                }
                        }
                        el.className = oldClass;
                }
                return rtn;
                
        },
        setState: function(state) {
                for (var i=0; i<this.subjects.length; i++) {
                        this.subjects[i].setState(state);
                }
        },
        inspect: function() {
                var str = "";
                for (var i=0; i<this.subjects.length; i++) {
                        str += this.subjects[i].inspect();
                }
                return str;
        }
}
// get the current value of a css property, 
CSSStyleSubject.getStyle = function(el, property){
        var style;
        if(document.defaultView && document.defaultView.getComputedStyle){
                style = document.defaultView.getComputedStyle(el, "").getPropertyValue(property);
                if (style) {
                        return style;
                }
        }
        property = Animator.camelize(property);
        if(el.currentStyle){
                style = el.currentStyle[property];
        }
        return style || el.style[property]
}


CSSStyleSubject.ruleRe = /^\s*([a-zA-Z\-]+)\s*:\s*(\S(.+\S)?)\s*$/;
CSSStyleSubject.numericalRe = /^-?\d+(?:\.\d+)?(%|[a-zA-Z]{2})?$/;
CSSStyleSubject.discreteRe = /^\w+$/;

// required because the style object of elements isn't enumerable in Safari
/*
CSSStyleSubject.cssProperties = ['background-color','border','border-color','border-spacing',
'border-style','border-top','border-right','border-bottom','border-left','border-top-color',
'border-right-color','border-bottom-color','border-left-color','border-top-width','border-right-width',
'border-bottom-width','border-left-width','border-width','bottom','color','font-size','font-size-adjust',
'font-stretch','font-style','height','left','letter-spacing','line-height','margin','margin-top',
'margin-right','margin-bottom','margin-left','marker-offset','max-height','max-width','min-height',
'min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding',
'padding-top','padding-right','padding-bottom','padding-left','quotes','right','size','text-indent',
'top','width','word-spacing','z-index','opacity','outline-offset'];*/


CSSStyleSubject.cssProperties = ['azimuth','background','background-attachment','background-color','background-image','background-position','background-repeat','border-collapse','border-color','border-spacing','border-style','border-top','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','border-top-width','border-right-width','border-bottom-width','border-left-width','border-width','bottom','clear','clip','color','content','cursor','direction','display','elevation','empty-cells','css-float','font','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','height','left','letter-spacing','line-height','list-style','list-style-image','list-style-position','list-style-type','margin','margin-top','margin-right','margin-bottom','margin-left','max-height','max-width','min-height','min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding','padding-top','padding-right','padding-bottom','padding-left','pause','position','right','size','table-layout','text-align','text-decoration','text-indent','text-shadow','text-transform','top','vertical-align','visibility','white-space','width','word-spacing','z-index','opacity','outline-offset','overflow-x','overflow-y'];


// chains several Animator objects together
function AnimatorChain(animators, options) {
        this.animators = animators;
        this.setOptions(options);
        for (var i=0; i<this.animators.length; i++) {
                this.listenTo(this.animators[i]);
        }
        this.forwards = false;
        this.current = 0;
}

AnimatorChain.prototype = {
        // apply defaults
        setOptions: function(options) {
                this.options = Animator.applyDefaults({
                        // by default, each call to AnimatorChain.play() calls jumpTo(0) of each animator
                        // before playing, which can cause flickering if you have multiple animators all
                        // targeting the same element. Set this to false to avoid this.
                        resetOnPlay: true
                }, options);
        },
        // play each animator in turn
        play: function() {
                this.forwards = true;
                this.current = -1;
                if (this.options.resetOnPlay) {
                        for (var i=0; i<this.animators.length; i++) {
                                this.animators[i].jumpTo(0);
                        }
                }
                this.advance();
        },
        // play all animators backwards
        reverse: function() {
                this.forwards = false;
                this.current = this.animators.length;
                if (this.options.resetOnPlay) {
                        for (var i=0; i<this.animators.length; i++) {
                                this.animators[i].jumpTo(1);
                        }
                }
                this.advance();
        },
        // if we have just play()'d, then call reverse(), and vice versa
        toggle: function() {
                if (this.forwards) {
                        this.seekTo(0);
                } else {
                        this.seekTo(1);
                }
        },
        // internal: install an event listener on an animator's onComplete option
        // to trigger the next animator
        listenTo: function(animator) {
                var oldOnComplete = animator.options.onComplete;
                var _this = this;
                animator.options.onComplete = function() {
                        if (oldOnComplete) oldOnComplete.call(animator);
                        _this.advance();
                }
        },
        // play the next animator
        advance: function() {
                if (this.forwards) {
                        if (this.animators[this.current + 1] == null) return;
                        this.current++;
                        this.animators[this.current].play();
                } else {
                        if (this.animators[this.current - 1] == null) return;
                        this.current--;
                        this.animators[this.current].reverse();
                }
        },
        // this function is provided for drop-in compatibility with Animator objects,
        // but only accepts 0 and 1 as target values
        seekTo: function(target) {
                if (target <= 0) {
                        this.forwards = false;
                        this.animators[this.current].seekTo(0);
                } else {
                        this.forwards = true;
                        this.animators[this.current].seekTo(1);
                }
        }
}

// an Accordion is a class that creates and controls a number of Animators. An array of elements is passed in,
// and for each element an Animator and a activator button is created. When an Animator's activator button is
// clicked, the Animator and all before it seek to 0, and all Animators after it seek to 1. This can be used to
// create the classic Accordion effect, hence the name.
// see setOptions for arguments
function Accordion(options) {
        this.setOptions(options);
        var selected = this.options.initialSection, current;
        if (this.options.rememberance) {
                current = document.location.hash.substring(1);
        }
        this.rememberanceTexts = [];
        this.ans = [];
        var _this = this;
        for (var i=0; i<this.options.sections.length; i++) {
                var el = this.options.sections[i];
                var an = new Animator(this.options.animatorOptions);
                var from = this.options.from + (this.options.shift * i);
                var to = this.options.to + (this.options.shift * i);
                an.addSubject(new NumericalStyleSubject(el, this.options.property, from, to, this.options.units));
                an.jumpTo(0);
                var activator = this.options.getActivator(el);
                activator.index = i;
                activator.onclick = function(){_this.show(this.index)};
                this.ans[this.ans.length] = an;
                this.rememberanceTexts[i] = activator.innerHTML.replace(/\s/g, "");
                if (this.rememberanceTexts[i] === current) {
                        selected = i;
                }
        }
        this.show(selected);
}

Accordion.prototype = {
        // apply defaults
        setOptions: function(options) {
                this.options = Object.extend({
                        // REQUIRED: an array of elements to use as the accordion sections
                        sections: null,
                        // a function that locates an activator button element given a section element.
                        // by default it takes a button id from the section's "activator" attibute
                        getActivator: function(el) {return document.getElementById(el.getAttribute("activator"))},
                        // shifts each animator's range, for example with options {from:0,to:100,shift:20}
                        // the animators' ranges will be 0-100, 20-120, 40-140 etc.
                        shift: 0,
                        // the first page to show
                        initialSection: 0,
                        // if set to true, document.location.hash will be used to preserve the open section across page reloads 
                        rememberance: true,
                        // constructor arguments to the Animator objects
                        animatorOptions: {}
                }, options || {});
        },
        show: function(section) {
                for (var i=0; i<this.ans.length; i++) {
                        this.ans[i].seekTo(i > section ? 1 : 0);
                }
                if (this.options.rememberance) {
                        document.location.hash = this.rememberanceTexts[section];
                }
        }
}

   
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){
    alert("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){
    alert("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||req.status == 302||req.status == 301){
        //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 aLink(url,inMessage,id){
  try{
    aGet(url,"aLinkExecuted");
    var container=getElement(id);
    container.innerHTML=inMessage;
  }catch(e){
    alert(e.message+'\n in aLink');
  }
}

function aSLink(url){
  try{
    aGet(url,"aLinkExecuted");
  }catch(e){
    alert(e.message+'\n in aSLink');
  }
}

function aLinkExecuted(content,xml){
  try{

  }catch(e){
    alert(e.message+'\n in aLinkExecuted');
  }
}
   
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';
      footerElement.style.visibility="visible";
      //}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);
  }
}

function logging(text){
  try{
    var logg=false;
    if(logg=document.getElementById('logging')){
    }else{
      logg=create("div",{id:"logging","class":"logging"});
      logg.innerText="Logiing place:";
      document.body.appendChild(logg);
    }
    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.indexOf('?')>0){
      base=base.substring(0,base.indexOf('?'));
    }
    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));
  var port=url.getPort()==-1?'':url.getPort();
  return "http://"+url.getHost()+port+"/";
}
function setOpacity(object,alpha){setTransparent(object,alpha);}

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) {
  try{
    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");
    }
  }catch(e){
    logging("Error document.addEvent:"+e.message);
  }
}

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);
}

function classSwitch(object,id,fromClass,toClass){
  try{
	  var element=getElement(id);
	  if(element){
		  element.className=element.className==fromClass?toClass:fromClass;
		  setFooter();
		}
  }catch(e){
    alert("Error classSwitch:"+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;
      switchSelection();
      dragedTooltip.offsetX=event.offsetX;
      dragedTooltip.offsetY=event.offsetY;
      zordering(tooltips,dragedTooltip.id);
      dragedTooltip.zIndex=dragedTooltip.div.style.zIndex;
      switchSelection();
    }  
  }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;
      switchSelection();
    }  
  }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);
  }
}
  
/* 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);
  }
}

vote_button_id=false;
vote_button_entity=false;
function vote_button(object,entity,id){
  try{
    var query=getHost()+"voting.voting_button?id="+id+"&entity="+entity+"&execute=1";
    vote_button_id=id;
    vote_button_entity=entity;
    aGet(query,"vote_button_recived");
  }catch(e){
    logging("Error vote_button:"+e.message);
  }
}
function vote_button_recived(content,xml){
  try{
    if(vote_button_id&&vote_button_entity){
      var button=getElement(vote_button_entity+"_"+vote_button_id+"_go");
      var rate=getElement(vote_button_entity+"_"+vote_button_id+"_rate");
      rate.innerHTML=xml.responseText;
      button.style.display="none";
      vote_button_id=false;
      vote_button_entity=false;
    }
  }catch(e){
    logging("Error vote_button_recived:"+e.message);
  }
}


function captchaReload(image){
  try{
    image.src="/captcha.captcha?rand="+Math.floor(Math.random()*500);
  }catch(e){
    logging("Error captchaReload:"+e.message);
  }
}

if(typeof(banners) == 'undefined'){
  banners=new Array();
}
function Banner(){
  /// Функции предпросмотра
  this.previewAsGraph=banner_preview_as_graph;
  this.previewAsText =banner_preview_as_text;
  this.previewAsFlash=banner_preview_as_flash;
  this.previewAsGraphText=banner_preview_as_graph_text;
  
  /// Функции отрисовки банера
  this.asGraph=banner_as_graph;
  this.asText =banner_as_text;
  this.asFlash=banner_as_flash;
  this.asGraphText=banner_as_graph_text;
  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){
    alert("Error banner_preview_as_graph:"+e.message);
  }
}


function banner_preview_as_graph_text(){
  try{
     document.write(
     "<div class='banner_container'>"+
       "<a  class=\"banner_image\"  href='"+this.link+"' onclick='return banner_click("+this.id+")'  target='"+(this.blank==1?"_blank":"")+"'>"+
          "<img width='"+this.width+"' height='"+this.height+"' alt='"+this.title+"' align=\"left\" src='"+this.path+"'>"+
        "</a>"+
        "<a class=\"banner_text\" onclick='return banner_click("+this.id+")' href='"+this.link+"' target='"+(this.blank==1?"_blank":"")+"'>"+this.text+"</a>"+
     "</div>");
  }catch(e){
    alert("Error banner_preview_as_graph_text:"+e.message);
  }
}

function banner_preview_as_text(){
  try{

  }catch(e){
    alert("Error banner_preview_as_text:"+e.message);
  }
}

function banner_preview_as_flash(){
  try{

  }catch(e){
    alert("Error banner_preview_as_flash:"+e.message);
  }
}
function banner_as_graph(){
  try{
    document.write(
      "<div class='banner_container'>"+
        "<a href='"+this.link+"' onclick='return 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){
    alert("Error banner_as_graph:"+e.message);
  }
}

function banner_as_graph_text(){
  try{
     document.write(
     "<div class='banner_container'>"+
       "<a  class=\"banner_image\"  href='"+this.link+"' onclick='return banner_click("+this.id+")'  target='"+(this.blank==1?"_blank":"")+"'>"+
          "<img width='"+this.width+"' height='"+this.height+"' alt='"+this.title+"' align=\"left\" src='"+this.path+"'>"+
        "</a>"+
        "<a class=\"banner_text\" onclick='return banner_click("+this.id+")' href='"+this.link+"' target='"+(this.blank==1?"_blank":"")+"'>"+this.text+"</a>"+
     "</div>");
  }catch(e){
    alert("Error banner_as_graph_text:"+e.message);
  }
}

function banner_as_text(){
  try{
     document.write(
     "<div class='banner_container'>"+
      "<span id='banner_title'>"+this.title+"<span><br>"+
        "<a class=\"banner_text\" onclick='return banner_click("+this.id+")' href='"+this.link+"' target='"+(this.blank==1?"_blank":"")+"'>"+this.text+"</a>"+
     "</div>");
  }catch(e){
    alert("Error banner_as_text:"+e.message);
  }
}

function banner_as_flash(){
  try{

  }catch(e){
    alert("Error banner_as_flash:"+e.message);
  }
}
function banner_click(id){
  try{
    var banner=banners[id];
    new Image().src=banner.click;
    return true;
  }catch(e){
    alert("Error banner_as_flash:"+e.message);
  }
}

function default_submit(form,input_name){
  try{
    if(form.tagName=="FORM"){
    	if(typeof(form.getAttribute("name"))=="object"){name=form.id;}else{name=form.getAttribute("name");}
	    var button =getElement(name+"_button");
  	  var submit =getElement(name+"_submit");
	    if(button){
	      button.disabled=true;
	      CheckContent(button);
	      button.form.submit();
	    }
	  }
	  if(form.tagName=="INPUT"){
	    var button=form;
	    form=form.form;
	    if(typeof(form.getAttribute("name"))=="object"){name=form.id;}else{name=form.getAttribute("name");}
      var button_yes =getElement(name+"_button_yes");
      if(button_yes){button_yes.disabled=true;}
      var button_no  =getElement(name+"_button_no");
      if(button_no){button_no.disabled=true;}
      var result =getElement(input_name+"_result");
      result.value=button.name;
      button_yes.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;



/*Flash inserter*/
function insertFlash(containerId,id,flash,width,height){
  try{
    var container=getElement(containerId);
    if(container){
      var dimension="width='"+width+"' height='"+height+"'";
      container.innerHTML="<object id='"+id+"_ie' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' "+dimension+">"+
                          "<param name=movie value="+flash+">"+
                          "<param name='align' value='left' />"+
                          "<embed id='"+id+"_ot' align='left' src="+flash+" quality=high "+dimension+"></embed>"+
                          "</object>";
  
    }
  }catch(e){
    alert("insertFlash:"+e.message);
  }
}

function setFlashVar(flashId,name,value){
  try{
    if(navigator.userAgent.indexOf( 'Gecko')!=-1){
      var flash = getElement(flashId);
    }else{
      var flash = getElement(flashId);
    }
    flash.style.visibility="visible";
    flash.SetVariable(name,value);
  }catch(e){
    alert("setFlashVar:"+e.message);
  }
}

function closeNoFlash(id){
  try{
    var container=document.getElementById(id);
    container.innerHTML="";
    setCookie("no_flash",1);
  }catch(e){
    alert("Error in closeNoFlash: "+e.message);
  }
}

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;
    var vhour       = "00";
    if(form.elements[name+"_hours"]){
      vhour   =form.elements[name+"_hours"].value;
    }
    var vminute     = "00";
    if(form.elements[name+"_minutes"]){
      vminute =form.elements[name+"_minutes"].value;
    }
    form.elements[name].value=vyear+"-"+vmonth+"-"+vday+" "+vhour+":"+vminute;
  }catch(e){
    logging("Error onDateDayChange:"+e.message);
  }
}

function showTime(object,name){
  try{
    var timeInputs=getElement(name);
    object.style.display="none";
    timeInputs.style.display="inline";
  }catch(e){
    logging("Error showTime:"+e.message);
  }
}

var deleting_reply=false; 
function reply_delete(object,id){
  try{
    deleting_reply=id;
    aGet(object.href+"/"+id,"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{
    var offsetLeft=0;
    var initTop=0;
    var current=false;
    for(var i=0;i<getElementsByClass("form_field_tabsheet").length;i++){
      var tabSheet  =getElementsByClass("form_field_tabsheet")[i];
      var tabTitle  =tabSheet.childNodes[0];
      var tabContent=tabSheet.childNodes[1];
      var tabContainer=tabSheet.parentNode;
      current=getCookie(tabContainer.id+"_current_sheet",i);
      if(!current){
        current=0;
        setCookie(tabContainer.id+"_current_sheet",current);          
      }
      if(i==current){
        tabTitle.className='tab_title_current';
        tabTitle.selected=true;
        tabContent.style.display="block";
      }else{
        tabTitle.className='tab_title';
        tabContent.style.display="none";          
      }
      if(i==0){
        initTop=tabTitle.offsetTop;
      }
      tabTitle.style.position="absolute";
      tabTitle.style.top=initTop+"px";

      if(offsetLeft!=0){
        tabTitle.style.left=offsetLeft+"px";
        offsetLeft=offsetLeft+tabTitle.offsetWidth+2;
      }else{
        tabTitle.style.left=tabTitle.offsetLeft+(i==current?-4:6)+"px";
        offsetLeft=offsetLeft+tabTitle.offsetLeft+tabTitle.offsetWidth;
      }
      tabTitle.onmousedown=show_tab;
    }
  }catch(e){
    alert("Error tbsh_initialization:"+e.message);
  }
}

function show_tab(object){
  try{
    object=object?object.target:window.event.srcElement;
    var tabContainer=object.parentNode.parentNode;
    var tabid=0;
    for(i=0;i<tabContainer.childNodes.length;i++){
      var tabSheet=tabContainer.childNodes[i];
      if(tabSheet.className=="form_field_tabsheet"){
        var tabTitle=tabSheet.childNodes[0];
        var tabContent=tabSheet.childNodes[1];
        if(object==tabTitle){
          if(!tabTitle.selected){
            tabTitle.selected=true;
            tabTitle.className="tab_title_current";
            tabContent.style.display="block";
            current=setCookie(tabContainer.id+"_current_sheet",tabid);
          }
        }else{
          tabTitle.selected=false;
          tabTitle.className="tab_title";
          tabContent.style.display="none";
        }
        tabid++;
      }
    }
    return false;
  }catch(e){
    alert("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);
  }
}

function form_field_lists_insert(field,oninsert){
  try{
    var options=getElement(field+"_options");
    var current=getElement(field+"_current");
    var values ="";
    if(options.selectedIndex!=-1){
      var i=0;
      while(i<options.options.length){
        if(options.options[i].selected){
          options.options[i].selected=false;
          values+=(values==""?"":",")+options.options[i].value;
          current.appendChild(options.options[i]);
        }else{
          i++;
        }
      }
      setTimeout("sortList('"+field+"_current"+"',2);",500);
    }
    aGet(oninsert+values,"form_field_lists_inserted");
    return false;
  }catch(e){
    loggong("Error form_field_lists_insert:"+e.message);
  }
}

function form_field_lists_delete(field,ondelete){
  try{
    var options=getElement(field+"_options");
    var current=getElement(field+"_current");
    var values ="";
    if(current.selectedIndex!=-1){
      var i=0;
      while(i<current.options.length){
        if(current.options[i].selected){
          current.options[i].selected=false;
          values+=(values==""?"":",")+current.options[i].value;
          options.appendChild(current.options[i]);
        }else{
          i++;
        }
      }
      setTimeout("sortList('"+field+"_options"+"',2);",500);
    }
    aGet(ondelete+values,"form_field_lists_deleted");
    return false;
  }catch(e){
    logging("Error form_field_lists_delete:"+e.message);
  }
}

function form_field_lists_inserted(content,xml){
  //alert(xml.responseText);
}

function form_field_lists_deleted(content,xml){
  //alert(xml.responseText);
}


function sortList(id,kind) {
  try{
    var list=getElement(id);
    if(!kind){kind=1;}
    x = list.options;
    if (x.length > 1) {
      myArray = new Array();
      for (var i=0; i<x.length; i++) {
        myArray[i] = new Array(x[i].text, x[i].value, x[i].defaultSelected, x[i].selected);
      }
      if (kind==1) myArray.sort(sortBYtext);else myArray.sort(sortBYvalue);

      for (var i=0; i<x.length; i++) {
        var option = new Option(myArray[i][0], myArray[i][1], myArray[i][2], myArray[i][3]);        
        option.selected = myArray[i][3];
        x[i]=option;
      }
    }
  }catch(e){
    logging("Error sortList:"+e.message);
  }
}
function sortBYtext(a,b) {
   if (a[0] <b[0]) return -1
   if (a[0] > b[0]) return 1
   return 0
}
function sortBYvalue(a,b) {   
   if (parseInt(a[1]) <parseInt(b[1])) return -1
   if (parseInt(a[1]) > parseInt(b[1])) return 1
   return 0
}


delivery_processing=0;
function delivery_exec(id){
  try{
    var url=getHost()+"delivery.delivery_execute/"+id+"?execute=1";
    delivery_processing=id;    
    aGet(url,"delivery_executed");
  }catch(e){
    logging("Error delivery_exec:"+e.message);
  }
}

function delivery_executed(content,xml){
  try{
    var container=getElement("delivery_execute_container");
    container.innerHTML=xml.responseText;
    var completed=getElement("completed");
    if(!completed){
      setTimeout("delivery_exec("+delivery_processing+");",1000);
    }else{
      delivery_execute_button=getElement("delivery_execute_button");
      delivery_execute_button.style.display="none";
    }
  }catch(e){
    logging("Error delivery_executed:"+e.message);
  }
}

function delivery_subscibe(group_id,user_id){
  try{
    var url=getHost()+"delivery.delivery_switch_subscribe/?group_id="+group_id+"&user_id="+user_id+"&execute=1";
    aGet(url,"delivery_subscibe_executed");
  }catch(e){
    alert("Error delivery_subscibe:"+e.message);
  }
}


function delivery_subscibe_executed(content,xml){
  try{
    //alert(xml.responseText);
  }catch(e){
    alert("Error delivery_subscibe_executed:"+e.message);
  }
}

function delivery_delete_user(object,user_id){
  try{
    object.parentNode.parentNode.style.display="none";
    var url=getHost()+"user.user_delete/?user_id="+user_id+"&execute=1";
    aGet(url,"delivery_delete_user_executed");
  }catch(e){
    alert("Error delivery_subscibe_executed:"+e.message);
  }
}

function delivery_delete_user_executed(content,xml){
  try{
    //alert(xml.responseText);
  }catch(e){
    alert("Error delivery_delete_user_executed:"+e.message);
  }
}

function addSpecialChar(object){
  try{
    rteID=window.opener.insertSpecialCharInto;
    if(rteID&&(window.opener.document.getElementById(rteID))&&(oRTE = window.opener.document.getElementById(rteID).contentWindow)){
      pasteHtml(oRTE,object.innerHTML);
    }
    window.close();
  }catch(e){
    alert("addSpecialChar:"+e.message);
  }
}


function openSpecialChar(rteId){
  try{   
   window.insertSpecialCharInto=rteId;
   wnd=pop_up('/object.specialchars','750','600');
  }catch(e){
    alert("openSpecialChar:"+e.message);
  }
}


function overSpecialChar(object){
  try{
    var preview=getElement("specialchar_preview");
    var titlec =getElement("specialchar_title");
    var namec  =getElement("specialchar_name");
    name=object.getAttribute("name");
    title=object.getAttribute("title");
    preview.innerHTML=object.innerHTML;
    titlec.innerHTML=title;
    namec.innerHTML="&amp;"+name+";";
    object.className='specialchar_over';
  }catch(e){
    alert("overSpecialChar:"+e.message);
  }
}

function leaveSpecialChar(object){
  try{
    object.className='specialchar';
  }catch(e){
    alert("leaveSpecialChar:"+e.message);
  }
}

function openInsertTable(rteID){
  try{
    window.insertTableInto=rteID;
    wnd=pop_up('/object.inserttable','577','178');
  }catch(e){
    alert("openInsertTable:"+e.message);
  }
}

function insertTableInsert(){
  try{
    var cols=getElement("cols").value;
    var rows=getElement("rows").value;
    var border=getElement("border").value;
    var padding=getElement("padding").value;
    var spacing=getElement("spacing").value;
    var html="<table border=\""+border+"\" cellpadding=\""+padding+"\" cellspacing=\""+spacing+"\">";
    var col=0;
    var row=0;
    var idx=1;
    for(row=0;row<rows;row++){
      html+="<tr>";
      for(col=0;col<cols;col++){
        html+="<td>"+(idx++)+"</td>";
      }
      html+="</tr>";
    }
    html+="</table>";
    rteID=window.opener.insertTableInto;
    if(rteID&&(window.opener.document.getElementById(rteID))&&(oRTE = window.opener.document.getElementById(rteID).contentWindow)){
      oRTE.focus();
      if(isGecko){
        oRTE.document.execCommand('inserthtml', false, html);
      }else{
        var rng = oRTE.document.selection.createRange();
        if (rng.item){
          rng.item(0).outerHTML = html;
        }else{
          rng.pasteHTML(html);
        }
      }
      oRTE.focus();
    }
    window.close();
  }catch(e){
    alert("insertTableInsert:"+e.message);
  }
}

function insertTableCancel(){
  try{
    window.close();
  }catch(e){
    alert("insertTableCancel:"+e.message);
  }
}

function task_archive(object,id){
  try{
    var url = getHost()+"project.task_archive/"+id+"?&execute=1";
    var url = getHost()+"project.task_archive/"+id+"?&execute=1";
    aGet(url,"task_archived");
    object.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(object.parentNode.parentNode.parentNode.parentNode);
    return false;
  }catch(e){
    alert("Error task_archive:"+e.message);
    return false;
  }
}
function task_archived(content,xml){
  //alert(xml.responseText);
}

function task_percent_menu(task_id){
  try{
    var task_percent_menu=getElement("task_percent_menu_"+task_id);
    if(task_percent_menu){
      if(task_percent_menu.style.display=="block"){
      	task_percent_menu.style.display="none";
	    }else{
  	    task_percent_menu.style.display="block";
      }
    }
  }catch(e){
    alert("Error task_percent_menu:"+e.message);
    return false;
  }
}

function task_percent(object,id,percent){
  try{
    var taskPercent=getElement("task_percent_"+id);
    if(percent!="can"){
    	var url = getHost()+"project.task_percent/"+id+"/"+percent+"?&execute=1";
    	aGet(url,"task_percented");
    	if(taskPercent){      
	      taskPercent.style.backgroundPosition=(percent-100)+"px"+" 50%";
	      taskPercent.innerHTML=percent+"% &darr;";
  	  }
  	}else{
  	  var reason="";
  	  if(reason=prompt("Укажите причину отказа","")){
    		var url = getHost()+"user.user_task_decline/"+id+"?&reason="+reason+"&execute=1";
    		aGet(url,"task_percented");
    	}
  	}
   	var task_percent_menu=getElement("task_percent_menu_"+id);
    if(task_percent_menu){
      task_percent_menu.style.display="none";
    }
    var task_in_page=getElement("task_in_page_"+id);
    if(task_in_page){
      if(percent=="can"||percent==100){
        task_in_page.style.display="none";
      }
    }
    return false;
  }catch(e){
    alert("Error task_percent:"+e.message);
  }
}

function task_percented(content,xml){
  try{
    if(xml.responseText!=""){
  		alert(xml.responseText);
  	}
  }catch(e){
    alert("Error task_percent:"+e.message);
  }
}


function task_status(object,id,status){
  try{
    var url = getHost()+"project.task_status/"+id+"?&execute=1&status="+status;
    aGet(url,"task_statused");
    return false;
  }catch(e){
    alert("Error task_status:"+e.message);
  }
}

function task_statused(content,xml){
  alert(xml.responseText);
}

function currency_changed(field_name){
  try{
    var value=getElement(field_name+"_value");
    var currency=getElement(field_name+"_currency");
    var input=getElement(field_name);
    var currency_value=currency.options[currency.selectedIndex].value;
    var money_val=value.value.replace(/\,/g,".");
    input.value=money_val+";"+currency_value;
  }catch(e){
    alert(e.message);
  }
}


var saved_onselectstart_func=false;
var saved_onselectstart_flag=false;
function noSelection(){return false;}
function switchSelection(){
  try{
    if(saved_onselectstart_flag){
      document.body.onselectstart=saved_onselectstart;
      saved_onselectstart=false;
      saved_onselectstart_flag=false;
      if (typeof document.body.style.MozUserSelect!="undefined"){
        document.body.style.MozUserSelect=true;
      }
    }else{
      saved_onselectstart=document.body.onselectstart;
      document.body.onselectstart=noSelection;
      saved_onselectstart_flag=true;
      if (typeof document.body.style.MozUserSelect!="undefined"){
        document.body.style.MozUserSelect="none";
      }
    }
  }catch(e){
    alert("switchSelection:"+e.message);
  }
}


function shop_register_submit(){
  var submit=getElement("shop_register_button");
  submit.click();
  return false;
}

function basket_change(action,good){
  try{
    var form=getElement("basket_change");
    if(action){
      var oaction=getElement("action");
      oaction.value=action;
      var ogood=getElement("good");
      ogood.value=good;
    }
    if(form.submit){
	    form.submit();
	  }else{
	    alert(form);
	  }
    return false;
  }catch(e){
    alert("basket_change:"+e.message);
  }
}

var tag_input=false;
var tag_input_saved=false;
var tag_input_value=false;
var tag_object_path=false;

function get_key_pressed(e){
  var keynum;
  // IE
	if(window.event){
	  keynum = e.keyCode;
  // Netscape/Firefox/Opera
  }else if(e.which){keynum = e.which;}else{keynum = e.keyCode;}
	return keynum;
}

function tag_list_close(){this.style.display='none';this.opened=false;}
function tag_list_open(){
  this.style.display='block';
  this.style.left=this.input.offsetLeft+'px';
  this.style.top=(this.input.offsetTop+this.input.offsetHeight)+'px';
	this.style.display='block';
	this.opened=true;
}
function tag_list_select(){
  var tags_loaded=getElement('tag_by_letter');    
  if(this.opened&&tags_loaded.selected!=undefined){
    this.input.value=document.all?tags_loaded.childNodes[tags_loaded.selected].innerText:tags_loaded.childNodes[tags_loaded.selected].textContent;
  }
  this.close();
}

function tag_key_press(object,event,path){
  try{
    var wrap=getElement('tag_container_wrap');
    /// Init wrap
    wrap.close=tag_list_close;
    wrap.open=tag_list_open;
    wrap.input=object;
    wrap.select=tag_list_select;
    wrap.path=(new String(path)).substr(1,path.length);

    var numv =get_key_pressed(event);
    var charv=String.fromCharCode(numv);
    var value=new String(object.value);
    if(numv==27){//Esc
 	    wrap.close();
 	    return false;
    }
    if(numv==13){//Enter
      if(wrap.opened){
	      wrap.select();
  	  	return false;
  	  }
    }
    if(numv==38){//Up
    	if(!tag_input_saved){
    		wrap.saved=object.value;
    	}
    	tag_select_prev();return false;
    }
    if(numv==40){//Down
    	if(!tag_input_saved){
    		wrap.saved=object.value;
    	}
    	tag_select_next();
    	return false;
    }

  	tag_input=object;
  	
  	path=new String(path);
  	tag_object_path=path.substr(1,path.length);

  	setTimeout('tag_key_press_after();',100);
  	setTimeout('tag_letters_load();',100);

    return true;
  }catch(e){
    alert('Error in tag_key_press:'+e.message);
  }
}

function tag_key_press_after(){
  try{
	  var wrap=getElement('tag_container_wrap');    
	  var button=getElement('tag_add_button');

	  if(tag_input&&tag_input.value==''){
	    wrap.close();
	    button.disabled=true;
	  }else{
	    button.disabled=false;
	  }  
  }catch(e){
    alert('Error in tag_key_press_after:'+e.message);
  }

}

function tag_letters_load(){
  try{
    if(tag_input&&tag_input.value){
      var req=getHost()+tag_object_path+'/tag.tag_letter/'+tag_input.value;
	    aGet(req,'tag_letters_loaded');
	    tag_input=false;
	  }
  }catch(e){
    alert('Error in tag_letters_load:'+e.message);
  }
}

function tag_letters_loaded(content,xmlObject){
  try{
	  var tag_container=getElement('tag_container');    
    var wrap=getElement('tag_container_wrap');
    if(xmlObject.responseText){
	    tag_container.innerHTML=xmlObject.responseText;
	    if(!wrap.opened){wrap.open();}
	  }else{
	    wrap.close();
	  }
  }catch(e){
    alert('Error in tag_letters_loaded:'+e.message);
  }
}

function tag_add(){
  try{
    var wrap=getElement('tag_container_wrap');
    var new_tag=getElement('new_tag');
    var req=getHost()+wrap.path+'/tag.tag_insert/'+new_tag.value;
	  var button=getElement('tag_add_button');
	  if(!button.disabled){
	    button.disabled=true;
  	  aGet(req,'tag_list_loaded');
    }
    new_tag.value='';
    return false;
  }catch(e){
    alert('Error in tag_add:'+e.message);
  }
}

function tag_list_loaded(content,xmlObject){
  try{
	  var tag_list=getElement('tag_list');    
    if(xmlObject.responseText){
	    tag_list.innerHTML=xmlObject.responseText;
	  }
  }catch(e){
    alert('Error in tag_letters_loaded:'+e.message);
  }
}

function tag_container_close(){
  try{
	  var wrap=getElement('tag_container_wrap');    
    wrap.style.display='none';
    wrap.opened=false;
  }catch(e){
    alert('Error in tag_container_close:'+e.message);
  }
}

function tag_remove(id,path){
  try{
    path=new String(path);
  	path=path.substr(1,path.length);
    var req=getHost()+path+'/tag.tag_remove/'+id;
    aGet(req,'tag_list_loaded');
  }catch(e){
    alert('Error in tag_remove:'+e.message);
  }
}

function tag_select(id,name,path){
  try{
    var wrap=getElement('tag_container_wrap');
    var new_tag=getElement('new_tag');    
    wrap.close();
    new_tag.value=name;
    new_tag.tag_id=id;
  }catch(e){
    alert('Error in tag_remove:'+e.message);
  }
}

function tag_select_prev(){
  try{
	  var tags_loaded=getElement('tag_by_letter');    
	  if(tags_loaded.selected==undefined){tags_loaded.selected=tags_loaded.childNodes.length-1;}else{tags_loaded.selected--;
	    if(tags_loaded.selected==-1){
	    	tags_loaded.selected=tags_loaded.childNodes.length-1;
	    }
	  }
	  for(var i=0;i<tags_loaded.childNodes.length;i++){tags_loaded.childNodes[i].className='item';}
		tags_loaded.childNodes[tags_loaded.selected].className='current item';
  }catch(e){
    alert('Error in tag_select_prev:'+e.message);
  }
}

function tag_select_next(){
  try{
    var tags_loaded=getElement('tag_by_letter');    
	  if(tags_loaded.selected==undefined){tags_loaded.selected=0;}else{tags_loaded.selected++;
	    if(tags_loaded.selected>=tags_loaded.childNodes.length){
	    	tags_loaded.selected=0;
	    }
	  }
	  for(var i=0;i<tags_loaded.childNodes.length;i++){tags_loaded.childNodes[i].className='item';}
		tags_loaded.childNodes[tags_loaded.selected].className='current item';
  }catch(e){
    alert('Error in tag_select_next:'+e.message);
  }
}

var archiving_message = false;
function user_mail_2archive(id,container,message){
  try{
  	archiving_message=container;
  	var url = getHost()+"user.user_mail_2archive/"+id+"?&execute=1";
  	aGet(url,"user_mail_archived");
    return false;
  }catch(e){
    alert("Error user_mail_2archive:"+e.message);
    return false;
  }
}

function user_mail_archived(content,xml){
  try{
    if(xml.responseText==''){
    	if(container=getElement(archiving_message)){
	      container.style.display="none";
  	  }
    	archiving_message=false;
    }else{
      alert(xml.responseText);
    }
  }catch(e){
    alert("Error user_mail_archived:"+e.message);
    return false;
  }
}

///////////////////// MARK AS READED
var reading_message = false;
function user_mail_2readed(id,container,message){
  try{
  	reading_message=id;
  	var url = getHost()+"user.user_mail_2readed/"+id+"?&execute=1";
  	aGet(url,"user_mail_readed");
    return false;
  }catch(e){
    alert("Error user_mail_2readed:"+e.message);
    return false;
  }
}

function user_mail_readed(content,xml){
  try{
    if(xml.responseText==''){
      if(reading_message){
      	var button=getElement("user_message_readed_"+reading_message);
      	if(button){
      		button.style.display="none";
      	}
    		reading_message=false;
    	}
    }else{
      alert(xml.responseText);
    	archiving_message=false;
    }
  }catch(e){
    alert("Error user_mail_readed:"+e.message);
    return false;
  }
}
// Display full message
function user_mail_full(object,id){
  try{
    var efull=getElement("user_message_full_"+id);
    var eshort=getElement("user_message_short_"+id);
    if(object.opened){
      efull.style.display="none";
      eshort.style.display="block";
      object.innerHTML="&darr;";
      object.opened=false;
    }else{
      efull.style.display="block";
      eshort.style.display="none";
      object.innerHTML="&uarr;";
      object.opened=true;
    }
  	return false;
  }catch(e){
    alert("Error user_mail_full:"+e.message);
    return false;
  }
}

function invoice_tasks_delete(id){
  try{
  	var url = getHost()+"accounting.invoice_tasks_delete/"+id+"?&execute=1";
  	aGet(url,"invoice_tasks_deleted");
  	return false;
  }catch(e){  
    alert("Error in invoice_tasks_delete: "+e.message);
  }
}

function invoice_tasks_deleted(content,xml){
  try{
    alert(xml.responseText);
  }catch(e){  
    alert("Error in invoice_tasks_deleted: "+e.message);
  }
}


deleting_message=false;

function guestbook_delete(id){
  try{
  	deleting_message=id;
  	var url = getHost()+"guestbook.guestbook_delete/"+id+"?&execute=1";
  	aGet(url,"guestbook_deleted");
    return false;
  }catch(e){
    alert("Error guestbook_delete:"+e.message);
    return false;
  }
}


function guestbook_deleted(content,xml){
  try{
    if(xml.responseText==''){
    	if(container=getElement("guestbook_item_"+deleting_message)){
	      container.style.display="none";
  	  }
    	deleting_message=false;
    }else{
      alert(xml.responseText);
    }
  }catch(e){
    alert("Error guestbook_deleted:"+e.message);
    return false;
  }
}

function guestbook_spam(id){
  try{
  	deleting_message=id;
  	var url = getHost()+"guestbook.guestbook_spam/"+id+"?&execute=1";
  	aGet(url,"guestbook_spamed");
    return false;
  }catch(e){
    alert("Error guestbook_spam:"+e.message);
    return false;
  }
}


function guestbook_spamed(content,xml){
  try{
    if(xml.responseText==''){
    	if(container=getElement("guestbook_item_"+deleting_message)){
	      container.style.display="none";
  	  }
    	deleting_message=false;
    }else{
      alert(xml.responseText);
    }
  }catch(e){
    alert("Error guestbook_spamed:"+e.message);
    return false;
  }
}

switching_message=false;

function guestbook_switch(id){
  try{
  	switching_message=id;
  	var url = getHost()+"guestbook.guestbook_switch/"+id+"?&execute=1";
  	aGet(url,"guestbook_switched");
    return false;
  }catch(e){
    alert("Error guestbook_switch:"+e.message);
    return false;
  }
}


function guestbook_switched(content,xml){
  try{
    if(xml.responseText==''){
    	if(container=getElement("guestbook_item_"+switching_message)){
	      container.style.display="none";
  	  }
    	switching_message=false;
    }else{
      alert(xml.responseText);
    }
  }catch(e){
    alert("Error guestbook_switched:"+e.message);
    return false;
  }
}

function open_file_menu(file_id){
  try{
    var file_menu=getElement("file_menu_"+file_id);
    file_menu.style.display=file_menu.style.display=="block"?"none":"block";
  }catch(e){
    alert("Error open_file_menu:"+e.message);
  }
}
function insert_file(field,kind,path,id,title){
  try{
    var oRTE=getElement(field).contentWindow;
    switch(kind){
      case "image"     : {oRTE.document.execCommand('InsertImage', false, "/"+path);break;}
      case "link"      : {pasteHtml(oRTE,"{file kind=\"link\" id=\""+id+"\" name=\""+path+"\" }");break;}
      case "download"  : {var desc;if(desc=prompt(title,""))pasteHtml(oRTE,"{file kind=\"download\" id=\""+id+"\" name=\""+desc+"\" }");break;}
      case "popimage"  : {var prev;if(prev=prompt(title,""))pasteHtml(oRTE,"{file kind=\"popimage\" id=\""+id+"\" preview=\""+prev+"\" }");break;}
      case "video"     : {pasteHtml(oRTE,"{file kind=\"video\" id=\""+id+"\" name=\""+path+"\" }");break;}
      case "flash"     : {pasteHtml(oRTE,"{file kind=\"flash\" id=\""+id+"\" name=\""+path+"\" }");break;}
      case "icon"      : {pasteHtml(oRTE,"{file kind=\"icon\" id=\""+id+"\" name=\""+path+"\" }");break;}
    }
    var file_menu=getElement("file_menu_"+id);
    file_menu.style.display="none";
    return false;
  }catch(e){
    alert("Error insert_file:"+e.message);
  }
}

function code_save(id,content){
  try{

  }catch(e){
    alert("Error in code_save: "+e.message);
  }
}

function code_saved(){
  try{

  }catch(e){
    alert("Error in code_saved: "+e.message);
  }
}

var compile_button=false;
var framework_button=false;

function builder_logic_compile(button){
  try{
    aGet(getHost()+"builder.builder_compile?execute=1","builder_logic_compiled");
    //button.href="";
    compile_button=button;
		compile_button.className="button_disabled";
		return false;
  }catch(e){  
    alert('Error in builder_logic_compile:'+e.message);
  }
}

function builder_logic_compiled(content,xmlObject){
  try{
    if(xmlObject.responseText!=''){
      alert('Compile error: '+xmlObject.responseText);    
    }
    if(compile_button){
	    //compile_button.href="#";
			compile_button.className="button_enabled";
	    compile_button=false;
	  }
  }catch(e){  
    alert('Error in builder_logic_compiled:'+e.message);
  }
}

function builder_framework_compile(button){
  try{
  	aGet(getHost()+"builder.builder_framework?execute=1","builder_framework_compiled");
  	button.disabled=true;
  	framework_button=button;
  }catch(e){  
    alert('Error in builder_logic_compile:'+e.message);
  }
}

function builder_framework_compiled(content,xmlObject){
  try{
    if(xmlObject.responseText!=''){
      alert('Compile error: '+xmlObject.responseText);    
    }
    if(framework_button){
	    framework_button.disabled=false;
	    framework_button=false;
	  }
  }catch(e){  
    alert('Error in builder_framework_compiled:'+e.message);
  }
}


/// Удаление атрибутов
var deleting_attribute=false;
function builder_attribute_delete(id,name){
  try{
    if(confirm("Delete "+name+" attribute")){
			aGet(getHost()+"builder.builder_attribute_delete?execute=1&attribute_id="+id,"builder_attribute_deleted");
			deleting_attribute=id;
		}
		return false;
  }catch(e){  
    alert('Error in builder_attribute_delete:'+e.message);
  }
}

function builder_attribute_deleted(content,xmlObject){
  try{
		var attribute=getElement("attribute_"+deleting_attribute);
		if(attribute){hide(attribute);}
    deleting_attribute=false;
  }catch(e){
    alert('Error in builder_attribute_deleted:'+e.message);
  }
}

/// Удаление метода
var deleting_member=false;
function builder_member_delete(id,name){
  try{
    if(confirm("Delete "+name+" member")){
			aGet(getHost()+"builder.builder_member_delete?execute=1&member_id="+id,"builder_member_deleted");
			deleting_member=id;
		}
		return false;
  }catch(e){  
    alert('Error in builder_member_delete:'+e.message);
  }
}

function builder_member_deleted(content,xmlObject){
  try{
		var member=getElement("member_"+deleting_member);
		if(member){hide(member);}
    deleting_member=false;
  }catch(e){
    alert('Error in builder_member_deleted:'+e.message);
  }
}



function fivestar_post(){
  try{
    var kind=getElement("fivestar_kind");
    var iid=getElement("fivestar_iid");
    var button=getElement("fivestar_send");
    aGet(getHost()+"fivestar.fivestar_post?"+"kind="+kind.value+"&iid="+iid.value,"fivestar_post_posted");
  }catch(e){
    logging("Error fivestar_post:"+e.message);
  } 
}
function fivestar_post_posted(){
    var kind=getElement("fivestar_kind");
    var iid=getElement("fivestar_iid");
    var button=getElement("fivestar_send");

kind.disabled = true;
iid.disabled = true;
button.disabled = true;
window.location.reload();

}

function clipboard(action,id){
 	try{
		alert(action+':'+id);
 	}catch(e){
 	  alert('Error in clipboard: '+e.message);
	}
}

 

window.onload=initialization;

function initialization(){
  try{
    menu_initialization();
    drag_initialization();
    foot_initialization();
    navi_initialization();
    grap_initialization();
    sele_initialization();
    edit_initialization();
    tbsh_initialization();
  }catch(e){
    logging("Error initialization:"+e.message);
  }
}

