/**
* global.functions.js
*
* Cross-browser function
*
* @author Mathieu Ducharme <mducharme@k3media.com>
*/


/**
* Return an element object
*
* @param string	The ID of the element
*
* @return HTMLElement	The object
*/
function getE(id)
{
	if(document.getElementById) {
		return(document.getElementById(id));
	}
        else if (document.all)
        {
               return(document.all[id]);
        }
        else if (document.layers)
        {
                return(document.layers[id]);
        }
}

/**
*
*/
function removeAllChildren(obj)
{
	if(!obj.hasChildNodes) {
		// TODO: Find alternative method
		return(obj);
	}
	
	while(obj.hasChildNodes()) {
		obj.removeChild(obj.firstChild);
	}
	
	return(obj);
}

/**
*
*/
function isFunction(a)
{
	return typeof a == 'function';
}

/**
*
*/
function isObject(a)
{
	return(a && typeof a == 'object') || isFunction(a);
}

/**
*
*/
function newStyle(obj)
{
	var s = new CSSStyleDeclaration();
	obj.style = s;
}

/**
* Add an event listener to an object
*
* @param HTMLElement
* @param string
* @param string
* @param bool
*
* @return bool		Success/Failure
*/
function addEvent(obj, event, fn)
{	
	var ret;
	
	if(!isObject(obj)) {
		return false;
	}
	
	if(obj.addEventListener) {
		// Mozilla
		try {
			obj.addEventListener(event, fn, false);
			ret = true;
		}
		catch(e) {
			ret = false;
		}
	}
	else if (obj.attachEvent) {
		// Explorer
		ret = obj.attachEvent("on"+event, fn);
	}

	return ret;
	
}

/**
* Add a function to the window load handler without removing the old one(s)
*
* @param function
*/
function addLoadEvent(f)
{	
	if (isFunction(window.onload)) {
		window.onload = f;
	} 
	else {
		var prevF = window.onload;
		window.onload = function() {
			prevF();
			f();
		}
	}
}

/**
* Remove an event listener from an object
*
* @param HTMLElement
* @param string
* @param string
* @param bool
*
* @return bool		Success/Failure
*/
function removeEvent(obj, event, fn, capture)
{
	if (obj.removeEventListener){
		// Mozilla
		obj.removeEventListener(event, fn, capture);
		return true;
	} 
	else if (obj.detachEvent){
		// Explorer
		var ret = obj.detachEvent("on"+event, fn);
		return ret;
	} 
}

