//equalize heights plugin
(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) {
			tallest = maxHeight;
		}
		return this.each(function() {
			$(this).height(tallest).css("overflow","hidden");
		});
	};
	
})(jQuery);

var is_browser = {
	ios: function() {
		var agent = navigator.userAgent.toLowerCase();
		return (agent.match(/iPhone/i) == "iphone" || agent.match(/iPhone/i) == "ipad");
	},
	
	any_ie: function() {
		return $.browser.msie;
	},
	
	ie_v: function(what_version) {
		return ($.browser.msie && $.browser.version.substr(0,1) == what_version);
	}
};


var app = {
	initialise: function() {
		app.setup_ajax_callbacks();
		//app.log("app.initialise");
		common.initialise();
		homepage.initialise();
		product_options.initialise();
		product_gallery.initialise();
		ask_a_question.initialise();
		pay_page.initialise();
	},

	 setup_ajax_callbacks: function (){
		var loading = $('#loading');
		loading.hide();

		$('body').ajaxStart(function (){
			loading.show();
		});
		$('body').ajaxStop(function (){
			loading.fadeOut();
		});
		$('body').ajaxError(function (event, xhr, ajaxOptions, thrownError) {
			if (xhr.status === 401) {
				alert("Sorry, " + xhr.responseText.toLowerCase());
			}
		});
	},
	
	log: function(message) {
		if(typeof console != 'undefined'){
			console.log(message);
		}
	}

};


var common = {

	initialise: function() {
		//app.log("common.initialise");
	},
	
	set_overlay_size: function() {
		$('#overlay').height($(document).height());
		$('#overlay').width($(document).width());
	},
	
	load_cart_preview_page: function() {
		$('#cart_preview_page').load('/cart_items/preview');
	},
	
	open_cart_preview: function(and_update_cart) {
		homepage.pause_resume_slideshow();
		$('#cart_preview').removeClass('hidden');
		common.set_overlay_size();
		if(and_update_cart){
			common.load_cart_preview_page();
		}else{
			$('#cart_preview_page').text('Updating your cart...')
		}
		$('#overlay').fadeIn(300, function(){
			$('#view_cart_button').removeClass('on_bg');
			$.scrollTo(  {top:'105px', left:'0px'} , 500 );
			if(and_update_cart){
				common.update_cart_count();
			}
		});
		$('#crumb_list').fadeTo(300, 0.1);
	},
	
	close_cart_preview: function() {
		homepage.pause_resume_slideshow();
		$('#overlay').fadeOut(300, function(){
			$('#cart_preview').addClass('hidden');
			$('#view_cart_button').addClass('on_bg');
		});
		$('#crumb_list').fadeTo(300, 1);
	},
	
	hide_product_menu: function() {
		product_menu_is_showing = false;

		$('#product_menu li:not(#show_hide_products)').fadeOut(annoying_menu_animation_speed);

		$('#product_menu').animate({
		    height: '30px'
		}, annoying_menu_animation_speed, function(){
			$('#show_or_hide').text('Show');
		});

		annoying_menu_animation_speed = 750;
	},
	
	initialize_products_menu: function() {
		if($('#be_annoying').length > 0){
			annoying_menu_animation_speed = 750;
		}else{
			annoying_menu_animation_speed = 0;
		}

		if($('#info_menu li').hasClass('on')){

			product_menu_is_showing = false;

			$('#show_hide_products').removeClass('hidden');
			product_menu_original_height = $('#product_menu').height();
			$('#product_menu').css("height", product_menu_original_height + "px");
			common.hide_product_menu();
		}
	},
	
	show_product_menu: function() {
		product_menu_is_showing = true;

		$('#product_menu').animate({
		    height: product_menu_original_height + 'px'
		}, 750, function(){
			//done
			$('#show_or_hide').text('Hide');
		});

		$('#product_menu li:not(#show_hide_products)').fadeIn(750);
	},
	
	toggle_products_menu: function() {
		if(product_menu_is_showing){
			common.hide_product_menu();
		}else{
			common.show_product_menu();
		}
	},
	
	baseline_images: function() {
		$('#product_grid .image_holder img').each(function(index) {
			$(this).css('margin-top', ($(this).parent().height() - $(this).height() ) + 'px');
		});
	},
	
	load_map: function() {
		if($('#map').length > 0){
			if (GBrowserIsCompatible()) {
		        var map = new GMap2(document.getElementById("map"));
		        var point = new GLatLng(51.53644597302751, -0.10441303253173828);

		        map.setCenter(point, 13);
		        map.addControl(new GSmallMapControl());
		        map.addControl(new GMapTypeControl());
		        map.setMapType(G_NORMAL_MAP);

		        var marker = new GMarker(point);
		        var html = '<span id="map_bubble">Regulation Ltd.<br />17a St Albans Place,<br />Islington.<br />London,<br />N1 0NX</span>';
		        GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); });

		        map.addOverlay(marker);

		        //marker.openInfoWindowHtml(html);
		      }
		}
	},
	
	update_cart_count: function() {
		$('#cart_count_preview').load('/cart_items/cart_count');
	}
	
};






