
united_states_id = 190; // used for billing and shipping addresses

var regexDigit=/^\d{1,5}$/

function recalculateWholesaleSubtotals() {
	subtotal = 0;
	$('.wholesale_quantity').each(function(intIndex) {
		thisId = $(this).attr('id').substring(9); // get the product id to access other elements
		subtotal += $(this).val() * $('#price_' + thisId).val();
	});
	$('#subtotal').text(subtotal.toFixed(2));
	
	
	
	var discountPercentage = 0;
	
	if (subtotal <= 50) {
		discountPercentage = 45;		
	} else if (subtotal <= 75) {
		discountPercentage = 47;
	} else {
		discountPercentage = 50;
	}
	
	$('.wholesale_quantity').each(function(intIndex) {
		thisId = $(this).attr('id').substring(9); // get the product id to access other elements
		productTotal = $(this).val() * $('#price_' + thisId).val();
		productDiscount = productTotal * (discountPercentage / 100);
		$('#total_' + thisId).text('$'+(productTotal - productDiscount).toFixed(2));
		$('#wholesale_price_' + thisId).text('$'+($('#price_' + thisId).val() - ($('#price_' + thisId).val() * (discountPercentage / 100))).toFixed(2));
	});
	
	discount = subtotal * (discountPercentage / 100);
	subtotalLessDiscount = subtotal - discount;
	
	$('#discount_percent').text(discountPercentage);
	$('#discount').text(discount.toFixed(2));	
	$('#subtotal_less_discount').text(subtotalLessDiscount.toFixed(2));
	
}

