/*
======================================================================
CORE JAVASCRIPT FUNCTIONS
Revision 3.02
Written by Will and Mikey
======================================================================
BASIC VARIABLES STUFF
======================================================================
*/
var dhtmlCapable = (document.getElementById || document.all || document.layers);
var hasCookiesOn = document.cookie;
var cssCachedStyles = new Array ();	// Used as a temporary lookup table to boost performance


/* added - icky old skool js ^_- */
function swapImg (imageSource, mode)
{
	if (typeof(imageSource) == 'object')
		imageID = imageSource.id;
	else
		imageID = imageSource;

	if (document.images[imageID]) {
		// Use the faster document.images array as a first preference
		fileSplit = extractImgState(document.images[imageID].src);
		
		if (mode == 'over')
			insertChar = fileSplit['middle'] +'o';
		else if (mode == 'out')
			insertChar = fileSplit['middle'].charAt(0);
		else if (mode == 'press')
			insertChar = 'p';
		
		document.images[imageID].src = fileSplit['leading'] + insertChar + fileSplit['trailing'];
		return true;
		
	} else if (curImg = getObjectRef(imageID)) {
		// If we do not have a document.images entry, test for an object (eg. form submit buttons of type image)
		fileSplit = extractImgState(curImg.src);
		
		if (mode == 'over')
			insertChar = fileSplit['middle'] +'o';
		else if (mode == 'out')
			insertChar = fileSplit['middle'][0];
		else if (mode == 'press')
			insertChar = 'p';
		
		curImg.src = fileSplit['leading'] + insertChar + fileSplit['trailing'];
		return true;
		
	} else {
		return false;
	}
}

/*
======================================================================
CORE DHTML
======================================================================
*/
function getObjectRef (objectName)
{
	if (typeof(objectName) == 'object')
	{
		return objectName;
	}
	else if (document.getElementById && document.getElementById(objectName))  
	{
		return document.getElementById(objectName);
	}
	else if (document.all && document.all[objectName])
	{
		return document.all[objectName];
	}
	else if (document.layers && document.layers[objectName])
	{
		return document.layers[objectName];
	}
	
	return false;
}

/*
------------------------------------------------------------------------------------------
*/

function swapClass (objectName, newClass, oldClass)
{
	// Get the object based on whether we've passed an ID name or an explicit reference
	var object = getObjectRef(objectName);
	var classPrepend = '', classAppend = '', classPosition, finalClass;
	
	// Swap the class
	if (object.className)
	{
		// Rip out the old class if necessary
		if (typeof oldClass == 'string' && oldClass != '')
		{
			var classPosition = object.className.indexOf(oldClass);
			
			if (classPosition >= 0)
			{
				// We've found an old class that needs to be replaced with the new
				classPrepend = object.className.substring(0, classPosition);
				classAppend = object.className.substr(classPosition + oldClass.length);
				finalClass = classPrepend + newClass + classAppend;
				
				if (object.className != finalClass)
				{
					// Replace old with new and return
					object.className = finalClass;
					return object.className;
				}
			}
			else
			{
				// No change necessary
				return object.className;
			}
		}
		else
		{
			// Replace the class outright
			object.className = newClass;
			return object.className;
		}
	}
	else
	{
		return false;
	}
}

/*
------------------------------------------------------------------------------------------
*/

function setStyle (objectName, styleName, value)
{
	var object = getObjectRef(objectName);
    object.style[styleName] = value;
}

/*
------------------------------------------------------------------------------------------
*/

function swapHighlight (objectName, polarity)
{
	var objectName = getObjectRef(objectName);
	
	// Attempt to just change the BG colour; if it fails, ignore
	switch (polarity)
	{
		case 'over':
			var changeStyle = findStyleRule('.'+ objectName.className +'over');
			if (changeStyle != false)
			{
				setStyle(objectName, 'backgroundColor', changeStyle.backgroundColor);
			}
			break;
		case 'out':
			var changeStyle = findStyleRule('.'+ objectName.className);
			if (changeStyle != false)
			{
				setStyle(objectName, 'backgroundColor', changeStyle.backgroundColor);
			}
			break;
	}
}

