// JavaScript Document

// General

function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   } else {
			return true;
	 }
}

function strpos( haystack, needle, offset){
    var i = (haystack+'').indexOf( needle, offset ); 
    return i===-1 ? false : i;
}


$(function(){
	$('.datepicker').datepicker({ dateFormat: 'dd/mm/yy'});
	// MAIN NAV styling
	$('a', 'li.headlink ul li:last-child').addClass('last');
	$('li.headlink').hover(
		function() { 
			$('ul', this).css('display', 'block');
			$('a', this).addClass('on');
		},
		function() { 
			$('ul', this).css('display', 'none'); 
			var bg = $('span', this).css('background-image');
			$('a', this).removeClass('on');
		}
	);
	
	// HOMEPAGE SPLASH TABS ROLLOVER
	var splash_image = '<img src="/img/homepage_splash_rufiji.jpg" alt="Rufiji - Outdoor apparel" />';
	$('#splash_image_area div').html(splash_image);
	var splash_starter_tab = 'splash_tab_rufiji';
	$('#splash_tab_rufiji span').css('background-position', '0px 0px');
	
	$('#splash_tabs li a span').hover(function(){
		var id = $(this).parent().attr('id').substr(11);
		var currentTab = $(this);
		var altText = $(this).parent().attr('title');
		var splash_image = '<img src="" alt="='+altText+'" />';
		var currentImg = $('#splash_image_area div').html();
		$('#splash_tabs li a span').css('background-position', '0px -69px');
		currentTab.css('background-position', '0px 0px');
		if(splash_image != currentImg){
			$('#splash_image_area div img').attr('src', '/img/homepage_splash_'+id+'.jpg').attr('alt' , altText);
		}
	});
	if($('#homepage_packing_email').length > 0 ){
		if(!$('#homepage_packing_email').val()){
			$(this).css('background-position', '0px 0px');
		}
	}
	
	// PACKING LIST HOMPAGE FOCUS
	$('#homepage_packing_email').focus(function() {
		$(this).css('background-position', '0px 0px');
	});
	$('#homepage_packing_email').blur(function() {
		if($(this).val()==''){
			$(this).css('background-position', '0px -23px');
		}
	});
	
	// Login submit
	$('.login').click(function(){
		$(this).parent().submit();
	});	
	
	$('.cancel').click(function(){
		window.location = $(this).attr('name');												 
	});
	
	// Expanding Areas
	var temp = $('.expandMe').parent().parent();	
	$('div:eq(1)', temp).hide();
	$('.expandMe').toggle(function(){
		var temp = $(this).parent().parent();	
		$('div:eq(1)', temp).slideDown();	
	}, function(){
		var temp = $(this).parent().parent();	
		$('div:eq(1)', temp).slideUp('slow');									 
	});
	
	
	// Clothing sizes
	$('ul.clothing_sizes > li').not('.out').click(function(){
		$(this).parent().children().not('.out').removeClass();
		$(this).addClass('on');
		$('#finalSize').val($(this).html());
		if($(this).attr('title') != ''){
			$('#inStock').html('<strong>This Size is temporarily out of stock.</strong> New stock arriving <strong>'+$(this).attr('title')+'</strong>. You are still able to order this item, and it will be placed on back order for you.');
		} else { 
			$('#inStock').html('&nbsp;<br />&nbsp;');
		}
	});
	
	if($('ul.clothing_sizes > li').length > 0){
		var temp = $('.clothing_sizes:visible li.on');
		if(temp.attr('title') != ''){
			$('#inStock').html('<strong>This Size is temporarily out of stock.</strong> New stock arriving <strong>'+temp.attr('title')+'</strong>. You are still able to order this item, and it will be placed on back order for you.');
		} else {
			$('#inStock').html('&nbsp;<br />&nbsp;');
		}
	}
	$('ul.clothing_sizes > li').not('.out').click(function(){
		$(this).parent().children().not('.out').removeClass();
		$(this).addClass('on');
		$('#finalSize').val($(this).html());
		if($(this).attr('title') != ''){
			$('#inStock').html('<strong>This Size is temporarily out of stock.</strong> New stock arriving <strong>'+$(this).attr('title')+'</strong>. You are still able to order this item, and it will be placed on back order for you.');
		} else {
			$('#inStock').html('&nbsp;<br />&nbsp;');
		}
	});
	
	if($('#finalSize').length > 0){
		$('#finalSize').val($('.clothing_sizes:visible li.on').html());
	}
	// Clothing colours
	$('ul.colours > li').mouseover(function(){
		$('ul.colours > li').removeClass();
		$(this).addClass('on');
		var id = $(this).attr('id');
		var imagePath = $(this).attr('title');
		if(imagePath){
			imagePath = '/img/products/big/'+imagePath;
			$('#main_image').attr('src', imagePath);
		}
		id = id.substr(7);
		temp = id.replace(/_/, ' ');
		$('#colour').val(temp);
		if($('#'+id+'_size li').length > 0){
			$('.clothing_sizes').hide();
			$('#'+id+'_size').show();
			//pos = strpos(id, '_');
			//id = id.substr(pos);
			id = id.replace(/_/, ' ');
			$('#colour').val(id);
			$('#finalSize').val($('.clothing_sizes:visible li.on').html());
			var temp = $('.clothing_sizes:visible li.on');
			if(temp.attr('title') != ''){
				$('#inStock').html('<strong>This Size is temporarily out of stock.</strong> New stock arriving <strong>'+temp.attr('title')+'</strong>. You are still able to order this item, and it will be placed on back order for you.');
			} else {
				$('#inStock').html('&nbsp;<br />&nbsp;');
			}
		}
	});
	
	//Add to Basket Clothing
	$('.add_to_basket_clothing').click(function(){
		$('#BasketAddForm').submit();										
	});
	
	$('.add_to_basket').click(function(){
		$(this).parent().submit();																	 
	});
	$('#add_to_basket_luggage').click(function(){
		$('#BasketAddForm').submit();																			 
	});
	
	$('.add_to_basket').click(function(){
		$('#BasketAddForm').submit();																	 
	});

	// Check quantity input contains only numbers
	$('.input_quantity').keyup(function(){
			while(isNaN($(this).val())){
				clearFields($(this));
			}
	});
	
	if($('#discount_code').length){
		if($('#discount_code').val() != ''){
			$(this).css('background', '#FFF');
		} else {
			$(this).css('background', '#FFF url(/img/text_enter_your_code.jpg) 5px 4px no-repeat');	
		}
	}
	
	// Discount code validation
	$('#discount_code').keyup(function(){
		if($(this).val() != ''){
			$(this).css('background', '#FFF');
		} else {
			$(this).css('background', '#FFF url(/img/text_enter_your_code.jpg) 5px 4px no-repeat');
		}
	});
	
	$('#discount_code').blur(function(){
		if($(this).val() != ''){
			$(this).css('background', '#FFF');
		} else {
			$(this).css('background', '#FFF url(/img/text_enter_your_code.jpg) 5px 4px no-repeat');
		}
	});
	
	// UPDATE SHIPPING METHOD
	$('#td_shipping select').change(function(){
		updateBasketTotal();
	});
	
	if($('#shipping').length > 0 ){
		updateBasketTotal();
	}
	
	// REMOVE FROM BASKET
	$('.remove').click(function(){
	
	});
	
	$('.update').click(function(){
		$('#basket').submit();
	});
	
	$('ul.buttons a.submit').click(function(){
		$('#orderForm').submit();												 
	});
	
	$('.thickbox_close').click(function(){
		tb_remove();																		
	});
	//Rental calculations
	$('#rental_quantity').change(function(){
		qty = $(this).val();
		weeks = $('#rental_weeks option:selected').val();
		$('#unit_weeks').val(weeks);
		price = $('#priceIncVAT').val();
		total = ((price*1)*(weeks*1)*(qty*1)).toFixed(2);
		$('.largePrice').html('&pound;'+total);
	});
	$('#rental_weeks').change(function(){
		weeks = $(this).val();
		$('#unit_weeks').val(weeks);
		qty = $('#rental_quantity option:selected').val();
		price = $('#priceIncVAT').val();
		total = ((price*1)*(weeks*1)*(qty*1)).toFixed(2);
		$('.largePrice').html('&pound;'+total);
	});
	
	// Checkout process
	// Different delivery address
	$('#add_different_address').click(function(){
		//$(this).parent().hide();
		$('#delivery_address').slideDown();	
	});
	if($('#OrderDeliveryToBilling:checked').length){
		$('#delivery_address').slideUp();		
	} else {
		$('#delivery_address').slideDown();		
	}
	// Same address as billing
	$('#OrderDeliveryToBilling').click(function(){
		if($('#OrderDeliveryToBilling:checked').length){
			$('#delivery_address').slideUp();		
		} else {
			$('#delivery_address').slideDown();		
		}
	});
	
	$('#remember_me').click(function(){
		if($('#remember_me:checked').length >=1){
			$('#remember_me_password').slideDown();	
		} else {
			$('#remember_me_password').slideUp();	
		}
	});
	
	$('.debit_credit_card').click(function(){
		$('#OrderPaymentMethod').val('Debit/Credit Card');
		$('#returning_customer').hide();
		$('#bank_transfer').hide();
		$('#cheque').hide();
		$('#returning_customer').hide();
		$('#debit_credit_card').show();
		$.scrollTo('#order_summary',500);
	});
	$('.cheque').click(function(){
		$('#OrderPaymentMethod').val('Cheque');
		$('#returning_customer').hide();
		$('#bank_transfer').hide();
		$('#debit_credit_card').hide();
		$('#returning_customer').hide();
		$('#cheque').show();
		$.scrollTo('#order_summary',500);
	});
	$('.bank_transfer').click(function(){
		$('#OrderPaymentMethod').val('Bank Transfer');
		$('#returning_customer').hide();
		$('#debit_credit_card').hide();
		$('#cheque').hide();
		$('#returning_customer').hide();
		$('#bank_transfer').show();
		$.scrollTo('#order_summary',500);
	});
	
	$('.order_now').click(function(){
		$('.error').hide();
		if($('#OrderAgreedTerms:checked').length){
			var valid = true;
			var notNulls = $('.not_null:visible');
			jQuery.each(notNulls, function(){
				if($(this).val() == '' ||  $('option:selected', this).val() == ''){
					$('#error_'+$(this).attr('id')).slideDown();
					valid = false;
				}
			});
			// validate email and confirmation email addresses
			if(valid == true){
				if(!echeck($('#OrderEmail').val())){
						$('#error_OrderEmail_valid').slideDown();
						valid = false;
				}
				if(!echeck($('#OrderConfirmEmail').val())){
						$('#error_OrderConfirmEmail_valid').slideDown();
						valid = false;
				}
			}
			// Check that email and confirmation email match
			if(valid == true){
				if($('#OrderEmail').val() != $('#OrderConfirmEmail').val()){
					$('#error_OrderEmail_match').slideDown();
					$('OrderConfirmEmail').val('');
					valid = false;
				}
			}
			// Validate start date
			if(valid == true){
				if($('#OrderStartDateYear option:selected').val() != ''){
					var myDate = new Date();
					var currentYear = myDate.getUTCFullYear();
					var currentMonth = PadDigits(myDate.getUTCMonth()+1, 2);
					if(currentYear == $('#OrderStartDateYear').val()){
						if(currentMonth < $('#OrderStartDateMonth').val()){
							$('#error_OrderStart').slideDown();
							valid = false;
						}
					}
				}
				
				// Validate expiry date
				var myDate = new Date();
				var currentYear = myDate.getUTCFullYear();
				var currentMonth = PadDigits(myDate.getUTCMonth()+1, 2);
				if(currentYear == $('#OrderExpiryDateYear').val()){
					if(currentMonth > $('#OrderExpiryDateMonth').val()){
						$('#error_OrderExpiry_past').slideDown();
						valid = false;
					}
				}
				
				// Validate security code
				if($('#OrderSecurityCode:visible').length){
					if(isNaN($('#OrderSecurityCode').val())){
						$('#error_OrderSecurityCode_valid').slideDown();
						valid = false;
					} else if($('#OrderSecurityCode').val().length < 3 || $('#OrderSecurityCode').val().length > 4){
						$('#error_OrderSecurityCode_valid').slideDown();
						valid = false;
					}
					
					// Validate card number
					if(isNaN($('#OrderCardNo:visible').val())){
						$('#error_OrderCardNo').slideDown();
						valid = false;
					} else if($('#OrderCardNo').val().length < 8 || $('#OrderCardNo').val().length > 18){
						$('#error_OrderCardNo').slideDown();
						valid = false;
					}
				}
			}
			if(valid == true){
				$('#orderForm').submit();		
			}
		} else {
			alert('You must to agree to our terms and conditions to complete your order.');
			$('#agreeToTermsLink').focus();
		}					 
	});
	$('#go_to_checkout').click(function(){
		if($('#delivery_method').val() == ''){
			alert('Please select your delivery country');
			$('#delivery_country').focus();
			return false;
		}
		$('#basketOrderForm').submit();																		
	});
	
	// Homepage packing list email send
	$('#homepage_packing_list_send').click(function(){
		$('#packingListForm').ajaxSubmit({
			success: function(responseText, responseCode) {
				$('#packing_list_email').html('<p>Your packing list has been emailed to: <br /> <strong>'+$('#homepage_packing_email').val()+'</strong></p>').fadeIn();	
			}
		});
	});
	
	$('#send_it').click(function(){
		var inputs = $('input.notNull, textarea.notNull');
		$('input.notNull').removeClass('empty');
		var ctn = 1;
		jQuery.each(inputs, function() {
			if($(this).val() == ''){
				if(ctn == 1){
					$(this).focus();
				}
				$(this).addClass('empty');
				ctn = 0;
			}
    });
		
		if(!echeck($('#UserEmail').val())){
			$('#UserEmail').addClass('empty');
			if(ctn == 1){
				$('#UserEmail').focus();
			}
			return false;													 
		}
		if($('#UserConfirmEmail').val() != $('#UserEmail').val()){
			$('#UserEmail').addClass('empty');
			$('#UserConfirmEmail').addClass('empty').val('');
			if(ctn == 1){
			$('#UserConfirmEmail').focus();
			}
			return false;
		}
		if(ctn == 0){
			return false;
		}
		$('#contactForm').submit();										 
	});
	
	//Apply discount
	$('#apply_discount').click(function(){
		$('#basket').submit();													
	});
	
	
	$('a.submit').click(function(){
		var temp = $(this).attr('id').split('_');
		var id = temp[1];
		$('form#orderForm_'+id).submit();
	});
	
	// Select shipping charge
	if($('#delivery_country').length > 0 && $('#shipping').length > 0){
		$('#delivery_country').change(function(){
			var val = "<select id='shipping' name='shipping' disabled='disabled'><option>Please wait</option></select>";
			$('#shipping').parent().html(val);
			$('#temp_delivery_country').val($('option:selected', this).val());
			var t = $(this);
			$.post('/shippingOptions/getShippingZoneByCountry', { country: $('option:selected', this).val() }, function(data){
				$('#zone').val(data);
				$.post('/shippingOptions/getShippingOptionsByCountry', { country: $('option:selected', t).val() }, function(data){
					var par = $('#td_shipping');
					par.html(data);
					updateBasketTotal();
				});
			});
		});
	}
	
	// Address change billing address
	if($('#OrderDeliveryCountry').length > 0){
		$('#OrderDeliveryCountry').change(function(){
			$.post('/checkout/paysVat', { id: $('option:selected', this).val(), rand: Math.random() }, function(data){
				data = data*1;
				$('#orderTotal').html('&pound;'+data.toFixed(2));
				var gV = $('#giftVoucherAmount').val()*1;
				$('#paymentTotal').html('&pound;'+(data-gV).toFixed(2));
			});
			$.post('/checkout/paysVatBoolean', { id: $('option:selected', this).val(), rand: Math.random() }, function(data){
				if(data == '1'){
					$('#incVat').html('(inc. VAT &amp; delivery)');
				} else {
					$('#incVat').html('(inc. delivery)');
				}
			});
		});
	}
});

