var format = "HTML";
var initHTML = "";
var edit;
var RangeType;
var bEditMode = null;

// 浏览器版本检测
var BrowserInfo = new Object() ;
BrowserInfo.MajorVer = navigator.appVersion.match(/MSIE (.)/)[1] ;
BrowserInfo.MinorVer = navigator.appVersion.match(/MSIE .\.(.)/)[1] ;
BrowserInfo.IsIE55OrMore = BrowserInfo.MajorVer >= 6 || ( BrowserInfo.MajorVer >= 5 && BrowserInfo.MinorVer >= 5 ) ;

function setFocus() {
	textEdit.focus();
}
function selectRange(){
	editr = textEdit.document.body.createTextRange()
	edit = textEdit.document.selection.createRange();
	RangeType = textEdit.document.selection.type;
}

//007

// 修正Undo/Redo
var history = new Object;
history.data = [];
history.position = 0;
history.bookmark = [];

// 保存历史
function saveHistory() {
		if (history.data[history.position] != textEdit.document.body.innerHTML){
			var nBeginLen = history.data.length;
			var nPopLen = history.data.length - history.position;
			for (var i=1; i<nPopLen; i++){
				history.data.pop();
				history.bookmark.pop();
			}

			history.data[history.data.length] = textEdit.document.body.innerHTML;

			if (textEdit.document.selection.type != "Control"){
				history.bookmark[history.bookmark.length] = textEdit.document.selection.createRange().getBookmark();
			} else {
				var oControl = textEdit.document.selection.createRange();
				history.bookmark[history.bookmark.length] = oControl(0);
			}

			if (nBeginLen!=0){
				history.position++;
			}
		}
}

// 初始历史
function initHistory() {
	history.data.length = 0;
	history.bookmark.length = 0;
	history.position = 0;
}

// 返回历史
function goHistory(value) {
	saveHistory();
	// undo
	if (value == "Undo"){
		if (history.position > 0){
			textEdit.document.body.innerHTML = history.data[--history.position];
			setHistoryCursor();
		}
	// redo
	} else {
		if (history.position < history.data.length -1){
			textEdit.document.body.innerHTML = history.data[++history.position];
			setHistoryCursor();
		}
	}
}
// 设置当前书签
function setHistoryCursor() {
	if (history.bookmark[history.position]){
		r = textEdit.document.body.createTextRange()
		if (history.bookmark[history.position] != "[object]"){
			if (r.moveToBookmark(history.bookmark[history.position])){
				r.collapse(false);
				r.select();
			}
		}
	}
}
// end 007
function execCommand(command) {	
	if (format == "HTML"){
		setFocus();
		selectRange();
		if ((command == "Undo") || (command == "Redo"))
			goHistory(command)
			//document.execCommand(command);
		else{
			if (arguments[1]==null)				
				edit.execCommand(command);
			else
				edit.execCommand(command, false, arguments[1]);}
		textEdit.focus();
		if (RangeType != "Control") edit.select();
	}else{
		if(format == "ABC"){
		alert("操作无效,现在是HTML状态!请切换到普通状态,才能进行编辑操作");
		}
		if(format == "PREVIEW"){
		alert("操作无效,现在是预览状态!请切换到普通状态,才能进行编辑操作");
		}
	}	
}

//***辅助线
 var borderShown = 0
 function sBorders(){
  allTables = textEdit.document.body.getElementsByTagName("TABLE");
  for(i=0; i < allTables.length; i++){
   if(!borderShown)
    allTables[i].runtimeStyle.borderTop = allTables[i].runtimeStyle.borderLeft = "1px dotted #BFBFBF";
   else
    allTables[i].runtimeStyle.cssText = '';
       
   allRows = allTables[i].rows;
   for(y=0; y < allRows.length; y++){
    allCells = allRows[y].cells;
    for(x=0; x < allCells.length; x++)
     if(!borderShown)
      allCells[x].runtimeStyle.borderRight = allCells[x].runtimeStyle.borderBottom = "1px dotted #BFBFBF";
     else
      allCells[x].runtimeStyle.cssText = '';
   }
  }

  borderShown = borderShown ? 0 : 1;
  if(!borderShown)
   textEdit.document.body.innerHTML = textEdit.document.body.innerHTML;
 }

//判断表格属性
function isTableSelected(){
  textEdit.focus()
  if(textEdit.document.selection.type == "Control"){
   var oControlRange = textEdit.document.selection.createRange();
   if(oControlRange(0).tagName.toUpperCase() == "TABLE"){
    selectedTable = textEdit.document.selection.createRange()(0);
    return true;
   }	
  }
 }
