//-----------------------------------------------------------------------------
// XET Toolkit 
// Copyright (c) 2006-2007 Xavier Amado (xavier@theadfirm.com || xamado@gmail.com)
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Editor v0.5
// XETEditor is a rich text editor that can be used to input rich content
// into a website replacing the standard textarea element of a form.
// The XETEditor can replace a textarea and then post the contents back to the 
// hidden textarea that it replaced, so it works perfectly inside a standard form
//-----------------------------------------------------------------------------

var styleSheet = configBaseURL + "styleEditor.css";

var tbData = new Array();
tbData[0] = new Array('select', 'formatblock', 'Formatting', new Array('Paragraph','Heading 1', 'Heading 2', 'Subheading', 'Note'), new Array('<p>','<h1>','<h2>','<h3>','<pre>'));
tbData[1] = new Array('select', 'fontsize', 'Size', new Array('1','2','3','4','5','6','7'), new Array('1','2','3','4','5','6','7'));
tbData[2] = new Array('separator', 'images/editor/separator.gif');
tbData[3] = new Array('button', 'bold', 'Bold', 'images/editor/bold.gif', true);
tbData[4] = new Array('button', 'italic', 'Italic', 'images/editor/italic.gif', true);
tbData[5] = new Array('button', 'underline', 'Underline', 'images/editor/underline.gif', true);
tbData[6] = new Array('separator', 'images/editor/separator.gif');
tbData[7] = new Array('button', 'justifyleft', 'Justify Left', 'images/editor/justifyleft.gif', true);
tbData[8] = new Array('button', 'justifycenter', 'Justify Center', 'images/editor/justifycenter.gif', true);
tbData[9] = new Array('button', 'justifyright', 'Justify Right', 'images/editor/justifyright.gif', true);
tbData[10]= new Array('separator', 'images/editor/separator.gif');
tbData[11]= new Array('button', 'insertorderedlist', 'Ordered List', 'images/editor/orderedlist.gif', false);
tbData[12]= new Array('button', 'insertunorderedlist', 'Unordered List', 'images/editor/unorderedlist.gif', false);
tbData[13]= new Array('separator', 'images/editor/separator.gif');
tbData[14]= new Array('button', 'outdent', 'Outdent', 'images/editor/outdent.gif', false);
tbData[15]= new Array('button', 'indent', 'Indent', 'images/editor/indent.gif', false);
tbData[16]= new Array('separator', 'images/editor/separator.gif');
tbData[17]= new Array('button', 'runimageselector', 'Insert Image', 'images/editor/image.gif', false);
tbData[18]= new Array('button', 'runfileselector', 'Insert File', 'images/editor/file.gif', false);
tbData[19]= new Array('button', 'insertlink', 'Insert Link', 'images/editor/link.gif', false);
tbData[20]= new Array('separator', 'images/editor/separator.gif');
tbData[21]= new Array('button', 'undo', 'Undo', 'images/editor/undo.gif', false);
tbData[22]= new Array('button', 'redo', 'Redo', 'images/editor/redo.gif', false);

var gImageUploaderURL = "";
var gFileUploaderURL = "fileUploader.php";

function xet_richtexteditor_init(imageUploaderURL)
{
	var textarea = document.getElementById("editor_replace");
	if(!textarea)
		return;
		
	// Go get daddy
	var parent = textarea.parentNode;
		
	// Grab the value of the textarea, we need that
	var value = textarea.value;
		
	// Create the rich text editor
	var editor = xet_richtexteditor_new(value);		
	parent.insertBefore(editor, textarea);
		
	// Hide! the textarea (we are going to use it to post back with the form)
	textarea.style.display = "none"; 
	
	gImageUploaderURL = imageUploaderURL;	
}

function xet_richtexteditor_init_textarea(textarea, imageUploaderURL)
{
	// Go get daddy
	var parent = textarea.parentNode;
		
	// Grab the value of the textarea, we need that
	var value = textarea.value;
		
	// Create the rich text editor
	var editor = xet_richtexteditor_new(value);		
	parent.insertBefore(editor, textarea);
		
	// Hide! the textarea (we are going to use it to post back with the form)
	textarea.style.display = "none"; 
	
	gImageUploaderURL = imageUploaderURL;	
}

