function InitShippingKitAutoAdjusts()
{
	$( "#postal_code" ).change(

		function()
		{
			var currentPostalCode = $( this ).val();
			
			var pc = currentPostalCode.toUpperCase();

			var ereg = new RegExp( /[A-Z]+/gi );

			pc = pc.replace( / /g, "" );

			if( ereg.test( pc ) )
			{
				//postal code (K2K 3C4)
				var formattedPostalCode = pc.substr( 0, 3 ) + " " + pc.substr( 3, 3 );
			}
			else
			{
				//zip code (90210)
				var formattedPostalCode = pc;
			}

			$( this ).val( formattedPostalCode );
		}

	);

	$( "#email" ).change(

		function()
		{
			$( this ).val( $( this ).val().toLowerCase() );
		}

	);

	$( "#phone" ).change(

		function()
		{
			var currentPhone	= $( this ).val();

			var digitsOnly		= currentPhone.replace( /[^0-9]+/g, "" );
			var digitsLen		= digitsOnly.length;
			var p				= digitsOnly;

			if( digitsLen >= 11 )
			{
				var formattedPhone = p.substr( 0, 1 ) + " (" + p.substr( 1, 3 ) + ") " + p.substr( 4, 3 ) + "-" +  p.substr( 7, 4 );
			}
			else if( digitsLen > 7)
			{
				var formattedPhone = "(" + p.substr( 0, 3 ) + ") " + p.substr( 3, 3 ) + "-" +  p.substr( 6, 4 );
			}
			else if( digitsLen > 3 )
			{
				var formattedPhone = p.substr( 0, 3 ) + "-" + p.substr( 3, 4 );
			}
			else if( digitsLen > 0 )
			{
				var formattedPhone = p;
			}
			else if( digitsLen == 0 )
			{
				var formattedPhone = "";
			}

			$( this ).val( formattedPhone );
		}

	);

	$( "#first_name, #last_name, #address, #city, #province" ).change(

		function()
		{
			$( this ).val( $( this ).val().replace( /\w+/g,
				
				function( word )
				{
					return word.charAt( 0 ).toUpperCase() + word.substr( 1 ).toLowerCase();
				}

			) );
		}

	);

	$( "#country" ).change(

		function()
		{
			switch( $( this ).val() )
			{
				case "":
				case "Canada":

					$( "#shipping_kit div.customs_info" ).fadeOut( "fast" );
					$( "#shipping_kit div.customs" ).removeClass( "required" );

				break;

				case "United States":
				default:

					$( "#shipping_kit div.customs_info" ).fadeIn( "fast" );
					$( "#shipping_kit div.customs" ).addClass( "required" );

				break;
			}
		}

	);

	// global onchange

	$( "#first_name, #last_name, #email, #phone, #address, #city, #province, #postal_code, #country, #videotape, #film, #film_hd, #slides, #audio, #other, #notes, #customs" ).each(
		
		function( i )
		{
			var isCheckbox = $( this ).is( "[type='checkbox']" );

			$( this ).change(

				function()
				{
					if( isCheckbox )
					{
						var valueToStore = $( this ).is( ":checked" ) ? "1" : "0";
					}
					else
					{
						var valueToStore = $( this ).val();
					}

					CreateCookie( document, $( this ).attr( "id" ), valueToStore, "" );
				}

			);

			var storedValue = null;

			var getVariables = window.location.href.slice( window.location.href.indexOf( "?" ) + 1 ).split( "&" );

			for( var j = 0; j < getVariables.length; j++ )
			{
				var keyValuePair = getVariables[ j ].split( "=" );

				if( keyValuePair[ 0 ].toLowerCase() == $( this ).attr( "id" ).toLowerCase() )
				{
					storedValue = urldecode( keyValuePair[ 1 ] );
				}
			}

			if( storedValue == null )
			{
				storedValue = ReadCookie( document, $( this ).attr( "id" ) );
			}

			if( storedValue != null )
			{
				if( isCheckbox )
				{
					if( storedValue == "1" )
					{
						this.checked = true;
					}
				}
				else
				{
					$( this ).val( storedValue );
				}
			}
		}

	);

	$( "#shipping_kit_form" ).submit(

		function()
		{
			var eraseCookies = false;

			if( ValidateShippingKitForm() )
			{
				if( $( this ).data( "submitted" ) != "1" )
				{
					if( eraseCookies )
					{
						$( "#first_name, #last_name, #email, #phone, #address, #city, #province, #postal_code, #country, #videotape, #film, #film_hd, #slides, #audio, #other, #notes, #customs" ).each(

							function( i )
							{
								EraseCookie( document, $( this ).attr( "id" ) );
							}

						);
					}

					$( this ).data( "submitted", "1" );
				}

				return true;
			}
			else
			{
				return false;
			}
		}

	);

	$( "#shipping_kit div.customs_info" ).fadeOut( 1 );
	$( "#country" ).trigger( "change" );
}

