var nError;
var nSpecialMan;
var bClearDateIfNotValid = false;
var vMonthDay= new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var vMonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var FORM_ELEMENT = 'ctl00_mainContent_';;
//String.prototype.lTrim = lTrim();
//String.prototype.rTrim = rTrim();

function textBoxCharacterCount(id)
{
    var iCountLabel = document.getElementById("ctl00_mainContent_" + id + "_lblCC_" + id);
    var iTxtBx = document.getElementById("ctl00_mainContent_" + id + "_" + id);
    if (iCountLabel != null)
    {
        iCountLabel.innerHTML = "(Character count: " + iTxtBx.value.length + ")";
    }
    else
    {
    //registration questions are created "differently"
        iCountLabel = document.getElementById("ctl00_mainContent_lblCC_" + id);
        iTxtBx = document.getElementById("ctl00_mainContent_" + id);
        if (iCountLabel != null)
        {
            iCountLabel.innerHTML = "(Character count: " + iTxtBx.value.length + ")";
        }
    }
}

function clickButton(e, buttonid)
{ 
	var bt = document.getElementById(buttonid); 
	if (typeof bt == 'object')
	{ 
		if(navigator.appName.indexOf("Netscape")>(-1))
		{ 
			if (e.keyCode == 13)
			{ 
				bt.click(); 
				return false; 
			} 
		} 
		if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
		{ 
			if (event.keyCode == 13)
			{ 
				bt.click(); 
				return false; 
			} 
		} 
	} 
} 

function cancelEnterKey()
{
	if(13==window.event.keyCode)
	{
		window.event.keyCode = 0;
	}
}

//custom text box methods
function restrictQuestionEntry(e,qET)
{
    var key;
    var keychar;
    //different browsers
    key = window.event.keyCode;
    //get the value as a character
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();
    //switch type of question entry type
    if (qET == 'an')
    {
        // alphas and numbers
        if (("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) == -1)
        {
            window.event.keyCode = 0;
        }
    }
    else if (qET == 'a')
    {
        // alphas
        if (("abcdefghijklmnopqrstuvwxyz").indexOf(keychar) == -1)
        {
            window.event.keyCode = 0;
        }
    }
    else if (qET == 'c')
    {
        // currency values
        if (("0123456789.").indexOf(keychar) == -1)
        {
            window.event.keyCode = 0;
        }
    }
    else
    {
        // numbers
        if (("0123456789").indexOf(keychar) == -1)
        {
            window.event.keyCode = 0;
        }
    }
}

function concatenateCustomTextBoxes(qId,cnt,delim)
{
    var iHiddenField = document.getElementById("ctl00_mainContent_" + qId + "_h");
    for (i = 0; i < cnt; i++)
    {
        var iTxtBx = document.getElementById("ctl00_mainContent_" + qId + "_" + i);
        if (i == 0)
        {
            iHiddenField.value = iTxtBx.value;
        }
        else
        {
            iHiddenField.value = iHiddenField.value + delim + iTxtBx.value;
        }
    }
}

function concatenateCurrencyValues(qId)
{
    var iHiddenField = document.getElementById("ctl00_mainContent_" + qId + "_h");
    var iTxtBx = document.getElementById("ctl00_mainContent_" + qId);
    var iSelect = document.getElementById("ctl00_mainContent_lstCurrency_" + qId);
    iHiddenField.value = iSelect.value + iTxtBx.value;
}

function ValidMail(str){
	if(str.length<4)return 0
	if(str.indexOf("@")<1) return 0
	if(str.indexOf(".")<1) return 0
	else return 1
}

function containsBothAlphaNumeric(iValue)
{
	var bNumeric = false;
	var bAlpha = false;
	
	for(var j=0; j<iValue.length; j++)
	{
        var alphaa = iValue.charAt(j);
	    var hh = alphaa.charCodeAt(0);
	    
	    if((hh > 47 && hh<58))
	    {
	        bNumeric = true;	        
	    }
	    else	
	    {
			if((hh > 64 && hh<91) || (hh > 96 && hh<123))
			{
			    bAlpha = true;
			}
        }
        
        if(bNumeric && bAlpha)
        {
            return true;
        }
	}
	
    return false;
}

function trim(s) 
{
 var r=/\b(.*)\b/.exec(s);
 return (r==null)?"":r[1];
}

function selectAllRows(iIn)
{
	var iForm = document.getElementById("abaEditForm");
	var iCol = iForm.all.tags('INPUT');
	var iItem;
	var bOn = iIn.checked;
	for(i=0;i<iCol.length;i++)
	{
		iItem = iCol.item(i);
		if(null!=iItem.ICSELECTME)
		{
			iItem.checked = bOn;
		}
	}

}

function checkMandatoryField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	
	if(null!=iField)
	{
		if(''==iField.value)
		{
			nError++;
			return '<li> A value must be specifed for ' + strDisplay + '.';
		}
	}
	
	return '';
}


function checkMandatoryNumericField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(''==iField.value)
		{
			nError++;
			return '<li> A value must be specifed for ' + strDisplay + '.';
		}
		
		if(!isPositiveReal(iField.value))
		{
			nError++;
			return '<li>' + strDisplay + ' should be a positive real number.';		
		}
	}
	return '';
}


