// <![CDATA[
/*
* Copyright: 2005 - this.year() CB.Net Ltd IT Department
* Note: All functions below are to make sure that we are sticking to standards and are mainly
* for visual effects and loading events and handlers.
*
* General functions to use across the website, we're using the functionality of prototype.js through here too
* @page common.functions.js
* @version 2.3.0
* @author Greg Shiers, Jarratt Ingram (CB.Net Ltd)
* @copyright: CB.Net Ltd IT Department 2002 - this.year()
*/

/*
* Function to create an element
* @usage $_C( element )
* @version 1.0
*/
function $_C ( element ){
	if ( typeof document.createElement != 'undefined' ) {
		return document.createElement(element);
	}
	else {
		alert('Your browser does not support document.createElement');
	}
}
/*
* Function to get the value of a cookie
* @usage GetCookie ( name )
* @param name
* @version 1.5
*/
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) {
		return null;
	}
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring( len, end ) );
}
/*
* Function to set a new Cookie
* @usage setCookie ( name, value, expires, path, domain, secure )
* @param name
* @param value
* @param expires
* @param path
* @param domain
* @param secure
* @version 1.0
*/
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}
/*
* Function to check all checkboxes within a table
* @usage selectCookie ( name , path , domain )
* @param name
* @param path
* @param domain
* @version 1.2
*/
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) {
		document.cookie = name + '=' +
		( ( path ) ? ';path=' + path : '') +
		( ( domain ) ? ';domain=' + domain : '' ) +
		';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}
/*
* Function to show or hide an element based on mouse event
* @usage showHideElement ( element )
* @param element (object)
* @version 1.5
*/
function showHideElement ( element ) {
	var div = $( element );
	( div.style.display == "block" || div.style.display == "" ) ? div.hide() : div.show() ;
}
/*
* Function to show or hide an element based on mouse event via a checkbox
* @usage showHideCheckbox ( element )
* @param element (object)
* @version 1.4
*/
function showHideCheckbox ( element , checkbox ) {
	// set the element variables
	var div = $(element), chk = $(checkbox);
	( chk.checked ) ? div.hide() : div.show();
}
/**
* Fucntion to find the scroll position of an element
* @version 1.4
* @returns Array
* @author Greg Shiers
*/
function getScrollingPosition( ) {
	//array for X and Y scroll position
	var position = [0, 0];
	//if the window.pageYOffset property is supported
	if( typeof window.pageYOffset != 'undefined' ) {
		//store position values
		position = [
		window.pageXOffset,
		window.pageYOffset
		];
	}
	//if the documentElement.scrollTop property is supported
	//and the value is greater than zero
	if(typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0) {
		//store position values
		position = [
		document.documentElement.scrollLeft,
		document.documentElement.scrollTop
		];
	}
	//if the body.scrollTop property is supported
	else if(typeof document.body.scrollTop != 'undefined') {
		//store position values
		position = [
		document.body.scrollLeft,
		document.body.scrollTop
		];
	}
//return the array
return position;
}

/**
* Finds the view point size of an element
* @version 1.0
* @author Greg Shiers
*/
function getViewportSize() {
	var size = [0,0];

	if (typeof window.innerWidth != 'undefined') {
		size = [
			window.innerWidth,
			window.innerHeight
			];
	}
	else if (typeof document.documentElement != 'undefined'
			&& typeof document.documentElement.clientWidth != 'undefined'
			&& document.documentElement.clientWidth != 0) {
		size = [
			document.documentElement.clientWidth,
			document.documentElement.clientHeight
		];
	}
	else {
		size = [
			document.getElementsByTagName('body')[0].clientWidth,
			document.getElementsByTagName('body')[0].clientHeight
		];
	}
	return size;
}
/**
* Gets the dimenstions of the page
* @version 1.0
* @returns Array
* @author Greg Shiers
*/
function getPageDimensions() {
	var body = document.getElementsByTagName("body")[0];
	var bodyOffsetWidth = 0;
	var bodyOffsetHeight = 0;
	var bodyScrollWidth = 0;
	var bodyScrollHeight = 0;
	var pageDimensions = [0, 0];
	if (typeof document.documentElement != "undefined" && typeof document.documentElement.scrollWidth != "undefined") {
		pageDimensions[0] = document.documentElement.scrollWidth;
		pageDimensions[1] = document.documentElement.scrollHeight;
	}
	bodyOffsetWidth = body.offsetWidth;
	bodyOffsetHeight = body.offsetHeight;
	bodyScrollWidth = body.scrollWidth;
	bodyScrollHeight = body.scrollHeight;
	if (bodyOffsetWidth > pageDimensions[0]) 	{ pageDimensions[0] = bodyOffsetWidth; }
	if (bodyOffsetHeight > pageDimensions[1]) 	{ pageDimensions[1] = bodyOffsetHeight; }
	if (bodyScrollWidth > pageDimensions[0]) 	{ pageDimensions[0] = bodyScrollWidth; }
	if (bodyScrollHeight > pageDimensions[1]) 	{ pageDimensions[1] = bodyScrollHeight; }
	return pageDimensions;
}

/*
* 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";
	}
}
/*
* Function to preload any icons / images that we might use for dynamic content
* @usage preloadImages (  ) 
* @version 1.5.2
* @author 
*/
function preloadImages () {
	// This is not a function, but will load images on the fly as we moive along parsing the page
	var names = ['/icons/progress.gif','/icons/error.png'];
	// 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
		objects[i].src = '/images'+names[i]; // Give it a src
	}
}

