// <![CDATA[
/******************************************************************************************
* Module: common.functions.js
* Version: 1.0
* Created: 20060801
* Description: Some common fucntions that we can use
* 
* CBNet Ltd
* 
* Copyright: 2006 CBNet Ltd
* 
* Email:  support@cbnet.info
* Author: Greg Shiers, Jarratt Ingram
******************************************************************************************/

/*
* Function to grab one or more elements
* @usage $('element1','element2')
* @returns Array
* @version 1.1
*/
function $( ) {
	var elements = new Array( );
	for ( var i = 0; i < arguments.length; i++ ) {
		var element = arguments[i];
		if ( typeof element == 'string' )
			element = document.getElementById ( element );
		if ( arguments.length == 1 )
			return element;
		elements.push ( element );
	}
	return elements;
}

/*
* Function to open a new window
* @usage openWindow(name, url, width, height, scroll )
* @param (name, url, width, height, scroll ) name: window name, url: page to be opened, width: window width, height: window height, scroll: window scroll
* @version 1.0
*/
function openWindow ( name , url , width , height , scroll ) {
	// Set Variables to position screen in the middle of the page
	var left = (screen.width) ? (screen.width-width)/2 : 0;
	var top = (screen.height) ? (screen.height-height)/2 : 0;

	// Open the new window
	// Set all to 0 except status cuase we need to show this for usability
	window.open(url,name,'left='+left+',top='+top+',toolbar=0,location=0,directories=0,status=1, menubar=0,scrollbars='+scroll+',resizable=0,width='+width+',height='+height);
}
/*
* Function to count charactors on a text field
* @usage countText ( field, countfield, maxlimit )
* @param ( field, countfield, maxlimit ) field: textarea that we are counting, countfield: field that updates with the true left charactors, maxlimit: max charactors
* @version 1.5
*/
function countText ( field, countfield, maxlimit ) {
	if ( document.getElementById && document.createTextNode ){
		// Lets set come variables
		var fld = $( field );
		var count = $( countfield );
		// if too long...trim it!
		( fld.value.length > maxlimit ) ? fld.value = fld.value.substring( 0, maxlimit ) : count.value = ( maxlimit - fld.value.length )
	}
}
/*
* Function to show or hide an element based on mouse event
* @usage showHideElement ( element )
* @param ( element ) element that needs the function applied
* @version 1.5
*/
function showHideElement ( element ) {
	var div = $( element );
	( div.style.display == "block" || div.style.display == "" ) ? div.style.display = "none" : div.style.display = "block" ;
}
/*
* Function to show or hide an element based on mouse event via a checkbox
* @usage showHideCheckbox ( element )
* @param ( element ) checkbox that needs the function applied
* @version 1.4
*/
function showHideCheckbox ( element , checkbox ) {
	// set the element variables
	var div = $( element ), chk = document.getElementById ( checkbox );
	( chk.checked ) ? div.style.display = "none" : div.style.display = "block";
}
/*
* Function to show or hide an element based on mouse event via a radio button
* @usage showHideRadioButton ( element, show )
* @param ( element, show ) radio button that needs the function applied, show: if you want to show the element or hide it
* @version 1.2
*/
function showHideRadioButton ( element , show ) {
	// set the element variables
	var div = $( element );
	( show ) ? div.style.display = "block" :  div.style.display = "none";
}
/*
* Function to show or hide an element based on mouse event via a radio button
* @usage showHideRadioButton ( element , selectbox , index )
* @param ( element , selectbox , index ) element: element effected, selectbox: the select box that needs to be validated, index: which index is the one to be selected
* @version 1.5
*/
function showHideSelectBox ( element , selectbox , index ) {
	// set the element variables
	var element = $( effected ), sel = $( selectbox );
	( sel.selectedIndex != index ) ? element.style.display = "none" : element.style.display = "block";
}
/*
* Function document.getElementsByClassName to find all element with a certain className
* @usage element.getElementsByClassName ( clsName )
* @param ( clsName ) the class you want to find
* @version 1.5
* @author 
*/
document.getElementsByClassName = function( clsName ){
	// Make the return value into a new arry
	var retVal = new Array();
	// Go through ALL Elements in the DOM by using the *
    var elements = document.getElementsByTagName("*");
	// Loop through ALL elements as defined
    for( var i = 0;i < elements.length;i++ ) {
		// Find all elements with a className
        if( elements[i].className.indexOf(" ") >= 0 ){
            var classes = elements[i].className.split( " " );
            for( var j = 0; j < classes.length; j++ ){
                if( classes[j] == clsName )
					// Return all elements by using the push() method which adds the next
					// element to the array of elements with the same classname
                    retVal.push( elements[i] );
            }
        }
        else if(elements[i].className == clsName)
            retVal.push ( elements[i] );
    }
	// Return the value
    return retVal;
}
/*
* Function to add a load event to the page when it loads
* to load a function with parameters we need to use addLoadListener ( function () { loadfunction ( parameters ) })
* @usage addLoadListener ( func )
* @param ( func ) the function you want to load
* @version 1.4
* @author 
*/
function addLoadListener( func ) { 
	if (typeof window.addEventListener != 'undefined') { //Check for window.addEventListener (FireFox)
    	window.addEventListener('load', func, false); // Set for FF
  	}
  	else if (typeof document.addEventListener != 'undefined') { // Check for document.addEventListener (FireFox)
    	document.addEventListener('load', func, false);
  	}
  	else if (typeof window.attachEvent != 'undefined') { // Check for window.attachEvent (IE)
    	window.attachEvent('onload', func);
  	}
  	else {
	var oldfn = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		}
		else {
			window.onload = function() {
				oldfn();
				func();
			};
		}
  	}
}
/*
* Function to add a event to a certain element
* to load a event with parameters we need to use attachEventListener ( function () { loadfunction ( parameters ) })
* @usage attachEventListener (  target, eventType, functionRef, capture  ) target: which element, eventType: which event, functionRef: which function, capture: true / false;
* @param ( func ) the function you want to load
* @version 1.1
* @returns Boolean
* @author 
*/
function attachEventListener( target, eventType, functionRef, capture ) {
	if (typeof target.addEventListener != "undefined") { //Check for target.addEventListener (FireFox)
		target.addEventListener(eventType, functionRef, capture); // Set the listener
	}
	else if (typeof target.attachEvent != "undefined") { // Check for target.attachEvent (IE)
		target.attachEvent("on" + eventType, functionRef);
	}
	else {
		eventType = "on" + eventType;

		if (typeof target[eventType] == "function") {
			var oldListener = target[eventType];

			target[eventType] = function() {
				oldListener();
				return functionRef();
			}
		}
		else {
			target[eventType] = functionRef;
		}
	}
	return true;
}
/*
* Function to remove an event to a certain element
* to load a event with parameters we need to use attachEventListener ( function () { loadfunction ( parameters ) })
* @usage detachEventListener (  target, eventType, functionRef, capture  ) target: which element, eventType: which event, functionRef: which function, capture: true / false;
* @param ( func ) the function you want to load
* @version 1.2
* @author 
*/
function detachEventListener( target, eventType, functionRef, capture ) {
	if (typeof target.removeEventListener != "undefined") {
		target.removeEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.detachEvent != "undefined") {
		target.detachEvent("on" + eventType, functionRef);
	}
	else {
		target["on" + eventType] = null;
	}
	return true;
}
/*
* Function to stop the default action of a element
* @usage stopDefaultAction ( event ) which event we want to stop
* @param ( event ) the event we want to stop
* @version 1.1
* @returns Boolean
* @author 
*/
function stopDefaultAction ( event ) {
	event.returnValue = false;
	if (typeof event.preventDefault != "undefined") {
	    event.preventDefault();
  	}
  return true;
}

