var xdoc;
var xwin;
#var viewMode;

function toggleMode(e,outer)
{
	spellcheck_markup_removeall();	

	if(!outer){
		if(!e) e=window.event;
		var outer=target(e);
		while(!outer.eframe) outer=outer.parentNode;
	}
	xwin=outer.eframe.contentWindow;
#	xwin=sw.active.field_eframe.contentWindow;

	xdoc=xwin.document;
	
 // change the display styles
  if(outer.eframe.viewMode == 2){
    xdoc.body.style.fontFamily = '';
    xdoc.body.style.fontSize = '';
    xdoc.body.style.color = '';
    xdoc.body.style.fontWeight = '';
    xdoc.body.style.backgroundColor = '';
#    document.getElementById(this.instance_name+'_toolbars').style.visibility='visible';
  }else{
    xdoc.body.style.fontFamily = 'monospace';
    xdoc.body.style.fontSize = '10pt';
    xdoc.body.style.color = '#000';
    xdoc.body.style.backgroundColor = '#fff';
    xdoc.body.style.fontWeight = 'normal';
#    document.getElementById(this.instance_name+'_toolbars').style.visibility='hidden';
  }

 // do the content swapping
  if(isMSIE()){
    _toggle_mode_ie(outer);
  }else{
    _toggle_mode_gecko(outer);
  }
  set_sendmode_html();
}

/**
* WYSIWYG_Editor::_toggle_mode_ie
*
* Toggles between design view and source view in the IFRAME element for MSIE
**/
function _toggle_mode_ie(outer){
  if(outer.eframe.viewMode == 2){
    xdoc.body.innerHTML = xdoc.body.innerText;
    xwin.focus();
    outer.eframe.viewMode = 1; // WYSIWYG
	outer.field_switch.value="$$st_edit_markup$$";
  }else{
    xdoc.body.innerText = xdoc.body.innerHTML;
    xwin.focus();
    outer.eframe.viewMode = 2; // Code
	outer.field_switch.value="$$st_edit_html$$";
  }
}

/**
* WYSIWYG_Editor::_toggle_mode_gecko
*
* Toggles between design view and source view in the IFRAME element for Gecko browsers
**/
function _toggle_mode_gecko(outer)
{
  if(outer.eframe.viewMode == 2){
    var html = xdoc.body.ownerDocument.createRange();
    html.selectNodeContents(xdoc.body);
    xdoc.body.innerHTML = html.toString();
    xwin.focus();
    outer.eframe.viewMode = 1; // WYSIWYG
	outer.field_switch.value="$$st_edit_markup$$";
}else{
    var html = document.createTextNode(xdoc.body.innerHTML);
    xdoc.body.innerHTML = '';
    xdoc.body.appendChild(html);
    xwin.focus();
    outer.eframe.viewMode = 2; // Code
	outer.field_switch.value="$$st_edit_html$$";
  }
}


function isMSIE()
{
  if(typeof(document.all)=='object'){
    return true;
  }else{
    return false;
  }
}


function init_editor(id, cb)
{
	if (pref.editor_textonly){
		el = dge('x'+id);
		if(!el) return;
		el.innerHTML = '<textarea id="txtframe" class="no_round plaintext_editor"></textarea>';
		class_add(el.tbar.parentNode,'hidden');
		if(cb!=U) cb();
		return;
	}
	
	eid = dge(id);	
	ew = eid.contentWindow;
	if(isChrome){
# 		In theory modern browsers support [contentEditable="true"] and older browsers [designMode="On"]
# 		In practise [desigMode] seems fine for all except Chrome that need [contentEditable] to make
#		make spellchecker work... without [designMode] as well the focus handling gets broken though?!
		ew.document.body.contentEditable = "true"
	}
	ew.document.designMode = "On";
	cb_when_loaded(ew, cb);
	return ew;
}

var delayed_ew, delayed_cb;
function cb_when_loaded(ew, cb)
{
	if(cb==U) return;
	delayed_ew = ew;
	delayed_cb = cb;
	try_cb();
}
function try_cb()
{
	var ew = delayed_ew;
	if(ew==U || ew.document==U || ew.document.body==U){
		setTimeout(try_cb,10);
		return;
	}
	if(delayed_cb!=U) delayed_cb();
}

var dm=true;
function toggle_editor(id)
{
	eid = document.getElementById(id);	
	ew = eid.contentWindow;
	if(dm/*true||ew.document.designMode == "On"*/){
		dbg('TOGGLE OFF')
		if(isChrome){
			ew.document.body.contentEditable = "false";
		}
		ew.document.designMode = "Off";
	}else{
		dbg('TOGGLE ON')
		if(isChrome){
			ew.document.body.contentEditable = "true";
		}
		ew.document.designMode = "On";
	}
	dm=!dm;
}

