
var nError;
var strError;
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 vErrorHighlight = new Array(50);
var nErrorHighlight=0;
var nRecommended = 0;
var strRecommended = "";
var ignoreRecommended = false;

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 trim(s) 
{
 var r=/\b(.*)\b/.exec(s);
 return (r==null)?"":r[1];
}


function resetErrorForm()
{
	for(var i=0;i<nErrorHighlight;i++)
	{
		vErrorHighlight[i].style.background = 'white';
		vErrorHighlight[i].ICERRORHI=0;
	}
	nErrorHighlight = 0;
	strRecommended = "";
    nRecommended = 0;
    strError = "";
    nError = 0
}

function highlightErrorField(iField)
{
    
	iField.style.background = 'yellow';
	iField.ICERRORHI=1;
	vErrorHighlight[nErrorHighlight++] = iField;
	
}

function highlightRecommendedField(iField)
{
	iField.style.background = 'orange';
	iField.ICERRORHI=1;
	vErrorHighlight[nErrorHighlight++] = iField;
}

function checkOtherTextField(strField, strDisplay, rowForOther) {
    if (getFormElement(rowForOther) != null) {
        if (getFormElement(rowForOther).style.display != 'none') {
            var iField = getFormElement(strField);
            if (null != iField) {
                if ('' == iField.value) {
                    highlightErrorField(iField);
                    nError++;
                    return '<LI>A value must be specified for ' + strDisplay + '.';
                }

            }
        }
    }
    return '';
}

function checkMandatoryField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(''==iField.value || 'NON'==iField.value || 'NOT'==iField.value)
		{
			highlightErrorField(iField);
			nError++;
			return '<LI>A value must be specified for ' + strDisplay + '.';
		}
		
	}
	
	return '';
}

function checkRecommendedField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	
	if(null!=iField)
	{
		if(''==iField.value || 'NON'==iField.value || 'NOT'==iField.value)
		{
			highlightRecommendedField(iField);
			nRecommended++;
			return '<LI>A value is recommended for ' + strDisplay + '.';
		}
		
	}
	
	return '';
}

function checkMandatoryValue(strValue, strDisplay)
{
	if(''==strValue|| 'NON'==strValue || 'NOT'==strValue)
	{
		nError++;
		return '<LI>A value must be specified for ' + strDisplay + '.';
	}
		
	return '';
}


function checkMandatoryNumericField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(''==iField.value)
		{
			highlightErrorField(iField);
			nError++;
			return '<LI>A value must be specified for ' + strDisplay + '.';
		}
		
		alert(isPositiveReal(iField.value));
		if(!isPositiveReal(iField.value))
		{
			highlightErrorField(iField);
			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)
		{
			highlightErrorField(iField);
			nError++;
			return '<LI>A value must be specified for ' + strDisplay + '.';
		}
		if(!isReal(iField.value))
		{
			highlightErrorField(iField);
			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(0==iField.options.length )
		{
			highlightErrorField(iField);
			nError++;
			return '<LI>A value must be selected for ' + strDisplay + '.';
		}
		else
		{
			if(iField.value==strNullValue || iField.value==''  || 'NON'==iField.value || 'NOT'==iField.value)
			{
				highlightErrorField(iField);
				nError++;
				return '<LI>A value must be selected for ' + strDisplay + '.';
			}
			
		}
		
	}
	return '';
}

function checkNINO(toCheck) {

  var valid = false;
  var exp = /^[A-CEGHJ-NOPR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}[0-9]{6}[ABCD\s]{1}/
  if (toCheck.match(exp)) {
    valid = true;
  }
  exp = /(^GB)|(^BG)|(^NK)|(^KN)|(^TN)|(^NT)|(^ZZ).+/
  if (toCheck.match(exp)) {
    valid = false;
  }
  
  // Return with the error status
  return valid;
}

function showErrorWindow(nError, strError, nSpecialMan, strSpecialMan) {

	if (0!=nError)
	{
		var nHeight = 170 + (nError*15);
	}
	else
	{
		var nHeight = 157 + (nSpecialMan*15);
    }

	var strPage;
	if(-1==location.href.indexOf("Popup")) {
	    
		strPage = "Popup/ShowError.aspx?strError=" + strError + "&strSpecialMan=" + strSpecialMan;
	}
	else
	{
		strPage = "ShowError.aspx?strError=" + strError + "&strSpecialMan=" + strSpecialMan;
}
	if (showErrorPage(strPage, nHeight, 370))
	{
		return true;
	}
	
	return false;
}

