/** url to page showing links */
var linkPage = "editor/internal-link.html?";


var isFirstInit = true;

/** last use editor */
var editSpanTmp = null;
var editorTmp = null;
/**
 * create new editor
 * @param position html editor number
 */
function createEditor(position) {
 var editor = new Object();
 if(position == 1) {
   editor.disabled = false;
 } else {
   editor.disabled = true;
 }
 editor.position = position;
 editor.editSpanId = "editSpan"+position;
 editor.designSpanId = "designSpan"+position;
 editor.isEditMode = false;
 editor.blockInEditMode = false;
 editor.systemFontId = "FontNameList"+position;
 editor.fontFormatsId = "FontFormats"+position;
 editor.fontSizeId = "FontSize"+position;
 editor.stylesId = "Styles"+position;
 editor.designMode = "design"+position;
 editor.htmlMode = "html"+position;
 editor.isGuideLines = false;
 editor.tmpGuideLines = false;

 return editor;
}

/**
 * Set to all elemetns unselectable on exept editSpans
 * @param counter number of html editor instance on page
 */
function initHtmlEditor(counter) {
  var tmpImage = new Image();
  for (i=0; i<document.all.length; i++) {
    if(document.all(i).htmlEditor)
      document.all(i).unselectable = "on";
      if(document.all(i).tagName == "IMG") {
        var srcImg = document.all(i).src;

        var overSrcImg = srcImg.substring(0, srcImg.indexOf("."))+
          "_over"+srcImg.substring(srcImg.indexOf("."));
        tmpImage.src = overSrcImg;
        //alert(overSrcImg);
      }
  }
  for(i=1; i<=counter; i++) {
   document.getElementById("editSpan"+i).unselectable = "off";
  }
}

/**
 * Disable html editor
 * @param isLookForDiv true - we have to find div in which w work,
 * false - we haven't do it
 * @param disabled true - disable editor, false - enable
 * @param editor - instance html editor
 */
function disabledEditor(isLookForDiv, disabled, editor) {
  var isDiv = document.activeElement.tagName;
  if(isDiv == "IFRAME" || isLookForDiv == false) {
    var systemFont = document.getElementById(editor.systemFontId);
    var fontFormats = document.getElementById(editor.fontFormatsId);
    var fontSize = document.getElementById(editor.fontSizeId);
    var styles = document.getElementById(editor.stylesId);
    var designMode = document.getElementById(editor.designMode);
    var htmlMode = document.getElementById(editor.htmlMode);

    editor.disabled = disabled;
    if(disabled == true) {
      if(systemFont) {
        systemFont.disabled = true;
      }
      if(fontFormats) {
        fontFormats.disabled = true;
      }
      if(fontSize) {
        fontSize.disabled = true;
      }
      if(styles) {
        styles.disabled = true;
      }
      if(document.getElementById("html"+editor.position)) {
        document.getElementById("html"+editor.position).src = "editor/images/html_dis.gif";
      }
      if(document.getElementById("design"+editor.position)) {
        document.getElementById("design"+editor.position).src = "editor/images/design_dis.gif";
      }

    } else {
      if(editor.isEditMode == false) {
        if(systemFont) {
          systemFont.disabled = false;
        }
        if(fontFormats) {
          fontFormats.disabled = false;
        }
        if(fontSize) {
          fontSize.disabled = false;
        }
        if(styles) {
          styles.disabled = false;
        }
      }
      if(document.getElementById("html"+editor.position)) {
        var htmlImg = document.getElementById("html"+editor.position);
        //alert(htmlImg.checked);
        if(htmlImg.checked == "")
          htmlImg.src = "editor/images/html.gif";
        else
          htmlImg.src = "editor/images/html_sel.gif";
      }
      if(document.getElementById("design"+editor.position)) {
        var designImg = document.getElementById("design"+editor.position);
        if(designImg.checked == "")
          designImg.src = "editor/images/design.gif";
        else
          designImg.src = "editor/images/design_sel.gif";
      }
    }
    for (i=0; i<document.all.length; i++) {
      if(document.all(i).editorPic == editor.position)
        button_disable(document.all(i), editor);
    }
  }
}

/**
 * Delete spaces from right
 * @param str string to right trim
 */
function rtrim(str) {
  while(str.charAt(str.length - 1) == " ") {
    str = str.substring(0, str.length - 1);
  }
  return str;
}

/**
 * Invoked when mouse is over button
 * @param eButton button
 * @param command button name
 * @param editor html editor
 * @param blockInEditMode block this button in disabled mode or not
 */
function button_over(eButton,command,editor, blockInEditMode) {
  if(editor.disabled == false &&
      (editor.isEditMode == false || blockInEditMode == false)) {
    eButton.src = 'editor/images/'+rtrim(command)+'_over.gif';
  }
}

function button_disable(eButton, editor) {
  //alert(editor.disabled+"   "+editor.isEditMode); 
  if(editor.disabled == true || editor.isEditMode == true) {
    eButton.src = "editor/images/"+eButton.id+"_dis.gif";
  } else {
    eButton.src = "editor/images/"+eButton.id+".gif";
  }
}

/**
 * Invoked when mouse is over picture
 * @param eButton button
 * @param command button name
 */
function button_out(eButton,command, editor) {
  if(editor.disabled == false && editor.isEditMode == false) {
    eButton.src = "editor/images/"+eButton.id+".gif";
  }
}

/* we don't use this function any more */
function postItBack(editor){
  if(editor.isEditMode == false || editor.blockInEditMode == false) {
    if(editor.isEditMode) {
      showSource(editor);
    }
    var editSpan = document.getElementById(editor.editSpanId);
    window.returnValue = document.all[editSpan].innerHTML;
    var proc = window.dialogArguments[1];
    proc(document.all[editSpan].innerHTML, window.dialogArguments[2]);
    window.close();
  }
}

/** we don't use this function any more */
function getSystemFonts(editor) {
  if(editor.position == 1) {
    alert("!");
  }
  var a=dlgHelper.fonts.count;
  var fArray = new Array();
  var oDropDown = document.getElementById(editor.systemFontId);
  for (i = 1;i < dlgHelper.fonts.count;i++) {
    fArray[i] = dlgHelper.fonts(i);
    var oOption = document.createElement("OPTION");
    oDropDown.add(oOption);
    oOption.text = fArray[i];
    oOption.Value = i;
    oDropDown.unselectable = "on";
  }
}

/** we don't use this function any more */
function changeFont(editor){
  var oDropDown = document.getElementById(editor.systemFontId);
  var sSelected=oDropDown.options[oDropDown.selectedIndex];
  document.execCommand("FontName", false, sSelected.text);
  //document.getElementById(editor.editSpanId).focus();
  eval(editor.editSpanId).focus();
}

/** we don't use this function any more */
function getBlockFormats(editor){
  var a=dlgHelper.blockFormats.count;
  var fArray = new Array();
  var oDropDown = document.getElementById(editor.fontFormatsId);
  for (i = 1;i < dlgHelper.blockFormats.count;i++) {
    fArray[i] = dlgHelper.blockFormats(i);
    var oOption = document.createElement("OPTION");
    oDropDown.add(oOption);
    oOption.text = fArray[i];
    oOption.Value = i;
  }
}