$(document).ready(function() {  
	
	removeNotices();
	
	$('input#coupon_code').focus(function() {
		if ($('input#coupon_code').val() == "have a coupon code?") {
			$('input#coupon_code').val('');
			$('input#coupon_code').css('color', '#000000');
		}
	});
	
	$('input#coupon_code').blur(function() {
		if ($('input#coupon_code').val() == "") {
			$('input#coupon_code').val('have a coupon code?');
			$('input#coupon_code').css('color', '#cccccc');
		}
	});
	
	$('.wholesale_quantity').change(function() {
		if ($(this).val().search(regexDigit)==-1 && $(this).val() != "") {
			alert('Please enter a valid quantity');
			$(this).val('');
		} else {
			thisId = $(this).attr('id').substring(9);
			newTotal = $(this).val() * $('#price_' + thisId).val();
			$('#total_' + thisId).text('$' + newTotal.toFixed(2));
		}
		recalculateWholesaleSubtotals();		
	})
	
	$('#join_button').click(function(){ 
		$.ajax({
			url: '/_ajax_subscribe.php',
			type: "POST",
			data: ({email : $('#subscriber_email').val()}),
			success: function(data) {
				$('#subscribe_form').html(data);
			}
		});
	});
	
	$('.email').click(function(){ 
		fake_string = $(this).attr('href');
		email_arr = fake_string.split('/',3);
		$(this).attr('href','mailto:' + email_arr[1] + '@' + email_arr[2]);
	});
	
	$('.thumb').click(
		function () {               
			new_image_id = $(this).attr('id').substring(2);
			old_image_id = $('.image_on').attr('id').substring(2);
			content_top = $('#i_' + new_image_id).height() + 8;
	    	$('#product_thumbs').animate({ 
				marginTop: content_top+"px"
			}, 750);
		  	$('.image_on').fadeOut(750);			
			$('.image_on').removeClass('image_on');
			$('.image_on').addClass('image_off');
			$('#i_' + new_image_id).fadeIn(750);
			$('#i_' + new_image_id).removeClass('image_off');
			$('#i_' + new_image_id).addClass('image_on');
			$('#t_' + new_image_id).removeClass('thumb_off');
			$('#t_' + new_image_id).addClass('thumb_on');
			$('#t_' + old_image_id).removeClass('thumb_on');
			$('#t_' + old_image_id).addClass('thumb_off');
		}
    ); 


	$('.thumb').hover(
		function () {
			$(this).addClass('thumb_hover');
		}, 
		function () {
			$(this).removeClass('thumb_hover');
		}
    );

	$('#top_menu li').hover(
		function () {
			$(this).addClass('top_menu_hover');
			$(this).find('ul').show();
		}, 
		function () {
			$(this).removeClass('top_menu_hover');
			$(this).find('ul').hide();
		}
    ); 
    
	$('form#product').submit(function() { 
		if ($('form#product').attr('action') == "") {
			addToCart();			
			return false;
		}
	});
	
	$('form#wholesale').submit(function() { 
		if ($('form#wholesale').attr('action') == "") {
			addMultiToCart();			
			return false;
		}
	});

	$('form#edit_account').submit(function() { 
		if ($('form#edit_account').attr('action') == "") {
			accountSave();			
			return false;
		}
	});
	
	$('form#register').submit(function() { 
		if ($('form#register').attr('action') == "") {
			accountRegister();			
			return false;
		}
	});  

	$('form#login').submit(function() { 
		if ($('form#login').attr('action') == "") {
			accountLogin();			
			return false;
		}
	});
	
	$('form#login input').keypress(function(e){
      if(e.which == 13) {
       	$('form#login').submit();
	  }
	});
	
	$('form#send_reset_link').submit(function() { 
		if ($('form#send_reset_link').attr('action') == "") {
			sendResetLink();			
			return false;
		}
	});
	
	$('form#password_reset').submit(function() { 
		if ($('form#password_reset').attr('action') == "") {
			passwordReset();			
			return false;
		}
	}); 
	
	$('select#shipping_country').change(function() { 
		if ($('select#shipping_country').val() == united_states_id) {
		       	$('#shipping_state_province_label').text('State'); 
			$('#shipping_zip_postal_code_label').text('Zip code');
			$('#shipping_state').show();
			$('#shipping_province').hide();
			if ($('#shipping_phone_prefix').val() == "") {
				$('#shipping_phone_prefix').val('1');
			}
		} else {
			$('#shipping_state_province_label').text('Province');
			$('#shipping_zip_postal_code_label').text('Postal code');
			$('#shipping_state').hide();
			$('#shipping_province').show();
			if ($('#shipping_phone_prefix').val() == "1") {
				$('#shipping_phone_prefix').val('');
			}
		}
	});
	
	$('select#billing_country').change(function() { 
		if ($('select#billing_country').val() == united_states_id) {
		       	$('#billing_state_province_label').text('State'); 
			$('#billing_zip_postal_code_label').text('Zip code');
			$('#billing_state').show();
			$('#billing_province').hide(); 
			if ($('#billing_phone_prefix').val() == "") {
				$('#billing_phone_prefix').val('1');
			}
		} else {
			$('#billing_state_province_label').text('Province');
			$('#billing_zip_postal_code_label').text('Postal code');
			$('#billing_state').hide();
			$('#billing_province').show();
			if ($('#billing_phone_prefix').val() == "1") {
				$('#billing_phone_prefix').val('');
			}
		}
	});
	
});

function addToCart() {   
	$('form#product').attr('action','/cart/add');		
	$('form#product').submit();
}

function addMultiToCart() {   
	$('form#wholesale').attr('action','/cart/add-multi');		
	$('form#wholesale').submit();
}  

function updateCart() { 
	$('form#cart').attr('action','/cart/update');
	$('form#cart').submit();
}

function emptyCart() {
	window.location = "/cart/empty";
} 

function updateCartAndCheckout(method) { 
	$('form#cart').attr('action','/cart/update'); 
	$('input#cart_action').val('checkout-' + method);
	$('form#cart').submit();
} 

function checkoutPlaceOrder() {
	$('form#checkout').attr('action','/checkout/save'); 
	$('input#checkout_action').val('place_order');
	$('form#checkout').submit();
}