function xet_richtexteditor_on_clicked()
{
	// Grab the contentWindow
	var win = document.getElementById("editor").contentWindow;
	
	// Untoggle all buttons by default
	for(var i = 0; i < tbData.length; i++)
	{
		if(tbData[i][4] != true)
			continue;
		
		var button = document.getElementById(tbData[i][1]);
		button.setAttribute("class", "tb_button");
		button.setAttribute("className", "tb_button");
	}
	
	// Get current selection
	var sel = win.getSelection();

	// Get the first range of the selection
	var range = sel.getRangeAt(0);
   
	// Get the end container of the selection
	var container = range.endContainer;
	
	var hasAlignment = false;

	if(container.nodeType == 1)
		var node = container;
	else var node = container.parentNode;
	
	while(node && node.tagName.toLowerCase() != "body")
	{
		var tag = node.tagName.toLowerCase();
		
		if(tag == "b") 
		{
			var button = document.getElementById("bold");
			button.setAttribute("class", "tb_button_selected");
			button.setAttribute("className", "tb_button_selected");
		}
		else if(tag == "i") 
		{
			var button = document.getElementById("italic");
			button.setAttribute("class", "tb_button_selected");
			button.setAttribute("className", "tb_button_selected");
		}
		else if(tag == "u") 
		{
			var button = document.getElementById("underline");
			button.setAttribute("class", "tb_button_selected");
			button.setAttribute("className", "tb_button_selected");
		}
		else if(tag == "div" && !hasAlignment)
		{
			var parent = node.parentNode;
			if(parent.getAttribute("align") == "left")
				var button = document.getElementById("justifyleft");
			else if(parent.getAttribute("align") == "center")
				var button = document.getElementById("justifycenter");
			else if(parent.getAttribute("align") == "right")
				var button = document.getElementById("justifyright");
			else var button = null;
			
			if(button) {
				button.setAttribute("class", "tb_button_selected");
				button.setAttribute("className", "tb_button_selected");
				
				hasAlignment = true;
			}		
		}
		
		node = node.parentNode;
	}
}

function xet_richtexteditor_new(value)
{
	// Outer container
	var container = document.createElement("div");
	container.setAttribute("class", "editor");
	container.setAttribute("className", "editor");
	
	// Toolbar
	var toolbar = document.createElement("div");
	container.appendChild(toolbar);
	toolbar.setAttribute("class", "toolbar");
	toolbar.setAttribute("className", "toolbar");
	
	// Toolbar buttons now
	for(var i = 0; i < tbData.length; i++)
	{
		var data = tbData[i];

		if(data[0] == 'button')
		{
			button = document.createElement("img");	
			button.setAttribute("class", "tb_button");
			button.setAttribute("className", "tb_button");
			button.setAttribute("src", data[3]);
			button.setAttribute("alt", data[2]);
			button.setAttribute("id", data[1]);

			// Store our needed values
			button.toggable = data[4];
			
			// Bind the command clicked event
			if(window.addEventListener) { // Mozilla
				button.addEventListener('click', xet_richtexteditor_on_command_clicked, false);
			} else { // IE
				button.attachEvent('onclick', xet_richtexteditor_on_command_clicked);
			}

			toolbar.appendChild(button);
		}
		else if(data[0] == 'select')
		{
			select = document.createElement("select");
			select.setAttribute("class", "tb_select");
			select.setAttribute("className", "tb_select");
			select.setAttribute("id", data[1]);
			
			// Bind the on changed event
			if(window.addEventListener) { // Mozilla
				select.addEventListener('change', xet_richtexteditor_on_command_selected, false);
			} else { // IE
				select.attachEvent('onchange', xet_richtexteditor_on_command_selected);
			}
			
			// Add a header			
			var option = document.createElement("option");
			option.innerHTML = data[2];
			select.appendChild(option);
			
			// Add all the options
			for(var j = 0; j < data[3].length; j++)
			{
				var option = document.createElement("option");			
				option.innerHTML = data[3][j];
				option.setAttribute("value", data[4][j]);
	
				select.appendChild(option);
			}
			
			toolbar.appendChild(select);
		}
		else if(data[0] == 'separator')
		{
			var sep = document.createElement("img");
			sep.setAttribute("src", data[1]);
			sep.setAttribute("class", "tb_separator");
			sep.setAttribute("className", "tb_separator");
			
			toolbar.appendChild(sep);
		}
	}
	
	// Editable iframe
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "editor");
	iframe.setAttribute("class", "editor");
	iframe.setAttribute("className", "editor");
	container.appendChild(iframe);

	var onLoadFrame = function() 
	{
		setTimeout(function() 
		{
			// Need to re-get the iframe
			iframe = document.getElementById("editor");
			editorDoc = iframe.contentWindow.document || iframe.contentDocument;
			if(editorDoc == null)
				alert("Houston, we have a problem.");
		
			// Fx workaround: delay modifying editorDoc.body right after iframe onload event
			editorDoc.body.innerHTML = value;
			editorDoc.designMode = 'on';

			// Lame way for checking for firefox, i know.			
			if(editorDoc.addEventListener) {
				editorDoc.execCommand("styleWithCSS", false, false);
				editorDoc.body.previousSibling.innerHTML = '<link href="'+styleSheet+'" rel="stylesheet" type="text/css" />';
			}
			
			// Bind the mouse click to update the toolbars
			if (editorDoc.addEventListener) {
				editorDoc.addEventListener('click', xet_richtexteditor_on_clicked, false);
				editorDoc.addEventListener('keyup', xet_richtexteditor_on_clicked, false);
			} else if (editorDoc.attachEvent) { // The IE way
	  			//editorDoc.attachEvent('onclick', xet_richtexteditor_on_clicked);
	  			//editorDoc.attachEvent('keyup', xet_richtexteditor_on_clicked);
			}
		}, 10);
		
	}
	
	// Attach the load event here. IE doesn't really need this to be in the load event
	// but since firefox does, both get it :)
	if (iframe.addEventListener) {
		iframe.addEventListener('load', onLoadFrame, false);
	} else if (iframe.attachEvent) { // The IE way
		iframe.attachEvent('onload', onLoadFrame);
	}
	
	return container;
}

