// 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(){
	function OrderDeliveryCountry(){
		$.post('/shippingOptions/getMethodPrice', { basket_id: $('#OrderBasketId').val(), country: $('#OrderDeliveryCountry option:selected').val() }, function(data){
			var $result = jQuery.parseJSON(data);
			$('#deliveryMethod').html($result.deliveryMethod);
			$('#deliveryPrice').html('£'+$result.deliveryPrice);			

			$.post('/checkout/paysVat', { id: $('#OrderDeliveryCountry option:selected').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: $('#OrderDeliveryCountry option:selected', this).val(), rand: Math.random() }, function(data){
				if(data == '1'){
					$('#incVat').html('(inc. VAT &amp; delivery)');
				} else {
					$('#incVat').html('(inc. delivery)');
				}
			});
		});
	}

	// Trip images
	if($('#tripImages').length > 0){
		$('#tripImages ul li img').click(function(){
			$('#tripMainImage img').attr('src', $(this).attr('id'));
			$('#tripMainImage div').html($(this).attr('alt'));
		});
	}
	
	
	if($('.fancybox').length > 0){
		$('.fancybox').fancybox();
	}
	// User registration
	if($('#UserAddForm').length > 0){
		$('#UserAddForm').submit(function(){
			if($('#UserPassword').val() == ''){
				$('#UserPassword').focus();
				alert('Password cannot be empty, please try again');
				return false;
			}
			if($('#UserPassword').val() != $('#UserConfirmPassword').val()){
				$('#UserPassword').val('').focus();
				$('#UserConfirmPassword').val('');
				alert('Passwords do not match, please try again');
				return false;
			}
		});
		
	}
	// My account edit use addresses
	if($('.same_as_billing').length > 0){
		$('.same_as_billing').click(function(){
			if($(this).val() == '1'){
				$billingInputs = $('#billingAddress input');
				$.each($billingInputs, function($index, $input){
					$('#deliveryAddress input:eq('+$index+')').val($('#billingAddress input:eq('+$index+')').val());
				});
				$billingTitle = $('#BillingAddressTitle option:selected').val();
				$options = $('#DeliveryAddressTitle option');
				$.each($options, function(){
					if($(this).val() == $billingTitle){
						$('#DeliveryAddressTitle option:eq('+$(this).index()+')').attr('selected', true);
					}
				});
				$billingCountry = $('#BillingAddressCountry option:selected').val();
				$options = $('#DeliveryAddressCountry option');
				$.each($options, function(){
					if($(this).val() == $billingCountry){
						$('#DeliveryAddressCountry option:eq('+$(this).index()+')').attr('selected', true);
					}
				});
			}
		});
	}
	// Delivery address user address edit
	
	if($('#deliveryAddress').length > 0){
		if($('#DeliveryAddressFirstName').val() != ''){
			$('#deliveryAddress').show();
		}
	}
	
	// Statecode
	if($('#OrderBillingStatecode').length > 0) {
		if($('#OrderBillingCountry option:selected').val() == 'UNITED STATES'){
			$('.statecode').show();
		} else {
			$('.statecode').hide();
		}
		$('#OrderBillingCountry').change(function(){
			if($('option:selected', this).val() == 'UNITED STATES'){
				$('.statecode').show();
			} else {
				$('.statecode').hide();
			}
		});
		if($('#OrderDeliveryCountry').val() == 'UNITED STATES'){
			$('.del_statecode').show();
		} else {
			$('.del_statecode').hide();
		}
	}
	
	if($('#UserStartDate').length > 0){		
		$('.datepicker').datepicker({ dateFormat: 'dd/mm/yy', showOtherMonths: true, selectOtherMonths: true});
	} else {
		$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd', showOtherMonths: true, selectOtherMonths: true});
	}
	
	// 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
	if($('#splash_tabs li:first a').attr('name') != ''){
		var splash_image = '<a href="'+$('#splash_tabs li:first a').attr('href')+'"><img src="'+$('#splash_tabs li:first a').attr('name')+'" alt="" /></a>';
	} else {
		var splash_image = '<a href="'+$('#splash_tabs li:first a').attr('href')+'"><img src="/img/homepage_splash_rufiji.jpg" alt="Rufiji - Outdoor apparel" /></a>';
	}
	$('#splash_image_area div').html(splash_image);
	var splash_starter_tab = 'splash_tab_rufiji';
	$('#splash_tabs li:first 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){
			if(currentTab.parent().attr('name') != ''){
				$('#splash_image_area div img').attr('src', currentTab.parent().attr('name')).attr('alt' , altText);
			} else {
				$('#splash_image_area div img').attr('src', '/img/homepage_splash_'+id+'.jpg').attr('alt' , altText);
			}
			$('#splash_image_area div a').attr('href', currentTab.parent().attr('href'));
		}
	});
	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($('#reason_'+$(this).attr('id')).length > 0){
			$('#inStock').html($('#reason_'+$(this).attr('id')).val()).show();			
		} else {
			if($(this).attr('title') !== undefined){
				$('#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.').show();
			} else { 
				$('#inStock').hide();
			}
		}
	});
	
	if($('ul.clothing_sizes > li').length > 0){
		var temp = $('.clothing_sizes:visible li.on');
		if($('#reason_'+temp.attr('id')).length > 0){
			$('#inStock').html($('#reason_'+temp.attr('id')).val().show());			
		} else {
			if(temp.attr('title') !== undefined){
				$('#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.').show();
			} else {
				$('#inStock').hide();
			}
		}
	}
	if($('#finalSize').length > 0){
		$('#finalSize').val($('.clothing_sizes:visible li.on').html());
	}
	// Clothing colours
	if($('.colours').length > 0){
		$('#productImages ul.'+$('.colours .on').attr('name')).show();
		var mainImage;
		$('#productImages a').hover(function(){
			mainImage = $('#main_image').attr('src');
			$('#main_image').attr('src', $(this).attr('name'));
		});
		
		$('ul.colours > li').mouseover(function(){
			$('ul.colours > li').removeClass();
			$(this).addClass('on');
			var id = $(this).attr('id');
			var imagePath = $(this).attr('name');
			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);
				$('#colour').val(id.replace(/_/, ' '));
				$('#finalSize').val($('.clothing_sizes:visible li.on').html());
				temp = $('#'+id+'_'+$('.clothing_sizes:visible li.on').html());
				if($('#reason_'+id).length > 0){
					$('#inStock').html($('#reason_'+id).val());	
				} else {
					if(temp.attr('title') !== undefined){
						$('#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.').show();
					} else {
						$('#inStock').hide();
					}
				}
			} else {
				$('#inStock').hide();
			}
		});
	}
	
	// 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(){
		BasketTotal();
	});
	
	if($('#shipping').length > 0 ){
		BasketTotal();
	}
	
	$('#_basket').click(function(){
		$('#basket').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){
		$billingInputs = $('#billingFields input');
		$.each($billingInputs, function($index, $input){
			$('#deliveryFields input:eq('+$index+')').val($('#billingFields input:eq('+$index+')').val());
		});
		$billingTitle = $('#OrderBillingTitle option:selected').val();
		$options = $('#OrderDeliveryTitle option');
		$.each($options, function(){
			if($(this).val() == $billingTitle){
				$('#OrderDeliveryTitle option:eq('+$(this).index()+')').attr('selected', true);
			}
		});
		$billingCountry = $('#OrderBillingCountry option:selected').val();
		$options = $('#OrderDeliveryCountry option');
		$.each($options, function(){
			if($(this).val() == $billingCountry){
				if($('#OrderBillingCountry option:selected').val() != $('#OrderDeliveryCountry option:selected').val()){
					$('#OrderDeliveryCountry option:eq('+$(this).index()+')').attr('selected', true);
					OrderDeliveryCountry();
				}
			}
		});
		$('#delivery_address').slideUp();		
	} else {
		$('#delivery_address').slideDown();		
	}
	// Same address as billing
	$('#OrderDeliveryToBilling').click(function(){
		if($('#OrderDeliveryToBilling:checked').length){
			$billingInputs = $('#billingFields input');
			$.each($billingInputs, function($index, $input){
				$('#deliveryFields input:eq('+$index+')').val($('#billingFields input:eq('+$index+')').val());
			});
			$billingTitle = $('#OrderBillingTitle option:selected').val();
			$options = $('#OrderDeliveryTitle option');
			$.each($options, function(){
				if($(this).val() == $billingTitle){
					$('#OrderDeliveryTitle option:eq('+$(this).index()+')').attr('selected', true);
				}
			});
			$billingCountry = $('#OrderBillingCountry option:selected').val();
			$options = $('#OrderDeliveryCountry option');
			$.each($options, function(){
				if($(this).val() == $billingCountry){
					if($('#OrderBillingCountry option:selected').val() != $('#OrderDeliveryCountry option:selected').val()){
						$('#OrderDeliveryCountry option:eq('+$(this).index()+')').attr('selected', true);
						OrderDeliveryCountry();
					}
				}
			});
			$('#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, .debit_credit_card span').click(function(){
		$('#OrderPaymentMethod').val('Debit/Credit Card');
		$('#returning_customer').hide();
		$('#bank_transfer').hide();
		$('#cheque').hide();
		$('#returning_customer').hide();
		$('#debit_credit_card').show();
		$.scrollTo('.order_now',500);
	});
	$('.cheque, .cheque span').click(function(){
		$('#OrderPaymentMethod').val('Cheque');
		$('#returning_customer').hide();
		$('#bank_transfer').hide();
		$('#debit_credit_card').hide();
		$('#returning_customer').hide();
		$('#cheque').show();
		$.scrollTo('.order_now',500);
	});
	$('.bank_transfer, .bank_transfer span').click(function(){
		$('#OrderPaymentMethod').val('Bank Transfer');
		$('#returning_customer').hide();
		$('#debit_credit_card').hide();
		$('#cheque').hide();
		$('#returning_customer').hide();
		$('#bank_transfer').show();
		$.scrollTo('.order_now',500);
	});
	
	$('.order_now').click(function(){
		$('.error').hide();
		if($('#UserNewPassword').length > 0){
			
		}
		if($('#OrderAgreedTerms:checked').length){
			var valid = true;
			var notNulls = $('.notNull:visible').get().reverse();
			jQuery.each(notNulls, function(){
				if($(this).val() == '' ||  $('option:selected', this).val() == ''){
					$(this).addClass('inputError');
					valid = false;
					$(this).focus();
				} else {
					$(this).removeClass('inputError');
				}
			});
			
			if($('#OrderBillingEmail').val() != $('#OrderBillingConfirmEmail').val() || !echeck($('#OrderBillingEmail').val())){
				$('#OrderBillingEmail').val('').focus();
				$('#OrderBillingConfirmEmail').val('');
				valid = false;
				$('#OrderBillingEmail').addClass('inputError');
			}
			if($('#OrderBillingCountry option:selected').val() == '192'){
				if($('#OrderBillingStatecode').val() == ''){
					$('#error_OrderBillingStateCode').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(){
			DeliveryPrice();
		});
		DeliveryPrice();
	}
	
	function DeliveryPrice(){
		if($('#delivery_country option:selected').val() != ''){
			var val = "<select id='shipping' name='shipping' disabled='disabled'><option>Please wait</option></select>";
			$('#shipping').parent().html(val);
			$('#temp_delivery_country').val($('#delivery_country option:selected').val());
			var t = $('#delivery_country');
			$.post('/shippingOptions/getShippingZoneByCountry', { country: $('#delivery_country option:selected').val() }, function(data){
				$('#zone').val(data);
				$.post('/shippingOptions/getShippingOptionsByCountry', { discountCode: $('#BasketDiscountCode').val(), total: $('#subtotal').val(), country: $('option:selected', t).val() }, function(data){
					var par = $('#td_shipping');
					par.html(data);
					BasketTotal();
				});
			});
		}
	}
	
	// Address change billing address
	
	if($('#OrderDeliveryCountry').length > 0){
		$('#OrderDeliveryCountry').change(function(){
			OrderDeliveryCountry();
		});
		$('#OrderBillingCountry').change(function(){
			if($('#OrderDeliveryToBilling:checked').length > 0){
				$billingCountry = $('#OrderBillingCountry option:selected').val();
				$options = $('#OrderDeliveryCountry option');
				$.each($options, function(){
					if($(this).val() == $billingCountry){
						$('#OrderDeliveryCountry option:eq('+$(this).index()+')').attr('selected', true);
						OrderDeliveryCountry();
					}
				});
			}
		});
	}
});

function BasketTotal(){
	// 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(){
		BasketTotal();
	});
	
}

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(); 
} 