var homepage = {

	initialise: function() {
		//app.log("homepage.initialise");
	},
	
	initialize_slideshow: function() {
		current_side_number = 1;
		amount_of_slides = $('.slide').length;
		slideshow_interval = 5500;
		slideshow_paused = false;

		$('.slide').hide();
		$('#slide_' + current_side_number).show();
		var initial_width = $('#preview_slide_1').width();
		if(initial_width == 0){
			$('#preview_slide_1').width(237);
		}
		$('#slide_preview_bar').css("left", ('-' + $('#preview_slide_1').width() + 'px'));

		setInterval("homepage.advance_a_slide()", slideshow_interval);
	},
	
	advance_a_slide: function() {
		if(!(slideshow_paused) && $('#slideshow').length != 0){
			if(current_side_number > (amount_of_slides - 1)){
				next_slide_number = 1;
			}else{
				next_slide_number = (current_side_number + 1);
			}

			// main slides
			var current_slide = $('#slide_' + current_side_number);
			var next_slide = $('#slide_' + next_slide_number);

			var current_preview = $('#preview_slide_' + current_side_number);
			var next_preview = $('#preview_slide_' + next_slide_number);

			next_slide.css("z-index", "1");
			current_slide.css("z-index", "2");

			next_slide.show();
			current_slide.fadeOut();

			//move preview slides
			var preview_bar_starting_offset = current_preview.width();
			var preview_bar_left = $('#slide_preview_bar').position();
			preview_bar_left = preview_bar_left.left;
			var preview_bar_new_left = preview_bar_left - current_preview.width();
			//console.log(preview_bar_starting_offset);

			$('#slide_preview_bar').animate({
			    left: (preview_bar_new_left) + 'px'
			}, 1000, function(){
				var new_preview = current_preview.clone();
				$('#slide_preview_bar').append(new_preview);

				remove_id = "remove_me";
				current_preview.attr("id",remove_id);
				$('#' + remove_id).remove();

				$('#slide_preview_bar').css("left", (0 - preview_bar_starting_offset) + "px");

				//load next picture
				//alert(next_slide_number);
				var next_to_load = $('#slide_' + (next_slide_number + 1) + ' a img' );

				if(	next_to_load.attr('src') == "/images/space.gif"){
					next_to_load.attr('src',  next_to_load.attr('alt'));
				}

			});

			//advance current slide
			if(current_side_number > (amount_of_slides - 1)){
				current_side_number = 1;
			}else{
				current_side_number++;
			}
		}
	},
	
	pause_resume_slideshow: function() {
		slideshow_paused = !slideshow_paused;
	},
	
	load_popular_categories: function() {
		
		var homepage_footer_holder_top = $('#homepage_footer_holder').position();
		homepage_footer_holder_top = homepage_footer_holder_top.top;
		var window_element = $(window);
		
		if( (window_element.scrollTop() + window_element.height()) > homepage_footer_holder_top ){
			$(window).unbind('scroll');
			$('#homepage_footer_holder').load('/home_subcats_section');
		}
		
		$(window).scroll(function() {
			(window_element.scrollTop() + window_element.height());
			//app.log(homepage_footer_holder_top);
			
			if( (window_element.scrollTop() + window_element.height()) > homepage_footer_holder_top ){
				$(window).unbind('scroll');
				$('#homepage_footer_holder').load('/home_subcats_section');
			}
			
		});
		
	}
	
	
};