function xet_richtexteditor_remove()
{
	var editor = document.getElementById("editor");
	editor.parentNode.parentNode.removeChild(editor.parentNode);
}



function xet_richtexteditor_on_command_clicked(evt, arg)
{
	var button = evt['target'] ? evt['target'] : evt['srcElement'];
	
	command = button.id;
	toggable = button.toggable;
	if(arg == undefined)
		arg = null;

	// Grab the document early
	var iframe = document.getElementById("editor");
	var editorDoc = iframe.contentWindow.document || iframe.contentDocument; 

	if(command == "runimageselector")
	{
		var callback = function(filename) { xet_richtexteditor_insert_image(filename); };
		xet_file_uploader_show(callback, gImageUploaderURL);
	}	
	else if(command == "runfileselector")
	{
		var callback = function(filename) { xet_richtexteditor_insert_file(filename); };
		xet_file_uploader_show(callback, gFileUploaderURL);
	}
	else if(command == "insertlink")
	{
		var url = prompt("Type the URL for the link", "");
		editorDoc.execCommand("createlink", false, url);
	}	
	else
	{
		editorDoc.execCommand(command, false, arg);

		if(command == "justifyleft" || command == "justifycenter" || command == "justifyright")
		{
			var b = document.getElementById("justifyleft");
			b.setAttribute("class", "tb_button");
			b.setAttribute("className", "tb_button");
			var b = document.getElementById("justifycenter");
			b.setAttribute("class", "tb_button");
			b.setAttribute("className", "tb_button");
			var b = document.getElementById("justifyright");
			b.setAttribute("class", "tb_button");
			b.setAttribute("className", "tb_button");
		}
	}
		
	if(toggable && button.getAttribute("class") == "tb_button") 
	{
		button.setAttribute("class", "tb_button_selected");
		button.setAttribute("className", "tb_button_selected");
	}
	else if(toggable) 
	{
		button.setAttribute("class", "tb_button");
		button.setAttribute("className", "tb_button");
	}
	
	document.getElementById("editor").contentWindow.focus();
}

function xet_richtexteditor_on_command_selected(evt)
{
	var selectList = evt['target'] ? evt['target'] : evt['srcElement'];
	var command = selectList.id;
	
	var index = selectList.selectedIndex;
	if (index == 0) 
		return;
		
	// Grab the tag
	var tag = selectList.options[index].value;
	
	// Apply the format to the text
	var iframe = document.getElementById("editor");
	var editorDoc = iframe.contentWindow.document || iframe.contentDocument;
	
	editorDoc.execCommand(command, false, tag);
	
	// Reset to 0 the select tag, maybe sometime find a way to detect the tag where the 
	// cursor is and update the select box on the fly? :/
	selectList.selectedIndex = 0;
	
	// Focus
	document.getElementById("editor").contentWindow.focus();
}

function xet_richtexteditor_set_view_source(viewSource)
{
  var html;
  
	if (viewSource) {
		html = document.createTextNode(document.getElementById('editor').contentWindow.document.body.innerHTML);
		document.getElementById('editor').contentWindow.document.body.innerHTML = "";
		html = document.getElementById('editor').contentWindow.document.importNode(html,false);
		document.getElementById('editor').contentWindow.document.body.appendChild(html);
	}
	else 
	{
		html = document.getElementById('editor').contentWindow.document.body.ownerDocument.createRange();
		html.selectNodeContents(document.getElementById('editor').contentWindow.document.body);
		document.getElementById('editor').contentWindow.document.body.innerHTML = html.toString(); 
	}
}