function isCursorInTableCell(){
  textEdit.focus();
  if(document.selection.type != "Control"){
   var elem = document.selection.createRange().parentElement();
   while(elem.tagName.toUpperCase() != "TD" && elem.tagName.toUpperCase() != "TH"){
    elem = elem.parentElement
    if(elem == null)
     break
   }
   if(elem){
    selectedTD = elem
    selectedTR = selectedTD.parentElement
    selectedTBODY =  selectedTR.parentElement
    selectedTable = selectedTBODY.parentElement
    return true
   }
  }
 }
//修改表格
 function ModifyTable(sNewTable){
  if(isTableSelected() || isCursorInTableCell()){
   res = showModalDialog('tablemod.html', selectedTable, 'dialogWidth: 360px; dialogHeight: 200px; center: yes; resizable: no; scroll: no; status: no;');
   if(res){
    if(res.width)
     selectedTable.width = res.width;
    else
     selectedTable.removeAttribute('width',0);

    if(res.cellPadding)
     selectedTable.cellPadding = res.cellPadding;
    else
     selectedTable.removeAttribute('cellPadding',0);
    
    if(res.bgColor)
     selectedTable.bgColor = res.bgColor;
    else
     selectedTable.removeAttribute('bgColor',0);

    if(res.background)
     selectedTable.background = res.background;
    else
     selectedTable.removeAttribute('background',0);

		  if(res.cellSpacing)
     selectedTable.cellSpacing = res.cellSpacing;
    else
     selectedTable.removeAttribute('cellSpacing',0);

	  	if(res.border)
     selectedTable.border = res.border;
    else
     selectedTable.removeAttribute('border',0);
   }
  }
 }

//修改单元格
 function ModifyCell(){
  if(isCursorInTableCell()){
   res = showModalDialog('Cell.html', selectedTD, 'dialogWidth: 360px; dialogHeight: 225px; center: yes; resizable: no; scroll: no; status: no;');
   if(res){
    selectedTD.colSpan = res.colSpan;
    selectedTD.rowSpan = res.rowSpan;
    if(res.width)
     selectedTD.width = res.width;
    else
     selectedTD.removeAttribute('width',0);

    if(res.height)
     selectedTD.height = res.height;
    else
     selectedTD.removeAttribute('height',0);
    
    if(res.bgColor)
     selectedTD.bgColor = res.bgColor;
    else
     selectedTD.removeAttribute('bgColor',0);

    if(res.background)
     selectedTD.background = res.background;
    else
     selectedTD.removeAttribute('background',0);

		  if(res.align && !res.align.match(/^None$/i))
     selectedTD.align = res.align;
    else
     selectedTD.removeAttribute('align',0);

	  	if(res.vAlign && !res.vAlign.match(/^None$/i))
     selectedTD.vAlign = res.vAlign;
    else
     selectedTD.removeAttribute('vAlign',0);
   }
  }else{
   alert('修改单元格属性前,需将光标停留在需要修改的单元格中');
  }
 }
//表格修改功能
 function insrowabove(){
  if(isCursorInTableCell()){
   var numCols = 0
   allCells = selectedTR.cells
   for(var i=0;i<allCells.length;i++) 
    numCols = numCols + allCells[i].getAttribute('colSpan')
   var newTR = selectedTable.insertRow(selectedTR.rowIndex)
   for(i = 0; i < numCols; i++){
    newTD = newTR.insertCell()
    newTD.innerHTML = " "
   }
  }	
 }

 function insrowbelow(){
  if(isCursorInTableCell()){
   var numCols = 0
   allCells = selectedTR.cells
   for(var i=0;i<allCells.length;i++)
    numCols = numCols + allCells[i].getAttribute('colSpan')
   var newTR = selectedTable.insertRow(selectedTR.rowIndex+1)
   for (i = 0; i < numCols; i++){
    newTD = newTR.insertCell()
    newTD.innerHTML = " "
   }
  }
 }

 function deleterow(){
  if(isCursorInTableCell())
   selectedTable.deleteRow(selectedTR.rowIndex)
 }

 function deletecol(){
  if(isCursorInTableCell()){
   moveFromEnd = (selectedTR.cells.length-1) - (selectedTD.cellIndex)
   allRows = selectedTable.rows
   for(var i=0;i<allRows.length;i++){
    endOfRow = allRows[i].cells.length - 1
    position = endOfRow - moveFromEnd
    if(position < 0)
     position = 0
    allCellsInRow = allRows[i].cells
    if(allCellsInRow[position].colSpan > 1)
     allCellsInRow[position].colSpan = allCellsInRow[position].colSpan - 1
    else
     allRows[i].deleteCell(position)
   }
  }
 }

 function inscolafter(){
  if (isCursorInTableCell()) {
   moveFromEnd = (selectedTR.cells.length-1) - (selectedTD.cellIndex)
   allRows = selectedTable.rows
   for(i=0;i<allRows.length;i++){
    rowCount = allRows[i].cells.length - 1
    position = rowCount - moveFromEnd
    if(position < 0)
     position = 0
    newCell = allRows[i].insertCell(position+1)
    newCell.innerHTML = " "
   }	
  }
 }

 function inscolbefore(){
  if (isCursorInTableCell()){
   moveFromEnd = (selectedTR.cells.length-1) - (selectedTD.cellIndex)
   allRows = selectedTable.rows
   for(i=0;i<allRows.length;i++){
    rowCount = allRows[i].cells.length - 1
    position = rowCount - moveFromEnd
    if(position < 0)
     position = 0
    newCell = allRows[i].insertCell(position)
    newCell.innerHTML = " "
   }	
  }
 }

