// JScript source code
// Date Validation
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){		
		return false;
	}
	else{
		return true;
	}
}

function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;		
	} 
	else {
		window.onload = function() {
		oldonload();
		func();
		}
	}
}

function emailCloak() {		
	if (document.getElementById) {
		var alltags = document.all? document.all : document.getElementsByTagName("*");
		for (i=0; i < alltags.length; i++) {
			if (alltags[i].className == "emailCloak") {
			var oldText = alltags[i].firstChild;
			var emailAddress = alltags[i].firstChild.nodeValue;
			var user = emailAddress.substring(0, emailAddress.indexOf("("));
			var website = emailAddress.substring(emailAddress.indexOf(")")+1, emailAddress.length);
			var newText = user+"@"+website;
			var a = document.createElement("a");
			a.href = "mailto:"+newText;
			var address = document.createTextNode(newText);
			a.appendChild(address);
			alltags[i].replaceChild(a,oldText);
			}
		}
	}	
}
addLoadEvent(emailCloak);

function clearText(field){
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}

function mainmenu(){
$(" #navlist ul ").css({display: "none"}); // Opera Fix
$(" #navlist li").hover(function(){
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).slideDown(100);
		},function(){
		$(this).find('ul:first').css({visibility: "hidden"});
		});
}

function clearemailfield(fieldVal){
	if (isValidEmail(fieldVal)==false){
		document.newsletterform.email.value='';
	}
}

// Validation Functions
function isValidEmail(str) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)){
		return true;
	}
	else {
		return false;
	}
}

