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

vdwBrochureOrder = {
	init : function() {
		if ($jq('#brochure-order-form').length == 0) { return; }
		vdwBrochureOrder.updateTotal();
		$jq('#order-products tbody .qty input').change(function() {
			vdwBrochureOrder.updateSubTotal($jq(this));
			vdwBrochureOrder.updateTotal();
		});
		$jq('.btn-whats-this').click(function(e) {
			e.preventDefault();
			alert('The Card Verification Value (CVV) appears on the back of your credit card and is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.');
		});
		$jq('#order-shipping-information li').not('.checkbox').hide();		
		$jq("#same_as_billing").click(function() {
			if ($jq(this).is(':checked')) {
				$jq('#order-shipping-information li').not('.checkbox').hide();		
			} else {
				$jq('#order-shipping-information li').not('.checkbox').show();		
			}
		});
		$jq('<ul id="error-container"></ul>').prependTo('#brochure-order-form').hide();
		$jq.validator.addMethod('cc_num', function(value, element, params) {
			return vdwBrochureOrder.validateCardNumber(value, element, params);
		}, $jq.format("Please enter a valid credit card number"));
		$jq.validator.addMethod('cc_exp', function(value, element, params) {
			return vdwBrochureOrder.validateCardExp(value, element, params);
		}, $jq.format("The expiration date you have entered would make the card invalid"));
		$jq.validator.addMethod("requiredGroup", function(value, element, params) {
			var all_empty = true;
			$jq(params[0]).each(function() {
				var x = $jq(this).val();
				if (!isNaN(x) && (x > 0)) {
					all_empty = false;
				}
			});
			return !all_empty;
		}, 'Please select at least one of these fields.');
		$jq.validator.addMethod("phoneUS", function(phone_number, element) {
			phone_number = phone_number.replace(/\s+/g, ""); 
			return this.optional(element) || phone_number.length > 9 &&
				phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
		}, "Please specify a valid phone number");
		$jq('input[type="submit"]').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 = vdwBrochureOrder.$val.form();
							if (valid) { $jq('#brochure-order-form').submit(); }
						}
					});
				}
			});	
		});
		vdwBrochureOrder.$val = $jq('#brochure-order-form').validate({
			onkeyup : false,
			onfocusout : false,
			onclick : false,
			errorLabelContainer : "#error-container",
			wrapper : "li",
			rules : {
				billing_address_1 : {
					required : true,
					minlength : 3
				},
				billing_phone : {
					required : true,
					phoneUS : true
				},
				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')); } },
				qty_26 : {
					requiredGroup : ['#order-products tbody .qty input']
				},
				cc_type : 'required',
				cc_num : {
					required : true,
					cc_num : ['cc_type']
				},
				cc_month : {
					required : true,
					cc_exp : ['cc_year']
				}
			},
			messages : {
				org_name : 'Organization name is required',
				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 : 'A valid phone number is required',
				billing_email : 'A valid 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 : 'A credit card number is required',
				cc_type : 'Credit card type is required',
				qty_26 : 'Please choose a quantity for at least one product'
			}
		});
	},
	calcSubTotal : function($qty_fld) {
		var qty = !isNaN($jq($qty_fld).val()) ? Number($jq($qty_fld).val()) : 0;
		var price = Number($jq($qty_fld).parents('tr').eq(0).find('.price span').text());
		var subtotal = Number(qty * price).toFixed(2);
		return subtotal;
	},
	updateSubTotal : function($qty_fld) {
		$jq($qty_fld).parents('tr').eq(0).find('.subtotal input').val(vdwBrochureOrder.calcSubTotal($qty_fld));
	},
	updateTotal : function() {
		var total = 0;
		$jq('#order-products tbody .qty input').each(function() {
			var subtotal = vdwBrochureOrder.calcSubTotal($jq(this));
			vdwBrochureOrder.updateSubTotal($jq(this));
			total += Number(subtotal);
		});
		$jq('#total').text(total.toFixed(2));
	},
	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 = vdwBrochureOrder.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;
		}
	},
	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' : '');
			}
		});	
	}
}

$jq(document).ready(vdwBrochureOrder.init);