function checkoutSaveAddresses() { 
	
	var formValid = true;
	var formMessage = "";
	
	validating = setTimeout(function() {
		
		if ($('#is_logged_in').val() == "false" && $('#email').val() == "") {
			formValid = false;
			formMessage += "You need an email address, or log in. ";
		}
		
		if ($('#billing_first_name').val() == "") {
			formValid = false;
			formMessage += "You need a billing first name. ";
		}
		
		if ($('#billing_last_name').val() == "") {
			formValid = false;
			formMessage += "You need a billing last name. ";
		}
		
		if ($('#billing_country').val() == "") {
			formValid = false;
			formMessage += "You need a billing country. ";
		}
		
		if ($('#billing_address_1').val() == "") {
			formValid = false;
			formMessage += "You need a billing street address. ";
		}
		
		if ($('#billing_city').val() == "") {
			formValid = false;
			formMessage += "You need a billing city. ";
		}
		
		if ($('#billing_country').val() == united_states_id && $('#billing_state').val() == "") {
			formValid = false;
			formMessage += "You need a billing state. ";
		}
		
		if ($('#billing_country').val() == united_states_id && $('#billing_postal_code').val() == "") {
			formValid = false;
			formMessage += "You need a billing zip code. ";
		}
		
		if ($('#billing_country').val() != united_states_id && $('#billing_postal_code').val() == "") {
			formValid = false;
			formMessage += "You need a billing postal code. ";
		} 
		  
		if ($('#billing_phone_prefix').val() == "") {
			formValid = false;
			formMessage += "You need a billing phone international prefix. ";
		}
		
		if ($('#billing_phone_number').val() == "") {
			formValid = false;
			formMessage += "You need a billing phone number. ";
		}
		                             
		if ($('#use_billing').val() != "on") {
			
			if ($('#shipping_first_name').val() == "") {
				formValid = false;
				formMessage += "You need a shipping first name. ";
			}

			if ($('#shipping_last_name').val() == "") {
				formValid = false;
				formMessage += "You need a shipping last name. ";
			}

			if ($('#shipping_country').val() == "") {
				formValid = false;
				formMessage += "You need a shipping country. ";
			}

			if ($('#shipping_address_1').val() == "") {
				formValid = false;
				formMessage += "You need a shipping street address. ";
			}

			if ($('#shipping_city').val() == "") {
				formValid = false;
				formMessage += "You need a shipping city. ";
			}

			if ($('#shipping_country').val() == united_states_id && $('#shipping_state').val() == "") {
				formValid = false;
				formMessage += "You need a shipping state. ";
			}

			if ($('#shipping_country').val() == united_states_id && $('#shipping_postal_code').val() == "") {
				formValid = false;
				formMessage += "You need a shipping zip code. ";
			}

			if ($('#shipping_country').val() != united_states_id && $('#shipping_postal_code').val() == "") {
				formValid = false;
				formMessage += "You need a shipping postal code. ";
			}
			
			if ($('#shipping_phone_prefix').val() == "") {
				formValid = false;
				formMessage += "You need a shipping phone international prefix. ";
			}

			if ($('#shipping_phone_number').val() == "") {
				formValid = false;
				formMessage += "You need a shipping phone number. ";
			}
			
		}
	
		if (formValid == true) { 
			$('form#checkout').attr('action','/checkout/save'); 
			$('input#checkout_action').val('address');
			$('form#checkout').submit();
		} else {       
			formMessage += "Please fix and resubmit. ";
			$('div#error p').html(formMessage);
			$('div#error').slideDown(750);
		}
	
	}, 10);
	
} 

function checkoutSaveShipping() { 
	
	var formValid = true;
	var formMessage = "";
	
	validating = setTimeout(function() {
		
		if (!$('input[name=shipmethod_id]:checked').val() > 0) {
			formValid = false;
			formMessage += "Please select a shipping option. ";
		}
	
		if (formValid == true) { 
			$('form#checkout').attr('action','/checkout/save'); 
			$('input#checkout_action').val('shipping');
			$('form#checkout').submit();
		} else {       
			formMessage += "Please fix and resubmit. ";
			$('div#error p').html(formMessage);
			$('div#error').slideDown(750);
		}
	
	}, 10);
	
	
}