function checkMandatoryNumericFieldAllowNegative(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(''==iField.value)
		{
			nError++;
			return '<li> A value must be specifed for ' + strDisplay + '.';
		}
		
		if(!isReal(iField.value))
		{
			nError++;
			return '<li>' + strDisplay + ' should be a real number (negatives allowed).';		
		}
	}
	return '';
}

function checkMandatoryList(strField, strDisplay, strNullValue)
{
	var iField = document.getElementById(strField);
	
	if(null!=iField)
	{
		if(!checkParentEnabled(iField))
		{
			return '';
		}
		
		if(0==iField.options.length )
		{
			nError++;
			return '<li> A value must be selected for ' + strDisplay + '.';
		}
		else
		{
			if(iField.value==strNullValue || iField.value=='')
			{
				nError++;
				return '<li> A value must be selected for ' + strDisplay + '.';
			}
			
		}
		
	}
	return '';
}

function showErrorWindow(nError, strError, nSpecialMan, strSpecialMan)
{
	if (0!=nError)
	{
		var nHeight = 250 + (nError*15);
	}
	else
	{
		var nHeight = 250 + (nSpecialMan*15);
	}
	var strPage = "popups/abaErrorPopup.aspx?strError=" + strError.substring(0,1000) + "&strSpecialMan=" + strSpecialMan;
	

	if (showPopupPage(strPage, nHeight, 350))
	{
		return true;
	}
	return false;
}

function showPopupPage(strPage, nHeight, nWidth)
{
	window.showHelp;
	var pcdialogargs = "dialogHeight:" + nHeight + "px;dialogWidth:" + nWidth + "px;scroll:no;status:no;center: Yes; help: No; resizable: No;";

    if(window.showModalDialog) 
    { 
        return showModalDialog(strPage,"",pcdialogargs );
    } 
    else 
    { 
        return window.open(strPage,null,'height='+nHeight+',width='+nWidth,'modal=yes'); 
    } 
}


function confirmDuplicate(strMessage)
{
	var bAdd = confirm(strMessage + "\n\nAre you sure you wish to continue?\n\nPress [ok] to continue or [cancel] to cancel.");
	
	if(bAdd)
	{
		// Need to set the nIgnoreDuplicates field to 1 and submit the form
		var iField = document.getElementById("nIgnoreDuplicate")
		iField.value=1;
		var iForm = document.getElementById("abaEditForm")
		iForm.submit();
	}
}



function checkOptionalNumericField(strField, strDisplay)
{
	
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(!isPositiveReal(iField.value))
		{
			nError++;
			return '<LI>' + strDisplay + ' should be a positive real number.';		
		}
	}
	return '';
}


function checkMandatoryOption(strField, strDisplay)
{

	var iField = document.getElementById(strField);

	if(null!=iField)
	{
		// This assumes that the first option in the list is 'None'
		if(0==iField.value)
		{
			nError++;
			return '<LI>A value must be specifed for ' + strDisplay + '.';
		}
	}
	return '';
}

function GetFieldNumericValue(strField)
{
	
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(isPositiveReal(iField.value))
		{
			return parseInt(iField.value)
		}
	}
	return 0;
}