function showRecommendedWindow(nRec, strRec)
{
    if(ignoreRecommended)
    {
        return true
    }
    else
    {
        var strPage = "Popup/ShowRecommended.aspx?strRecommended=" + strRec;
     
         showRecommendedPage(strPage); 
         return false;
    }
}

function popUpRegisterEvent(strRef, strRefOther) {
    var strPage = "Popup/Modeless.aspx?strHREF=Popup/RegisterEvent.aspx&strRef=" + escape(strRef) + "&strRefOther=" + escape(strRefOther);
    iBox.showURL(strPage, "", { width: screen.width, height: screen.height });
}

function popUpEventEmailConfirmation(strRef) {
    var strPage = "Popup/Modeless.aspx?strHREF=Popup/EventEmailConfirmation.aspx&strRef=" + escape(strRef);
    iBox.showURL(strPage, "", { width: 800, height: 400 });
}

function showHolding(ref) {
    //var strPage = "Popup/Modeless.aspx?strHREF=Popup/ViewHolding.aspx&strRef=" + escape(ref);
    //iBox.showURL(strPage, "", { width: 700, height: 300 });
    var strPage = "popup/Modeless.aspx?strHREF=ViewHolding.aspx?strRef=" + escape(ref);

    var pcdialogargs = "dialogHeight: 150px; dialogWidth: 600px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);
    //return arr;
    document.getElementById("icPage_mainContent_btnRefresh").click()
}

function popUpPostcode(postcode) {
    var strPage = "Popup/Modeless.aspx?strHREF=Popup/PostcodePopup.aspx&strRef=" + postcode;

    //hack for popup in a popup
    strPage = strPage.replace("popup/popup/", "popup/");
    iBox.showURL(strPage, "", { width: 800, height: 400 });
}


function popUpPartnerInfo() {
    var strPage = "Popup/Modeless.aspx?strHREF=../Popup/PartnerInformation.aspx";
    //iBox.showURL(strPage, "", { width: 960, height: 600 });
    var pcdialogargs = "dialogHeight: 600px; dialogWidth: 800px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);
}

function assignMentor(mentoringId) {
    var strPage = "Popup/Modeless.aspx?strHREF=Popup/assignMentor.aspx&strRef=" + escape(mentoringId);
    iBox.showURL(strPage, "", { width: 800, height: 400 });
}

//todo for non error pages
function showRecommendedPage(strPage)
{
   iBox.showURL(strPage, "", "");
   
}
///ucMeetingControl_
function showOrganisationPopup(prefix) {

    var orgId = getFormElement(prefix + "hdnOrganisationId").value;
    
    var indId = getFormElement(prefix + "hdnIndividualId").value;
    var meetingId = getFormElement(prefix + "hdnMeetingId").value;

    var strPage = "Popup/Modeless.aspx?strHREF=Popup/AddOrganisation.aspx&strRef=" + orgId + "&strOther=" + indId + "&strReturn=" + meetingId + "&strPrefix=" + prefix;
    iBox.showURL(strPage, "", { width: 800, height: 800 });

}

function addPartnershipDetails() {

    var strPage = "popup/Modeless.aspx?strTitle='Select Organisation'&strHREF=popup/SetPartnership.aspx";
    showPopupPage(strPage, 600, 900);
}

function showMeetingsPopup(meetingControl, meetingDate, meetingTime)
{
	var strPage = "popup/Modeless.aspx?strTitle='Upcoming Meetings'&strHREF=popup/UpcomingMeetings.aspx";
	showPopupPage(strPage, 300, 550);
}

function popUpChangeClientManager(individualId) {

    var strPage = "popup/Modeless.aspx?strTitle='Upcoming Meetings'&strHREF=ChangeClientManager.aspx&strRef=" + individualId;
    var pcdialogargs = "dialogHeight: 600px; dialogWidth: 800px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);

    if (arr!= null && arr != "") {
        document.location.href = 'EditTransaction.aspx?nActionId=2&strRef=' + arr;
    }
}