Event.observe ( window , 'load' , function ( e ) { 
	if ( $('advanced_search') && $('search_button') ) {
		Event.observe($('search_button'), "click", function ( e ) {
			// Stop the default action
			Event.stop( e );
			if ($('advanced_search').hasClassName('none')) {
				$('advanced_search').removeClassName('none');
				$('search_button').update('<strong>Basic search</strong>').writeAttribute('title','Click here to go to the basic search');
			}
			else {
				$('advanced_search').addClassName('none');
				// Clear the values on the keyword and Bank name fields
				$('entity_select').selectedIndex = "0";
				$('keyword').clear();
				
				$('search_button').update('<strong>Advanced search</strong>').writeAttribute('title','Click here to go to the advanced search');
			}
		})
	}
	/* script that loads the box for the bank's image logo */
	if ( $('entity_logo_image') ) {
		var dimensions = $('entity_logo_image').getDimensions();
		var width = dimensions.width;
		/* if the height is less than or equal to 25 pixels, then we set the height manually at 25 pixels */
		var height = (dimensions.height <= 25 ) ? ( height = 25 ) : ( height = dimensions.height );
		/* set the width and height of the container that the logo sits in */
		$('entity_logo').setStyle({
			"width" : (width+20)+"px",
			"height" : (height+20)+"px"
		});
//		alert("image height is currently "+height+" pixels");
		/* set the padding of the entity bar at the top, as to align the text inside it */
		$('entity').setStyle ({
			paddingRight: (width+50)+"px"
		});
	}
	if ( $('success') ) {
		setTimeout(function(){
			Effect.Fade('success', { duration: 3.0 });
		}, 30000 )
	}
	// Add the external links code here, this converts as above in function
	externalLinks();
});

sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

var ajax = {
	getSimpleResults : function ( page ) {
		var element = $('tab_contents');
		element.update("&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"/images/icons/progress.gif\" class=\"icor\" /><strong>loading...</strong>");
		new Ajax.Request(page, {
			method: 'get',
			onComplete: function(transport) {
				element.update(transport.responseText);
			},
			onFailure : function () {
				element.update("There has been an error trying to retrieve the relevant data, we have informed the administrator");
				return false;
			}
		});
	},
	
	branchCode : function ( page ) {
		var element = $('bc_check');
		new Ajax.Request(page, {
			method: 'get',
			onComplete: function(transport) {
				element.update(transport.responseText).addClassName('red');
			},
			onFailure : function () {
				element.update("Error checking branch code");
				return false;
			}
		});
	}	
}

