// Images 图片的路径
imagesDir = "../edit/icons/";

// 弹出窗口的路径
popupsDir = "../edit/popups/";

// 名片的高和宽
cardolWidth = 510;
cardolHeight = 295;

var cardEditorID = 'cardEditor';
														
var defaultBackground = '../edit/renderImage.php?imagename=photoimage/0000000000.jpg&imgWidth=510&imgHeight=300&cuteit=0';

var saveStatus = 0;
var designid = "";
// 列出所用字体
/*var Fonts = new Array();
	Fonts[0] = "Arial";
	Fonts[1] = "Sans Serif";
	Fonts[2] = "Tahoma";
	Fonts[3] = "Verdana";
	Fonts[4] = "Courier New";
	Fonts[5] = "Georgia";
	Fonts[6] = "Times New Roman";
	Fonts[7] = "Impact";
	Fonts[8] = "Comic Sans MS";*/

// 列出可用格式 
var BlockFormats = new Array("Address", "Bulleted List", "Definition", "Definition Term", "Directory List", "Formatted",
							"Heading 1","Heading 2","Heading 3", "Heading 4", "Heading 5", "Heading 6", 
							"Menu List", "Normal", "Numbered List");

// 列出所用字号
var FontSizes = new Array("0","9pt", "11pt", "12pt", "14pt", "18pt", "24tpt", "36pt","9pt","12pt","14pt","16pt","20pt","24pt","30pt","36pt");

var buttonNameGroup = new Array
						(	[],
						 	["forecolor","bold", "italic", "underline"],
							["alignleft", "aligncenter", "alignright"], 
							["undo", "redo","cut", "copy", "paste","viewSource","portrait"]
						);


var ToolbarList = {
	//Name            buttonID                 buttonTitle           buttonImage
	"bold":           ['Bold',                 '粗体',               imagesDir + 'bold.gif'],
	"italic":         ['Italic',               '斜体',             	 imagesDir + 'italics.gif'],
	"underline":      ['Underline',            '下划线',         	 imagesDir + 'underline.gif'],
	"strikethrough":  ['Strikethrough',        'Strikethrough',      imagesDir + 'strikethrough.gif'],
	"seperator":      ['',                     '',                   imagesDir + 'seperator.gif'],
	"subscript":      ['Subscript',            'Subscript',          imagesDir + 'subscript.gif'],
	"superscript":    ['Superscript',          'Superscript',        imagesDir + 'superscript.gif'],
	"justifyleft":    ['Justifyleft',          'Justifyleft',        imagesDir + 'justify_left.gif'],
	"justifycenter":  ['Justifycenter',        'Justifycenter',      imagesDir + 'justify_center.gif'],
	"justifyright":   ['Justifyright',         'Justifyright',       imagesDir + 'justify_right.gif'],
	"alignleft":   	  ['Alignleft',            '居左',       		 imagesDir + 'align_left.gif'],
	"aligncenter":    ['Aligncenter',          '居中',       		 imagesDir + 'align_center.gif'],
	"alignright":     ['Alignright',           '居右',       		 imagesDir + 'align_right.gif'],
	"unorderedlist":  ['InsertUnorderedList',  'InsertUnorderedList',imagesDir + 'list_unordered.gif'],
	"orderedlist":    ['InsertOrderedList',    'InsertOrderedList',  imagesDir + 'list_ordered.gif'],
	"outdent":        ['Outdent',              'Outdent',            imagesDir + 'indent_left.gif'],
	"indent":         ['Indent',               'Indent',             imagesDir + 'indent_right.gif'],
	"cut":            ['Cut',                  '剪切',               imagesDir + 'cut.gif'],
	"copy":           ['Copy',                 '复制',               imagesDir + 'copy.gif'],
	"paste":          ['Paste',                '粘贴',               imagesDir + 'paste.gif'],
	"forecolor":      ['ForeColor',            '颜色',          	 imagesDir + 'forecolor.gif'],
	"backcolor":      ['BackColor',            '背景色',          	 imagesDir + 'backcolor.gif'],
	"undo":           ['Undo',                 '撤消',               imagesDir + 'undo.gif'],
	"redo":           ['Redo',                 '重做',               imagesDir + 'redo.gif'],
	"inserttable":    ['InsertTable',          '插入表格',        	 imagesDir + 'insert_table.gif'],
	"background":     ['Background',           '更改背景图片',		 imagesDir + 'insert_picture.gif'],
	"insertimage":    ['InsertImage',          '插入图标',			 imagesDir + 'insert_icon.gif'],
	"inserttext":     ['InsertText',           '插入文字',			 imagesDir + 'insert_text.gif'],
	"createlink":     ['CreateLink',           '链接',				 imagesDir + 'insert_hyperlink.gif'],
	"viewSource":     ['ViewSource',           '原文件',			 imagesDir + 'view_source.gif'],
	"viewText":       ['ViewText',             '设计图',			 imagesDir + 'view_text.gif'],
	"help":           ['Help',                 'Help',               imagesDir + 'help.gif'],
	"save":           ['Save',                 'Save',               imagesDir + 'save.gif'],
	"saveas":         ['Saveas',               'Save as',          	 imagesDir + 'saveas.gif'],
	"selectfont":     ['SelectFont',           '选择字体',			 imagesDir + 'select_font.gif',		imagesDir + 'select_font_on.gif'],
	"selectsize":     ['SelectSize',           '选择大小',           imagesDir + 'select_size.gif',		imagesDir + 'select_size_on.gif'],
	"landscape":	  ['Landscape',				'横式名片',			 imagesDir + 'landscape.gif'],
	"portrait":		  ['Portrait',				'竖式名片',			 imagesDir + 'portrait.gif'],
	"preview":		  ['Preview',				'预览',				 imagesDir + 'preview.gif']
};

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement)
{
	HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) 
      			this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else 
				this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
};