/** we don't use this function any more */
function changeFormat(editor){
  var oDropDown = document.getElementById(editor.fontFormatsId);
  var sSelected=oDropDown.options[oDropDown.selectedIndex];
  document.execCommand("FormatBlock", false, sSelected.text);
  //document.getElementById(editor.editSpanId).focus();
  eval(editor.editSpanId).focus();
}

/** we don't use this function any more */
function changeFontSize(editor){
  var oDropDown = document.getElementById(editor.fontSizeId);
  var sSelected=oDropDown.options[oDropDown.selectedIndex];
  document.execCommand("FontSize", false, sSelected.value);
  //document.getElementById(editor.editSpanId).focus();
  eval(editor.editSpanId).focus();
}

/**
 * Insert/edit link
 */
function insertLink(editor){
  if(isExec(editor)) {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    if(eval(editor.editSpanId).document.selection.type != "Control") {
    var sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
    var inLink = null;
    if(sel && sel.tagName == "A") {
      inLink = new Object();
      inLink.link = sel.href;
      inLink.title = sel.innerHTML;
      inLink.tooltip = sel.title;
      if (sel.target != null || sel.target != "") {
        inLink.target = sel.target;
      } else {
        inLink.target = "";
      }
    }

    var dd = new Date();
    var urla = linkPage + dd.getTime();
    var link = showModalDialog(urla, inLink, "dialogWidth:650px;dialogHeight:605px;status=no;");

    if(link != null) {
      if(link.title.length == 0) {
        link.title = link.href;
      }
      if(sel && sel.tagName == "A") {
        sel.href = link.href;
        sel.target = link.target;
        sel.innerHTML = link.title;
        sel.title = link.tooltip;
      } else {
        //document.getElementById(editor.editSpanId).focus();
        eval(editor.editSpanId).focus();
        var sel = eval(editor.editSpanId).document.selection.createRange();
        if (link.target != null || link.target != "") {
          sel.pasteHTML("<a href='"+link.href+"' target='"+link.target+"' title='"+link.tooltip+"'>"+link.title+"</a>");
        } else {
          sel.pasteHTML("<a href='"+link.href+"'>"+link.title+"</a>");
        }
      }
     }
    } else {
      alert("You can't insert link in another object");
    }
  }
}

/** insert image */
function storeImageResData(results) {
  editSpanTmp.focus();
  var sel = editSpanTmp.document.selection.createRange();
   var imgToIns = editSpanTmp.document.createElement("img");
   imgToIns.src    = results[0];
   imgToIns.alt    = results[1];
   imgToIns.align  = results[2];
   imgToIns.border = results[3];
   imgToIns.hspace = results[4];
   imgToIns.vspace = results[5];
   imgToIns.width  = results[6];
   imgToIns.height = results[7];
   sel.pasteHTML(imgToIns.outerHTML);
}

/** show page with resorces */
function showImageResources(editor) {
  if(isExec(editor)) {
    if(eval(editor.editSpanId).document.selection.type != "Control") {
      editSpanTmp = eval(editor.editSpanId);
      if (pageName == null) {
        var dlgWin = showModalDialog("editor/res-image.jsp", storeImageResData, "dialogWidth:790px;dialogHeight:602px;status=no;");
      } else {
        var dlgWin = showModalDialog("editor/res-image.jsp?pagename="+pageName, storeImageResData, "dialogWidth:790px;dialogHeight:602px;status=no;");
      }
    }  else {
      alert("You can't insert image in another object");
    }
  }
 return false;
}

/** insert document */
function storeDocumentResData(results) {
  editSpanTmp.focus();
  var sel = editSpanTmp.document.selection.createRange();
  var hrefToIns = editSpanTmp.document.createElement("a");
  hrefToIns.href   = results[0];
  hrefToIns.innerText = results[1];
  hrefToIns.title  = results[2];
  hrefToIns.target  = "_blank";
  sel.pasteHTML(hrefToIns.outerHTML);
}


/** show page with resorces */
function showDocumentResources(editor) {
  if(isExec(editor)) {
    if(eval(editor.editSpanId).document.selection.type != "Control") {
      editSpanTmp = eval(editor.editSpanId);
      if (pageName == null) {
        var dlgWin = showModalDialog("editor/res-text.jsp", storeDocumentResData, "dialogWidth:790px;dialogHeight:628px;status=no;");
      } else {
        var dlgWin = showModalDialog("editor/res-text.jsp?pagename="+pageName, storeDocumentResData, "dialogWidth:790px;dialogHeight:628px;status=no;");
      }

    } else {
      alert("You can't insert document in another object");
    }
  }
 return false;
}


/** change style in current element */
function changeStyles(editor) {
  var styleDwopDownId = document.getElementById(editor.stylesId);
  if(isExec(editor)) {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    var sSelected=styleDwopDownId.options[styleDwopDownId.selectedIndex];
    var styles = sSelected.value;
    if(styles != "") {
      var dotPosition = styles.indexOf(".")+1;
      var styleName = styles.substring(dotPosition, styles.length)
      var sel = eval(editor.editSpanId).document.selection;
      var selectedText = sel.createRange();
      var styleTag = styles.substring(0, dotPosition-1);
      if(sel != null && selectedText.text != null && selectedText.text.length > 0) {
        try {
          if(styleTag == "formatting") {
            var curTag = selectedText.parentElement();
            var formatting = styles.substring(dotPosition, styles.length);
            var headingStyle = null;
            if(formatting.indexOf(".") > 0) {
             headingStyle = formatting.substring(formatting.indexOf(".")+1, formatting.length);
             formatting = formatting.substring(0, formatting.indexOf("."));
             //alert("H: "+formatting+" style: "+headingStyle);
            }
            document.execCommand("FormatBlock", false, formatting);
            if(headingStyle != null)
             selectedText.parentElement().className = headingStyle;
            else selectedText.parentElement().className = "";
          } else if(styleTag == "span") {
            selectedText.pasteHTML("<span class='"+styleName+"'>"+selectedText.htmlText+"</span>");
          }
        } catch(e)   {
          alert("You've selected text in different tags. It's impossible to set style in this situation");
        }
      } else {
         try {
          if(styleTag == "formatting") {
            var curTag = selectedText.parentElement();
            var formatting = styles.substring(dotPosition, styles.length);
            var headingStyle = null;
            if(formatting.indexOf(".") > 0) {
             headingStyle = formatting.substring(formatting.indexOf(".")+1, formatting.length);
             formatting = formatting.substring(0, formatting.indexOf("."));
             //alert("H: "+formatting+" style: "+headingStyle);
            }
            document.execCommand("FormatBlock", false, formatting);
            if(headingStyle != null)
             selectedText.parentElement().className = headingStyle;
            else selectedText.parentElement().className = "";
          } else {
           var tag = selectedText.parentElement();
           var isFound = false;
           while(isFound == false && tag != null) {
             //alert("Cur Tag: "+tag.tagName.toLowerCase()+" Find Tag: "+styleTag.toLowerCase());
             if(tag.tagName.toLowerCase() == styleTag.toLowerCase()) {
               isFound = true;
             } else {
               if(tag.tagName != null && tag.id.indexOf("editSpan") == -1)
                 tag = tag.parentElement;
               else tag =  null;
             }
          }
          if(isFound == true) {
            if(styleName != null && styleName.length > 0)
              tag.className = styleName;
            else
              tag.className = "";
          }
         }
        } catch(e) {
          alert("You can not apply this style to selected object");
        }
      }
    }
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
  }
}

