$(document).ready(function(){
	
	// Box
	$('.close').click(function()
	{
		$(this).parent('.title').parent('.topBox').slideUp();
	});
	$('#showSingleHeadboardPresets').click(function()
	{
		$('html, body').animate({scrollTop:0});
		setTimeout("$('.topBox.single').slideDown();",250);
	});
	$('#showTwinSepHeadboardPresets').click(function()
	{
		$('html, body').animate({scrollTop:0});
		setTimeout("$('.topBox.twinsep').slideDown();",250);
	});
	$('#showTwinLargeHeadboardPresets').click(function()
	{
		$('html, body').animate({scrollTop:0});
		setTimeout("$('.topBox.twinlarge').slideDown();",250);
	});
	
	$('.topBox ul li').click(function()
	{
	
		var value = $(this).attr('data-value');
		var field = $(this).attr('data-field');
		var elm = '#'+field+' option[value="'+value+'"]';
		$(elm).attr("selected","selected");
		
		$(this).parent('ul').parent('.content').parent('.topBox').slideUp();
		$('html, body').animate({scrollTop:700});
		
		updateImage();
	
	});
	
	$('.updateimage').change(function()
	{
		updateImage();
	});
	
	// Validate
	$('#form').submit(function()
	{
	
		var count = 0;
		$('.error-arrow').hide();
		if($('.bedtype_price:checked').val()=="Single Bed")
		{
			// Check select box's
			$.each($('select.validate-single'), function(index, value) {	
				if($(value).val() == '')
				{
					$(value).parent("label").parent("p").parent('.bed-step-content').parent('.bed-step').children('.bed-step-title').children('.error-arrow').show();
					count = 1;
				}
			});
			
			// Check colours
			var c = 0;
			$.each($("input[name='bed-colour']"), function(index, value) {
				if($(value).attr("checked") == true)
				{
					c = 1;
				}
			});
			if(c == 0)
			{
				count = 1;
				$("input[name='bed-colour']").parent(".texture").parent('.bed-step-content').parent('.bed-step').children('.bed-step-title').children('.error-arrow').show();
			}
		}
		if($('.bedtype_price:checked').val()=="Twin Beds")
		{
			// Check select box's
			$.each($('select.validate-twin'), function(index, value) {	
				if($(value).val() == '')
				{
					$(value).parent("label").parent("p").parent('.bed-step-content').parent('.bed-step').children('.bed-step-title').children('.error-arrow').show();
					count = 1;
				}
			});
			
			// Check colours
			var c = 0;
			$.each($("input[name='bed-colour']"), function(index, value) {
				if($(value).attr("checked") == true)
				{
					c = 1;
				}
			});
			if(c == 0)
				{
				count = 1;
				$("input[name='bed-colour']").parent(".texture").parent('.bed-step-content').parent('.bed-step').children('.bed-step-title').children('.error-arrow').show();
			}
		}
		
		if(count > 0)
		{
			if($('html, body').scrollTop() <= 0)
			{
				$('html, body').animate({scrollTop:0}, 'slow');
			}
			alert("Please check you have chosen a bed width, base colour and a mattress.");
			return false;
		}
		else
		{
			return true;
		}
	
	});
	
	// Price box to scroll with the page
	$('#bed-floater').scrollFollow({ offset:10 });
	
	// Load everything at start
	totUpPrices();
	checkBedType();
	checkHeadboardOption();
	checkHeadboardTwinOption()
	updateImage();
	
	// Reset
	$('#resetButton').click(function()
	{
		globalReset(true,true);
	});
	
	// Update the prices when you change a bed
	$('.bedtype_price').click(function()
	{
		globalReset(true,false);
	});
	
	// Update headboads when you pick
	$('.headboard_option').click(function()
	{
		checkHeadboardOption();
	});
	
	$('.headboard-twin-type').click(function()
	{
		$.each($('.headboard-options select'), function(index, value) {
			$(value).children("option[value='']").attr("selected","selected");	
		});
		totUpPrices();
		checkHeadboardTwinOption();
	});
	
	$("select[name='bed-headboard-single'],select[name='bed-headboard-twin'],select[name='bed-headboard-twin-onelarge'],select[name='bed-headboard-twin-twoseperate']").change(function()
	{
		updateImage();
	});
	
	// Simulate a checkbox kind of thing with the texture boxes
	$('.texture').click(function()
	{
	
		// Uncheck
		$('.texture').removeClass("checked");
		$('.texture').children("input").attr("checked","");
	
		// Check
		$(this).addClass("checked");
		$(this).children("input").attr("checked","checked");
		
		checkHeadboardOption();
		
	});
	
	// Update prices when something that requires a change is changed
	$('.pricechanger_auto').change(function()
	{
		totUpPrices();
	});
	
	// Hide or show width in slider
	$('.bed-width-single, .bed-width-twin').change(function()
	{
	
		if($(this).val()=="")
		{
			$('#width-modal').fadeOut(300);
			setTimeout("$('#width-modal').hide()",300);
		}
		else
		{
			$('#width-modal').fadeIn(300);
			setTimeout("$('#width-modal').show()",300);
			$('#width-modal').text($(this).val());
		}
	
	});
	
	// Deal with disabling and enabling the pocketmatic option {Single Beds}
	$('.bed-width-single').change(function()
	{
		if($(this).val()=="2' 6\"" || $(this).val()=="3'")
		{
			$('.pocketmatic-mattress').attr("disabled","");
		}
		else
		{
			$('.pocketmatic-mattress').attr("disabled","disabled");
			if($('.pocketmatic-mattress').parent("select").val()=="Pocketmatic")
			{
				$('.pocketmatic-mattress').parent("select").children("option[value=]").attr("selected","selected");
			}
		}
	});
	
	// Deal with disabling and enabling the pocketmatic option {Twin Beds}
	$('.bed-width-twin').change(function()
	{
		if($(this).val()=="4' 6\"" || $(this).val()=="6'")
		{
			$('.pocketmatic-mattress').attr("disabled","");
		}
		else
		{
			$('.pocketmatic-mattress').attr("disabled","disabled");
			if($('.pocketmatic-mattress').parent("select").val()=="Pocketmatic")
			{
				$('.pocketmatic-mattress').parent("select").children("option[value='']").attr("selected","selected");
			}
		}
		updateImage();
	});
	
	$("select[name='bed-mattress-single'],select[name='bed-mattress-twin-first'],select[name='bed-mattress-twin-second']").change(function()
	{
		updateImage();
	});
	
	// Work out the prices with VAT and Non-VAT products and update the price box
	function totUpPrices()
	{
	
	    var totalprice = 0;
	    var totalpricenew = 0;
	    
	    // Check Type of bed prices
	    var objs = $('.bedtype_price');
	    $.each(objs, function(index, value) {
	    
	    	if($(value).attr("checked"))
	    	{
	    		if($(this).hasClass("no_vat"))
	    		{
					totalprice = totalprice + parseInt($(this).attr("data-cost"));
					totalpricenew = totalpricenew + parseInt($(this).attr("data-cost"));
	    		}
	    		else
	    		{
	    		
	    			var previousprice = totalpricenew;	    			
	    			var thisprice = parseInt($(this).attr("data-cost"));
	    			var vat = parseInt(thisprice / 100 * 17.5);
	    			var thisincvatprice = thisprice + vat;
	    			
	    			// Exc VAT
	    			totalprice = totalprice + parseInt($(this).attr("data-cost"));
	    			
	    			// Inc VAT
	    			totalpricenew = parseInt(previousprice + thisincvatprice);

	    		}
	    	}
	    
	    });
	    
	    // Check Delivery Options
	    var objs = $('.deliveryoptions_price');
	    $.each(objs, function(index, value) {
	    		
	    	if($(value).attr("checked"))
	    	{
	    		if($(this).hasClass("no_vat"))
	    		{
					totalprice = totalprice + parseInt($(this).attr("data-cost"));
					totalpricenew = totalpricenew + parseInt($(this).attr("data-cost"));
	    		}
	    		else
	    		{
	    			var previousprice = totalpricenew;	    			
	    			var thisprice = parseInt($(this).attr("data-cost"));
	    			var vat = parseInt(thisprice / 100 * 17.5);
	    			var thisincvatprice = thisprice + vat;
	    			
	    			// Exc VAT
	    			totalprice = totalprice + parseInt($(this).attr("data-cost"));
	    			
	    			// Inc VAT
	    			totalpricenew = parseInt(previousprice + thisincvatprice);
	    		}
	    	}
	    	
	    });
	    
	    // Check Checkbox Prices
	    var objs = $('input[type=checkbox]');
	    $.each(objs, function(index, value) {
	    		
	    	if($(value).attr("checked"))
	    	{
	    		if($(this).hasClass("no_vat"))
	    		{
					totalprice = totalprice + parseInt($(this).attr("data-cost"));
					totalpricenew = totalpricenew + parseInt($(this).attr("data-cost"));
	    		}
	    		else
	    		{
	    			var previousprice = totalpricenew;	    			
	    			var thisprice = parseInt($(this).attr("data-cost"));
	    			var vat = parseInt(thisprice / 100 * 17.5);
	    			var thisincvatprice = thisprice + vat;
	    			
	    			// Exc VAT
	    			totalprice = totalprice + parseInt($(this).attr("data-cost"));
	    			
	    			// Inc VAT
	    			totalpricenew = parseInt(previousprice + thisincvatprice);
	    		}
	    	}
	    		
	    });
	
	    // Check Dropdown Prices
	    var objs = $('.select_price');
	    $.each(objs, function(index, value) {
	    
	    	newvalue = $(value).attr("value");
	    	$.each($(value).children("option"), function(i, l){
	    		if($(this).attr("value")==newvalue)
	    		{
	    			if($(this).parent("select").hasClass("no_vat"))
	    			{
						totalprice = totalprice + parseInt($(this).attr("data-cost"));
						totalpricenew = totalpricenew + parseInt($(this).attr("data-cost"));
	    			}
	    			else
	    			{
	    				var previousprice = totalpricenew;	    			
	    				var thisprice = parseInt($(this).attr("data-cost"));
	    				var vat = parseInt(thisprice / 100) * 17.5;
	    				var thisincvatprice = thisprice + vat;
	    				
	    				// Exc VAT
	    				totalprice = totalprice + parseInt($(this).attr("data-cost"));
	    				
	    				// Inc VAT
	    				totalpricenew = parseInt(previousprice + thisincvatprice);
	    			}
	    		}
	    	});
	    
	    });
	    
	    $('#totalexvat').text(totalprice);
	    $('#price-exl-vat-input').val(totalprice);
	    $('#totalincvat').text(totalpricenew);
	    $('#price-inc-vat-input').val(totalpricenew);
	}
	
	// Hide and show the different options depending on the bed type chosen (Single or Twin)
	function checkBedType()
	{
		
	    var objs = $('.bedtype_price');
	    var checkedType = '';
	    var twinbeds;
	    $.each(objs, function(index, value) {
	    
	        if($(value).attr("checked"))
	        {
	        	checkedType = $(value).val();
	        }
	        if($(value).val() == "Twin Beds")
	        {
	        	twinbeds = $(value);
	        }	    
	    });
	    if(checkedType == "Single Bed")
	    {
	    	$('.show_with_single').show();
	    	$('.show_with_twin').hide();
	    	$('.changeOnTwin').text("Would you like a headboard?");
	    }
	    else
	    {
	    	$(twinbeds).attr("checked","checked");
	    	$('.show_with_twin').show();
	    	$('.show_with_single').hide();
	    	$('.changeOnTwin').text("Would you like headboards?");
	    }
	    
	    // Clear error fields
	    $('.error-arrow').hide();
	}
	
	// Check if you have asked to have a headboard or not
	function checkHeadboardOption()
	{
	    var objs = $('.headboard_option');
	    var checkedType = '';
	    $.each(objs, function(index, value) {
	    
	        if($(value).attr("checked"))
	        {
	        	checkedType = $(value).val();
	        }
	    
	    });
	    if(checkedType == "Yes")
	    {
	    	if($('.texture:checked').val() != undefined)
	    	{
	    		$('.colorinfo').hide();
	    		$('.colorinfo.baseandheadboard').show();
	    	}
	    	else
	    	{
	    		$('.colorinfo').hide();
	    	}
	    	$('.headboard-options').show();
	    	checkHeadboardTwinOption();
	    }
	    else
	    {
	    	if($('.texture:checked').val() != undefined)
	    	{
	    		$('.colorinfo').hide();
	    		$('.colorinfo.base').show();
	    	}
	    	else
	    	{
	    		$('.colorinfo').hide();
	    	}
	    	$('.headboard-options').hide();
			$.each($('.headboard-options select'), function(index, value) {
				$(value).children("option[value='']").attr("selected","selected");	
			});
			// Update prices
			totUpPrices();
	    }
		
	    updateImage();
	}
	
	function checkHeadboardTwinOption()
	{
		if($('.bedtype_price:checked').val()=="Twin Beds")
		{
			if($('.headboard-twin-type:checked').val()=="One Large")
			{
				$("select[name='bed-headboard-twin-onelarge'], .twin-large").show();
				$("select[name='bed-headboard-twin-twoseperate'], .twin-sep").hide();
			}
			else
			{
				$("select[name='bed-headboard-twin-twoseperate'], .twin-sep").show();
				$("select[name='bed-headboard-twin-onelarge'], .twin-large").hide();
			}
		}
		else
		{
			$("select[name='bed-headboard-twin-onelarge'], .twin-sep").hide();
			$("select[name='bed-headboard-twin-twoseperate'], .twin-large").hide();
		}
	}
	
	// Reset Everything
	function globalReset(doRest,clearAll)
	{
		
		// Remove the bed texture selection
		$('.texture.checked').removeClass("checked");
		$('.texture').children("input").attr("checked","");
		
		// Set all <select> back to the Please Select option
		$.each($('select'), function(index, value) {
				
			$(value).children("option[value='']").attr("selected","selected");
			$(value).children("option[value='0']").attr("selected","selected");
				
		});
		$('.pocketmatic-mattress').attr("disabled","");
		
		// Remove ticks from tick box's
		$("input[type='checkbox']").attr("checked","");
		
		if(clearAll)
		{
			$('.reset_radio_default, .reset_radio_all').attr("checked","checked");
		}
		else
		{
			$('.reset_radio_default').attr("checked","checked");
		}
		
		if(doRest)
		{
			// Put prices back to normal
			checkBedType();
			checkHeadboardOption();
			totUpPrices();
			updateImage();
			$('#width-modal').fadeOut(300);
			setTimeout("$('#width-modal').hide()",300);
		}
		
		if($('html, body').scrollTop() <= 0)
		{
			$('html, body').animate({scrollTop:0}, 'slow');
		}
		
	}
	
	// Update image box
	function updateImage()
	{
		
		// Defaults
		var imageRoot = 'bedMedia/beds/';
		var imageLocation = imageRoot;
		
		// Check bed type
		imageLocation = imageLocation + $('.bedtype_price:checked').attr("data-image");
		
		// Check color
		if($('.texture:checked').val() == undefined)
		{
			$('#bed-image-wrap-head .color').css('backgroundImage','url(images/color-none.png)');
			imageLocation = imageLocation + "-ivory";
		}
		else
		{
			var image = $('.texture:checked').parent("div.texture").attr("data-image");
			imageLocation = imageLocation + "-" + image;
			$('#bed-image-wrap-head .color').css('backgroundImage',"url('bedMedia/colors/"+image+".png')");
		}
		
		// Check headboards
		if($('.bedtype_price:checked').attr("data-image")=='single')
		{
			if($('.headboard_option:checked').val()=="Yes")
			{
				imageLocation = imageLocation + "-" + $("select[name='bed-headboard-single'] option:selected").attr("data-image");
			}
			else
			{
				imageLocation = imageLocation + '-none';
			}
		}
		
		if($('.bedtype_price:checked').attr("data-image")=='twin')
		{
			if($('.headboard_option:checked').val()=="Yes")
			{
				if($('.headboard-twin-type:checked').val()=="One Large")
				{
					if($("select[name='bed-headboard-twin-onelarge'] option:selected").val() != '')
					{
						imageLocation = imageLocation + "-" + $("select[name='bed-headboard-twin-onelarge'] option:selected").attr("data-image") + "one";
					}
					else
					{
						imageLocation = imageLocation + "-none";
					}
				}
				else
				{
					if($("select[name='bed-headboard-twin-twoseperate'] option:selected").val() != '')
					{
						imageLocation = imageLocation + "-" + $("select[name='bed-headboard-twin-twoseperate'] option:selected").attr("data-image") + "two";
					}
					else
					{
						imageLocation = imageLocation + "-none";
					}
				}
			}
			else
			{
				imageLocation = imageLocation + '-none';
			}
		}
		
		// Check if drawers
		if($('.bedtype_price:checked').attr("data-image")=='single')
		{
			if($('.single-drawers').attr("checked"))
			{
				imageLocation = imageLocation + '-drawers';
			}
			else
			{
				imageLocation = imageLocation + '-nodrawers';
			}
		}
		else
		{
			if($('.twin-drawers').attr("checked"))
			{
				imageLocation = imageLocation + '-drawers';
			}
			else
			{
				imageLocation = imageLocation + '-nodrawers';
			}
		}
		
		// Check mattress
		if($('.bedtype_price:checked').val()=="Single Bed")
		{
			$('.single-mattress-info').html($("select[name='bed-mattress-single'] option:selected").attr("data-image"));
		}
		else
		{
			$('.twin-mattress-info-one').html($("select[name='bed-mattress-twin-first'] option:selected").attr("data-image"));
			$('.twin-mattress-info-two').html($("select[name='bed-mattress-twin-second'] option:selected").attr("data-image"));
		}
		
		// Finish up
		imageLocation = imageLocation + ".jpg";
		
		$('#bed-image').attr("src",imageLocation);
		$("input[name='bed-image-url']").val(imageLocation);
		
		
	}
	
	// Function to round numbers up
	function roundNumber(num, dec) {
		var result = Math.round(num*Math.pow(10,dec))/10;
		return result;
	}	

});