addEvent(window, "load", updateInteractiveFields);

function updateInteractiveFields () {
	var divs = document.getElementsByTagName('div');
	
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className.indexOf('richtext') >= 0)
		{
			//get the id of the textarea
			var txtArea	= divs[i].getElementsByTagName('textarea')[0];
			var txtid	= txtArea.id.match(/(.*)\[(.*)\]/);
			txtid		= RegExp.$1+'_'+RegExp.$2;
			txtArea.id	= txtid;
			
			var tooldiv = document.createElement('div');
			tooldiv.id = divs[i].id+'__toolbar';
			tooldiv.className = 'toolbar';
			prependChild(divs[i], tooldiv);
			
			//insert richtextbuttons
			initToolbar(divs[i].id+'__toolbar', txtArea.id, toolbar);
		}
		
		if (divs[i].className.indexOf('image') >= 0)
		{
			//get the id of the field
			var field	= divs[i].getElementsByTagName('input')[0];
			var txtid	= field.id.match(/(.*)\[(.*)\]/);
			txtid		= RegExp.$1+'_'+RegExp.$2;
			field.id	= txtid;
			
			var button	= divs[i].getElementsByTagName('button')[0];
			
			if (button != null) {
				eval("button.onclick = function(){" +
					"var input = document.getElementById(txtid);" +
					"input.value = '';" +
					"window.open('"+
						jsEscape(imageSettings['url'])+"','"+
						jsEscape(txtid)+"','"+
						jsEscape(imageSettings['options'])+
					"');" +
					"return false;}");
			}
		}
	}
}


/**
 * Creates a toolbar button through the DOM
 *
 * Style the buttons through the toolbutton class
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function createToolButton(icon,label,key,id){
	var btn = document.createElement('button');
	var ico = document.createElement('img');

	// preapare the basic button stuff
	btn.className	= 'toolbutton button';
	btn.title		= label;
	if(key){
		btn.title += ' [ALT+'+key.toUpperCase()+']';
		btn.accessKey = key;
	}

	// set IDs if given
	if(id){
		btn.id = id;
		ico.id = id+'_ico';
	}

	// create the icon and add it to the button
	ico.src = IMG_DIR+icon;
	btn.appendChild(ico);

	return btn;
}

/**
 * Create a toolbar
 *
 * @param	string	tbid	ID of the element where to insert the toolbar
 * @param	string	edid	ID of the editor textarea
 * @param	array	tb		Associative array defining the buttons
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function initToolbar(tbid,edid,tb){
	if(!document.getElementById){ return; }
	var toolbar	= document.getElementById(tbid);
	var cnt		= tb.length;
	for (var i = 0; i < cnt; i++){
		// create new button
		btn = createToolButton(tb[i]['icon'],
								 tb[i]['title'],
								 tb[i]['key']);

		// add button action dependend on type
		switch(tb[i]['type']){
			case 'format':
				var sample = tb[i]['title'];
				if(tb[i]['sample']){ sample = tb[i]['sample']; }
				
				eval("btn.onclick = function() {"+
					"insertTags('"+
						jsEscape(edid)+"','"+
						jsEscape(tb[i]['open'])+"','"+
						jsEscape(tb[i]['close'])+"','"+
						jsEscape(sample)+
					"');"+
					"return false;"+
				"}");
				toolbar.appendChild(btn);
				break;
			case 'insert':
				eval("btn.onclick = function(){insertAtCarret('"+
										jsEscape(edid)+"','"+
										jsEscape(tb[i]['insert'])+
									"');return false;}");
				toolbar.appendChild(btn);
				break;
			case 'mediapopup':
				eval("btn.onclick = function(){window.open('"+
										jsEscape(tb[i]['url'])+"','"+
										jsEscape(edid)+"','"+
										jsEscape(tb[i]['options'])+
									"');return false;}");
				toolbar.appendChild(btn);
				break;
		} // end switch
	} // end for
}

/**
 * Format selection
 *
 * Apply tagOpen/tagClose to selection in textarea, use sampleText instead
 * of selection if there is none. Copied and adapted from phpBB
 *
 * @author phpBB development team
 * @author MediaWiki development team
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Jim Raynor <jim_raynor@web.de>
 */