/*
------------------------------------------------------------------------------------------
*/

function collapseTab (newTab)
{
	// Get the object based on whether we've passed an ID name or an explicit reference
	// nb. tabSelected is defined outside of this function
	var currentTabObj = getObjectRef('tab_'+ currentTab), newTabObj = getObjectRef('tab_'+ newTab);
	
	if (!currentTabObj || !newTabObj)
	{
		alert('WARNING: The tab ['+ newTab +'] could not be located.');
		return;
	}
	
	// Hide the old tab
	var changeStyle = findStyleRule('.hideitem');
	(changeStyle != false) ? setStyle(currentTabObj, 'display', changeStyle.display) : swapClass(currentTabObj, 'hideitem');
	
	// Show the new tab
	var changeStyle = findStyleRule('.showitem');
	(changeStyle != false) ? setStyle(newTabObj, 'display', changeStyle.display) : swapClass(newTabObj, 'showitem');
	
	currentTab = newTab;
}

/*
------------------------------------------------------------------------------------------
*/

function collapseSect (sectID, polarity, imgName, imgState)
{
	var changeImg = getObjectRef(imgName);
	var changeImgTo;
	
	switch (polarity)
	{
		case 'show':
			swapClass(sectID +'_off', 'hideitem', 'showitem');
			swapClass(sectID +'_on', 'showitem', 'hideitem');
			(changeImg !== false) ? changeImgTo = imgState[0] : null;
			break;
		case 'hide':
			swapClass(sectID +'_off', 'showitem', 'hideitem');
			swapClass(sectID +'_on', 'hideitem', 'showitem');
			(changeImg !== false) ? changeImgTo = imgState[1] : null;
			break;
		case 'toggle':
			var sectRef = getObjectRef(sectID);
			
			if (sectRef.className == 'hideitem')
			{
				swapClass(sectRef, 'showitem', 'hideitem');
				(changeImg !== false) ? changeImgTo = imgState[0] : null;
			}
			else
			{
				swapClass(sectRef, 'hideitem', 'showitem');
				(changeImg !== false) ? changeImgTo = imgState[1] : null;
			}
			
			break;
		case 'on':
			swapClass(sectID, 'showitem', 'hideitem');
			(changeImg !== false) ? changeImgTo = imgState[0] : null;
			break;
		case 'off':
			swapClass(sectID, 'hideitem', 'showitem');
			(changeImg !== false) ? changeImgTo = imgState[1] : null;
			break;
		default:
			return;
	}
	
	if (changeImg !== false)
	{
		var imgSplit = extractImgState(changeImg.src);
		changeImg.src = imgSplit['leading'] + changeImgTo + imgSplit['trailing'];
	}
}

/*
------------------------------------------------------------------------------------------
*/

function collapseSectGroup (selectedValue, elementSuffix, elementPrefix)
{
	var count = (typeof elementSuffix == 'number') ? elementSuffix : elementSuffix.length - 1;
	var elementPrefix = (typeof elementPrefix == 'undefined') ? '' : elementPrefix;

	for (var i = 0; i <= count; i++)
	{
		var currentValue = (typeof elementSuffix == 'number') ? i : elementSuffix[i];
		
		if (selectedValue !== '' && selectedValue == currentValue)
		{
			collapseSect(elementPrefix + currentValue, 'on');
		}
		else
		{
			collapseSect(elementPrefix + currentValue, 'off');
		}
	}
}

/*
------------------------------------------------------------------------------------------
*/

function extractImgState (filename, lastSplitChar, includeServer)
{
	// Returns an array with ['leading'] ['middle'] and ['trailing'] elements
	var fileSplit = new Array();
	var lastSplitChar = (typeof(lastSplitChar) == 'undefined') ? '-' : lastSplitChar;
	var leadExtract = filename.lastIndexOf('-') + 1;
	var trailExtract = filename.lastIndexOf('.');
	
	fileSplit['leading'] = filename.substr(0, leadExtract);
	
	// Rip out the server prepend, as this often interferes with mouseOver sources
	if (!includeServer && fileSplit['leading'].indexOf('://') != -1)
	{
		// The indexOf '/' here starts at the 9th character in, which is pretty safe for a URL
		fileSplit['leading'] = fileSplit['leading'].substr(fileSplit['leading'].indexOf('/', 9));
	}
	
	fileSplit['middle'] = filename.substring(leadExtract, trailExtract);
	fileSplit['trailing'] = filename.substr(trailExtract);
	
	return fileSplit;
}

