/*
# $Id$
#
# Provides a number of utiilty functions packaged within the global "Util" namespace.
*/

/*
# @namespace Util
*/
var Util = {};

/*
# @method void linkCss( string src )
# src	= Url to CSS source file
#
# Writes code to link the specified CSS file into the current HTML document.
*/
Util.linkCss = function(src) {

	// Write inline if the document has not fully loaded yet
	if(!window._hasLoaded) {
		document.write('<style type="text/css" media="screen" >@import url("'+src+'");</style>');
	}
	else {
		var css = document.createElement('link');
		css.href = src;
		css.type = "text/css";
		css.rel = "stylesheet";
		css.media = "screen";
		document.documentElement.appendChild(css);
	}
}

/*
# @method object xmlToObject( XML xml )
# xml	= XML document to be converted
#
# Converts an XML tree into a native Object.
*/
Util.xmlToObject = function(xml) {

	// Vars
	var resultObj = new Object();

	// Parse child nodes
	for(var c=0; c<xml.childNodes.length; c++) {
		var node = xml.childNodes[c];
		var nType = node.nodeType;
		var nName = node.nodeName;

		// Parse child nodes
		if(nType==1) {
			if(resultObj[nName]==null) {

				// Build child node-set
				resultObj[nName] = Util.xmlToObject(node);

				// Add attributes to result object
				if(typeof resultObj[nName]=='object' && node.attributes!=null) {
					for(var a=0; a<node.attributes.length; a++) {
						resultObj[nName][node.attributes[a].name] = node.attributes[a].value;
					}
				}
			}
			else {
				// Convert the node to an array
				if(typeof resultObj[nName]!='object' || resultObj[nName].length==null) resultObj[nName] = [resultObj[nName]];

				// Build the child node-set
				var childObj = Util.xmlToObject(node);

				// Add attributes to result object
				if(typeof childObj=='object' && node.attributes!=null) {
					for(var a=0; a<node.attributes.length; a++) {
						childObj[node.attributes[a].name] = node.attributes[a].value;
					}
				}

				// Add the child node-set as a new array element
				resultObj[nName].push(childObj);
			}
		}

		// Parse node value
		if(nType==3) {
			if(resultObj['#text']==null) resultObj['#text'] = '';
			resultObj['#text'] += node.nodeValue;
		}

		// Parse CDATA section
		if(nType==4) {
			if(resultObj['#text']==null) resultObj['#text'] = '';
			resultObj['#text'] += node.nodeValue;
		}
	}

	// If ONLY a '#text' node is present in the result, then we can assume that
	// it's a text-node, so can collapse the object into a scalar value
	if(resultObj['#text']!=null) {
		var scalar = resultObj['#text'];
		delete(resultObj['#text']);
		var count = 0;
		for(var i in resultObj) count++;
		if(count==0) resultObj = scalar;
	}
	else if(xml.childNodes.length==0 && xml.nodeValue==null && xml.attributes.length==0) {
		resultObj = '';
	}

	// Result
	return resultObj;
}

/*
# @method bool inArray( mixed needle, mixed haystack )
# needle	= Item to find
# haystack	= Array of items in which to search
#
# Finds the needle in the haystack.
*/
Util.inArray = function(needle, haystack) {

	// Find the needle
	for(var i=0; i<haystack.length; i++) {
		if(haystack[i]==needle) {
			return true;
		}
	}
}

/*
# @method window.addOnLoad( Function func )
# func	= Function
#
# Adds a function to a queue of functions that will be executed when the window.onload event is fired.
*/
window.onLoadQueue = new Array();
window.addOnLoad = function(func) {
	window.onLoadQueue.push(func);
}
window.onload = function() {
	window._hasLoaded = true;
	for(var i=0; i<window.onLoadQueue.length; i++) {
		window.onLoadQueue[i]();
	}
}

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
Util.dump = function(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 

/*
# @method bool getListMenu()
#
*/
Util.getListMenu = function(sel) {
	var data = sel.getData();
	// Clear rows
	while(sel.infoElement.firstChild) {
		sel.infoElement.removeChild(sel.infoElement.childNodes[0]);
	}
	
	if(data!='') {
		try{
			data = data.push ? data : [data];
			for(var i=0; i<data.length; i++) {
				// add row
				var row = sel.infoElement.insertRow(sel.infoElement.rows.length);
				var cell = [];
				// add cell 1
				if(data[i].relativeUrl){
					cell[0] = row.insertCell(cell.length);
					cell[0].innerHTML = "<a href='"+data[i].relativeUrl+"' target='new' title='preview in new window' >"+data[i].name+"</a>"
					cell[0].classname = '';
				}else{
					cell[0] = row.insertCell(cell.length);
					cell[0].innerHTML = data[i].title==null ? data[i].documenttitle : data[i].title ;
					cell[0].classname = '';
				}
				// add cell 2
				cell[1] = row.insertCell(cell.length);
				cell[1].innerHTML = "<a href='/' onclick='"+sel.getOption('objectName')+".popById("+data[i].id+");return false;'>delete</a>";
				if(data.length>1){
					cell[1].innerHTML += " | <a href='/' onclick='"+sel.getOption('objectName')+".promote("+data[i].id+",1);return false;'>up</a> | ";
					cell[1].innerHTML += "<a href='/' onclick='"+sel.getOption('objectName')+".promote("+data[i].id+",-1);return false;'>down</a>";
				}
				cell[1].classname = '';
			}
		}catch(er){alert(er.description)}
	}else{
		try{
			var row = sel.infoElement.insertRow(sel.infoElement.rows.length);
			var cell = [];
			// add cell 1
			cell[0] = row.insertCell(cell.length);
			cell[0].innerHTML = "No selection has been made...";
			cell[0].classname = '';
			// add cell 2
			cell[1] = row.insertCell(cell.length);
			cell[1].innerHTML = "";
			cell[1].classname = '';
		}catch(er){alert(er.description)}
	}
	
}

Util.isUrl = function(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}
