/**
 * runtime include javascript, creates script node
 * @param {String} src url
 */
function include(src) {
	var inc = document.createElement("script");
		inc.type = "text/javascript";
		inc.language = "javascript";
		inc.src = src; // prevent caching+"?"+Math.random();
	document.body.appendChild(inc);
 }
/**
 * runtime include stylesheet
 * @param {String} href url
 * @param {String} media screen, print etc.
 */
  function loadStyleSheet(href,media) {
  	var link = document.createElement("link");
  	link.rel = "stylesheet";
  	link.type = "text/css";
  	link.media = media;
  	link.href = href;
  	document.body.appendChild(link);
  	
   }
  
/**
 * Quick replace
 * @param {String} s
 * @param {String} r
 * @return {String}
 */
String.prototype.qReplace = function (s, r) {
	return  this.split(s).join(r);
}
/**
 * Trim whitespace
 * @return {String}
 */
String.prototype.trim = function () {
	return this.replace(/^\s+$/,"");
}
  
/**
 * Convert to boolean
 */  
function toBoolean(value) {
	if (typeof value == 'string') {
		return (value.toLowerCase() == 'true') ? true : false; 
	} else {
		return value;
	}
}
 
/**
 * get Iframe Document
 * @param {DOMIFrame} iframe
 */
function getIframeDoc(iframe) {
	return iframe.contentWindow.document || document.frames[iframe.id].document;
}
/**
 * get Iframe Window
 * @param {DOMIFrame} iframe
 */
function getIframeWin(iframe) {
	return  iframe.contentWindow || document.frames[iframe.id];
}

/**
 * create new DOM Element to document with given properties
 * 
 * eg.
 * 	var div = createElement( document, 'div', { id:'MyDiv', className:'green'} )
 *  var link = createElement( iframeDocument, 'a', { href:'http://www.ambientia.fi', style:{color:'red'} } )
 * 
 * @param {document} toDoc target document
 * @param {String} type tag name of object
 * @param {Object} propertyObject (optional) properties to copy to created object
 * @return {DOMObject}
 */
function createElement( toDoc, type, propertyObject ) {
  var e,p,s;
  e = toDoc.createElement(type);
  for(p in propertyObject) {
    if (p == 'style')
      for(s in propertyObject[p])
        e[p][s] = propertyObject[p][s];
    else
      e[p] = propertyObject[p];
  }
  return e;
}

/**
 * @param {editor} editor
 * @param {String} icon path
 * @param {String} txt label
 * @param {String} desc Description
 * @return {DOMObject}
 */
function newMenuBtn ( editor, icon, txt, desc ) {

	//button part
	var o = new Element('div', { title:desc, 'class' : 'dropdown'} );
	document.body.appendChild(o);
	o.editor = editor;
	o.onmouseover = function () { 
		if (this.className.indexOf('off') == -1) this.className= 'dropdown on hover'
	};
  	
  	o.onmouseout = function () { 
  		if (this.className.indexOf('off') == -1) this.className = 'dropdown on';
  	};
	o.lbl = new Element('div');
	o.appendChild(o.lbl);	
	o.setText = function (txt) {
		var lbl = new Element('div').update(txt);
		this.replaceChild(lbl,this.lbl);
		this.lbl = lbl;	
	}
	o.setIcon = function (n) {
		if (isNaN(n)) var n = 0;
		var offset = n * 24;
		this.lbl.style.backgroundPosition = '0px -'+offset+"px";
	}
	o.setIconImg = function (icon) { 
		if (!icon || icon =="" ) return;
		this.lbl.style.backgroundImage = 'url('+net.ambientia.ced.path.img+icon +')'; } 
	o.setText (txt);
	o.setIcon (icon);
	o.isOpen = false;
	o.active = false;
	
	//menu
	o.open = function () {
		if (!this.menu) { this.createMenu() }
		this.menu.style.display = 'block';
		//fix min-width for IE
		if (isIE && this.menu.offsetWidth < 200) this.menu.style.width = "200px"
		this.isOpen = true;
	}
	
	o.close = function () {
		if (this.menu) this.menu.style.display = 'none';
		this.isOpen = false;
	}
	
	o.createMenu = function () {
		var offs = $(this).cumulativeOffset();
		this.menu =  new Element('div', {style:'position:absolute;top:'+(offs.top+20)+'px;left:'+offs.left+'px', 'class' : 'menu' });
		this.menu.style.display = "none";
		document.body.appendChild(this.menu);
	}
	
	o.clearItems = function () {
		if (!this.menu) { this.createMenu() }
		this.menu.update('');
	}
	
	o.addItem = function (txt, icon, command) {
		if (!this.menu) { this.createMenu() }
		var item = new Element('div', { style : 'background-image:url('+net.ambientia.ced.path.img+'icons.gif)' }).update(txt);
		var offset = icon * 24;
		item.style.backgroundPosition = '0px -'+offset+"px";
		item.onmouseover = function () { this.addClassName("hover"); }
   		item.onmouseout = function () { this.removeClassName("hover"); }
   		item.p = this;
   		item.onmousedown = command;
		this.menu.appendChild(item);
		return item;
	}

	o.menuOn = function () {
		this.className = 'dropdown on';
		this.active = true;
	}
	
	o.menuOff = function () {
		this.className = 'dropdown off';
		this.active = false;
	}
	
	
	return o;
}

