$( document ).ready( function() {

	// gallery images
	var w = $( '#prodImageCaption' ).html();
	$( 'div.extras div:first a' ).addClass( 'active' ).css( 'border: 1px solid #000' );
	$( 'div.extras div a' ).each( function() {

		var h = $( this ).attr( 'href' );
		var c = $( this ).attr( 'title' );

		$( this ).mouseover( function() {
			$( 'div.extras .active' ).removeClass( 'active' );
			$( this ).addClass( 'active' );
			$( '#prodImageCell img' ).attr( 'src', $( this ).attr( 'href' ) );
			if( c ) {
				$( '#prodImageCaption' ).html( c );
			}
		});
		$( this ).mouseout( function() {
			$( '#prodImageCaption' ).html( w );
		});
	});

	// product details image gallery
	$( '#content a.lightbox' ).lightBox();

	// media player controls
	$( '#content a.media' ).media();

	// external links
	$( '#content a[rel="external"]' ).attr( 'title', 'Visit website (Opens in a new window)' ).click( function() {
		return ! window.open( '/?out=' + this.href );
	});

	// dev links
	$( '#footer a[rel="dev"], #content a[rel="new"]' ).click( function() {
		return ! window.open( this.href );
	});

});

function recalculatePrice(option_id) {

	// Loop over all option select boxes and save current selection
	if ( typeof option_values[ option_id ] != "undefined" ) {
	currentSelection = new Array();
		for ( option_key in option_values[ option_id ] ) {
			var select = document.getElementById("select_"+option_id+"_"+option_key);
			// Get current selection
			if ( select.selectedIndex >= 0 ) {
				currentSelection[ option_id+"_"+option_key ] = select.options[select.selectedIndex].value;
			} else {
				currentSelection[ option_id+"_"+option_key ] = '0';
			}
		}
	}

	// Loop over all option select boxes and recreate them
	if ( typeof option_values[ option_id ] != "undefined" ) {
		for ( option_key in option_values[ option_id ] ) {
			var select = document.getElementById("select_"+option_id+"_"+option_key);
			// Get current selection
			var number = select.selectedIndex;
			// Delete all options
			select.options.length = 0;
			// Rebuild select box options
			var list = option_values[ option_id ][ option_key ];
			for(i=0; i<list.length; i+=2 ) {
				var price = '';
				if ( diffvalue[ list[i] ] != 0 ) {
					// If config set, show price difference in combo box
					if ( displayPriceDelta ) {
						price = ' [ ';
						price += diffvalue[ list[i] ] < 0 ? '-' : '+';
						if ( difftype[ list[i] ] != "%" ) {
							 price += "£" + Math.abs( diffvalue[ list[i] ] );
						} else {
							 price += Math.abs( diffvalue[ list[i] ] ) + "%";
						}
						price += ' ]';
					}
				}
				// Decide whether to show this option:
				var show = true; // always show by default...
				if ( deps[ list[ i ] ] ) {
					show = false; // ...unless it has a dependency set
					var depsArray = deps[ list[ i ] ];
					// get dependencies and loop over each
					if ( depsArray ) {
						for ( d in depsArray ) {
							// format: 1_2:2_1,£,1899,0
							var dep = depsArray[ d ].split(','); // separate dependency from outcomes
							var subs = dep[0].split(':') // get individual dependencies
							var found = 0;
							// Loop thro reqd individual dependencies and see if they are met
							for ( s in subs ) {
								for ( key in currentSelection ) {
									if ( "opt_" + option_id + "_" + subs[ s ]  == currentSelection[ key ] ) {
										found++;
										if ( found == subs.length ) {
											// All dependencies are met so display and change price differences
											show = true;
											difftype[ list[i] ] = dep[ 1 ];
											diffvalue[ list[i] ] = Number(dep[ 2 ]);
											if ( displayPriceDelta ) {
												if ( diffvalue[ list[i] ] != 0 ) {
													price = ' [ ';
													price += diffvalue[ list[i] ] < 0 ? '-' : '+';
													if ( difftype[ list[i] ] != "%" ) {
														price += "£" + Math.abs( diffvalue[ list[i] ] );
													} else {
														price += Math.abs( diffvalue[ list[i] ] ) + "%";
													}
													price += ' ]';
												}
											}
										}
									}
								}
							}
						}
					}
				}
				if ( show ) {
					// Add option to select box
					select.options[select.options.length] = new Option(list[i+1] + price, list[i]);
				}
			}

			// Try to set selection back to current settting
			if ( select.options.length > number ) {
				if ( number == -1 ) {
					select.selectedIndex = 0;
					currentSelection[ option_id + "_" + option_key ] = 0;
				} else {
					select.selectedIndex = number;
					currentSelection[ option_id + "_" + option_key ] = select.options[select.selectedIndex].value;
				}
			}
		}
	}

	// Recalculate prices
	var price = document.getElementById("price-"+option_id);
	var options = document.getElementById("price-options-"+option_id);
	if ( options ) {
		var selects = options.getElementsByTagName("select");
		var newprice = base_price[option_id];
		for (i=0; i<selects.length; i++) {
			if( selects[i].name != 'qty_' + option_id ) {
				if ( selects[i].selectedIndex >= 0 ) {
					var idx = selects[i].options[selects[i].selectedIndex].value;
					if ( difftype[idx] == "£" ) {
						newprice += diffvalue[idx];
					} else {
						multiplier = diffvalue[idx] / 100;
						newprice += base_price[option_id] * multiplier;
					}
				}
			}
		}

		// Discounts
		var oldprice = document.getElementById("old-price-"+option_id);
		if ( discounttype[option_id] ) {
			oldprice.innerHTML = "(Old Price: £"+newprice.toFixed(2)+")";
			if ( discounttype[option_id] == "0" ) {
			newprice = ( newprice - ( ( discountvalue[option_id] * newprice ) / 100 ) );
			} else {
			newprice = ( newprice - discountvalue[option_id] );
			}
			price.innerHTML = newprice.toFixed(2);
		} else {
			price.innerHTML = newprice.toFixed(2);
			oldprice.innerHTML = "";
		}
	}
}

