/** 
  * Created by: Dave Sniper  
  * Copyright 2009 - KD WEB 
  * Free to use or contribute this code .. at your own risk 
  * This script is only used for Tablecloth page
 */

 

 
/** function convert inch to cm  
 */
function convertInchToCm(inch){
	return inch * 2.54;
}


/** function convert inch to cm  
 */
function convertCmToInch(cm){
	return cm / 2.54;
}




/** 
*  Function is to calculate Rectangular Table cost based on its dimension figure
*   l = length
*   w = width
*   d = drop
*   Fabric cost 	€ (euro) 16.10 per m2
*   Applique cost 	€ (euro) 1.45 per m2
*   Sewing cost 	€ (euro) 0.90 per m2
*/ 
function calRectangularTable(length, width, drop){
	
	// Converting variables to integer or float...
	l = parseFloat(length);
	w = parseFloat(width);
	d = parseFloat(drop);
	
	// Calculate all measurement
	var fabric 			= (l+d+d)*(w+d+d) / 10000;
	var hem    			= (d*8+l+l+w+w) / 100;
	var centerpiece 	= (l+l-122+w+w-122) / 100;
	var totalApplique 	= hem + centerpiece;
	var sewing			= totalApplique*2 - 0.8;
	
	
	// Calculate price for each above pieces depanding on its based cost.
	var fabricPrice 	= fabric *  $.cookie('recFabric');
	var appliquePrice	= totalApplique * $.cookie('recApplique');
	var sewingPrice		= sewing * $.cookie('recSewing');
	
	// Calculate fCost??
	var productCost 	= fabricPrice + appliquePrice + sewingPrice;
	
	// Add Margin
	var marginCookie = $.cookie('recMargin');
	var marginCost =  (productCost/ (100-marginCookie)) * marginCookie;
	productCost  +=	marginCost;		
	
	// Convert currency from Euro to Pounds
	productCost   = productCost / $.cookie('euro_rate');	
	
	// Add VAT
	productCost  += productCost * $.cookie('default_vat') / 100;
	
	// Return result
	return (productCost).toFixed(2);
}


/** Function is to calculate D-Shape Table cost based on its dimension figure
*   l = length
*   w = width
*   d = drop
*   Fabric cost 	€ (euro) 16.10 per m2
*   Applique cost 	€ (euro) 1.45 per m2
*   Sewing cost 	€ (euro) 1.55 per m2
*/ 
function calDShapeTable(length, width, drop){
	
	// Converting variables to integer or float...
	l = parseFloat(length);
	w = parseFloat(width);
	d = parseFloat(drop);
	
	// Calculate all measurement
	var fabric 			= (d*2+l)*(d*2+w) / 10000;
	var hem    			= ( (l-w)*2 + (d*2+w)*22/7 ) / 100;
	var centerpiece 	= ( (l-w)*2 + (w-61)*22/7 ) / 100;
	var totalApplique 	= hem + centerpiece;
	var sewing			= totalApplique * 2;
	
	
	// Calculate price for each above pieces depanding on its based cost.
	var fabricPrice 	= fabric *  $.cookie('dFabric');
	var appliquePrice	= totalApplique * $.cookie('dApplique');
	var sewingPrice		= sewing * $.cookie('dSewing');
	
	// Calculate fCost??
	var productCost 	= fabricPrice + appliquePrice + sewingPrice;
	
	// Add Margin
	var marginCookie = $.cookie('dMargin');
	var marginCost =  (productCost/ (100-marginCookie)) * marginCookie;
	productCost  +=	marginCost;	
	
	// Convert currency from Euro to Pounds
	productCost   = productCost / $.cookie('euro_rate');
	
	// Add VAT
	productCost  += productCost * $.cookie('default_vat') / 100;
	
	// Return result
	return (productCost).toFixed(2);
	
}