var viewTextMode = 0;
var portraitMode = 0;
var portraitModeBack = 0;
var dropdownID = null;

function oo(ID){
	return document.getElementById(ID);
}

function generate_cardol(textareaID) 
{	
	var n = textareaID;
	oo(n).style.display = 'none'; 
	toolbarWidth = parseFloat(cardolWidth) + 2;

	var toolbar = '<table cellpadding="1" cellspacing="0" border="0" style="width:' + toolbarWidth + 'px;" id="toolBar_'+n+'" unselectable="on"><tr><td unselectable="on" class="toolbar">';

	for(var i=0; i<buttonNameGroup.length;i++) {

		if(buttonNameGroup[i]==='')	{
			toolbar += '<div class="toolbarnewline"></div>';
			continue;
		}

		toolbar += '<div class="toolbarblock"><table cellpadding="0" cellspacing="0" border="0"><tr><td><img src="' +ToolbarList["seperator"][2]+ '" border=0 width="3" hspace="2"></td>';

		if(i==0){
			toolbar += '<td><span id="FontSelect' + n + '"></span></td>';
			toolbar += '<td><span id="FontSizes'  + n + '"></span></td>';
		}

		var buttonName = buttonNameGroup[i];
    	for(var j=0; j<buttonName.length; j++){
	
	    	var buttonObj 			= ToolbarList[buttonName[j]];
		 	var buttonID            = buttonObj[0];
	     	var buttonTitle         = buttonObj[1];
	        var buttonImage         = buttonObj[2];
			
			if(buttonName[j] == "viewSource"){
		    	toolbar += '<td width=22>';
				toolbar += '<span id="HTMLMode' + n + '"><img src="'  +buttonImage+  '" border=0 title="' +buttonTitle+ '" id="' +n+'_'+buttonID+ '" class="button" onClick="formatText(\''+buttonID+'\',\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; " onmouseout="if(className==\'buttonOver\'){className=\'button\'};" width="20" height="20"></span>';
				toolbar += '<span id="textMode' + n + '"><img src="' + ToolbarList['viewText'][2] + '" border=0 title="'+ ToolbarList['viewText'][1] +'" id="' +n+'_'+ ToolbarList['viewText'][0] +'" class="button" onClick="formatText(\''+ ToolbarList['viewText'][0] +'\',\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; " onmouseout="if(className==\'buttonOver\'){className=\'button\'};"  width="20" height="20"></span>';
	      		toolbar += '</td>';
			}
			else if(buttonName[j] == "portrait"){
				toolbar += '<td width=22>';
				toolbar += '<span id="portraitMode' + n + '"><img src="'  + buttonImage +  '" border=0 title="' +buttonTitle+ '" id="' + n + '_' + buttonID+ '" class="button" onClick="formatText(\''+ buttonID +'\',\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; " onmouseout="if(className==\'buttonOver\'){className=\'button\'};"  width="20" height="20"></span>';
				toolbar += '<span id="landscapeMode' + n + '"><img src="' + ToolbarList['landscape'][2] + '" border=0 title="'+ ToolbarList['landscape'][1] +'"  id="'+n+'_'+ ToolbarList['landscape'][0] +'" class="button" onClick="formatText(\''+ ToolbarList['landscape'][0] +'\',\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; " onmouseout="if(className==\'buttonOver\'){className=\'button\'};"  width="20" height="20"></span>';
	      		toolbar += '</td>';
			}else
		    	toolbar += '<td width=22><img src="' +buttonImage+ '" border=0 title="' +buttonTitle+ '" id="' + n + '_' + buttonID+ '" class="button" nowClassName="button" onClick="formatText(\''+buttonID+'\',\'' + n + '\');" onmouseover="this.className=\'buttonOver\'; " onmouseout="this.className=this.nowClassName;" width="20" height="20"></td>';
    	}
		toolbar += "</tr></table></div>";
	}
	
	toolbar += '</td></tr></table>';
	
	var iframe = '<table cellpadding="0" cellspacing="0" border="0" style="width:' + cardolWidth + 'px; height:' + cardolHeight + 'px;border: 1px inset #CCCCCC; border-top: 0px;"><tr><td valign="top" >\n'
  	+ '<iframe frameborder="0" id="cardol' + n + '" scrolling="no"></iframe>\n'
  	+ '</td></tr></table>\n';

  	oo(n).insertAdjacentHTML("afterEnd", toolbar + iframe);
  	
	outputFontSelect(n);
	outputFontSizes(n); 
	outputColor('ForeColor',n); 
	outputColor('BackColor',n); 
	
	oo("textMode" + n).style.display = 'none'; 
	oo("landscapeMode" + n).style.display = 'none'; 
  	oo("cardol" + n).style.height = cardolHeight + "px";
  	oo("cardol" + n).style.width = cardolWidth + "px";

	var doc = oo("cardol" + n).contentWindow.document;
	doc.open();
	doc.write("<HTML><BODY style='margin:2px;' background='"+oo('c_background').value+"'>"+oo('c_content').value+"</BODY></HTML>");
	doc.close();

	rotateDesign(oo('c_portrait').value);
	doc.body.contentEditable = true;
	
	doc.designMode = "on";
	doc.execCommand("2D-position",false,true);
	doc.execCommand("MultipleSelection");
	doc.execCommand("LiveResize");	

	if (doc.attachEvent) 
	{
		for (var idx=0; idx < document.forms.length; idx++){
	  		document.forms[idx].attachEvent('onsubmit', function() { updateValues(); });
		}
		document.attachEvent('onmouseup', function() { if(dropdownID && ((event.srcElement.tagName!='IMG'&&event.srcElement.tagName!='BUTTON')||!oo('toolBar_'+n).contains(event.srcElement))){oo(dropdownID).style.display='none';}  });
		doc.attachEvent('onmouseup', function() { editor_buttons_on(n); });
		doc.attachEvent('onfocusout', function() { editor_content_changed(n); });
		document.attachEvent('onreadystatechange', function() { if(document.readyState=='complete') editor_content_changed(n);  });
	}
	else 
	{
		for (var idx=0; idx < document.forms.length; idx++){
			document.forms[idx].addEventListener('submit',function OnSubmit() { updateValues(); }, true);
		}
		doc.addEventListener('onmouseup',function OnMouseUp() {  editor_buttons_on(n); }, true);
		doc.addEventListener('onfocusout',function OnFocusout() { editor_content_changed(n); }, true);
		document.addEventListener('onreadystatechange',function OnReadystatechange() { if(document.readyState=='complete') editor_content_changed(n); }, true);
	}
};