function showErrorPage(strPage, nHeight, nWidth)
{
	//window.showHelp;
    iBox.showURL(strPage, "Error With Form", "");
    //iBox.showURL(strPage, "Error With Form", { width: 800, height: 400 });
        //iBox.show(strPage);.
}

//todo for non error pages
function showPopupPage(strPage, nHeight, nWidth)
{
   iBox.showURL(strPage, "", "");
   
}

function clearErrorForPopup()
{
    resetErrorForm();
    document.getElementById("divErrorMessage").innerHTML = "";
}

function showErrorForPopup(message) {
    document.getElementById("divErrorMessage").innerHTML = "&nbsp;&nbsp;Please fix the following before submitting again:<br /><br />" + message;
}
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("icEditForm")
		iForm.submit();
	}
}



function checkOptionalNumericField(strField, strDisplay)
{
	
	var iField = document.getElementById(strField);
	if(null!=iField)
	{
		if(!isPositiveInt(iField.value))
		{
			highlightErrorField(iField);
			nError++;
			return '<LI>' + strDisplay + ' should be a positive integer.';		
		}
	}
	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)
		{
			highlightErrorField(iField);
			nError++;
			return '<LI>A value must be specified 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)
{

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;        	
	}
}

var currentPopUpField;

function expandTextbox(strField)
{
    var iImage = window.event.srcElement;
    var bAutoEnabled = (null != iImage.ICEXPANDIMAGE_AUTOENABLE);
    var iField = document.getElementById(strField);
    if (null == iField) {
        // Here we try and find a text box to expand - assumption is:
        // Clicked image sits in a <TR>
        // TEXTAREA sits in the next <TR> therefore
        //  1. Mark <TR> which image sits in with an attribute
        //  2. Find <TABLE> parent of <TR>
        //  3. Find <TR> children of said parent and iterate looking for attribute
        //  4. Once found, remove the attribute and remember the next <TR>
        //  5. Looking inside the remembered <TR> for a TEXTAREA - if there is only one assume this is our bad boy!
        var iTR = GetFirstParentWithTag(iImage, "TR");

        if (null == iTR) return;
        iTR.ICRemoveAfterProcessing = 1;

        var iTable = GetFirstParentWithTag(iTR, "TABLE");
        if (null == iTable) return;

        var iTRs = iTable.all.tags("TR");
        var iTRWithTextArea = null;
        for (var i = 0; i < iTRs.length; i++) {
            if (null != iTRs[i].ICRemoveAfterProcessing) {
                iTRs[i].ICRemoveAfterProcessing = null;
                if (i < iTRs.length - 1) {
                    iTRWithTextArea = iTRs[i + 1];
                }
                break;
            }
        }
        if (null == iTRWithTextArea) return;
        var iTextAreas = iTRWithTextArea.all.tags("TEXTAREA");
        if (null == iTextAreas) return;
        if (1 != iTextAreas.length) return;
        strField = iTextAreas[0].id;
        iField = iTextAreas[0];
    }
    if (null != iField)
    {
        var strExtra = "";
        if (bAutoEnabled)
        {
            strExtra = "&allowSave=false";
        }
        var strPage = "popup/ExpandTextbox.aspx?transparent=true" + strExtra + "&strText=" + escape(iField.value);
        showPopupPage(strPage, 330, 560);
        currentPopUpField = strField;

    }
}


function updateNotes(strReturn)
{
    iBox.hide();
	
	if(null!=strReturn)
	{
		document.getElementById(currentPopUpField).value = strReturn;
	}
}