/** Function is to calculate Circular Table cost based on its dimension figure
*   l = length
*   d = drop
*   Fabric cost 	€ (euro) 16.10 per m2
*   Applique cost 	€ (euro) 1.45 per m2
*   Sewing cost 	€ (euro) 0.90 per m2
*/ 
function calCircularTable(diameter, drop){
	
	// Converting variables to integer or float...
	diameter = parseFloat(diameter);	
	d = parseFloat(drop);
	
	// Calculate all measurement
	var fabric 			= (diameter+d+d)*(diameter+d+d) / 10000;
	var hem    			= (diameter+d+d) * 22 / 700;
	var centerpiece 	= (diameter-66) * 22 / 700;
	var totalApplique 	= hem + centerpiece;
	var sewing			= totalApplique*2;
	
	
	// Calculate price for each above pieces depanding on its based cost.
	var fabricPrice 	= fabric *  $.cookie('roundFabric');
	var appliquePrice	= totalApplique * $.cookie('roundApplique');
	var sewingPrice		= sewing * $.cookie('roundSewing');
	
	// Calculate fCost??
	var productCost 	= fabricPrice + appliquePrice + sewingPrice;
	
	// Add Margin
	var marginCookie = $.cookie('roundMargin');
	var marginCost =  (productCost/ (100-marginCookie)) * marginCookie;
	productCost  +=	marginCost;
	
	// Convert currency from Euro to Pounds
	productCost   = productCost / $.cookie('euro_rate');
	
		
	// Add VAT
	productCost  += productCost * $.cookie('default_vat') / 100;
	
	// Return result
	return (productCost).toFixed(2);
	
}

/**
* Function to switch input size form for table page
*/


function switchSizeInputs(){	
	var parentElement = $('.calInput');	
	switch ($('input[name=tableClothsType]:checked').val()){
		case 'rectangular':
			$('li.classDiameter',parentElement).hide();
			$('li.classLength',parentElement).show();
			$('li.classWidth',parentElement).show();
			
		break;
		case 'd-shaped':
			$('li.classDiameter',parentElement).hide();
			$('li.classLength',parentElement).show();
			$('li.classWidth',parentElement).show();
			
		break;
		
		case 'round':
			$('li.classDiameter',parentElement).show();
			$('li.classLength',parentElement).hide();
			$('li.classWidth',parentElement).hide();
		break;					
	}		

}