function checkNumericKey() 
{
	var Key = window.event.keyCode;

	if(Key<48 || Key>57)
	{
	    if (Key != 46) 
	    {
	        event.keyCode = 0;
	    }
	}
}

/*Sean Hasson
added 26/02/03
checks Ctrl+V Event 
Field as Param
*/

function checkCtrlKey(){
	var Ctrl = window.event.ctrlKey;
	var Key = window.event.keyCode;

	//if a ctrl+v or ctrl+upper(V)

	if( (Key==86 || Key==118)  && Ctrl)
	{
		event.keyCode=0;

	}

}


/*Sean Hasson
added 26/02/03
checks if Paste event is NAN	
Field as Param
*/
function checkPasteEvent(objTextField)
{
	var myVal=objTextField.value;

	if (objTextField.inchange)
	{
		//check on inchange state and test here..e.g clicking on another element
		if (isNaN(myVal))
		{
	     //is not a number..reset the textbox
	     objTextField.inchange=true;
	     //objTextField.value=0;        	
		}
	}

	objTextField.inchange=false;

	//querky test if empty textbox i.e ''
	if ((myVal==' ') || (myVal=='')){
	     //is not a number..reset the textbox
	     objTextField.inchange=true;
	     //objTextField.value=0;        	
	}

	if (isNaN(myVal))
	{
	     //is not a number..reset the textbox
	     objTextField.inchange=true;
	     //objTextField.value=0;        	
	}
}


function checkDate(iDate)
{
	if(bClearDateIfNotValid)
	{
		bIgnoreDateCheck = false;
	}
	var strDate = iDate.value;
	if(''==strDate){return true;}
	if(!isDate(strDate, 'dd/MM/yyyy'))
	{
		
		if(bClearDateIfNotValid)
		{
			iDate.value='';
			bClearDateIfNotValid = false;
		}
		else
		{
			alert('Please ensure that the date is of format dd/mm/yyyy.');
			iDate.focus();
		}
	}
	else
	{
		
		if((Date.parse(strDate)<=Date.parse('01/02/1753'))||(Date.parse(strDate)>=Date.parse('01/01/9999')))
		{
			alert('Date is not valid. Please check and try again.');
			iDate.focus();
		}
	}
}

function setClearDateIfNotValid()
{
	bClearDateIfNotValid = true;
}



function checkMandatoryRadio(strName, strDisplay, nRadioValues)
{
	for(var i=0; i<nRadioValues; i++)
	{	
		var iField = document.getElementById(strName + '_' + i);
	
		if(null!=iField)
		{
			if(!checkParentEnabled(iField))
			{
				return '';
			}
			
			if(iField.checked)
				return ''
		}
	}
	
	nError++;
	return '<li> A value must be selected for ' + strDisplay + '.';
}

function clearDate(strDateField)
{
	var iDate = document.getElementById(FORM_ELEMENT + strDateField);

	if(null!=iDate)
	{
		iDate.value = '';
	}
}

function checkFieldMaxLength(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		var iMaxLength = iField.abaMaxLength;
		if(null!=iMaxLength)
		{
		    if(iField.value.length > iMaxLength)
		    {
				nError++;
				return '<li> A value specified for ' + strDisplay + ' must be less than ' + iMaxLength;
		    }
		}
	}
	
	return '';
}

function checkParentEnabled(element)
{
	while (element.tagName != "FORM") // Get wrapping table
	{
		if(element.disabled || element.style.display=='none')
		{
			return false;
		}
		
		element = element.parentNode;
	}
	return true;
}