function InitShippingKitForm()
{
	$( "#shipping_kit_form div.required" ).find( "input" ).each(

		function( i )
		{
			$( this ).keyup(

				function()
				{
					Validate( this, IsValid( this ) );
				}

			);
		}
	);

	$( "#shipping_kit_form div.required" ).find( "input[type='checkbox']" ).each(

		function( i )
		{
			$( this ).change(

				function()
				{
					Validate( this, GetSiblingAndSelfCheckCount( this ) > 0 );
				}

			);
		}
	);

	$( "#shipping_kit_form div.required" ).find( "select" ).each(

		function( i )
		{
			$( this ).change(

				function()
				{
					Validate( this, IsValid( this ) );
				}

			);
		}

	);
}

function Validate( thisObj, isValid )
{
	if( isValid )
	{
		ClearRequired( thisObj );
	}
	else
	{
		MakeRequired( thisObj );
	}
}

function ValidateShippingKitForm()
{
	var allValid = true;

	$( "#shipping_kit_form div.required" ).find( "input, select" ).each(

		function( i )
		{
			if( ! IsValid( this ) )
			{
				MakeRequired( this );

				allValid = false;
			}
		}

	);

	if( !allValid )
	{
		InitShippingKitForm();
	}

	returnValue = allValid;

	return returnValue;
}

function IsValid( thisObj )
{
	var isValid = true;

	if( $( thisObj ).is( "[name='email']" ) )
	{
		if( ! IsValidEmail( thisObj.value ) )
		{
			isValid = false;
		}
	}

	if( $( thisObj ).is( "[type='checkbox']" ) )
	{
		isValid = GetSiblingAndSelfCheckCount( thisObj ) > 0 ? true : false;
	}
	else
	{
		if( thisObj.value == "" || thisObj.selectedIndex == 0 )
		{
			isValid = false;
		}
	}

	var returnValue = isValid;

	return returnValue;
}

function GetSiblingAndSelfCheckCount( thisObj )
{
	var numCheck = 0;

	$( thisObj ).parent( "div.required" ).children( "input[type='checkbox']" ).each (

		function( j )
		{
			numCheck += $( this ).is( ":checked" ) ? 1 : 0;
		}

	);

	var returnValue = numCheck;

	return returnValue;
}

function MakeRequired( thisObj )
{
	$( thisObj ).parent( "div.required" ).addClass( "required_on" );
}

function ClearRequired( thisObj )
{
	$( thisObj ).parent( "div.required" ).removeClass( "required_on" );
}

function IsValidEmail( value )
{
	var ereg = new RegExp( "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$" );

	returnValue = ereg.test( value );

	return returnValue;
}

function CreateCookie( doc, name, value, days )
{
	if( days )
	{
		var date = new Date();
		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
		var expires = "; expires=" + date.toGMTString();
	}
	else
	{
		var expires = "";
	}

	doc.cookie = name + "=" + value + expires + "; path=/";
}

function ReadCookie( doc, name )
{
	var nameEQ = name + "=";
	var ca = doc.cookie.split( ';' );

	for( var i = 0; i < ca.length; i++ )
	{
		var c = ca[ i ];

		while( c.charAt(0) == ' ' )
		{
			c = c.substring( 1, c.length );
		}

		if( c.indexOf( nameEQ ) == 0 )
		{
			return c.substring( nameEQ.length, c.length );
		}
	}

	return null;
}

function EraseCookie( doc, name )
{
	CreateCookie( doc, name, "", -1 );
}

var listULs = Array();
var clickedUL;

function InitLeftNav()
{
	$( "div#hierarchy_nav" ).find( "div.button_toggle" ).each(

		function( i )
		{
			$( this ).click(

				function( i )
				{
					//find all ul's
					$( this ).parent().parent().parent().find( "ul" ).each( function( j ) { listULs[ j ] = $( this ); } );

					//find neighbouring ul only
					$( this ).parent().parent().find( "ul" ).each( function( j ) { clickedUL = $( this ); } );

					//toggle ul's
					for( var k = 0; k < listULs.length; k++ )
					{
						if( listULs[ k ].attr( "id" ) != clickedUL.attr( "id" ) )
						{
							listULs[ k ].slideUp();
							listULs[ k ].parent().find( "div.button_toggle" ).each( function( j ) { $( this ).addClass( "button_toggle_shut" ); } );
							
						}
						else
						{
							listULs[ k ].slideToggle();
							listULs[ k ].parent().find( "div.button_toggle" ).each( function( j ) { $( this ).toggleClass( "button_toggle_shut" ); } );
						}
					}
				}

			);
		}

	);
}

function ParseNav( navId )
{
	$( "div#" + navId ).find( "li" ).each(

		function( i )
		{
			$( this ).hover(

				function()
				{
					$( this ).addClass( "over" );
				},

				function()
				{
					$( this ).removeClass( "over" );
				}

			);
		}
	);
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

$( document ).ready(

	function()
	{
		ParseNav( "nav" );
		InitLeftNav();
		InitShippingKitAutoAdjusts();

		$( "a[rel=lightbox]" ).lightbox();
	}

);