var product_options = {

	initialise: function() {
		//app.log("product_options.initialise");
	},
	
	update_prices: function() {
		running_add_to_price = 0;
		initial_price = $('#initial_price').val();

		$('#add_form select').each(function(index) {
			//update the options with its name and its add or subtract...
			$(this).each(function(index) {

				//get selected id
				var selected_id = "";
				var selected_price = 0;
				$('option:selected', this).each(function(index) {
					selected_id = $(this).val();
					selected_price = parseFloat($('#add_option_price_' + selected_id).val());
				});


				$('option', this).each(function(index) {
					//update text on options
					if($(this).val() != "default_option"){

						var this_id = $(this).val();

						var option_price = $('#add_option_price_' + this_id).val();
						var option_name = $('#add_option_name_' + this_id).val();

						if(isNaN(selected_price)){

							if(option_price == 0){
								$(this).text(option_name);
							}else{
								$(this).text(option_name + " (add £" + option_price + ") " );
							}						
						}else{
							var adjustment_price = parseFloat(option_price) - parseFloat(selected_price);

							if(adjustment_price == 0){
								$(this).text(option_name);
							}

							if(adjustment_price > 0){
								$(this).text(option_name + " (add £" + adjustment_price.toFixed(2) + ") "  );
							}

							if(adjustment_price < 0){
								$(this).text(option_name + " (subtract £" + (adjustment_price * -1).toFixed(2) + ") "  );
							}

						}
					}
		        });

				//add selected id price to running price
				if($('#add_option_price_' + selected_id).length > 0){
					running_add_to_price = parseFloat(running_add_to_price) + parseFloat($('#add_option_price_' + selected_id).val());
				}

			});

		});

		var new_price = parseFloat(running_add_to_price) + parseFloat(initial_price);
		new_price = new_price.toFixed(2);

		//animate_price_change_on_product
		var price_animate_speed = 'fast';

		if(!(animate_price_change_on_product)){
			price_animate_speed = 0;
		}


		if(first_load_for_price){
			$('#the_price').html(product_options.total_price_sale_inflection(new_price));
			first_load_for_price = false;
		}else{
			$('#the_price').fadeOut(price_animate_speed, function() {
				$('#the_price').html(product_options.total_price_sale_inflection(new_price));
				$('#the_price').fadeIn(price_animate_speed);
			});
		}
		
		//sale inflection
		

	},
	
	total_price_sale_inflection: function(start_price) {
		var inflected_price = start_price;
		
		if(start_price == 0){
			inflected_price = '<span id="please_select">Select options<Br /> to calculate price</span>';
		}else{
			
			if( $('#sale_amount').length > 0 ){				
				inflected_price = '<span id="was_price"><del>£' + start_price + '</del></span>£' + product_options.get_sale_amount(start_price);
			}else{
				inflected_price = '£' + start_price	
			}
		}
		
		return inflected_price;
	},
	
	get_sale_amount: function(start_price){				
		var was_price = start_price;
		var sale_price = 0;
		var sale_amount = $('#sale_amount').val();
	
		if($('#sale_type').val() == "percent" ){
			sale_price = product_options.sale_percent(was_price, sale_amount);
		}
	
		if($('#sale_type').val() == "pounds" ){
			sale_price = product_options.sale_pounds(was_price, sale_amount);
		}
	
		sale_price = sale_price.toFixed(2);
		
		return sale_price;	
	},
	
	sale_percent: function(amount, percent_off) {
		return (amount * (1 - percent_off / 100));
	},
	
	sale_pounds: function(amount, pounds_off) {
		return (amount - pounds_off);
	},
	
	validate_adding_form_options: function() {
		$(".required_container").each(function(index) {
			if($(this).find('select').val() == "default_option"){
				$(this).find('.possibly_required_box').addClass('required_box');
				adding_form_is_valid = false;
			}
		});
	},
	
	validate_single_form_option: function(single_form_option) {
		var required_container = single_form_option.parent().parent();

		if(single_form_option.val() == "default_option"){
			required_container.find('.possibly_required_box').addClass('required_box');
			adding_form_is_valid = false;
		}else{
			required_container.find('.possibly_required_box').removeClass('required_box');
			adding_form_is_valid = true;
		}
		
	}
	
};







