// initialise everything
var utils_init = function initialiseScript(e) {
	loadScripts();
	initFormFields();
	initQuoteMask();
	fixValidation();
	infoBoxes();
	addSearchEvent();
	replacePopupUrl();
	setUpDropdownNav();
    addHoverForIE6();
}


//// Previously in master page, moved here for tidiness
var runFill = function run_fill(evt)
{
    if (!evt)
        evt = window.event;
    if (evt.keyCode == 118)
        fillFormSingle();
    if (evt.keyCode == 119)
        fillFormCouple();
    if (evt.keyCode == 120)
        fillFormFamily();
    if (evt.keyCode == 121)
        loadValues();
}

Event.observe(window, 'load', utils_init, false);
Event.observe(document, 'keypress', runFill, false);

//(function($)
//{
//    $(document).ready(utils_init);
//    $("body").keypress(runFill);

//})(jQuery)


function addHoverForIE6() {
	var buttonClasses = ['large-button', 'double-button','white-button'];
	imagePreloader();
	for(var i = 0; i < buttonClasses.length; i++) {
		var className = buttonClasses[i];
	
		var spanEls = xGetElementsByClassName(className);
		if(spanEls.length <=0) return;

		for (var ii=0; ii<spanEls.length; ii++) {
			xWalkTree(spanEls[ii], appendHoverClass);
		}
	}

}
function xWalkTree(n, f)
{
  f(n);
  for (var c = n.firstChild; c; c = c.nextSibling) {
    if (c.nodeType == 1) xWalkTree(c, f);
  }
}

function appendHoverClass(submitButton){
	submitButton.onmouseover=function() {
	this.className+=" hover";    
	}
	submitButton.onmouseout=function() {
	this.className=this.className.replace(new RegExp(" hover\\b"), "");    
	}
}
function imagePreloader() 
{
newimage= new Image(); 
newimage.src = "/Style%20Library/Images/large-button-right-hover.gif";
}

function replacePopupUrl() {
	// replace standard href with javascript function
	var popupLinks = xGetElementsByClassName('nib-editCustom-PopupLink');
	for(var i = 0; i < popupLinks.length; i++) {
		var url = popupLinks[i].href;
		if(url.indexOf("openPopup")==-1)		
			popupLinks[i].href = 'javascript:openPopup("' + url + '");';
	}
	popupLinks = xGetElementsByClassName('ms-rteCustom-PopupLink');
	for(var j = 0; j < popupLinks.length; j++) {
		url = popupLinks[j].href;	
		if(url.indexOf("openPopup")==-1)		
			popupLinks[j].href = 'javascript:openPopup("' + url + '");';
	}	
}

function openPopup(url){
	var wleft = (screen.width - 408) / 2;
 	var wtop = (screen.height - 648) / 2;
	var popupwindow= window.open (url, "","resizable=0,status=0,scrollbars=0,width=408,height=648,left="+ wleft + ",top=" +wtop);
	
}



function fixIndicator() {
	if((navigator == null) || (navigator.userAgent == null) || (navigator.userAgent.match(/\bMSIE 6\.0\b/) == null)) return;
	
	var indicator = xGetElementById('indicator');
	var container = xGetElementById('MSO_ContentTable');
	var elementAbove = xGetElementById('page_indicator');
	
	if(indicator == null || container == null) return;
	var topPos = xHeight(container);
	xTop(indicator, topPos );
}

