﻿var SEGMENT_NOT_SELECTED ="<li>Please choose a profession.<\/li>";
var LOOKING_FOR_NOT_SELECTED = "<li>Please choose your school.<\/li>";
var POSTCODE_NOT_SELECTED = "<li>Please enter a valid postcode.<\/li>";
var res;

// box 1
Event.observe(window, 'load', function() {
    Event.observe('Template_ddl_AllSegments', 'change', getDDDetails);
    $('Template_btn_ChooseProfession').style.display='none';

    Event.observe('Template_ddl_Products', 'change', submitProduct);
    Element.addClassName('home_content_d2', 'jsOn');

    $('Template_ddl_AllSegments').options[0].selected = "1" ;
	if($('Template_ddl_Segments').value == ''){
	    $('Template_txt_Postcode').disabled = 'disabled';
	    $('Template_btn_Submit').disabled = 'disabled';
	}
    Event.observe('Template_ddl_Segments', 'change', enablePostcode);
});
function enablePostcode() {
	if($('Template_ddl_Segments').value != ''){
		$('Template_txt_Postcode').disabled = '';
		$('Template_btn_Submit').disabled = '';
	}else{
		$('Template_txt_Postcode').disabled = 'disabled';
		$('Template_btn_Submit').disabled = 'disabled';
	}
}
function submitProduct() {
    document.location.href = '/content/default.aspx?pageId=' + $('Template_ddl_Products').value ;
}
function getDDDetails(){
    res = new Ajax.Request('/content/services/productlookup.ashx?Template$ddl_AllSegments=' + $('Template_ddl_AllSegments').value, {onComplete: updateDD});
}
function updateDD(){
    var optionsXml = res.transport.responseXML.getElementsByTagName("option");
    var dropdownOptions = new Array();
    for(var i = 0; i < optionsXml.length; i++) {
        nameNodes = optionsXml[i].getElementsByTagName("name");
        valueNodes = optionsXml[i].getElementsByTagName("value");
        name = nameNodes[0].firstChild.nodeValue;
        value = valueNodes[0].firstChild.nodeValue;
        newOption = new Option(name, value);
        dropdownOptions.push(newOption);
    }
    $('Template_ddl_Products').options.length = 0;
    $('Template_ddl_Products').options[0] = (new Option("Please select", ""));
    dropdownOptions.each(
        function(element) {
            $('Template_ddl_Products').options[$('Template_ddl_Products').options.length] = element;
        }
    );
        
    $('Template_ddl_Products').disabled = false;
    $('Template_ddl_Products').focus = true;    
}

// box 2 - form submition
function homeFC(f, e){
    // validation
    var errors = '';

    // box 2 - postcode

    if($('Template_ddl_Segments').value==''){
        errors += SEGMENT_NOT_SELECTED;
		Element.addClassName('Template_ddl_Segments', 'error');
    }else{
		Element.removeClassName('Template_ddl_Segments', 'error');
	}
    var pc = $('Template_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_txt_Postcode', 'error');
    }else{
		Element.removeClassName('Template_txt_Postcode', 'error');
    }
    if(errors == '')
        return true;

    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($('home_content_d3').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
	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;
}

