/*************************************************************************
 Description:  ProNeeds Core JS Library
 Created:      21/07/2008
 Author:       Mike Hearfield - Presentation Team
 Copyright:    Vertex Financial Services 2008, All Rights Reserved.
**************************************************************************/

//====================================================================
function getNextSibling(startBrother){
	endBrother=startBrother.nextSibling;
	while(endBrother.nodeType!=1){
		endBrother = endBrother.nextSibling;
	}
	return endBrother;
}
//====================================================================


//====================================================================
function addEvent(obj, evType, fn, useCapture) {
		if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on' + evType, fn);
		return r;
	} else {
		obj['on' + evType] = fn;
	}
}
//====================================================================

//====================================================================
function ascendDOM(e, target) {
	while (e.nodeName.toLowerCase() != target && e.nodeName.toLowerCase() != 'html') {
		e = e.parentNode;
	}
	return (e.nodeName.toLowerCase() == 'html') ? null : e;
}
//====================================================================


//====================================================================
function getMultipleElementsByTagName(tagNames, parentNode) {	   
	var out = new Array();
	
	for( var i = 0, j = tagNames.length; i < j; i++ ) {
		elementsFound =	parentNode.getElementsByTagName(tagNames[i]);			
		for (var k = 0, l = elementsFound.length; k < l; k++)
			 
			out.push( elementsFound.item(k) );
	}
	
	return out;
}
//====================================================================		


//====================================================================
// Adds event to window.onload without overwriting currently 
// assigned onload functions.
function addLoadEvent(func){ 
				var oldonload = window.onload;
		if (typeof window.onload != 'function') {			        
				window.onload = func;
		}else{			        
				window.onload = function(){
								if (oldonload !=null)
								{
						oldonload();
						}
						func();
				}
		}
}
//====================================================================

//====================================================================
function showBlock(id){	
    if(document.getElementById(id) != null)
        document.getElementById(id).style.display = "block";
}
//====================================================================

//====================================================================
function hideBlock(id){
    if (document.getElementById(id) != null) {
        document.getElementById(id).style.display = "none";
        turnOffValidator(id);
    }
}
//====================================================================

//====================================================================
function toggleBlock(id){
    if (document.getElementById(id).style.display != "block")
		showBlock(id);
	else
		hideBlock(id);
}
//====================================================================

//====================================================================
function centreBlock(id){
	var div = document.getElementById(id)
	var availHeight = document.body.parentNode.clientHeight;
	var availWidth = document.body.parentNode.clientWidth;
	var offsetY = document.body.parentNode.scrollTop;
	var offsetX = document.body.parentNode.scrollLeft;
	var posTop = Math.ceil(availHeight / 2) - Math.ceil(parseFloat(div.style.height) / 2) + offsetY;
	var posLeft = Math.ceil(availWidth / 2) - Math.ceil(parseFloat(div.style.width) / 2) + offsetX;

	div.style.top = posTop + "px";
	div.style.left = posLeft + "px";
}
//====================================================================

//====================================================================
function showMe(id){
    document.getElementById(id).className = "expand";
}
function hideMe(id){
    document.getElementById(id).className = "collapse";
}
function toggleMe(id){
    if (document.getElementById(id).className == "expand")
		hideMe(id);
	else
		showMe(id);
}

function toggleName(thing){
	if(thing.innerHTML.indexOf("[+]") != -1){
		thing.innerHTML = thing.innerHTML.replace("[+]","[-]");
	}else{
		if(thing.innerHTML.indexOf("[-]") != -1){
			thing.innerHTML = thing.innerHTML.replace("[-]","[+]");
		}				
	}		
}
//====================================================================

//====================================================================
function focusOnFirstFieldIn(id){
    var inps = document.getElementById(id).getElementsByTagName("INPUT");
	for(var i=0, j=inps.length; i<j; i++){
		if(inps[i].type != "hidden"){
			inps[i].focus();
			break;
		}
	}
}