/** Function to validate table form */
function validateTableForm(){

	var inputElements = $('.calInput');
	// Get variables from the input
	
	var length 		= parseFloat(inputElements.find('input[name="length"]').val());
	var width 		= parseFloat(inputElements.find('input[name="width"]').val());
	var drop 		= parseFloat(inputElements.find('input[name="drop"]').val());
	var diameter 	= parseFloat(inputElements.find('input[name="diameter"]').val());
	var quantity 	= parseFloat(inputElements.find('input[name="qty[]"]').val());
	
	// Table type
	var tableType = $('input[name="tableClothsType"]:checked').val();
	var productPrice = 0;
	var error = false;
	
	
	if (tableType == "round"){		
		
		// User selected round table .. so must have diameter
		if (diameter == 0 || isNaN(diameter)) inputElements.find('input[name="diameter"]').addClass("error");
		else inputElements.find('input[name="diameter"]').removeClass("error");		
		
		if (drop == 0 || isNaN(drop))	inputElements.find('input[name="drop"]').addClass("error");
		else inputElements.find('input[name="drop"]').removeClass("error");
		
		if ( (diameter == 0) || isNaN(diameter) || (drop ==0) || isNaN(drop) ) error = true;
		
	}else{		
		
		// User selected regtangular and D-shaped tabel .. so all other size : length, width and drop required		
		if (length == 0 || isNaN(length)) inputElements.find('input[name="length"]').addClass("error");
		else inputElements.find('input[name="length"]').removeClass("error");
		
		if (width == 0 || isNaN(width)) inputElements.find('input[name="width"]').addClass("error");
		else inputElements.find('input[name="width"]').removeClass("error");
		
		if (drop == 0 || isNaN(drop)) inputElements.find('input[name="drop"]').addClass("error");
		else inputElements.find('input[name="drop"]').removeClass("error");
		
		if ( (drop ==0) || (length==0) || (width == 0) || isNaN(length) || isNaN(width) || isNaN(drop) ) error = true;
	}
	
	// validate quantity
	if ( (quantity  == 0) || isNaN(quantity) ) {		
		inputElements.find('input[name="qty[]"]').addClass('error');
		error = true;
	}else{
		inputElements.find('input[name="qty[]"]').removeClass('error');
	}
	
	
	// All input is valid when we will check for the min and max length
	if (!error){
		
		
		// CONVERT TO CM IF INCHES OPTION IS SELECTED
		if ( $('#sizeSwitcher input[name="sizeSwitcher"]:checked').val() == "inch"){			
			length = convertInchToCm(length);
			width = convertInchToCm(width);
			drop = convertInchToCm(drop);
			diameter = convertInchToCm(diameter);
		}		
		
		var totalLength 	= drop*2 + length;
		var totalWidth		= drop*2 + width;
		var totalDiameter 	= drop*2 + diameter;
		var errorMsg = "";
		
		if (tableType != "round"){
			// For round table type			
			if (totalWidth<130 || totalWidth>254 || totalLength<130 || totalLength>2000){
				errorMsg  = '<p class="error">'	+
									'<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>'+
									'The table size you have entered will result in a tablecloth that is wider than the fabric will allow <br />' +
									'Please recheck your <strong>width</strong> and <strong>drop</strong> and retry. (Try reducing the drop)'+
									'If error persists please contact us for assistance.'+
								'</p>';
			}			
			if(width<90){
				errorMsg  = '<p class="error">'	+
									'<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>'+
									'The table width you have entered is less than the minimum 90cm (35”), which will not allow the placing of the appliqué centre piece.' +
									'In this instance please contact us for assistance.'+									
								'</p>';				
			}

			if( errorMsg != ""){
				$('.warning-popup').html(errorMsg).show();
				error = true;
				return !error;
			}
		}else{			
			// For regtangle + D-shape table
			if (totalDiameter<130 || totalDiameter>254){
				errorMsg  = '<p>'	+
									'<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>'+
									'The table size you have entered will result in a tablecloth that is wider than the fabric will allow <br />' +
									'Please recheck your <strong>diameter</strong> and <strong>drop</strong> and retry. (Try reducing the drop) <br /><br />'+
									'If error persists please contact us for assistance.'+
								'</p>';
			}

			if(diameter<90){
				errorMsg  = '<p class="error">'	+
									'<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>'+
									'The table diameter you have entered is less than the minimum 90cm (35”), which will not allow the placing of the appliqué centre piece.' +
									'In this instance please contact us for assistance.'+									
								'</p>';		
			}	
				
			if ( errorMsg != ""){
				$('.warning-popup').html(errorMsg).show();
				error = true;
				return !error;
			}
		}		
	}else{
		errorMsg  = '<p>'+
						'<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>'+
						'The highlight field(s) cannot be zero or left blank'+
					'</p>';
		$('.warning-popup').html(errorMsg).show();
	}
	
	if(!error) $('.warning-popup').html("").hide();
	
	return !error;
}



/** function to validate Table Cloths page before submitting to the basket 
********************************************************************/

function validateSubmitTableCloths(){
	
	$('#summarybox li.error').html("").hide();
	
	// Validate the table sizes
	errorMsg = "";
	
	if (!validateTableForm()){
		errorMsg = "error found!";
	}
	
	if (errorMsg == ""){ 
		$('.warning-popup').html("").hide();
		return true;
	}
	else{		
		return false;
	}
	
}




