//******************************************************************************************
// Global Scope Variables
//******************************************************************************************
var selectsHidden;
var heightDiff = 0;
var widthDiff = 0;

//******************************************************************************************
//Help popup functionality

function displayPopUp(icon, popUpID, xShift, yShift, fade, hideSelects, alignAbsolute)
{
    icon.style.cursor = 'pointer';
    
    // Set Pop Up text and display
    var popUp = document.getElementById(popUpID);

    popUp.style.display = 'block';
    popUp.style.position = 'absolute';
    popUp.style.zIndex = '9999';
    
    // Set Pop Up position below icon image
    var xPos = getAscendingLefts(icon);
    var yPos = getAscendingTops(icon);
    
    if (!alignAbsolute)
		alignAbsolute = false;
    
	if (!alignAbsolute)
	{
		if (xShift)
			xPos = xPos + xShift;
	        
		if (yShift)
			yPos = yPos + yShift;
		
		popUp.style.top = (yPos + (icon.clientHeight) + 1) + 'px';
		popUp.style.left = (xPos + (icon.clientWidth) + 1) + 'px';
	}
	else
	{
		popUp.style.top = yPos + 'px';
		popUp.style.left = xPos + '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';
    }
    
    if ( horizontalScrollRequired(popUp) )
    {
        var newLeft = parseInt(popUp.style.left.substr(0, (popUp.style.left.length - 2))) - parseInt(widthDiff) - 5;
        popUp.style.left = newLeft + 'px';
        
        // Reset variable
        widthDiff = 0;
    }
    
    // Hide selects overlapping pop up
    if (hideSelects)
    {
        if (hideSelects == true)
            checkSelectOverlap(popUp);
    }
    
    // Fade in pop up
    if (fade)
    {
        if (fade == true)
            fadePopUp(popUp, 0, 100, 500);
    }
    
    // Hide selects overlapping pop up
    if (hideSelects)
    {
        if (hideSelects == true)
            checkSelectOverlap(popUp);
    }
}

//Ascertains the correct left position...
function getAscendingLefts(elem)
{
    if (elem == null)
        return 0;
    else
        return elem.offsetLeft + getAscendingLefts(elem.offsetParent);
}

//Ascertains the correct top position...
function getAscendingTops(elem)
{
    if (elem == null)
        return 0;
    else
        return elem.offsetTop + getAscendingTops(elem.offsetParent);
} 

// Work out whether the pop up window when opened will be taller than the screen available
function scrollRequired(popUp)
{
    var scrollY, screenHeight;

    if (document.all) 
    {
        if (!document.documentElement.scrollTop)
            scrollY = document.body.scrollTop;
        else
            scrollY = document.documentElement.scrollTop;
    }
    else
        scrollY = window.pageYOffset;

    if ( document.all )
       screenHeight = document.documentElement.clientHeight;
    else
       screenHeight = window.innerHeight;

    var bottomPos = parseInt(popUp.style.top.substr(0, (popUp.style.top.length - 2))) + parseInt(popUp.clientHeight);
    var totalHeight = parseInt(scrollY) + parseInt(screenHeight);

    if ( bottomPos > totalHeight )
    {
        heightDiff = parseInt(bottomPos) - parseInt(totalHeight);
        return true;
    }
    else
        return false;
}

// Work out whether the pop up window when opened will be wider than the screen available
function horizontalScrollRequired(popUp)
{
    var scrollX, screenWidth;
 
    if (document.all) 
    {
        if (!document.documentElement.scrollLeft)
            scrollX = document.body.scrollLeft;
        else
            scrollX = document.documentElement.scrollLeft;
    }
    else
        scrollX = window.pageXOffset;

    if ( document.all )
       screenWidth = document.documentElement.clientWidth;
    else
       screenWidth = window.innerWidth;

    var rightPos = parseInt(popUp.style.left.substr(0, (popUp.style.left.length - popUp.style.left.indexOf("px")) + 1)) + parseInt(popUp.clientWidth);
    var totalWidth = parseInt(scrollX) + parseInt(screenWidth);

    if ( rightPos > totalWidth )
    {
        widthDiff = parseInt(rightPos) - parseInt(totalWidth);
        return true;
    }
    else
        return false;
}