function convert( str ) {

	postcodeNull();

	if( str.name.toLowerCase().indexOf( 'postcode' ) != -1 || str.id.toLowerCase().indexOf( 'postcode' ) != -1 ) {

		var c = document.getElementById( 'Country_Req' );

		if( c && c.value == 'United Kingdom' ) {
			str.value = checkPostCode( str.value, convert );
		} else {
			str.value = str.value.toUpperCase();
		}

	} else if( str.name.toLowerCase().indexOf( 'telephone' ) != -1 || str.name.toLowerCase().indexOf( 'other_number' ) != -1 ) {

		var replaceAlpha = str.value.replace( /([^.0-9-])/g, '' );
		str.value = replaceAlpha;

	} else if( str.name.toLowerCase().indexOf( 'email' ) != -1 ) {

		var eMailLowered = str.value.toLowerCase();
		str.value = eMailLowered;

	} else if( str.value != '' ) {

		var pattern = /(\w)([\/'a-zA-Z0-9_-]*)/;
		var a = str.value.split(/\s+/g);
		for( i = 0 ; i < a.length; i ++ ) {
			var parts = a[ i ].match( pattern );
			var firstLetter = parts[ 1 ].toUpperCase();
			var restOfWord = parts[ 2 ];
			a[ i ] = firstLetter + restOfWord;
		}
		str.value = a.join( ' ' );
	}
}

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 verifyForm( theForm, total ) {

	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 = 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( '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 || theFld.value.indexOf( 'MAESTRO' ) != -1 ) {
				var cardIssue = theForm.elements[ 'card_issue_number' ];
				if( cardIssue.value == '' ) {
					alert( 'Issue Number must be completed when paying by Maestro, 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 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 );

	// 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 false;
		} else {
			return postCode;
		}
	}
}

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;
	}
}

function mailTo( e, m ) {

	if( ! e ) var e = 'info';
	if( ! m ) var m = 'Enquiry via web site...';
	var d = 'bedexpert.co.uk';
	return '<a href="mailto:' + e + '@' + d + '?subject=Enquiry via web site..." title="' + m + '">' + e + '@' + d + '</a>';
}