//图片功能
 function isImageSelected() {
  textEdit.focus()
  if (textEdit.document.selection.type == "Control") {
   var oControlRange = textEdit.document.selection.createRange();
   if (oControlRange(0).tagName.toUpperCase() == "IMG") {
    selectedImage = textEdit.document.selection.createRange()(0);
    return true;
   }	
  }
 }

 function sImgDlg(){
  res = showModalDialog('sImg.php', null, 'dialogWidth: 330px; dialogHeight: 180px; center: yes; resizable: no; scroll: no; status: no;');
  if(res == 'lib')
   res = showModalDialog('lib.php', null, 'dialogWidth: 770px; dialogHeight: 450px; center: yes; resizable: no; scroll: no; status: no;');
  if(res)
   return res;
 }

 function sNewImg(){
  if(isImageSelected())
   temp = selectedImage;
  else
   temp = 0;
  
  res = sImgDlg();
  if(res){
//   document.forms.imgUpl.nSel.outerHTML = '<select name=nSel>' + document.forms.imgUpl.nSel.innerHTML + '<option value=images/' + res.replace(/^.*\//ig, '') + '">' + res.replace(/^.*\//ig, '') + '</option></select>';
//   uplTd.style.display = 'block';

   textEdit.focus();
   textEdit.document.execCommand("InsertImage", false, res);
  
   if(isImageSelected() && temp){
    selectedImage.style.position = temp.style.position;
    selectedImage.style.zIndex = temp.style.zIndex;
    selectedImage.style.top = temp.style.top;
    selectedImage.style.left = temp.style.left;
    selectedImage.style.borderColor = temp.style.borderColor;
    selectedImage.border = temp.border;
    selectedImage.style.alt = temp.alt;
    selectedImage.hspace = temp.hspace;
    selectedImage.vspace = temp.vspace;
    selectedImage.align = temp.align;
   }
  }
 }

function sImgProps(){
  if(isImageSelected()){
   sPrePos = selectedImage.style.position;
   res = window.showModalDialog('sImgProp.php', selectedImage, 'dialogWidth: 360px; dialogHeight: 320px; center: yes; resizable: no; scroll: no; status: no;');
   if(res){
    for(key in res)
     if(key == 'style'){
      for(sub_key in res.style)
       selectedImage.style[sub_key] = res.style[sub_key];
     }else{
      selectedImage[key] = res[key];
     }

    if(!res.align)
     selectedImage.removeAttribute('align');

    if(sPrePos.match(/^absolute$/i) && !selectedImage.style.position.match(/^absolute$/i)){
     sFired = selectedImage.parentElement;
     while(!sFired.tagName.match(/^table$|^body$/i))
      sFired = sFired.parentElement;
     if(sFired.tagName.match(/^table$/i) && sFired.style.position.match(/absolute/i));
      sFired.outerHTML = selectedImage.outerHTML;
    }else if(!sPrePos.match(/^absolute$/i) && selectedImage.style.position.match(/^absolute$/i))
     selectedImage.outerHTML = '<table style="position: absolute;"><tr><td>' + selectedImage.outerHTML + '</td></tr></table>';
   }
  }else
   alert('编辑图片属性时,请首先选中一张图片');
 }
 
//007
 function isFlashSelected() {
  textEdit.focus()
  if (textEdit.document.selection.type == "Control") {
   var oControlRange = textEdit.document.selection.createRange();
   if (oControlRange(0).tagName.toUpperCase() == "OBJECT") {
    selectedFlash = textEdit.document.selection.createRange()(0);
    return true;
   }	
  }
 }