/**
 * Select textranges in textareas
 * @param {FormInputElement} input
 * @param {Integer} selectioStart
 * @param {Integer} selectionEnd
 */
function setSelectionRange(input, selectionStart, selectionEnd)
{
	if (input.setSelectionRange)
	{
		input.setSelectionRange(selectionStart, selectionEnd);
		input.focus();
	}
	else if (input.createTextRange)
	{
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}
/**
 * selects first matching string from input-area
 * @param {formElement} input
 * @param {String} string
 */
function selectString (input, string)
{
	var match  = new RegExp(string, "i").exec(input.value.replace(/\r\n|\r|\n/g, ' '));
	if (match)
	{
	setSelectionRange (input, match.index, match.index + match[0].length);
	}
}

function removeEmptyNodes(rnode)
{
	[ 'a', 'b', 'span'].each(
	
		function ( nodeName )
		{
			$A( rnode.getElementsByTagName( nodeName ) ).each( 
				
				function (node)
				{
					if (node.innerHTML.trim() == "") node.parentNode.removeChild(node);
				}
			
			);
		}
	
	);
}


var dom2xhtml = {
	checkNodeAttrs : {
		img : {
			attrs : ['src','width','height','border','class','hspace','vspace','alt','align','id']
		},
		a : {
			attrs : ['href','target','title','class']
		},
		h1 : {
			attrs : ['class']
		},
		h2 : {
			attrs : ['class']
		}, 
		h3 : {
			attrs : ['class']
		}, 
		h4 : {
			attrs : ['class']
		}, 
		h5 : {
			attrs : ['class']
		},
		h6 : {
			attrs : ['class']
		},  
		p : {
			attrs : ['class','align']
		},
		div : {
			attrs : ['class','align','style','id']
		},
		table : {
			attrs : ['border','width','class','cellpadding','cellspacing','align']
		},
		tr: {
			attrs : ['class','valign','align']
		},
		td : {
			attrs : ['width','class','rowspan','colspan','align','valign','bgcolor']
		},
		form : {
			attrs : ['name','id','action']
		},
		input : {
			attrs : ['name', 'id', 'type', 'value']
		},
		textarea : {
			attrs : ['name', 'id', 'rows', 'cols', 'wrap']
		},
		span : {
			attrs : ['class']
		},
		param : {
			attrs : ['name', 'value']
		}
	},
	addNewLine : [ 'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul','li', 'form'],
	deleteEmpty : [ 'a', 'span', 'b', 'i', 'strong', 'u' ],
	deleteTag: [ 'style', 'script' ]
}

function domToXHTML(node, depth)
{

  var xhtml = "";
  if (node)
  {
  	depth ++;
    var j;
	var attrValue;
	var nodeName = node.nodeName.toLowerCase();

	if (jQuery.inArray( nodeName, dom2xhtml.deleteEmpty ) != -1)
	{
		if ( node.childNodes.length == 0 || (node.type == 3 && node.value.trim() == "") )
			return "";
	}
	
	if (jQuery.inArray( nodeName, dom2xhtml.deleteTag )  != -1 || (nodeName == "p" && jQuery(node).html() == "") )
	{
		return "";
	}
	
	var printTag = ( node.nodeType == 1 && nodeName != "body" && nodeName != "font");	
	
	
    if (printTag) {
		if (jQuery.inArray( nodeName, dom2xhtml.addNewLine ) != -1 ) {
			xhtml += "\n";
			for (var i = 2; i < depth; i++) xhtml += " ";
		}
		xhtml += "<"+nodeName;
	}
	
	//get and validate attributes
	if (dom2xhtml.checkNodeAttrs[nodeName]) {
		var attrs = dom2xhtml.checkNodeAttrs[nodeName].attrs;

		for (var a = 0; a < attrs.length; a++) {
			attrValue = jQuery(node).attr( attrs[a] );			
			if ( attrValue != null && attrValue != "" )
			{
					// Do this so all image tags etc. behave correctly, 
					// /files should not need .. in any case.
					if(attrs[a] == 'src' && attrValue.indexOf("../files/") == 0)
					{
						attrValue = attrValue.substring(2);
					}
					
					xhtml += ' '+attrs[a]+'="'+attrValue+'"';
			}
		}
	}
	
	//convert style width to tags
	if (!isIE && nodeName == 'img') {
		var w = parseInt(node.style.width);
		var h = parseInt(node.style.height);
		if (w) xhtml += ' width="'+w+'"';
		if (h) xhtml += ' height="'+h+'"';
	}

	if (nodeName == 'br' || nodeName == 'img' || nodeName == 'input' || nodeName == 'param') {
		xhtml += " />\n";
	} else {
		if (printTag) xhtml += ">";
		
		if (node.nodeType == 3) {
			var txt = node.nodeValue.trim();
			txt = txt.replace(RegExp("<","g"),"&lt;");
			txt = txt.replace(RegExp(">","g"),"&gt;");
			xhtml += txt;
		}
		
		for (var i = 0; i < node.childNodes.length; i++)
		  xhtml += domToXHTML(node.childNodes[i], depth); 
				
		if (printTag) {
			if ( jQuery.inArray( nodeName, dom2xhtml.addNewLine ) != -1 ) {
				xhtml += "</"+nodeName+">\n";
			} else
				xhtml += "</"+nodeName+">";
		}
    
	}
  }				
  return xhtml;
}

var dom2html32 = {
	checkNodeAttrs : {
		img : {
			attrs : ['src','width','height','border','hspace','vspace','alt','align']
		},
		a : {
			attrs : ['href','target','title'],
			fontFace : 'arial'
		},
		p : {
			attrs : ['align'],
			fontFace : 'arial'
		},
		div : {
			attrs : ['align']
		},
		table : {
			attrs : ['border','width','cellpadding','cellspacing']
		},
		tr: {
			attrs : ['align','valign']
		},
		td : {
			attrs : ['rowspan','colspan','align','valign','bgcolor'],
			fontFace: 'arial'
		},
		script : {
			attrs : ['language']
		},
		form : {
			attrs : ['name','action']
		},
		input : {
			attrs : ['name', 'type', 'value']
		},
		textarea : {
			attrs : ['name', 'rows', 'cols', 'wrap']
		},
		object : {
			attrs : ['classid', 'codebase', 'width', 'height', 'class', 'style']
		},
		param : {
			attrs : ['name', 'value']
		},
		embed : {
			attrs : ['src', 'quality', 'bgcolor', 'width', 'height']
		},
		font : {
			attrs : ['size','color', 'face']
		},
		span : {
			attrs : ['class']
		}
	},
	addNewLine : [ 'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul','li', 'script', 'form']
}

function domToHTML32(node, depth)
{
  var html = "";
  if (node)
  {
  	depth ++;
    var j;
	var attrValue;
	var nodeName = node.nodeName.toLowerCase();
	
	var printTag = ( node.nodeType == 1 && nodeName != "body" && nodeName != "tbody"  && nodeName != "font");
		
    if (printTag) {
		if (dom2html32.addNewLine.indexOf(nodeName) != -1 ) {
			html += "\n";
			for (var i = 2; i < depth; i++) html += " ";
		}
		html += "<"+nodeName.toUpperCase();
	}
	
	//get and validate attributes
	if (dom2html32.checkNodeAttrs[nodeName]) {
		var attrs = dom2html32.checkNodeAttrs[nodeName].attrs;
		
		for (var a = 0; a < attrs.length; a++) {
			if ( (attrValue = node.getAttribute(attrs[a]) ) ) {
				html += ' '+attrs[a].toUpperCase()+'="'+attrValue+'"';
			}
		}
	} 

	if (nodeName == 'br' || nodeName == 'img' || nodeName == 'input' || nodeName == 'param') {
		html += ">\n";
	} else {
		if (printTag) html += ">";
		
		if (dom2html32.checkNodeAttrs[nodeName] && dom2html32.checkNodeAttrs[nodeName].fontFace) {
			html += '<FONT FACE="'+dom2html32.checkNodeAttrs[nodeName].fontFace+'">';
		}
		
		if (node.nodeType == 3) {
			html += node.nodeValue.trim();
		}
		
		for (var i = 0; i < node.childNodes.length; i++)
		  html += domToHTML32(node.childNodes[i], depth); 
		
				
		if (printTag) {
			if (dom2html32.checkNodeAttrs[nodeName].fontFace) {
				html += '</FONT>';
			}
		
			if (dom2html32.addNewLine.indexOf(nodeName) != -1 ) {
				html += "</"+nodeName.toUpperCase()+">\n";
			} else
				html += "</"+nodeName.toUpperCase()+">";
		}
    
	}
  }				
  return html;
}