function updateOrganisations(strOrganisation)
{
    iBox.hide();
	
	if(null!=strOrganisation) {
		var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
		vOrganisation = strOrganisation.split('~');
		// Need to check if the Organisation already exists
		if(0==oSelect.length)
		{	
			vOrganisation[1] = "* " + vOrganisation[1];
		}
		for(var i=0;i<oSelect.options.length;i++)
		{
			var oOption = oSelect.options[i];
			if(oOption.value == vOrganisation[0])
			{
				alert('This Organisation is already selected');
				return;
			}
		}
		oSelect.options[oSelect.length] = new Option(vOrganisation[1], vOrganisation[0]);
		if("NEW"==vOrganisation[0])
		{
			alert('You have chosen to associate this individual with a New Organisation.\nYou will be brought to the Add Organisation screen when you Save this record.');
		}
	}

	//this is pure hack to get the form to work after the popup is closed - do not remove - Paddy :)
	var hackField = getFormElement('ucIndividualControl_txtForename');
	if (hackField != null)
	    hackField.focus();

}

function updatePartnership(strData) {
    iBox.hide();

    var vDates = strData.split('#');
    var dtStart = vDates[0];
    var dtEnd = vDates[1];

    var oSelect = getFormElement('ucIndividualControl_lstOrganisation');
    var displayText = oSelect.options[oSelect.selectedIndex].text;
    displayText = displayText.split(" (")[0];

    oSelect.options[oSelect.selectedIndex].value = oSelect.options[oSelect.selectedIndex].value.split('~')[0] + "~" + dtStart + "~" + dtEnd;
    
    if (dtEnd != "") {
        oSelect.options[oSelect.selectedIndex].text = oSelect.options[oSelect.selectedIndex].text.split('(')[0] + " (" + dtStart + " - " + dtEnd +")";
    }
    else {
        oSelect.options[oSelect.selectedIndex].text = oSelect.options[oSelect.selectedIndex].text.split('(')[0] + " (" + dtStart + " - present)";
    }

    //this is pure hack to get the form to work after the popup is closed - do not remove - Paddy :)
    getFormElement('ucIndividualControl_txtIndividualNotes').focus();
}

var controlId, dateId, timeId

function setMeetingsPopup(tcontrolId, tdateId, ttimeId)
{
    controlId = tcontrolId;
    dateId = tdateId;
    timeId = ttimeId;
}

function updateCalendarTime(strTime)
{
    iBox.hide();
    if(null!=strTime)
	{
	
		var vReturn = strTime.split("T");
		getFormElement(controlId + dateId).value = convertToBritishFormat(vReturn[0], '-', '/');
		getFormElement(controlId + timeId).value = vReturn[1].substring(0, 5);
	}
	
}

 
function validateInputForm(strFormName)
{
	
	strError='';
	strRecommended =''
	var objForm = document.getElementById(strFormName);
	var iCol = objForm.getElementsByTagName("input");

	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];
	
		if("text" == oElement.type.toLowerCase())
		{
			
			var strName = oElement.getAttribute("icMandatory");
			
			if(null!=strName)
			{
			    strError = strError + checkMandatoryField(oElement.getAttribute("id"), strName);
			}
			else
			{
		        if(!ignoreRecommended)
                {
			        //is recommended?
			        strName = oElement.getAttribute("icRecommended");
    			
			        if(null!=strName)
			        {
			            strRecommended = strRecommended + checkRecommendedField(oElement.getAttribute("id"), strName);
			        }
			    }
			}
	   }
	}

	var iCol = objForm.getElementsByTagName("textarea");

	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];
		var strName = oElement.getAttribute("icMandatory");
		if(null!=strName)
		{
			strError = strError + checkMandatoryField(oElement.getAttribute("id"), strName);
		}
    }
	iCol = objForm.getElementsByTagName("select");
	for(i=0;i<iCol.length;i++)
	{
		var oElement=iCol[i];
							
		var strName = oElement.getAttribute("icMandatory");
		if(null!=strName)
		{
			strError = strError + checkMandatoryList(oElement.getAttribute("id"), strName, oElement.icNull);
		}
	}
	return strError;
}


function checkStandardForm()
{
	nError = 0;
	strError='';
	
	strError = strError + validateInputForm('icFormHolder');
	
	if(nError>0)
	{
		showErrorWindow(nError, strError, 0, '');
		return false;
	}
		
	return true;
}

