// $Id: inc.js.general_functions.js 272 2007-02-05 19:55:37Z conor $

/**
 * Outputs information passed to the display.
 *
 * @param text {string} The information to be output to the browser.
 */
function d(text)
{
	document.writeln(text + "<br />");
}

/**
 * Adds a function or an instaniated object and a method to the list of functions/methods which
 * should be run when the page has been loaded.
 *
 * @author Conor Kerr
 * @copyright 2008 Ceon (http://ceon.net)
 * @param func {string} The name of a function to run.
 * @param obj {object} An object from which a method should be run.
 * @param method {string} The name of the method within the specified object to run.
 * @returns {none}
 */
function CeonAddLoadEvent(func, obj, method)
{
	var oldonload = window.onload;
	
	if (typeof window.onload != 'function') {
		if (func == '') {
			window.onload = function()
			{
				obj[method]();
			}
		} else {
			window.onload = func;
		}
	} else {
		window.onload = function()
		{
			if (oldonload) {
				oldonload();
			}
			if (func == '') {
				obj[method]();
			} else {
				func();
			}
		}
	}
}

/**
 * Adds a function or an instaniated object and a method to the list of functions/methods which
 * should be run when the page has been resized.
 *
 * @author Conor Kerr
 * @copyright 2008 Ceon (http://ceon.net)
 * @param func {string} The name of a function to run.
 * @param obj {object} An object from which a method should be run.
 * @param method {string} The name of the method within the specified object to run.
 * @returns {none}
 */
function CeonAddResizeEvent(func, obj, method)
{
	var oldonresize = window.onresize;
	
	if (typeof window.onresize != 'function') {
		if (func == '') {
			window.onresize = function()
			{
				obj[method]();
			}
		} else {
			window.onresize = func;
		}
	} else {
		window.onresize = function()
		{
			if (oldonresize) {
				oldonresize();
			}
			if (func == '') {
				obj[method]();
			} else {
				func();
			}
		}
	}
}



/**
 * Returns true if an element has a specified class name
 */
function hasClass(node, className) {
	if (node.className == className) {
		return true;
	}
	var reg = new RegExp('(^| )'+ className +'($| )')
	if (reg.test(node.className)) {
		return true;
	}
	return false;
}

/**
 * Adds a class name to an element
 */
function addClass(node, className) {
	if (hasClass(node, className)) {
		return false;
	}
	node.className += ' '+ className;
	return true;
}

/**
 * Removes a class name from an element
 */
function removeClass(node, className) {
	if (!hasClass(node, className)) {
		return false;
	}
	// Replaces words surrounded with whitespace or at a string border with a space. Prevents multiple class names from being glued together.
	node.className = eregReplace('(^|\\s+)'+ className +'($|\\s+)', ' ', node.className);
	return true;
}

/**
 * Toggles a class name on or off for an element
 */
function toggleClass(node, className) {
	if (!removeClass(node, className) && !addClass(node, className)) {
		return false;
	}
	return true;
}


/**
 * Removes an element from the page
 */
function removeNode(node) {
  if (typeof node == 'string') {
    node = $(node);
  }
  if (node && node.parentNode) {
    return node.parentNode.removeChild(node);
  }
  else {
    return false;
  }
}


/**
 * Emulate PHP's ereg_replace function in javascript
 */
function eregReplace(search, replace, subject) {
  return subject.replace(new RegExp(search,'g'), replace);
}


function getStyle(el, styleProp)
{
	var x = document.getElementById(el);
	if (window.getComputedStyle)
		var y = window.getComputedStyle(x,null).getPropertyValue(styleProp);
	else if (x.currentStyle)
		var y = eval('x.currentStyle.' + styleProp);
	return y;
}

function getElementStyle(elemID, IEStyleProp, CSSStyleProp) {
	var elem = document.getElementById(elemID);
	if (elem.currentStyle) {
		return elem.currentStyle[IEStyleProp];
	} else if (window.getComputedStyle) {
		var compStyle = window.getComputedStyle(elem, "");
		return compStyle.getPropertyValue(CSSStyleProp);
	}
	return "";
}


/**
 * Retrieves the absolute position of an element on the screen
 */
