var StaffOrderInfo = {
	//FORM FIELDS IDS
	'fields': [ 'first_name', 'last_name', 'address', 'address2', 'city', 'zip', 'company' ],
	
	//PHONE FIELDS IDS
	'phonefields': [ 'billing-phone', 'shipping-phone', 'billing-companyphone', 'shipping-companyphone', 'schedule-phone', 'phone'],
	
	//LASTNAME AUTOCOMPLETER
	'autocompleter': function () {
		if( !$('#billing-last_name').size() || !$('.remove-product-so').size() ) return false;
		
		$('#billing-last_name').autocomplete(
			'/admin/customers/json-search',
			{
				'parse': function (response) {
					if($('#new-account:checked').size())
						return [];
					
					return $.map(
						eval(response),
						function (row) {
							return { data: row, result: row['billing-last_name'] };
						}
					);
				},
				
				'formatItem': function (item) {
					if($('#new-account:checked').size())
						return '';
					
					return [
						item['billing-first_name'],
						item['billing-last_name'],
						item['shipping-phone1'], item['shipping-phone2'], item['shipping-phone3']
					].join(' ');
				}
			}
		);
		
		//set billing/shipping info after user selected search result
		$('#billing-last_name').result(StaffOrderInfo.populateBilling);
	},
	
	//BIND SECTION EVENTS
	'bindEvents': function () {
		$('#tostep3').livequery('click', this.infoSubmit);
		
		$('#bill-country, #shipp-country').livequery('change', function () {
			StaffOrderInfo.checkAndCopy.call(this);
			Common.changeShippingCountry.call(this);
			Common.updateStates.call(this);
			
			if($('#same-as-billing:checked').size() || $(this).attr('id') == 'shipp-country')
				Checkout.fedexPrices();
			
			$.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal);
		});
		
		$('#bill-country, #shipp-country').change(Checkout.changeZipLength);
		$('#same-as-billing').click(this.setSameShipping);
		$('#bill-state').livequery('change', this.checkAndCopy);
		$('#bill-country').livequery('change', this.checkAndCopy);
		$('#shipping-zip').keyup(Checkout.fedexPrices);
		$('#billing-zip').keyup(function () { if($('#same-as-billing').attr('checked')) Checkout.fedexPrices(); });
		$('#no-email').click(this.noEmail);
		$('#new-account').click(function () { $('#email-row').toggle(); });
		
		$('#prepaid-freight-usa').click(function () { if($(this).attr('checked')) $('input.shipping-method[@value=1]').attr('checked', 1)});
		$('#prepaid-freight-can').click(function () { if($(this).attr('checked')) $('input.shipping-method[@value=4]').attr('checked', 1) });
		
		$('.shipping-method').click(function () { if( ! ($(this).val() == 1 || $(this).val() == 4)) $('#prepaid-freight-usa, #prepaid-freight-can').removeAttr('checked'); });
		
		$('[@id ^= "billing-phone"]').livequery('keyup', this.checkAndCopy);
		$('[@id ^= "billing-companyphone"]').livequery('keyup', this.checkAndCopy);
		
		for(i in this.fields)
			$('#billing-'+this.fields[i]).livequery('keyup', this.checkAndCopy);
		
		return true;
	},
	
	//BIND INPUT VALIDATORS
	'bindValidators': function () {
		for(var id in {'billing-company-phone': 1, 'shipping-company-phone': 1, 'shipping-phone': 1})
			for(var i=1; i<=3; i++)
				$('#'+id+i).size() ?$('#'+id+i).validation({ type: 'int' }) : 0;
		
		return true;
	},
	
	//POPULATE BILLING/SHIPPING INFO WITH SEARCH RESULT
	'populateBilling': function (event, data, formatted) {
		$('#no-email').removeAttr('checked');
		$('#same-as-billing').removeAttr('checked');
		
		StaffOrderInfo.clearShipping();
		
		for(var type in { 'bill': 1, 'shipp': 1 }) {
			if(data[type+'-country'] == 'can')
				$('#'+type+'ing-zip').attr('maxlength', 6);
			else
				$('#'+type+'ing-zip').attr('maxlength', 5);
		}
		
		for(var id in data) {
			$('#'+id).removeAttr('disabled');
			$('#'+id).val(data[id]);
		}
		
		$('#bill-country, #shipp-country');
		
		Common.updateStates.call($('#bill-country'));
		Common.updateStates.call($('#shipp-country'));
		
		$('#bill-state').val(data['bill-state']);
		$('#shipp-state').val(data['shipp-state']);
		
		Common.changeShippingCountry();
		Checkout.fedexPrices();
		
		$('#new-account').removeAttr('checked');
		$('#email-row').hide();
	},
	
	//NO EMAIL CHECKBOX
	'noEmail': function () {
		if($(this).attr('checked'))
			$('#email').attr('disabled', 1);
		else
			$('#email').removeAttr('disabled');
		
		return true;
	},
	
	//DYNAMIC PART COPYING
	'checkAndCopy': function () {
		if ($('#same-as-billing').attr('checked'))
			$('#' + this.id.replace(/bill/gi, 'shipp')).attr('value', $('#' + this.id).val());
	},
	
	//PHONES AUTOTAB
	'autoTabs': function () {
		for(var i in this.phonefields) {
			if($('#'+this.phonefields[i]).size()) {
				$('#'+this.phonefields[i]+'1').autotab({ target: this.phonefields[i]+'2', format: 'numeric' });
				$('#'+this.phonefields[i]+'2').autotab({ target: this.phonefields[i]+'3', format: 'numeric', previous: this.phonefields[i]+'1' });
				$('#'+this.phonefields[i]+'3').autotab({ previous: this.phonefields[i]+'2', format: 'numeric' });
			}
		}
	},
	
	//PREPARE FORMS FOR SUBMITTING AND THAN SUBMIT
	'infoSubmit': function () {
        if (!StaffOrderInfo.validateStates())
            return;

		$('#tostep3-wait').show();
		
		StaffOrderInfo.implodePhones();
		
		$('#shipping-cartzip').removeAttr('disabled');
		StaffOrderInfo.clearShipping();
		
		//submit info and draw payment form on success
		$('#info-form').ajaxSubmit({
			target: '#info',
			success: function () {
				var orderid = $('#orderid').attr('value') ? $('#orderid').attr('value') : 0;
				var installedid = $('#installedid').attr('value') ? $('#installedid').attr('value') : 0;
					
				if(readySteps['info'])
					window.location = '/admin/stafforder';
					//$('#payment').load('/admin/stafforder/payment/'+orderid+'/'+installedid, function () { $('#tostep3-wait').hide(); });
				else
					$('#tostep3-wait').hide();
			}
		});
		
		return false;
	},
	
	//FILL PHONE FIELDS
	'fillPhoneFields': function () {
		/*if( ! $('#billing-phone').size())
			return false;*/
		
		for(var i in StaffOrderInfo.phonefields) {
			if($('#'+StaffOrderInfo.phonefields[i]).size()) {
				var phoneParts = $('#'+StaffOrderInfo.phonefields[i]).attr('value').split('-');
				
				for(var j=0; j<=2; j++)
					$('#'+StaffOrderInfo.phonefields[i]+''+(j+1)).attr('value', phoneParts[j]);
			}
		}
		
		return true;
	},
  
	//IMPLODE PHONE FIELDS
	'implodePhones': function () {
		for(var i in StaffOrderInfo.phonefields) {
			var phoneParts = [];
			
			for(var j=1; j<=3; j++)
				if($('#'+StaffOrderInfo.phonefields[i]+''+j).attr('value'))
					phoneParts.push($('#'+StaffOrderInfo.phonefields[i]+''+j).attr('value'));
			
			$('#'+StaffOrderInfo.phonefields[i]).attr('value', phoneParts.join('-'));
		}
		
		return true;
	},
	
	//REDRAW STATES LIST ON COUNTRY CHANGE
	'setStates': function (countrySelectId) {
		if( !$('#'+countrySelectId).size() && !$(this).attr('id'))
			return false;
		
		var countrySelectId = typeof countrySelectId == 'string' ? countrySelectId : $(this).attr('id');
		var countryId = $('#'+countrySelectId+' option:selected').attr('value');
		
		var stateSelectId = countrySelectId.replace(/\-country/gi, '-state');
		
		$('#'+stateSelectId+' option').hide();
		$('#'+stateSelectId+' option[@value='+countries[countryId][0]+']').attr('selected', 'selected');
		
		for(var i in countries[countryId])
			$('#'+stateSelectId+' option[@value='+countries[countryId][i]+']').show();
		
		$.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal);
		
		return false;
	},
	
	//SET TAX AND TOTAL VALUES
	'setTaxTotal': function (data) {
		if( ! $('#total').size())
			return 0;
		
		productTotal = (typeof productTotal == 'undefined' ? 0 : productTotal);
		shipping = (typeof shipping == 'undefined' ? 0 : shipping);
		
		if($('#shipp-country').val() != 'can')
			tax = (typeof data.tax == 'number' ? data.taxsum+shipping*data.tax : 0);
		else
			tax = 0;
        
		total = productTotal + shipping + tax;
		
		$('#tax').html('Tax: $'+tax.toFixed(2));
		$('#total').html('Total Due: $'+total.toFixed(2));
		
		return 1;
	},
	
	//SET SHIPPING COST
	'setShippingTotal': function (data) {
		var canTax = 0;
		var PST = 0.15, HST = 0.06;
		
		if( ! $('#total').size() || typeof productTotal == 'undefined')
			return 0;
		
		shipping = (typeof data.cost != 'undefined' ? data.cost : 0);
		
		//canadian tax
		if(shipping && $('#shipp-country').val() == 'can') {
			if(shipping != 0)
				shipping += (productTotal + shipping)*(PST + HST);
		}
		
		//total = productTotal + shipping + tax;
		
		if(typeof total == 'object')
			var total = 0;
		
		total = productTotal + shipping;
			
		$('#shipping').size() ? $('#shipping').html('Shipping: $'+shipping.toFixed(2)) : 0;
		$('#total').html('Total Due: $'+total.toFixed(2));
		
		$.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal);
		
		return 1;
	},
	
	//CLEAR SHIPPING VALUES
	'clearShipping': function () {
		for(var i in StaffOrderInfo.fields) { $('#shipping-'+StaffOrderInfo.fields[i]).removeAttr('disabled'); }
		
		for(i=1; i<=3; i++) {
			$('#shipping-companyphone'+i).removeAttr('disabled');
			$('#shipping-phone'+i).removeAttr('disabled');
		}
		
		$('#shipp-state').removeAttr('disabled');
		$('#shipp-country').removeAttr('disabled');
		
		return true;
	},
	
	//SET SAME SHIPPING INFO LIKE BILLING
	'setSameShipping': function () {
		if( ! $(this).attr('checked')) {
			StaffOrderInfo.clearShipping();
			return true;
		}
		
		//set country and state
		StaffOrderInfo.syncSelects('bill-country', 'shipp-country');
		Checkout.changeZipLength.call($('#shipp-country'));
		
		for(var i in StaffOrderInfo.fields) {
			if($('#shipping-'+StaffOrderInfo.fields[i]).size() && $('#billing-'+StaffOrderInfo.fields[i]).size())
				$('#shipping-'+StaffOrderInfo.fields[i]).attr('value', $('#billing-'+StaffOrderInfo.fields[i]).attr('value')).attr('disabled', 1);
		}
		
		//StaffOrderInfo.setStates('shipp-country');
		Common.updateStates.call($('#shipp-country'));
		StaffOrderInfo.syncSelects('bill-state', 'shipp-state');
		
		for(var i=1; i<=3; i++) $('#shipping-phone'+i).attr('value', $('#billing-phone'+i).attr('value')).attr('disabled', 1);
		
		if($('#shipping-companyphone1').size())
			for(var i=1; i<=3; i++) $('#shipping-companyphone'+i).attr('value', $('#billing-companyphone'+i).attr('value')).attr('disabled', 1);
		
		for(var id in {'shipp-country': 1, 'shipp-state': 1 }) $('[@id^="'+id+'"]').attr('disabled', 1);
		
		//$.getJSON('/checkout/taxinfo/'+$('#shipp-state').val(), StaffOrderInfo.setTaxTotal);
		
		Common.changeShippingCountry();
		Checkout.fedexPrices();
		
		return true;
	},
	
	//SYNCHRONISE SELECTORS
	'syncSelects': function (sourceId, destId) {
		$('#'+destId+' option[@value='+$('#'+sourceId+' option:selected').attr('value')+']').attr('selected', 'selected');
	},
    
    //UNSHIPPABLESTATESBOX
	'validateStates': function () {
        if (typeof unshippableStateList != 'undefined' && unshippableStateList[$('#shipp-state').val()]) {
            Shadowbox.open({
                player: 'html',
                title: '',
                height: 180,
                width: 400,
                content: '<div style="background-color:white;">\n\
    				<div style="background-color:white; margin:20px">\n\
                    <strong>We can no longer ship Aprilaire product into the ' + unshippableStateList[$('#shipp-state').val()] + ', please contact your installing contractor, local heating and cooling contractor or use our dealer locator at <a href="http://www.aprilaire.com/">www.aprilaire.com</a>.</strong></div>\n\
                    <br><center><a href="javascript:void(0)" onclick="Shadowbox.close()" style="color:blue; text-decoration: underline; font-size:12pt">Close</a></center></div>'
            });
			
            return false;
        }
		
        return true;
	}
};

$(document).ready(function() {
	StaffOrderInfo.bindValidators();
	StaffOrderInfo.bindEvents();
	
	StaffOrderInfo.fillPhoneFields();
	StaffOrderInfo.autoTabs();
	StaffOrderInfo.autocompleter();
	StaffOrderInfo.noEmail.call($('#no-email'));
	
	Common.changeShippingCountry.call($('#shipp-country'));
    // 3-Dec, 2008
    billingState = $('#bill-state').val();
    shippingState = $('#shipp-state').val();
    
	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));
	
	$.map(
		$('#bill-country, #shipp-country'),
		function(object) {
			$('#'+$(object).attr('id')+' option[@value="'+userCountry+'"]').attr('selected', 1);
			Common.updateStates.call(object);
			$('#'+$(object).attr('id').replace(/country/, 'state')+' option[@value="'+userState+'"]').attr('selected', 1);
		}
	);
	
    // 3-Dec, 2008
    $('#bill-state').val(billingState)
    $('#shipp-state').val(shippingState);
	
	if($('#same-as-billing').attr('checked')) {
		StaffOrderInfo.setSameShipping.call($('#same-as-billing'));
	}
});