function getX( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
	iReturnValue += oElement.offsetLeft;
	oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

var pwdCover = null;
var pwdField = null;

function initTDPassword() {
	var pwdFields = $$('input.clear_password');
	if(pwdFields.length <=0) return;
	
	pwdField = pwdFields[0];
	pwdCover = document.createElement('span');
	pwdCover.className = 'password_cover';
	xTop(pwdCover, pwdField.offsetTop);
	//xLeft(pwdCover, 5);
	xInnerHtml(pwdCover, 'Password');

	pwdField.parentNode.appendChild(pwdCover);
	Event.observe(pwdCover, 'click', passwordClick);
	Event.observe(pwdField, 'focus', passwordClick);
}

function passwordClick(ev) {
	if(pwdCover != null) {
		// remove pwdCover
		pwdCover.parentNode.removeChild(pwdCover);
		pwdCover = null;
	}
	
	if(pwdField != null) {
		pwdField.focus();
	}
}

var secondaryElem = null;
var secondaryOff = false;

function initQuoteMask() {
	var secondaryElems = $$('div.secondary');
	if(secondaryElems.length <= 0) return;
	
	secondaryElem = secondaryElems[0];
	//event removed as it causes AJAX errors. Will revisit this.
	Event.observe(document.body, 'mousemove', handleQuoteMask);
}

function handleQuoteMask(oEvent) {
	if(secondaryElem == null || secondaryElem.parentNode == null) {
		secondaryElem = null;
		Event.stopObserving(document.body, 'mousemove', handleQuoteMask);
		return;
	}
	
	var oEvent = new xEvent(oEvent);
	var xPoint = oEvent.pageX;
	var yPoint = oEvent.pageY;
		
	if(xHasPoint(secondaryElem, xPoint, yPoint) ) {
		clearQuoteMask();
	} else if(!secondaryOff) {
		secondaryOff = true;
		setTimeout(addQuoteMask, 3000);		
	}
}

function clearQuoteMask() {
	if(secondaryElem == null) return;
	secondaryElem.className = secondaryElem.className.replace(/\s?\bsecondary\b/, '');
}

function addQuoteMask() {
	if(secondaryElem == null) return;
	if(!/\bsecondary\b/.test(secondaryElem.className)) {
		secondaryElem.className += ' secondary';
	}
	secondaryOff = false;
}

function handleQuickQuote() {
  var elemCover = xGetElementById('quick_quote_cover_type');
  var elemAge = xGetElementById('quick_quote_age_group');
  var elemState = xGetElementById('quick_quote_state');
  
  if(elemCover == null || elemAge == null || elemState == null) return;
  
  var qs = '?type=' + escape(elemCover.options[elemCover.selectedIndex].value) +
  		   '&age=' + escape(elemAge.options[elemAge.selectedIndex].value) +
  		   '&state=' + escape(elemState.options[elemState.selectedIndex].value);
  var variation = getVariationUrl();
  window.location.assign(variation + 'newtonib/quote.aspx' + qs);
}

function getVariationUrl()
{
  var re = new RegExp("\/\\w+\/");
  var m = re.exec(window.location.pathname);
  if(m == null)
  	return '/home/';
  else
	return m;
}

// Key functions
function loadScripts() {
	// Only good for items that don't need to do something on load
	loadScript('/Style%20Library/JavaScript/googlefix.js');
	loadScript('/Style%20Library/JavaScript/common.js');
}

function initFormFields()
{
    var clearFields = xGetElementsByClassName('clear_default');
    if (clearFields != null)
    {
        for (var i = 0; i < clearFields.length; i++)
        {
            var elemField = clearFields[i];
            Event.observe(elemField, 'focus', clearFieldWrapper);
        }

        var pwdFields = xGetElementsByClassName('password_switch');
        for (var i = 0; i < pwdFields.length; i++)
        {
            var elemField = pwdFields[i];
            Event.observe(elemField, 'focus', switchPassword);
        }
    }
}

function fixValidation() {
	// Enforce dateorder of dmy on relevant validators
	var cmpDates = $$('*[dateorder]');
	for(var i = 0; i < cmpDates.length; i++) {
		var cmp = cmpDates[i];
		cmp.dateorder = 'dmy';
	}
}





// Helper functions
function loadScript(scriptUrl) {
	var elemScript = document.createElement('script');
	elemScript.setAttribute('type', 'text/javascript');
	elemScript.setAttribute('language', 'javascript');
	elemScript.setAttribute('src', scriptUrl);
	
	var elemHead = document.getElementsByTagName('head')[0];
	
	elemHead.appendChild(elemScript);	
}

function clearFieldWrapper(objEvent) {
	var elem = Event.element(objEvent);
	if (elem.defaultValue == elem.value) {
		elem.value = '';
	}
}

function switchPassword(objEvent) {
	var elem = Event.element(objEvent);
	if(elem.type == 'text') {
		var repl = document.createElement('input');
		repl.type = 'password';
		repl.id = elem.id;
		repl.className = elem.className;
		repl = elem.parentNode.replaceChild(repl, elem);
		//repl.focus();
	}
}

function TrimString(str) {
    str = str.replace( /^\s+/g, "" );// strip leading
    return str.replace( /\s+$/g, "" );// strip trailing
}

function toggleClass(elem, className) {
	if(elem == null || className == '')
		return;
		
	if(elem.className.match('\\b'+ className + '\\b')) {
		elem.className = TrimString(elem.className.replace(className, ''));
	} else {
		elem.className = elem.className + ' ' + className;
	}
}

var currInfoBox = null;
var currBalloon = null;

var infoboxClasses = ['infobox', 'infobox-large', 'nib-editCustom-Infobox', 'ms-rteCustom-Infobox'];

function infoBoxes() {
	for(var i = 0; i < infoboxClasses.length; i++) {
		var className = infoboxClasses[i];

		var elems = xGetElementsByClassName(className);
	
		for(var j = 0; j < elems.length; j++) {
			xAddEventListener(elems[j], 'mousemove', handleInfoBox);
		}
	}
}

function matchInfoboxClass(elemClassName) {
	for(var i = 0; i < infoboxClasses.length; i++) {
		var pattern = '\\b' + infoboxClasses[i] + '\\b';
		var re = new RegExp(pattern);
		if(re.test(elemClassName)) {
			return true;
		}
	}
	
	return false;
}

function handleInfoBox(oEvent) {
	var ev = new xEvent(oEvent);
	var elemInfo = ev.target;
	
	if(elemInfo == null || !matchInfoboxClass(elemInfo.className) ) return;
	
	if(!elemInfo.className.match(/\bdisplay\b/)) {
		if(currInfoBox != null)
			hideInfoBox();
		
		currInfoBox = elemInfo;
		
		setTimeout(showInfoBox, 300);
	}
}

function getWindowWidth() {
	var myWidth = 0, myHeight = 0;
	if( typeof(window.innerWidth ) == 'number') 
	{  //Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} 
	else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
	{  //IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} 
	else if(document.body && (document.body.clientWidth || document.body.clientHeight)) 
	{  //IE 4 compatible
	myWidth = document.body.clientWidth;
	myHeight = document.body.clientHeight;
	}
	return myWidth;
}

function showInfoBox() {
	var startY = document.documentElement.scrollWidth;

	if(currInfoBox == null || currInfoBox.className.match(/\bdisplay\b/)) return;
	if(!matchInfoboxClass(currInfoBox.className)) { currInfoBox = null; return; }
	toggleClass(currInfoBox, 'display');
	
	var sContents = xInnerHtml(currInfoBox);
	if(sContents.match(/infobox_panel/)) return;
	var sNewMarkup = '<iframe src="javascript:false;" class="infobox_shim" frameborder="0"></iframe><div class="infobox_arrow"></div><div class="infobox_box"><div class="infobox_panel"><div class="infobox_panel_header"><span class="infobox_panel_corner"></span></div><div class="infobox_body clearfix">' + sContents + '</div></div><div class="infobox_panel_footer"><span class="infobox_panel_corner"></span></div></div>';

	currBalloon = document.createElement('span');
	currBalloon.className = 'infobox_container';
	xInnerHtml(currBalloon, sNewMarkup);
	
	// sizes the balloon
	var infoX = xPageX(currInfoBox) + 15;
	var infoY = xPageY(currInfoBox);
	xMoveTo(currBalloon, infoX, infoY);
	var balloonWidth = Math.min ( Math.ceil(sContents.length / 100) * 150,  400);
	xWidth(currBalloon, balloonWidth);

	if (((infoX + balloonWidth) > 1280) || ((infoX + balloonWidth) > getWindowWidth())) 
	{
		sNewMarkup = '<iframe src="javascript:false;" class="infobox_shim" frameborder="0"></iframe><div class="infobox_arrow_right"></div><div class="infobox_box"><div class="infobox_panel"><div class="infobox_panel_header"><span class="infobox_panel_corner"></span></div><div class="infobox_body clearfix">' + sContents + '</div></div><div class="infobox_panel_footer"><span class="infobox_panel_corner"></span></div></div>';
		xInnerHtml(currBalloon, sNewMarkup);
		infoX = infoX - balloonWidth - 35;
		xMoveTo(currBalloon, infoX, infoY);
	}
	
	document.body.appendChild(currBalloon);
	
	//sizes the iframe shim
	var shim = currBalloon.childNodes[0];
	xWidth(shim, xWidth(currBalloon) - 11);
	xHeight(shim, xHeight(currBalloon.childNodes[2]) - 1);
	
	if(startY != document.documentElement.scrollWidth)
		currBalloon.scrollIntoView(false);
	
	xAddEventListener(document, 'mousemove', handleWindow);
}

function handleWindow(oEvent) {
	var ev = new xEvent(oEvent);
	if(currInfoBox == null || currBalloon == null) return;
	if(!xHasPoint(currInfoBox, ev.pageX, ev.pageY, -10) && !xHasPoint(currBalloon, ev.pageX, ev.pageY, -5)) {
		setTimeout(hideInfoBox, 300);
	}
}

function hideInfoBox() {
	if(currInfoBox == null || currBalloon == null) return;
	if(!matchInfoboxClass(currInfoBox.className)) { currInfoBox = null; return; }
	
	document.body.removeChild(currBalloon);
	currBalloon = null;
	
	toggleClass(currInfoBox, 'display');
	
	xRemoveEventListener(document, 'mousemove', handleWindow);
}


function addSearchEvent() {
	xAddEventListener( xGetElementById('btSearch'), 'click', searchClick, false);
}

function searchClick(){
	var searchTerm = xGetElementById('tbSearch').value;
	if(searchTerm == "")
		return false;
	else
		location.href='/search/results.aspx?k=' + searchTerm;
}

function searchKeyDownEvent(event, strUrl){
	 if (IsKeyDownSubmit(event))
	 {
	 submitSearchKeywords(strUrl);
	 return false;
	 }
	 return true;
}

function submitSearchKeywords(strUrl){
	var searchTerm = xGetElementById('idSearchString').value;
	
	if(searchTerm == "")
		return false;
	else
	{
		strUrl=strUrl+"?k="+escapeProperly(searchTerm);
		location.href=strUrl;
	}
}

var currentNavBranch = [];
var primeNav = null;
var currentNavMenu = null;
var currentSubMenu = null;

function setUpDropdownNav() {
	primeNav = xGetElementsByClassName('primary_nav', null, 'ul')[0];
	if(primeNav == null) return;
	
	WalkMenus(primeNav);
	
	xAddEventListener(document, 'mousemove', HandleNavEvent, false);
	
}

function WalkMenus(elemParent) {
	var items = xGetElementsByTagName('li', elemParent);
	var icount = items.length;
	for(var i = 0; i < icount; i++) {
		var mnu = items[i];
		xAddEventListener(items[i], 'mouseover', HandleNavEvent, false);
		xAddEventListener(items[i], 'click', HandleNavEvent, false);
		
		var submenus = xGetElementsByTagName('ul', mnu);
		if(submenus.length > 0 && mnu.firstChild.tagName.toLowerCase() == 'a') {
			setClass(mnu.firstChild, 'nav-more');
		}
		
		var links = xGetElementsByTagName('a', mnu);
		var jcount = links.length;
		for(var j = 0; j < jcount; j++) {
    		xAddEventListener(links[j], 'mouseover', HandleNavEvent, false);
    		xAddEventListener(links[j], 'click', HandleNavEvent, false);
		}
	}
}

function HandleNavEvent(e) {
	var evt = new xEvent(e);
	var elem = evt.target;
	switch(evt.type.toLowerCase()) {
		case 'mousemove':
			checkOpenBranch(evt.pageX, evt.pageY, -4);
			break;
			
		case 'mouseover':
			// If a link has triggered the event, we want to capture its LI parent
			if(elem.tagName.toLowerCase() == 'a') elem = elem.parentNode;
			
			// Check whether the event target is a child of the current menu or submenu
			if(isAlreadyOpen(elem)) return;
			
			var menuClass = xGetElementsByTagName('ul', elem).length > 0 ? 'submenu' : 'hover';
			openMenu(elem, menuClass);
			break;
			
		case 'click':
			if(xGetElementsByTagName('ul', elem).length < 1) {
				var level = getMenuLevel(elem);
				NavItemBehaviour(level - 1, 'selected');
				checkOpenBranch(0, 0, -4);
				return true;
			}
			break;
	}
}

function checkOpenBranch(x, y, padding) {
	var count = currentNavBranch.length;
	if(count < 1) return;
	
	while (count--) {
		var menuItem = currentNavBranch[count];
		if(menuItem == null) return;
				
		var submenus = xGetElementsByTagName('ul', menuItem);
		
		var mouseOverMenu = menuHasPoint(menuItem, x, y, padding);
		if(submenus.length > 0 && submenus[0] != null) {
			mouseOverMenu = mouseOverMenu || menuHasPoint(submenus[0], x, y, padding);
		}
		
		if(!mouseOverMenu) {
			NavItemStatic(count);
		} else {
			return;
		}
	}
}

function isAlreadyOpen(elem) {
	if(elem == null) return false;
	
	if(xDef(elem.hasAttribute)) {
    	return elem.hasAttribute('prevclass');
	} else {
		return (elem.getAttribute('prevclass') != null);
	}
}

function openMenu(elem, menuClass) {
	var level = getMenuLevel(elem);
	if(level > 0) {
    	var max = currentNavBranch.length;
    	if(max >= level) {
			NavItemStatic(level - 1);
    	}

    	currentNavBranch[level - 1] = elem;
    	NavItemBehaviour(level - 1, menuClass);
    	
    	if(menuClass == 'submenu') {
         	var shim = null;
         	var iframes = xGetElementsByTagName('iframe', elem)
         	if(iframes.length < 1) {
             	shim = createShim(); /* for IE 6*/
    			elem.appendChild(shim);
			} else {
				shim = iframes[0].parentNode;			
			}
			
   			var submenu = xGetElementsByTagName('ul', elem)[0];
        	
        	sizeAndPositionMenu(submenu, iframes[0]);
        } 
	}	
}


function createShim() {
	var menuShim = document.createElement('div');
	menuShim.innerHTML = '<iframe src="javascript:void()" frameborder="0" style="position:absolute;z-index:-1;"></iframe>';
	return menuShim;
}

function removeShim(parentElem) {
	var iframes = xGetElementsByTagName('iframe', parentElem);
	if(iframes.length > 0) {
		var shim = iframes[0].parentNode;
		parentElem.removeChild(shim);
	}
}

function getMenuLevel(elem) {
	var levels = 0;
	if(IsDescendentOf(elem, primeNav)) {
		var currElem = elem;
		while(currElem != primeNav) {
			if(currElem.parentNode.tagName.toLowerCase() == 'ul')
				levels ++;
			currElem = currElem.parentNode;
		}
	}
	return levels;
}

function sizeAndPositionMenu(elem, iframe) {
	if(elem == null || iframe == null) return;
	
	var margin = getMargin(elem.parentNode.firstChild);
	var parentWidth = xWidth(elem.parentNode);
	var childWidth = xWidth(elem);
	var childHeight = xDef(elem.clientHeight) && (elem.clientHeight > 0) ? elem.clientHeight : xHeight(elem);
	
	// Don't resize until IE returns non-zero values for width & height
	if(childWidth > 0 && childHeight > 0) {
    	var newWidth = Math.max(parentWidth + margin, childWidth);
    	
    	xWidth(elem, newWidth);
    	xHeight(elem, childHeight);
    	
		xWidth(iframe, newWidth);
		xHeight(iframe, childHeight);
    	
    	var level = getMenuLevel(elem);
    	if(level > 1) {
    		var parentTop = getMenuTop(elem.parentNode);
    		xLeft(elem, parentWidth);
    		xTop(elem, parentTop);
    		
    		xLeft(iframe, parentWidth);
    		xTop(iframe, parentTop);
    	} else {
        	var parentHeight = xHeight(elem.parentNode);
    		xLeft(elem, 0);
        	xTop(elem, parentHeight);
        	
        	xLeft(iframe, 0);
        	xTop(iframe, parentHeight);
    	}
	}
}

function getMenuTop(elem) {
	if((elem == null) || (xDef(elem.currentStyle) && elem.currentStyle['position'] == 'relative'))
		return 0;
	
	var parentTop = xDef(elem.offsetTop) ? elem.offsetTop : xTop(elem);
	return parentTop;
}

function getMargin(elem) {
	if(elem == null) return;
	// All browsers but IE6 are using negative margins, which we need to adjust for
	if(xDef(elem.currentStyle) && elem.currentStyle["marginRight"] == 'auto') {
		return 0;
	} else {
		return 5;
	}
}

function IsDescendentOf(descendentNode, ancestorNode) {
	if(descendentNode == null || ancestorNode == null) return false;
	
	if(descendentNode.tagName.toLowerCase() == 'body') return false;
	
	if(descendentNode.parentNode == null) return false;
	
	if(descendentNode.parentNode == ancestorNode) return true;
		
	return IsDescendentOf(descendentNode.parentNode, ancestorNode);
}

function menuHasPoint(menuElem, x, y, padding) {
	if(menuElem == null) return false;
	
	var eX=xPageX(menuElem),eY=xPageY(menuElem);
	var eW = xDef(menuElem.clientWidth) ? Math.max(menuElem.clientWidth, xWidth(menuElem)) : xWidth(menuElem);
	var eH = xDef(menuElem.clientHeight) ? Math.max(menuElem.clientHeight, xHeight(menuElem)) : xHeight(menuElem);
	
	return(x>=eX+padding&&x<=eX+eW-padding&&y>=eY+padding&&y<=eY+eH-padding);
}

function NavItemBehaviour(level, className) {
	var elem = currentNavBranch[level];
	if(elem == null) return;

	elem.setAttribute('prevclass', elem.className);
	setClass(elem, className);
}

function NavItemStatic(level) {
	var count = currentNavBranch.length;
	while(count > level) {
     	var elem = currentNavBranch[count-1];
    	if(elem == null) return;
    	
    	if(isAlreadyOpen(elem)) {
			removeShim(elem);
           	setClass(elem, elem.getAttribute('prevclass'));
        	elem.removeAttribute('prevclass');
    		currentNavBranch.pop();
    		count--;
    	}
	}
}

function setClass(elem, className) {
	if(elem == null) return;
	elem.className = className;
}

/* Compiled from X 4.17 by XC 1.06 on 31May08 */
function xEvent(evt){var e=evt||window.event;if(!e)return;this.type=e.type;this.target=e.target||e.srcElement;this.relatedTarget=e.relatedTarget;/*@cc_on if(e.type=='mouseover')this.relatedTarget=e.fromElement;else if(e.type=='mouseout')this.relatedTarget=e.toElement;@*/if(xDef(e.pageX)){this.pageX=e.pageX;this.pageY=e.pageY;}else if(xDef(e.clientX)){this.pageX=e.clientX+xScrollLeft();this.pageY=e.clientY+xScrollTop();}if(xDef(e.offsetX)){this.offsetX=e.offsetX;this.offsetY=e.offsetY;}else if(xDef(e.layerX)){this.offsetX=e.layerX;this.offsetY=e.layerY;}else{this.offsetX=this.pageX-xPageX(this.target);this.offsetY=this.pageY-xPageY(this.target);}this.keyCode=e.keyCode||e.which||0;this.shiftKey=e.shiftKey;this.ctrlKey=e.ctrlKey;this.altKey=e.altKey;if(typeof e.type=='string'){if(e.type.indexOf('click')!=-1){this.button=0;}else if(e.type.indexOf('mouse')!=-1){this.button=e.button;/*@cc_on if(e.button&1)this.button=0;else if(e.button&4)this.button=1;else if(e.button&2)this.button=2;@*/}}}xLibrary={version:'4.17',license:'GNU LGPL',url:'http://cross-browser.com/'};function xAddEventListener(e,eT,eL,cap){if(!(e=xGetElementById(e)))return;eT=eT.toLowerCase();if(e.addEventListener)e.addEventListener(eT,eL,cap||false);else if(e.attachEvent)e.attachEvent('on'+eT,eL);else{var o=e['on'+eT];e['on'+eT]=typeof o=='function'?function(v){o(v);eL(v);}:eL;}}function xCamelize(cssPropStr){var i,c,a=cssPropStr.split('-');var s=a[0];for(i=1;i<a.length;++i){c=a[i].charAt(0);s+=a[i].replace(c,c.toUpperCase());}return s;}function xClientHeight(){var v=0,d=document,w=window;if((!d.compatMode||d.compatMode=='CSS1Compat')&&!w.opera&&d.documentElement&&d.documentElement.clientHeight){v=d.documentElement.clientHeight;}else if(d.body&&d.body.clientHeight){v=d.body.clientHeight;}else if(xDef(w.innerWidth,w.innerHeight,d.width)){v=w.innerHeight;if(d.width>w.innerWidth)v-=16;}return v;}function xClientWidth(){var v=0,d=document,w=window;if((!d.compatMode||d.compatMode=='CSS1Compat')&&!w.opera&&d.documentElement&&d.documentElement.clientWidth){v=d.documentElement.clientWidth;}else if(d.body&&d.body.clientWidth){v=d.body.clientWidth;}else if(xDef(w.innerWidth,w.innerHeight,d.height)){v=w.innerWidth;if(d.height>w.innerHeight)v-=16;}return v;}function xDef(){for(var i=0;i<arguments.length;++i){if(typeof(arguments[i])=='undefined')return false;}return true;}function xGetComputedStyle(e,p,i){if(!(e=xGetElementById(e)))return null;var s,v='undefined',dv=document.defaultView;if(dv&&dv.getComputedStyle){s=dv.getComputedStyle(e,'');if(s)v=s.getPropertyValue(p);}else if(e.currentStyle){v=e.currentStyle[xCamelize(p)];}else return null;return i?(parseInt(v)||0):v;}function xGetElementById(e){if(typeof(e)=='string'){if(document.getElementById)e=document.getElementById(e);else if(document.all)e=document.all[e];else e=null;}return e;}function xGetElementsByClassName(c,p,t,f){var r=new Array();var re=new RegExp("(^|\\s)"+c+"(\\s|$)");var e=xGetElementsByTagName(t,p);for(var i=0;i<e.length;++i){if(re.test(e[i].className)){r[r.length]=e[i];if(f)f(e[i]);}}return r;}function xGetElementsByTagName(t,p){var list=null;t=t||'*';p=p||document;if(typeof p.getElementsByTagName!='undefined'){list=p.getElementsByTagName(t);if(t=='*'&&(!list||!list.length))list=p.all;}else{if(t=='*')list=p.all;else if(p.all&&p.all.tags)list=p.all.tags(t);}return list||new Array();}function xHasPoint(e,x,y,t,r,b,l){if(!xNum(t)){t=r=b=l=0;}else if(!xNum(r)){r=b=l=t;}else if(!xNum(b)){l=r;b=t;}var eX=xPageX(e),eY=xPageY(e);return(x>=eX+l&&x<=eX+xWidth(e)-r&&y>=eY+t&&y<=eY+xHeight(e)-b);}function xHeight(e,h){if(!(e=xGetElementById(e)))return 0;if(xNum(h)){if(h<0)h=0;else h=Math.round(h);}else h=-1;var css=xDef(e.style);if(e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){h=xClientHeight();}else if(css&&xDef(e.offsetHeight)&&xStr(e.style.height)){if(h>=0){var pt=0,pb=0,bt=0,bb=0;if(document.compatMode=='CSS1Compat'){var gcs=xGetComputedStyle;pt=gcs(e,'padding-top',1);if(pt!==null){pb=gcs(e,'padding-bottom',1);bt=gcs(e,'border-top-width',1);bb=gcs(e,'border-bottom-width',1);}else if(xDef(e.offsetHeight,e.style.height)){e.style.height=h+'px';pt=e.offsetHeight-h;}}h-=(pt+pb+bt+bb);if(isNaN(h)||h<0)return;else e.style.height=h+'px';}h=e.offsetHeight;}else if(css&&xDef(e.style.pixelHeight)){if(h>=0)e.style.pixelHeight=h;h=e.style.pixelHeight;}return h;}function xInnerHtml(e,h){if(!(e=xGetElementById(e))||!xStr(e.innerHTML))return null;var s=e.innerHTML;if(xStr(h)){e.innerHTML=h;}return s;}function xLeft(e,iX){if(!(e=xGetElementById(e)))return 0;var css=xDef(e.style);if(css&&xStr(e.style.left)){if(xNum(iX))e.style.left=iX+'px';else{iX=parseInt(e.style.left);if(isNaN(iX))iX=xGetComputedStyle(e,'left',1);if(isNaN(iX))iX=0;}}else if(css&&xDef(e.style.pixelLeft)){if(xNum(iX))e.style.pixelLeft=iX;else iX=e.style.pixelLeft;}return iX;}function xMoveTo(e,x,y){xLeft(e,x);xTop(e,y);}function xNum(){for(var i=0;i<arguments.length;++i){if(isNaN(arguments[i])||typeof(arguments[i])!='number')return false;}return true;}function xPageX(e){var x=0;e=xGetElementById(e);while(e){if(xDef(e.offsetLeft))x+=e.offsetLeft;e=xDef(e.offsetParent)?e.offsetParent:null;}return x;}function xPageY(e){var y=0;e=xGetElementById(e);while(e){if(xDef(e.offsetTop))y+=e.offsetTop;e=xDef(e.offsetParent)?e.offsetParent:null;}return y;}function xRemoveEventListener(e,eT,eL,cap){if(!(e=xGetElementById(e)))return;eT=eT.toLowerCase();if(e.removeEventListener)e.removeEventListener(eT,eL,cap||false);else if(e.detachEvent)e.detachEvent('on'+eT,eL);else e['on'+eT]=null;}function xScrollLeft(e,bWin){var offset=0;if(!xDef(e)||bWin||e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){var w=window;if(bWin&&e)w=e;if(w.document.documentElement&&w.document.documentElement.scrollLeft)offset=w.document.documentElement.scrollLeft;else if(w.document.body&&xDef(w.document.body.scrollLeft))offset=w.document.body.scrollLeft;}else{e=xGetElementById(e);if(e&&xNum(e.scrollLeft))offset=e.scrollLeft;}return offset;}function xScrollTop(e,bWin){var offset=0;if(!xDef(e)||bWin||e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){var w=window;if(bWin&&e)w=e;if(w.document.documentElement&&w.document.documentElement.scrollTop)offset=w.document.documentElement.scrollTop;else if(w.document.body&&xDef(w.document.body.scrollTop))offset=w.document.body.scrollTop;}else{e=xGetElementById(e);if(e&&xNum(e.scrollTop))offset=e.scrollTop;}return offset;}function xStr(s){for(var i=0;i<arguments.length;++i){if(typeof(arguments[i])!='string')return false;}return true;}function xTop(e,iY){if(!(e=xGetElementById(e)))return 0;var css=xDef(e.style);if(css&&xStr(e.style.top)){if(xNum(iY))e.style.top=iY+'px';else{iY=parseInt(e.style.top);if(isNaN(iY))iY=xGetComputedStyle(e,'top',1);if(isNaN(iY))iY=0;}}else if(css&&xDef(e.style.pixelTop)){if(xNum(iY))e.style.pixelTop=iY;else iY=e.style.pixelTop;}return iY;}function xWidth(e,w){if(!(e=xGetElementById(e)))return 0;if(xNum(w)){if(w<0)w=0;else w=Math.round(w);}else w=-1;var css=xDef(e.style);if(e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){w=xClientWidth();}else if(css&&xDef(e.offsetWidth)&&xStr(e.style.width)){if(w>=0){var pl=0,pr=0,bl=0,br=0;if(document.compatMode=='CSS1Compat'){var gcs=xGetComputedStyle;pl=gcs(e,'padding-left',1);if(pl!==null){pr=gcs(e,'padding-right',1);bl=gcs(e,'border-left-width',1);br=gcs(e,'border-right-width',1);}else if(xDef(e.offsetWidth,e.style.width)){e.style.width=w+'px';pl=e.offsetWidth-w;}}w-=(pl+pr+bl+br);if(isNaN(w)||w<0)return;else e.style.width=w+'px';}w=e.offsetWidth;}else if(css&&xDef(e.style.pixelWidth)){if(w>=0)e.style.pixelWidth=w;w=e.style.pixelWidth;}return w;}

        
function traverseTree(status, control)
{
	if(control == null)
	{
		for(var i = 0; i < Page_Validators.length; i++)
		{
			Page_Validators[i].enabled = status;
			Page_Validators[i].style.display = status ? 'inline' : 'none';
		}	
	}
	else	
	{	
		if(control.evaluationfunction != null)
		{
			control.enabled = status;
			control.style.display = status ? 'inline' : 'none';	
		}
		for( var i=0; i < control.childNodes.length; i++)
		{
			traverseTree(status, control.childNodes[i]);
		}
	}	
}

function enableValidators(containerID)
{
	var control;
	if(containerID == null)
	{
		control = null;					
	}
	else
	{
		control = document.getElementById(containerID);		
	}	
	if( containerID == null || control != null )
		traverseTree(true,  control);	
}

function disableValidators(containerID)
{
	var control;
	if(containerID == null)
	{
		control = null;					
	}
	else
	{
		control = document.getElementById(containerID);		
	}	
	if( containerID == null || control != null )
		traverseTree(false,  control);	
}

function traverseTreeCTV(status, controlToValidateID, control)
{
	if(control == null)
	{
		for(var i = 0; i < Page_Validators.length; i++)
		{
			if(Page_Validators[i].controltovalidate != null &&
			 Page_Validators[i].controltovalidate == controlToValidateID)
			{
				Page_Validators[i].enabled = status;//disable validator
				Page_Validators[i].style.display = status ? 'inline' : 'none';
			}			
		}		
	}
	else
	{
		if(control.controltovalidate != null && control.controltovalidate == controlToValidateID)
		{
			control.enabled = status;//disable validator
			control.style.display = status ? 'inline' : 'none';
		}
		for( var i=0; i < control.childNodes.length; i++)
		{
			traverseTreeCTV(status, controlToValidateID, control.childNodes[i]);
		}
	}
}
function enableCTVValidators(controlToValidateID, containerID)
{
	var control;
	if(containerID == null)
	{
		control = null;
	}
	else
	{
		control = document.getElementById(containerID);
	}
	if( containerID == null || control != null )
		traverseTreeCTV(true, controlToValidateID, control );
}
function disableCTVValidators(controlToValidateID, containerID)
{
	var control;
	if(containerID == null)
	{
		control = null;
	}
	else
	{
		control = document.getElementById(containerID);
	}
	if( containerID == null || control != null )
		traverseTreeCTV(false, controlToValidateID, control );
}
function setGroupValidatorsStatus(groupID, status)
{
	for(var i = 0; i < Page_Validators.length; i++)
	{
		if(Page_Validators[i].validationGroup == groupID)
		{
			Page_Validators[i].enabled = status;
			Page_Validators[i].style.display = status ? 'inline' : 'none';		
		}
	}	
}
function enableGroupValidators(groupID)
{
	setGroupValidatorsStatus(groupID, true)
}
function disableGroupValidators(groupID)
{
	setGroupValidatorsStatus(groupID, false)
}
function hideValidators(containerID)
{
	var control;
	if(containerID == null)
	{
		control = null;					
	}
	else
	{
		control = document.getElementById(containerID);		
	}	
	if( containerID == null || control != null )
		traverseTreeShowHide(false,  control);	
}
function showValidators(containerID)
{
	var control;
	if(containerID == null)
	{
		control = null;					
	}
	else
	{
		control = document.getElementById(containerID);		
	}	
	if( containerID == null || control != null )
		traverseTreeShowHide(true,  control);	
}

function traverseTreeShowHide(status, control)
{
	if(control == null)
	{
		for(var i = 0; i < Page_Validators.length; i++)
		{		
			Page_Validators[i].style.display = status ? 'inline' : 'none';						
		}	
	}
	else	
	{	
		if(control.evaluationfunction != null)
		{
			control.style.display = status ? 'inline' : 'none';		
		}
		for( var i=0; i < control.childNodes.length; i++)
		{
			traverseTreeShowHide(status, control.childNodes[i]);
		}
	}	
}
function hide(alsoDisable, containerID )
{
	if(alsoDisable == null)
		alsoDisable = false;
	var container;
	if(containerID == null)
	{
		container = null;
	}
	else
	{
		container = document.getElementById(containerID);
	}
	if(containerID == null || container != null)
	{
		if(container != null)
		    container.style.display = 'none';
		if(containerID != null)
		    hideClass(containerID);
		    
		if(alsoDisable)
			disableValidators(containerID);
		else
			hideValidators(containerID);
	}
}
function show(alsoEnable, containerID)
{
	if(alsoEnable == null)
		alsoEnable = false;
	var container;
	if(containerID == null)
	{
		container = null;
	}
	else
	{
		container = document.getElementById(containerID);
	}
	if(containerID == null || container != null)
	{
	    if(container != null)
	    	container.style.display = 'block';
	    if(containerID != null)
		    showClass(containerID);
	
		if(alsoEnable)
			enableValidators(containerID);
		else
			showValidators(containerID);
	}
}

function showHide(containerID)
{
	var container;
	if(containerID == null)
	{
		container = null;
	}
	else
	{
		container = document.getElementById(containerID);
	}
	if(containerID == null || container != null)
	{
		if(container.style.display == null)
		{
			hide(containerID);
			hideClass(containerID);
		}
		else if(control.style.display == 'none')
		{
			show(containerID);
			showClass(containerID);
		}
		else
		{
			hide(containerID);
			hideClass(containerID);
		}
	}
}

function showClass(compentId)
{
    var who = document.getElementById(compentId);           
    if(jscss('check', who, 'hide'))
        jscss('swap', who, 'hide', 'show'); 
    else
        jscss('add', who, 'show'); 
}

function hideClass(compentId)
{
    var who = document.getElementById(compentId);
    if(jscss('check', who, 'show'))
        jscss('swap', who, 'show', 'hide'); 
    else
        jscss('add', who, 'hide'); 
}

function jscss(a,o,c1,c2)
{
    switch (a)
    {
        case 'swap':
            if(jscss('check',o,c1))
                o.className = o.className.replace(c1,c2);
            else
                o.className = o.className.replace(c2,c1);                        
            break;
            
        case 'add':
            if(!jscss('check',o,c1))
            {
                if(o.className)
                    o.className += ' ' + c1;
                else
                    o.className += c1;
            }
            break;
            
        case 'remove':                    
            var rep;
            if(o.className.match(' '+c1))
                rep = ' ' + c1;
            else
                rep = c1;
            o.className=o.className.replace(rep,'');
            break;
            
        case 'check':
            return new RegExp('\\b'+c1+'\\b').test(o.className)
            break;
    }
}

function copyField(source, destination)
{    
    var src = document.getElementById(source);
    var des = document.getElementById(destination);
    if(src != null && des != null)
        des.value = src.value;
}

function checkForCommas(source, args)
{
    var text = args.Value;
    for(i=0; i < text.length; i++)
    {
        if(text.charAt(i) == ',')
        {
            args.IsValid = false;
            return;
        }       
    }
}

function isDigit(num) 
{
	if (num.length>1)
	{
	    return false;
	}
	var string="1234567890";
	if (string.indexOf(num)!=-1)
	{
	    return true;
	}
	return false;
}
function isNumeric(val)
{
    return(parseFloat(val,10)==(val*1));
}
function IsNumeric(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;
        }
   }
   return IsNumber;   
}
function isBlank(val)
{
	if(val==null)
	{
	    return true;
	}
	for(var i=0;i<val.length;i++) 
	{
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
	}
	return true;
}
function isInteger(val)
{
	if (isBlank(val)){return false;}
	for(var i=0;i<val.length;i++)
	{
		if(!isDigit(val.charAt(i)))
		{
		    return false;
		}
    }
	return true;
}
function checkRepeating(source, args)
{
    if(args.Value.match(/(.)\1{3,}/)) 
        args.IsValid = false;
    else 
        args.IsValid = true;
    
}
function blockComma(e)
{
    var keynum;
    var keychar;   
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }    
    return (keynum != 188)
}   
function blockDigit(e)
{
    var keynum;
    var keychar;   
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }    
    return (keynum == 8  || keynum == 9 || keynum == 13 || keynum == 17 || keynum == 32 || keynum == 46 || keynum == 222 || keynum == 189 || (keynum >= 35  && keynum <= 40) ||  (keynum >= 65  && keynum <= 90) || keynum == 127  )

}
function blockAlpha(e)
{
    var keynum;
    var keychar;   
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
    return (keynum == 8  || keynum == 9 || keynum == 13 || keynum == 17 || keynum == 46 || (keynum >= 35  && keynum <= 40) || (keynum >= 96  && keynum <= 105) || (keynum >= 48  && keynum <= 57)  || keynum == 127 )
   
}