function toggleForm(id){
	toggleMe(id);
	if (document.getElementById(id).className == "expand") {
		focusOnFirstFieldIn(id);
	}
}
//====================================================================

//====================================================================
function setupDTs(id){
    var dta = document.getElementById(id).getElementsByTagName("dt");
	for(var i=0, j=dta.length; i<j; i++){			
		dta[i].onmouseover = function(){this.addClass("hover");};
		dta[i].onmouseout = function(){this.removeClass("hover");};
		dta[i].onclick = function(){toggleMe(getNextSibling(this).id);toggleName(this);};
		dta[i].setAttribute("title","Click here to expand / collapse this section.");			
		if(dta[i].className != "expand")
			hideMe(getNextSibling(dta[i]).id);
		toggleName(dta[i]);
	}
}
//====================================================================

//==================================================================== TRIM
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
}
//====================================================================

//==================================================================== 
function launchPopup(popupId)	{
	if(popupId.indexOf("div") == -1)
    popupId = 'div' + popupId;
	showBlock(popupId); 
	centreBlock(popupId);
}
//====================================================================

//====================================================================
function closePopup(popupId)	{
	hideBlock(popupId);
}
//====================================================================

//====================================================================
//Changes the first letter in the textbox to uppercase.
function sentenceCase(objId)		{
	val = objId.value;
	objId.value  = 	val.charAt(0).toUpperCase() + val.substring(1,val.length);
}
//====================================================================

//====================================================================
//Changes the first letter of each word in the textbox to uppercase.
function capitalizeFirstLetters(objId)		{
	
	val = objId.value;
	newVal = '';
	val = val.split(' ');
	for(var count=0; count < val.length; count++)  {
			index1 = val[count].indexOf("-");
			index2 = val[count].indexOf("'");
			if (index1 != -1)
			{
					index = index1;
			}
			else
			{
					index = index2;
			}
			if (index != -1)
			{
					str1 = val[count].substring(0,index + 1);
					str2 = val[count].substring(index+1, val[count].length);
					newVal += capitalizeFirstLetterOfString(str1) + capitalizeFirstLetterOfString(str2) + ' ';
			}
			else
			{
					newVal += capitalizeFirstLetterOfString(val[count]) + ' ';
			}
	}
	objId.value = newVal.trim();
}
//====================================================================

//====================================================================
function capitalizeFirstLetterOfString(value)   {
    
    value = value.substring(0,1).toUpperCase() +
			value.substring(1,value.length);
    return value;

}
//====================================================================

//====================================================================
function isInteger(sText)
{
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;

 
    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
    }
  
    if (sText.length == 0)
    {
    IsNumber = false;
    }    
    return IsNumber;
   
 }
//====================================================================

//====================================================================
function numberOfRowsSelected(){
	var arrInput = document.getElementsByTagName("input");
	var numberOfRowsChecked = 0;
	for (var i = 0; i < arrInput.length;  i++) 
	{                
		if (arrInput[i].type == 'checkbox')
		{
				if (arrInput[i].checked)
				{
						numberOfRowsChecked++;
				}		        
		}			            
	}
	return numberOfRowsChecked;
}
//====================================================================

//====================================================================
// Takes a string/int and returns a currency formatted string to 2 decimal places and append £ to value.
function addCurrency(strValue) {
    var currencySymbol = "$";
	return currencySymbol + formatCurrency(strValue);
}
//====================================================================

//====================================================================
// Takes a string/int and returns a currency formatted string to 2 decimal places.
function formatCurrency(strValue) {
	strValue = roundNumber(returnSum(strValue),2); //should now have a float with no currency symbol

	//sort out the commas
	while (strValue.toString().match(/^\d\d{3}/)){
		 strValue = strValue.toString().replace(/(\d)(\d{3}(\.|,|$))/, '$1,$2');
	}
	
	return  strValue;
}
//====================================================================

