/*
-----------------------------------------------
FlowerPowerFundraising.com
Script: vdwCheckout.js
Author: Ben Glassman
Organization: Vermont Design Works
Created: 20 Feb 2009
----------------------------------------------- */

vdwCheckout = {
	init : function(add_item_url) {
		var self = this;
		self.add_item_url = add_item_url;
		$jq('.btn-add-to-cart').click(function(e) {
			e.preventDefault();
			var qty = $jq('#qty').val();
			if (isNaN(qty) || (!isNaN(qty) && qty < 1)) {
				alert('Quantity must be greater than 0');
			} else {
				$jq.post(self.add_item_url, { product_id : $jq('#product_id').val(), qty : $jq('#qty').val() }, vdwCheckout.showMiniCart);
			}
		});
		$jq('<ul id="error-container"></ul>').prependTo('#checkout-form').hide();
		$jq('#checkout-form .btn-proceed-checkout a').click(function(e) {
			e.preventDefault();
			$jq.ajax({
				type : 'POST',
				url : '/assets/zip_lookup/zip_lookup.php',
				cache: false,
				data: {
					state: function() { return $jq("#billing_state").val(); },
					zip: function() { return $jq("#billing_zip").val(); }
				},
				success : function(data, textStatus) {
					$jq('#billing_zip_valid').val((data == 'true') ? '1' : '');
					$jq.ajax({
						type : 'POST',
						url : '/assets/zip_lookup/zip_lookup.php',
						cache: false,
						data: {
							state: function() { return $jq("#shipping_state").val(); },
							zip: function() { return $jq("#shipping_zip").val(); }
						},
						success : function(data, textStatus) {
							$jq('#shipping_zip_valid').val((data == 'true') ? '1' : '');
							var valid = vdwCheckout.$val.form();
							if (valid) { $jq('#checkout-form').submit(); }
						}
					});
				}
			});
		});
		$jq('.btn-submit-order a').click(function(e) {
			e.preventDefault();
			$jq(this).parents('form').submit();
		});
		$jq('.btn-update-qty').click(function(e) {
			e.preventDefault();
			$jq(this).parents('form').submit();
		});
		$jq('#shipping-information li').not('.checkbox').hide();
		$jq("#same_as_billing").click(function() {
			if ($jq(this).is(':checked')) {
				$jq('#shipping-information li').not('.checkbox').hide();
			} else {
				$jq('#shipping-information li').not('.checkbox').show();
			}
			// vdwCheckout.checkCAProhibited();
		});
//		$jq('#billing_state').change(vdwCheckout.checkCAProhibited);
//		$jq('#shipping_state').change(vdwCheckout.checkCAProhibited);
		$jq.validator.addMethod('cc_num', function(value, element, params) {
			return vdwCheckout.validateCardNumber(value, element, params);
		}, $jq.format("Please enter a valid credit card number"));
		$jq.validator.addMethod('cc_exp', function(value, element, params) {
			return vdwCheckout.validateCardExp(value, element, params);
		}, $jq.format("The expiration date you have entered would make the card invalid"));
		vdwCheckout.$val = $jq('#checkout-form').validate({
			errorLabelContainer : "#error-container",
			wrapper : "li",
			rules : {
				billing_address_1 : {
					required: true,
					minlength: 3
				},
				billing_zip : {
					required : true,
					digits : true,
					minlength : 5,
					maxlength : 5
				},
				billing_zip_valid : 'required',
				shipping_first_name : { required : function(element) { return !($jq("#same_as_billing").is(':checked')); } },
				shipping_last_name : { required : function(element) { return !($jq("#same_as_billing").is(':checked')); } },
				shipping_address_1 : { required : function(element) { return !($jq("#same_as_billing").is(':checked')); } },
				shipping_city : { required : function(element) { return !($jq("#same_as_billing").is(':checked')); } },
				shipping_state : { required : function(element) { return !($jq("#same_as_billing").is(':checked')); } },
				shipping_zip : {
					required : function(element) { return !($jq("#same_as_billing").is(':checked')); },
					digits : true,
					minlength : 5,
					maxlength : 5
				},
				shipping_zip_valid : { required : function(element) { return !($jq("#same_as_billing").is(':checked')); } },
				cc_type : 'required',
				cc_num : {
					required : true,
					cc_num : ['cc_type']
				},
				cc_month : {
					required : true,
					cc_exp : ['cc_year']
				}
			},
			messages : {
				billing_first_name : 'First name is required',
				billing_last_name : 'Last name is required',
				billing_address_1 : 'Address is required',
				billing_city : 'City is required',
				billing_state : 'State is required',
				billing_zip : {
					required : 'Billing zip is required',
					digits : 'Billing zip is required (digits only)',
					minlength : 'Billing zip is required (5 digits)',
					maxlength : 'Billing zip is required (5 digits)'
				},
				billing_zip_valid : 'The Billing zip code you entered was not found in the state you selected',
				billing_phone : 'Phone is required',
				billing_email : 'Email is required',
				shipping_first_name : 'Shipping first name is required',
				shipping_last_name : 'Shipping last name is required',
				shipping_address_1 : 'Shipping address is required',
				shipping_city : 'Shipping city is required',
				shipping_state : 'Shipping state is required',
				shipping_zip : {
					required : 'Shipping zip is required',
					digits : 'Shipping zip is required (digits only)',
					minlength : 'Shipping zip is required (5 digits)',
					maxlength : 'Shipping zip is required (5 digits)'
				},
				shipping_zip_valid : 'The Shipping zip code you entered was not found in the state you selected',
				cc_num : 'Credit card number is required',
				cc_type : 'Credit card type is required'
			}
		});
	},
	validateCardNumber : function(value, element, params) {
		var valid = true;
		if( value.length == 0 ) { valid = false; }
		for( var i = 0; i < value.length; ++i ) {
			var c = value.charAt(i);
			if( c < '0' || c > '9' ) { valid = false; }
		}
		var length = value.length;
		switch( $jq('#' + params[0]).val() ) {
			case 'American Express':
				if( length != 15 ) {
					valid = false;
				}
				var prefix = parseInt( value.substring(0,2));
				if( prefix != 34 && prefix != 37 ) {
					valid = false;
				}
				break;
			case 'Discover':
				if( length != 16 ) {
					valid = false;
				}
				var prefix = parseInt( value.substring(0,4));
				if( prefix != 6011 ) {
					valid = false;
				}
				break;
			case 'MasterCard':
				if( length != 16 ) {
					valid = false;
				}
				var prefix = parseInt( value.substring(0,2));
				if( prefix < 51 || prefix > 55) {
					valid = false;
				}
				break;
			case 'Visa':
				if( length != 16 && length != 13 ) {
					valid = false;
				}
				var prefix = parseInt( value.substring(0,1));
				if( prefix != 4 ) {
					valid = false;
				}
				break;
			}
			if (valid) { valid = vdwCheckout.mod10(value); }
			return valid;
	},
	mod10 : function(card_number) { // LUHN Formula for validation of credit card numbers.
		var ar = new Array( card_number.length );
		var i = 0,sum = 0;
		for( i = 0; i < card_number.length; ++i ) {
			ar[i] = parseInt(card_number.charAt(i));
		}

		for( i = ar.length -2; i >= 0; i-=2 ) {
			ar[i] *= 2;
			if( ar[i] > 9 ) ar[i]-=9;
		}


		for( i = 0; i < ar.length; ++i ) {
			sum += ar[i];
		}

		return (((sum%10)==0)?true:false);
	},
	validateCardExp : function(value, element, params) {
		var now = new Date();
		var month = value;
		var year = $jq('#' + params[0]).val();
		var expiresIn = new Date(year,month,0,0,0);
		expiresIn.setMonth(expiresIn.getMonth());
		if(now.getTime() < expiresIn.getTime()) {
			$jq('#' + params[0]).removeClass('error');
			return true;
		} else {
			$jq('#' + params[0]).addClass('error');
			return false;
		}
	},
	showMiniCart : function(data, textStatus) {
		if ($jq('#mini-cart').length) { $jq('#mini-cart').remove(); }
		$miniCart = $jq(data);
		$miniCart.append('<a href="#" class="btn-close">X</a>').find('a.btn-close').click(function(e) {
			e.preventDefault();
			$jq(this).parent().slideUp('fast', function() { $jq('#mini-cart').remove(); })
		});
		containerOffset = $jq('#container').offset();
		formOffset = $jq('#add-to-cart').offset();
		var formHeight = $jq('#add-to-cart').height()
		var top = ((formOffset.top - containerOffset.top) + formHeight + 5) + 'px';
		var left = (formOffset.left - containerOffset.left) + 'px';
		$miniCart.appendTo('#container').hide().css({ top : top, left : left }).slideDown('fast');
		var itemsInCart = $jq('#items-in-cart').text();
		$jq('#cart-item-count').text(itemsInCart);
	},
	validateZip : function(state_fld, zip_fld, valid_fld) {
		$jq.ajax({
			type : 'POST',
			url : '/assets/zip_lookup/zip_lookup.php',
			cache: false,
			data: {
				state: function() { return $jq("#" + state_fld).val(); },
				zip: function() { return $jq("#" + zip_fld).val(); }
			},
			success : function(data, textStatus) {
				$jq('#' + valid_fld).val((data == 'true') ? '1' : '');
			}
		});
	},
	checkCAProhibited : function() {
		var state = $jq("#same_as_billing").is(':checked') ? $jq('#billing_state').val() : $jq('#shipping_state').val();
		var ca_prohibited = $jq('#ca_prohibited').val();
		if (ca_prohibited && state == 'CA') {
			alert('Top Hat Blueberry cannot be shipped to California. If you select california for your shipping address and proceed with checkout, this item will be removed from your cart.');
		}
	}
}

