// @TODO: clean up file for readability/maintainability

$().ready(function() {
	// hide all product details
	$('.details_product').hide();
	$('input.product').bind('click', function(){
		var productId = this.id.replace('product_', '');

		// hide any opened product details list
		$('.details_product').hide();
		// reset the form
		// @TODO: make resetting of the form work properly
		$('.details_product :input').resetForm();
		// also reset any price fields that have been selected
		$('.details_product .price').removeClass('price_selected');

		// show details of the selected product
		$('#details_' + productId).show();

		// hide the block of non-mandatory options for this product
		$('#details_' + productId + ' .mandatoryitems_checked').hide();

		// hide the parts of this product
		$('#details_' + productId + ' .product_parts').hide();

		// hide the optionlist of the product-parts
		$('#details_' + productId + ' .part_option').hide();

		// remove all part-options from the DOM that are a mandatory option of the product itself
		$('input:hidden.mandatory_option').each(function (i) {
			var ids = this.name.replace('mandatory_', '').split('_');
			var productId = ids[0];
			var optionId = ids[1];
			var removeClass = '#details_' + productId + ' .option_' + productId + '_' + optionId;

			$(removeClass).remove();
		});
	});
	

	/**
	 * Show the rest of the options and/or parts when the mandatory option has been selected
	 */
	$('.details_product .mandatoryitems input:radio').bind('click', function(){
		var ids = parseId(this.id);
		var productId = ids.productId;
		var stop = false;

		var optiondivs = $('.product_' + productId + '.mandatoryitems div');
		$(optiondivs).each( function()
		{		
			if( $('input:radio:checked',this).size() == 0)
			{
				stop = true;
			}
		});

		if(!stop)
		{

			// show the block of non-mandatory options for this product
			$('#details_' + ids['productId'] + ' .mandatoryitems_checked').show();

			// show the parts of this product
			$('#details_' + ids['productId'] + ' .product_parts').show();
		}
	});



	/**
	 * Process the price of the selected option when checkbox/radiobutton/selectbox is clicked
	 */
	$('.product input:checkbox, .product input:radio, .product select, .details_product input:checkbox, .details_product input:radio, .details_product select').bind('click', function(){
		if (this.type == 'select-one')
		{
			var id = this.id.replace('_option', '');
			var ids = parseId(id);
		}
		else
		{
			var ids = parseId(this.id);
		}

		// initially consider this to be the product itself
		var isProduct = true;

		// for options or parts without values
		var pricegroup_selector = '.price_' + ids['productId'];
		var price_selector = '#price_' + ids['productId'];
		var lbl_price_selector = '#lbl_price_' + ids['productId'];

		if (ids['optionId'] != undefined)
		{
			isProduct = false;
			pricegroup_selector += '_' + ids['optionId'];
			price_selector += '_' + ids['optionId'];
			lbl_price_selector += '_' + ids['optionId'];
		}

		if (ids['valueId'] != undefined)
		{
			// add values to the selectors (but not to the group!)
			price_selector += '_' + ids['valueId'];
			lbl_price_selector += '_' + ids['valueId'];
		}

		if (this.type == 'select-one')
		{
			// add the value to the group selector
			pricegroup_selector += '_' + ids['valueId'];

			// hide all prices
			$(pricegroup_selector).removeClass('price_selected');
			$(pricegroup_selector).hide();

			// show the price matching the selected option
			$(price_selector + '_' + this.value).addClass('price_selected');
			$(lbl_price_selector + '_' + this.value).addClass('price_selected');
			$(lbl_price_selector + '_' + this.value).show();
		}

		if (this.type != 'select-one' && !this.checked)
		{
			$(price_selector).removeClass('price_selected');
			$(lbl_price_selector).removeClass('price_selected');
			// hide the optionlist of this type
			$('.' + ids['type'] + '_option_' + ids['type'] + '_' + ids['productId'] + '_' + ids['optionId']).hide();
		}
		else
		{
			// remove class from all radiobuttons' prices and hide the price-field
			if (this.type == 'radio')
			{
				if (isProduct)
				{
					$('.product_price').removeClass('price_selected');
				}
				else
				{
					$(pricegroup_selector).removeClass('price_selected');
					$(pricegroup_selector).hide();
				}
			}

			// add class to the price of the selected checkbox/radiobutton and its label
			$(price_selector).addClass('price_selected');
			$(lbl_price_selector).addClass('price_selected');

			// display the price
			if (this.type == 'radio')
			{
				$(pricegroup_selector).show();
			}

			var mandatoryoptions = $('.product_' + ids['productId'] + '.mandatoryitems');

			// show the optionlist of this type
			$('.' + ids['type'] + '_option_' + ids['type'] + '_' + ids['productId'] + '_' + ids['optionId']).show();

			// show non-mandatory options and parts if no mandatory options are available
			if(mandatoryoptions.size() == 0)
			{
					// show the block of non-mandatory options for this product
					$('#details_' + ids['productId'] + ' .mandatoryitems_checked').show();

					// show the parts of this product
					$('#details_' + ids['productId'] + ' .product_parts').show();
			}
		}

		// set the total price
		setOrderTotalPrice();
	});


	/**
	 * Calculate and set the price of the given desired amount of items
	 * Used for options where an amount can be given and price is per item
	 */
	$('input:text.input_validate_number').bind('keyup mouseup blur', function(){
		desiredAmount = this.value;
		if (isNaN(desiredAmount) ||
		    desiredAmount == '' ||
		    desiredAmount <= 0)
		{
			$(this).val('');
			desiredAmount = 1;
		}
		priceOfOne = $('#base_price_' + this.id).val();
		priceOfOne = priceOfOne.replace(',', '.');

		price = parseInt(desiredAmount) * parseFloat(priceOfOne);
		setPrice(this.id, price);
	});
	
	// Trigger product if defined
	if(typeof(product) != 'undefined')
	{
		var productdiv = $('label:contains("'+product+'")').parent();
		$('input.product', productdiv).trigger('click');
		$('input.product', productdiv).trigger('click');
	}

	$('input.bestel-button').hover(
		function()
		{
			var src = $(this).attr('src');
			src = src.replace('donker','licht');
			$(this).attr('src', src);
		},
		function()
		{
			var src = $(this).attr('src');
			src = src.replace('licht','donker');
			$(this).attr('src', src);
		}
	);
});