function digitOnly(e)
{
    var keynum;
    var keychar;   
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
    if(e.shiftKey==1)
        return false;
    
    return (keynum == 8  || keynum == 9 || keynum == 13 || keynum == 17 || keynum == 46 || keynum == 127 || (keynum >= 48  && keynum <= 57) || (keynum >= 96  && keynum <= 105)  || (keynum >= 35  && keynum <= 40) )
   
}
function clearDOB(txt) 
{
    var txt = document.getElementById(txt);
    if (txt.value == 'dd/mm/yyyy')
        txt.value = "";
    txt.focus();
}
function clearCreditDate(txt) 
{
    var txt = document.getElementById(txt);
    if (txt.value == 'mm/yy')
        txt.value = "";
}
function copyField(source, destination)
{    
    var src = document.getElementById(source);
    var des = document.getElementById(destination);
    if(src != null && des != null)
        des.value = src.value;
}
function checkPastExpiry(year, month, expiry)
{
    var txtExpiry = document.getElementById(expiry);
    if(txtExpiry.value == "" || txtExpiry.value == "mm/yy")
        return false;
        
    var isValid = true;       
    
    var dteToday = new Date(year, month,1,0,0,0);
    if(txtExpiry.value.indexOf('/') == -1)
        return false;
    var split = txtExpiry.value.split("/");
    
    if(isInteger(split[0]))
    {
        if(parseInt(split[0], 10) < 1)
            return false;
    }
    else
    {
        return false;
    }
    
    if(isInteger(split[1]))
    {
        if(parseInt(split[1], 10) < 1)
            return false;
    }
    else
    {
        return false;
    }
    
    var dteExpiry;
    if(split[1].length == 1)
        dteExpiry = new Date("200" + split[1], split[0], 1, 0,0,0)    
    else
        dteExpiry = new Date("20" + split[1], split[0], 1, 0,0,0)
        
    if(dteToday >= dteExpiry)
        isValid = false;
    
    return isValid;
}