function validateSpecialMandatory(strFormName)
{

	var strSpecialMan='';
	var objForm=document.all.item(strFormName);

	for(i=0;i<objForm.elements.length;i++)
	{
	   var oElement=objForm.elements[i];
		
		//check text fields
	   if(("text" == oElement.type.toLowerCase()))
	   {
			var oManElement=oElement.name + 'SpecialMandatory';
			if(null!=(document.getElementById(oManElement)))
			{
			    var strName=document.getElementById(oManElement).value;
			    strSpecialMan = strSpecialMan + checkSpecialMandatoryField(oElement.name, strName);
			}
	   }
	}
	return strSpecialMan;
}

function checkSpecialMandatoryField(strField, strDisplay)
{
	var iField = document.getElementById(strField);
	
	if(null!=iField)
	{
		if(''==iField.value)
		{
			nSpecialMan++;
			return '<LI>' + strDisplay + '.';
		}
	}
	
	return '';
}



function postcodePopup(strPagePrepend, strFieldPrepend) {

    var iPostcode = document.getElementById(strPagePrepend + "txt" + strFieldPrepend + "Postcode");
    var iAddress1 = document.getElementById(strPagePrepend + "txt" + strFieldPrepend + "Address1");
    var iAddress2 = document.getElementById(strPagePrepend + "txt" + strFieldPrepend + "Address2");
    var iAddress3 = document.getElementById(strPagePrepend + "txt" + strFieldPrepend + "Address3");
    var iTown = document.getElementById(strPagePrepend + "txt" + strFieldPrepend + "Town");
    var iImgPostcode = document.getElementById(strPagePrepend + "img" + strFieldPrepend + "Postcode");
    var iAddressStatus = document.getElementById(strPagePrepend + "hdn" + strFieldPrepend + "AddressStatus");
    var iPostcodeVerify = document.getElementById(strPagePrepend + "hdn" + strFieldPrepend + "PostcodeVerify");

    var hdnAddress1 = document.getElementById(strPagePrepend + "hdnAddress1");
    var hdnAddress2 = document.getElementById(strPagePrepend + "hdnAddress2");
    var hdnAddress3 = document.getElementById(strPagePrepend + "hdnAddress3");
    var hdnTown = document.getElementById(strPagePrepend + "hdnTown");
    var outsideNI = document.getElementById(strPagePrepend + "cbROIClient");

    var strPostcode = iPostcode.value;
    var nLenBefore = strPostcode.length;
    var strWithoutSpaces = strPostcode.replace(/\ /g, '');
    var nLenAfter = strWithoutSpaces.length;

    if (nLenAfter == nLenBefore) {
        if (6 == nLenBefore) {
            strPostcode = strPostcode.substr(0, 3) + ' ' + strPostcode.substr(3);
        }
        if (7 == nLenBefore) {
            strPostcode = strPostcode.substr(0, 4) + ' ' + strPostcode.substr(4);
        }
    }

    var strPage = ""
    if (window.location.href.indexOf("Popup/") < 0) {
        strPage += "popup/";
    }
    strPage +="Modeless.aspx?strHREF=" + ICPOSTCODE_POPUP_LOCATION + "PostcodePopup.aspx?strPostcode=" + escape(strPostcode) + "&nAppId=2";
    //alert(strPage);
    strPage = strPage.replace("popup/popup/", "popup/");
    //alert(strPage);
    var pcdialogargs = "dialogHeight: 370px; dialogWidth: 440px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);

    if (arr != null) {
        var vAddress = arr.split("**");

        iAddress1.value = vAddress[0];
        iAddress2.value = vAddress[1];
        iAddress3.value = vAddress[2];
        iTown.value = vAddress[3];
        iPostcode.value = vAddress[6];
        if (iPostcodeVerify != null) {

            iPostcodeVerify.value = vAddress[6];

        }
        if (iAddressStatus != null) {
            iAddressStatus.value = vAddress[7];
        }

        hdnAddress1.value = iAddress1.value;
        hdnAddress2.value = iAddress2.value;
        hdnAddress3.value = iAddress3.value;
        hdnTown.value = iTown.value;

        if (vAddress[4] == "OTH")
            outsideNI.checked = true;

        if ("0" == vAddress[7]) {
            if (window.location.href.indexOf("Popup/") > 0) {
                iImgPostcode.src = "../images/icons/search.gif";
            }
            else {
                iImgPostcode.src = "images/icons/search.gif";
            }
        }
        else {
            iImgPostcode.src = "images/icons/searchAlert.gif";
        }
    }
}