var product_gallery = {

	initialise: function() {
		//app.log("product_gallery.initialise");
	},
	
	initialize_product_gallery: function() {
		var first_image_height = 200;

		$('#current_image a').each(function(index, value){
			if(index > 0){
				$(this).hide();
			}else{
				first_image_height = $(this).find('img').height() + 4;
			}
		});

		$('#current_image').css('height', (first_image_height +  'px'));
	},
	
	update_current_image: function(preview_clicked_index, image_href) {
		var new_image_height = 0;

		$('#current_image a:eq('+preview_clicked_index+') img').attr("src",image_href);

		$('#current_image .current').removeClass('current').fadeOut('fast',function(){

			$('#current_image a:eq('+preview_clicked_index+')').fadeIn('fast');

			new_image_height = $('#current_image a:eq('+preview_clicked_index+') img').height();

			if(new_image_height > 100){
				$('#current_image').animate({
				    height: (new_image_height + 4)
				}, 200);
			}
		});

		$('#current_image a:eq('+preview_clicked_index+')').addClass('current');
	},
	
	gallery_image_load_compeate: function(start_width, start_height, start_x, start_y) {
		$('#fastlook_box').removeClass('hidden');

		$('#overlay').fadeIn(300, function(){
		});
	},
	
	fastlook_image: function(image_href, start_width, start_height, start_x, start_y) {
		var img = new Image();
	    $(img).load(function () {
			$('#fastlook_box').empty();
			$(this).hide(); 
			$('#fastlook_box').append(this);
			$('#fastlook_box img').wrap('<div id="image_wrapper" />');
			$('#fastlook_box #image_wrapper').append('<span id="fastlook_close"></span>');
			$(this).fadeIn(300);
			}, product_gallery.gallery_image_load_compeate(start_width, start_height, start_x, start_y)
		).error(function () {
	    }).attr('src', image_href);

		$.scrollTo(  {top:'30px', left:'0px'} , 500 );
	},
	
	close_previewed_image: function() {
		$('#overlay').fadeOut(300);

		$('#fastlook_box img').fadeOut(300, function(){
			$('#fastlook_box').addClass('hidden');
		});
	}
	
}



var ask_a_question = {

	initialise: function() {
		//app.log("ask_a_question.initialise");
	},
	
	validate_email: function(emailAddress) {
		var pattern = new RegExp(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i);
		return pattern.test(emailAddress);
	},
	
	validate_ask_question: function() {
		ask_question_form_is_valid = true;

		if($('#ContactQuestionQuestion').val() == ""){
			ask_question_form_is_valid = false;
			$('#ContactQuestionQuestion').parent().addClass('error');
		}else{
			$('#ContactQuestionQuestion').parent().removeClass('error');
		}


		if( !(ask_a_question.validate_email( $('#ContactQuestionEmail').val() ))   ){
			ask_question_form_is_valid = false;
			$('#ContactQuestionEmail').parent().addClass('error');
		}else{
			$('#ContactQuestionEmail').parent().removeClass('error');
		}
	},
	
	close_and_finish: function() {
		$('#ask_question_form').slideUp(700, function(){
			$('#ask_question_form').remove();
			$('#ask_a_question_link').html('<img alt="&lt;-" src="/images/tick.png">Thanks, question asked.');
			$('#ask_a_question_link').append('<span class="note">Your question will be read by a member of staff shortly and someone should get back to you.</span>');
			$('#ask_a_question').addClass('asked');
		});
	}
	
}