//====================================================================
// takes an int, converts to string and rounds to 2 decimal places.
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
//	result = result.toString();
//	if( (result.substr(result.indexOf(".")+1).length == 1) && (result != 0) )
//		result = result + "0"
	return result;
}
//====================================================================

//====================================================================
function returnSum(str){
	var sum;// = parseInt(str);
	sum = str.toString().trim();
	sum = sum.replace(/,/g,"");
	sum = sum.replace('$',"");
	sum = roundNumber(parseFloat(sum),2);
	
	if( (isNaN(sum)) || (sum.length == 0) )
		sum = 0;

	return sum;
}
//====================================================================

//====================================================================
function loadCalculator(calc){
	var src = "";
	var popupTitle = "";
	
	switch (calc.toLowerCase()){
		case "lifecover":
			src = "calculators/lifeCoverCalculator.html";
			popupTitle = "Life cover calculator";
			break;
		case "ip":
			src = "calculators/IPCalculator.html";
			popupTitle = "Income protection calculator";
			break;
		case "ci":
			src = "calculators/CICalculator.html";
			popupTitle = "Critical illness calculator";
			break;
		case "budget":
			src = "calculators/budgetCalculator.html";
			popupTitle = "Budget calculator";
			break;
	}
	
	if(src != ""){			
		launchPopup("divCalcLoaderPopup");
		document.getElementById("ifrCalcLoader").src = src;
		document.getElementById("popupTitle").innerHTML = popupTitle;
	}
}
//====================================================================

//====================================================================
function loadDocument(doc){
	var src = "";
	var popupTitle = "";
	
	switch (doc.toLowerCase()){
		case "how":
			src = "docs/jargonBuster.html";
			popupTitle = "How we do it";
			break;
		case "rules":
			src = "docs/productGuides.html";
			popupTitle = "Rules";
			break;
		case "awards":
			src = "docs/needsGuides.html";
			popupTitle = "Awards and testimonials";
			break;
	}
	
	if(src != ""){			
		launchPopup("divDocLoaderPopup");
		document.getElementById("ifrDocLoader").src = src;
		document.getElementById("docTitle").innerHTML = popupTitle;
	}
}
//====================================================================

//====================================================================
function getInitialWindow(passedWindow)
    {
        var currentWindow = passedWindow;
        
        if (currentWindow == null)
        {
            return null;
        }
        
        if (currentWindow.parent != null && 
            currentWindow.location.href != currentWindow.parent.location.href)
        {
            return getInitialWindow(currentWindow.parent);
        }
        else
        {
            return currentWindow;
        }
    }
    
//====================================================================

//====================================================================
    
    function loadUrlInInitialWindow(currentWindow,url)
    {
        var initialWindow = getInitialWindow(currentWindow);
        if (initialWindow != null)
        {
            try
            {
                initialWindow.location.href = url;
            }
            catch(err)
            {
            }
            
        }
    }
//====================================================================

//====================================================================
// This method will going to return the all validators attached to a 
//control
function getAttachedValidators(control)
{
    var attachedValidators = new Array();
    var index;
    
    if (Page_Validators != null && control != null)
    {
        for(var index=0;index<Page_Validators.length;index++)
        {
            if (control.id == Page_Validators[index].controltovalidate)
            {
                attachedValidators.push(Page_Validators[index]);
            }
        }
    }
    return attachedValidators;
}
//====================================================================


//====================================================================
// This method fire all the validators attached with the passed in control.
function fireAttachedValidators(control) {
    controlToValidate = document.getElementById(control);
    if (controlToValidate) {
        var attachedValidators = getAttachedValidators(controlToValidate);
        //fire validator again
        for (var index = 0; index < attachedValidators.length; index++) {        
            ValidatorValidate(attachedValidators[index])  
            if (!attachedValidators[index].isvalid)
            {
                return false;
            }
        }
    }
    return true;
}

//====================================================================
// This method will going to place transparent div on the screen, so that
// user can't modify anything till that div is showing