function sFlashProps(){
	if(isFlashSelected()){
   		sPrePos = selectedFlash.style.position;
   		flashvar = window.showModalDialog('sFlashProp.php', selectedFlash, 'dialogWidth: 400px; dialogHeight: 370px; center: yes; resizable: no; scroll: no; status: no;');
   		if(flashvar){
			flashvar = flashvar.split("*");
			var flash_path = flashvar[0];
			var flash_name = flashvar[1];
			var flash_border = flashvar[2];
			var flash_title = flashvar[3];
			var flash_width = flashvar[4];
			var flash_width_unit = flashvar[5];
			var flash_height = flashvar[6];
			var flash_height_unit = flashvar[7];
			var flash_hspace = flashvar[8];
			var flash_vspace = flashvar[9];
			var flash_autoplay = flashvar[10];
			var flash_menu = flashvar[11];
			var flash_loop = flashvar[12];
			var flash_font = flashvar[13];
			var flash_align = flashvar[14];
			var flash_quality = flashvar[15];
			var flash_scale = flashvar[16];
		
			var string = "<object codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" height=\"" + flash_height + flash_height_unit + "\" width=\"" + flash_width + flash_width_unit + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" name=\"" + flash_name + "\" hspace=\"" + flash_hspace + "\" vspace=\"" + flash_hspace + "\" title=\"" + flash_title + "\" border=\"" + flash_border + "\">";
				string += "<param name=\"_cx\" value=\"12700\">";
				string += "<param name=\"_cy\" value=\"8467\">";
				string += "<param name=\"FlashVars\" value=\"\">";
				string += "<param name=\"Movie\" value=\"" + flash_path + "\">";
				string += "<param name=\"Src\" value=\"" + flash_path + "\">";
				string += "<param name=\"WMode\" value=\"Window\">";
				string += "<param name=\"Play\" value=\"" + flash_autoplay +"\">";
				string += "<param name=\"Loop\" value=\"" + flash_loop +"\">";
				string += "<param name=\"Quality\" value=\"" + flash_quality + "\">";
				string += "<param name=\"SAlign\" value=\"" + flash_align + "\">";
				string += "<param name=\"Menu\" value=\"" + flash_menu + "\">";
				string += "<param name=\"Base\" value=\"\">";
				string += "<param name=\"AllowScriptAccess\" value=\"always\">";
				string += "<param name=\"Scale\" value=\"" + flash_scale + "\">";
				string += "<param name=\"DeviceFont\" value=\"" + flash_font  + "\">";
				string += "<param name=\"EmbedMovie\" value=\"0\">";
				string += "<param name=\"BGColor\" value=\"\">";
				string += "<param name=\"SWRemote\" value=\"\">";
				string += "<param name=\"MovieData\" value=\"\">";
				string += "<embed src=\"" + flash_path + "\" quality=\"" + flash_quality + "\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"" + flash_width + flash_width_unit + "\" height=\"" + flash_height + flash_height_unit + "\"></embed>";
				string += "</object>";
				
			selectedFlash.outerHTML = string;
		}
	}else
   		alert('编辑FLASH属性时,请首先选中一张FLASH');
 }

//查找
function findtext(searchval,retval){
 	selectRange();
    edit.collapse(false);
    if (edit.findText(searchval,1000000000,retval)) {
         edit.select();
		 findreplace()
    } else {
         var startfromtop = confirm("搜索完成，是否要从顶部开始重新搜索？");
         if (startfromtop){
             edit.expand("textedit");
             edit.collapse();
             edit.select();
             findtext(searchval,retval);
        } 
    }
}
 
//替换
function replacetext(searchval,strreplace,retval){
		selectRange();
        if (retval == 4){
            if (edit.text == searchval) edit.text = strreplace;
        } else {
            if (edit.text.toLowerCase() == searchval.toLowerCase()) edit.text = strreplace;
        }
        findtext(searchval,retval);
}

 function findreplace () {
 	var string =  window.showModalDialog('findreplace.php', null, 'dialogWidth: 320px; dialogHeight: 160px; center: yes; resizable: no; scroll: no; status: no;');
 	if (string) {
		string = string.split("*");
		var strsearch = string[0];
		var strreplace = string[1];
		var blnmatchcase = string[2];
		var blnmatchword = string[3];
		var type = string[4];
		var retval = string[5];
	}
	if (type == "find") {
		findtext(strsearch,retval);
	} else if (type == "replace") {
		replacetext (strsearch,strreplace,retval);
	}	
 }