/*
------------------------------------------------------------------------------------------
*/

function findStyleRule (styleName)
{
	// If no stylesheets exist, return! This also denies Opera any usability until they implement this property
	if (!document.styleSheets)
	{
		return false;
	}
	
	// Check if the CSS style has already been cached (or has been searched for and explicitly set to false)
	if (cssCachedStyles[styleName] || cssCachedStyles[styleName] === false)
	{
		return cssCachedStyles[styleName];
	}
	
	// If the style has not been cached, continue	
	var theRules = new Array();
	
	// We need to count backwards, so that the last defined CSS takes precedence over the first
  	for (i = document.styleSheets.length - 1; i >= 0; i--)
	{
    	// Mozilla/IE W3C compatibility
		theRules = (document.styleSheets[i].cssRules) ? document.styleSheets[i].cssRules : document.styleSheets[i].rules;
		
		// Go through and find our style if it exists
		for (j = 0; j < theRules.length; j++)
		{
			if(theRules[j].selectorText) {
				var rulePos = theRules[j].selectorText.indexOf(styleName);
				if (rulePos != -1)
				{
					var nextChar = theRules[j].selectorText.charAt(rulePos + theRules[j].selectorText.length);
					// Make sure it's not actually a longer word mess
					if (nextChar == '' || nextChar == ',')
					{
						// Add the style to our CSS cache and then return
						cssCachedStyles[styleName] = theRules[j]['style'];
						return cssCachedStyles[styleName];
					}
				}
			}
		}
    }
	
	// Report to our cache that the style could not be found, then return false
	cssCachedStyles[styleName] = false;
	return false;
}

/*
======================================================================
WINDOW FUNCTIONS
======================================================================
*/
function openWindow (url, windowName, width, height, xpos, ypos, resizable, scrollbars, locationbar, toolbar, menubar, statusbar)
{
	var width = (!width) ? 512 : width, height =  (!height) ? 384 : height;
	
	var xpos = (xpos == 'center') ? (screen.width / 2) - (width / 2) : xpos;
	var ypos = (ypos == 'center') ? (screen.height / 2) - (height / 2) : ypos;
	
	// Options for the popup window
	var resizable = (resizable) ? 'yes' : 'no';
	var scrollbars = (scrollbars) ? 'yes' : 'no';
	var locationbar = (locationbar) ? 'yes' : 'no';
	var toolbar = (toolbar) ? 'yes' : 'no';
	var menubar = (menubar) ? 'yes' : 'no';
	var statusbar = (statusbar) ? 'yes' : 'no';
		
	return window.open(url, windowName, 'width='+ width +', height='+ height +', left='+ xpos +', top='+ ypos +', resizable='+ resizable +', scrollbars='+ scrollbars +', location='+ locationbar +', toolbar='+ toolbar +', status='+ statusbar +', menubar='+ menubar);
}

/*
------------------------------------------------------------------------------------------
*/

function confirmEvent (eventType, eventItem, extendedError, joinItem)
{
	var extendedError = (!extendedError) ? '' : "\n"+ extendedError, joinItem = (!joinItem) ? 'this' : joinItem;
	
	return confirm('Are you sure you want to '+ eventType +' '+ joinItem +' '+ eventItem +'?'+ extendedError);
}

/*
======================================================================
BROWSER COOKIE FUNCTIONS
======================================================================
*/
function setCookie (name, value, expires, path, domain, secure)
{
	var curCookie = name +'='+ escape(value)
		+((expires) ? '; expires='+ expires.toGMTString() : '') 
		+((path) ? '; path='+ path : '; path=/firefly/account')
		+((domain) ? '; domain='+ domain : '')
		+((secure) ? '; secure' : '') +';';

	document.cookie = curCookie;
}

