//******************************************************************************************
// Global Scope Variables
//******************************************************************************************
var selectsHidden;
var heightDiff = 0;

//******************************************************************************************
// General Helper Functions
//******************************************************************************************

// Limit the amount of characters user can enter in a text area...
function textAreaMaxLimit(field, maxlimit, evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode

    // cancel keypress if text is over max length
    if (field.value.length >= maxlimit)
    {
        // Allow Backspace (8) & delete (46) keys
        if ((charCode == 8) || (charCode == 46))
            return true;

        // Allow left arrow (37) & up arrow (38) & right arrow (39) & down arrow (40) keys
        if ((charCode == 37) || (charCode == 38) || (charCode == 39) || (charCode == 40))
            return true;
            
        // Allow shift (16) & Ctrl (17) & Home (36) & End (35)keys 
        if ((charCode == 16) || (charCode == 17) || (charCode == 36) || (charCode == 35))
            return true;
                    
        return false;
    }        
}

// Object that determines screen scroll position
function scrollPosition()
{
    if (document.all) 
        if (!document.documentElement.scrollTop)
        {
            this.scrollX = document.body.scrollLeft;
            this.scrollY = document.body.scrollTop;
        }
        else
        {
            this.scrollX = document.documentElement.scrollLeft;
            this.scrollY = document.documentElement.scrollTop;
        }
    else
    {
        this.scrollX = window.pageXOffset;
        this.scrollY = window.pageYOffset;
    }   
}

// Function to display a progress image in various scenarios
function showProgressImage(progressImageId, hideButton, inputControlsToValidate, inputControlsToCompare, radioControlsToValidate)
{
    var imgSrc = "";
    
    if (inputControlsToValidate != null || radioControlsToValidate != null)
    {
        var showProgress = true;
        
        // Check input control collection
        if (inputControlsToValidate != null)
            for (var x = 0; x < inputControlsToValidate.length; x++)
            {
                var controlToValidate = document.getElementById(inputControlsToValidate[x]);
                
                if (controlToValidate.value == '')
                    showProgress = false;
            }
        
        // Check input comparison collection
        if (showProgress)
            if (inputControlsToCompare != null)
            {
                var controlToCompare1 = document.getElementById(inputControlsToCompare[0]);
                var controlToCompare2 = document.getElementById(inputControlsToCompare[1]);
                
                if (controlToCompare1.value != controlToCompare2.value)
                    showProgress = false;
            }
        
        // Check radio button collection
        if (showProgress)
            if (radioControlsToValidate != null)
            {
                for (var y = 0; y < radioControlsToValidate.length; y++)
                {
                    var radioChecked = false;
                    var count = 0;
                    var radioControlName = radioControlsToValidate[y];
                    var radioControl = document.getElementById(radioControlName + "_" + count);
                    
                    while (radioControl != null)
                    {
                        if (radioControl.checked == true)
                            radioChecked = true;
                        
                        count++;
                        radioControl = document.getElementById(radioControlName + "_" + count);
                    }
                    
                    // If no radio button has been checked don't show progress
                    if (!radioChecked)
                    {
                        showProgress = false;
                        break;
                    }   
                }
            }
        
        // Show progress only if all controls are populated
	    if (showProgress)
	    {
	        // Hide button if required
	        if (hideButton != null)
	            hideButton.style.display = 'none';
    	    
	        // Display progress image	
		    document.getElementById(progressImageId).style.display = 'inline';
		
	        // Cause animated gif to reload and start animation 
	        imgSrc = document.getElementById(progressImageId).src;
	        setTimeout("document.getElementById('" + progressImageId + "').src = '" + imgSrc + "'", 0);
	    }
	    else
	    {
	        // Reset default values
	        if (hideButton != null)
	            hideButton.style.display = 'inline';
	        
	        document.getElementById(progressImageId).style.display = 'none';
	    }
	}
	else
	{
	    // Hide button if required
        if (hideButton != null)
            hideButton.style.display = 'none';
	            
	    // We have no controls to validate so display progress image	
	    document.getElementById(progressImageId).style.display = 'inline';
		
	    // Cause animated gif to reload and start animation 
	    imgSrc = document.getElementById(progressImageId).src;
	    setTimeout("document.getElementById('" + progressImageId + "').src = '" + imgSrc + "'", 0);
	}
}