// Array.prototype.inArray
// inArray Prototype Array object by EmbiMedia
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

// Function that finds the first text element of the form and set focus() to that element
// PARAM: NONE
function findFocus() {
	if (document.forms[0] != 'undefined') { // Check that there is a form
		// find the form
		if ( document.forms[0] && document.forms[0].getAttribute('id') != "login_form" ) {
			var form = document.forms[0];
			var elements = form.elements[1]; // We select elements[1] because the elements[0] is the fieldset
			if ( elements ) { // If there is an element lets focus onto it
				if (elements.type=="text" || elements.type=="textarea" || elements.type=="password" ) {
					elements.focus();
					elements.className = 'frm hover';
				}
			}
		}
		else { return false; } // return false if there is no element
	}
	else { return false; }
}
// Add the load listener to the find the focus ;)
addLoadListener( findFocus );

// This little script will preload the images for us
function preloadImages () {
	var names = ['progress'];
	// Create an object to pass the above array through the for loop below
	var objects = [];
	// Loop through all the images if there are more than 1
	for (var i = 0; i < names.length; i++) {
		objects[i] = new Image(); // Create the image object
		objects[i].setAttribute('src', '/images/icons/'+names[i] + '.gif'); // Give it a src
	}
}
// Load this when the page loads
addLoadListener( preloadImages );

/*
* Opens a rel="external" in a new window, to validate in XHTML strict
* This code was found on http://www.sitepoint.com/article/standards-compliant-world in order to be able to validate a page with 
* opening a new link in a new window without target="_blank"
* @usage addLoadListener ( externalLinks );
* @version 1.0
* @author www.sitepoint.com
*/
function externalLinks(){
	if (!document.getElementsByTagName) return; // Check for DOM / Browser compatability
	var anchors = document.getElementsByTagName("a"); // Set var, which will narrow down all the a elements in the document
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
}
// Load this function on page load
addLoadListener ( externalLinks );


/*
* Function to preload any icons / images that we might use for dynamic content
* @usage preloadImages (  ) 
* @version 1.5.2
* @author 
*/
function loadProgressBar ( elem , hidden , message ) {
	// This is not a function, but will load images on the fly as we moive along parsing the page
	var parent = $( elem );
	// If we want to hide an element
	if ( hidden ) {
		$( hidden ).style.display = "none";
	}
	// Lets create a new div to add the progress information to
	
	if ( parent ) { 
		var div = document.createElement('div');
	}
	// apprent the element (div)
	if ( div ) {
		// Set attributes for the new div
		div.setAttribute('id', 'progress');
		div.innerHTML = '<img src="/images/icons/progress.gif" height="20" width="16" alt="Progress" title="Progress" class="icor" />' + message;
		// Apprent the div to the correct element	
		parent.appendChild ( div );
	}
}
// ]]>