function ed_mousedown(e)
{
	t=target(e);
		
	if(t.getAttribute('menu')=='true'){
		var outer=t;
		while(!outer.eframe) outer=outer.parentNode;
		var m=ed_show_menu(t.className);
		m.eframe=outer.eframe;
		if(isIE) ignore_one_hide=true;
		do_menu_show('ed_menu_'+t.className,e,true);
		dge('ed_menu_'+t.className)._hide_sel=t;
	}
  	return stopEvent(e);
}

function ed_show_menu(id){
	var o=dge('ed_menu_'+id);
	if (!o){
		var o=document.createElement("div");
		o.className = 'xmenu';
		o.id = 'ed_menu_'+id;
		if (id=='fontname'){
			o.innerHTML='<a href="#" class="fontname" param="arial,san-serif">Arial</a>'+
						'<a href="#" class="fontname" param="comic sans ms,san-serif">Comic Sans MS</a>'+
						'<a href="#" class="fontname" param="courier new,monospace">Courier New</a>'+
						'<a href="#" class="fontname" param="garamond,serif">Garamond</a>'+
						'<a href="#" class="fontname" param="helvetica,san-serif">Helvetica</a>'+
						'<a href="#" class="fontname" param="tahoma,san-serif">Tahoma</a>'+
						'<a href="#" class="fontname" param="times new roman,serif">Times New Roman</a>'+
						'<a href="#" class="fontname" param="verdana,san-serif">Verdana</a>';

		}else if (id=='fontsize'){
			o.innerHTML='<a href="#" class="fontsize" param="1" >8 pt</a>'+
						'<a href="#" class="fontsize" param="2">10 pt</a>'+
						'<a href="#" class="fontsize" param="3">12 pt</a>'+
						'<a href="#" class="fontsize" param="4">14 pt</a>'+
						'<a href="#" class="fontsize" param="5">16 pt</a>'+
						'<a href="#" class="fontsize" param="6">24 pt</a>'+
						'<a href="#" class="fontsize" param="7">30 pt</a>';
		}else if (id=='forecolor' || id=='backcolor'){
			o.innerHTML='<table onmousedown="stopEvent(event)" onmouseup="ed_color_select(event,\''+id+'\')">'+ed_color_swatches(5,'labels')+'</table>';

		}else if (id=='lists'){
			o.innerHTML='<a href="#" class="insertorderedlist" param="1"><div class="xmenu_icon"></div> $$st_edit_ol_tt$$</a>'+
						'<a href="#" class="insertunorderedlist" param="7"><div class="xmenu_icon"></div> $$st_edit_ul_tt$$</a>';

		}else if (id=='layouttext'){
			o.innerHTML='<a href="#" class="insertorderedlist" param="1"><div class="xmenu_icon"></div> $$st_edit_ol_tt$$</a>'+
						'<a href="#" class="insertunorderedlist" param="7"><div class="xmenu_icon"></div> $$st_edit_ul_tt$$</a>'+
						'<a href="#" class="justifyleft" param="1"><div class="xmenu_icon"></div> $$st_edit_left_tt$$</a>'+
						'<a href="#" class="justifycenter" param="2"><div class="xmenu_icon"></div> $$st_edit_center_tt$$</a>'+
						'<a href="#" class="justifyright" param="3"><div class="xmenu_icon"></div> $$st_edit_right_tt$$</a>'+
						'<a href="#" class="indent" param="6"><div class="xmenu_icon"></div> $$st_edit_indent_tt$$</a>'+
						'<a href="#" class="outdent" param="7"><div class="xmenu_icon"></div> $$st_edit_outdent_tt$$</a>';

		}else if (id=='insertsmiley'){
			o.innerHTML='<table onmousedown="stopEvent(event)" onmouseup="ed_smiley_select(event,\''+id+'\')">'+ed_smiley_swatches(5,'labels')+'</table>';
			o.className += ' xmenu_wider';

		}else{
			o.innerHTML="boohoo..."
		}
		o.onmouseup=ed_click;
		o.onmouseout=function(e){if(!e) e=window.event; menu_action_mouseout(e,o.id)}; 
		o.onmouseover=function(e){if(!e) e=window.event; menu_action_mouseover(event,o.id)};

#		o.innerHTML='Some guff';
		document.body.appendChild(o);
	}
	return o;
}

#	WARNING: label colors also defined in swm.c	 (both definitions should match)
var label_cols= [	\
	["#F1F5EC","#B2D1C1",""],["#FFE3E3","#F0B2B2",""],["#F3E7B3","#C4AD4C",""],["#D3E2C3","#98BB74",""],["#C0D6FF","#6B9EFF",""],\
	["#E8EDF6","#CDD2DA",""],["#FDE9F4","#DACACF",""],["#FFF0E1","#F9D4B2",""],["#FFFFD4","#D0D0C0",""],["#DFE2FF","#B2B2F0",""],\
	["#D7C8FA","#D7C8FA",""],["#F0A3A3","#F0A3A3",""],["#F2C98F","#F2C98F",""],["#A9CC87","#A9CC87",""],["#8CB4FF","#8CB4FF",""]];