// Displays a menuless pop up window
function popup(url, aname, theheight, thewidth, scrollers) 
{
    // Work out screen location
    var winX = 0;
    var winY = 0;
    var winnX =  (screen.width - thewidth) / 2;
    var winnY = (screen.height - theheight) / 2;
    
    // Parameter list
    var str_WinParams = 'top=' + winnY + ',left=' + winnX + ',toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + thewidth + ',height=' + theheight;
    
    // Open the window
    var thewindowobject = window.open(url, aname, str_WinParams);
    
    // Focus it if we can
    if (window.focus) 
        thewindowobject.focus();
}

// Adds a list item to a list
function addListItem(list, listItem)
{
	try
	{
		list.add(listItem, null);
	}
	catch (e)
	{
		list.add(listItem);
	}
}

function getClientWidth()
{
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf('msie') != -1) && (agt.indexOf('opera') == -1));

	if (is_ie)
		return document.documentElement.clientWidth;
	else
		return Math.min(window.innerWidth, document.documentElement.clientWidth);
}
function getClientHeight()
{
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf('msie') != -1) && (agt.indexOf('opera') == -1));
    
	if (is_ie)
		return document.documentElement.clientHeight;
	else
		return Math.min(window.innerHeight, document.documentElement.clientHeight);
}

//******************************************************************************************
// Help Pop Up Functions
//******************************************************************************************
function displayPopUpHelp(icon, popUpID, inPopUp) 
{ 
	// Set Pop Up text and display
	if (inPopUp == null)
	    var inPopUp = false;
	else
	    inPopUp = true;
	    
	var popUp = document.getElementById(popUpID);
	popUp.style.display = 'block';
	popUp.style.position = 'absolute';
    
	// Set Pop Up position below icon image
	var xPos = getAscendingLefts(icon, inPopUp);
	var yPos = getAscendingTops(icon, inPopUp);
	
	if (!inPopUp)
	{
	    popUp.style.top = (yPos + (icon.offsetHeight + 3)) + 'px';
	    popUp.style.left = (xPos + (icon.offsetHeight + 3)) + 'px';
	}
	else
	{
	    popUp.style.top = (yPos + (icon.offsetHeight / 2) - (popUp.offsetHeight / 2)) + 'px';
	    popUp.style.left = (xPos + (icon.offsetHeight + 3)) + 'px';
	}
	
	if ( scrollRequired(popUp) )
	{
	    var newTop = parseInt(popUp.style.top.substr(0, (popUp.style.top.length - 2))) - parseInt(heightDiff) - 5;
	    popUp.style.top = newTop + 'px';
	    
	    // Reset variable
	    heightDiff = 0;
	}
	
	// Hide selects overlapping pop up
    checkSelectOverlap(popUp, inPopUp);

	// Fade in pop up
	fadePopUp(popUp, 0, 100, 500);
	
	// Hide selects overlapping pop up
    checkSelectOverlap(popUp, inPopUp);
}

// Ascertains the correct left position...
function getAscendingLefts(elem, inPopUp)
{
	if (elem == null)
		return 0;
    else if (elem.style.position=='absolute' && inPopUp)
        return 0;
	else
		return elem.offsetLeft + getAscendingLefts(elem.offsetParent, inPopUp);
}

// Ascertains the correct top position...
function getAscendingTops(elem, inPopUp)
{
	if (elem == null)
		return 0;
    else if (elem.style.position=='absolute' && inPopUp)
        return 0;
	else
		return elem.offsetTop + getAscendingTops(elem.offsetParent, inPopUp);
}

// Work out whether the pop up window when opened will be taller than the screen available
function scrollRequired(popUp, inPopUp)
{
    var screenHeight = 0;
    var scrollPos = new scrollPosition();
    
    if ( document.all )
       screenHeight = document.documentElement.offsetHeight;
    else
       screenHeight = window.innerHeight;
       
    var bottomPos = getAscendingTops(popUp, inPopUp);
      
    var bottomPos = parseInt(popUp.style.top.substr(0, (popUp.style.top.length - 2))) + parseInt(popUp.offsetHeight);
    var totalHeight = parseInt(scrollPos.scrollY) + parseInt(screenHeight);
    
    if ( bottomPos > totalHeight )
    {
        heightDiff = parseInt(bottomPos) - parseInt(totalHeight);
        return true;
    }
    else
        return false;
}