var pay_page = {

	initialise: function() {
		//app.log("pay_page.initialise");
	},
	
	update_card_type_fields: function() {
		
		var cart_type_selected = $('#OrderCardType').val();

		if(cart_type_selected == "MasterCard" || cart_type_selected == "Visa/Delta/Electron" || cart_type_selected == "American Express" || cart_type_selected == "Solo/Maestro"){
			$('#OrderCardNumber').parent().slideDown();
			$('#OrderEndDateMonth').parent().slideDown();
			$('#OrderSecurityNumber').parent().slideDown();
		}	

		if(cart_type_selected == "MasterCard" || cart_type_selected == "Visa/Delta/Electron"){
			$('#OrderIssueNumber').parent().slideUp();
			$('#OrderStartDateMonth').parent().slideDown();
		}

		if(cart_type_selected == "American Express"){
			$('#OrderIssueNumber').parent().slideUp();
			$('#OrderStartDateMonth').parent().slideUp();
		}

		if(cart_type_selected == "Solo/Maestro"){
			$('#OrderIssueNumber').parent().slideDown();
			$('#OrderStartDateMonth').parent().slideDown();
		}

		if(cart_type_selected == ""){
			$('#OrderIssueNumber').parent().slideUp();
			$('#OrderStartDateMonth').parent().slideUp();
			$('#OrderCardNumber').parent().slideUp();
			$('#OrderEndDateMonth').parent().slideUp();
			$('#OrderSecurityNumber').parent().slideUp();
		}

		$('#OrderAddForm .form_note').fadeOut(0);

	},
	
	address_checked_check: function() {
		if( $('#OrderUseBaAsSa:checked').length > 0 ){
			$('#shipping_address_area').slideUp();
		}else{
			$('#shipping_address_area').slideDown();
		}
	}
	
}





var video_player = {
	initialise: function() {
		//globals
		delay_play_interval = [];
		to_play = [];
		
		//locals
		var mp3_height = 24;
		var video_height = 336;
		
		//close box
		$('#close_video_box').click(function(){
			$('#overlay').fadeOut(333);
			$('#vac_rac_player_holder').hide();
			homepage.pause_resume_slideshow();
			video_player.try_to_pause_all();
			return false;
		});
		
		//bind video popup links
		var video_player_divs = $('.video_player_holder');
		
		$('.video_box a').each(function(index, item){
			var link = $(this);
			var url = link.attr('href');
				link.click(function(){
					
					
					if( link.parent().attr('id') == "shop_video_box" ){
						$('#vac_rac_player h1').text('Retail Shop');
					}
					$('#vac_rac_player .button').hide();
					
					if( is_browser.ios() ){
						return true;
					}
					
					video_player.try_to_pause_all();
				
					$.scrollTo(0, 333);
					$('#vac_rac_player_holder').show();
					$('#overlay').fadeIn(333);
					homepage.pause_resume_slideshow();
					//return false;
				
					//overlay.open();
					var video_holder = $('#overlay_video');
					var index_id = '_id' + 'blah';
					var is_mp3 = (url.indexOf(".mp3") != -1);
					if(is_mp3){ var height = mp3_height; }else{ var height = video_height; }
					video_player.load_video(video_holder, (index + video_player_divs.length), index_id, url, height);
					return false;
				});
		});
		
		if( $('#play_video').length > 0 ){
			var index = 0;
			var link = $('#shop_video_box a');
			var url = link.attr('href');
				
			$.scrollTo(0, 333);
			$('#vac_rac_player_holder').show();
			$('#overlay').fadeIn(333);
			//homepage.pause_resume_slideshow();
			//return false;
		
			//overlay.open();
			var video_holder = $('#overlay_video');
			var index_id = '_id' + 'blah';
			var is_mp3 = (url.indexOf(".mp3") != -1);
			if(is_mp3){ var height = mp3_height; }else{ var height = video_height; }
			video_player.load_video(video_holder, (index + video_player_divs.length), index_id, url, height);
		}
		
	},
	
	load_video: function(video_holder, index, index_id, video_url, video_height) {
		//add new player
		video_holder.html(video_player.new_player_html(index_id, video_url, video_height));
		//autoplay
		delay_play_interval[index] = setInterval(function() { video_player.play_when_playable(index_id, index); } , 200);
	},
	
	new_player_html: function(index_id, video_url, height) {
		return '<object id="player_ie'+index_id+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player_ie'+index_id+'" width="608" height="'+height+'"><param name="movie" value="/swfs/player.swf" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="flashvars" value="file='+video_url+'" /><embed type="application/x-shockwave-flash" id="player2_nonie'+index_id+'" name="player2_nonie'+index_id+'" src="/swfs/player.swf" width="608" height="'+height+'" allowscriptaccess="always" allowfullscreen="true" flashvars="file='+video_url+'" /></object>';
	},
	
	play_when_playable: function(index_id, index) {
		if( is_browser.any_ie() ){
			var player_id = "player_ie" + index_id;
		}else{
			var player_id = "player2_nonie" + index_id;
		}

		to_play[index] = document.getElementById(player_id);

		if(typeof to_play[index].sendEvent == "function") {
			video_player.try_to_pause_all(index);
			clearInterval(delay_play_interval[index]);
			to_play[index].sendEvent('PLAY');
		}
	},
	
	try_to_pause_all: function(current_index) {
		$.each(to_play, function(index, value) {
			if(value != undefined && current_index != index && (typeof to_play[index].sendEvent == "function")){
				to_play[index].sendEvent('PLAY', false);
			}
		});
	}	
};