function isValidSubExpiry(txtCCDateID)
{
    var txtDate = document.getElementById(txtCCDateID);
    var textLength = txtDate.value.length;
    
    switch(textLength)
    {
        case 1: 
            if(!isFinite(txtDate.value))
                txtDate.value = "";
            break;
        case 2:
            if(!isFinite(txtDate.value.substring(0,2)) && !(isFinite(txtDate.value.substring(0,1)) && txtDate.value.substring(1,2) == "/"))
                txtDate.value = "";
            break;
        case 3:
            if(!(isFinite(txtDate.value.substring(0,2)) && txtDate.value.substring(2,3) == "/"))
                txtDate.value = "";
            break;
    }
   
}         

function checkExpiryChar(e, txtCCDateID)
{
    var keynum;
    var keychar;   
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
    txtDate = document.getElementById(txtCCDateID);
    if (txtDate.value == 'mm/yy')
    {
        txtDate.value = "";        
        txtDate.focus();
    }
    else
    {
        isValidSubExpiry(txtCCDateID);
        var textLength = txtDate.value.length;        
        keychar = convertKeypadChar(keynum);             
        //return if keypressed was backspace, tab or any other control key
        if((keynum > 7 && keynum < 47) || (keynum > 111 && keynum < 124))     
            return true;

        switch(textLength)
        {
            case 1:
                if(IsNumeric(keychar))
                {
                    if( (keychar == '0' || keynum == 96) || 
                        (keychar == '1' || keynum == 97) )
                        txtDate.value = txtDate.value;
                    else
                        txtDate.value = "0" +  txtDate.value + "/";
                }
                else
                    txtDate.value = "";
                break;
            case 2:
                if(keynum == 191)
                {
                    if(txtDate.value == '1')
                        txtDate.value = "0" +  txtDate.value;
                    else
                    {
                        if(IsNumeric(txtDate.value.substring(0,1)) && txtDate.value.substring(0,1) != 0)
                            txtDate.value = "0" +  txtDate.value;
                        else
                            txtDate.value = txtDate.value.substring(0, 1);    
                    }
                }
                else
                {            
                    if(txtDate.value.substring(0,1) == "1")
                    {
                        if(  (keychar == '0' || keynum == 96) || 
                             (keychar == '1' || keynum == 97) || 
                             (keychar == '2' || keynum == 98)  )
                            txtDate.value = txtDate.value.substring(0, 2) + "/";
                        else                
                            txtDate.value = txtDate.value.substring(0, 1);                
                    }
                    else
                    {
                        if(((IsNumeric(keychar)) || (keynum >= 96 && keynum <= 105)) && (keychar != '0' && keynum != 96) )
                            txtDate.value = txtDate.value.substring(0, 2) + "/";
                        else                
                            txtDate.value = txtDate.value.substring(0, 1);   
                    }
                }
                break;
            case 3:
                if(keynum != 191)
                    txtDate.value = txtDate.value.substring(0, 2) + "/";
                break;
            case 4:
                if(!(IsNumeric(keychar)) && !(keynum >= 96 && keynum <= 105))
                    txtDate.value = txtDate.value.substring(0, 3);
                break;
            case 5:
                if(!(IsNumeric(keychar)) && !(keynum >= 96 && keynum <= 105) && keynum != 9)
                    txtDate.value = txtDate.value.substring(0, 4);
                var cont = document.getElementById(txtCCDateID);
                var vals = cont.Validators;
                var i;
                for (i = 0; i < vals.length; i++) {
                    ValidatorValidate(vals[i]);
                }
                ValidatorUpdateIsValid(); 
                break;        
        }   
    }                                                    
        
}