//
 function sUplDlg(){
  res = showModalDialog('sUpl.php', null, 'dialogWidth: 330px; dialogHeight: 225px; center: yes; resizable: no; scroll: no; status: no;');
  if(res){
//   document.forms.fileUpl.nSel.outerHTML = "<select name=nSel>" + document.forms.fileUpl.nSel.innerHTML + "<option value=uploads/' + res + '>' + res + '</option></select>";
//   upfTd.style.display = "block";
  }
  textEdit.focus();
 }

 function sUplMng(){
  res = showModalDialog('sMgr.php', null, 'dialogWidth: 330px; dialogHeight: 225px; center: yes; resizable: no; scroll: yes; status: no;');
  if(res){
  }
 }
///////////////////

function swapModes(Mode) {	
	switch(Mode){
		case 1:
			if (format == "ABC"){
				textEdit.document.body.innerHTML = textEdit.document.body.innerText;
				textEdit.document.body.style.fontFamily = "";
				textEdit.document.body.style.fontSize ="";
			}
			else{
				initHTML = textEdit.document.body.innerHTML;
				initEditor();
			}
			format = "HTML";
			break;	
		case 2:
			if (format == "PREVIEW"){
				initHTML = textEdit.document.body.innerHTML;
				initEditor();
			}	
			textEdit.document.body.innerText = textEdit.document.body.innerHTML;
			textEdit.document.body.style.fontFamily = "Verdana";
			textEdit.document.body.style.fontSize = "9pt";
			format = "ABC";
			break;
		case 3:
			var strHTML = "";
			if(format == "ABC"){
				strHTML = textEdit.document.body.innerText;
				textEdit.document.body.style.fontFamily = "";
				textEdit.document.body.style.fontSize ="";				
			}
			else{
				strHTML = textEdit.document.body.innerHTML;				
			}			
			format = "PREVIEW";
			textEdit.document.designMode="Off";
			textEdit.document.open();
			textEdit.document.write(strHTML);
			textEdit.document.close();
			if(textEdit.document.styleSheets.length == 0){
				textEdit.document.createStyleSheet();
				var oSS = textEdit.document.styleSheets[0];
				//oSS.addRule("TABLE.ubb","border: 1px solid #A9A9A9;FONT-SIZE: 9pt; ");
				oSS.addRule("TABLE","FONT-SIZE: 9pt; ");
				//oSS.addRule("TD.ubb","border: 1px solid #A9A9A9;FONT-SIZE: 9pt; ");
				oSS.addRule("TD","FONT-SIZE: 9pt; ");
				oSS.addRule("BODY","FONT-SIZE: 9pt;");
				oSS.addRule("IMG","border: 0");
			}
			break;
		default:
			return(0);
	}
	textEdit.focus();
	return(1);
}


//get type
function specialtype(Mark,tiaojian){

	if (format == "HTML"){
		var strHTML;
		setFocus();
		selectRange();	
		if (RangeType == "Text"){
			strHTML = "<" + Mark + " " + tiaojian + " " + ">" + edit.text + "</" + Mark + ">"; 
			edit.pasteHTML(strHTML);
			textEdit.focus();
			edit.select();			
		}
	}
}
function pasteHTML(HTML){	
	if (format == "HTML"){
		setFocus();
		selectRange();
		edit.pasteHTML(HTML);
		textEdit.focus();
		if (RangeType != "Control") edit.select();
	}
}
function initEditor() {
	textEdit.document.designMode="On";
	textEdit.document.open();
	textEdit.document.write(initHTML);
	textEdit.document.close();
	initHTML = "";
	if(textEdit.document.styleSheets.length == 0){
		textEdit.document.createStyleSheet();
		var oSS = textEdit.document.styleSheets[0];
		//oSS.addRule("TABLE.ubb","border: 1px solid #A9A9A9;FONT-SIZE: 9pt; ");
		oSS.addRule("TABLE","FONT-SIZE: 9pt; ");
		//oSS.addRule("TD.ubb","border: 1px solid #A9A9A9;FONT-SIZE: 9pt; ");
		oSS.addRule("TD","FONT-SIZE: 9pt; ");
		oSS.addRule("IMG","border: 0");
		oSS.addRule("BODY","font-size: 9pt");
	}	
}

function init() {
	initEditor();
	with (parent){
		if (loaded){
			parent.status = "";
			/*with (parent.document){
				all.editor.style.display = "block";
				forms[0].body.style.display = "none";
				forms[0].body.title = "";
			}*/
		}
		else
			loaded = 1;	
	}
	textEdit.document.oncontextmenu = new Function("return showContextMenu(textEdit.event);");
}

initHTML = parent.parent.strHTML;
window.onload = init;