/**
 * Check if the maximum number of items have been selected.
 * If so, cancel last selection and alert
 */
function checkMaximum(element, option, maximum)
{
	var amount = 0;
	$('.' + option + ':checked').each(function() {
		amount++;
		if (amount > maximum)
		{
			alert('Er mogen maximaal ' + maximum + ' items uit deze lijst geselecteerd worden.');
			// uncheck the clicked checkbox
			element.click();
			element.checked = false;
			return false;
		}
	});
	return true;
}

/**
 * Sets the price of the given item.
 * Also updates the corresponding label.
 */
function setPrice(elementId, price)
{
	var ids = parseId(elementId);

	elementId = 'price_' + ids['productId'] + '_' + ids['optionId'];
	price = formatPrice(price);

	$('#' + elementId).val(price);
	$('#lbl_' + elementId).html('€ ' + formatPrice(price));
	setOrderTotalPrice();

	return true;
}

function formatPrice(price)
{
	price = price + ''; // replace only works on strings
	price = price.replace(',', '.'); // replace comma's with dots so toFixed() uses the decimals
	price = parseFloat(price); // turn value into a number
	price = price.toFixed(2); // make it a proper money-amount (123.45)
	price = price.replace('.', ','); // put the comma back where it belongs
	return price;
}

/**
 * Sets the total price for the currently selected product and options
 */
function setOrderTotalPrice()
{
	var total = 0;
	var totalincbtw = 0;
	var btw = 0;

	$('input.price_selected').each(function() {
		// replace comma's with dots so parseFloat also sees the decimal part
		value = this.value.replace(',', '.');
		total += parseFloat(value);
	});

	var btw = total * 0.19;

	totalincbtw = formatPrice(total + btw);
	btw = formatPrice(btw);
	total = formatPrice(total);

	$('#ex_btw').val(total);
	$('#btw').val(btw);
	$('#ordertotal').val(totalincbtw);
	
	$('#lbl_ordertotal').html('€ ' + totalincbtw);
	$('#lbl_btw').html('€ ' + btw);	
	$('#lbl_ex_btw').html('€ ' + total);		
}

/**
 * Split up the given id into their separate id parts
 */
function parseId(id)
{
	var id = id.replace('input_', '').split('_');

	var ids = new Array();
	ids['type'] = id[0];
	ids['productId'] = id[1];
	ids['optionId'] = id[2];
	ids['valueId'] = id[3];

	return ids;
}

/**
 * Check if parts with optiongroups have at least one option selected
 */
function validateproductselection()
{
	// first remove all errors
	var iErrors = 0;	
	$('label.selecterror').removeClass('selecterror');

	$('div.part').each(
		function()
		{
			// get optiongroup from parts
			var partoptions = $('div.part_option', this);
			
			if( $('input[type="checkbox"]:first',this).is(':checked') && partoptions.size() > 0)
			{
				// get select from optiongroup
				var partselect = $('select', partoptions);
				// get nummeric fields from optiongroup
				var partinput = $('input.input_validate_number', partoptions);
				// get checkboxes from optiongroup
				var partcheckbox = $('input[type="checkbox"]', partoptions);

				// check selects
				if ( partselect.size() > 0 && partselect.val() == '')
				{
					var selectname = partselect.attr('id');
					var selectlabel = $('label',this).addClass('selecterror');
					iErrors++;
				}
				
				// check numeric inputs
				else if ( partinput.size() > 0 && partinput.val() == '')
				{
					var inputname = partinput.attr('id');
					var inputlabel = $('label',this).addClass('selecterror');
					iErrors++;
				}

				// check checkboxes
				else if (partcheckbox.size() > 0 && $('input[type="checkbox"]:checked', partoptions).size() == 0)
				{
					//var inputname = partcheckbox.attr('id');
					var inputlabel = $('label:first',this).addClass('selecterror');
					iErrors++;
				}

			}
		}
	);
	// show errors
	if (iErrors > 0)
	{
		$('.errormessage').css('display','block');
		return false;		
	}
	// submit
	else
	{
		return true;
	}
}