/*
------------------------------------------------------------------------------------------
*/

function getCookie (name)
{
	var dc = document.cookie, prefix = name +'=', begin = dc.indexOf(prefix);
	  
	if (begin == -1)
	{
		return null;
	}

	begin += prefix.length;
	    
	if (dc.indexOf(prefix, begin) != -1)
	{
		begin = dc.indexOf(prefix, begin);
		begin += prefix.length;
	}
	    
	var end = document.cookie.indexOf(';', begin);
	  
	if (end == -1)
	{
		end = dc.length;
	}

	return unescape(dc.substring(begin, end));
}

/*
------------------------------------------------------------------------------------------
*/

function deleteCookie (name, path, domain)
{
	var dc = document.cookie;

	if (dc.indexOf(name) > 0)
	{
		document.cookie = name +'=;'
			+((path) ? '; path='+ path : '')
			+((domain) ? '; domain='+ domain : '')
			+'; expires=Thu, 01-Jan-70 00:00:01 GMT';
	}
}

/*
------------------------------------------------------------------------------------------
*/

function setSelection (groupID, tabID)
{
	if (hasCookiesOn != '')
	{
		setCookie('current_view['+ groupID +']', tabID);
	}
}

/*
------------------------------------------------------------------------------------------
*/

function hook ()
{
	return;
}

/*
======================================================================
LOADER
======================================================================
*/

function showLoader ()
{
	loadTimer = setTimeout('showLoaderCore(true)', 1400);
}

/*
------------------------------------------------------------------------------------------
*/

function showLoaderCore (firstRun)
{
	clearTimeout(loadTimer);
	
	waitScreen = getObjectRef('waitscreen');
		
	if (typeof(waitScreen.style) != 'object')
	{
		return;
	}
		
	if (typeof(waitScreen.style.setProperty) == 'function')
	{
		waitScreen.style.setProperty('visibility', 'visible', null);
	}
	else
	{
		waitScreen.style.visibility = 'visible';
	}
		
	hideFloatElements();
		
	/* Sets height of waitscreen, hides flash audio help */
	
	var contentHeight = document.body.offsetHeight-225;
	
	/*Could be written better, but works in IE -- See below*/
	document.getElementById('waitscreen').style.height = contentHeight + 'px';
		
	/*waitScreen.style.setProperty('height', contentHeight + 'px', null);*/
	
	step2Help = getObjectRef('step2help');

	if (typeof(step2Help.style) != 'object')
	{
		return
	}
	
	if (typeof(step2Help.style.setProperty) == 'function')
	{
		step2Help.style.setProperty('visibility', 'hidden', null);
	}
	else{
		step2Help.style.visibility = 'hidden';
	}
	
	var scrollOffset = getScrollOffset('n');
	
	if (typeof(waitScreen.style.setProperty) == 'function')
	{
		waitScreen.style.setProperty('top', scrollOffset +'px', null);
	}
	else
	{
		waitScreen.style.top = scrollOffset +'px';
	}
	
	loadTimer = setTimeout('showLoaderCore()', 20);
}

/*
------------------------------------------------------------------------------------------
*/

function getScrollOffset (returnType)
{
	var scrollX = 0, scrollY = 0, returnArray = new Array();
	
	if (typeof(window.pageYOffset) == 'number')
	{
		// Mozilla compliant
		scrollX = window.pageXOffset;
		scrollY = window.pageYOffset;
	}
	else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
	{
		// DOM compliant
		scrollX = document.body.scrollLeft;
		scrollY = document.body.scrollTop;
	}
	else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
	{
		// IE6 standards compliant mode
		scrollX = document.documentElement.scrollLeft;
		scrollY = document.documentElement.scrollTop;
	}
	
	switch (returnType.toLowerCase())
	{
		case 'x':			
			return scrollX;
			break;
		case 'y':
			return scrollY;
			break;
		default:
			return new Array(scrollX, scrollY);
			break;
	}
	
}
/*
------------------------------------------------------------------------------------------
*/

