/* Created by: Hung Bui
  * Copyright 2009 - KD WEB 
  * Free to use or contribute this code .. at your own risk 
  * sc_  means selected_currency
 */
function generateProductElements(){
	$('.recommended>li').each(
		function (iterator, element){
			var title = $(element).find('h3').html();
			
			// initialising sub-total
			var sub_total = 0;
			var sub_quantity = 0;			
			// traversing the doc and calculate total price				
			$('ul.items',element).each(function(iterator, ul){			
				sub_total +=				
						//quantity (can be specified to select[name=quantity] option:selected)
						$('select[name=qty[]]',ul).val()						
						//times						
						*						
						//price   (can be specified to input[name=price[]])
						$('input[name=price[]]',ul).val()
				;				 
				sub_quantity += 1 * ($('select[name=qty[]]',ul).val());			
			});
			
			// Get currency price for current currency
			sc_sub_total = priceSymbolFormating(currencyConvertor(sub_total));		
			
			$('<ul />')
			.attr('rel',iterator)
			.html(	'<li class="sum-title">'+title+'</li>' + 
					'<li class="sum-total"><span class="priceTag" title="'+sub_total+'">'+sub_total+'</span></li>'+
					'<li class="sum-quantity">qty '+sub_quantity+'</li>')
			.css({'display': (sub_quantity == 0)? 'none':'block'})
			.appendTo('#selectedProList');			
		}
	);
}


/**	Function is to calculate total price and show in the summary box
*
*
*
*/
function calTotalPrice(){	
	//intial total price value
	var total = 0;	
	
	// traversing doc and calculate total price
	$('.items li.subProdQuantity').each(
		function (iterator, element){
			var price = $(this).parent().find('input[name=price[]]').val();
			var quantity = $(element).find('select[name=qty[]]').val();
			total += quantity * price;
		}		
	);	
	
	// Go through all the "li" and calculate all product price with its quantity
	$('.recommended>li').each(
		function (iterator, element){						
			// initialising sub-total
			var sub_total = 0;
			var sub_quantity = 0;			
			// traversing the doc and calculate total price				
			$('ul.items',element).each(function(iterator, ul){			
				sub_total +=				
						//quantity (can be specified to select[name=quantity] option:selected)
						$('select[name=qty[]]',ul).val()						
						//times						
						*						
						//price   (can be specified to input[name=price[]])
						$('input[name=price[]]',ul).val()
				;				
				sub_quantity += parseInt( $('[name=qty[]]',ul).val(), 10);			
			});
			
			// Convert price in pounds into selected currency ! These converting functions are in multiple_currency.js file
			sc_sub_total = priceSymbolFormating(currencyConvertor(sub_total));
			
			if (sub_quantity !=0){				
				$('#selectedProList ul[rel='+iterator+'] li:nth-child(2)').html('<span class="priceTag" title="'+sub_total+'">'+sc_sub_total+'</span>');
				$('#selectedProList ul[rel='+iterator+'] li:last').text('qty '+sub_quantity);
				$('#selectedProList ul[rel='+iterator+']').addClass('show');				
			}
			else
			{
				$('#selectedProList ul[rel='+iterator+']').removeClass('show').hide();
			}									
		}
	);
	
	$('#selectedProList ul.show').fadeIn();
	$('#selectedProList ul:not(.show)').hide();
		
	
	//parce total price to total div	
	sc_total = priceSymbolFormating(currencyConvertor(total));
	$('#totalCost').html('<span class="priceTag" title="'+total+'">'+sc_total+'</span>');
}


/* function to validate Bed linen  page before submitting to the basket 
********************************************************************/

function validateSubmitBedLinen(){
	
	$('#summarybox li.error').html("").hide();
	
	// Validate the table sizes
	errorMsg = "";
	
	
	// initial total quantity
	var total = 0;
	
	// traversing doc and calculate total price
	$('.items li.subProdQuantity').each(
		function (iterator, element){
			var price = $(this).parent().find('input[name=price[]]').val();
			var quantity = $(element).find('select[name=qty[]]').val();
			total += quantity * price;
		}		
	);	
			
	if (total > 0){ 
		$('#summarybox li.error').html("").hide();
		return true;
	}
	else
	{
		errorMsg = "You need to select a product quantity.";
		$('#summarybox li.error').html(errorMsg).show();
		return false;
	}
	
}





