/*************************************************************************
 Description:  Exweb Core JS Library
 Created:      November 2006
 Author:       Mike Hearfield
 Copyright:    Vertex Financial Services 2007, 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 $(id){
		var d = document.getElementById(id);
		return d;
	}
	//====================================================================
	
	//====================================================================
	function addClass(obj,cls){
		obj.className = obj.className+" "+cls;
	}
	
	function removeClass(obj,cls){
		obj.className = obj.className.replace(cls,"");
	}

	function toggleClass(obj,cls){
		var string = obj.className;
		var cond1 = (string == cls); // it's the only thing
		var cond2 = (string.indexOf(" "+cls+" ") != -1); // it's in there
		var cond3 = (string.indexOf(cls+" ") == 0); // it's first
		var cond4 = (string.lastIndexOf(" "+cls) == string.length-cls.length); // it's last
		if( cond1 || cond2 || cond3 || cond4){
			string = string.replace(cls,"");
		}else{
			string = string+" "+cls;
		}
		obj.className = string;
	}
	//====================================================================
	
	//====================================================================
	function toggleBlock(id){	  
		if($(id).style.display != "block")
			$(id).style.display = "block";
		else
			$(id).style.display = "none";
	}
	//====================================================================
	
	//====================================================================
	function centreBlock(id){
		var posTop = (document.body.parentNode.scrollTop + 150);
		$(id).style.top = posTop + "px";		
		var posLeft = (document.body.offsetWidth/2) - ($(id).offsetWidth/2);
		$(id).style.left = posLeft + "px";
	}
	//====================================================================
	
	//====================================================================
	function showMe(id){
		$(id).className = "expand";
	}
	function hideMe(id){
		$(id).className = "collapse";
	}
	function toggleMe(id){
		if($(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 = $(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($(id).className == "expand"){
			focusOnFirstFieldIn(id);
		}
	}
	//====================================================================

	//====================================================================
	function setupDTs(id){
		var dta = $(id).getElementsByTagName("dt");
		for(var i=0, j=dta.length; i<j; i++){			
			dta[i].onmouseover = function(){addClass(this,"hover");};
			dta[i].onmouseout = function(){removeClass(this,"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]);
		}
	}
	//====================================================================

	//====================================================================
	function hoverLIs(id){
		var lia = $(id).getElementsByTagName("li");
		for(var i=0, j=lia.length; i<j; i++){			
			lia[i].onmouseover = function(){addClass(this,"hover");};
			lia[i].onmouseout = function(){removeClass(this,"hover");};
		}
	}
	//====================================================================

	//==================================================================== EXPAND A THING
	function prepObjForSliding(objId){	   
		var obj = $(objId);		
		obj.style.height = obj.clientHeight + 'px';
		obj.style.display = 'none';
		addClass(obj,"onScreen");
	}
	
	function toggleSlide(objId, options){	    
		try{
			var obj = $(objId);
			if(obj.style.display != 'block'){
				Slide(objId).down(options);
				//focusOnFirstFieldIn(objId);
			}else{
				Slide(objId).up(options);
			}
		}
		catch(error){
			// Do nothing.
		}
	}
	
	//from http://firblitz.com/2007/3/6/re-how-to-create-digg-comment-style-sliding-divs-with-javascript-and-css
	var slideInUse = new Array();
	
	function Slide(objId, options) {
		try{
			this.obj = $(objId);
			this.duration = 1;
			this.height = parseInt(this.obj.style.height);
		
			if(typeof options != 'undefined') { this.options = options; } else { this.options = {}; }
			if(this.options.duration) { this.duration = this.options.duration; }
				
			this.up = function() {
				this.curHeight = this.height;
				this.newHeight = '1';
				if(slideInUse[objId] != true) {
					var finishTime = this.slide();
					window.setTimeout("Slide('"+objId+"').finishup("+this.height+");",finishTime);
				}
			}
			
			this.down = function() {
				this.newHeight = this.height;
				this.curHeight = '1';
				if(slideInUse[objId] != true) {
					this.obj.style.height = '1px';
					this.obj.style.display = 'block';
					this.slide();
				}
			}
			
			this.slide = function() {
				slideInUse[objId] = true;
				var frames = 30 * duration; // Running at 30 fps
		
				var tIncrement = (duration*1000) / frames;
				tIncrement = Math.round(tIncrement);
				var sIncrement = (this.curHeight-this.newHeight) / frames;
		
				var frameSizes = new Array();
				for(var i=0; i < frames; i++) {
					if(i < frames/2) {
						frameSizes[i] = (sIncrement * (i/frames))*4;
					} else {
						frameSizes[i] = (sIncrement * (1-(i/frames)))*4;
					}
				}
				
				for(var i=0; i < frames; i++) {
					this.curHeight = this.curHeight - frameSizes[i];
					window.setTimeout("document.getElementById('"+objId+"').style.height='"+Math.round(this.curHeight)+"px';",tIncrement * i);
				}
				
				window.setTimeout("delete(slideInUse['"+objId+"']);",tIncrement * i);
				
				if(this.options.onComplete) {
					window.setTimeout(this.options.onComplete, tIncrement * (i-2));
				}
				
				return tIncrement * i;
			}
			
			this.finishup = function(height) {
				this.obj.style.display = 'none';
				this.obj.style.height = height + 'px';
			}
			
			return this;
		}
		catch(error){
			// Do nothing.
		}
	}

	//====================================================================
	
	//==================================================================== TRIM
	String.prototype.trim = function() {
		a = this.replace(/^\s+/, '');
		return a.replace(/\s+$/, '');
	}
	//====================================================================
	function LaunchPopup(popupId, controlName)	{
	    var strPopupId = 'div' + popupId;
	    toggleBlock(strPopupId); 
	    centreBlock(strPopupId);
	    if (typeof controlName != 'undefined') {
		    $('hhidControlName').value = controlName;
		}
	}
	//====================================================================

	//====================================================================
	function ClosePopup(popupId)	{
		 var strPopupId = 'div' + popupId;
		toggleBlock(strPopupId);
		if ($('hhidControlName').value != '') {
		    var obj= $('hhidControlName').value;
		    $('hhidControlName').value = '';
		    $(obj).focus();
		}
}
//====================================================================

//====================================================================
//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;
}

//====================================================================

//====================================================================

function styleBlock(strId) {
    document.getElementById(strId).style.display = 'block';
   }
   //====================================================================

   //====================================================================
   // 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 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;
   }

   //====================================================================
   //This is the override on the ASP.NETs java script function as default button functionality doesn't work in 
   //firefox with that.
   function WebForm_FireDefaultButton(event, target) {
   	if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
   		var defaultButton;
   		if (__nonMSDOMBrowser) {
   			defaultButton = document.getElementById(target);
   		}
   		else {
   			defaultButton = document.all[target];
   		}
   		if (defaultButton && typeof (defaultButton.click) != "undefined") {
   			defaultButton.click();
   			event.cancelBubble = true;
   			if (event.stopPropagation) event.stopPropagation();
   			return false;
   		}
   		var defaultButtonHref = defaultButton.getAttribute('href');
   		if (typeof (defaultButtonHref) != "undefined") {

   			//check if onclick event exists and fire it.           
   			var defaultButtonOnclick = defaultButton.getAttribute('onclick');
   			var blnResult;
   			if (typeof (defaultButtonOnclick) != "undefined" && defaultButtonOnclick != "") {
   				blnResult = defaultButton.onclick();
   			}

   			if (blnResult != false) {
   				eval(defaultButtonHref);
   			}
   			event.cancelBubble = true;
   			if (event.stopPropagation) event.stopPropagation();
   			return false;
   		}
   	}
   	return true;
   }