/** insert/ edit table */
function editTable(editor){
  if(isExec(editor)) {
    var styles = showModalDialog("editor/dlg_ins_table.html", "", "status:no;dialogWidth:340px;dialogHeight:360px;help:no");
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    if(styles != null) {
      var isGL = false;
      if(editor.isGuideLines) {
        guidelines(editor);
        isGL = true;
      }
      eval(editor.editSpanId).document.selection.createRange().pasteHTML(styles);
      if(isGL)
        guidelines(editor);
    }
  }
}

/** insert new row in table */
function insertRow(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    insertRowFunc(check);	
  }
}

function insertRowFunc(check) {
    if(check != false) {
      var rowIndex = check.parentElement.rowIndex;
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var newRow = parentTable.insertRow(rowIndex+1);
      var index = 0;
      for(i = 0; i< parsedTable.rows[rowIndex].cells.length; i++) {
        if(parsedTable.rows[rowIndex].cells[i].isVisible == false) {
          for(j = rowIndex-1; j>= 0; j--) {
            if(parsedTable.rows[j].cells[i].isVisible == true) {
               parentTable.rows[j].cells[parsedTable.rows[j].cells[i].realIndex].rowSpan += 1;
               i += (parsedTable.rows[j].cells[i].tableCell.colSpan -1);
               j = -1;
             }
           }
        } else if(parsedTable.rows[rowIndex].cells[i].tableCell.rowSpan > 1) {
          parentTable.rows[rowIndex].cells[parsedTable.rows[rowIndex].cells[i].realIndex].rowSpan += 1;
        } else {
          var newCell = parentTable.rows[rowIndex+1].insertCell(index);
          index++;
          newCell.colSpan = parsedTable.rows[rowIndex].cells[i].tableCell.colSpan;
          i += newCell.colSpan -1;
        }
      }
    }
    return true;
}

/** insert new column in table */
function insertColumn(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
    var check = checkTag(sel, "TD");
    insertColumnFunc(check);
  }
}

function insertColumnFunc(check) {
    if(check != false) {
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var cellIndex = getCellByIndex(check.cellIndex, check.parentElement.rowIndex, parsedTable).index;
      for(i = 0; i < parsedTable.rows.length; i++) {
        if(parsedTable.rows[i].cells[cellIndex].isVisible == true) {
          if(parsedTable.rows[i].cells[cellIndex].tableCell.colSpan > 1 ||
            parsedTable.rows[i].cells[cellIndex].tableCell.rowSpan > 1) {
            parentTable.rows[i].cells[parsedTable.rows[i].cells[cellIndex].realIndex].colSpan +=1;
            i += parsedTable.rows[i].cells[cellIndex].tableCell.rowSpan - 1;
          } else
            parentTable.rows[i].insertCell(parsedTable.rows[i].cells[cellIndex].realIndex+1);
        } else {
          for(j = cellIndex; j >= 0; j--) {
            if(parsedTable.rows[i].cells[j].isVisible == true) {
              parentTable.rows[i].cells[parsedTable.rows[i].cells[j].realIndex].colSpan += 1;
              //alert("X: "+j+" Y: "+i);
              i += parsedTable.rows[i].cells[j].tableCell.rowSpan - 1;
            }
          }
        }
      }
    }
    return true;
}

/** delete current row in table */
function deleteRow(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    deleteRowFunc(check);
  }
}

function deleteRowFunc(check) {
    if(check != false) {
      var rowIndex = check.parentElement.rowIndex;
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      for(i = 0; i < parsedTable.rows[rowIndex].cells.length; i++) {
        if(parsedTable.rows[rowIndex].cells[i].isVisible == false) {
          for(j = rowIndex-1; j>= 0; j--) {
            if(parsedTable.rows[j].cells[i].isVisible == true) {
              parentTable.rows[j].cells[parsedTable.rows[j].cells[i].realIndex].rowSpan -= 1;
              i += (parsedTable.rows[j].cells[i].tableCell.colSpan -1);
              j = -1;
            }
          }
        } else if(parsedTable.rows[rowIndex].cells[i].tableCell.rowSpan > 1) {
          var lowRowIndex = rowIndex + 1;
          var index = 0;
          for(j = i; j >= 0; j--) {
            if(parsedTable.rows[lowRowIndex].cells[j].isVisible == true) {
              index = j+1;
              j = -1;
            }
          }
          var newCell = parentTable.rows[lowRowIndex].insertCell(index);
          newCell.colSpan = parsedTable.rows[rowIndex].cells[i].tableCell.colSpan;
          newCell.rowSpan = parsedTable.rows[rowIndex].cells[i].tableCell.rowSpan-1;
          i += (newCell.colSpan -1);
        }
      }
      parentTable.deleteRow(rowIndex);
    }
    return true;
}

/** check if cursor is in edit div*/
function isInEditSpanForTable(element) {
 return true;
 /*
 try {
   if(element.id.indexOf("editSpan") != -1) {// || !checkId(element,"editSpan"))
     return false;
   }
   if(!checkId(element,"editSpan"), false) {
     return false;
   }
   return true;
 } catch(e) {
   return false;
 }*/
}


/** check if there's such id*/
function checkId(item, id, wasIFrame) {
  //alert(wasIFrame+" item: "+item);
  var currIFrame = false;
  if (item.id.indexOf(id)!=-1) {
    return true;
  }
  if (item.tagName=='BODY' && wasIFrame) {
    return false;
  }
  if(item.tagName=='IFRAME' && !wasIFrame) {
    currIFrame = true;
  }
  item=item.parentElement;
  return checkId(item,id,currIFrame);
}

/** delete current column in table */
function deleteColumn(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    deleteColumnFunc(check);
  }
}

function deleteColumnFunc(check) {
    if(check != false) {
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var rowIndex = checkTag(check, "TR").rowIndex;
      var cellIndex = getCellByIndex(check.cellIndex, rowIndex, parsedTable).index;

      for(i = 0; i < parsedTable.rows.length; i++) {
        if(parsedTable.rows[i].cells[cellIndex].isVisible == true) {
          if(parsedTable.rows[i].cells[cellIndex].tableCell.colSpan > 1) {
            var newCell = parentTable.rows[i].insertCell(parsedTable.rows[i].cells[cellIndex].realIndex+1);
            newCell.colSpan = parsedTable.rows[i].cells[cellIndex].tableCell.colSpan - 1;
            newCell.rowSpan = parsedTable.rows[i].cells[cellIndex].tableCell.rowSpan;
          }
          parentTable.rows[i].deleteCell(parsedTable.rows[i].cells[cellIndex].realIndex);
          i += parsedTable.rows[i].cells[cellIndex].tableCell.rowSpan - 1;
        } else {
          for(j = cellIndex; j >= 0; j--) {
            if(parsedTable.rows[i].cells[j].isVisible == true) {
              parentTable.rows[i].cells[parsedTable.rows[i].cells[j].realIndex].colSpan -= 1;
              i += parsedTable.rows[i].cells[j].tableCell.rowSpan - 1;
            }
          }
        }
      }
    }
    return true;
}

/** add row span in current row */
function addRowSpan(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    addRowSpanFunc(check);
  }
}

