var Checkout = {
	'incorrectPaymentFields': [],
	
	//FEDEX TYPES ID:LABEL
	'fedexTypes': {
		'usa': {
			1: 'FedEx Ground',
			2: 'FedEx 2Day',
			3: 'FedEx Priority Overnight'
		},
		'can': {
			4: 'FedEx Ground (CAN)',
			5: 'FedEx 2Day (CAN)',
			6: 'FedEx Standart Overnight (CAN)'
		}
	},
	
	//BIND SECTION EVENTS
	'bindEvents': function () {
		$('#cancel-button').click(function () { window.location.href = "/"; /* StaffOrder.cancelOrder(1); */ });
		$('#editinfo-button').click(function () { window.location = '/checkout/info/'+orderid+'/'+installedid; });
		$('#editcart-button').click(function () { window.location = '/cart'; });
		$('#review-button, #makechanges-button').click(this.submitInfo);
		$('#paypal-review-button').click(this.paypalSubmitInfo);
		$('#purchase-button').click(this.purchaseOrder);
		$('#cc-type').livequery('change', this.changePaymentForm);
		
		$('#shipp-state').change(function () { $.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal); });
		$('#shipping-zip, #shipping-cartzip').keyup(this.fedexPrices);
		$('#shipp-country').change(function () { Common.changeShippingCountry(); Checkout.fedexPrices(); });
		
		$('#bill-country, #shipp-country').change(this.changeZipLength);
		$('#billing-zip').keyup(function () {
			if($('#same-as-billing').attr('checked')) {
				$.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal);
				Checkout.fedexPrices();
			}
		});
        
		$('#schedule-form').submit(this.submitScheduleForm);
		$('.shipping-method').click(this.setShippingCost);
		$('.print-link').click(this.printOrder);
	},
	
	//CHANGE ZIP LENGTH
	'changeZipLength': function () {
		if( ! $('#shipp-country').size())
			return 0;
		
		var context = this;
		var length = ( $(this).val() == 'can' ? 6 : 5 );
		var applyTo = [$(this)];
		
		if($('#same-as-billing').attr('checked')) {
			applyTo.push($('#shipp-country'));
		}
		
		for(var i in applyTo)
			if(typeof applyTo[i] == 'object')
					$('#'+applyTo[i].attr('id').replace(/\-country/, 'ing-zip')).attr('maxlength', length);
		
		return 1;
	},
	
	//CHANGE CCN INPUT LENGTH
	'changePaymentForm': function () {
		if($(this).val() == 'amexpress')
			$('#ccn-cell')
				.html('')
				.append('<input id="ccn1" name="ccn[1]" class="border input100 xxxs" size="4" maxlength="4" value="" style="margin-right: 7px;" />')
				.append('<input id="ccn2" name="ccn[2]" class="border input100 xxxs" size="6" maxlength="6" value="" style="margin-right: 7px;" />')
				.append('<input id="ccn3" name="ccn[3]" class="border input100 xxxs" size="5" maxlength="5" value="" style="margin-right: 7px;" />');
		else
			$('#ccn-cell')
				.html('')
				.append('<input id="ccn1" name="ccn[1]" class="border input100 xxxs" size="4" maxlength="4" value="" style="margin-right: 4px;" />')
				.append('<input id="ccn2" name="ccn[2]" class="border input100 xxxs" size="4" maxlength="4" value="" style="margin-right: 4px;" />')
				.append('<input id="ccn3" name="ccn[3]" class="border input100 xxxs" size="4" maxlength="4" value="" style="margin-right: 4px;" />')
				.append('<input id="ccn4" name="ccn[4]" class="border input100 xxxs" size="4" maxlength="4" value="" style="margin-right: 4px;" />');
		
		Checkout.bindAutotabs();
		
		return true;
	},
	
    //PRINT ORDER FROM THANK YOU PAGE
    'printOrder': function() {
        window.open(
			$(this).attr('href'),
			null,
			"height=600,width=800,status=no,toolbar=no,menubar=no,location=no"
		);
		
		return false;
    },
    
    //SUBMIT Schedule FORM
	'submitScheduleForm': function () {
		StaffOrderInfo.implodePhones();
	},
	
	//GET AND SHOW ALL FEDEX PRICES
	'fedexPrices': function () {
		var zip = ($('#shipping-zip').attr('value') ? $('#shipping-zip').attr('value') : $('#shipping-cartzip').attr('value'));
		var state = $('#shipp-state').val();
		var country = $('#shipp-country').val();
		var orderid = $('#orderid').val() ? $('#orderid').val() : 0;
		var PST = 0.15, HST = 0.06;
		
		if( ! zip) return false;
		
		if((zip.length > 4 && country == 'usa') || (zip.length > 5 && country == 'can')) {
			$('#fedex-error').html('Please wait...');
			
			for(var i in Checkout.fedexTypes[country]) {
				$.ajax({
					type: 'GET',
					async: true,
					url: '/checkout/shipinfo/'+i+'/'+orderid+'/'+zip,
					
					success: function(response) {
						var data = eval('('+response+')');
						
						//show error on failure
						if( ! data.success) {
							var message = data.message ? data.message : 'FedexError: Wrong zip';
							$('#fedex-error').html(message);
							return 0;
						}
						
						$('#fedex-error').html('');
						
						//join price with service label
						if($('#f'+data.serviceid).size()) {
							currentShipping = data.cost;
							
							if($('#shipp-country').val() == 'can')
								currentShipping += (productTotal + currentShipping)*(PST + HST);
							
							$('#f'+data.serviceid+' td').eq(1).html(Checkout.fedexTypes[country][data.serviceid]+' $'+currentShipping.toFixed(2));
						}
					}
				});
			}
			
			Checkout.setShippingCost.call($('.shipping-method:checked').eq(0));
		}
		
		return 1;
	},
	
	//RETRIEVE AND SET SHIPPING COST
	'setShippingCost': function () {
		var zip = ($('#shipping-zip').size() ? $('#shipping-zip').attr('value') : $('#shipping-cartzip').attr('value'));
		
		if(zip) {
			//get http://checkout/shipinfo/:serviceid/:orderid/:zip
			$.getJSON('/checkout/shipinfo/'+$(this).val()+'/'+$('#orderid').val()+'/'+zip, StaffOrderInfo.setShippingTotal);
			return true;
		} else {
			//alert('You must first enter shipping zip');
			return false;
		}
	},
	
	//AUTOTAB ROUTINES
	'bindAutotabs': function () {
		if($('#ccn1').size()) {
			$('#ccn1').autotab({ target: 'ccn2', format: 'numeric' });
			$('#ccn2').autotab({ target: 'ccn3', format: 'numeric', previous: 'ccn1' });
			$('#ccn3').autotab({ target: 'ccn4', format: 'numeric', previous: 'ccn2' });
			$('#ccn4').autotab({ previous: 'ccn3', format: 'numeric' });
		}
		
		return true;
	},
	
	//SEND PURCHASE ORDER REQUEST
	'purchaseOrder': function () {
		$.getJSON(
			'/admin/stafforder/confirm/'+orderid+'/'+installedid,
            
			function (data) {
				if(data.success) {
					alert('Order accepted!');
					window.location = '/checkout/thanx/'+orderid+'/'+installedid;
				} else {
					alert('ERROR: '+data.message);
				}
				
				$('#purchase-button').hide();
			}
		);
		
		return false;
	},
	
	//UPDATE SHIPPING COST
	'setTaxCost': function () {
		$.getJSON('/checkout/shipinfo/'+$('#shipp-state').val(), StaffOrderInfo.setShippingTotal);
	},
	
	//VALIDATE PAYMENT INFO
	'validatePayment': function () {
		if( ! $('tr.card').size())
			return true;
		
		var date = new Date();
		Checkout.incorrectPaymentFields = [];
		
		if($('#ccn-exp-year').val() == date.getFullYear() && parseInt($('#ccn-exp-month').val().replace(/^0/, '')) < (date.getMonth() + 1))
			Checkout.incorrectPaymentFields.push('Expiration Date');
		
		if($('#cc-type').val() == '')
			Checkout.incorrectPaymentFields.push('Card Type');
		
		if( ! $('#cc-name').val())
			Checkout.incorrectPaymentFields.push('Name on Card');
		
		for(var i=1; i<=3; i++)
			if( ! ($('#ccn'+i).val() || $('#ccn'+i).val().length == 4)) {
				Checkout.incorrectPaymentFields.push('Card Number');
				break;
			}
		
		if($('#ccn4').size()  && (! ($('#ccn4').val() || $('#ccn4').val().length < 3)))
			Checkout.incorrectPaymentFields.push('Card Number');
		
		if( ! $('#cvv').val())
			Checkout.incorrectPaymentFields.push('CCV Number');
		
		if(Checkout.incorrectPaymentFields.length)
			return false;
		else
			return true;
	},
	
	//SUBMIT INFO FORMS
	'submitInfo': function () {
        if (!StaffOrderInfo.validateStates())
			return false;
		
		if( ! Checkout.validatePayment()) {
			alert('Payment Method fields are incorrect or empty: '+Checkout.incorrectPaymentFields.join(', '));
			return false;
		}
		
		Checkout.sendPaymentInfo();
		
		StaffOrderInfo.implodePhones();
		StaffOrderInfo.clearShipping();
		
		$('#shipping-cartzip').size() ? $('#shipping-cartzip').removeAttr('disabled') : 0;
		
		if($(this).attr('id') == 'makechanges-button')
			$('#makechanges').val('1');
		
		$('#info-form').submit();
	},
    
	//CREATE ORDER IN DB
	'createOrder': function () {
		var success = true;
		
		$.ajax({
			type: 'GET',
			async: false,
			url: '/admin/stafforder/create',
			
			success: function (response) {
				var data = eval('('+response+')');
				
				if( ! data.success) {
					alert(data.message);
					
					success = false;
					return 0;
				}
				
				orderid = data.orderId;
				installedid = data.installedOrderId;
				
				$('#orderid').attr('value', data.orderId);
				$('#installedid').attr('value', data.installedId);
				
				return 1;
   			}
 		});
		
		return success;
	},
	
	//SEND ORDER PAYMENT INFO
	'sendPaymentInfo': function () {
		
		$.ajax({
			type: 'POST',
			async: false,
			url: '/admin/stafforder/payment/'+$('#orderid').val()+'/'+$('#installedid').val(),
			data: Checkout.serializePaymentInfo()
		});
		
		/*
		$.post(
			'/admin/stafforder/payment/'+$('#orderid').val()+'/'+$('#installedid').val(),
			Checkout.serializePaymentInfo(),
			function(data){alert("Data Loaded: " + data);}
		);*/
	},
	
	//SERIALIZE PAYMENT INFO
	'serializePaymentInfo': function () {
		var serialized = {};
		var ccFields = {
			'ccn[1]': 1,
			'ccn[2]': 1,
			'ccn[3]': 1,
			'ccn[4]': 1,
			'cvv': 1,
			'cc-type': 1,
			'cc-name': 1,
			'ccn-exp-month': 1,
			'ccn-exp-year': 1
		};
		
		for(var ccField in ccFields) serialized[ccField] = $('#'+ccField).val();
		
		serialized['ccn[1]'] = $('#ccn1').val();
		serialized['ccn[2]'] = $('#ccn2').val();
		serialized['ccn[3]'] = $('#ccn3').val();
		
		if($('#ccn4').size())
			serialized['ccn[4]'] = $('#ccn4').val();
		else
			serialized['ccn[4]'] = '';
			
		return serialized;
	}
};

$(document).ready(
	function () {
		StaffOrderInfo.fillPhoneFields();
		
		Common.changeShippingCountry();
		
		if($('.shipping-method').size())
			Checkout.setShippingCost.call($('.shipping-method:checked').eq(0));
		else
			StaffOrderInfo.setShippingTotal([]);
		
		for(var field in { 'bill-country': 1, 'shipp-country': 1 })
			if($('#'+field).size())
				$('#'+field.replace(/\-country/, 'ing-zip')).attr('maxlength', ($('#'+field).val() == 'usa' ? 5 : 6));
		
		$.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal);
		
		Checkout.changePaymentForm.call($('#cc-type'));
		Checkout.bindEvents();
		Checkout.bindAutotabs();
		Checkout.fedexPrices();
		
		setTimeout('Cart.ping()', 3*60*1000);
	}
);