function insertTags (edid, tagOpen, tagClose, sampleText) {
	var txtarea = document.getElementById(edid);
	// IE
	if (document.selection && !is_gecko) {
		var theSelection	= document.selection.createRange().text;
		var replaced		= true;
		if (!theSelection){
			replaced		= false;
			theSelection	= sampleText;
		}
		txtarea.focus();
	
		// This has change
		var text = theSelection;
		if (theSelection.charAt(theSelection.length - 1) == " ") {// exclude ending space char, if any
			theSelection = theSelection.substring(0, theSelection.length - 1);
			r		= document.selection.createRange();
			r.text	= tagOpen + theSelection + tagClose + " ";
		} else {
			r		= document.selection.createRange();
			r.text	= tagOpen + theSelection + tagClose;
		}
		if (!replaced){
			r.moveStart('character', -text.length-tagClose.length);
			r.moveEnd('character', -tagClose.length);
		}
		r.select();
	// Mozilla
	} else if (txtarea.selectionStart || txtarea.selectionStart == '0') {
		var startPos	= txtarea.selectionStart;
		var endPos		= txtarea.selectionEnd;
		replaced		= (endPos - startPos) > 0;
		var scrollTop	= txtarea.scrollTop;
		var myText		= (txtarea.value).substring(startPos, endPos);
		if (!myText) { myText = sampleText; }
		if (myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
			subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
		} else {
			subst = tagOpen + myText + tagClose;
		}
		txtarea.value = txtarea.value.substring(0, startPos) + subst +
						txtarea.value.substring(endPos, txtarea.value.length);
		txtarea.focus();
	
		//set new selection
		if (replaced) {
			var cPos =startPos + (tagOpen.length+myText.length + tagClose.length);
			txtarea.selectionStart	= cPos;
			txtarea.selectionEnd	= cPos;
		} else {
			txtarea.selectionStart	= startPos + tagOpen.length;
			txtarea.selectionEnd	= startPos + tagOpen.length+myText.length;
		}
		txtarea.scrollTop = scrollTop;
		// All others
	} else {
		var copy_alertText = alertText;
		var re1 = new RegExp("\\$1","g");
		var re2 = new RegExp("\\$2","g");
		copy_alertText = copy_alertText.replace(re1, sampleText);
		copy_alertText = copy_alertText.replace(re2, tagOpen + sampleText + tagClose);
	
		if (sampleText) {
			text = prompt(copy_alertText);
		} else {
			text = "";
		}
		if(!text) { text = sampleText;}
		text = tagOpen + text + tagClose;
		//append to the end
		txtarea.value += "\n" + text;
	
		// in Safari this causes scrolling
		if(!is_safari) {
			txtarea.focus();
		}
	}
	// reposition cursor if possible
	if (txtarea.createTextRange) {
		txtarea.caretPos = document.selection.createRange().duplicate();
	}
}

/*
 * Insert the given value at the current cursor position
 *
 * @see http://www.alexking.org/index.php?content=software/javascript/content.php
 */
function insertAtCarret(edid,value){
	var field = document.getElementById(edid);
	
	//IE support
	if (document.selection) {
		field.focus();
		sel = document.selection.createRange();
		sel.text = value;
	//MOZILLA/NETSCAPE support
	} else if (field.selectionStart || field.selectionStart == '0') {
		var startPos	= field.selectionStart;
		var endPos	= field.selectionEnd;
		var scrollTop = field.scrollTop;
		field.value = field.value.substring(0, startPos) +
						value +
						field.value.substring(endPos, field.value.length);
	
		field.focus();
		var cPos=startPos+(value.length);
		field.selectionStart=cPos;
		field.selectionEnd=cPos;
		field.scrollTop=scrollTop;
	} else {
		field.value += "\n"+value;
	}
	// reposition cursor if possible
	if (field.createTextRange){
		field.caretPos = document.selection.createRange().duplicate();
	}
}

/**
 * Escape special chars in JavaScript
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function jsEscape(text){
	if (text == null)	{ text = ''; }
	
	text	= new String(text); 
	var re	= new RegExp("\\\\", "g");
	text	= text.replace(re, "\\\\");
	re		= new RegExp("'", "g");
	text	= text.replace(re, "\\\'");
	re		= new RegExp('"', "g");
	text	= text.replace(re, '&quot;');
	re		= new RegExp("\\\\\\\\n", "g");
	text	= text.replace(re, "\\n");
	return text;
}

/**
 * Adds a node as the first childenode to the given parent
 *
 * @see appendChild()
 */
function prependChild(parent,element) {
	if(!parent.firstChild){
		parent.appendChild(element);
	}else{
		parent.insertBefore(element,parent.firstChild);
	}
}