 $(document).ready(function(){
   // after document loads
$("#quantity_button").click(function(){calcSubtotal()});

$("#ship_button").click(function(){calcShipping()});

enableStep2(false);
enableStep3(false);
enableStep4(false);
});// after document loads

var empty_amt = '0.00';

function calcSubtotal(){
	$('#quant_warn, #quant_warn_json').hide();
	if($('#quantity').attr('readonly')){
		$('#quantity, #promo_code').attr('readonly','');
		$('#subtotal,#check_subtotal').html(empty_amt);
		$("#quantity, #quantity, #price").attr('value','');
		$('#quantity_button').attr({value:'Calculate Subtotal',disabled:false});

        enableStep2(false);
		$('#ship_table_div').fadeOut("slow");
		$('#ship_button').attr({value:'Calculate Shipping',disabled: true});
		enableStep3(false);
		enableStep4(false);
		
		calcTotal();
	}else{
		var quant = $("#quantity").attr('value');
		var numeric = /^\d+$/;
		if (!quant.match(numeric)){
			$('#quant_warn').html('Please enter a numeric quantity.').show();
			quant = '';
		}else{
			quant = $("#quantity").attr('value');
			quant = parseInt(quant);
			if (quant >200){
				$('#quant_warn').html('For orders of greater than 200, please contact TTI directly at (415) 475-5472.').show();
				$('#price').attr('value','');
                        }else if (quant==0 || quant%10 != 0){
                                $('#quant_warn').html('Orders must be multiples of 10 and less than 200').show();
                                $('#price').attr('value','');
			}else{
				$('#quantity, #promo_code').attr('readonly','true');
				$('#quantity_button').attr({value:'Calculating Subtotal...',disabled:true});
				$('#quant_load').toggle();
				
				quant_data = {'quantity':$('#quantity').attr('value'),
			                 'code':$('#promo_code').attr('value')};
				$.ajax({
					type:"POST",
					url: "/cgi-bin/QuantityDiscount.py",
					data:quant_data,
					dataType:"json",
					error:noQuantity,
					success:populateQuantity,
					timeout:10000
				});
			};
		};	
	};
};

function noQuantity(){
	alert('There has been a general error in calculating your subtotal.  Please reload the page.');
};


populateQuantity = function(data){
	$('#quant_load').toggle();
	if (data.error) {
		$('#quant_warn_json').html('There was an error calculating your subtotal. Please check the values of the quantity and any promo codes and recalculate.').show();
	};
	if (data.formError){
		$('#quant_warn_json').html('Please fix the marked fields and resubmit the address form.').show();
	};
	if (data.discount){
		if(data.discount == 'true'){
		    $('#discount').html(data.discount_amount);
			$('#discount_row').show();
			$('#custom').attr('value','discount code: ' + $('#promo_code').attr('value'));
		}else{
			if(data.discount == 'unrecognized'){
				$('#quant_warn_json').html("The promo code you have entered is unrecognized.  You can reenter the code by first clicking 'Change Quantity Info.'").show();
			};
			$('#discount_row').hide();
			$('#custom').attr('value','discount code: none');
		};
	    $('#price').html(data.price);
	    $('#item_name').attr('value', data.quantity + ' Flat jacks @ $' + data.price);
		$("#subtotal, #check_subtotal").html(data.subtotal);
		$("#quantity").attr('value',data.quantity);
	};
	enableStep2(!data.form_error && !data.error);
	enableStep3(false);
	enableStep4(false);
	$('#quantity_button').attr({value:'Change Quantity Info',disabled:false});
	
	calcTotal();
};




function enableStep1(doEnable){

};

function enableStep2(doEnable){
	$('#first_name, #last_name, #address1, #address2, #city, #zip, #company_name, #phone_number, #po_number, #referral').attr('readonly', (doEnable) ? '': 'true');
	$('#state').attr('disabled', (doEnable) ? '' : 'true');
	if(doEnable){
		$('#ship_table_div').fadeOut("slow");
		$("#tax_rate").attr('value','');
		$('#shipping, #check_tax').html(empty_amt);
		$('#ship_button').attr({value:'Calculate Shipping',disabled: !doEnable});
	};

	calcTotal();
};

function enableStep3(doEnable){
	if($('#state').attr('value') == 'CA' && doEnable){
		$('#tax_location_CA').attr({checked:true, disabled:false});
		$('#tax_location_other').attr({checked:false, disabled:true});
		$('.subheader').fadeIn();
	}else{
		$('#tax_rate').attr('value', doEnable ? '0.00' : '');
		$('#tax_location_other').attr({checked:doEnable, disabled:!doEnable});
		$('#tax_location_CA').attr({checked:false, disabled:true});
		$('.subheader').fadeOut();
	};
	$('#tax_resell, #tax_CA').attr('checked','');
	calcTotal();
};

function enableStep4(doEnable){
	$('#encrypted').attr('value','');
	$('#paypal_redirect').hide();
	$('#confirm_button').attr('disabled', !doEnable);
	calcTotal();
};

function calcTotal(){
    itemize = parseFloat($('#check_subtotal').text());
	itemize += parseFloat($('#shipping').text());
	itemize += parseFloat($('#check_tax').text());
	$('#check_total').text(itemize.toFixed(2));
};

function noShipping(){
	alert('There has been a general error in the retrieval of shipping rates.  Please reload the page.');
};