// Use the setTimeout method to fad in a pop up window
function fadePopUp(popUp, opacStart, opacEnd, millisec) 
{ 
    // Speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    // Set the opacity
    if ( opacStart < opacEnd ) {
		for(i = opacStart; i <= opacEnd; i++) { 
			setTimeout("setOpacity(" + i + ", '" + popUp.id + "')", (timer * speed)); 
			timer++; 
		} 
    }
    else {
		for(i = opacStart; i >= opacEnd; i--) { 
			setTimeout("setOpacity(" + i + ", '" + popUp.id + "')", (timer * speed)); 
			timer++; 
		}
    }
} 

// Set the opacity of a pop up control
function setOpacity(opacity, popUpID) 
{  
    var popUp = document.getElementById(popUpID);
        
    // Set opacity values to work in all browsers
    popUp.style.opacity = (opacity / 100); 
    popUp.style.MozOpacity = (opacity / 100); 
    popUp.style.KhtmlOpacity = (opacity / 100); 
    popUp.style.filter = 'alpha(opacity=' + opacity + ')'; 
}

// Hide a pop up control + show any hidden select elements
function hidePopUpHelp(popUp) 
{
	popUp = document.getElementById(popUp);
    popUp.style.opacity = (0); 
    popUp.style.MozOpacity = (0); 
    popUp.style.KhtmlOpacity = (0); 
    popUp.style.filter = 'alpha(opacity=0)'; 
    popUp.style.display = 'none';
    
    // Show all select controls
    showSelect();
}

// Show any hidden select elements in the control array
function showSelect() 
{
	if (selectsHidden.length != 0)
	{
		// Show all select controls as they may have been hidden
		for ( var x = 0; x < selectsHidden.length; x++ ) {
			selectsHidden[x].style.visibility = 'visible';
		}
		
		selectsHidden.length = 0;
    }
    else
    {
		// Need to do this for when pop up is not closed using onmouseout
		var selects = new Array();
		selects = document.getElementsByTagName('SELECT');
		
		// Show all select controls as they may have been hidden
		for ( var x = 0; x < selects.length; x++ ) {
			selects[x].style.visibility = 'visible';
		}
    } 
}

// Check if the pop up control will overlap any select elements & hide them
function checkSelectOverlap(popUp, inPopUp) 
{
	selectsHidden = new Array();
    var selectControls = new Array();
    selectControls = document.getElementsByTagName('select');
    
    var popUpxPos = getAscendingLefts(popUp, inPopUp);
    var popUpyPos = getAscendingTops(popUp, inPopUp);

    for ( var x = 0; x < selectControls.length; x++ ) 
    {
        var selectControl = selectControls[x];
        
        var selectxPos = getAscendingLefts(selectControl, inPopUp);
		var selectyPos = getAscendingTops(selectControl, inPopUp);
		
		var selectxPosMax = selectxPos + selectControl.offsetWidth;
		var selectyPosMax = selectyPos + selectControl.offsetHeight;
        
        // Work out if select control sits within the dimensions of the pop up and hide if it does
        if ( selectxPos >= popUpxPos && selectxPosMax <= (popUpxPos + popUp.offsetWidth) ) {
            if (selectyPosMax >= popUpyPos && selectyPos <= (popUpyPos + popUp.offsetHeight) ) 
            {
                selectControl.style.visibility = 'hidden';
                selectsHidden[selectsHidden.length] = selectControl;
            }
        }
    }
}

//******************************************************************************************
// Restrict Key Strokes to Input Controls
//******************************************************************************************
// Restrict user entry to numbers only for an input control
function checkNum(e) 
{
	var characterCode;
	var isValid = false;

    characterCode = (e.which) ? e.which : event.keyCode

    
    // Allow numbers
    if ((characterCode >= 48) && (characterCode <= 57))
        isValid = true;
        
    // Allow Tab & Backspace
    if ((characterCode == 8) || (characterCode == 9))
        isValid = true;
  
    if (!isValid)
    {
        try 
        {
            event.cancelBubble = true;
            event.returnValue = false;	
        }
        catch(e)
        {
            return false;
        }
        return false;
    }
    else
    
    return true;   
}