function convertKeypadChar(kCode)
{

    if(kCode == 96)
        return "0";
    if(kCode == 97)
        return "1";
    if(kCode == 98)
        return "2";
    if(kCode == 99)
        return "3";
    if(kCode == 100)
        return "4";
    if(kCode == 101)
        return "5";
    if(kCode == 102)
        return "6";
    if(kCode == 103)
        return "7";
    if(kCode == 104)
        return "8";
    if(kCode == 105)
        return "9";
    
    return String.fromCharCode(kCode)
}

function isValidSubDate(txtDateID)
{
    var txtDate = document.getElementById(txtCCDateID);
    var textLength = txtDate.value.length;
    
    switch(textLength)
    {
        case 1: 
            if(!isFinite(txtDate.value))
                txtDate.value = "";
            break;
        case 2:
            if(!isFinite(txtDate.value.substring(0,2)) && !(isFinite(txtDate.value.substring(0,1)) && txtDate.value.substring(1,2) == "/"))
                txtDate.value = "";
            break;
        case 3:
            if(!(isFinite(txtDate.value.substring(0,2)) && txtDate.value.substring(2,3) == "/"))
                txtDate.value = "";
            break;        
    }   
}  

function onDateKeyEntered(e, txtCCDateID)
{
    return true;
}