function checkoutSavePayment() { 
	
	var formValid = true;
	var formMessage = "";
	
	validating = setTimeout(function() {
		
		if ($('#cc_type').val() == "") {
			formValid = false;
			formMessage += "Select a credit card type. ";
		}
		
		if ($('#cc_type').val() == "Amex" && $('#cc_number').val().length != 15) {
			formValid = false;
			formMessage += "Enter 15-digit card account number. ";
		}
		
		if (($('#cc_type').val() == "Visa" || $('#cc_type').val() == "MasterCard" || $('#cc_type').val() == "Discover") && $('#cc_number').val().length != 16) {
			formValid = false;
			formMessage += "Enter 16-digit card security code. ";
		}
		
		if ($('#cc_type').val() == "" && $('#cc_id').val() == "") {
			formValid = false;
			formMessage += "Enter your card account number. ";
		}
		
		if ($('#cc_exp_month').val() == "") {
			formValid = false;
			formMessage += "Enter your card's expiration month. ";
		}
		
		if ($('#cc_exp_year').val() == "") {
			formValid = false;
			formMessage += "Enter your card's expiration year. ";
		}
		
		if ($('#cc_type').val() == "Amex" && $('#cc_id').val().length != 4) {
			formValid = false;
			formMessage += "Enter 4-digit card security code from the front of your card. ";
		}
		
		if (($('#cc_type').val() == "Visa" || $('#cc_type').val() == "MasterCard" || $('#cc_type').val() == "Discover") && $('#cc_id').val().length != 3) {
			formValid = false;
			formMessage += "Enter 3-digit card security code from the back of your card. ";
		}
	
		if (formValid == true) { 
			$('form#checkout').attr('action','/checkout/save'); 
			$('input#checkout_action').val('payment');
			$('form#checkout').submit();
		} else {       
			formMessage += "Please fix and resubmit. ";
			$('div#error p').html(formMessage);
			$('div#error').slideDown(750);
		}
	
	}, 10);
	
	
}

function accountRegister() { 

	var formValid = true;
	var formMessage = "";
	
	$('#account_form_button').html('validating...');

    validating = setTimeout(function() {
	
		var recaptcha_verification = "action=check_captcha&privatekey=6LeYb8USAAAAACmA5IIT8Q0g92IoV56evdHfLVdC&remoteip=" + $('input#ip_address').val() + "&challenge=" + Recaptcha.get_challenge() + "&response=" + encodeURI(Recaptcha.get_response());
	
 		$.ajax({
			type: "POST", 
			async: false,
			url: "/_ajax_captcha.php",
			data: recaptcha_verification,
			success: function(msg){
				if (msg.indexOf('true') < 0) {
					formValid = false;
					formMessage += "Try your Captcha entry again. ";
				}
			}
		});
		
		if ($('#username').val() == "") {
			formValid = false;
			formMessage += "You need a username. ";
		}
	
		if ($('#username').val() != "") {
			$.ajax({
				type: "POST", 
				async: false,
				url: "/_ajax_validator.php",
				data: "action=check_username&username=" + $('#username').val(),
				success: function(msg){
					if (msg != "OK") {
						formValid = false;
						formMessage += "That username is already registered. ";
					}
				}
			});
		}
	
		if ($('#email').val() != "") { 
			$.ajax({
				type: "POST", 
				async: false,
				url: "/_ajax_validator.php",
				data: "action=check_email&email=" + $('#email').val(),
				success: function(msg){
					if (msg != "OK") {
						formValid = false;
						formMessage += "That e-mail address is already registered. ";
					}
				}
			});
		} 
		
		
		/*
		
		if ($('input[name="response"]').val() != "") { 
			$.ajax({
				type: "POST", 
				async: false,
				url: "/_ajax_validator.php",
				data: "action=check_email&email=" + $('#email').val(),
				success: function(msg){
					if (msg != "OK") {
						formValid = false;
						formMessage += "That e-mail address is already registered. ";
					}
				}
			});
		}

*/
		
		if ($('#email').val() == "") {
			formValid = false;
			formMessage += "You need an e-mail address. ";
		}
	
		if ($('#email_confirm').val() != $('#email').val()) {
			formValid = false;
			formMessage += "Your e-mail addresses don't match. ";
		}   
	
		if ($('#password').val() == "") {
			formValid = false;
			formMessage += "You need a password. ";
		}                                                           
		 
		if ($('#password_confirm').val() != $('#password').val()) {
			formValid = false;
			formMessage += "Your passwords don't match. ";
		} 
	
		if ($('#first_name').val() == "") {
			formValid = false;
			formMessage += "You need a first name. ";
		}
	
		if ($('#last_name').val() == "") {
			formValid = false;
			formMessage += "You need a last name. ";
		}		
		
		$('#account_form_button').html('register');   
		
		if (formValid == true) { 
			$('form#register').attr('action','/account/edit');		
			$('form#register').submit();
		} else { 
			Recaptcha.reload();
			formMessage += "Please fix and resubmit. ";
			$('div#error p').html(formMessage);
			$('div#error').slideDown(750);
		}
	
	}, 10); 
	
}

