
var overwriteWithNode = (window.getSelection)?w3_overwriteWithNode:ie_overwriteWithNode;

function isTextNode(node) {
	return node.nodeType==3;
}


function rightPart(node, ix) {
	return node.splitText(ix);
}
function leftPart(node, ix) {
	node.splitText(ix);
	return node;
}

function ie_overwriteWithNode(editWindow, node) {
	var rng = editWindow.document.selection.createRange();
	var marker = writeMarkerNode(editWindow, rng);
	marker.appendChild(node);
	marker.removeNode(); // removes node but not children
}

// writes a marker node on a range and returns the node.
function writeMarkerNode(editWindow, rng) {
	var id = editWindow.document.uniqueID;
	var html = "<span id='" + id + "'></span>";
	rng.pasteHTML(html);
	var node = editWindow.document.getElementById(id);
	return node;
}

// overwrites the current selection with a node
function w3_overwriteWithNode(editWindow, node) {
	var rng = editWindow.getSelection().getRangeAt(0);
	rng.deleteContents();
	if (isTextNode(rng.startContainer)) {
		var refNode = rightPart(rng.startContainer, rng.startOffset)		
		refNode.parentNode.insertBefore(node, refNode);
	} else {
		if (rng.startOffset==rng.startContainer.childNodes.length) {
			refNode.parentNode.appendChild(node);
		} else {
			var refNode = rng.startContainer.childNodes[rng.startOffset];
			refNode.parentNode.insertBefore(node, refNode);
		}
	}	
}