function addRowSpanFunc(check) {
    if(check != false) {
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var rowIndex = checkTag(check, "TR").rowIndex;
      var cellIndex = check.cellIndex;
      var highCell = getCellByIndex(cellIndex, rowIndex, parsedTable);
      if(highCell != null && parsedTable.rows.length > rowIndex+highCell.tableCell.rowSpan) {
        var lowCell = parsedTable.rows[rowIndex+highCell.tableCell.rowSpan].cells[highCell.index];
        if(lowCell.isVisible == true ) {
          if(highCell.tableCell.colSpan == lowCell.tableCell.colSpan) {
            var rowSpan = highCell.tableCell.rowSpan;
            parentTable.rows[rowIndex].cells[highCell.realIndex].rowSpan += lowCell.tableCell.rowSpan;
            parentTable.rows[rowIndex+rowSpan].deleteCell(lowCell.realIndex);
          } else alert("Can't merge cells from different rows because the cells have to have the same width");
        } else alert("Can't make your action because there is no any cell below to merge with");
      } else alert("Can't make your action because there is no any cell below to merge with");
    }
    return true;
}

/** delete row span in current row */
function deleteRowSpan(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    deleteRowSpanFunc(check);
  }
}

function deleteRowSpanFunc(check) {
    if(check != false) {
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var rowIndex = checkTag(check, "TR").rowIndex;
      var cellIndex = check.cellIndex;
      var highCell = getCellByIndex(cellIndex, rowIndex, parsedTable);
      if(highCell != null && highCell.tableCell.rowSpan > 1) {
        var lowRowIndex = rowIndex+highCell.tableCell.rowSpan-1;
        var lowCell = null;
        for(i = highCell.index; i < parsedTable.rows[lowRowIndex].cells.length; i++) {
          if(parsedTable.rows[lowRowIndex].cells[i] != null &&
            parsedTable.rows[lowRowIndex].cells[i].isVisible == true) {
            lowCell =  parsedTable.rows[lowRowIndex].cells[i].realIndex;
            i = parsedTable.rows[lowRowIndex].cells.length;
          }
        }
        if(lowCell == null) {
          for(i = 0; i < highCell.index; i++) {
            if(parsedTable.rows[lowRowIndex].cells[i] != null &&
              parsedTable.rows[lowRowIndex].cells[i].isVisible == true) {
              lowCell =  parsedTable.rows[lowRowIndex].cells[i].realIndex+1;
              i = parsedTable.rows[lowRowIndex].cells.length;
            }
          }
        }
        if(lowCell == null)
          lowCell = 0;
        parentTable.rows[rowIndex].cells[highCell.realIndex].rowSpan -= 1;
        var newCell = parentTable.rows[lowRowIndex].insertCell(lowCell);
        newCell.colSpan =   highCell.tableCell.colSpan;
      } else alert("Can't make your action because there is no any cells to separate");
    }
    return true;
}

/** add col span in current column */
function addColSpan(editor) {
  var sel = null;
  try {
    //document.getElementById(editor.editSpanId).focus();
    eval(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    addColSpanFunc(check);
  }
}

/** delete col span in current column */
function deleteColSpan(editor) {
  var sel = null;
  try {
    eval(editor.editSpanId).focus();//document.getElementById(editor.editSpanId).focus();
    sel = eval(editor.editSpanId).document.selection.createRange().parentElement();
  } catch(e) {
    return;
  }
  //alert("SEL TAG: "+sel.tagName+" check tag: "+checkTag(sel, "TD").tagName);
  if(isExec(editor) && isInEditSpanForTable(sel)) {
    var check = checkTag(sel, "TD");
    deleteColSpanFunc(check);
  }
}

function deleteColSpanFunc(check) {
    if(check != false) {
      var cellIndex = check.cellIndex;
      var rowIndex = checkTag(check, "TR").rowIndex;
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var leftCell = getCellByIndex(cellIndex, rowIndex, parsedTable);
      if(leftCell != null && leftCell.tableCell.colSpan > 1) {
        parentTable.rows[rowIndex].cells[leftCell.realIndex].colSpan -= 1;
        var newCell = parentTable.rows[rowIndex].insertCell(leftCell.realIndex+1);
        newCell.rowSpan = leftCell.tableCell.rowSpan;
      } else alert("Can't make your action because there is no any cells to separate");
    }
    return true;
}

/** show hdesign/html mode */
function showSource(editor) {
  showHtml(editor);
  showDesign(editor);
}

/**
 * we don't use this function
 */
function escaper(text) {
  while (text.indexOf('"') != -1)  text = text.replace('"', '\\&amp;quot;');
  while (text.indexOf("'") != -1)  text = text.replace("'", '\\&amp;#39;');
  return text;
}

function initIFrame(id, isHtml, cssArray, defaultClass, editor) {
  
  for(i=0; i<cssArray.length-1;i++) {
    id.document.createStyleSheet(cssArray[i]);
  }
  if(isHtml) {
    id.document.body.innerHTML = document.all['editSpan'+editor.position].innerHTML;
    id.document.body.className = defaultClass;
    var funcName = 'showContextMenu("editor'+editor.position+'"); return false;';
    id.document.oncontextmenu = new Function(funcName);
    //funcName = 'goNextPage("'+editor.editSpanId+'");';
    //id.document.onkeydown = new Function(funcName);
  } else {
    var funcName = 'goNextPage("'+editor.designSpanId+'");';
    id.document.onkeydown = new Function(funcName);
  }
  id.document.designMode = "On";
  document.getElementById("design"+editor.position).checked = "true";

  if(isFirstInit) {
    isFirstInit = false;
    var imgArray = new Array();
    var imgOverArray = new Array();
    var imgDisArray = new Array();

    imgArray[0] = new Image();
    imgArray[0].src = "editor/images/html.gif";
    imgOverArray[0] = new Image();
    imgOverArray[0].src = "editor/images/html_sel.gif";
    imgDisArray[0] = new Image();
    imgDisArray[0].src = "editor/images/html_dis.gif";
    imgArray[1] = new Image();
    imgArray[1].src = "editor/images/design.gif";
    imgOverArray[1] = new Image();
    imgOverArray[1].src = "editor/images/design_sel.gif";
    imgDisArray[1] = new Image();
    imgDisArray[1].src = "editor/images/design_dis.gif";


    for (j=0; j<document.all.length; j++) {
      var editorButton =  document.all(j);
      if(editorButton.editorPic) {
        var i = j+2;
        imgArray[i] = new Image();
        imgArray[i].src = "editor/images/"+editorButton.id+".gif";
        imgOverArray[i] = new Image();
        imgOverArray[i].src = "editor/images/"+editorButton.id+"_over.gif";
        imgDisArray[i] = new Image();
        imgDisArray[i].src = "editor/images/"+editorButton.id+"_dis.gif";
      }
    }
  }
}


/** show html mode */
function showHtml(editor) {
  var editSpan = eval(editor.editSpanId).document.body;
  var designSpan = eval(editor.designSpanId).document.body;
  if(editSpan != null && editor.isEditMode == false) {
    if(isExec(editor)) {
      if(editor.isGuideLines) {
        guidelines(editor);
        editor.isGuideLines = false;
        editor.tmpGuideLines = true;
      }
      designSpan.innerText = editSpan.innerHTML;
      designSpan.innerHTML = ccParser(designSpan.innerHTML);
      eval("document.all."+editor.editSpanId).style.display = "none";
      eval("document.all."+editor.designSpanId).style.display = "";
      editor.isEditMode = true;
      disableDropDowns(editor);
      designSpan.focus();
      designSpan.setActive();
      return true;
    }
  }
  return false;
}

function onHtmlClick(editor, position) {
  if(showHtml(editor)) {
    var htmlId = document.getElementById("html"+position);
    if(htmlId.checked == "" || htmlId.checked == null) {
      var designId = document.getElementById("design"+position);
      htmlId.src = "editor/images/html_sel.gif";
      designId.src = "editor/images/design.gif";
      designId.checked = "";
      htmlId.checked = "checked";

    }
  }
}

function onDesignClick(editor, position) {
  if(showDesign(editor)) {
    var designId = document.getElementById("design"+position);
    if(designId.checked == "" || designId.checked == null) {
      var htmlId = document.getElementById("html"+position);
      htmlId.src = "editor/images/html.gif";
      designId.src = "editor/images/design_sel.gif";
      designId.checked = "checked";
      htmlId.checked = "";
    }
  }
}


/** show design mode */
function showDesign(editor) {
  var editSpan = eval(editor.editSpanId).document.body;
  var designSpan = eval(editor.designSpanId).document.body;
  if(editSpan  && editor.isEditMode == true) {
      try {
        editSpan.innerHTML = designSpan.innerText;

        eval("document.all."+editor.designSpanId).style.display = "none";
        eval("document.all."+editor.editSpanId).style.display = "";

        editor.isEditMode = false;
        disableDropDowns(editor);
        if(editor.tmpGuideLines) {
          guidelines(editor);
          editor.tmpGuideLines = false;
        }
	
        editSpan.focus();
        editSpan.setActive();
        return true;
      } catch(e) {
        alert("Invalid HTML construction.Look for '<p><hr>' and fix it ;)");
        document.getElementById("html"+editor.position).checked = true;
        showHtml(editor);
      }
  }
  return false;
}

function cleanCode(editor) {
  if(isExec(editor)) {
    if (confirm("This function will remove all styles and formatting in the current document, except the basic HTML tags structuring the text. We highly recommend doing this after you paste from Microsoft Word or other applications - otherwise your formatted text might not look correctly in many browsers.")){
      var editSpan = eval(editor.editSpanId).document.body;
      editSpan.innerHTML = doCleanCode(editSpan.innerHTML)
    }
  }
}

function doCleanCode(code) {
  for(i =0; i<2; i++) {
    // removes all Class attributes on a tag eg. '<p class=asdasd>xxx</p>' returns '<p>xxx</p>'
    code = code.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, "<$1$3")
    // removes all style attributes eg. '<tag style="asd asdfa aasdfasdf" something else>' returns '<tag something else>'
    code = code.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, "<$1$3")
    // removes all face attributes on font tag <font face=Arial> returns <font>
    code = code.replace(/<([\w]+) face="([^"]*)"([^>]*)/gi, "<$1$3")
    code = code.replace(/<([\w]+) face=([^ |>]*)([^>]*)/gi, "<$1$3")
    // removes all lang attributes on a tag eg. <span lang=US-ENl> returns <span>
    code = code.replace(/<([\w]+) lang=([^ |>]*)([^>]*)/gi, "<$1$3")
    // gets rid of all xml stuff... <xml>,<\xml>,<?xml> or <\?xml>
    code = code.replace(/<\\?\??xml[^>]>/gi, "")
    // get rid of ugly colon tags <a:b> or </a:b>
    code = code.replace(/<\/?\w+:[^>]*>/gi, "")
    // removes all empty <p> tags
    code = code.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi,"")
    // removes all empty span tags
    //code = code.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi,"")
    //removes all span
    code = code.replace(/<span([^>])*>/gi,"")
    code = code.replace(/<\/span>/gi,"")
    code = code.replace(/<font([^>])*>/gi,"")
    code = code.replace(/<\/font>/gi,"")

  }
  return code
}