function accountSave() {
	
	var formValid = true;
	var formMessage = "";
	
	$('#account_form_button').html('validating...');

    	validating = setTimeout(function() {
	
		if ($('#username').val() == "") {
			formValid = false;
			formMessage += "You need a username. ";
		}  
	
		if ($('#username').val() != "" && ($('#username').val() != $('#old_username').val())) {
			$.ajax({
				type: "POST", 
				async: false,
				url: "/_ajax_validator.php",
				data: "action=check_username&username=" + $('#username').val(),
				success: function(msg){ 
					if (msg != "OK") {
						formValid = false;
						formMessage += "That username is already registered. ";
					}
				}
			});		
		}
		
		if ($('#old_email').val() != "" && ($('#email').val() != $('#old_email').val())) { 
			$.ajax({
				type: "POST", 
				async: false,
				url: "/_ajax_validator.php",
				data: "action=check_email&email=" + $('#email').val(),
				success: function(msg){
					if (msg != "OK") {
						formValid = false;
						formMessage += "That e-mail address is already registered. ";
					}
				}
			}); 
		}
	
		if ($('#email').val() == "") {
			formValid = false;
			formMessage += "You need an e-mail address. ";
		} 
	
		if (($('#email').val() != $('#old_email').val()) && ($('#email_confirm').val() != $('#email').val())) {
			formValid = false;
			formMessage += "Your e-mail addresses don't match. ";
		}   
	
		if ($('#password').val() == "") {
			formValid = false;
			formMessage += "You need a password. ";
		}                                                           
		 
		if (($('#password').val() != $('#old_password').val()) && ($('#password_confirm').val() != $('#password').val())) {
			formValid = false;
			formMessage += "Your passwords don't match. ";
		} 
	
		if ($('#first_name').val() == "") {
			formValid = false;
			formMessage += "You need a first name. ";
		}
	
		if ($('#last_name').val() == "") {
			formValid = false;
			formMessage += "You need a last name. ";
		}                                      
		
		$('#account_form_button').html('save');		
		
		if (formValid == true) { 
			$('form#edit_account').attr('action','/account/edit');		
			$('form#edit_account').submit();
		} else {
			formMessage += "Please fix and resubmit. ";
			$('div#error p').html(formMessage);
			$('div#error').slideDown(750);
		} 
	
	}, 10); 
	
} 

function forgotPassword() {
	document.location = "/account/forgot";
}