function showTransparentScreen() {
    if ($(".divWrapper")) {
        $(".divWrapper").height(Math.max($("#divOuter").height(), $(document).height()));
        $(".divWrapper").width(Math.max($("#divOuter").width(), $(document).width()));
    }
}

//====================================================================
//This method hides the transparent div on the screen
function hideTransparentScreen() {
    
    if ($(".divWrapper")) {
        $(".divWrapper").height("0px");
        $(".divWrapper").width("0px");
    }
    if (document.getElementById("imgRefreshing") != null)
        document.getElementById("imgRefreshing").style.display = 'none';
}

//====================================================================
//This method return the width of screen
function pageWidth()
{
        return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;
}
//====================================================================
//This method return the height of screen 
function pageHeight() 
{       return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;
}

//====================================================================

//====================================================================
function SetPackageCostStyle() {

 	$("#spnSolutionPrice").each(function() {
 	alert("whee!");
 		switch ($(this).html().indexOf(".") - 1) {
 			case 2: $(this).css({ fontSize: "2.1em", paddingTop: "25px" }); break; //£10
 			case 3: $(this).css({ fontSize: "1.9em", paddingTop: "26px" }); break; //£100
 			case 4: $(this).css({ fontSize: "1.7em", paddingTop: "27px" }); break; //£1000
 			case 5: $(this).css({ fontSize: "1.5em", paddingTop: "29px", paddingRight: 1 }); break; //£10000
 			case 2: $(this).css({ fontSize: "2.1em", paddingTop: "25px" }); break; //£10    
 		}
 	})
 }

//====================================================================

//====================================================================
function addClassName (elem, className) 
{
    RemoveClassName(elem, className);
    elem.className = trim(elem.className + " " + className);
}
//====================================================================

//====================================================================

function removeClassName (elem, className) 
{
    elem.className = trim(elem.className.replace(className, ""));
}
//====================================================================

//====================================================================

function turnOffValidator(id) {
    if (id == "divpopSaveQuote") {
        ValidatorEnable(document.getElementById("ctl00_uctlSaveQuotes_valCompareRegExpressionEmail"), false);
        ValidatorEnable(document.getElementById("ctl00_uctlSaveQuotes_valCompareRetypeEmail"), false);
        ValidatorEnable(document.getElementById("ctl00_uctlSaveQuotes_valRegExpressionEmail"), false);
        ValidatorEnable(document.getElementById("ctl00_uctlSaveQuotes_valRequiredEmail"), false);
        ValidatorEnable(document.getElementById("ctl00_uctlSaveQuotes_valRequiredRetypeEmail"), false);
    }
}

//====================================================================

//====================================================================
//If any input type button is place in place holder for conatining 
//default button functionality then in that case its class name 
//should be added in the following array, so that action button is not 
//fired inplace of its own click.
//====================================================================
var negativeDefaultBtnList = new Array("autocomplete","search");
function fire_DefaultButton(e, target, ignoreCssCheck)
{
    var doFire = true; // should we fire the default button?
    var kCode = (window.event)?event.keyCode:e.which;
    // check to see if it's the enter key 
    if(kCode == 13){
       
        var src = (window.event)?event.srcElement:e.target;
        if(src!=null){
            var strTagName = src.tagName.toLowerCase();
            if (strTagName == "input" || strTagName == "select")
            {
                if (!ignoreCssCheck)
                {
                    var srcClass = src.className.toLowerCase();
                    for(var i=0, j=negativeDefaultBtnList.length; i<j; i++)
                    {
                        if (srcClass.indexOf(negativeDefaultBtnList[i].toLowerCase()) != -1)
                        {
                            doFire = false;
                            break;
                        }
                    }
                }
            }
            else 
            {
               doFire = false; 
            }
        }
    }
    else {
        doFire = false;
    }
    
    if (doFire)
        {
            pauseChecking();
            return  WebForm_FireDefaultButton(e, target);
        }
        
}