function checkField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	var bVisible = true;

	if(null!=iField)
	{
	    if(strField.indexOf("_ctl02_") == -1)  //do not check for user controls
	    {
		    if(!checkParentEnabled(iField))
		    {
			    return '';
		    }
	    }
		//Check mandatory
		var strName = iField.getAttribute("abaMandatory");
		if(null!=strName)
		{
			if(''==iField.value)
			{
				nError++;
				return '<li> A value must be specifed for ' + strDisplay + '.';
			}
		}
		
		//Check email format
		var strName = iField.getAttribute("abaEmailField");
		if(null!=strName)
		{
			if(!ValidMail(iField.value))
			{
				nError++;
				return '<li> A valid email address must be specifed for ' + strDisplay + '.';
			}
		}
		
		//Check postcode format
		var strName = iField.getAttribute("abaPostcodeField");
		if(null!=strName)
		{
			if(!checkPostCode(iField.value))
			{
				nError++;
				return '<li> A valid postcode must be specifed for ' + strDisplay + '.';
			}
			else
			{
				iField.value = checkPostCode(iField.value)
			}
		}
	
		//Check min length
		var iMinLength = iField.getAttribute("abaMinLength");
		var strName = iField.getAttribute("abaMandatory");
		if(null!=iMinLength && null!=strName)
		{
			if(iField.value.length < iMinLength)
			{
				nError++;
				return '<li> A value specified for ' + strDisplay + ' must be equal to or more than ' + iMinLength + ' characters.';
			}
		}
		
		//Check max length
		var iMaxLength = iField.getAttribute("abaMaxLength");
		if(null!=iMaxLength)
		{
			if(iField.value.length > iMaxLength)
			{
				nError++;
				return '<li> A value specified for ' + strDisplay + ' must be equal to or less than ' + iMaxLength + ' characters.';
			}
		}
	}

	
	return '';
}

function validateInputForm(strFormName)
{
	var strError='';
	var iCol='';
	
	iCol = document.getElementsByTagName("INPUT");
	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];

		if("text" == oElement.type.toLowerCase() || "password" == oElement.type.toLowerCase())
		{
			var strName = oElement.getAttribute("abaDisplay");
			if(null!=strName)
			{
			    if(strError.length < 1000)
		        {
				    strError = strError + checkField(oElement.id, strName);
				}
			}
		}
	}	
  
    iCol = document.getElementsByTagName("TEXTAREA");
	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];
		var strName = oElement.getAttribute("abaDisplay");
		if(null!=strName)
		{
			 if(strError.length < 1000)
		       {
			    strError = strError + checkField(oElement.id, strName);
			   }
		}
	}

    iCol = document.getElementsByTagName("SELECT");
	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];
							
		var strName = oElement.getAttribute("abaMandatory");
		if(null!=strName)
		{
			if(strError.length < 1000)
		       {
			    strError = strError + checkMandatoryList(oElement.id, strName, oElement.getAttribute("abaNull"));
			   } 
		}
	}
	
	iCol = document.getElementsByTagName("TABLE");
	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];
		
		var strName = oElement.getAttribute("abaMandatory");
		if(null!=strName)
		{
			var nTotal = oElement.getAttribute("abaRadioTotal");
			if(null!=nTotal)
			{
				if(strError.length < 1000)
		        {
				strError = strError + checkMandatoryRadio(oElement.id, strName, nTotal);
				}
			}
		}
	}
	
	return strError;
}

function checkQuestionForm()
{
	nError = 0;
	var strError='';
	
	strError = strError + validateInputForm('aspnetForm');
	
	if(nError>0)
	{
		showErrorWindow(nError, strError, 0, '');
		
		//alert(strError);
		return false;
	}
	
	return true;
}

function checkForm()
{
	nError = 0;
	var strError='';
	strError = strError + validateInputForm('aspnetForm');
	
	if(nError>0)
	{
		showErrorWindow(nError, strError, 0, '');
		
		//alert(strError);
		return false;
	}
	
	setPageValid(true);
		
	return true;
}

function setPageValid(value)
{
	bPageValid = document.getElementById("ctl00_bPageValid");
	if(null!=bPageValid)
	{
		bPageValid.value=value;
	}
}

function showQuestionSelect(iField)
{
	for(var i=0; i< iField.options.length; i++)
	{	
		var strName = iField.options[i].abaShowQuestionId;
		
		if(null!=strName)
		{
			var iTr = document.getElementById(FORM_ELEMENT + 'q_' + strName + '_tr');
			if(null!=iTr)
			{
			    if(iTr.style.display != '')
			    {
				    iTr.style.display = 'none';
				}
			}
		}
	}
	
	
	var strName = iField.options[iField.selectedIndex].abaShowQuestionId;
	
	if(null!=strName)
	{
		var iTr = document.getElementById(FORM_ELEMENT + 'q_' + strName + '_tr');
		if(null!=iTr)
		{
			iTr.style.display = '';
		}
		
	}
}