function editor_content_changed(n){};

function editor_buttons_on(n){
	var buttonOnIDs = ["Bold","Italic","Underline","Strikethrough"];
	for(var i=0;i<buttonOnIDs.length;i++){
		var id = buttonOnIDs[i];
		if(oo(n+'_'+id)){
			if(oo("cardol" + n).contentWindow.document.queryCommandValue(id)){
				oo(n+'_'+id).className = oo(n+'_'+id).nowClassName = "buttonOn";
			}else{
				oo(n+'_'+id).className = oo(n+'_'+id).nowClassName = "button";
			}
		}
	}
	if(dropdownID) oo(dropdownID).style.display = 'none';
}

function formatText(id, n, selected) {
	oo("cardol" + n).contentWindow.focus();
	var formatIDs = new Array("FontSize","FontName","Bold","Italic","Underline","Subscript","Superscript","Strikethrough","Justifyleft","Justifyright","Justifycenter","InsertUnorderedList","InsertOrderedList","Indent","Outdent","ForeColor","BackColor","InsertImage","InsertTable","CreateLink","InsertText");
	for (var i = 0; i <= formatIDs.length;) {
		if (formatIDs[i] == id) {
			 var disabled_id = 1; 
		}
		i++;
	}	

	if (viewTextMode == 1 && disabled_id == 1) {
	  alert ("在HTML模式下，该功能无法使用。");	
	  return false;
	}

	if (id == "FontSize") {		
		fontsize(n,selected);
	}
	else if (id == "FontName") {
		oo("cardol" + n).contentWindow.document.execCommand("FontName", false, selected);
	}
	else if(id == 'ForeColor'||id == 'BackColor'){
		showColor(id,n);
		return true;
	}  
	else if(id == 'Alignleft'){
		alignBlock(n,'left');
	}
	else if(id == 'Aligncenter'){
		alignBlock(n,'center');
	}
	else if(id == 'Alignright'){
		alignBlock(n,'right');
	}
	else if (id == "Background") {
		openGallery(0);
	}	
	else if (id == "InsertImage") {
		openGallery(1);
	}
	else if(id == "InsertText"){
		var input = window.prompt("请输入文字:","");
		if(input==''||input==null) return false;
		var text = '<div style="position:absolute; LEFT:0px; TOP: 0px; WIDTH:120; HEIGHT:30; white-space:nowrap;">'+input+'</div>';
		insertHTMLEnd(text, n);
	}
	else if (id == "ViewSource") {
		viewSource(n);
	}
	else if (id == "ViewText") {
		viewText(n);
	}	
	else if (id == "Help") {
		window.open(popupsDir + 'about.html','popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=330');
	}	  
	else if (id == "Portrait"){
		rotateDesign(1); 
	}	  
	else if (id == "Landscape"){
		rotateDesign(0);  
	}
	else if(id=="Preview"){
		openPreview();
	}	  
	else{
		  oo("cardol" + n).contentWindow.document.execCommand(id, false, null);
	}
	editor_buttons_on(n);
};