$(document).ready(function(){

	switchSizeInputs();
	
	// Switch input field when user select table's type
	$('input[name="tableClothsType"]').click(switchSizeInputs);
	
	
	// Switch measurement figures and display
	$('input[name="sizeSwitcher"]').click(
		function(){
			
			//Change the current displaying measurement type to the selected one [ inch or cm]
			$('span.measurement').text($(this).val());
			
			//Get closest parent element 'calculationBox'			
			var calculationBoxElem = $(this).closest('.calculationBox');
			
			var convert;
			
			switch ($('input[name="sizeSwitcher"]:checked').val()){
				case 'inch':		
					// set convert  cmToInch function to convert variable
					convert = convertCmToInch;
				break;
				case 'cm':
					// set convert  inchToCm function to convert variable
					convert = convertInchToCm;
				break;			
			}
			
			// Convert all current measurement input field to new values
			calculationBoxElem.find('input.sizeChangable').each(
				function(iterator, elem){							
					$(elem).val(
						convert($(elem).val()).toFixed(1)
					);
				}
			);			
		}
	);
		
	
	//do the calculation base on prices
	$('.calPrice').click(		
		function(){			
			
			//Validate the form fields
			if (!validateTableForm()) return false;
									
			var inputContainer = $(this).parent();
			
			// Get variables from the input
			var length 		= parseFloat(inputContainer.find('input[name="length"]').val());
			var width 		= parseFloat(inputContainer.find('input[name="width"]').val());
			var drop 		= parseFloat(inputContainer.find('input[name="drop"]').val());
			var diameter 	= parseFloat(inputContainer.find('input[name="diameter"]').val());
			var quantity 	= parseFloat(inputContainer.find('input[name="qty[]"]').val());
			
			var length_cm = 0;
			var width_cm = 0;
			var width_cm = 0;
			var diameter_cm = 0;
			
			
			// CONVERT TO CM IF INCHES OPTION IS SELECTED
			if ( $('#sizeSwitcher input[name="sizeSwitcher"]:checked').val() == "inch"){			
				length_cm = convertInchToCm(length);
				width_cm = convertInchToCm(width);
				drop_cm = convertInchToCm(drop);
				diameter_cm = convertInchToCm(diameter);
			}else{
				length_cm = length
				width_cm = width;
				drop_cm = drop;
				diameter_cm = diameter;
			}
			
			// Table type
			var tableType = $('input[name="tableClothsType"]:checked').val();
			var productPrice;
			var sizeType = $('#sizeSwitcher input[name="sizeSwitcher"]:checked').val();
									
			// Calculate product cost based on Table Type
			switch (tableType){
				case 'rectangular':										
					productPrice = calRectangularTable(length_cm,width_cm,drop_cm);
					var tableSizes = length.toFixed(1) + " x " + width.toFixed(1) + " x " + drop.toFixed(1) + sizeType;
				break;
				case 'd-shaped':
					productPrice = calDShapeTable(length_cm,width_cm,drop_cm);
					var tableSizes = length.toFixed(1) + " x " + width.toFixed(1) + " x " + drop.toFixed(1) + sizeType;
				break;
				
				case 'round':
					productPrice = calCircularTable(diameter_cm,drop_cm);
					var tableSizes = diameter.toFixed(1) + " x " + drop.toFixed(1) + sizeType;
				break;					
			}
			
			// Showing the results in Summary Box 			
			var summaryBoxEle = $('#summarybox'); // summary box containner			
			
			// Table type
			$(summaryBoxEle).find('#selectedShape >span').text(tableType);
			
			// table size figures			
			$(summaryBoxEle).find('#selectedMeasurement >span').text(tableSizes);
			
			// Quantity box			
			$(summaryBoxEle).find('#selectedQuantity >span').text(quantity);
						
			// Tablecloth dimensions
			var tableClothLenght 	= length + drop*2;			
			var tableClothWidth  	= width  + drop*2;
			var tableClothDiameters = diameter  + drop*2;
			
			if (tableType == "round"){
				$(summaryBoxEle).find('#selectedTableClothDimensions >span').text(tableClothDiameters.toFixed(1) + sizeType);
			}else{
				$(summaryBoxEle).find('#selectedTableClothDimensions >span').text(tableClothLenght.toFixed(1)+ ' x ' + tableClothWidth.toFixed(1) + sizeType);
			}
			
			// Total cost
			subTotal		= (productPrice * quantity).toFixed(2);
			sc_subTotal 	= priceSymbolFormating(currencyConvertor(subTotal));
			sc_productPrice = priceSymbolFormating(currencyConvertor(productPrice));
			
			$(summaryBoxEle).find('#totalCost').html('<span class="priceTag" title="'+subTotal+'">'+sc_subTotal+'</span>');
			$(summaryBoxEle).find('#unitPrice').html('<span class="priceTag" title="'+productPrice+'">'+sc_productPrice+'</span>');
		}	
	);
	
	
	/** 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;
	});
	
	
	/*MAGIC UTILITY   
	*****************************************************************************/
	
	// TO REMOVE ALL IMAGES WITH EMPTY SRC ATTRIBUTE
	$('img').each( function(){
		if ( $(this).attr('src') == "" ){
			$(this).hide();
		}
	});
	
});