// Restrict user entry to numbers + spaces only for an input control
function checkNumSpaces(e) 
{
	var characterCode;
	var isValid = false;

    characterCode = (e.which) ? e.which : event.keyCode
    
    // Allow numbers
    if ((characterCode >= 48) && (characterCode <= 57))
        isValid = true;
        
    // Allow Spaces, Tab & Backspace
    if ((characterCode == 32) || (characterCode == 8) || (characterCode == 9))
        isValid = true;
    
    if (!isValid)
    {
        try 
        {
            event.cancelBubble = true;
            event.returnValue = false;	
        }
        catch(e)
        {
            return false;
        }
        return false;
    }
    else
    
    return true; 
}

// Restrict user entry to numbers, letters and [-&,] characters only for an input control
function checkAlphaNum(e) 
{
	var characterCode;
	var isValid = false;

    characterCode = (e.which) ? e.which : event.keyCode
    
    // Allow numbers
    if ((characterCode >= 48) && (characterCode <= 57))
        isValid = true;
    
    // Allow upper case letters
    if ((characterCode >= 65) && (characterCode <= 90))
        isValid = true;
    
    // Allow lower case letters
    if ((characterCode >= 97) && (characterCode <= 122))
        isValid = true;
    
    // Allow the characters [-&, '] + Tab & Backspace
    if ((characterCode == 45) || (characterCode == 38) || (characterCode == 44) || 
        (characterCode == 32) || (characterCode == 39) || (characterCode == 8) ||
        (characterCode == 9))
        isValid = true;
    
    if (!isValid)
    {
        try 
        {
            event.cancelBubble = true;
            event.returnValue = false;	
        }
        catch(e)
        {
            return false;
        }
        return false;
    }
    else
    
    return true; 
}

// Restrict user entry to numbers, letters and spaces characters only for an input control
function checkAlphaNumPostcode(e) 
{
	var characterCode;
	var isValid = false;

    characterCode = (e.which) ? e.which : event.keyCode
    
    // Allow numbers
    if ((characterCode >= 48) && (characterCode <= 57))
        isValid = true;
    
    // Allow upper case letters
    if ((characterCode >= 65) && (characterCode <= 90))
        isValid = true;
    
    // Allow lower case letters
    if ((characterCode >= 97) && (characterCode <= 122))
        isValid = true;
    
    // Allow the characters [-&, '] + Tab & Backspace
    if ((characterCode == 32) || (characterCode == 8) || (characterCode == 9))
        isValid = true;
    
    if (!isValid)
    {
        try 
        {
            event.cancelBubble = true;
            event.returnValue = false;	
        }
        catch(e)
        {
            return false;
        }
        return false;
    }
    else
    
    return true;
}

//******************************************************************************************
// Event Handlers
//******************************************************************************************
function addEvent(obj, type, fn)
{
	if (obj.addEventListener)
		obj.addEventListener(type, fn, false);
	else if (obj.attachEvent)
		obj.attachEvent("on" + type, fn);
}

function removeEvent(obj, type, fn)
{
    if (obj.removeEventListener)
        obj.removeEventListener(type, fn, false);
    else if (obj.detachEvent)
        obj.detachEvent("on" + type, fn);
}

//******************************************************************************************
// ImageButton MouseOver Effects = Correction of PNG Images
//******************************************************************************************
var arrButtonMouseOvers = new Array();
var arrButtonMouseOversPNG = new Array();
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function setUpMouseOvers(e)
{
    var arrInputs = document.getElementsByTagName('input');
    
    for(var x = 0; x < arrInputs.length; x++)
    {
        var img = arrInputs[x];
    
        if (img.type != 'undefined')
            if (img.type == 'image')
            {
                if ((version >= 5.5) && (version < 7) && (img.src.toLowerCase().indexOf('.png') > -1))
                    new buttonMouseOverPNG(img);
                else
                    new buttonMouseOver(img);
            }
    }
}

function buttonMouseOver(obj) 
{
    // If the objects already in the array, leave it
    for (var i = 0; i < arrButtonMouseOvers.length; i++) 
        if (obj == arrButtonMouseOvers[i].obj) 
            return;

    // Assign image object to this object and create image objects
    this.obj = obj;
    this.off = new Image();
    this.off.src = obj.src;
    this.on = new Image();

    // Use regex to create the on image SRC and assign to this object
    if (this.off.src.toLowerCase().indexOf('_off') > -1) 
    {
        var onSrc = this.off.src.replace(/_[Oo][Ff]{2}/, "_On");
        this.on.src = onSrc;
    }
    else
        return;

    // Assign this object to a variable so we can assign it in functions below
    var thisObject  = this;

    // Create event handlers to change the image on mouse over
    var fnMouseOver = function() { obj.src = thisObject.on.src;  };
    var fnMouseOut = function() { obj.src = thisObject.off.src;  };
    
    addEvent(obj, "mouseover", fnMouseOver);
    addEvent(obj, "mouseout", fnMouseOut);

    // Put this object into the rollovers array
    arrButtonMouseOvers[arrButtonMouseOvers.length] = this;
}