function fontsize(n,size){
	var Editor = oo("cardol" + n).contentWindow;
	
	if(size==0) size=prompt('请输入字号(pt):',12)+'pt';
	if(size==parseInt(size)) Editor.document.execCommand("fontSize", false, size);
	else {
		Editor.document.execCommand("BackColor", false, "transparent");
		var html = Editor.document.body.innerHTML;
		html = html.replace(/<[^>]+>/mig,
				function(){
					var a = arguments;
					return a[0].replace(/BACKGROUND\-COLOR: transparent/mig,"FONT-SIZE:"+size);
				}
			);	
		Editor.document.body.innerHTML = html;
	}
}

function alignBlock(n,str){
	var doc=oo('cardol' + n).contentWindow.document;
	if (doc.selection.type == "Control"){ 
		var oControlRange = doc.selection.createRange();
		for (i = 0; i < oControlRange.length; i++)
		if(str=="left"){
			oControlRange(i).style.left="6px";
		}
		else if(str == "center"){
			var lefttmp=(cardolWidth-oControlRange(i).offsetWidth)/2
			oControlRange(i).style.left=lefttmp+"px";
		}
		else if(str == "right"){
			var lefttmp=cardolWidth-oControlRange(i).offsetWidth
			oControlRange(i).style.left=lefttmp+"px";
		}
	}
}

