jQuery(function(){
	
	// Add show/hide desc click
	$('.tillval-beskrivning-link').click(function() {
  		// Hide all others first
  		$('.tillval-beskrivning').slideUp();
		
		// Show selected (if hidden)
  		$('#tillval-beskrivning-'+this.id+':hidden').slideDown();
	});
	
	// Add description-teasers
	$('#tillval tr').hover(function(){
		$('.tillval-more', this).show();
	}, function(){
		$('.tillval-more', this).hide();
	});
	
	// Model (preview and calculator)
	$('.tillval-check').click(function() {
		var additionCode = this.id.substr(this.id.length-1, 1);
		additionChanged(additionCode, this.checked);
	});
	
	// SPECIAL LINKING ON FRONT PAGE
	$('#frontBread p span').each(function() {
		if ($(this).html() == 'Stugun Sture') {
			$(this).wrapInner('<a href="/produkter/sture.php" class="stugun_inline sture_inline"/>');
			//$(this).css('color', '#8E6400');
		} else if ($(this).html() == 'Stugun Solvig') {
			$(this).wrapInner('<a href="/produkter/solvig.php" class="stugun_inline solvig_inline"/>');
			//$(this).css('color', '#6C951D');
		}
	});
	
	function additionChanged(additionCode, selected, skipSpecialValidationLogic) {
		// Toggle addition
		var modelSystemName = getModelSystemName();
		var imgId = 'addition_'+additionCode;
		if (selected) {
			// Add element to model (if not allready there)
			if ($('#'+imgId).length==0) {
				$('<img src="/grafik/model/'+modelSystemName+'_'+additionCode+'.png" class="addition" id="'+imgId+'"/>').appendTo('#model');
			}
		} else {
			// Remove element from model
			$('#'+imgId).remove();
		}

		if (skipSpecialValidationLogic === undefined || !skipSpecialValidationLogic) {
			// Now let's see if any special logic will turn off/on other choices
			handleSpecialAdditionalLogic(additionCode, selected);
		}

  		// Recalculate sum
  		calculateAndShowWantedPrice();
  		
  		// Regenerate Facebook-link
  		var additionCodesStr = "";
  		$('.tillval-check:checked').each(function() { 
  			var additionCode = this.id.substr(this.id.length-1, 1);
  			additionCodesStr += additionCode; 
  		});
  		/*if ($('#inc_assembly').attr('checked')) {
  			additionCodesStr += 'Z';
  		}*/
  		var shareURL = 'http://stugun.net/share.php?options='+modelSystemName+'_'+additionCodesStr;
		$('#fb_share').attr('href', 'http://www.facebook.com/sharer.php?u='+encodeURI(shareURL));
	}
	
	///////////
	// Presets
	function activatePreset(presetClass) {
		$('.tillval-check:checked').each(function() {
			// Inactivate all selected first
			var additionCode = this.id.substr(this.id.length-1, 1);
			inactivateAddition(additionCode);
		});
		$('#tillval tr .'+presetClass).closest('td').each(function(){
			var additionCode = this.id.substr(this.id.length-1, 1);
			activateAddition(additionCode);
		});
	}
	$('#presetCottage').click(function() {
		activatePreset('cottage');
	});
	$('#presetStorage').click(function() {
		activatePreset('storage');
	});
	$('#presetSauna').click(function() {
		activatePreset('sauna');
	});
	///////////
	
	
	///////////
	// Deep linking (permanent link to custom additions)
	if (window.location.hash.length > 0) {
		var hash = window.location.hash;
		hash = hash.replace(/^#/, '');

		for (var i=0; i<hash.length; i++) {
			var additionCode = hash.charAt(i);
			activateAddition(additionCode, true);
		}
	}
	
	
	///////////
	// VAT-toggle
	$('#inc_vat').click(function() {
		$('#vatWrapper .active').removeClass('active');
		$(this).addClass('active');
		calculateAndShowWantedPrice();
	});
	$('#ex_vat').click(function() {
		$('#vatWrapper .active').removeClass('active');
		$(this).addClass('active');
		calculateAndShowWantedPrice();
	});
	///////////
	
	///////////
	// Assembly-toggle
	$('#inc_assembly_wrapper').click(function() {
		$('input', this).attr('checked', true);		// Ensure on
		additionChanged('Z', true);
		calculateAndShowWantedPrice();
	});
	$('#ex_assembly_wrapper').click(function() {
		if (isAdditionOn('O')) {
			$('#tillval-check-Z').attr('checked', true);  // Force include assembly
			alert('Isoleringspaketet kräver att du valt frakt och montage (nederst i listan)');
		} else {
			$('input', this).attr('checked', true);   // Ensure on
			additionChanged('Z', false);
			calculateAndShowWantedPrice();
		}
	});
	///////////

	function calculateAndShowWantedPrice() {
		if ($('#basePrice').length !== 0) {
			var assemblySelected = $('#inc_assembly_wrapper input').attr('checked');
			var vatSelected = $('#inc_vat').hasClass('active');
			var sumExcludedVAT = Number($.trim($('#basePrice').val()));
			
			if (assemblySelected) {
				sumExcludedVAT += Number($.trim($('#basePriceAssembled').val()));
			}

			$('#tillval tr').each(function() {
				var checkbox = $('.tillval-check', this);
				var selected = checkbox.attr('checked');
				var price = Number(checkbox.val());
				var priceAssembly = 0;
				var priceAssemblyTmp = "";

				// Base price
				if (!isNaN(price)) {
					
					// Adding assembly-price
					if (assemblySelected) {
						priceAssemblyTmp = $.trim($('.tillval-price-assembly', this).html());
						if (priceAssemblyTmp.length > 0) {
							priceAssembly = Number(priceAssemblyTmp);
							if (!isNaN(priceAssembly)) {
								price +=  priceAssembly;
							}
						}
					}

					if (selected) {
						// Aggregate
						sumExcludedVAT += price;
					}

					// VAT or not?
					if (vatSelected) {
						price = Math.ceil(price * 1.25);
					}

					// Display right price
					$('.tillval-price', this).html('('+price+':-)');

				} else {
					$('.tillval-price', this).html('(pris kommer)');
				}

			});
			var sumIncludedVAT = 0;
			if (!isNaN(sumExcludedVAT)) {
				sumIncludedVAT = Math.ceil(sumExcludedVAT * 1.25);
			}
			$('#sumIncudedVAT').html(sumIncludedVAT+":-");
			$('#sumExcludedVAT').html(sumExcludedVAT+":-");
	
			if (vatSelected) {
				$('#sumExcludedVAT').hide();
				$('#sumIncudedVAT').show();
			} else {
				$('#sumIncudedVAT').hide();
				$('#sumExcludedVAT').show();
			} 
		}
	}
	
	function getModelSystemName() {
		var msn = document.getElementById('model_system_name');
		return (msn?msn.value:'');
	}
	
	function inactivateAddition(additionCode) {
		if ($('#tillval-check-'+additionCode).attr('checked')) {
			document.getElementById('tillval-check-'+additionCode).checked = false;
			additionChanged(additionCode, false);
		}
	}
	function activateAddition(additionCode, skipSpecialValidationLogic) {
		if (!$('#tillval-check-'+additionCode).attr('checked')) {
			document.getElementById('tillval-check-'+additionCode).checked = true;
			additionChanged(additionCode, true, skipSpecialValidationLogic);
		}
	}
	function isAdditionOn(additionCode) {
		return $('#tillval-check-'+additionCode).attr('checked');
	}
	
	function handleSpecialAdditionalLogic(additionCode, onNow) {
		// Vinduer
		if (additionCode==="A" && !onNow) {
			// Remove spröjs
			inactivateAddition('B');
			inactivateAddition('P');
		}
		if (additionCode==="B" && onNow) {
			inactivateAddition('P');
			activateAddition('A');
		}
		if (additionCode==="P" && onNow) {
			inactivateAddition('B');
			activateAddition('A');
		}

		// Fargepakker
		if (additionCode==="J" && onNow) {
			inactivateAddition('R');
		}
		if (additionCode==="R" && onNow) {
			inactivateAddition('J');
		}

		// Tak
		if (additionCode==="D" && onNow) {
			inactivateAddition('Q');
		}
		if (additionCode==="Q" && onNow) {
			inactivateAddition('D');
		}
		
		// Lock (L/T) + double-door (C)
		if (additionCode==="L" && onNow) {
			if (isAdditionOn('C')) {
				// Show double-lock (T)
				$('#addition_L').attr('src', '/grafik/model/'+getModelSystemName()+'_T.png');
			}
		}
		if (additionCode==="C") {
			if (isAdditionOn('L')) {
				if (onNow) {
					// Swap to double-lock
					$('#addition_L').attr('src', '/grafik/model/'+getModelSystemName()+'_T.png');
				} else {
					// Swap to single-lock
					$('#addition_L').attr('src', '/grafik/model/'+getModelSystemName()+'_L.png');
				}
			}
		}
		
		// Isolasjon
		if (additionCode==="O" && onNow) {
			if ($('#ex_assembly_wrapper input').attr('checked')) {
				inactivateAddition('O');
				alert('Isoleringspaketet kräver att du valt frakt och montage (nederst i listan)');
			}
		}
		
	}

	$('#showOrderFormButton').click(function(){
		$('#orderFormWrapper').slideDown();
	});
	$('#resetOrderFormButton').click(function(){
		$('#orderFormWrapper').slideUp();
	});

	$(document).ajaxError(function(e, xhr, settings, exception) {
		alert('error in: ' + settings.url + ' \\n'+'error:\\n' + exception);
	});
	
	// Init (VAT)
	$('#inc_vat').addClass('active');

	calculateAndShowWantedPrice(); 
	
	// Validatious config
	v2.Field.prototype.positionErrorsAbove = false;
	
	// Init navigation
	if (getModelSystemName()!=='') {
		$('#produktmeny li img').each(function() {
			var imgUrl;
			if (this.id == 'nav_'+getModelSystemName()) {
				imgUrl = $(this).attr('src').substr(0, $(this).attr('src').length-4); // Subtract ".png"
				$(this).attr('src', imgUrl+'MARK.png');
			}
		});
	}
	
	// Make sure the product-helper gets attention
	//setInterval('productHelperAnimation()', 5000);

	
	// Checkboxes substitution
	/*$('input[type=checkbox]').checkbox({
  		cls:'jquery-safari-checkbox',
		empty: 'http://stugun.net/js/jquery-checkbox/empty.png'
	});*/

	// Gallery
	$('.thumb_box a').lightBox({
		fixedNavigation:true,
		imageLoading: '/css/lightbox-ico-loading.gif',
		imageBtnClose: '/css/lightbox-btn-close.gif',
		imageBtnPrev: '/css/lightbox-btn-prev.gif',
		imageBtnNext: '/css/lightbox-btn-next.gif',
		imageBlank: '/css/lightbox-blank.gif',
		txtImage: '',
		txtOf: '/'
	});
	
});


function sendOrdre() {
	// Populate form with selected additionals
	$('.tillval-check:checked').each(function() {
  		var additionCode = this.id.substr(this.id.length-1, 1);
  		var additionTitle;
  		if ($('#'+additionCode).length !== 0) {
	  		additionTitle = $.trim($('.tillval-tittel', $('#'+additionCode)).html());
		} else if (additionCode == 'Z') {
			additionTitle = 'Frakt och montage';
		}
		$('<input type="hidden" name="tillval_'+additionCode+'" value="'+additionTitle+'"/>').appendTo('#orderForm');
	});
	
	$.post('/sendOrder_ajax.php', $('#orderForm').serialize(), function(data) {
		//$('#showOrderFormButton').hide();
		$('#orderForm').slideUp(function() {
			$('#showOrderFormButtonWrapper').hide();			
			$('#orderFormWrapper .confirmation').show();
		});
	});
}


function productHelperAnimation() {
	$('#products_helper').effect('shake', { times: 3, distance: 1}, "fast");
}

