$( document ).ready( function() {

	// menu show/hide active/clicked
	$( 'dl#nav li:has(ul):not(.active)' ).addClass( 'closed' ).find( 'ul:visible' ).hide();
	$( 'dl#nav li:has(ul:visible)' ).addClass( 'open' );
	$( 'dl#nav li:has(ul) > a, dl#nav li:has(ul) > span' ).click( function() {
		$( this ).siblings( 'ul:hidden' ).slideDown( 'fast' ).parent().removeClass( 'closed' ).addClass( 'open' ).siblings().find( ' > ul:visible' ).slideUp( 'fast' ).parent( 'li' ).removeClass( 'open' ).addClass( 'closed' );
		return false;
	});

	// external links
	$( 'a[@rel="external"]' ).addClass( 'external' ).attr( 'title', 'Visit web site - opens in a new window' ).click( function() {
		window.open( '/?out=' + this.href );
		return false;
	});

	$( 'a[@rel="mail"]' ).addClass( 'email' ).attr( 'title', 'Click to send an e-mail' ).click( function() {
		window.open( '/?out=' + this.href );
		return false;
	});

	// log-out confirm
	$( '#container 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;
		}
	});

	// product details image gallery
	$( 'a.thickbox' ).lightBox();

	// dev links
	$( 'a[@rel="dev"]' ).click( function() {
		window.open( this.href );
		return false;
	});

	// add form validation
	$( 'form.verify_form' ).submit( function() {
		return verifyForm( this );
	});

	// add verfiy link to siteseal alt img
	$( '#siteseal img' ).css( 'cursor', 'hand' ).click( function() {
		verifySeal();
	});

});

function verifySeal() {
	window.open( 'https://seal.godaddy.com:443/verifySeal?sealID=10669524710b9e63aa127118f2af8db917e4a0963762196445891741', 'SealVerfication', 'location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=460' );
}

function verifyForm( theForm ) {

	var c = document.getElementById( 'Country_Req' );
	postcodeNull( c );

	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 = parse( 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 ) {

			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 ) {

			var minChars = ( theForm.elements[ 'card_type' ].value == 'AMEX' ? 15 : 16 );

			if( theFld.value.length < minChars ) {
				alert( fldName + ' must contain at least ' + minChars + ' characters' );
				theFld.focus();
				return false;
			}
		}

		if( fldName.indexOf( 'Security' ) != -1 ) {

			var minChars = ( theForm.elements[ 'card_type' ].value == 'AMEX' ? 4 : 3 );

			if( theFld.value.length < minChars ) {
				alert( fldName + ' must contain at least ' + minChars + ' 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 Maestro/Solo' );
					cardIssue.focus();
					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' || c.value == 'Antarctica' ) ) {
		var p = document.getElementById( 'Postcode_Req' );
		if( p && p.value == '' ) {
			p.value = 'N/A';
		}
	}
}

function parse( str ){

	if( str == void( 0 ) || str == '' ) return '';
	if( isNaN( parseInt( str ) ) ) {
		return str.charAt( 0 ).toUpperCase() + str.substr( 1 ).toLowerCase();
	}
	else {
		return str;
	}
}

function convert( str ) {

	postcodeNull();

	name = str.name.toLowerCase();

	if( name.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( name.indexOf( 'card_number' ) != -1 || name.indexOf( 'card_Security' ) != -1 ) {

		str.value = str.value.replace( /[^0-9]*/g, '' );

	} else if( name.indexOf( 'telephone' ) != -1 || name.indexOf( 'other_number' ) != -1 ) {

		var replaceAlpha = str.value.replace( /([^.0-9-\+\(\)\s])/g, '' );
		str.value = normalizeString( replaceAlpha );

	} else if( name.indexOf( 'email' ) != -1 || name.indexOf( 'e-mail' ) != -1 ) {

		str.value = normalizeString( str.value.toLowerCase() );

	} else if( str.value != '' ) {

		var a = normalizeString( str.value ).split( /\s+/g );
		for( var i = 0; i < a.length; i ++ ) {
			var parts = a[ i ].match( /(\w)([\/'a-zA-Z0-9_-]*)/ );
			var firstLetter = parts[ 1 ].toUpperCase();
			var restOfWord = parts[ 2 ];
			a[ i ] = firstLetter + restOfWord;
		}
		str.value = a.join( ' ' );
	}
}

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;
	}
}