function insertHTML(html, n) {
  var browserName = navigator.appName;
	if (browserName == "Microsoft Internet Explorer") {	  
	  oo('cardol' + n).contentWindow.document.body.insertAdjacentHTML("afterBegin",html);   
	} 	 
	else {
	  var div = oo('cardol' + n).contentWindow.document.createElement("div");
		div.innerHTML = html;
		var node = insertNodeAtSelection(div, n);		
	}	
}

function insertHTMLEnd(html, n)
{
	var browserName = navigator.appName;
	if (browserName == "Microsoft Internet Explorer") {	  
	  oo('cardol' + n).contentWindow.document.body.insertAdjacentHTML("BeforeEnd",html);   
	}  
	else {
	  var div = oo('cardol' + n).contentWindow.document.createElement("div");
		div.innerHTML = html;
		var node = insertNodeAtSelection(div, n);		
	}
}


function insertNodeAtSelection(insertNode, n) {
  var sel = oo('cardol' + n).contentWindow.getSelection();

  var range = sel.getRangeAt(0);

  sel.removeAllRanges();

  range.deleteContents();

  var container = range.startContainer;
  var pos = range.startOffset;

  range=document.createRange();

  if (container.nodeType==3 && insertNode.nodeType==3) {
    container.insertData(pos, insertNode.nodeValue);
    range.setEnd(container, pos+insertNode.length);
    range.setStart(container, pos+insertNode.length);
  } 	
	else {
    var afterNode;
    
		if (container.nodeType==3) {
      var textNode = container;
      container = textNode.parentNode;
      var text = textNode.nodeValue;

      var textBefore = text.substr(0,pos);

      var textAfter = text.substr(pos);

      var beforeNode = document.createTextNode(textBefore);
      afterNode = document.createTextNode(textAfter);

      container.insertBefore(afterNode, textNode);
      container.insertBefore(insertNode, afterNode);
      container.insertBefore(beforeNode, insertNode);

      container.removeChild(textNode);
    } 
	  else {

      afterNode = container.childNodes[pos];
      container.insertBefore(insertNode, afterNode);
    }

    range.setEnd(afterNode, 0);
    range.setStart(afterNode, 0);
  }

  sel.addRange(range);
};

function _dec_to_rgb(value) {
  var hex_string = "";
  for (var hexpair = 0; hexpair < 3; hexpair++) {
    var myByte = value & 0xFF;            
    value >>= 8;                         
    var nybble2 = myByte & 0x0F;         
    var nybble1 = (myByte >> 4) & 0x0F;   
    hex_string += nybble1.toString(16);   
    hex_string += nybble2.toString(16);   
  }
  return hex_string.toUpperCase();
};


