$( document ).ready( function() {

	// hide all except active menu
	$( '#nav > li' ).not( '.active' ).find( '> a + ul, > span + ul' ).hide();

	// expand/collapse
	$( '#nav > li[ul] > a, #nav > li[ul] > span' ).click( function() {
		$( this ).find( '+ ul' ).slideToggle( 'fast' );
		return false;
	});

	// add form validation
	$( 'form.verify_form' ).submit( function() {
		return verifyForm( this );
	});

	// add form validation
	$( 'form.verify_form input' ).blur( function() {
		return convert( this );
	});

	// log-out confirm
	$( 'div#header div#user p a.logout' ).click( function() {
		var c = confirm( 'Are you sure you want to log-out?' );
		if( c ) {
			this.href = this.href + '?true';
		} else {
			return false;
		}
	});

	// dev/external links
	$( 'a[@rel="dev"],a[@rel="external"]' ).click( function() {
		return ! window.open( this.href );
	});

});

function verifyForm( theForm, total ) {

	postcodeNull();

	for( i = 0; i < theForm.elements.length; i ++ ) {

		var theFld = theForm.elements[ i ];
		var reqFld = ( theFld.id.indexOf( '_Req' ) != -1 ) ? true : false;
		var valSet = ( theFld.value == 0 || theFld.value == '' ) ? false : true;
		var fldChop = theFld.id.split( '_Req' );
		var fldName = fldChop[ 0 ].split( '_' ).join( ' ' );

		if( reqFld == true && ( valSet == false || ( theFld.type == 'checkbox' && theFld.checked == false ) ) ) {
			alert( fldName + ' cannot be left blank' );

			if( theFld.type == 'text' || theFld.type == 'textarea' ) {
				theFld.focus();
				theFld.select();
			} else {
				theFld.focus();
			}
			return false;
		}

		if( ( fldName.indexOf( 'Email' ) != -1 || fldName.indexOf( 'E-mail' ) != -1 ) && valSet ) {
			if( !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test( theFld.value )) {
				alert( fldName + ' \'' + theFld.value + '\' is not in a recognised format' );
				theFld.focus();
				theFld.select();
				return false;
			}
		}

		if( fldName.indexOf( 'Postcode' ) != -1 ) {

			var c = document.getElementById( 'Country_Req' );
			if( c && c.value == 'United Kingdom' && ! checkPostCode( theFld.value ) ) {
				alert( 'You must enter a full valid UK Postcode, including a space between the Outcode & Incode' );
				theFld.focus();
				theFld.select();
				return false;
			}
		}

		if( fldName.indexOf( 'Card Number' ) != -1 && theFld.value.length < 16 ) {
			alert( fldName + ' must contain at least 16 characters' );
			theFld.focus();
			return false;
		}

		if( fldName.indexOf( 'Card Type' ) != -1 ) {
			if( theFld.value.indexOf( 'Switch' ) != -1 || theFld.value.indexOf( 'Solo' ) != -1 ) {
				var cardIssue = theForm.elements[ 'card_issue_number' ];
				if( cardIssue.value == '' ) {
					alert( 'Issue Number must be completed when paying by Switch or Solo' );
					cardIssue.focus();
					return false;
				}
			}
		}
	}

	if( total ) {
		if( ! confirm( 'Confirm you wish to proceed with this order for: ' + total ) ) {
			return false;
		}
	}

	var btns = document.getElementsByTagName( 'input' );
	for( btn = 0; btn < btns.length; btn ++ ) {

		if( btns[ btn ].type == 'submit' ) {
			btns[ btn ].disabled = true;
			btns[ btn ].value = 'Sending...';
		}
	}
	return true;
}

function trim( str ) {
   return str.replace( /^\s*|\s*$/g, '' );
}

function postcodeNull( c ) {

	if( ! c ) {
		c = document.getElementById( 'Country_Req' );
	}

	if( c && ( c.value == 'Ireland' ) ) {
		var p = document.getElementById( 'Postcode_Req' );
		if( p && p.value == '' ) {
			p.value = 'N/A';
		}
	}
}

function convert( str ) {

	if( str.type == 'text' && str.name && str.value != '' ) {

		var fldName = str.name.toLowerCase();
		str.value = str.value.toLowerCase();

		if( fldName.indexOf( 'account_ref' ) != -1 ) {

			str.value = str.value.toUpperCase();

		} else if( fldName.indexOf( 'postcode' ) != -1 ) {

			var c = document.getElementById( 'Country_Req' );
			if( c && c.value == 'United Kingdom' ) {
				str.value = checkPostCode( str.value.toUpperCase(), true );
			} else {
				str.value = str.value.toUpperCase();
			}

		} else if( fldName.indexOf( 'email' ) != -1 || fldName.indexOf( 'e-mail' ) != -1 || fldName.indexOf( 'e_mail' ) != -1 || fldName.indexOf( 'web_address' ) != -1 ) {

			str.value = str.value.replace( /\s/g, '' );

		} else if( fldName.indexOf( 'telephone' ) != -1 || fldName.indexOf( 'other_number' ) != -1 ) {

			str.value = str.value.replace( /([^.0-9-extmob\+\(\)\s])/g, '' );

		} else {

			var a = str.value.split( /\s+/g );
			for( i = 0 ; i < a.length; i ++ ) {
				var word = a[ i ];
				if( word ) {
					word = word.replace( word.charAt( 0 ), word.charAt( 0 ).toUpperCase() );
					if( word.indexOf( '-' ) != -1 ) {
						var pos = ( word.lastIndexOf( '-' ) + 1 );
						word = word.replace( word.charAt( pos ), word.charAt( pos ).toUpperCase() );
					}
					if( word.indexOf( '(' ) != -1 ) {
						var pos = ( word.indexOf( '(' ) + 1 );
						word = word.replace( word.charAt( pos ), word.charAt( pos ).toUpperCase() );
					}
					if( word.charAt( 1 ) == '\'' ) {
						word = word.replace( word.charAt( 2 ), word.charAt( 2 ).toUpperCase() );
					}
					if( word.charAt( 0 ) == 'M' && word.charAt( 1 ) == 'c' ) {
						word = word.replace( word.charAt( 2 ), word.charAt( 2 ).toUpperCase() );
					}
					a[ i ] = word;
				}
			}
			str.value = a.join( ' ' );
		}
		str.value = normalizeString( str.value );
	}
}

function normalizeString( s ) {

	// Regular expressions for normalizing white space.
	var whtSpEnds = new RegExp( '^\\s*|\\s*$', 'g' );
	var whtSpMult = new RegExp( '\\s\\s+', 'g' );

	s = s.replace( whtSpMult, ' ' );  // Collapse any multiple whites space
	s = s.replace( whtSpEnds, '' );   // Remove leading or trailing white space

	return s;
}

function checkPostCode( toCheck, convert ) {

	// 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 );

	// specific over-rides to allow XX1 or XX2
	pcexp.push( /^(xx[12])$/i );

	// Load up the string to check
	var postCode = trim( 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 {
		if( convert ) {
			return postCode;
		} else {
			return false;
		}
	}
}

function clearSaved( path ) {

	var c = confirm( 'Are you sure you want to permanently remove this Saved Order?' );
	if( c ) {
		return window.location = path;
	} else {
		return false;
	}
}
