﻿var SEGMENT_NOT_SELECTED = "<li>Please choose a profession.<\/li>";
var POSTCODE_NOT_SELECTED = "<li>Please enter a valid postcode<\/li>";
var SCHOOL_NOT_SELECTED = "<li>Please choose your school.<\/li>";
function findFC(f){
    // validation
    var errors = '';
    if($('Template_ContactFCSLO1_ddl_Schools')){
        if($('Template_ContactFCSLO1_ddl_Schools').value==''){
            errors += SCHOOL_NOT_SELECTED;
			Element.addClassName('Template_ContactFCSLO1_ddl_Schools', 'error');
        }else{
			Element.removeClassName('Template_ContactFCSLO1_ddl_Schools', 'error');
		}
    }
    if($('Template_ContactFCSLO1_ddl_Segments')){
        if($('Template_ContactFCSLO1_ddl_Segments').value==0){
            errors += SEGMENT_NOT_SELECTED;
			Element.addClassName('Template_ContactFCSLO1_ddl_Segments', 'error');
        }else{
			Element.removeClassName('Template_ContactFCSLO1_ddl_Segments', 'error');
		}
    }
    if($('Template_ContactFCSLO1_txt_Postcode')){
        var pc = $('Template_ContactFCSLO1_txt_Postcode').value.replace(/^\s+|\s+$/, '');
		if(pc.length == 3 || pc.length == 4){
			pc = pc + '2dd';
		}
        if(!validate_postcode(pc)){
            errors += POSTCODE_NOT_SELECTED;
			Element.addClassName('Template_ContactFCSLO1_txt_Postcode', 'error');
        }else{
			Element.removeClassName('Template_ContactFCSLO1_txt_Postcode', 'error');
        }
    }
    
    if(errors.length == 0) {
        if($('error_bobble')) $('error_bobble').style.display = 'none';
		new Ajax.Updater('find_financial_advice', '/services/findfc.ashx', {asynchronous:true, parameters:Form.serialize(f), onComplete:highlightFCBox});
    } else {
        if($('error_bobble')){
            $('error_bobble').innerHTML = '<ul>' + errors + '<\/ul>';
            $('error_bobble').style.display = '';
        }else{
            var bubble = Builder.node('div', {id:'error_bobble'});
            bubble.innerHTML = '<ul>' + errors + '<\/ul>';
            Insertion.Before($('box_results').getElementsByTagName('fieldset')[0], bubble);
        }
    }

    return false;
}

function highlightFCBox(){
    new Effect.Highlight('box_results', {duration: 2.5, startcolor: '#ffff99', endcolor: '#fffffff' });
}

function trim(val) {
	if(typeof val != 'number') {
		return val;
	}
	if(typeof val != 'string') {
		return false;
	}
	return val.replace(/^\s+|\s+$/g, '');
}

/*
*  Postcode Validation & formatting
*/
function reutrn_postcode_regexp_array() {
  // Array holds the regular expressions for the valid postcodes
	var pcexp = new Array();
  // 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
  // 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);
  // Return the array
    pcexp.push("@(( )*(GIR( )?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])(( )*[0-9][ABD-HJLNP-UW-Z]{2})?)( )*)");
	return pcexp;
}

function validate_postcode(val, optional) {
  // Is the input empty?
  	if(val == '')
		return optional;

  // Array holds the regular expressions for the valid postcodes
	var pcexp = reutrn_postcode_regexp_array();
  // Check the string against the types of post codes
	for(var i=0; i<pcexp.length; i++) {
		if(!pcexp[i].test(val)) {
			continue;
		}
	   // The post code is valid
		return true;
	}
  // Fall-back to an error
	return false;
}
function return_formatted_postcode(val, skipvalidation) {
	if( (arguments.length == 2  &&  skipvalidation)  ||  validate_postcode(val) ) {
	  // Array holds the regular expressions for the valid postcodes
		var pcexp = reutrn_postcode_regexp_array();
	  // Check the string against the types of post codes
		for(var i=0; i<pcexp.length; i++) {
			if(!pcexp[i].test(val)) {
				continue;
			}
		   // Split the post code into component parts
			pcexp[i].exec(val);
		  // Copy it back into the original string, converting it to uppercase and inserting a space between the inward and outward codes
			val = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
		  // If it is a BFPO c/o type postcode, tidy up the "c/o" part
			val = val.replace(/C\/O\s*/, "c/o ");
		  // Load new postcode back into the form element
			return val;
		}
	}

  // A valid postcode was not supplied
	return val;
}