function xet_richtexteditor_save_forms()
{
	var iframe = document.getElementById("editor");
	var editorDoc = iframe.contentDocument || iframe.contentWindow.document;
	
	var updatedValue = editorDoc.body.innerHTML;
	var textarea = iframe.parentNode.nextSibling; // HACK, let's move this to using classes.
	textarea.value = updatedValue;
}




function xet_richtexteditor_insert_image(imageURL)
{
	// Get the alignment class
	var imgclass = "wrapright";
	//var radio = document.getElementsByName("imageselector_textwrap");
	//for(i = 0; i < 3; i++)
	//{
	//	if(radio[i].checked) {
	//		imgclass = radio[i].value;
	//	}
	//}
	
	// Now execute the insert html command
	var iframe = document.getElementById("editor");
	var editorDoc = iframe.contentWindow.document || iframe.contentDocument;
	
	var image = configBaseURL + imageURL;
	var imageHtml = '<img src="'+image+'" alt="image" class="'+imgclass+'" />';
	
	if(editorDoc.selection) // IE
	{
		// Gotta give focus to the window so the image doesn't appear at the top of the whole page
		// stupid IE bugs this took me 2 fucking days to fix!!!
		iframe.contentWindow.focus();			
		
		// Create the range
		var sel = editorDoc.selection;
		var rng = sel.createRange();

		// Insert the code properly
		if (rng.item)
			rng.item(0).outerHTML = imageHtml;
		else {
			rng.pasteHTML(imageHtml);
		}
		
	}
	else // FX
	{
		editorDoc.execCommand("inserthtml", false, imageHtml);
	}
}

function xet_richtexteditor_insert_file(fileURL)
{
	// Now execute the insert html command
	var iframe = document.getElementById("editor");
	var editorDoc = iframe.contentWindow.document || iframe.contentDocument;
	
	var fileName = configBaseURL + fileURL;
	var fileHtml = '<a href="'+fileName+'" target="_blank">Click here to download '+fileURL+'</a>';
	
	if(editorDoc.selection) // IE
	{
		// Gotta give focus to the window so the image doesn't appear at the top of the whole page
		// stupid IE bugs this took me 2 fucking days to fix!!!
		iframe.contentWindow.focus();			
		
		// Create the range
		var sel = editorDoc.selection;
		var rng = sel.createRange();

		// Insert the code properly
		if (rng.item)
			rng.item(0).outerHTML = fileHtml;
		else {
			rng.pasteHTML(imageHtml);
		}
		
	}
	else // FX
	{
		editorDoc.execCommand("inserthtml", false, fileHtml);
	}
}

function xet_richtexteditor_insert_media()
{
	// Get the value, this should be our image URL
	var list = document.getElementById("mediaselector_list");
	var value = list.value;
	
	// Get the alignment class
	var tagclass = "wrapnone";
	var radio = document.getElementsByName("mediaselector_textwrap");
	for(i = 0; i < 3; i++)
	{
		if(radio[i].checked) {
			tagclass = radio[i].value;
		}
	}
	
	// Close the selector
	xet_richtexteditor_close_file_selector();
	
	// Create the embed object
	var embed = document.createElement("embed");
	embed.setAttribute("style", "border: 1px solid red;");
	embed.setAttribute("width", "320");
	embed.setAttribute("src", value);
	embed.setAttribute("type", "application/x-oleobject");
	embed.setAttribute("autostart", "false");
	embed.setAttribute("class", tagclass);

	// Huge hack here to convert the embed element to text
	var div = document.createElement("div");
	div.appendChild(embed);
	
	// Got it!!
	var text = div.innerHTML;

	// Huge hack, remove it real quick ;)
	div.removeChild(embed);
	
	// Now create a range and either replace or insert the text html
	var iframe = document.getElementById("editor");
	var editorDoc = iframe.contentWindow.document || iframe.contentDocument; 
	if(editorDoc == null)
		alert("Houston, we have a problem.");
		
	if(editorDoc.selection)
	{
		// Gotta give focus to the window so the image doesn't appear at the top of the whole page
		// stupid IE bugs this took me 2 fucking days to fix!!!
		iframe.contentWindow.focus();		
		
		var rng = editorDoc.selection.createRange();
	
		if (rng.item)
			rng.item(0).outerHTML = text;
		else
			rng.pasteHTML(text);
	}
	else 
	{
		editorDoc.execCommand("inserthtml", false, text);
	}
}

function updateImagePreview(option)
{
	var filename = option.value;
	
	var image = document.getElementById("imageselector_preview");
	image.setAttribute("src", filename);
}