$(document).ready(function(){

	//create quantity dropdown	
	var  quantityDropDown = '<select name="qty[]">';	
	var i=0;
	for (i = 0; i<=10; i++){		
		quantityDropDown += '<option value="'+i+'">'+i+'</option>';
	}
	quantityDropDown += '</select>';	
	
	//set quantity dropdown list to its li
	$('.items li.subProdQuantity').each(
		function(iterator, element){
			$(element).html(quantityDropDown);			
		}
	);

	//innitial caculating the total cost
	calTotalPrice();
	
	//generate the list
	generateProductElements();
	
	//do the calculation base on prices
	$(".subProdQuantity>select").change(calTotalPrice);
	
		
	
	/* IMAGE GALLERY 
	************************************ */
	
	$('#imgGallery').hide();
	
	//reset all thumbnail images's href to "#nogo" .. to handle javascript being turned off
	$('a.thumbItem').each( function(){
		$(this).attr('href','#nogo');
	});
	
	//handle click event when user click on thumbnail image in the Gallery
	$(".thumbnailList a.thumbItem").click(function() {
		// get orginal image src on event
		var imgSrc = $(this).parent().find('input').val();		
	
		// only load / replace a new image
		if ($('#LargeImgContainer img.largeImage').attr('src') != imgSrc){
			$('#LargeImgContainer img.largeImage')
				.fadeOut(
					300
					, 
					function()
					{
						// remove current large image
						$(this).remove();
						//display loading image
						$('#LargeImgContainer img.loadingImage').show();						
						
						$('#LargeImgContainer')
							.append(
								$('<img>')
									.attr('src',imgSrc)
									.addClass('largeImage')
									.hide()
									.load(
										function()
										{
											// hide loading image
											$('#LargeImgContainer img.loadingImage').hide();
											
											// show latest large image
											$(this).fadeIn();
										}
									)
							)
						;
					}
				)
			;
		}		
		return false;
	});
	
	
	// SWITCH INCH TO CM OR VICE VERSAR
	$('input[name="sizeSwitcher"]').click(
		function(){
			
			switch ($('input[name="sizeSwitcher"]:checked').val()){
				case 'inch':		
					// show all inch values
					$('.size_cm').hide();
					$('.size_inches').show();
				break;
				case 'cm':
					// show cm values					
					$('.size_inches').hide();
					$('.size_cm').show();
				break;			
			}								
		}		
	);
	
	// 09-09-2009 - Hung Bui
	// We need to tweak the product option a little bit to make it clearer for customers. We will pop-up a warning message and ask for client to weather add all current selected products to basket or terminate them
	// This is to stop customers from confusing select multiple products with different colour options at once.. which is not allowed 
	
	$("input[name^='option_']:checked").each( function(){	
		$('li.item-colour >span').text($('span>span',$(this).parent()).text());
	});
	
	
	$('.coloursOptItems li').click(function(){
		// This event will fire first and before the same event handler in options.tpl.htm template system
		var curColour = $('li.item-colour:first >span').text();
		var newColour = $('span>span',$(this)).text();		
		if (curColour != newColour){			
			
			// handling the product quantity
			var quantity = 0;
			$("select[name=qty[]]").each(function(){		
				quantity += parseInt( $(this).val(), 10);				
			});
			
			if (quantity  == 0){
				//update current color with new selection
				$('input[name=curColour]').val($('.colourOpt:checked').val());
			}	
			else
			{
				if ($('.pop-notice').is(':visible'))
				{
					//keep the old message.
				}
				else
				{
					$('.pop-notice span.pop-notice-colour').text(curColour);
					$('.pop-notice').show();
				}
			}
			
			// update colours
			$('li.item-colour >span').text(newColour);			
		}		
	});
	
	
	$('#bedlinen_hitNo').click(function(){
		$('.pop-notice').hide();		
		//update current color with new selection
		$('input[name=curColour]').val($('.colourOpt:checked').val());
		return false;
	});
	
	
	$('#bedlinen_hitYes').click(function(){		
		//we do not want to change PHP. we will revert the selection via javascript.
		$('.colourOpt[value='+$('input[name=curColour]').val()+']').attr('checked', 'checked');		
		$('.pop-notice').hide();		
		$('#productDisplay').submit();		
	});
	
			
	/* ************************************ MAGIC UTILITY   ************************************** */
	
	// TO REMOVE ALL IMAGES WITH EMPTY SRC ATTRIBUTE
	$('img').each( function(){
		if ( $(this).attr('src') == "" ){
			$(this).hide();
		}
	});
	
});