function getFullState(stateCode)
{
    switch(stateCode)
    {
        case "A":
            return "ACT";
        case "N":
            return "NSW";
        case "Q": 
            return "QLD";
        case "V":
            return "VIC";
        case "NT":
            return "NT";
        case "S":
            return "SA";
        case "W":
            return "WA";
        case "T": 
            return "TAS";
        default:
            return "NSW";                
    }
}

function dateAddExtention(p_Interval, p_Number)
{
    var thing = new String();
    p_Interval = p_Interval.toLowerCase();

    if (isNaN(p_Number))
        return false;
    p_Number = new Number(p_Number);
    switch (p_Interval.toLowerCase())
    {
        case "yyyy":
            {// year 
                this.setFullYear(this.getFullYear() + p_Number);
                break;
            }
        case "q":
            {		// quarter 
                this.setMonth(this.getMonth() + (p_Number * 3));
                break;
            }
        case "m":
            {		// month 
                this.setMonth(this.getMonth() + p_Number);
                break;
            }
        case "y": 	// day of year 
        case "d": 	// day 
        case "w":
            {		// weekday 
                this.setDate(this.getDate() + p_Number);
                break;
            }
        case "ww":
            {	// week of year 
                this.setDate(this.getDate() + (p_Number * 7));
                break;
            }
        case "h":
            {		// hour 
                this.setHours(this.getHours() + p_Number);
                break;
            }
        case "n":
            {		// minute 
                this.setMinutes(this.getMinutes() + p_Number);
                break;
            }
        case "s":
            {		// second 
                this.setSeconds(this.getSeconds() + p_Number);
                break;
            }
        case "ms":
            {		// second 
                this.setMilliseconds(this.getMilliseconds() + p_Number);
                break;
            }
        default:
            {
                return false;
            }
    }
    return this;
}
Date.prototype.dateAdd = dateAddExtention;