function outputFontSelect(n) {
	var FontSelectObj        = ToolbarList['selectfont'];
	var FontSelect           = FontSelectObj[2];
	var FontSelectOn         = FontSelectObj[3];
	
	Fonts.sort();
	var FontSelectDropDown = new Array;
	FontSelectDropDown[n] = '<table border="0" cellpadding="0" cellspacing="1"><tr><td onMouseOver="oo(\'selectFont' + n + '\').src=\'' + FontSelectOn + '\';" onMouseOut="oo(\'selectFont' + n + '\').src=\'' + FontSelect + '\';"><img src="' + FontSelect + '" id="selectFont' + n + '" width="85" height="20" onClick="showFonts(\'' + n + '\');"><br>';
	FontSelectDropDown[n] += '<span id="Fonts' + n + '" class="dropdown" style="width: 145px; display:none;">';
	
	for (var i = 0; i <= Fonts.length;) {
		if (Fonts[i]) {
			FontSelectDropDown[n] += '<button type="button" onClick="formatText(\'FontName\',\'' + n + '\',\'' + Fonts[i] + '\')\;" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 120px;"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family:' + Fonts[i] + '; font-size: 12px;">' + Fonts[i] + '</td></tr></table></button><br>';	
		}  
		i++;
	}
	FontSelectDropDown[n] += '</span></td></tr></table>';
	oo('FontSelect' + n).insertAdjacentHTML("afterBegin", FontSelectDropDown[n]);
};

function outputFontSizes(n) {

	var FontSizeObj        = ToolbarList['selectsize'];
	var FontSize           = FontSizeObj[2];
	var FontSizeOn         = FontSizeObj[3];
	var size_cn = "自定义,七号,六号,五号,四号,三号,二号,一号".split(',');

	var FontSizesDropDown = new Array;
	FontSizesDropDown[n] = '<table border="0" cellpadding="0" cellspacing="1"><tr><td onMouseOver="oo(\'selectSize' + n + '\').src=\'' + FontSizeOn + '\';" onMouseOut="oo(\'selectSize' + n + '\').src=\'' + FontSize + '\';"><img src="' + FontSize + '" id="selectSize' + n + '" width="49" height="20" onClick="showFontSizes(\'' + n + '\');"><br>';
	FontSizesDropDown[n] += '<span id="Sizes' + n + '" class="dropdown" style="width:80px; display:none;">';
	
	for (var i = 0; i <= FontSizes.length;) {
		if (FontSizes[i]) {
			FontSizesDropDown[n] += '<button type="button" onClick="formatText(\'FontSize\',\'' + n + '\',\'' + FontSizes[i] + '\')\;" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 100%; height:20px;">' + (size_cn[i]?size_cn[i]:FontSizes[i]) + '</button><br>';	
		}	  
		i++;
	}
	FontSizesDropDown[n] += '</span></td></tr></table>';
	oo('FontSizes' + n).insertAdjacentHTML("afterBegin", FontSizesDropDown[n]);
};

function outputColor(c,n){
	if(!oo(n+'_'+c.toLowerCase())) return false;
	var string = '<br><span id="' + c + n + '" class="dropdown" style="width: 200px;overflow:hidden;display:none;">';
	string += '<iframe name="'+c+'_win" src="../edit/popups/select_color.html?color=000000&command='+c+'&cardol=' + n +'" width="100%" height="140px" frameborder="0" scrolling="no" unselectable="on"></iframe></span>';
	oo(n+'_'+c.toLowerCase()).insertAdjacentHTML("afterEnd", string);
}

function showFonts(n) { 
	if (oo('Fonts' + n).style.display == 'block') {
		oo('Fonts' + n).style.display = 'none';
	}
	else {
		oo('Fonts' + n).style.display = 'block';
		if(dropdownID&&dropdownID!='Fonts' + n) oo(dropdownID).style.display = 'none';
		dropdownID = 'Fonts' + n;
	}
};

