//******************************************************************************************
//                COPYRIGHT ENDSLEIGH INSURANCE SERVICES LIMITED 2007
//******************************************************************************************
//   PROJECT         :   insurance.net
//   LANGUAGE        :   JavaScript
//   FILENAME        :   Helper.js
//   ENVIRONMENT     :   Microsoft Visual Studio
//******************************************************************************************
//   FILE FUNCTION   :   
//   EXECUTABLE TYPE :   JS
//   SPECIFICATION   :   None
//
//   RELATED DOCUMENTATION : None
//
//******************************************************************************************
//   ABSTRACT        :   JavaScript helper functions used by Endsleigh Product websites.
//                       
//   AUTHOR          :   C. Newton       CREATION DATE : 21-Aug-2007
//
//******************************************************************************************
//   BUILD INFORMATION   :   Endsleigh Build System
//   EXECUTABLE NAME     :   
//   MAIN ENTRY POINTS   :   
//
//   EVENTS              :   
//
//******************************************************************************************
//   PVCS SECTION:
//   ~~~~~~~~~~~~~
//   PVCS FILENAME: $Logfile:   Z:\Endsleigh\Resources\Web\Scripts\Helper.js  $
//   PVCS REVISION: $Revision:   1.0  $
//
//   $Log:   Z:\Endsleigh\Resources\Web\Scripts\Helper.js  $
//
//******************************************************************************************

//******************************************************************************************
// Global Scope Variables
//******************************************************************************************
var heightDiff = 0;

//******************************************************************************************
// Array Extension Functions
//******************************************************************************************

//used to remove error image elements from array
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

//******************************************************************************************
// General Helper Functions
//******************************************************************************************

/*
Displays red x images for validators that fail.
Validators and red x image containing span ids must follow naming conventions, and img itself must have class .errorIcon and be inside a span with this id.
The img is made visible/hidden, not the span.
*/

function setErrorImagesAfterValidation(valGroupName, arrReqPrefixes, errImgSuffix) {
    try {
        if ($) {

            var idsFailed = [];

            if (arrReqPrefixes == undefined || arrReqPrefixes == null) {
                arrReqPrefixes = ['req_', 'regex_', 'cust_'];
            }

            if (errImgSuffix == undefined || errImgSuffix == null) {
                errImgSuffix = '_errImg';
            }

            for (var i = 0; i < Page_Validators.length; i++) {
                var val = Page_Validators[i];
                if (valGroupName == undefined || valGroupName == null || valGroupName == '' || IsValidationGroupMatch(val, valGroupName)) {
                    var id = val.id;
                    for (var j = 0; j < arrReqPrefixes.length; j++) {
                        id = id.replace(arrReqPrefixes[j], '');
                    }

                    id += errImgSuffix;

                    if (val.isvalid) {
                        $("#" + id).hide();
                    }
                    else {
                        idsFailed.push(id);
                    }                    
                }
            }

            for (var i = 0; i < idsFailed.length; i++) {
                var id = idsFailed[i];
                $("#" + id).show();
            }

        }
    }
    catch (e) {
    }
}

// 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
//******************************************************************************************
var popUps = new Array();

function displayPopUpHelp(icon, popUpID) 
{ 	
	var showHelp = null;
	
	for (var i = 0; i < popUps.length; i++)
	{
		if (popUps[i].HelpPopUp.id == popUpID)
		{
			showHelp = popUps[i];
			break;
		}
	}
	
	if (showHelp == null)
	{
		showHelp = new ShowHelp(icon.id, null, popUpID);
		popUps[popUps.length] = showHelp;
	}
	
	showHelp.displayHelp();
}

// Hide a pop up control + show any hidden select elements
function hidePopUpHelp(popUpID) 
{
	var showHelp = null;
	var i;
	for (i = 0; i < popUps.length; i++)
	{
		if (popUps[i].HelpPopUp.id == popUpID)
		{
			showHelp = popUps[i];
			break;
		}
	}
	
	if (showHelp != null)
	{
		showHelp.hideHelp();
		popUps.splice(i, 1);
	}
}

// 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);
}

//******************************************************************************************
// 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;
}

// Restrict user entry to numbers and decimal point only for an input control
function checkNumCurrency(e) 
{
	var characterCode;
	var isValid = false;

	characterCode = (e.which) ? e.which : event.keyCode
    //allow decimal point
	if (characterCode == 46 || characterCode== 45)
	{
		isValid = true;
	}
	
	// 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 and decimal point only for an input control
function checkNumDecimal(e) 
{
	var characterCode;
	var isValid = false;

	characterCode = (e.which) ? e.which : event.keyCode
    //allow decimal point
	if (characterCode == 46)
	{
		isValid = true;
	}
	
	// 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;
}

//******************************************************************************************
// 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 processElements()
{
    setUpMouseOvers();
    correctPNGImages();
}

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();

	if (this.off.src.toLowerCase().indexOf('_off') > -1) 
    {   
		var onSrc = this.off.src.replace(/_[Oo][Ff]{2}/, "_On");
        this.on.src = onSrc;
	}
	else
		this.on.src = this.off.src;
	
    // 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)
{
	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();
	var onImg = new Image();
	offImg.style.filter = img.style.filter;
	
	if (imgSrc.toLowerCase().indexOf('_off') > -1) 
		onImg.style.filter = img.style.filter.replace(/_[Oo][Ff]{2}/, "_On");
	else
		onImg.style.filter = offImg.style.filter;
	
	// 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))
    {
        var images = new Array();
        images = document.getElementsByTagName('IMG');
        var pngImages = new Array();

        //Identify the png images.
        for (var x = 0; x < images.length; x++)
        {
            var img = images[x];

            if (img.src.indexOf('.png') > -1)
            {
                if (img.src.toLowerCase().indexOf('_off') == -1)
                {
                    pngImages[pngImages.length] = img;
                }
            }
        }

        //Process the png images.
        for (var x = 0; x < pngImages.length; x++)
        {
            var imgID = (pngImages[x].id) ? "id='" + pngImages[x].id + "' " : ""
            var imgClass = (pngImages[x].className) ? "class='" + pngImages[x].className + "' " : ""
            var imgTitle = (pngImages[x].title) ? "title='" + pngImages[x].title + "' " : "title='" + pngImages[x].alt + "' "
            var imgStyle = "display:inline-block;" + pngImages[x].style.cssText
            if (pngImages[x].align == "left") imgStyle = "float:left;" + imgStyle
            if (pngImages[x].align == "right") imgStyle = "float:right;" + imgStyle
            if (pngImages[x].parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
                    + " style=\"" + "width:" + pngImages[x].offsetWidth + "px; height:" + pngImages[x].offsetHeight + "px;" + imgStyle + ";"
                    + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                    + "(src=\'" + pngImages[x].src + "\', sizingMethod='image');\"></span>"
            pngImages[x].outerHTML = strNewHTML
        }
    }
}

//******************************************************************************************
// Set up MouseOver effects for all buttons on the page + Fix PNG images
//******************************************************************************************
addEvent(window, "load", processElements);

//******************************************************************************************
// 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);

// Scrolls a particular element into view.
function scrollToElement(element)
{
    if (typeof (element) == "string")
	    element = $get(element);
	    
    element.scrollIntoView();
    element.focus();
}

//******************************************************************************************
// 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();
		}
	}
}