function hideFloatElements ()
{
	for (var i = 0; i < document.forms.length; i++)
	{
		for (var j = 0; j < document.forms[i].elements.length; j++)
		{
			if (document.forms[i].elements[j].type.toLowerCase() == "select-one" || document.forms[i].elements[j].type.toLowerCase() == 'select-multiple')
			{
				document.forms[i].elements[j].style.visibility = 'hidden';
			}
		}
	}
}

/**
 * Create Bar function (display progress bar)
 */

var w3c=(document.getElementById)?true:false;
var ie=(document.all)?true:false;
var N=-1;

function createBar(w,h,bgc,brdW,brdC,blkC,speed,blocks,count,action) {
	if(ie||w3c){
		var t='<div id="_xpbar'+(++N)+'" style="visibility:visible; position:relative; overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';
		t+='<span id="blocks'+N+'" style="left:-'+(h*2+1)+'px; position:absolute; font-size:1px">';
		for(i=0;i<blocks;i++){
			t+='<span style="background-color:'+blkC+'; left:-'+((h*i)+i)+'px; font-size:1px; position:absolute; width:'+h+'px; height:'+h+'px; '
			t+=(ie)?'filter:alpha(opacity=100)':'-Moz-opacity:100';
			t+='"></span>';
		}
		t+='</span></div>';
		document.write(t);
		var bA=(ie)?document.all['blocks'+N]:document.getElementById('blocks'+N);
		bA.bar=(ie)?document.all['_xpbar'+N]:document.getElementById('_xpbar'+N);
		bA.blocks=blocks;
		bA.N=N;
		bA.w=w;
		bA.h=h;
		bA.speed=speed;
		bA.ctr=0;
		bA.count=count;
		bA.action=action;
		bA.togglePause=togglePause;
		bA.showBar=function(){
			this.bar.style.visibility="visible";
		}
		bA.hideBar=function(){
			this.bar.style.visibility="hidden";
		}
		bA.tid=setInterval('startBar('+N+')',speed);
		return bA;
	}
}

function startBar(bn) {
	var t=(ie)?document.all['blocks'+bn]:document.getElementById('blocks'+bn);
	if(parseInt(t.style.left)+t.h+1-(t.blocks*t.h+t.blocks) >= 0) {
		t.style.left=-(t.h*2+1)+'px';
		t.ctr++;
		if(t.ctr>=t.count) {
			eval(t.action);
			t.ctr=0;
		}
	} else {
		t.style.left=(parseInt(t.style.left)+t.h+1)+'px';
	}
}

function togglePause() {
	if(this.tid==0) {
		this.tid=setInterval('startBar('+this.N+')',this.speed);
	} else {
		clearInterval(this.tid);
		this.tid=0;
	}
}
/*
======================================================================
AJAX FUNCTIONS
======================================================================
*/
function showLoading() {
	var item = document.getElementById('ajaxLoading'); 
	item.style.display = 'block';
	item.style.top = getScrollOffset('y')+'px';
}

/*
------------------------------------------------------------------------------------------
*/

function hideLoading() {
    setTimeout(function () {
		var item = document.getElementById('ajaxLoading'); 
		item.style.display = 'none';
    }, 120);
}
/*
------------------------------------------------------------------------------------------
*/

function moveLoader()
{
	if (window.innerHeight)
	{
		  pos = window.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  pos = document.body.scrollTop
	}
}
/*
------------------------------------------------------------------------------------------
*/

function selectPaymentMethodGroup(selectPaymentMethod,payMethodDirectDebit,payMethodCreditCard){
	
	var creditCardDiv = document.getElementById(payMethodCreditCard);
	var directDebitDiv =  document.getElementById(payMethodDirectDebit);
											
	if (selectPaymentMethod == 'DirectDebit'){
		creditCardDiv.style.display="none";
		directDebitDiv.style.display="block";
	} else if(selectPaymentMethod == 'CreditCard') {
		creditCardDiv.style.display="block";
		directDebitDiv.style.display="none";
	}
}

/*
------------------------------------------------------------------------------------------
*/
function sortCodeSetFocus(textBox,nextTextBoxName) {
    var nextTextBox = document.getElementById(nextTextBoxName);
  	if(textBox.value.length==2){ 
 		nextTextBox.focus() 
  	}
}