function ed_colors(){
 	return label_cols.concat([	\
		["purple","#999",""],["red","#999",""],["yellow","#999",""],["green","#999",""],["blue","#999",""],\
		["white","#999",""],["#aaa","#999",""],["#777","#999",""],["#444","#999",""],["black","#999",""]]);
}
function ed_color_select(e,id)
{
	var cols=ed_colors();
	var el=target(e);
	var picked=el.getAttribute('pickid');
	if(!picked) return;
	ed_click2(e,id,cols[picked][0]);
}
function ed_color_swatches(per_line)
{
	var cols=ed_colors();
	var txt='';
	for(var i=0;i<cols.length;i++){
  		if( i%per_line == 0 )txt += '<tr>'; 	
		txt+='<td class="swatch_hover"><div class="swatch" style="background:'+cols[i][0]+';border:1px solid '+cols[i][1]+';" pickid="'+i+'"></div>';
	}
	return txt;
}
function ed_smiley_select(e,id)
{
	dbg('smiley selected');
	var el=target(e);
	var picked=el.getAttribute('pickid');
dbg('PICKED'+picked);
	if(!picked) return;
	editor_add_img('||www_base||shared/emoticons/'+picked+'.png?||vz||&remo='+picked);
	if(window.set_sendmode_html) set_sendmode_html();	
	smiley_selected();
}
function ed_smiley_swatches()
{
	var txt='';
	for(var j=1;j<=5;j++){ 
		txt += '<tr>'; 	
		for(var i=1;i<=5;i++){
			txt+='<td class="swatch_hover"><div class="emo_swatch" style="background: url(||www_base||shared/emoticons/e'+j+i+'.png?||vz||) no-repeat;border:1px solid clear;" pickid="e'+j+i+'"></div>';
		}
	}
	return txt;
}


# *** Actually execute command in the html editor ***
function editor_do(cmd,param)
{
	xwin=(sw.active ? sw.active.field_eframe.contentWindow : document.getElementById('eframe1').contentWindow);
#	xdoc=xwin.document;
  	xwin.document.execCommand(cmd,false, param);
  	xwin.focus();
  	return false;
}

# Editor toolbar click handling events which never get outside these DOM elements
# generic handler for all single action html editor items
function ed_click(e,param,t)
{
	if(!e) e=window.event;
	t=target(e);
	if(t.className=='xmenu_icon') t=t.parentNode;
	var outer=t;
	while(!outer.eframe) outer=outer.parentNode;
	xwin=outer.eframe.contentWindow;
	xwin.focus();
	if (t.tagName.toLowerCase()=="a" && t.getAttribute('menu')!='true'){
		if(t.className=='createlink'){

#			if(ed_insert_smarts()) return;

			if(isIE){
				xwin.document.execCommand('createlink',false, undefined);
			}else{
				var link_fn=function(val){
					if (!val) return;
					xwin.focus();
					xwin.document.execCommand('createlink',false, val);
#					kk  =   xwin.document.selection.createRange();  
#					tt  =   xwin.document.selection.createRange().text ;      
#					str =  "<a href=' " +val+ " ' target='_blank' >aaa</a>";
#					kk.pasteHTML(str); 								
				};
				if(window.x_prompt){
					x_prompt("Url to insert as link :","",link_fn);
				}else{
					var x=prompt("Url to insert as link :");
					link_fn(x);
				}
			}
		}else if(t.className=='insertimage'){
			image_dialog();
		}else{
			var param=t.getAttribute('param');
			if(param==null) param=undefined;
			xwin.document.execCommand(t.className,false, param);
		}
		if (t.parentNode._hide_sel) class_remove(t.parentNode._hide_sel,'hoverjs');
		if(window.set_sendmode_html && t.className!='removeformat') set_sendmode_html();
#		if(t.className=='removeformat' && get_range_std(get_selection_std(xwin))==null) quote_breakout();
	}
  	stopEvent(e);
}
function ed_click2(e,cmd,param,xwin)
{
	if(!e) e=window.event;
	t=target(e);
	var outer=t;
	while(!outer.eframe) outer=outer.parentNode;
	xwin=outer.eframe.contentWindow;
	xwin.focus();
	xwin.document.execCommand(cmd,false, param);
	if(window.set_sendmode_html) set_sendmode_html();
}


# Anything that needs more specialised action for some reason
function ed_click_ex(e,cmd,param)
{
	xwin=(sw.active ? sw.active.field_eframe.contentWindow : document.getElementById('eframe1').contentWindow);
#	xdoc=xwin.document;
  	xwin.focus();
  	xwin.document.execCommand(cmd,false, param);
  	return stopEvent(e);
}

function ed_spell_check(e)
{
	// Handle editor window only spellchecks
	// Do whatever it takes to setup a generic request etc
	// Get editor window and send off as a spellcheck request
//	if(!e) e=window.event;
//	var outer=target(e);
//	while(!outer.eframe) outer=outer.parentNode;
//	xwin=outer.eframe.contentWindow;
//	marijn_check_spelling('foobar',xwin)	

	// Just do surgeweb message spellchecks for now...
	main_message_spellcheck(e);
}