/*
* Function to add an error to the validation class written
* @usage addError 
* @param element
* @param message
* @version 1.2.1
* @author 
*/
function addError( element, message ) {
	element.next('span').removeClassName('complete').addClassName('incomplete');
	element.removeClassName('input_complete').addClassName('input_error');
	element.previous('label').update( message ).addClassName('red')
}
/*
* Function to remove an error to the validation class once validation has been confirmed
* @usage removeError 
* @param element
* @param message
* @version 1.2.1
* @author 
*/
function removeError ( element, message ) {
	element.removeClassName('input_error').addClassName('input_complete');
	element.next('span').removeClassName('incomplete').addClassName('complete');
	element.previous('label').update( message ).removeClassName('red')
}
/*
* Function to reset error to it's origional status
* @usage resetErorr 
* @param element
* @param message
* @version 1.2.1
* @author 
*/
function resetErorr ( element ) {
	element.removeClassName('input_complete').removeClassName('input_error');
	element.next('span').removeClassName('complete').removeClassName('incomplete');
}

/*
* Function to reset error to it's origional status
* @usage resetErorr 
* @param element
* @param message
* @version 1.2.1
* @author 
*/
function convertErorr ( element, message ) {
	element.removeClassName('input_complete').removeClassName('input_error');
	element.next('span').removeClassName('complete').removeClassName('incomplete');
	element.previous(0).update( message ).removeClassName('red')
}
/*
* Function to reset error to it's origional status
* @usage showTabs 
* @param element
* @param links
* @version 1.0
* @author 
*/
function showTabs( links, page ) {
	if(document.getElementById && document.createTextNode) {
		// Lets set some variables, get all the "a" elements within "Tabs" div
		var total = $('tabs').getElementsByTagName('a').length;
		var anum = total;  
		
		// set the dyunamic objects.
		var aobj = $("lnk" + anum);
		while ( aobj ) {
			// Change the class in the link element
			// Make sure that the class name is not active, if is it
			// Active, then change it to "tab", and all the rest to "tab"
			
			if (aobj.id == links) aobj.className = "active";	
			else aobj.className = "tab";	
			aobj = $("lnk" + anum--); 			
		}
		ajax.getSimpleResults( page );
	}
}

/*
 * Function to check if branch code alerady exisits
 * @usage checkBranchCode
 * @param page
 * @version 1.0
 * @author
 */
function checkBranchCode( page ) {
	// First check if there is a value in the text box.
	// Then only send an AJAX call to the server
	if ( !validation.empty($('branch_code')) ) {
		ajax.branchCode( page );
	}
}
/**
* Function reverts the field to to a password box
* @usage RevertFieldTypeToPassword
* @param field
* @version 1.4
* @author Greg Shiers
**/
function RevertFieldTypeToPassword ( field ) {
	if ( $(field).readAttribute('type') == "text" ) {
		$(field).writeAttribute('type', 'password');
	}
}
/**
* Function generate a random password
* @usage GeneratePassword
* @param field
* @version 1.4
* @author Greg Shiers
**/
function GeneratePassword( field ) {
	//$(field).writeAttribute('type', 'text');
	var length=8;
	var sPassword = "";
    var noPunction = true;
    for (i=0; i < length; i++) {
        numI = getRandomNumber();
        if (noPunction) { while (checkPunctuation(numI)) { numI = getRandomNumber(); } }
        sPassword = sPassword + String.fromCharCode(numI);
    }
    $(field).value = sPassword
	$(field).focus();
    return true;
}
/**
* Function that creates a random number
* @usage getRandomNumber
* @param N/A
* @version 1.4
* @author Greg Shiers
**/
function getRandomNumber() {
    var rndNum = Math.random()
    rndNum = parseInt(rndNum * 1000);
    rndNum = (rndNum % 94) + 33;
    return rndNum;
}
/**
* Function that creates a random number
* @usage checkPunctuation
* @param N/A
* @version 1.3
* @author Greg Shiers
**/
function checkPunctuation(num) {
    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }
    return false;
}

// ]]>