function showFontSizes(n) { 
	if (oo('Sizes' + n).style.display == 'block') {
		oo('Sizes' + n).style.display = 'none';
	}
	else {
		oo('Sizes' + n).style.display = 'block'; 
		if(dropdownID&&dropdownID!='Sizes' + n) oo(dropdownID).style.display = 'none';
		dropdownID = 'Sizes' + n;
	}
};

function showColor(c,n) {
	if (oo(c + n).style.display == 'block') {
		oo(c + n).style.display = 'none';
	}
	else {
		oo(c + n).style.display = 'block'; 	
		if(dropdownID&&dropdownID!=c + n) oo(dropdownID).style.display = 'none';
		dropdownID = c + n;
	}
};


function viewSource(n) {
  var getDocument = oo("cardol" + n).contentWindow.document;
  var browserName = navigator.appName;
		 
  if (browserName == "Microsoft Internet Explorer") {
    var iHTML = getDocument.body.innerHTML;
    getDocument.body.innerText = iHTML;
	}
  else {
    var html = document.createTextNode(getDocument.body.innerHTML);
    getDocument.body.innerHTML = "";
    getDocument.body.appendChild(html);
	}
  
  	oo('HTMLMode' + n).style.display = 'none'; 
	oo('textMode' + n).style.display = 'block';
	
	getDocument.body.style.fontSize = "12px";
	getDocument.body.style.fontFamily = "Courier New"; 
	
	viewTextMode = 1;
};

function viewText(n) { 
	var getDocument = oo("cardol" + n).contentWindow.document;
	var browserName = navigator.appName;
		 
	if (browserName == "Microsoft Internet Explorer") {
	var iText = getDocument.body.innerText;
	getDocument.body.innerHTML = iText;
	}
	else {
	var html = getDocument.body.ownerDocument.createRange();
	html.selectNodeContents(getDocument.body);
	getDocument.body.innerHTML = html.toString();
	}
	
	oo('textMode' + n).style.display = 'none'; 
	oo('HTMLMode' + n).style.display = 'block';
	
	getDocument.body.style.fontSize = "";
	getDocument.body.style.fontFamily = ""; 
	viewTextMode = 0;
};

function changeBackgroundImage(urlImg){
	var doc = oo('cardol' + cardEditorID).contentWindow.document;
	doc.body.background= urlImg;
}

function insertIcon(urlImg){
	var image = '<img src="' + urlImg + '" style="position:absolute; TOP: 0px; LEFT: 0px;" border="0">';
 	insertHTMLEnd(image, cardEditorID);
}

function updateValues(){
		var getDocument = oo("cardol" + cardEditorID).contentWindow.document;	
		if(currentSide==0){
			oo('c_content').value = getDocument.body.innerHTML;
			oo('c_background').value = getDocument.body.background;
			oo('c_portrait').value = portraitMode;
		}else{
			oo('c_contentBack').value = getDocument.body.innerHTML;
			oo('c_backgroundBack').value = getDocument.body.background;	
			oo('c_portraitBack').value = portraitModeBack;
		}
}


function openPreview(){
	updateValues();
	var myform = null;
	for(var i=0;i<document.forms.length;i++){
		if(document.forms[i].contains(oo('formArea'))){
			myform = document.forms[i];
		}
	}
	if(!myform){
		alert('找不到表单,文件代码有误.');
		return false;
	}
	var storeVar = ['action','target','method'];
	var news = ['../edit/preview.php','previewWin','post'];
	var stores = new Array();
	var myattributes = new Array();
	for(var i=0;i<storeVar.length;i++){
		for(var j=0;j<myform.attributes.length;j++){
			if(myform.attributes[j].name==storeVar[i]){
				stores[i] = myform.attributes[j].value;
				myform.attributes[j].value = news[i];	
				myattributes[myattributes.length] = j;
				break;
			}
		}
	}
	myform.submit();
	for(var j=0;j<myattributes.length;j++){
		myform.attributes[myattributes[j]].value = stores[j];
	}
}