$(document).ready(function(){
	
	app.initialise();
	
	first_load_for_price = true;
	animate_price_change_on_product = true;
	
	annoying_menu_animation_speed = 750;
	
	ask_question_form_is_valid = true;
	
	//initialization
	common.set_overlay_size();
	common.initialize_products_menu();
	
	//order form keyup
	$('#OrderName').blur(function(){
		if($('#OrderSaName').val() == ""){
			$('#OrderSaName').val($(this).val());
		}
	});
		
	//ask q form slideup
	$('#ask_question_form').slideUp(0);
	
	$('#ask_a_question_link a',this).bind({
		click: function() {
			$('#ask_question_form').slideToggle(600, function(){
				$.scrollTo(  $('#ask_a_question') , 500 );
				
				$('#ContactQuestionEmail').focus();
				
				$('#click_to_ask').toggle(0);
				$('#ask_a_question_text').toggle(0);
				
			});
			return false;
		}
	});
	
	
	$('.radio_update').click(function(){
		var location = $(this).parent().find('a').attr('href');
		window.location = location;
	});
	
	//product adding form
	$('#ContactQuestionAddForm').submit(function() {
		$('#ContactQuestionAddForm .submit input').val('Submitting...');
		ask_a_question.validate_ask_question();
		
		if(ask_question_form_is_valid){
			
			var dataString = $(this).serialize();
			
			$.ajax({
			    type: "POST",
			    url: "/contact_questions/add",
			    data: dataString,
			    success: function() {
					$('#ContactQuestionAddForm .submit input').val('Done');
					ask_a_question.close_and_finish();
			    }
			  });
		}else{
			$('#ContactQuestionAddForm .submit input').val('Ask Question');
		}

		return false;
	});
	
	
	if($('#view_product').length > 0){
		product_options.update_prices();
	}

	//bind handelers
	$('#your_cart_button .button',this).bind({
		click: function() {
			common.open_cart_preview(true);
			return false;
		}
	});
	
	$('#view_cart_button',this).bind({
		click: function() {
			common.close_cart_preview();
			return false;
		}
	});
	
	$('#continue_shopping').live('click', function() {
		common.close_cart_preview();
		return false;
	});
	
	$('#better_get_shopping_close').live('click', function() {
		common.close_cart_preview();
		return false;
	});
	
	$('#overlay',this).bind({
		click: function() {
			common.close_cart_preview();
			return false;
		}
	});
	
	$('#fastlook_box',this).bind({
		click: function() {
			product_gallery.close_previewed_image();
			return false;
		}
	});
	
	$('#show_hide_products',this).bind({
		click: function() {
			common.toggle_products_menu();
			return false;
		}
	});
	
	$('#add_form select',this).bind({
		change: function() {			
			animate_price_change_on_product = true;
			if($('#add_option_price_' + $(this).val() ).val() == 0){
				animate_price_change_on_product = false;
			}			
			product_options.update_prices();
			
			if($(this).parent().parent().hasClass('required_container')){
				product_options.validate_single_form_option($(this));
			}
		}
	});
	
	
	/* sort by */
	if($('#filter_menu').length > 0){
		
		$(document).click(function() {
			$('#filter_menu').addClass('hidden');
		});

		$("#sort_by").click(function(e) {
			e.stopPropagation();
		});

		$('#sort_by a').bind({
			click: function() {	
				$('#filter_menu').removeClass('hidden');
				return false;
			}
		});

		$('#filter_menu a').bind({
			click: function() {	
				$('#filter_menu').addClass('hidden');
			}
		});
		
	}
	
	
	$('#search_box').bind({
		focus: function() {
			if($(this).val() == 'Search Regulation'){
				$(this).val('');
			}
		},
		blur: function() {
			if($(this).val() == "" ){
				$(this).val('Search Regulation');
			}
		}
	});
	
	$('#search_form').submit(function(){
		if($('#search_box').val() == "Search Regulation" || $('#search_box').val() == ""){
			$('#search_box').focus();
			return false;
		}
	});
	
	adding_form_is_valid = true;
	
	//product adding form
	$('#add_form').submit(function() {
		$('#add_button').val('Adding...');
		$('#add_button').attr('disabled', 'disabled');
		//disable button
		
		product_options.validate_adding_form_options();
		//if 0 in qty
		if($('#qty').val() == 0){
			$('#qty').val(1);
		}
		
		if(adding_form_is_valid){
			
			var dataString = $(this).serialize();
			common.open_cart_preview(false);
			
			$.ajax({
			    type: "POST",
			    url: "/cart_items/add",
			    data: dataString,
			    success: function() {
					$('#add_button').val('+ Add to Cart');
					common.open_cart_preview(true);
					$('#add_button').removeAttr("disabled"); 
			    }
			  });
		}else{
			$('#add_button').val('+ Add to Cart');
			$('#add_button').removeAttr("disabled");
		}

		return false;
	});

	
	
	//flash slideup
	$('#flashMessage').append('<a href="#" class="close" >&nbsp;</a>');
	$('#flashMessage .close').live('click', function(){
		$(this).parent().slideUp();
		return false;
	});
	
	//hide no-animate hiding
	$('#OrderIssueNumber').parent().hide();
	$('#OrderStartDateMonth').parent().hide();
	$('#OrderCardNumber').parent().hide();
	$('#OrderEndDateMonth').parent().hide();
	$('#OrderSecurityNumber').parent().hide();
	
	pay_page.update_card_type_fields();
	pay_page.address_checked_check();
	//enter card details stuff
	$('#OrderCardType').change( function() {
		pay_page.update_card_type_fields();
		$('#OrderCardNumber').focus();
	});
	
	$('#OrderUseBaAsSa').change( function() {
		pay_page.address_checked_check();
	});
	
	
	//order form popups
	$('#OrderAddForm .form_note').fadeOut(0);	
	
	$('#OrderAddForm input',this).bind({
		focus: function() {
			$(this).parent().find('.form_note').fadeIn();
			
			var input_position = $(this).position();
						
			var callout_left = (input_position.left + $(this).width() + 20);
						
			$(this).parent().find('.form_note').css('left', (callout_left + 'px') );
		},
		blur: function() {
			$(this).parent().find('.form_note').fadeOut();
		}
	});
	
	$('#OrderAddForm select',this).bind({
		focus: function() {
			$(this).parent().find('.form_note').fadeIn();
			
			var input_position = $(this).position();
						
			var callout_left = (input_position.left + $(this).width() + 20);
						
			$(this).parent().find('.form_note').css('left', (callout_left + 'px') );
		},
		blur: function() {
			$(this).parent().find('.form_note').fadeOut();
		}
	});
	
	$('#OrderAddForm textarea',this).bind({
		focus: function() {
			$(this).parent().find('.form_note').fadeIn();
			
			var input_position = $(this).position();
						
			var callout_left = (input_position.left + $(this).width() + 20);
						
			$(this).parent().find('.form_note').css('left', (callout_left + 'px') );
		},
		blur: function() {
			$(this).parent().find('.form_note').fadeOut();
		}
	});
	
	
	if ($.browser.webkit) {
		$('#cart_arrow').css('top', '40px');
	}
	
	$('#OrderAddForm .submit input').removeAttr("disabled"); 
	$('#OrderAddForm .submit input').width($('#OrderAddForm .submit input').width() + 10);
	
	$('#OrderAddForm').submit(function(){
	    $('#OrderAddForm .submit input').attr('disabled', 'disabled');
		$('#OrderAddForm .submit input').fadeTo(0, 0.8);
		$('#OrderAddForm .submit input').val('Submitting...')
	});
	
	//here you are
	$('#cart_preview_page .remove').live('click', function() {
		$('#preview_totals').html('<li>Recalculating...</li>');
		$(this).load($(this).attr('href'), function(){
			$(this).parent().parent().fadeOut(500, function(){
				common.load_cart_preview_page();
				common.update_cart_count();
			});
		});		
		return false;
	});
	
	$('#ContactQuestionOther').parent().hide();
	
	
	$('#ajax_email_subscribe_error').hide();
	$('#SubscriberAddForm').submit(function () {
		
		
		if( !(ask_a_question.validate_email( $('#SubscriberEmail').val() ))   ){
			$('#ajax_email_subscribe_error').hide();
			$('#SubscriberAddForm .error-message').hide();
			$('#ajax_email_subscribe_error').show();
			$('#SubscriberEmail').focus();
			return false;
		}else{
			$('#ajax_email_subscribe_error').hide();
			$('#SubscriberAddForm .error-message').hide();
		}
		
	});

	video_player.initialise();
	
});