function alertDeleteNotAllowed()
{
	alert('You do not have permission to delete enquiries.');
	return false;
}


function getFormElement(strName)
{
	return document.getElementById("ct100_mainContent_" + strName);
}

function checkSearchForm()
{
    var iSearch = document.getElementById("ct100_txtSearch");
	if(null!=iSearch)
	{
		if(iSearch.value.length<3)
		{
			alert('Please choose a search term of 3 or more characters.');
			return false;
		}
	}
	return true;
}

function checkHiddenSavedBefore()
{
	var iHiddenSavedBefore = window.document.getElementById('icPage:hdnSavedBefore');
	if("1" == iHiddenSavedBefore.value)
	{
		alert('This record has been saved before.\nYou have pressed the Back button on your browser.\nYou cannot save this record again.\nPlease find the existing record and edit it.');
		return true;
	}
	return false;
}


function setHiddenSavedBefore()
{
	var iHiddenSavedBefore = window.document.getElementById('icPage:hdnSavedBefore');
	iHiddenSavedBefore.value = 1;
}


function checkTimeFormat(field, strName)
{	
	//alert("in here "+ field.id);
	if(field.value!='')
	{
		
		var vTime=field.value.split(':');		
		if(field.value.length<5)
		{
			
			nError++;
			highlightErrorField(field);
			return '<LI>' + strName + ' must be of format HH:MM';
		}	
		else
		{
			
			if(parseInt(vTime[0])>23)
			{
			
				nError++;
				highlightErrorField(field);
				return '<LI>' + strName + ' [Hours] must be in range 0 to 23';
			}
			if(parseInt(vTime[1])>59)
			{
			
				nError++;
				highlightErrorField(field);
				return '<LI>' + strName + ' [Minutes] must be in range 0 to 59';
			}
		}
	}
	return ''
}

function toggleDetails(objectNameToToggle, toggleButton)
{

	var objectToToggle = window.getFormElement( objectNameToToggle);

	if(objectToToggle.style.display != 'none')
	{
		objectToToggle.style.display = 'none'
		toggleButton.src = "images/icons/expandOnBlack.gif";
	}else
	{
		objectToToggle.style.display = ''
		toggleButton.src = "images/icons/collapseOnBlack.gif";
	}
}

//This function return a date object after accepting 
//a date string ans dateseparator as arguments
function getDateObject(dateString,dateSeperator)
{
	var curValue=dateString;
	var sepChar=dateSeperator;
	var curPos=0;
	var cDate,cMonth,cYear;

	//extract day portion
	curPos=dateString.indexOf(sepChar);
	cDate=dateString.substring(0,curPos);
	
	//extract month portion				
	endPos=dateString.indexOf(sepChar,curPos+1);			
	cMonth=dateString.substring(curPos+1,endPos);

	//extract year portion				
	curPos=endPos;
	endPos=curPos+5;			
	cYear=curValue.substring(curPos+1,endPos);
	
	//Create Date Object
	dtObject=new Date(cYear,cMonth,cDate);	
	return dtObject;
}


function checkFollowUpdateDate(tranDate, followupDate, helpText)
{
    if (followupDate.value != "")
    {
        var td = getDateObject(tranDate.value, "/")
        var fd =  getDateObject(followupDate.value, "/")
        if (td > fd)
        {
			highlightErrorField(tranDate);
			highlightErrorField(followupDate);
            nError++;
            return "<li>Follow-up date cannot be greater than " +  helpText + " date</li>";
            
        }
    }
    return "";
}


//for recommended error page
function clickYes()
{
    //set ignore recommended to true to avoid validation second time around
    parent.ignoreRecommended=true; 
    
    //hide the popup
    parent.iBox.hide();
    
    //get all input items to find submit button
    var buttons = parent.document.getElementsByTagName("input");
    var i =0
    var submitButton
    for (i=0; i<buttons.length;i++)
    {
       
        if (buttons[i].getAttribute("type") == "submit" && buttons[i].getAttribute("icSubmit") != null)
        {
            submitButton = buttons[i];
            i = buttons.length;
        }
    }
    if (submitButton != null)
    {
        submitButton.click();
    }
}