/** disable drop downs when we're in html more or lost focus */
function disableDropDowns(editor){
  var systemFont = document.getElementById(editor.systemFontId);
  var fontFormats = document.getElementById(editor.fontFormatsId);
  var fontSize = document.getElementById(editor.fontSizeId);
  var styles = document.getElementById(editor.stylesId);

  if(editor.isEditMode == true) {
    if(systemFont)
      systemFont.disabled = true;
    if(fontFormats)
      fontFormats.disabled = true;
    if(fontSize)
      fontSize.disabled = true;
    if(styles)
      styles.disabled = true;
  } else {
    if(systemFont)
      systemFont.disabled = false;
    if(fontFormats)
      fontFormats.disabled = false;
    if(fontSize)
      fontSize.disabled = false;
    if(styles)
      styles.disabled = false;
  }
  
  for (i=0; i<document.all.length; i++) {
    if(document.all(i).editorPic == editor.position)
      button_disable(document.all(i), editor);
  }
  
}

/** parse html for html mode */
function ccParser(html) {

  html = html.replace(/@/gi,"_AT_");
  html = html.replace(/#/gi,"_HASH_");

  var htmltag = /(&lt;[\/]*[a-zA-Z]*[ ]*([\w\=\]\[\%\|\,\?\-\"\'\.\/\;\: \)\(-]*|[&amp;]*)*&gt;)/gi;
  html = html.replace(htmltag,"<span class=ccp_tag>$1</span>");
  
  var imgtag = /<span class=ccp_tag>(&lt;[\/]*img[ ]*[\w\=\&amp;\]\[\%\|\,\?\-\"\'\.\/\;\: \)\(-]*&gt;)<\/span>/gi;
  html = html.replace(imgtag,"<span class=ccp_img>$1</span>");

  var formtag = /<span class=ccp_tag>(&lt;[\/]*(form|input){1}[ ]*[\w\=\&amp;\]\[\%\,\|\?\-\"\'\.\/\;\: \)\(-]*&gt;)<\/span>/gi;
  html = html.replace(formtag,"<br><span class=ccp_form>$1</span>");

  var tabletag = /<span class=ccp_tag>(&lt;[\/]*(table|tbody|th|tr|td){1}[ ]*[\w\=\&amp;\]\[\%\|\,\?\-\"\'\.\;\: \)\(-]*&gt;)<\/span>/gi;
  html = html.replace(tabletag,"<span class=ccp_table>$1</span>");

  var Atag = /<span class=ccp_tag>(&lt;[\/]*a&gt;){1}<\/span>/gi;
  html = html.replace(Atag,"<span class=ccp_A>$1</span>");

  var Atag = /<span class=ccp_tag>(&lt;[\/]*a[ ]*[\w\=\&amp;\]\[\%\|\,\?\-\"\'\.\/\;\: \)\(-]*&gt;){1,}<\/span>/gi;
  html = html.replace(Atag,"<span class=ccp_A>$1</span>");

  var parameter = /=("[ \w\'\.\/\;\:\)\(-]+"|'[ \w\=\&amp;\]\[\%\,\?\-\"\'\.\|\/\;\: \)\(-]+')/gi;
  html = html.replace(parameter,"=<span class=ccp_paramvalue>$1</span>");

  var entity = /&amp;([\w]+);/gi;
  //html = html.replace(entity,"<span class=ccp_entity>&amp;$1;</span>");
  html = html.replace(entity,"<span class=ccp_entity>&$1;</span>");

  var comment = /(&lt;\!--[\W _\w\=\%\"\'\.\|\/\;\:\)\(-]*--&gt;)/gi;
  html = html.replace(comment,"<br><span class=ccp_htmlcomment>$1</span>");

  html = html.replace(/_AT_/gi,"@");
  html = html.replace(/_HASH_/gi,"#");
  
  return html;
}

/** change current TEdit */
function changeTEdit() {
 if (tEdit) { tEdit.changePos(); tEdit.resizeCell() }
}

/** exec commend - use in buttons */
function exec(command, editor) {
  var sel;
  var edit = eval(editor.editSpanId);
  var textRn;
  try {
    eval(editor.editSpanId).focus();
    textRn = eval(editor.editSpanId).document.selection.createRange();
    sel = textRn.parentElement();
  } catch(e) {
    return;
  }

  var allowExec = true;
  if(isExec(editor)) {
    if(command == "inserthorizontalrule" && sel.tagName == "P") {
      textRn.moveStart("character", -2);
      if(textRn.text == null || textRn.text == "") {
        allowExec = false;
        alert("Invalid construction <p><hr/>");
      }
    }
    if(allowExec)
      eval(editor.editSpanId).document.execCommand(command);
  }
}

/** check if we should exec any command */
function isExec(editor) {
  if(editor.isEditMode == false && editor.disabled == false)
    return true;
  return false;
}

function nextLine() {
//  if(event.keyCode==13)
//    with(document.selection.createRange())pasteHTML('<br>'),select()
}


/** check if we're in such tag */
function checkTag(item,tagName) {
  //alert(item.tagName+"   "+tagName);
  if (item.tagName.search(tagName)!=-1) {
    return item;
  }
  if (item.tagName=='BODY') {
    return false;
  }

  item=item.parentElement;
  return checkTag(item,tagName);
}

/** parse table and create its structure*/
function parseTable(table) {

 ourTable = new Object();
 ourTable.rows = new Array(table.rows.length);
 ourTable.rows[0] = new Object();
 var cellsQuantity = 0;
 //determine quantity of cells
 for(x = 0; x < table.rows[0].cells.length; x++)
  cellsQuantity += table.rows[0].cells[x].colSpan;

 //init rows
 for(x = 0; x < table.rows.length; x++) {
   ourTable.rows[x] = new Object();
   ourTable.rows[x].cells =  new Array(cellsQuantity);
 }

 for(i = 0; i<ourTable.rows.length; i++ ) {
   //ourTable.rows[i] = new Object();
   //ourTable.rows[i].cells =  new Array(cellsQuantity);

   for(x = 0; x < cellsQuantity; x++) {
     tableCell = table.rows[i].cells[x];
     var tmpX = x;
     //if there's another cell on its place,
     //so we have to shift current cell
     while(ourTable.rows[i].cells[x] != null)
       x++;
     //check if we have inserted this cell earlier,
     //because there's rowspan and current cell doesn't exist
     if(tableCell != null) {
       for(y = 0; y < tableCell.colSpan; y++) {
         for(z = 0; z < tableCell.rowSpan; z++) {
           cell = new Object();
           //if current cell isn't a cell which is overlaped
           if(y == 0 && z == 0) {
            cell.tableCell = tableCell;
            cell.isVisible = true;
           } else cell.isVisible = false;
           while(ourTable.rows[i+z].cells[x+y])
           cell.phantomIndex = x+y;
           if(ourTable.rows[i+z].cells[x+y] == null) {
             ourTable.rows[i+z].cells[x+y] = cell;
           }
         }
       }
     }
     x = tmpX;
   }
 }

 for(j = 0; j<ourTable.rows.length; j++) {
   var count = 0;
   for(k = 0; k<ourTable.rows[j].cells.length; k++) {
     ourTable.rows[j].cells[k].index = k;
     if(ourTable.rows[j].cells[k].isVisible == true)
       ourTable.rows[j].cells[k].realIndex = count++;
   }
 }
 /*for(j = 0; j<ourTable.rows.length; j++)
  for(k = 0; k<ourTable.rows[j].cells.length; k++)
    alert("X: "+k+" Y: "+j+" Visible: "+ourTable.rows[j].cells[k].isVisible);
 */
 return ourTable;
}

/** return table cell by coordinats */
function getCellByIndex(indexX, indexY, parsedTable) {
   var cell = null;
   for(k = 0; k<parsedTable.rows[indexY].cells.length; k++) {
       if(parsedTable.rows[indexY].cells[k].realIndex == indexX) {
       cell = parsedTable.rows[indexY].cells[k];
       k = parsedTable.rows[indexY].cells.length;
     }
   }
   return cell;
}

/** set drop down selected in first position */
function setToFirstItem(dropDown) {
 dropDown.selectedIndex = 0;
}

//hide context menu or not
var isHide = true;


function hide() {
  if(self.menu) {
    menu.hide();
    menu = null;
  }
  //isHide = true;
}

function yo() {
  //isHide = false;
  alert("!!");
  return true;
}

function setTDProperties() {
  var td = checkTag(tmpElement, "TD");
  if(td != null)	 {
    var tdProperties = new Object();
	tdProperties.bgColor = td.bgColor;
	var width = td.width;
	if(width == null || width == "") {
	  tdProperties.isWidthPx = false;
	  tdProperties.width = width;
	} else {
	  if(width.indexOf("%") == -1) {
  	    tdProperties.isWidthPx = true;
	    tdProperties.width = width;
	  } else {
	    tdProperties.isWidthPx = false;
	    tdProperties.width = width.substring(0, width.length-1);
  	  }
	}
	var height = td.height;
	if(height == null || height =="") {
	  tdProperties.isHeightPx = false;	
	  tdProperties.height = height;
	} else {
	  if(height.indexOf("%") == -1) {
  	    tdProperties.isHeightPx = true;
	    tdProperties.height = height;
	  } else {
	    tdProperties.isHeightPx = false;
	    tdProperties.height = height.substring(0, height.length-1);
  	  }	
	}
	tdProperties.align = td.align;
	tdProperties.vAlign = td.vAlign;
        
        var newTDProperties = showModalDialog("editor/td_properties.html", tdProperties, "status:no;dialogWidth:446px;dialogHeight:204px;help:no");
	
	if(newTDProperties != null) {
	  if(newTDProperties.bgColor != "" && newTDProperties.bgColor != "None")
	    td.bgColor = newTDProperties.bgColor;
	  else
	    td.removeAttribute("bgColor");
	  
  
	  if(newTDProperties.width != "" && newTDProperties.width != "%" && newTDProperties.width != null)
  	    td.width = newTDProperties.width;
  	  else 
  	    td.removeAttribute("width");
	  
	  if(newTDProperties.height != "" && newTDProperties.height != "%" && newTDProperties.height != null)
  	    td.height = newTDProperties.height;
  	  else 
  	    td.removeAttribute("height");   

  	  if(newTDProperties.align != "" && newTDProperties.align != "None" && newTDProperties.align != null)
  	    td.align = newTDProperties.align;
  	  else
  	    td.removeAttribute("align");

  	  if(newTDProperties.vAlign != "" && newTDProperties.vAlign != "None" && newTDProperties.vAlign != null)
  	    td.vAlign = newTDProperties.vAlign;
  	  else
  	    td.removeAttribute("vAlign");
	}
  }
}

function setImageProperties() {
  var image = tmpElement;
  if(image != null)	 {
    var imageProperties = new Object();
	imageProperties.alt = image.alt;
	imageProperties.width = image.width;
	if(image.style != null && image.style.width != null && image.style.width != "")
	  imageProperties.width = image.style.width.substring(0,image.style.width.indexOf("px"));
	imageProperties.height = image.height;
	if(image.style != null && image.style.height != null && image.style.height != "")
	  imageProperties.height = image.style.height.substring(0,image.style.height.indexOf("px"));
	imageProperties.align = image.align;
	imageProperties.border = image.border;
        imageProperties.hspace = image.hspace;
        imageProperties.vspace = image.vspace;

        var newImageProperties = showModalDialog("editor/image_properties.html", imageProperties, "status:no;dialogWidth:500px;dialogHeight:240px;help:no");
	
	if(newImageProperties != null) {
	  if(newImageProperties.alt != "" && newImageProperties.alt != null)
	    image.alt = newImageProperties.alt;
	  else
	    image.removeAttribute("alt");
	  
  
	  if(newImageProperties.width != "" && newImageProperties.width != null)
  	    image.width = newImageProperties.width;
  	  else 
  	    image.removeAttribute("width");
  	  image.style.removeAttribute("width");
	  
	  if(newImageProperties.height != "" && newImageProperties.height != null)
  	    image.height = newImageProperties.height;
  	  else 
  	    image.removeAttribute("height");   
  	  image.style.removeAttribute("height");

  	  if(newImageProperties.align != "" && newImageProperties.align != "None" && newImageProperties.align != null)
  	    image.align = newImageProperties.align;
  	  else
  	    image.removeAttribute("align");

  	  if(newImageProperties.hspace != "" && newImageProperties.hspace != null) 
  	    image.hspace = newImageProperties.hspace;
  	  else
  	    image.removeAttribute("hspace");

  	  if(newImageProperties.border != "" && newImageProperties.border != null)
  	    image.border = newImageProperties.border;
  	  else
  	    image.removeAttribute("border");

  	  if(newImageProperties.vspace != "" && newImageProperties.vspace != null)
  	    image.vspace = newImageProperties.vspace;
  	  else
  	    image.removeAttribute("vspace");

	}
  }
}

function setLinkProperties() {
  var linka = checkTag(tmpElement, "A");;
  if(linka != null)	 {
    var linkProperties = new Object();
	linkProperties.url = linka.href;
	linkProperties.title = linka.innerHTML;
	linkProperties.tooltip = linka.title;
        linkProperties.target = linka.target;

        var newLinkProperties = showModalDialog("editor/link_properties.html", linkProperties, "status:no;dialogWidth:480px;dialogHeight:236px;help:no");
	
	if(newLinkProperties != null) {
	  if(newLinkProperties.url != "" && newLinkProperties.url != null)
	    linka.href = newLinkProperties.url;
	  else
	    linka.removeAttribute("href");

	  if(newLinkProperties.tooltip != "" && newLinkProperties.tooltip != null)
	    linka.title = newLinkProperties.tooltip;
	  else
	    linka.removeAttribute("title");
	  
          linka.innerHTML = newLinkProperties.title;

	  if(newLinkProperties.target != "" && newLinkProperties.target != "None" && newLinkProperties.target != null)
  	    linka.target = newLinkProperties.target;
  	  else 
  	    linka.removeAttribute("target");   

	}
  }
}

/*function setHRProperties() {
  var hr = tmpElement;
  if(hr != null)	 {
    var hrProperties = new Object();
    hrProperties.style = hr.style;
    var newHRProperties = showModalDialog("editor/hr_properties.html", hrProperties, "status:no;dialogWidth:500px;dialogHeight:120px;help:no");
	
	if(newHRProperties != null) {
	  alert(newHRProperties.style);
	  if(newHRProperties.style != "" && newHRProperties.style != null)
	    hr.setAttribute("style", newHRProperties.style);
	  else
	    hr.removeAttribute("style");
      }	  
  }
}*/

function setTableProperties() {
  var table = checkTag(tmpElement, "TABLE");
  if(table != null)	 {
    var tableProperties = new Object();
	tableProperties.bgColor = table.bgColor;
	
	var isGL = false;
	if(editorTmp.isGuideLines == true) {
	  isGL = true;
          guidelines(editorTmp);
	}
	tableProperties.border = table.border;
	if(isGL == true) {
          guidelines(editorTmp);
	}
	tableProperties.cellPadding  = table.cellPadding;
	tableProperties.cellSpacing  = table.cellSpacing;
	var width = table.width;
	if(width == null || width == "") {
	  tableProperties.isWidthPx = false;
	  tableProperties.width = width;
	} else {
	  if(width.indexOf("%") == -1) {
  	    tableProperties.isWidthPx = true;
	    tableProperties.width = width;
	  } else {
	    tableProperties.isWidthPx = false;
	    tableProperties.width = width.substring(0, width.length-1);
  	  }
	}
	if(table.style != null && table.style.width != null && table.style.width != "") {
	  tableProperties.width = table.style.width.substring(0,table.style.width.indexOf("px"));
	  tableProperties.isWidthPx = true;
	}

	var height = table.height;
	if(height == null || height =="") {
	  tableProperties.isHeightPx = false;	
	  tableProperties.height = height;
	} else {
	  if(height.indexOf("%") == -1) {
  	    tableProperties.isHeightPx = true;
	    tableProperties.height = height;
	  } else {
	    tableProperties.isHeightPx = false;
	    tableProperties.height = height.substring(0, height.length-1);
  	  }	
	}
	if(table.style != null && table.style.height != null && table.style.height != "") {
          tableProperties.height = table.style.height.substring(0,table.style.height.indexOf("px"));
          tableProperties.isHeightPx = true;
        }

	tableProperties.align = table.align;
    var newTableProperties = showModalDialog("editor/table_properties.html", tableProperties, "status:no;dialogWidth:460px;dialogHeight:235px;help:no");
	if(newTableProperties != null) {
	  if(newTableProperties.bgColor != "" && newTableProperties.bgColor != "None")
	    table.bgColor = newTableProperties.bgColor;
	  else
	    table.removeAttribute("bgColor");
	  
	  isGL = false;
	  var isTmpBorder = false;
	  if(table.nobord)
	    isTmpBorder = true;
	  if(editorTmp.isGuideLines == true) {
	    isGL = true;
            guidelines(editorTmp);
	  }
	  if(newTableProperties.border != "" && newTableProperties.border != null)
  	    table.border = newTableProperties.border;
  	  else
  	    table.removeAttribute("border");
  	  if(isGL == true)
  	    guidelines(editorTmp);
  	  if(isTmpBorder)
  	    table.borderColor = 'black';

  	  if(newTableProperties.cellPadding != "" && newTableProperties.cellPadding != null)
  	    table.cellPadding = newTableProperties.cellPadding;
  	  else
  	   table.removeAttribute("cellPadding");
  	  
  	  if(newTableProperties.cellSpacing != "" && newTableProperties.cellSpacing != null)
	    table.cellSpacing = newTableProperties.cellSpacing;
	  else 
	    table.removeAttribute("cellSpacing");
	  
	  if(newTableProperties.width != "" && newTableProperties.width != "%" && newTableProperties.width != null)
  	    table.width = newTableProperties.width;
  	  else 
  	    table.removeAttribute("width");
  	  table.style.removeAttribute("width");
	  
	  if(newTableProperties.height != "" && newTableProperties.height != "%" && newTableProperties.height != null)
  	    table.height = newTableProperties.height;
  	  else 
  	    table.removeAttribute("height");   
  	  table.style.removeAttribute("height");

  	  if(newTableProperties.align != "" && newTableProperties.align != "None" && newTableProperties.align != null)
  	    table.align = newTableProperties.align;
  	  else
  	    table.removeAttribute("align");
	}
  }
}

function checkEsc() {
  if(window.event.keyCode == 27) {
    hide();
  }
}

function insertRowContext() {
  hide();
  insertRowFunc(tmpElement);
  return true;
}

function insertColumnContext() {
  hide();
  insertColumnFunc(tmpElement);
  return true;
}

function deleteRowContext() {
  hide();
  deleteRowFunc(tmpElement);
  return true;
}

function deleteColumnContext() {
  hide();
  deleteColumnFunc(tmpElement);
  return true;
}

function addRowSpanContext() {
  hide();
  addRowSpanFunc(tmpElement);
  return true;
}

function deleteRowSpanContext() {
  hide();
  deleteRowSpanFunc(tmpElement);
  return true;
}

function deleteColSpanContext() {
  hide();
  deleteColSpanFunc(tmpElement);
  return true;
}

function addColSpanContext() {
  hide();
  addColSpanFunc(tmpElement);
  return true;
}

function addColSpanFunc(check) {
    if(check != false) {
      var cellIndex = check.cellIndex;
      var rowIndex = checkTag(check, "TR").rowIndex;
      var parentTable= checkTag(check, "TABLE");
      var parsedTable = parseTable(parentTable);
      var leftCell = getCellByIndex(cellIndex, rowIndex, parsedTable);
      if(leftCell != null && parentTable.rows[rowIndex].cells.length > cellIndex+leftCell.tableCell.colSpan-1) {
        var rightCell = parsedTable.rows[rowIndex].cells[leftCell.index+leftCell.tableCell.colSpan];
        if(leftCell.tableCell.rowSpan == rightCell.tableCell.rowSpan) {
          parentTable.rows[rowIndex].deleteCell(rightCell.realIndex);
          parentTable.rows[rowIndex].cells[leftCell.realIndex].colSpan += rightCell.tableCell.colSpan;
        } else alert("Can't merge cells from different columns because the cells have to have the same height");
      } else alert("Can't make your action because there is no any cell rigth to merge with");
    }
    return true;
}


function over(noda) {
  noda.style.backgroundColor = 'black';//'#0066cc';
  noda.style.cursor = 'default';
  noda.style.color = 'White';
}

function out(noda) {
  noda.style.backgroundColor = '#DDDDDD';
  noda.style.cursor = '';
  noda.style.color = 'Black'
}

function sinit(editSpanStr) {
  var el,temp;
  var ss = new Object();
  ss.x = 0;
  ss.y = 0;
    el = document.all[editSpanStr];
    if(el.offsetParent) {
      temp = el;
      while(temp.offsetParent) {
        temp=temp.offsetParent;
        ss.x+=temp.offsetLeft;
        ss.y+=temp.offsetTop;
      }
    }
    ss.x+=el.offsetLeft;
    ss.y+=el.offsetTop;
  return ss;
}

var tmpElement = null;
var tmpTextRange = null;

function showContextMenu(editorStr) {
  //hide();
  editorTmp = eval(editorStr);
  var edit = eval(eval(editorStr).editSpanId);
  isFoundLayer = false;
  var id = "";
  var oControlRange = edit.document.selection.createRange();
  if (edit.document.selection.type == "Control"){
    tmpTextRange = null;
    if(document.getElementById(oControlRange(0).tagName+"Submenu")) {
      id = document.getElementById(oControlRange(0).tagName+"Submenu");
      menu = layer(oControlRange(0).tagName+"Submenu");
      tmpElement = oControlRange(0);
      isFoundLayer = true;
    }
   } else {
    tmpTextRange = oControlRange;
    var selElement = oControlRange.parentElement();
    while(selElement != null && !isFoundLayer) {
      if(document.getElementById(selElement.tagName+"Submenu") != null) {
        isFoundLayer = true;
        //selElement = document.getElementById(selElement.tagName+"Submenu");
        tmpElement = selElement;
        id = eval(selElement.tagName+"Submenu");
        menu = layer(selElement.tagName+"Submenu");
      }
      else {
        selElement = selElement.parentElement;
      }
      
    }
    if(selElement == null || !isFoundLayer) {
      id = eval("TextSubmenu");
      menu = layer("TextSubmenu");
      isFoundLayer = true;
    }
   }
   if(isFoundLayer) {
    var ss = sinit(eval(editorStr).editSpanId);
    menu.moveTo(ss.x+edit.window.event.clientX, ss.y+edit.window.event.clientY);
    menu.show();
    id.focus();
    id.setActive();
    
   }

  return false;
}

function cutMenuAction() {
  if(tmpTextRange != null) {
    tmpTextRange.execCommand('Cut');
  }
}

function copyMenuAction() {
  if(tmpTextRange != null) {
    tmpTextRange.execCommand('Copy');
  }
}

function pasteMenuAction() {
  if(tmpTextRange != null) {
    tmpTextRange.execCommand('Paste');
  }
}

function selectAllMenuAction() {
  if(editorTmp != null) {
    eval(editorTmp.editSpanId).document.execCommand('SelectAll');
  }
}

var isHide = true;

function guidelines(editor) {
  var doc = eval(editor.editSpanId).document;
  for (i=0; i<doc.all.length; i++) {
    var curElement = doc.all(i);
    if(!editor.isGuideLines && curElement.tagName == "TABLE") {
      curElement.setAttribute("orig", curElement.border);
      if(curElement.border == null || curElement.border == "" || curElement.border==0) {
        curElement.border = 1;
        curElement.setAttribute("nobord", 1);
        curElement.borderColor = "gray";
      }
    } else if(editor.isGuideLines && curElement.tagName == "TABLE") {
      var border = curElement.getAttribute("orig");
      if(border != null && border != "" && border != 0)
        curElement.border = border;
      else {
      	curElement.removeAttribute("border");
      }
      if(curElement.getAttribute("nobord") == 1) {
        curElement.removeAttribute("nobord");
        curElement.removeAttribute("borderColor");
  	//curElement.style.removeAttribute("borderColor");
      }
      curElement.removeAttribute("orig");
    }
  }
  if(editor.isGuideLines)
    editor.isGuideLines = false;    
  else
    editor.isGuideLines = true;
}

function goNextPage(designSpanId) {
  var designSpanEl = eval(designSpanId);
  if(designSpanEl.window.event.keyCode == 13) {
    if(designSpanEl.window.event.shiftKey) {
      designSpanEl.document.execCommand("InsertParagraph");
      var range = designSpanEl.document.selection.createRange();
      range.moveStart("character", 0);
      range.select();
    } else {
      var range = designSpanEl.document.selection.createRange();
      range.pasteHTML('<br/>&nbsp;');
      range.moveStart("character", -1);
      range.select();
      range.execCommand('Cut');
    }
    designSpanEl.window.event.returnValue = false;
    return false;
  }
  return true;
}