/**
* Returns a XMLHttpRequest Object
*
* @return XMLHttpRequest / ActiveXObject
*/
function getXMLHttpRequest()
{
	req = false;
	if(window.XMLHttpRequest) {
	// Mozilla
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
	} 
	else if(window.ActiveXObject) {
	// Explorer
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	return(req);
}

/**
*
*/
function toggleView(obj)
{
	if(obj.style.display == '' || obj.style.display == 'none') {
		obj.style.display = 'block';
	}
	else {
		obj.style.display = 'none';
	}
}

/**
*
*/
function listToggle(li, imgPlus, imgMinus)
{
	
	if(!isObject(li)) {
		
		return(false);
	}
	
	var ul = li.getElementsByTagName('ul')[0];
		
	if(!isObject(ul)) {
		return(false);
	}

	var lis = ul.getElementsByTagName('li');
	for(var i = 0; i < lis.length; i++) {
		var obj =lis[i];
		if(obj.style.display == '' || obj.style.display == 'none') {
			obj.style.display = 'list-item';
			if(li.firstChild.nodeName == 'IMG') {
				li.firstChild.src = imgMinus;
			}
		}
		else {
			obj.style.display = 'none';
			if(li.firstChild.nodeName == 'IMG') {
				li.firstChild.src = imgPlus;
			}
		}
	}

}

/**
* Get the object that an event is attached to
*
* This function fixes the bug with the Explorer Event model where the property
* "this" seems to have been forgotten.
*
* Call like this:
* function(e) { getEventObj((e ? e : window.event), this); }
* to ensure the correct event is passed with all browsers (explorer win 5+)
*
* @param Event
* @param Object		The source object, in firefox, empty object in Explorer
*
* @return Object	The source object, in all browsers (wishful)
*
* @author Mathieu Ducharme <mducharme@k3media.com>
*/
function getEventObj(e, obj)
{
	if(e.srcElement) {
		// Explorer (and konqueror, which supports both models)
		return(e.srcElement);
	}
	else {
		// Firefox
		return(obj);
	}
}

/**
* Prepare an UL so it hide/show
*/
function prepareUL(ul, c, imgPlus, imgMinus, imgBlank)
{
	
	if(!isObject(ul)) {
		return(false);
	}

	var item;
	
	var lis = ul.getElementsByTagName('li');
	for(var i = 0; i < lis.length; i++) {
	
		var iconImg = document.createElement('img');
	
		item = lis[i];

		// Initialize item
		listToggle(item, imgPlus, imgMinus);
		
		// Add the image only if it has child
		if(item.className == c) {

			// Add the icon image
			iconImg.src = imgPlus;
			item.insertBefore(iconImg, item.firstChild);
			
			// Add the click event to the icon
			addEvent(iconImg, 'click', 
				function(e) {
					var obj = getEventObj((e ? e : window.event), this);
					listToggle(obj.parentNode, imgPlus, imgMinus); 
				}
			);
			
			// Hide
			listToggle(item, imgPlus, imgMinus);
			
			// Recursive
			// TODO: Why 2??? Found by trial & error
			if(isObject(item.getElementsByTagName('ul')[2])) {
				prepareUL(item.getElementsByTagName('ul')[2], c, imgPlus, imgMinus, imgBlank);
			}
		}
		else {
			iconImg.src = imgBlank;
			item.insertBefore(iconImg, item.firstChild);
		}
	}
}

/**
*
*/
function scrollDiv(div, speed)
{
	clearTimeout(window.scrollTimer);
	div.scrollTop += speed;
	window.scrollTimer = setTimeout(function() { scrollDiv(div, speed); }, 15);
}

function moveDiv(div, pixels)
{
	div.scrollTop += pixels;
}
/**
* Stop the scroll
*/
function stopScroll()
{
	clearTimeout(window.scrollTimer);
}

function objOpacity(obj, val)
{
	if(obj.style.filter) {
		obj.style.filter = 'alpha(opacity='+val+')';
	}
	else {
		obj.style.opacity = val/100;
	}
}

function selMulti(selId, id, name)
{
	// Do not add non-object values (like the default "0")
	if(id > 0) {
		var v = getE(selId+'_hid').value;
		v = v.split('|'); // v is now an array
		
		var add = true;
		
		// Check if the id was already selected
		for(var i=0; i<v.length; i++) {
			if(v[i] == id) {
				add=false;
				continue;
			}
		}
		
		// Only add if necessary
		if(add) {

			var span = document.createElement('span');
			span.id = selId+'_span_'+id;
			span.innerHTML = name;
			
			if(v != '') {
				var br = document.createElement('br');
				br.id = selId+'_br_'+id;
				getE(selId+'_div').appendChild(br);
			}
			
			getE(selId+'_div').appendChild(span);
			
			var sep2 = (v == '') ? ('') : ('|');
			getE(selId+'_hid').value += sep2 + id;
			
			// Add the "delete" button to remove an object from the list
			var img = document.createElement('img');
			img.id = selId+'_img_'+id;
			img.src = 'http://demo.k3-media.com/common/core/ui/img/fileclose.png';
			
			getE(selId+'_span_'+id).insertBefore(img, getE(selId+'_span_'+id).firstChild);
			
			// Add the "delete" event on the image click
			addEvent(getE(selId+'_img_'+id), 'click',
			function()
			{
				var hidVal = getE(selId+'_hid').value;
				var hidArr = hidVal.split('|'); // v is now an array
				var newHid = new Array();
				for(var i=0; i<hidArr.length; i++) {
					if(hidArr[i] != id) {
						newHid.push(hidArr[i]);
					}
				}
				
				// Remove the span
				if(getE(selId+'_br_'+id)) {
					getE(selId+'_div').removeChild(getE(selId+'_br_'+id));
				}
				getE(selId+'_div').removeChild(getE(selId+'_span_'+id));
				
				//getE(selId+'_div').innerHTML = newDiv.join('<br>');
				getE(selId+'_hid').value = newHid.join('|');
				
			});
		}
	}
}

/**
* Prepare a select object to use a better select widget
*
* @param string	The select ID to prepare, AS STRING
*
* @return The hidden input
*/
function prepSelMulti(selId)
{
	// Create the div element
	var div = document.createElement('div');
	div.id = selId+'_div';

	// Create the hidden input
	var hid = document.createElement('input');
	hid.type = 'hidden';
	hid.name = getE(selId).name.substr(0, getE(selId).name.length-2);
	hid.id = selId+'_hid';
	
	// Remove the "multiple" option to show a standard select
	getE(selId).multiple = false;
	
	// Add the hidden input and the div
	getE(selId).parentNode.insertBefore(hid, getE(selId));
	getE(selId).parentNode.insertBefore(div, getE(selId));
	
	// Change the name of the original select ("orig[]") to "orig_old[]"
	getE(selId).name = hid.name.substr(0, hid.name.length-2)+'_old[]';
	
	// Add the main event on the select change to fill the correct stuff
	addEvent(getE(selId), 'change', 
	function() 
	{
		
		var id = getE(selId).options[getE(selId).selectedIndex].value;
		var name = getE(selId).options[getE(selId).selectedIndex].innerHTML;
		selMulti(selId, id, name);
		
	});
		
	// Select the "selected" optiosn automatically
	var opts = getE(selId).options;
	for(var j=0; j< opts.length; j++) {
		if(opts[j].selected) {
			selMulti(selId, opts[j].value, opts[j].innerHTML);
		}
	}
	
	return hid;
}

/**
* @param Object	The link (<a>) object that calls this function
* @param integer	Width of the window to open
* @param integer	Height of the window to open
*/
function linkPopWin(a, w, h)
{
	var r = parseInt(Math.random()*999999);
	var newWin = window.open(a.href, "CMSPopup"+r , "width="+w+",height="+h+",scrollbars=yes");
	return false;
}	