function CheckKeyCode(e)
{
    if (navigator.appName == "Microsoft Internet Explorer")
    {
        if((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode == 8))
        {
            return true;
        }
        else
        {
        return false;
        }
    }
    else
    {
        if ((e.charCode >= 48 && e.charCode <= 57) || (e.charCode == 0))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

function checkEmail(inputvalue) {
    var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if (pattern.test(inputvalue)) {
        return true;
    } else {
        return false;
    }
}

/*********************************************************************
O R G A N I S A T I O N   s C R I P T S
*********************************************************************/
function getOrganisationList() {
    var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
    var strReturn = '';
    var strItem = '';

    for (var i = 0; i < oSelect.options.length; i++) {
        var oOption = oSelect.options[i];
        if (0 == oOption.text.indexOf('*')) {
            strItem = "*" + oOption.value;
        }
        else {
            strItem = oOption.value;
        }

        if ('' == strReturn) {
            strReturn = strItem;
        }
        else {
            strReturn += '%' + strItem;
        }
    }

    return strReturn;
}

function removeOrganisation() {
    var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
    if (-1 == oSelect.selectedIndex) {
        alert('A Organisation must be selected');
    }
    else {
        var oOption = oSelect.options[oSelect.selectedIndex];
        var bDefault = (0 == oOption.text.indexOf('*'));

        oSelect.options[oSelect.selectedIndex] = null;


        if (bDefault) {
            // The default was removed, therefore we need to make 
            // the top one the default.
            if (oSelect.options.length > 0) {
                oSelect.options[0].text = "* " + oSelect.options[0].text;
            }
        }
    }
}

function defaultOrganisation() {
    var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
    if (-1 == oSelect.selectedIndex) {
        alert('A Organisation must be selected');
    }
    else {

        var bDefault = (0 == oSelect.options[oSelect.selectedIndex].text.indexOf('*'));

        if (bDefault) {
            alert('This is already the default Organisation');
        }
        else {
            for (var i = 0; i < oSelect.options.length; i++) {
                var oOption = oSelect.options[i];
                if (i == oSelect.selectedIndex) {
                    oOption.text = "* " + oOption.text;
                }
                else {
                    if (0 == oOption.text.indexOf('*')) {
                        oOption.text = oOption.text.substring(2);
                    }
                }
            }
        }
    }
}

function showInfoOrganisation() {
    var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
    if (-1 == oSelect.selectedIndex) {
        alert('A Organisation must be selected');
    }
    else {
        if ("NEW" == oSelect.options[oSelect.selectedIndex].value) {
            alert('You cannot see the info for a new Organisation.\nYou will have the opportunity to add the new Organisation details on the next screen.');
        }
        else {
            window.location = "editOrganisation.aspx?nActionId=2&strRef=" + oSelect.options[oSelect.selectedIndex].value;
        }
    }
}

function transferData() {
    var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
    if (-1 == oSelect.selectedIndex) {
        alert('A Organisation must be selected');
    }
    else {
        var selOrg = oSelect.options[oSelect.selectedIndex].value;

        if ("NEW" == selOrg) {
            alert('You cannot see the info for a new Organisation.\nYou will have the opportunity to add the new Organisation details on the next screen.');
        }
        else {
            document.getElementById(organisationPrefix + '_hdnSelectedOrganisation').value = selOrg;
            return confirm("This operation will replace details on this form with that of the selected organisation(" + selOrg + ").\nAre you sure you wish to continue?");
        }
    }
    return false;
}

function ProcessOrganisations() {
    // -----------------------------------------------------------------------
    var oSelect = document.getElementById(organisationPrefix + '_lstOrganisation');
    var strOrganisationList = "";

    for (var i = 0; i < oSelect.options.length; i++) {
        var oOption = oSelect.options[i];
        if (0 == oOption.text.indexOf('*')) {
            strItem = "1*" + oOption.value + "*" + oOption.text.substring(2);
        }
        else {
            strItem = "0*" + oOption.value + "*" + oOption.text;
        }

        if (0 != i) {
            strOrganisationList += "%";
        }

        strOrganisationList += strItem;
    }
    document.getElementById(organisationPrefix + '_hdnOrganisationList').value = strOrganisationList;
}

function chooseMeetingDefaultRegion(strRegion)
{
    var strPage = "popup/Modeless.aspx?strHREF=bookMeeting.aspx&strRegion=" + escape(strRegion);

    var pcdialogargs = "dialogHeight: 720px; dialogWidth: 820px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);
    return arr;
}

function chooseMeeting(strPostcode, clientManager, callCentre) {
    var strPage = "popup/Modeless.aspx?strHREF=bookMeeting.aspx&strPostcode=" + escape(strPostcode) + "&strClientManager=" + escape(clientManager);
    
    var pcdialogargs = "dialogHeight: 720px; dialogWidth: 820px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);
    return arr;
}
function chooseMeetingCC(strPostcode, clientManager) {
    var strPage = "popup/Modeless.aspx?strHREF=bookMeeting.aspx&strPostcode=" + escape(strPostcode) + "&bCC=true&strClientManager=" + escape(clientManager);
    
    var pcdialogargs = "dialogHeight: 720px; dialogWidth: 820px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);
    return arr;
}

function selectMeetingDate(userId) {
    var strPage = "Popup/Modeless.aspx?strHREF=SelectMeetingDate.aspx&strRef=" + userId;
    var pcdialogargs = "dialogHeight: 250px; dialogWidth: 820px; center: Yes; help: No; resizable: No; status: No;scroll: No;";
    var arr = showModalDialog(strPage, "", pcdialogargs);

    return arr;
}



function CompareDates(date1, date2) {
    ///<summary>Compates two dates</summary>
    ///<param name="date1">Date 1</param>
    ///<param name="date1">Date 1</param>
    ///<returns>Returns 1 if date1>date2, -1 if date1<date2, 0 otherwise</returns>
    var dt1 = parseInt(date1.substring(0, 2), 10);
    var mon1 = parseInt(date1.substring(3, 5), 10);
    var yr1 = parseInt(date1.substring(6, 10), 10);
    var dt2 = parseInt(date2.substring(0, 2), 10);
    var mon2 = parseInt(date2.substring(3, 5), 10);
    var yr2 = parseInt(date2.substring(6, 10), 10);
    var tempDate1 = new Date(yr1, mon1 - 1, dt1);
    var tempDate2 = new Date(yr2, mon2 - 1, dt2);

    if (tempDate1 < tempDate2) {
        return -1;
    }
    else if (tempDate1 > tempDate2) {
        return 1;
    }
    else {
        return 0;
    }
}

function checkAddressFields(prefix) {
    var obj = document.getElementById(prefix + "_cbROIClient");

    if (obj.checked) {
        enableTextbox(prefix + "_txtAddress1")
        enableTextbox(prefix + "_txtAddress2");
        enableTextbox(prefix + "_txtAddress3");
        enableTextbox(prefix + "_txtTown");
        disableTextbox(prefix + "_imgPostcode");
        disableTextbox(prefix + "_txtPostcode");

        // getFormElement("imgPostcode").style.display='none'
    } else {
        disableTextbox(prefix + "_txtAddress1")
        disableTextbox(prefix + "_txtAddress2");
        disableTextbox(prefix + "_txtAddress3");
        disableTextbox(prefix + "_txtTown");
        enableTextbox(prefix + "_imgPostcode");
        enableTextbox(prefix + "_txtPostcode");
    }
}

function enableTextbox(suffixOfControl) {

    document.getElementById(suffixOfControl).disabled = false;
    document.getElementById(suffixOfControl).style.borderColor = 'black';
}
function disableTextbox(suffixOfControl) {

    document.getElementById(suffixOfControl).disabled = true;
    document.getElementById(suffixOfControl).style.borderColor = '#AFAFAF';
}


function directReferralToINI(currentProgramme) {
    var btnReferralToINI = document.getElementById('icPage_SidePanel_btnReferralToINI');
    var hdnCurrentProgramme = document.getElementById('icPage_SidePanel_hdnCurrentProgramme');

    hdnCurrentProgramme.value = currentProgramme;
    if (confirm("Please confirm that you wish to refer this client to Invest NI")) {
        btnReferralToINI.click();
    }
}