//Fade the pop up.
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 the pop up.
function hidePopUp(popUp, fade)
{
    popUp = document.getElementById(popUp);
    
    if (fade)
    {
        if (fade == true)
        {
            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 the select controls that have been hidden.
function showSelect()
{
    if (selectsHidden)
    {
        // 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;
    }
}

// Check if the pop up control will overlap any select elements & hide them
function checkSelectOverlap(popUp)
{
    selectsHidden = new Array();

    var selectControls = new Array();

    selectControls = document.getElementsByTagName('select');

    var popUpxPos = getAscendingLefts(popUp);
    var popUpyPos = getAscendingTops(popUp);

    for ( var x = 0; x < selectControls.length; x++ )
    {
        var selectControl = selectControls[x];

        if (selectControl.id.indexOf(popUp.id) == -1)
        {
            var selectxPos = getAscendingLefts(selectControl);
            var selectyPos = getAscendingTops(selectControl);
            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 other key strokes...
    if (allowableCharacterCode(characterCode))
        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, "img_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);

//******************************************************************************************
// Script to overcome the validation summary scrolling to the top
//******************************************************************************************
var _obj_activevalidationsummary=null;
function saveLocalValidationSummary(validationsummaryid)
{
//        alert("save validation summary id = " + validationsummaryid);
    _obj_activevalidationsummary = document.getElementById(validationsummaryid);
}
function gotoActiveSummary()
{
//    alert("goto active summary.");
    if (_obj_activevalidationsummary != null)
    {
        var coors = findPos(_obj_activevalidationsummary);
        window.scrollTo(coors[0],coors[1]);
        _obj_activevalidationsummary = null;
    }
}
function scrolltoValidationSummaryScript()
{
//    alert("ValidationSummary registration on server code behind.");
    if (typeof(ValidatorOnSubmit) == "function") 
    {
        var isValidated = ValidatorOnSubmit();
        if (!isValidated)
        {
            gotoActiveSummary();
            return false;
        }
        return true;
    }
    else
		return true;
}
function findPos(obj) 
{
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

//******************************************************************************************
// Misc snippets
//******************************************************************************************

// Changed the mouse cursor as appropriate.
function mousePointer(element, style)
{
    if (style == 'pointer')
    {
        if (document.all)
            element.style.cursor = 'hand';
        else
            element.style.cursor = 'pointer';
    }
    else
    {
        element.style.cursor = 'default';
    }
}

//Captures key down events and clicks a button if it's enter.
function keyPressEvent(buttonToClick, e)
{
	try
	{
		if (!e) e = window.event;
		
		if (e.keyCode == 13)
		{	
			e.returnValue = false;
			e.cancelBubble = true;
			
			if (buttonToClick != '')
			{
				$get(buttonToClick).click();
			}
		}		
	}
	catch (e)
	{
		alert(e.message);
	}
}	

function checkMaxLength(e, element, maxLength)
{
	var characterCode;
	var isNewCharacter = false;
	var retVal = true;

    characterCode = (e.which) ? e.which : event.keyCode
    
    if (!allowableCharacterCode(characterCode))
    {   
		if (element.value.length >= maxLength)
		{
			retVal = false;
		}
	}
	
	return retVal;
}

function allowableCharacterCode(characterCode)
{
	var retVal = false;
	
	//Backspace and tab.
	if (characterCode >= 8 && characterCode <= 9)
	{
		retVal = true;
	}
		
	//Shift, control, alt, pause, break, caps lock.
	if (characterCode >= 16 && characterCode <= 20)
		retVal = true;
	
	//Escape.
	if (characterCode == 27)
		retVal = true;
	
	//Page up, page down, end, home, left arrow, up arrow, right arrow, down arrow.
	if (characterCode >= 33 && characterCode <= 40)
		retVal = true;
		
	//Insert and delete.
	if (characterCode >= 45 && characterCode <= 46)
		retVal = true;
	
	return retVal;
}