$(window).load(function(){
	
	//initialization
	homepage.initialize_slideshow();
	
	//equalize cols
	$('#homepage_footer .a_column').equalHeights();	
	
	$('#product_grid .product_line_break').each(function(index) {
		$('#product_grid .image_holder_' + (index + 1) ).equalHeights();
		$('#product_grid .line_' + (index + 1) ).equalHeights();		
		$('#product_grid .price_' + (index + 1) ).equalHeights();		
	});
	
	$('#product_grid .price').each(function(index) {
		if($(this).height() > 30 && !$(this).hasClass('on_sale')){			
			$(this).html('<Br/>' + $(this).html())
		}
	});
	
	//this puts each product preview image on select a product page at the bottom of their div
	common.baseline_images();
	
	//gallery stuff
	product_gallery.initialize_product_gallery();
	
	$('#gallery #previews a').each(function(index, value){
		$(this).bind({
			click: function() {
				if(!($(this).parent().hasClass('on'))){
					$('#gallery #previews a').parent().removeClass('on');
					$(this).parent().addClass('on');
					product_gallery.update_current_image(index, $(this).attr('href'));
				}
				return false;
			}
		});
	});
	
	$('#gallery #current_image a').bind({
		click: function() {	
			var inner_image = $('img', this);
			var image_offset = inner_image.offset();
			product_gallery.fastlook_image($(this).attr('href'), inner_image.width(), inner_image.height(), image_offset.top, image_offset.left);
			return false;
		}
	});
	
	$('#place_order .error-message').each(function(index) {		
		$(this).text('↑ ' + $(this).text());
	});
	
	common.load_map();
	
	$('#notice').show();
	$('#add_button').width($('#add_button').width() + 10);
	
	if($('#homepage_footer_holder').length > 0){
		homepage.load_popular_categories();
	}

});