function updateBasketTotal(){
	// Do not change as it will break the checkout/index page, cake doesn't like js to change fields in a secure section
	var shippingPrice = $('#td_shipping select option:selected').val()*1;
	if(isNaN(shippingPrice)){
		shippingPrice = 0;
	}
	var total = $('#original_total').val()*1;
	var voucher = $('#gift_voucher_amount').val()*1;
	if($('#zone').val() > 2){
		$('#vat_row').hide();
		$('#shipping_price').html('&pound;'+shippingPrice);
		total = total+shippingPrice;
		$('#subtotal').val($('#original_total').val());
		$('#delivery_price').val(shippingPrice);
		$('#vat').val(0);
		$('#vat_total').html('0.00');
		$('#total').html((total-voucher).toFixed(2));
	} else {
		$('#vat_row').show();
		var vatRate = $('#vatRate').val()*1;
		$('#shipping_price').html('&pound;'+shippingPrice);
		shipVat = shippingPrice*(vatRate/100);
		$('#subtotal').val($('#original_total').val());
		$('#delivery_price').val(shippingPrice);
		var vatAmount = ($('#vatTotal').val()*1)+shipVat;
		if(vatAmount < 0){
			vatAmount = 0;
		}
		$('#vat').val(vatAmount.toFixed(2));
		if(total < 0){
			total = 0;
		}
		$('#vat_total').html(vatAmount.toFixed(2));
		$('#total').html((total+shippingPrice+vatAmount-voucher).toFixed(2));
	}
	var del_method = $('#td_shipping select option:selected').html();
	if(del_method){
		del_method = del_method.split('(');
		$('#delivery_method').val(del_method[0]);
	}
	$('#td_shipping select').unbind();
	
	$('#td_shipping select').change(function(){
		updateBasketTotal();
	});
	
}

function clearFields(element){
	// Is not a number
	len = element.val().length;
	var ret = element.val().substr(0, len-1);
	element.val(ret);
}	

$(function(){
	$('.register').click(function(){
		$(this).parent().submit();
	});
});

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	 return false
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	 return false
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}
	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}
	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}
	if (str.indexOf(" ")!=-1){
		return false
	}
	return true					
}

function PadDigits(n, totalDigits) { 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) { 
			pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
} 