var RichTextManager = Class.create({

	getSelection: function(w) {
		var userSelection;
		if (w.getSelection) {
			userSelection = w.getSelection();
		}
		else if (w.document.selection) { // should come last; Opera!
			userSelection = w.document.selection.createRange();
		}
		
		if (userSelection.text)	userSelection = userSelection.text;
		
		return userSelection;
	},
	
	getSelectionRange: function(w) {
		var userSelection;
		if (w.getSelection) {
			userSelection = w.getSelection();
		}
		else if (w.document.selection) { // should come last; Opera!
			userSelection = w.document.selection.createRange();
		}	
		
		if (userSelection.getRangeAt)
			return userSelection.getRangeAt(0);
		else { // Safari!
			var range = document.createRange();
			range.setStart(userSelection.anchorNode,userSelection.anchorOffset);
			range.setEnd(userSelection.focusNode,userSelection.focusOffset);
			return range;
		}
	},
	
	select: function(w,node) {
		
		var range = this.getSelectionRange(w);
		
	    //function to store range of current selection
	    if (range.selectNode) {
			range.selectNode(node);
		}
		if (range.moveToElementText) {
			range.moveToElementText(node);
		}
	},
	
	doCreate: function(richTextId,rawParams) {
		var hiddenField = $(richTextId);
		var content = "";
		if (hiddenField) content = hiddenField.defaultValue;
		if (!$(richTextId + '_iframe')) return;
		var w = $(richTextId + '_iframe').contentWindow;
		var doc = w.document;
		try {
			doc.designMode = "on";
		}
		catch(e) {
			setTimeout("$('" + richTextId + "_iframe').contentWindow.document.designMode = 'on';",100);
		}
		doc.open();
		doc.write('<html><head><title></title></head><body style="font-family: Verdana, sans-serif; font-size: 10px;' + rawParams + ';cursor: text;">' + content + '</body></html>');
		doc.close();
		
		// Registrar un evento en el submit, para actualizar el campo de texto asociado
		var frm=hiddenField.parentNode;
		while ( frm && frm.nodeName != 'FORM') {
			frm=frm.parentNode;
		}
		if( frm ) {
			Element.observe(frm,'ws:updateText',function(event){ richText.updateTextField(richTextId); });
		}
		//w.focus();
	},

	create: function(richTextId,rawParams) {
		setTimeout('richText.doCreate(\'' + richTextId + '\',\'' + rawParams + '\')',1000);
	},
	
	updateTextField: function(richTextId) {
		var hiddenField = $(richTextId);
		var iframe = $(richTextId + '_iframe');
		var w = iframe.contentWindow;
		hiddenField.value = w.document.body.innerHTML;
		//w.focus();
	},
	
	updateRichText: function(richTextId) {
		var hiddenField = $(richTextId);
		var iframe = $(richTextId + '_iframe');
		var w = iframe.contentWindow;
		w.document.body.innerHTML = hiddenField.value;
		//w.focus();
	},
	
	execCommand: function(richText,command,iface,params) {
		var w = $(richText + '_iframe').contentWindow;
		w.document.execCommand(command,iface,params);
		w.focus();
	},
	
	insertFile: function(richTextId) {
		system.getPopUp().setContent('Loading data...'); 
		system.getPopUp().setContentWithURL(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',
											{command:'printFilePicker',style:system.getCurrentStyle(),richTextId:richTextId});
		system.getPopUp().open();
	},
	
	insertImage: function(richTextId) {
		system.getPopUp().setContent('Loading data...'); 
		system.getPopUp().setContentWithURL(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',
											{command:'printImagePicker',style:system.getCurrentStyle(),richTextId:richTextId});
		system.getPopUp().open();
	},
	
	insertLink: function(richTextId) {
		system.getPopUp().setContent('Loading data...'); 
		system.getPopUp().setContentWithURL(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',
											{command:'printLinkPicker',style:system.getCurrentStyle(),richTextId:richTextId});
		system.getPopUp().open();
	},
	
	insertHTMLClip: function(richTextId) {
		system.getPopUp().setContent('Loading data...');
		system.getPopUp().setContentWithURL(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',
											{command:'printHTMLClipPicker',style:system.getCurrentStyle(),richTextId:richTextId});
		system.getPopUp().open();
	},

	insertActionText: function(richTextId,formId,command) {
		var params = $(formId).serialize(true);
		params.command = command;
		params.style = system.getCurrentStyle();
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',{
			method:'post',
			parameters:params,
			onSuccess:function(transport) {
				richText.insertAtEnd(richTextId,transport.responseText);
			}
		});
	},

	insertFileText: function(richTextId,formId) {
		var params = $(formId).serialize(true);
		params.command = 'getInsertFileText';
		params.style = system.getCurrentStyle();
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',{
			method:'post',
			parameters:params,
			onSuccess:function(transport) {
				richText.insertAtEnd(richTextId,transport.responseText);
			}
		});
	},


	insertImageText: function(richTextId,formId) {
		var params = $(formId).serialize(true);
		params.command = 'getInsertImageText';
		params.style = system.getCurrentStyle();
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',{
			method:'post',
			parameters:params,
			onSuccess:function(transport) {
				richText.insertAtEnd(richTextId,transport.responseText);
			}
		});
	},
	
	insertLinkText: function(richTextId,formId) {
		var params = $(formId).serialize(true);
		params.command = 'getInsertLinkText';
		params.style = system.getCurrentStyle();
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_rich_text_actions.php',{
			method:'post',
			parameters:params,
			onSuccess:function(transport) {
				richText.insertAtEnd(richTextId,transport.responseText);
			}
		});
	},

	insertAtEnd: function(richText,appendText) {
		var w = $(richText + '_iframe').contentWindow;
		w.document.body.innerHTML = w.document.body.innerHTML + appendText;
		w.focus();
	},
	
	setColor: function(richText,format) {
		var w = $(richText + '_iframe').contentWindow;
		w.document.execCommand('foreColor',false,format);
		w.focus();
	},

	setStyle: function(richText,format) {
		var w = $(richText + '_iframe').contentWindow;		
		w.document.execCommand('formatBlock',false,format);
		w.focus();
	},

	
	// setStyle: function(richText,format) {
	// 	var w = $(richText + '_iframe').contentWindow;
	// 	var userSelection = this.getSelection(w);
	// 	
	// 	switch (format) {
	// 		case 'p':
	// 			var elem = w.document.createElement("p");
	// 			elem.innerHTML = userSelection;
	// 			elem.className = 'textBlockParagraph';
	// 			break;
	// 		default:
	// 			w.document.execCommand('formatBlock',false,format);
	// 			w.focus();
	// 			return;
	// 			break;
	// 	}
	// 	
	// 	overwriteWithNode(w,elem);
	// 	this.select(w,elem);
	// 	w.focus();
	// },

	setFont: function(richText,font) {
		var w = $(richText + '_iframe').contentWindow;
		if (!w) return;
		w.document.execCommand('fontname',false,font);
		w.focus();
	},

	setFontSize: function(richText,size) {
		var w = $(richText + '_iframe').contentWindow;
		if (!w) return;
		w.document.execCommand('fontsize',false,size);
		w.focus();
	},
	
	showText: function(richTextId) {
		this.updateRichText(richTextId);
		$(richTextId + '_iframeContainer').show();
		$(richTextId + '_warningMessage').hide();
		$(richTextId).hide();
		$('richTextTabButonText_' + richTextId).className = 'richTextTabButtonSelected';
		$('richTextTabButonHTML_' + richTextId).className = 'richTextTabButton';
	},
	
	showHTML: function(richTextId) {
		this.updateTextField(richTextId);
		$(richTextId + '_iframeContainer').hide();
		$(richTextId).show();
		$('richTextTabButonText_' + richTextId).className = 'richTextTabButton';
		$('richTextTabButonHTML_' + richTextId).className = 'richTextTabButtonSelected';
	}
});

var richText = new RichTextManager();