function buttonMouseOverPNG(img)
{
    if (img.src.toLowerCase().indexOf('_off') > -1)
    {   
        var imgSrc = img.src;
        var imageName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
        img.src = imgSrc.replace(imageName, "spacer.gif");
        
        img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +  imgSrc + "', sizingMethod='image')"
        
        var offImg = new Image();
        offImg.style.filter = img.style.filter;
        
        var onImg = new Image();
        onImg.style.filter = img.style.filter.replace(/_[Oo][Ff]{2}/, "_On");

        // Assign image object to this object and create image objects
        this.obj = img;
        this.off = offImg;
        this.on = onImg;

        // Assign this object to a variable so we can assign it in functions below
        var thisObject  = this;

        // Create event handlers to change the image on mouse over
        var fnMouseOver = function() { img.style.filter = thisObject.on.style.filter;  };
        var fnMouseOut = function() { img.style.filter = thisObject.off.style.filter;  };
        
        addEvent(img, "mouseover", fnMouseOver);
        addEvent(img, "mouseout", fnMouseOut);

        // Put this object into the rollovers array
        arrButtonMouseOversPNG[arrButtonMouseOversPNG.length] = this;
    }
}

function correctPNGImages()
{
    if ((version >= 5.5) && (version < 7))
    {
        for (var x = 0; x < document.images.length; x++ )
        {
            var img = document.images[x];
            
            if (img.src.indexOf('.png') > -1)
                if (img.src.toLowerCase().indexOf('_off') == -1)
                { 
                    var imgID = (img.id) ? "id='" + img.id + "' " : ""
                    var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                    var imgStyle = "display:inline-block;" + img.style.cssText 
                    if (img.align == "left") imgStyle = "float:left;" + imgStyle
                    if (img.align == "right") imgStyle = "float:right;" + imgStyle
                    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle
                    + " style=\"" + "width:" + img.offsetWidth + "px; height:" + img.offsetHeight + "px;" + imgStyle + ";"
                    + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                    + "(src=\'" + img.src + "\', sizingMethod='image');\"></span>" 
                    img.outerHTML = strNewHTML
                }
        }
    }
}

//******************************************************************************************
// Set up MouseOver effects for all buttons on the page + Fix PNG images
//******************************************************************************************
addEvent(window, "load", setUpMouseOvers);
addEvent(window, "load", correctPNGImages);

//******************************************************************************************
// Scroll code.
//******************************************************************************************
// Variables used to override auto scrolling of validation controls
var buttonClicked = false;
var origScrollX = 0;
var origScrollY = 0;

// Set scroll coordinates when How Much button is clicked
function setScrollPosition() 
{
    // Get scroll position      
    var scrollPos = new scrollPosition();
    
    // Set gloabl variables
    origScrollX = scrollPos.scrollX;
    origScrollY = scrollPos.scrollY;
    buttonClicked = true;
}

// Called when window.onscroll event is fired - move page to original scroll position
function checkScroll()
{      
    // Get scroll position      
    var scrollPos = new scrollPosition();

    // If button has been clicked and page is scrolled to 0,0 then reset position
    if (buttonClicked && (scrollPos.scrollX == 0) && (scrollPos.scrollY == 0))
    {
        // Scroll page to its original position
        window.scrollTo(origScrollX, origScrollY);
        
        // Reset global variables
        origScrollX = 0;
        origScrollX = 0;
        buttonClicked = false;
    }   
}

//Add the event so that all scrolls are recorded.
addEvent(window, "scroll", checkScroll);

//******************************************************************************************
// Code for handling click events.
//******************************************************************************************
function buttonClickEvent(buttonToClick)
{
	if (window.event.keyCode == 13)
	{	
		event.returnValue=false;
		event.cancel = true;
		
		if (buttonToClick != '')
		{
			buttonToClick = document.getElementById(buttonToClick);
			buttonToClick.click();
		}
	}
}