populateShipping = function(data){
	$('#ship_load').toggle();
	if (data.error) {
		$('#ship_warn').html(data.error).show();
	};
	if (data.formError){
		$('#ship_warn').html('Please fix the marked fields and resubmit the address form.').show();
		for(var row in data.formError){
			id = "#" + row + "_form_err";
			$(id).show();
			$('#ship_button').attr({value:'Change Shipping Info',disabled:false});
		};
	};
	if (data.rates){
		ship_rates = data.rates;
		$('#ship_table_div').fadeIn("slow");
		myRow = $("#ship_table tr:eq(1)").clone();
		$("#ship_table tr:gt(0)").remove();
		for (row in ship_rates){
			nextRow = myRow.clone();
			ship_rate = ship_rates[row];
			nextRow.children('td').children('input').attr('value',row);
			nextRow.children('td').children('input')
			nextRow.children('td:eq(1)').html(row);
			nextRow.children('td:eq(2)').children('span').html(ship_rate);
			nextRow.insertAfter("#ship_table tr:last");
		};
		$('#ship_table_div').fadeIn("slow");
		$('#ship_table input').click(function(event){selectShipping(event)});
		enableStep2(false);
	};
	if(data.taxes){
		if (data.taxes == 'no_rate'){
		    $('#tax_error').show();
			$('#tax_table').hide();
			$('#tax_rate').html('0.00');
		}else{
			$('#tax_error').hide();
			$('#tax_location').html($('#city').attr('value') + ', ' + $('#state').attr('value'));
			$('#tax_rate').html(data.taxes);
			$('#tax_table').show();
		};
	};
	$('#ship_button').attr({value:'Change Shipping Info',disabled:false});
	calcTotal();
};

var ship_rates = {};

function calcShipping(){
	$('.form_err').hide();
	if($('#ship_button').attr('value') == 'Change Shipping Info'){
		enableStep2(true);
		enableStep3(false);
		enableStep4(false);
		calcTotal();
	}else{
		$('.form_err').hide();
		$('#ship_load').toggle();
		ship_data = {'first_name':$('#first_name').attr('value'),
			         'last_name':$('#last_name').attr('value'),
					 'address1':$('#address1').attr('value'),
					 'address2':$('#address2').attr('value') + ' ',
					 'company_name':$('#company_name').attr('value'),
					 'phone_number':$('#phone_number').attr('value'),
					 'city':$('#city').attr('value'),
					 'state':$('#state').attr('value'),
					 'zip':$('#zip').attr('value'),
					 'quantity':$('#quantity').attr('value')};

		$.ajax({
			type:"POST",
			url: "/cgi-bin/RateAvailableServices.py",
			data:ship_data,
			dataType:"json",
			error:noShipping,
			success:populateShipping,
			timeout:10000
		});
	};
};

function selectShipping(e){
	var shipping_cost = ship_rates[e.target.value];
	$('#shipping').html(shipping_cost);
	
	enableStep2(false);
	enableStep3(true);
	enableStep4($('#tax_location_other').attr('checked'));
	calcTotal();
};


function taxChoice(taxApplies){
	$('#reseller_cert').attr('disabled', taxApplies ? 'true' : '');
	stotal = $('#check_subtotal').text();
	tot_parse = parseFloat(stotal);
	tot_fixed = tot_parse.toFixed(2);
	var taxable = parseFloat(parseFloat($('#check_subtotal').text()).toFixed(2));
	var tax_rate = 0.00;
	if (taxApplies){
	    tax_rate = parseFloat(parseFloat($('#tax_rate').text()).toFixed(2));
	}
	calc_tax = (taxable * tax_rate / 100.0).toFixed(2);
	$('#check_tax').text(calc_tax);
    enableStep4(true);
	calcTotal();
};

function checkOut(){
	
	if( $('#quantity').attr('value') != '' &&
		$('input[name=ship_service_type]').filter(
		    function() {return $(this).attr('checked');}).length == 1 &&
		$('#tax_location_other, #tax_resell, #tax_CA').filter(
		    function() {return $(this).attr('checked');}).length == 1){
		button_data = {'first_name':$('#first_name').attr('value'),
			         'last_name':$('#last_name').attr('value'),
					 'address1':$('#address1').attr('value'),
					 'address2':$('#address2').attr('value') + ' ',
					 'city':$('#city').attr('value'),
					 'state':$('#state').attr('value'),
					 'zip':$('#zip').attr('value'),
					 'quantity':$('#quantity').attr('value'),
					 'code':$('#promo_code').attr('value'),
					 'shipping':$('#shipping').html(),
					 'use_tax_rate':$('#tax_CA').attr('checked'),
                                         'company_name':$('#company_name').attr('value'),
                                         'phone_number':$('#phone_number').attr('value'),
                                         'po_number':$('#po_number').attr('value'),
                                         'referral':$('#referral').attr('value')
                              };

		$.ajax({
			type:"POST",
			url: "/cgi-bin/MakeButton.py",
			data:button_data,
			dataType:"json",
			error:noButton,
			success:populateButton,
			timeout:10000
		});
		$('#button_load').show();
	} else {
		alert("Please finish steps one through three before attempting to check out.");
	};
};

function noButton(){
	alert('There has been an error processing your form.  Please refresh the page and fill out the form again.');
	$('#button_load').hide();
	enableStep4(false);

};

function populateButton(data){
	$('#button_load').hide();
	if(data.encrypted){
		$('#confirm_button').attr('disabled',true);
		$('#encrypted').attr('value',data.encrypted);
		$('#paypal_redirect').show();
	}else{
		noButton();
	}
};