function passwordReset() {
  
   	var formValid = true;
	var formMessage = "";
	
	if ($('#reset_code').val() == "") {
		formValid = false;
		formMessage += "You need your really long reset code. ";
	}
	                     	
	if ($('#password').val() == "") {
		formValid = false;
		formMessage += "You need a password. ";
	}                                                           
		 
	if ($('#password_confirm').val() != $('#password').val()) {
		formValid = false;
		formMessage += "Your passwords don't match. ";
	}
	
	if (formValid == true) { 
		$('form#password_reset').attr('action','/account/reset');
		$('form#password_reset').submit();
	} else {
		formMessage += "";
		$('div#error p').html(formMessage);
		$('div#error').slideDown(750);
	}   
}

function sendResetLink() {
  
   	var formValid = true;
	var formMessage = "";
	                     	
	if ($('#login_field').val() == "") {
		formValid = false;
		formMessage += "Enter your username or e-mail address. ";
	}
	
	if (formValid == true) { 
		$('form#send_reset_link').attr('action','/account/forgot');
		$('form#send_reset_link').submit();
	} else {
		formMessage += "";
		$('div#error p').html(formMessage);
		$('div#error').slideDown(750);
	}   
}

function accountLogin() { 
	 
	var formValid = true;
	var formMessage = "";
	                     	
	if ($('#login_field').val() == "") {
		formValid = false;
		formMessage += "Enter your username or e-mail address. ";
	}
	
	if ($('#password').val() == "") {
		formValid = false;
		formMessage += "Enter your password. ";
	}
	
	if (formValid == true) { 
		$('form#login').attr('action','/account/login');
		$('form#login').submit();
	} else {
		formMessage += "";
		$('div#error p').html(formMessage);
		$('div#error').slideDown(750);
	}                                    
  	
}

function accountLoginAndCheckout() {   
	
	var formValid = true;
	var formMessage = "";
	
	if ($('#login').val() == "") {
		formValid = false;
		formMessage += "Enter your username e-mail address. ";
	}
	
	if ($('#password').val() == "") {
		formValid = false;
		formMessage += "Enter your password. ";
	}
	                      
	if (formValid == true) { 
		$('form#login_and_checkout').attr('action','/account_do_login.php');
		$('form#login_and_checkout #redirect').attr('value','checkout');
		$('form#login_and_checkout').submit();		
	} else {                     
		formMessage += "Fix your stuff and resubmit. ";
		$('div#error p').html(formMessage);
		$('div#error').show('blind');
		return false;
	}
	                     
}


function saveShipping() { 
	
	var formValid = true;
	var formMessage = "";
	
	if ($('#email').val() == "") {
		formValid = false;
		formMessage += "You need an e-mail address. ";
	} 
		
	if ($('#first_name').val() == "") {
		formValid = false;
		formMessage += "You need a first name. ";
	}
	
	if ($('#last_name').val() == "") {
		formValid = false;
		formMessage += "You need a last name. ";
	}
	
	if ($('#address_1').val() == "") {
		formValid = false;
		formMessage += "You need an address. ";
	}
	
	if ($('#city').val() == "") {
		formValid = false;
		formMessage += "You need a city. ";
	}       
	
	if ($('#province').val() == "") {
		formValid = false;
		formMessage += "You need a state. ";
	}
	
	if ($('#postal_code').val() == "") {
		formValid = false;
		formMessage += "You need a zip code. ";
	}
		
	if (formValid == true) {
		$('form#shipping_and_checkout').attr('action','/checkout');
		$('form#shipping_and_checkout').submit();
	} else {
		formMessage += "Fix your stuff and resubmit. ";
		$('div#error p').html(formMessage);
		$('div#error').show('blind');
	}
	
}

function checkout() {
	$('form#basket').attr('action','/checkout/');
	$('form#basket').submit();	
}

function removeNotices() {
	if ($('.notice').is(':visible')) {
		$('.notice').animate({opacity: 1.0}, 3000).fadeOut('slow', function() {
	      $(this).remove();
	    });		
	}
}