function showQuestionRadioButtonList(iField)
{
	var iSelected;
	var iOption;
	var iSpan;
	var iId
	var iTrQuestion
	
	iOption = iField.getElementsByTagName("input");
	if(null!=iOption)
	{
		for (var i=0; i < iOption.length; i++) 
		{
			if("RADIO" == iOption[i].type.toUpperCase())
			{
				if(iOption[i].checked)
				{
					iSelected = iOption[i].value;
					break;
				}
			}	
		}
	} 

	iSpan = iField.getElementsByTagName("span");
	if(null!=iSpan)
	{
		for(var i=0; i< iSpan.length; i++)
		{
			iId = iSpan[i].id;
			
			if(null!=iId)
			{
				iTrQuestion = document.getElementById(FORM_ELEMENT + 'q_' + iSpan[i].abaShowQuestionId + '_tr');
				if(null!=iTrQuestion)
				{
					if(iId == iSelected)
					{
						iTrQuestion.style.display = '';
					}
					else
					{
						iTrQuestion.style.display = 'none';
					}
				}
			}
		}
	}
}

function showQuestionOnLoad()
{
	var objForm = document.getElementById('aspnetForm');

	iCol = objForm.all.tags("SELECT");
	for(i=0;i<iCol.length;i++)
	{
		showQuestionSelect(iCol[i]);
	}
	
	
	var iCol = objForm.all.tags("TABLE");
	for(i=0;i<iCol.length;i++)
	{
		showQuestionRadioButtonList(iCol[i]);
	}
}

function showUnbookVisit()
{
	var strPage = "popups/abaUnbookVisit.aspx";
	var pcdialogargs = "dialogHeight: 300px; dialogWidth: 500px; center: Yes; help: No; resizable: No; status: No;";
	
	var oReturn = new Object();
	var oReturn = showModalDialog(strPage,"",pcdialogargs);
	
	if (oReturn != null) 
	{
		return oReturn;
	}
}
/*==============================================================================

Application:   Utiity Function
Author:        John Gardner

Version:       V1.0
Date:          18th November 2003
Description:   Used to check the validity of a UK postcode

Version:       V2.0
Date:          8th March 2005
Description:   BFPO postcodes implemented.
               The rules concerning which alphabetic characters are alllowed in 
               which part of the postcode were more stringently implementd.
  
Parameters:    toCheck - postcodeto be checked. 

This function checks the value of the parameter for a valid postcode format. The 
space between the inward part and the outward part is optional, although is 
inserted if not there as it is part of the official postcode.

If the postcode is found to be in a valid format, the function returns the 
postcode properly formatted (in capitals with the outward code and the inward
code separated by a space. If the postcode is deemed to be incorrect a value of 
false is returned.
  
Example call:
  
  if (checkPostCode (myPostCode)) {
    alert ("Postcode has a valid format")
  } 
  else {alert ("Postcode has invalid format")};
                    
------------------------------------------------------------------------------*/

function checkPostCode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  

  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}


var iHelpElOn=null;
var strOldColor='';
function doMouseOver(el, strEmptyText)
{
	var iHelpDiv = document.getElementById("abaHelpText")
	var iText = strEmptyText;
	if(null!=iHelpDiv)
	{
		iHelpDiv.innerHTML = "&nbsp;"
	}
	
	if(null!=iHelpElOn)
	{
		//iHelpElOn.style.background='black';
	}
	
	if(null==el)
	{
		var iEl = window.event.srcElement;
	}
	else
	{
		var iEl = el;
	}
	
	if(null==iEl)
	{
		return;
	}
	
	if(iEl.disabled){return;}
	
	if(null!=iEl.abadescription)
	{
		iText = iEl.abadescription;
	}
	
	if(iEl.type=='checkbox' || iEl.type=='radio')
	{
		iHelpElOn = null;
	}
	else
	{
		//iEl.style.background='#CDD8F7';
		iHelpElOn = iEl;
	}
	if(null!=iHelpDiv)
	{
		iHelpDiv.innerHTML = iText;
	}	
}