function CalloutEnable(validator, extender, enable, type)
{
    if (enable)
    {
        if (!$find(extender))
        {
            if(type == 'required')
                validator.evaluationfunction = RequiredFieldValidatorEvaluateIsValid;
            if (type == 'custom')
                validator.evaluationfunction = CustomValidatorEvaluateIsValid;
            $create(AjaxControlToolkit.ValidatorCalloutBehavior, { closeImageUrl: '/WebResource.axd?d=S3JuAHM4gvwgCMbpdo6zJOx2YZh55RYGGF5V5AOk4d-TH43b_3hVK8w2jbZFSQlOGyJd_tstEBK-HYq6AIlNyPlhN6C_4PFOOE5XgtKcPsB1Q_qvvu_F_viloVCvifFN0KFo6XSuh29JcXQc9LHKYA2&t=633834464245935964', warningIconImageUrl: "/Style%20Library/Images/error-icon.png", highlightCssClass: "error-field", id: extender }, null, null, validator);
        }
    }
    else
    {
        var behavior = $find(extender);
        var controlVal = document.getElementById(validator.controltovalidate);
        if (Sys.UI.DomElement.containsCssClass(controlVal, "error-field"))
            Sys.UI.DomElement.removeCssClass(controlVal, "error-field");
        if (behavior)
            behavior.dispose();
    }
}

//Used with onKeypress event only
function blockAlpha(e)
{
    if (window.event) keyCode = e.keyCode; // IE
    else if (e.which) keyCode = e.which; // Netscape/Firefox/Opera     
    
    //return if keypressed was backspace, tab, period or any other control key
    if (keyCode == 47 || keyCode == 46 || keyCode == 8 || keyCode == 9 || keyCode == 190)
    {
        window.event.returnValue = true;
        return true;
    }
//    if (code >= 35 && code <= 40)
//    {
//        window.event.returnValue = true;
//        return true;
//    }
    var result = isNumber(keyCode);
    e.returnValue = result;
    return result;
}

function isNumber(code)
{
    
    if (code == 48 || code == 49 || code == 50 || code == 51 || code == 52 || code == 53 || code == 54 || code == 55 || code == 56 || code == 57)
        return true;
    else
        return false;
}

function clearDate(txt)
{
    text = document.getElementById(txt);
    if (text.value == 'dd' || text.value == 'mm' || text.value == 'yyyy' || text.value == 'dd/mm/yyyy')
        text.value = '';
}

function onDateBlur(txt)
{
    text = document.getElementById(txt);
    if (text.value == '')
        text.value = 'dd/mm/yyyy';
}