/* Quick Login Panel */
function checkquicklogin(){
	var ftxt = '';

	if (document.memberlogin.Username.value==''){
		ftxt += '\n- Please enter your Username.';
	}
	
	if (document.memberlogin.Password.value==''){
		ftxt += '\n- Please enter your Password.';
	}
	
	if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

/* Quick Call Back */
function checkcallbackform(){
    var ftxt = '';
    
    if (document.callbackform.ContactName.value==''||document.callbackform.ContactName.value=='Name:'){
        ftxt += '\n- Please enter your Contact Name.';    
    }
    
    if (document.callbackform.ContactNumber.value==''||document.callbackform.ContactNumber.value=='Contact Number:'){
        ftxt += '\n- Please enter your Contact Number.';    
    }
    
    if (document.callbackform.ContactComment.value==''||document.callbackform.ContactComment.value=='Nature of Enquiry'){
        ftxt += '\n- Please enter your Nature of Enquiry.';    
    }
    
    if (document.callbackform.TimetoCall.value==''){
        ftxt += '\n- Please select a Time to Call.';    
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

/* Apply Form */
var bRequireCompanyNumber = false;
function controlCompanyNumber(){    
    var CompanyRow = document.getElementById("CompanyRow");
    
    var CompanyTypeID = document.applyform.CompanyTypeID.value;
    var TheControl = CompanyTypeID.split("|");
    
    if (TheControl[0]=='True'){
        CompanyRow.style.display='block';
        bRequireCompanyNumber = true;
    }
    else {
        CompanyRow.style.display='none';
        bRequireCompanyNumber = false;
    }
}

/* Control Head Office Field */
var RequireHeadOfficeNumber = false;
function controlHeadOffice(theVal){
    var HeadOfficeRow = document.getElementById("HeadOfficeRow");

    //var Mem_ApplicationFor = document.applyform.Mem_ApplicationFor.value;
    var Mem_ApplicationFor = theVal;
    var AppFor = Mem_ApplicationFor.split("|");
    
    if (AppFor[0]=='REGIONALOFFICE'){
        HeadOfficeRow.style.display='block';
        RequireHeadOfficeNumber = true;
    }
    else {
        HeadOfficeRow.style.display='none';
        RequireHeadOfficeNumber = false;
    }
}

function checkapplyform(){
    var ftxt = '';
    var ydetails = '';
    
    if (document.applyform.Mem_Title.value==''){
        ydetails += '\n- Please enter your Title.';
    }
    
    if (document.applyform.Mem_FirstName.value==''){
        ydetails += '\n- Please enter your First Name.';
    }
    
    if (document.applyform.Mem_LastName.value==''){
        ydetails += '\n- Please enter your Surname.';
    }
    
    if (document.applyform.Mem_Position.value==''){
        ydetails += '\n- Please enter your Position.';
    }
    
    if (document.applyform.Mem_MobileNumber.value==''){
        ydetails += '\n- Please enter your Mobile Number.';
    }
    
    if (document.applyform.Mem_ApplicationFor.value==''){
        ydetails += '\n- Please select the Type of Application.';
    }
    
    if (RequireHeadOfficeNumber){
        if (document.applyform.Mem_HeadOfficeNo.value==''){
            ydetails += '\n- Please enter your Head Office Membership No.';
        }
    }
    
    if (ydetails!==''){
        ftxt += '\n** Your Details **\n' + ydetails;
    }
    
    var cdetails = '';
    
    if (document.applyform.Mem_CompanyName.value==''){
        cdetails += '\n- Please enter your Company Name.';
    }

    if (document.applyform.DandBAttempted.value == '' || document.applyform.DandBAttempted.value == 'False') {
        cdetails += '\n- Please click on Get Address Details.';
    }
    
    if (document.applyform.Mem_Address1.value==''){
        cdetails += '\n- Please enter your Address 1.';
    }
    
    if (document.applyform.Mem_Town.value==''){
        cdetails += '\n- Please enter your Town/City.';
    }
    
    if (document.applyform.Mem_County.value==''){
        cdetails += '\n- Please enter your County.';
    }
    
    if (document.applyform.Mem_Postcode.value==''){
        cdetails += '\n- Please enter your Postcode.';
    }

    if (isDate(document.applyform.Mem_CompanyStarted.value) == false) {
        cdetails += '\n- Please enter the Date your Company Started.';
    }
    
    if (document.applyform.Mem_Telephone.value==''){
        cdetails += '\n- Please enter your Telephone Number.';
    }
    
    if (isValidEmail(document.applyform.Mem_Email.value)==false){
        cdetails += '\n- Please enter your Email Address.';
    }
    
    if (document.applyform.CompanyTypeID.value==''){
        cdetails += '\n- Please select your Company Type.';
    }
    
    if (bRequireCompanyNumber){
        if (document.applyform.Mem_CompanyNumber.value==''){
            cdetails += '\n- Please enter your Registered Company Number.';
        }
    }

    if (document.applyform.ParentCompanyExists.value == '') {
        cdetails += '\n- Please select if you have a Parent Company.';
    }

    if (document.applyform.AssociatedCompanyExists.value == '') {
        cdetails += '\n- Please select if you have any Associated Companies?';
    }
    
    if (cdetails!==''){
        if (ftxt!==''){
            ftxt += '\n';
        }
        ftxt += '\n** Your Company Information **\n' + cdetails;
    }

    var pdetails = '';

    if (document.applyform.ParentCompanyExists.value == 'True') {
        if (document.applyform.Mem_ParentCompany.value == '') {
            pdetails += '\n- Please enter a Company Name.';
        }

        if (document.applyform.Mem_ParentAddress.value == '') {
            pdetails += '\n- Please enter an Address.';
        }

        if (document.applyform.Mem_ParentRegNumber.value == '') {
            pdetails += '\n- Please enter a Companies House Registration Number.';
        }

        if (pdetails !== '') {
            if (ftxt !== '') {
                ftxt += '\n';
            }
            ftxt += '\n** Ultimate/Global Parent Company Details **\n' + pdetails;
        }
    }

    var adetails = '';

    if (document.applyform.AssociatedCompanyExists.value == 'True') {
        if (adetails !== '') {
            if (ftxt !== '') {
                ftxt += '\n';
            }
            ftxt += '\n** Associated Company Details **\n' + adetails;
        }
    }
    
        
    var mdetails = '';
    
    if (document.applyform.MembershipTypeID.value==''){
        mdetails += '\n- Please select a Membership Option.';
    }
    
    if (mdetails!==''){
        if (ftxt!==''){
            ftxt += '\n';
        }
        ftxt += '\n** Membership Options **\n' + mdetails;        
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
	    if (document.applyform.TermsAgreed.checked==false){
	        alert('You must agree to ther Terms & Conditions.');
	        return false;
	    }
	    else {
		    return true;
		}
	}
}

function controlTerms(){
    var MemberTerms = document.getElementById("MemberTerms");    
    var AssociateTerms = document.getElementById("AssociateTerms");
    
    var Mem_ApplicationFor = document.applyform.Mem_ApplicationFor.value;
    var AppCode = Mem_ApplicationFor.split("|");  
    
    if (AppCode[0]=='ASSOCIATE'){
        MemberTerms.style.display='none';        
        AssociateTerms.style.display='block';
    }
    else {
        MemberTerms.style.display='block';        
        AssociateTerms.style.display='none';
    }
}

/* Membership Registratio Prices */
function dataCatch(discountedPrice,previousPrice,theSaving,theTotal){ 	
    document.getElementById("TheDiscountedPrice").innerHTML = discountedPrice;
    document.getElementById("ThePreviousPrice").innerHTML = previousPrice;
    document.getElementById("TheSaving").innerHTML = theSaving;
    //document.getElementById("TheTotal").innerHTML = theTotal;
}

function getPrice(theVal) {
    /*
	if(document.layers && document.layers['datadiv'].load){				
		document.layers['datadiv'].load('Scripts/GetRegisterPrice.asp?TypeID='+ typeid,0);		
	}
	else if(window.frames && window.frames.length){				
		window.frames['dataframe'].window.location.replace('Scripts/GetRegisterPrice.asp?TypeID='+ typeid);				
	}	
	
	alert('Scripts/GetRegisterPrice.asp?TypeID='+ typeid);
	*/
    var thearray = theVal.split("|");
    var typeid = thearray[0];

    var ThePrice = document.getElementById("ThePrice");
    ThePrice.innerHTML = '£' + thearray[1] + '.00';
}

/* Enquiry Form */
function checkenquiryform(){
    var ftxt = '';
    
    if (document.enquiryform.Name.value==''){
        ftxt += '\n- Please enter your Name.';
    }
    
    if (document.enquiryform.Position.value==''){
        ftxt += '\n- Please enter your Position.';
    }
    
    if (document.enquiryform.Telephone.value==''){
        ftxt += '\n- Please enter your Telephone Number.';
    }
    
    if (document.enquiryform.Mobile.value==''){
        ftxt += '\n- Please enter your Mobile Number.';
    }
    
    if (isValidEmail(document.enquiryform.email.value)==false){
        ftxt += '\n- Please enter your Email Address.';
    }
    
    if (document.enquiryform.Company.value==''){
        ftxt += '\n- Please enter your Company Name.';
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

/* Reset Password */
function checkresetform(){
    var ftxt = '';
    
    if (document.resetform.Username.value==''){
        ftxt += '\n- Please enter your Username.';
    }
    
    if (isValidEmail(document.resetform.EmailAddress.value)==false){
        ftxt += '\n- Please enter your Email Address.';
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	} 
}

/* Login Form */
function checloginform(){
    var ftxt = '';
    
    if (document.loginform.Username.value==''){
        ftxt += '\n- Please enter your Username.';
    }
    
    if (document.loginform.Password.value==''){
        ftxt += '\n- Please enter your Password.';
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

/* Pre-fill from Premium Indication */
function checkprefillform(){
    if (document.prefill.AccessKey.value==''){
        alert('Please enter an Access Key');
        return false;
    }
    else {
        return true;
    }
}

/* FAQ Form */
function checkfaqform(){
    var ftxt = '';
    
    if (document.faqform.Name.value==''){
        ftxt += '\n- Please enter your Name.';
    }
    
    if (document.faqform.Company.value==''){
        ftxt += '\n- Please enter your Company Name.';
    }
    
    if (isValidEmail(document.faqform.email.value)==false){
        ftxt += '\n- Please enter your Email Address.';
    }
    
    if (document.faqform.Question.value==''){
        ftxt += '\n- Please enter your Question.'
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

/* Application form - STEP 2 */
var appProviderArray = '';
function controlAppProviders(){
    appProviderArray = '';
    for (var i=0;i<document.applyform.ProviderCount.value;i++){
        var thisRow = false;        
        
        if (document.getElementById("Active"+(i+1)).value=='True'){
            // Enable Fields
            thisRow = false;
            if (appProviderArray!==''){
                appProviderArray += ',';
            }
            appProviderArray += (i+1);
        }
        else {
            // Disable Fields            
            thisRow = true;
        }
        
        document.getElementById("RiskCategory"+(i+1)).disabled=thisRow;
        document.getElementById("DateRegistered" + (i + 1)).disabled = thisRow;
        document.getElementById("DateofRating" + (i + 1)).disabled = thisRow;
        //document.getElementById("DateRatingReviewed"+(i+1)).disabled=thisRow;
        document.getElementById("StillRegistered" + (i + 1)).disabled = thisRow;
        document.getElementById("InDispute" + (i + 1)).disabled = thisRow;
        document.getElementById("ReasonforLeaving"+(i+1)).disabled=thisRow;
        //document.getElementById("DisputeCauseOther"+(i+1)).disabled=thisRow;
    }
    
    //alert(providerArray);
}

function controlAppWarrantyDispute(theVal, thePos) {
    var DisputeCause = document.getElementById("DisputeCause" + thePos);
    var DisputeCauseOther = document.getElementById("DisputeCauseOther" + thePos);

    var ReasonforLeaving = document.getElementById("ReasonforLeaving" + thePos);
    var InDispute = document.getElementById("InDispute" + thePos);

    if (ReasonforLeaving.value == 'In dispute') {
        InDispute.selectedIndex = 0;
    }

    if (theVal == 'True' || ReasonforLeaving.value == 'In dispute') {
        DisputeCause.disabled = false;
        DisputeCauseOther.disabled = false;
    }
    else {
        DisputeCause.disabled = true;
        DisputeCauseOther.disabled = true;
    }

    //alert(theVal);
}

function controlAppWarrantyCancel(theVal,thePos){
    var ReasonforLeaving = document.getElementById("ReasonforLeaving" + thePos);
    var DisputeCause = document.getElementById("DisputeCause" + thePos);
    
    if (theVal=='True'){
        ReasonforLeaving.disabled=true;
        //DisputeCause.disabled=true;
    }
    else {
        ReasonforLeaving.disabled=false;
        //DisputeCause.disabled=false;
    }
}


function controlStep2Claims(){
    var claimtext = document.getElementById("claimtext");
    var theval = document.applyform.WarrantyClaims.value;
    var claimupload = document.getElementById("claimupload");
    
    if (theval==''){
        claimtext.innerHTML = 'Please select an option from the list above to continue.';
        claimupload.style.display = 'none';
    }
    else {
        if (theval=='True'){
            claimtext.innerHTML = 'Please upload a statement of claims history from your previous warranty provider.';
            claimupload.style.display='block';
        }
        else {
            claimtext.innerHTML = 'Please upload a null statement of claims history from your previous warranty provider.';
            claimupload.style.display='block';
        }
    }
}

function checkapplysteptwo(){
    var ftxt = '';

    var wtxt = '';

    var ProviderCount = document.applyform.ProviderCount.value;
    var ProviderArray = document.applyform.ProviderArray.value;
    var Providers = ProviderArray.split(",");

    var today = new Date();

    //alert(today);
    
    for (i = 0; i < ProviderCount; i++) {
        var rowtext = '';
    
        if (document.getElementById("Active" + (i + 1)).value == 'True') {
            if (isDate(document.getElementById("DateRegistered" + (i + 1)).value) == false) {
                rowtext += '\n- Please enter a Date Registered.';
            }
            else {
                var dateregone = document.getElementById("DateRegistered" + (i + 1)).value;
                var datearrone = dateregone.split("/");
                var dateregistered = new Date(datearrone[1] + '/' + datearrone[0] + '/' + datearrone[2]);
            
                //var dateregistered = new Date();
                if (dateregistered > today) {
                    rowtext += '\n- Please ensure the Date Registered is not in the future.';
                }
            }

            if (isDate(document.getElementById("DateofRating" + (i + 1)).value) == false) {
                rowtext += '\n- Please enter a Date of Rating.';
            }
            else {
                var dateratone = document.getElementById("DateofRating" + (i + 1)).value;
                var dateratarrone = dateratone.split("/");
                var dateofrating = new Date(dateratarrone[1] + '/' + dateratarrone[0] + '/' + dateratarrone[2]);
            
                //var dateofrating = new Date(document.getElementById("DateofRating" + (i + 1)).value);
                if (dateofrating > today) {
                    rowtext += '\n- Please ensure the Date of Rating is not in the future.';
                    //alert(dateofrating);
                    //alert(today);
                }
            }

            /*
            if (isDate(document.getElementById("DateRatingReviewed" + (i + 1)).value) == false) {
                rowtext += '\n- Please enter a Date Rating Reviewed.';
            }
            else {
                var dateratingreviewed = new Date(document.getElementById("DateRatingReviewed" + (i + 1)).value);
                if (dateratingreviewed > today) {
                    rowtext += '\n- Please ensure the Date Rating Reviewed is not in the future.';
                }
            }
            */

            if (document.getElementById("StillRegistered" + (i + 1)).value == 'False' && document.getElementById("ReasonforLeaving" + (i + 1)).value == '') {
                rowtext += '\n- Please select your reason for leaving.';
            }

            if (document.getElementById("InDispute" + (i + 1)).value == 'True' && document.getElementById("DisputeCause" + (i + 1)).value == '') {
                rowtext += '\n- Please select your dispute main cause.';
            }
            else {
                if (document.getElementById("DisputeCause" + (i + 1)).value == 'Other' && document.getElementById("DisputeCauseOther" + (i + 1)).value == '') {
                    rowtext += '\n- Please enter the reason for your dispute.';
                }
            }

            if (rowtext !== '') {
                if (wtxt !== '') {
                    wtxt += '\n\n';
                }
                wtxt += '* ' + Providers[i] + ' *\n' + rowtext;
            }
        }
    }

    if (wtxt !== '') {
        if (ftxt !== '') {
            ftxt += '\n\n';
        }
        ftxt += '\n*** Current Warranty Providers ***\n\n' + wtxt;
    }

    var ptxt = '';
    
    if (document.applyform.WarrantyClaims.value==''){
        ptxt += '\n- Please select if you have had a Previous Claim?';
    }

    if (ptxt !== '') {
        if (ftxt !== '') {
            ftxt += '\n\n';
        }
        ftxt += '*** Any Previous Warranty Claims? ***\n' + ptxt;
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
	    //return false;
		return true;
	}
}

/* Application Form - Step 3 */
function checkapplystepthree(){
    var ftxt = '';
    
    if (document.applyform.EnableManagementPolicies.value=='True'){
        var typeInput = document.applyform.ManTypeArr.value;
        var typeArr = typeInput.split(",");
        var completedCount = 0;
        
        for (var i=0;i<typeArr.length;i++){
            if (eval('document.applyform.TypeID'+ typeArr[i] + '.value')!==''){
                completedCount += 1;
            }
        }
        
        if (completedCount<typeArr.length){
            ftxt += '\n- Please select an option for all ' + typeArr.length + ' Management Policy Options.';
        }
    }
    
    if (document.applyform.TechnicalCompetency.value=='True'){
        if (document.applyform.CharteredBuildingCompanyMember.value==''){
            ftxt += '\n- Please select if you have a Chartered Building Company Member.';
        }
        
        if (document.applyform.MasterBondMember.value==''){
            ftxt += '\n- Please select if you are a MasterBond Member.';
        }
        
        /* Tecnical Competency Questions - If no membership numbers supplied */
        if (document.applyform.TechQuestionsRequired.value=='True'){
            var QuestionsField = document.applyform.QuestionsArr.value;
            var QuestionsArr = QuestionsField.split(",");
            
            var questionCount = 0;
            for (var i=0;i<QuestionsArr.length;i++){
                if (eval('document.applyform.Question' + QuestionsArr[i] + '.value')!==''){
                    questionCount += 1;
                }
            }
            
            if (questionCount<QuestionsArr.length){
                ftxt += '\n- Please select an Answer for all ' + QuestionsArr.length + ' Questions.';
            }
        }
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

var charteredbuildingcompany = false;
var masterbond = false;

var membershipcount = 0;

var techcount = 0;
function controlStep3CharteredBuildingCompany(theval){
    var CharteredMembershipNumber = document.getElementById("CharteredMembershipNumber");
    
    if (theval=='True'){        
        charteredbuildingcompany = true;   
    }
    else if(theval=='False') {
        charteredbuildingcompany = false;
    }
}

function controlStep3MasterBond(theval){
    var MasterBondMemberNumber = document.getElementById("MasterBondMemberNumber");
    
    if (theval=='True'){
        masterbond = true;
    }
    else if (theval=='False') {
        masterbond = false;
    }
}
function controlStep3TechQuestions() {
    var OrgRaw = document.applyform.OrgArray.value;
    var OrgArray = OrgRaw.split(",");
    
    var otheranswered = false;
    for (var i = 0; i < OrgArray.length; i++) {
        if (eval('document.applyform.Membership' + OrgArray[i] + '.value') == 'True') {
            otheranswered = true;
        }
    }

    var showtaquestions = false;

    if (charteredbuildingcompany == false || masterbond == false || otheranswered == false) {
        showtaquestions = true;
    }
    else {
        showtaquestions = false;
    }

    var TechQuestions = document.getElementById("TechQuestions");

    if (showtaquestions) {
        TechQuestions.style.display='block';
        document.applyform.TechQuestionsRequired.value = 'True';
    }
    else {
        TechQuestions.style.display='none';
        document.applyform.TechQuestionsRequired.value = 'False';
    }
}

/* Application Form - Step 4 */
function checkapplystepfour(){
    if (document.applyform.EnableExperience.value=='True'){
        /*
        if (document.applyform.Related_Name1.value==''||document.applyform.Related_Experience1.value==''||document.applyform.Related_Years1.value==''){
            alert('Please enter at least one Director.');
            return false;
        }
        else {
            return true;
        }
        */
    }
    else {
        return true;
    }
}

/* Application Form - Step 5 */
function checkapplystepfive(){
    if (document.applyform.TermsAgreed.checked == false) {
        alert('Please agree to the Terms & Conditions.');
        return false;
    }
    else {
        return true;
    }
}

/* Application Form - Step 6 */
function checkapplystepsix() {
    if (document.applyform.DeclarationAgreed.checked == false) {
        alert('Please agree to the Terms & Conditions.');
        return false;
    }
    else {
        return true;
    }
}

/* Launch Centre Window */
var win = null;
function launchWindow(mypage, myname, w, h, features) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    if (winl < 0) winl = 0;
    if (wint < 0) wint = 0;
    var settings = 'height=' + h + ',';
    settings += 'width=' + w + ',';
    settings += 'top=' + wint + ',';
    settings += 'left=' + winl + ',';
    settings += features;
    win = window.open(mypage, myname, settings);
    win.window.focus();
}

/* Control Parent Company Block */
function controlParentCompany(theval) {
    var ParentCompanyArea = document.getElementById("ParentCompanyArea");

    if (theval == 'True') {
        ParentCompanyArea.style.display = 'block';
    }
    else {
        ParentCompanyArea.style.display = 'none';
    }
}

/* Control Associated Company Blcok */
function controlAssociateCompany(theval) {
    var AssociatedCompanyArea = document.getElementById("AssociatedCompanyArea");

    if (theval == 'True') {
        AssociatedCompanyArea.style.display = 'block';
    }
    else {
        AssociatedCompanyArea.style.display = 'none';
    }
}

/* Application D&B */
function controlExtraFields(theVal,theText) {
    var ExtraFields = document.getElementById("ExtraFields");

    if (theVal) {
        ExtraFields.style.display = 'block';
    }
    else {
        ExtraFields.style.display = 'none';
    }

    var ExtraFieldsAddressNotify = document.getElementById("ExtraFieldsAddressNotify");

    if (theText) {
        ExtraFieldsAddressNotify.style.display = 'block';
    }
    else {
        ExtraFieldsAddressNotify.style.display = 'none';
    }
}

function getDandBCompanies() {
    var addresslist = '';

    if (document.applyform.Mem_CompanyName.value == '' || document.applyform.Mem_Postcode.value == '') {
        alert('Please enter your Company Name and Postcode.');
        return false;
    //if (document.applyform.Mem_CompanyName.value == '') {
    //    alert('Please enter your Company Name.');
    //    return false;
	}
    else {    
        // Call - Get list of addresses
        try {
            // Moz supports XMLHttpRequest. IE uses ActiveX.
            // browser detction is bad. object detection works for any browser
            xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            // browser doesn't support ajax. handle however you want
        }

        xmlhttp.onreadystatechange = function() {
            if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
                //alert(xmlhttp.responseText);
                controlDandBCompanies(xmlhttp.responseText);
            }
        }

        xmlhttp.open("GET", 'DandB_Data/GetCompanies.asp?Company=' + document.applyform.Mem_CompanyName.value + '&Postcode=' + document.applyform.Mem_Postcode.value);
        xmlhttp.send(null);        

        return true;
    }
}

function populatDandBFields(theArr) {
    var theFields = theArr.split("|");

    if (theFields.length == 7) {        
        //John Smith Ltd|123 Road Street|Sutton Coldfield|Birmingham|B123 A12|0121 123 456|1234567      
        /*
        OLD FIELDS ARRAY
        document.applyform.Mem_Address1.value = theFields[1];
        document.applyform.Mem_Town.value = theFields[2];
        document.applyform.Mem_County.value = theFields[3];
        document.applyform.Mem_Telephone.value = theFields[5];
        */

        document.applyform.Mem_CompanyName.value = theFields[0];
        document.applyform.Mem_Address1.value = theFields[1];
        document.applyform.Mem_Town.value = theFields[2];
        document.applyform.Mem_County.value = theFields[3];
        document.applyform.Mem_Postcode.value = theFields[4];
        document.applyform.Mem_Telephone.value = theFields[5];
        document.applyform.Mem_DandBNumber.value = theFields[6];
    }
}

var addressLookupArray = new Array();
function controlDandBCompanies(addressArr) {
    // Response - List received
    // 0 Address = Show error (suggest to retry and link to manuall enter
    // 1 Address = Do not show list, auto-populate fields and show fields - populatDandBFields()
    // >1 Address = Show list and allow selection

    document.applyform.DandBAttempted.value = 'True';

    var NotFoundArea = document.getElementById("NotFoundArea");

    // Default
    document.getElementById("LookupArea").style.display = 'none';

    //addressArr
    var addressArray = addressArr.split("~");

    if (addressArray.length <= 0) {
        NotFoundArea.style.display = 'block';
        controlExtraFields(false,true);
    }
    else {
        if (addressArray.length == 1) {
            populatDandBFields(addressArray[0]);
            controlExtraFields(true,false);            
        }
        else {
            document.getElementById("LookupArea").style.display = 'block';

            var LookupEntries = document.getElementById("LookupEntries");
            var LookupText = '';

            // Set array to null
            //addressLookupArray = null;

            for (var i = 0; i < addressArray.length; i++) {
                var innerRaw = addressArray[i];
                var innerArray = innerRaw.split("|");

                if (innerArray.length == 7) {
                    // Set Array
                    addressLookupArray[i] = innerArray[0] + '|' + innerArray[1] + '|' + innerArray[2] + '|' + innerArray[3] + '|' + innerArray[4] + '|' + innerArray[5] + '|' + innerArray[6]
                    
                    // Set Text
                    LookupText += '<div class="addressitem" onclick="setDandBAddress('+ i +')"><strong>' + innerArray[0] + '</strong><br />' + innerArray[1] + ', ' + innerArray[2] + ', ' + innerArray[3] + ' ' + innerArray[4] + '</div>';
                }
            }

            LookupEntries.innerHTML = LookupText;
        }
    }
}

function setDandBAddress(arrayPos) {
    //alert(arrayPos);
    if (addressLookupArray.length >= (arrayPos + 1)) {
        var addressRaw = addressLookupArray[arrayPos];
        var addressLine = addressRaw.split("|");

        if (addressLine.length == 7) {
            document.applyform.Mem_CompanyName.value = addressLine[0];
            document.applyform.Mem_Address1.value = addressLine[1];
            document.applyform.Mem_Town.value = addressLine[2];
            document.applyform.Mem_County.value = addressLine[3];
            document.applyform.Mem_Postcode.value = addressLine[4];
            document.applyform.Mem_Telephone.value = addressLine[5];
            document.applyform.Mem_DandBNumber.value = addressLine[6];
			
			//2011-09-12 make company a disabled field
			//document.applyform.Mem_CompanyName.readOnly = true;
			document.applyform.Mem_CompanyName.disabled = true;
			document.applyform.Mem_CompanyName.style.borderStyle = "none";
        }
    }

    controlExtraFields(true,false);

    document.getElementById("LookupArea").style.display = 'none';
    //John Smith Ltd|123 Road Street|Sutton Coldfield|Birmingham|B123 A12|0121 123 456|1234567
}

/* Membership Options */
function controlMembershipOption() {
    var TheRaw = document.applyform.Mem_ApplicationFor.value;
    var TheArr = TheRaw.split("|");

    var MembershipTypeID = document.applyform.MembershipTypeID;

    if (TheArr.length == 2) {        
        if (TheArr[0] == 'ASSOCIATE') {
            MembershipTypeID.selectedIndex = 4;
        }
        else if (TheArr[0] == 'REGIONALOFFICE') {
            MembershipTypeID.selectedIndex = 3;
        }
        else {
            MembershipTypeID.selectedIndex = 0;
        }

        getPrice(document.applyform.MembershipTypeID.value) 
    }
}

/* PI System - Front-end */
function checkPIStepOne() {
    var ftxt = '';
    var ydetails = '';

    if (document.applyform.Mem_Title.value == '') {
        ydetails += '\n- Please enter your Title.';
    }

    if (document.applyform.Mem_FirstName.value == '') {
        ydetails += '\n- Please enter your First Name.';
    }

    if (document.applyform.Mem_LastName.value == '') {
        ydetails += '\n- Please enter your Surname.';
    }

    if (document.applyform.Mem_Position.value == '') {
        ydetails += '\n- Please enter your Position.';
    }

    if (document.applyform.Mem_MobileNumber.value == '') {
        ydetails += '\n- Please enter your Mobile Number.';
    }

    if (document.applyform.Mem_ApplicationFor.value == '') {
        ydetails += '\n- Please select the Type of Application.';
    }

    if (RequireHeadOfficeNumber) {
        if (document.applyform.Mem_HeadOfficeNo.value == '') {
            ydetails += '\n- Please enter your Head Office Membership No.';
        }
    }

    if (ydetails !== '') {
        ftxt += '\n** Your Details **\n' + ydetails;
    }

    var cdetails = '';

    if (document.applyform.Mem_CompanyName.value == '') {
        cdetails += '\n- Please enter your Company Name.';
    }

    if (document.applyform.DandBAttempted.value == '' || document.applyform.DandBAttempted.value == 'False') {
        cdetails += '\n- Please click on Get Address Details.';
    }

    if (document.applyform.Mem_Address1.value == '') {
        cdetails += '\n- Please enter your Address 1.';
    }

    if (document.applyform.Mem_Town.value == '') {
        cdetails += '\n- Please enter your Town/City.';
    }

    if (document.applyform.Mem_County.value == '') {
        cdetails += '\n- Please enter your County.';
    }

    if (document.applyform.Mem_Postcode.value == '') {
        cdetails += '\n- Please enter your Postcode.';
    }

    if (isDate(document.applyform.Mem_CompanyStarted.value) == false) {
        cdetails += '\n- Please enter a date of when your company was started.';
    }

    if (document.applyform.Mem_Telephone.value == '') {
        cdetails += '\n- Please enter your Telephone Number.';
    }

    if (isValidEmail(document.applyform.Mem_Email.value) == false) {
        cdetails += '\n- Please enter your Email Address.';
    }

    if (document.applyform.CompanyTypeID.value == '') {
        cdetails += '\n- Please select your Company Type.';
    }

    if (bRequireCompanyNumber) {
        if (document.applyform.Mem_CompanyNumber.value == '') {
            cdetails += '\n- Please enter your Registered Company Number.';
        }
    }

    if (document.applyform.ParentCompanyExists.value == '') {
        cdetails += '\n- Please select if you have a Parent Company.';
    }

    if (document.applyform.AssociatedCompanyExists.value == '') {
        cdetails += '\n- Please select if you have any Associated Companies?';
    }

    if (cdetails !== '') {
        if (ftxt !== '') {
            ftxt += '\n';
        }
        ftxt += '\n** Your Company Information **\n' + cdetails;
    }

    var pdetails = '';

    if (document.applyform.ParentCompanyExists.value == 'True') {
        if (document.applyform.Mem_ParentCompany.value == '') {
            pdetails += '\n- Please enter a Company Name.';
        }

        if (document.applyform.Mem_ParentAddress.value == '') {
            pdetails += '\n- Please enter an Address.';
        }

        if (document.applyform.Mem_ParentRegNumber.value == '') {
            pdetails += '\n- Please enter a Companies House Registration Number.';
        }

        if (pdetails !== '') {
            if (ftxt !== '') {
                ftxt += '\n';
            }
            ftxt += '\n** Ultimate/Global Parent Company Details **\n' + pdetails;
        }
    }

    var adetails = '';

    if (document.applyform.AssociatedCompanyExists.value == 'True') {
        if (adetails !== '') {
            if (ftxt !== '') {
                ftxt += '\n';
            }
            ftxt += '\n** Associated Company Details **\n' + adetails;
        }
    }

    if (ftxt !== '') {
        alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
        return false;
    }
    else {
        return true;
    }
}

//BELOW ADDED JULY 2011 //
function HideComingSoon() {
            document.getElementById('comingsoon').style.display = "none";
            document.cookie = "SeenPopUp=True";

}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function ChkComingSoon() {
            var ChkComing = getCookie("SeenPopUp");
            if (ChkComing == 'True') {
                        document.getElementById('comingsoon').style.display = "none";
            } else {
                        document.getElementById('comingsoon').style.display = "block";
            }
}