function absolutePosition(el) {
  var sLeft = 0, sTop = 0;
  var isDiv = /^div$/i.test(el.tagName);
  if (isDiv && el.scrollLeft) {
    sLeft = el.scrollLeft;
  }
  if (isDiv && el.scrollTop) {
    sTop = el.scrollTop;
  }
  var r = { x: el.offsetLeft - sLeft, y: el.offsetTop - sTop };
  if (el.offsetParent) {
    var tmp = absolutePosition(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

function dimensions(el) {
  return { width: el.offsetWidth, height: el.offsetHeight };
}


function attachElements(element1, element2)
{
	element1 = document.getElementById(element1);
	element2 = document.getElementById(element2);
	
	// Insert the element as the first child of the parent element (before any text or other elements).
	var element1_child = element1.firstChild;
	element1.insertBefore(element2, element1_child);
	
	// Align the inserted element to the top right of the parent element
	addClass(element2, 'ControlPanelForm');
}


function fade(obj, destOpacity, rate, delta)
{
	var curOpacity, newOpacity, direction;

	if (typeof(obj) != 'object') {
		if (document.getElementById)
			obj = document.getElementById(obj);
		else 
			return false;
	} else {
		// Make sure an id has been set
		if (obj.id.length == 0)
			return false;
	}

	if (!obj.filters && !obj.style.MozOpacity)
		return false; // Not IE or Mozilla
	
	//curOpacity = 0;
	/*if(obj.style.MozOpacity)
		curOpacity = (obj.style.MozOpacity * 100);
	else if (obj.filters && obj.filters.alpha && obj.filters.alpha.opacity)
		curOpacity = obj.filters.alpha.opacity;*/
	if(obj.style.MozOpacity)
		curOpacity = (obj.style.MozOpacity * 100);
	else
		curOpacity = obj.filters.alpha.opacity;
	
	/*if (curOpacity == 0) {
		//obj.style.MozOpacity
		obj.filters.alpha.opacity = 0;
	}*/
		
	
	// Check if this is a new object
	if (typeof(obj.tId) != 'undefined') 
		clearTimeout(obj.tId); // Get rid of previous timeout for this object
	else
		obj.startOpacity = curOpacity; // Store the original opacity within the object itself

	if (destOpacity == -1)
		destOpacity = obj.startOpacity; // Fade back to original opacity

	// Fix mozilla bug
	if (destOpacity == 100)
		destOpacity = 99;

	// Get difference between destination opacity and current opacity
	diff = destOpacity - curOpacity;
	// Set default direction to "fade in"
	direction = 1;
	
	if (curOpacity >= destOpacity)
		direction = -1; // Request has been made to fade out so reverse direction

	// Get the required change (Minimum between specified delta and what's left to go)
	delta = Math.min(direction * diff, delta);

	/*newOpacity = (curOpacity + (direction * delta));
	alert(newOpacity);
	newOpacity = ((newOpacity == 100) ? 99.999 : newOpacity);*/

	if(obj.style.MozOpacity) {
		obj.style.MozOpacity = (curOpacity + (direction * delta)) / 100;
		obj.style.MozOpacity = newOpacity;
		//newOpacity = obj.style.MozOpacity * 100;
		
	} else {
		obj.filters.alpha.opacity += direction * delta;
		newOpacity = obj.filters.alpha.opacity;
	}
	
	/*if (newOpacity == 99.999)
		newOpacity = 100*/
	
	//obj.mine += "Calc is " + ((curOpacity + (direction * delta)) / 100);
	if (newOpacity != destOpacity) {
		// Create a new timeout for this object
		obj.tId = setTimeout("fade('"+obj.id+"',"+destOpacity+","+rate+","+delta+")",rate);
		//obj.mine += ("  After is " + newOpacity + "this is" + "fade('"+obj.id+"',"+destOpacity+","+rate+","+delta+")\n");
	}
}


//addLoadEvent(collapseAutoAttach);

function collapseAutoAttach() {
	var fieldsets = document.getElementsByTagName('fieldset');
	var legend, fieldset;
	for (var i = 0; fieldset = fieldsets[i]; i++) {
		if (!hasClass(fieldset, 'Collapsible')) {
			continue;
		}
		legend = fieldset.getElementsByTagName('legend');
		if (legend.length == 0) {
			continue;
		}
		legend = legend[0];
		var a = document.createElement('a');
		a.href = '#';
		a.onclick = function() {
			toggleClass(this.parentNode.parentNode, 'Collapsed');
			if (!hasClass(this.parentNode.parentNode, 'Collapsed')) {
				collapseScrollIntoView(this.parentNode.parentNode);
				if (typeof textAreaAutoAttach != 'undefined') {
					// Add the grippie to a textarea in a collapsed fieldset.
					textAreaAutoAttach(null, this.parentNode.parentNode);
				}
			}
			this.blur();
			return false;
		};
		a.innerHTML = legend.innerHTML;
		while (legend.hasChildNodes()) {
			removeNode(legend.childNodes[0]);
		}
		legend.appendChild(a);
		collapseEnsureErrorsVisible(fieldset);
	}
}

function collapseEnsureErrorsVisible(fieldset) {
	if (!hasClass(fieldset, 'collapsed')) {
		return;
	}
	var inputs = [];
	inputs = inputs.concat(fieldset.getElementsByTagName('input'));
	inputs = inputs.concat(fieldset.getElementsByTagName('textarea'));
	inputs = inputs.concat(fieldset.getElementsByTagName('select'));
	for (var j = 0; j<3; j++) {
		for (var i = 0; i < inputs[j].length; i++) {
			if (hasClass(inputs[j][i], 'error')) {
				return removeClass(fieldset, 'Collapsed');
			}
		}
	}
}

function collapseScrollIntoView(node) {
	var h = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
	var offset = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
	var pos = absolutePosition(node);
	if (pos.y + node.scrollHeight > h + offset) {
		if (node.scrollHeight > h) {
			window.scrollTo(0, pos.y);
		} else {
			window.scrollTo(0, pos.y + node.scrollHeight - h);
		}
	}
}