function openGallery(type){
	window.open('../edit/show_gallery.php?type=' + type, 'popup', 'location=0,status=0,scrollbars=1,resizable=1,width=500,height=480');
}

function selectTemplate(){
	window.open('../edit/showTemplates.php','template','left='+(screen.width-400)+',location=0,status=0,scrollbars=0,resizable=1,width=380,height=520');
}

function templateSide(templateid){
	window.showModalDialog('../edit/showTemplates.php?action=side&templateid='+templateid,window,"dialogWidth: 270px; dialogHeight:230px; edge: Raised; center: Yes; help: No; resizable: No; status: No;");
}

function openTemplate(bg, html, mode,side,templateid) {
	if (viewTextMode == 1) {
	  alert ("在HTML模式下，该功能无法使用。");	
	  return false;
	}
	if(currentSide==side){
		rotateDesign(mode);
		var getDocument = oo("cardol" + cardEditorID).contentWindow.document;
		getDocument.body.background = bg;
		getDocument.body.innerHTML = html;
		editor_content_changed(cardEditorID);
	}else{
		var b = side?'Back':'';
		oo('c_background'+b).value = bg;
		oo('c_content'+b).value = html;
		oo('c_portrait'+b).value = mode;
	}
	if(templateid>=0) oo('c_templateid').value = templateid;
}

var currentSide = 0;
function swapSide(side){
	updateValues();
	var getDocument = oo("cardol" + cardEditorID).contentWindow.document;	
	if(side == 'backSide'){
		oo('frontSideLink').innerHTML = '正面';
		oo('backSideLink').innerHTML = '<strong>・背面</strong>';
		currentSide = 1;
		openTemplate(oo('c_backgroundBack').value,oo('c_contentBack').value,oo('c_portraitBack').value,currentSide,oo('c_templateid').value);
	}
	else{
		oo('frontSideLink').innerHTML = '<strong>・正面</strong>';
		oo('backSideLink').innerHTML = '背面';
		currentSide = 0;
		openTemplate(oo('c_background').value,oo('c_content').value,oo('c_portrait').value,currentSide,oo('c_templateid').value);
	}
}

var currentPortraitMode = 0;
function rotateDesign(portrait){
	
	if( portrait==1 ){
		oo('portraitMode' + cardEditorID).style.display = 'none'; 
		oo('landscapeMode' + cardEditorID).style.display = 'block';
		oo('portraitLink').innerHTML = '横式名片';
		oo('landscapeLink').innerHTML = '<strong>・竖式名片</strong>';
		if(currentSide==0) portraitMode = 1; else portraitModeBack = 1; 
		cardolWidth = 295;
		cardolHeight = 510;
		currentPortraitMode = 1;
	}
	else{
		oo('landscapeMode' + cardEditorID).style.display = 'none'; 
		oo('portraitMode' + cardEditorID).style.display = 'block';
		oo('portraitLink').innerHTML = '<strong>・横式名片</strong>';
		oo('landscapeLink').innerHTML = '竖式名片';		
		if(currentSide==0) portraitMode = 0; else portraitModeBack = 0; 
		cardolWidth = 510;
		cardolHeight = 295;
		currentPortraitMode = 0;
	}

	var getDocumentContainer = oo("cardol" + cardEditorID).parentNode.parentNode.parentNode.parentNode;
	getDocumentContainer.style.height = cardolHeight + "px";
  	getDocumentContainer.style.width = cardolWidth + "px";

	var getDocument = oo("cardol" + cardEditorID);
	getDocument.style.height = cardolHeight + "px";
  	getDocument.style.width = cardolWidth + "px";
	updateValues();

}