var cansubmit = false; // We havent chosen any wine by default so... why continue?
var defaultbg = "";
var quantity_total = 0;

$(function(){
	$('._qty').change(function(){UpdateQty(this);UpdateTotals();});
	$('._qty').each(function(){$(this).val('0');UpdateQty(this);UpdateTotals();});
	$('#button_action').click(function(){DoAction();});
	defaultbg = $("#total").css("background-color");
});

function ForceQty() {
	/*
	var cur = $(obj).val();
	if(cur % 12 === 0) {
		// is divisible
		return true;
	} else {
		// isnt divisible
		while(cur % 12 !== 0) {
		   cur--;
		}
		$(obj).val(cur);
	}
	*/
	//alert("Quantity: ");
}

function UpdateQty(obj){
    var row_id=0;
    var p=0;
    var q=0;
    var t=0;
	if($(obj).val()=='')$(obj).val('0');
	if(!($(obj).val()>0))$(obj).val('0');
	$(obj).val(parseInt($(obj).val()));
	row_id=$(obj).parent().parent().attr('id');
	q=parseInt($(obj).val());
	p=$('#price_'+row_id).val();
	t=((q*p*100)/100).toFixed(2);
	$('#total_'+row_id).val(t);
}
function UpdateTotals(){
    var row_id=0;
	var tot_total=0;
	var tot_deposit=0;
    var thisPrice=0;
    var thisTotal=0;
    var thisDeposit=0;
    var thisQty=0;
    var thisItem='';
    var thisId='';
    var accumHTML='';
    var itemnum=1;
	var totQty = 0;
	//``````````````````````````````````````````````
	$('._total').each(function(i){
		row_id=$(this).parent().parent().attr('id')
		thisTotal=$(this).val();
		if (thisTotal=='undefined' || thisTotal==''){
			thisTotal=0;
		}
		tot_total+=parseFloat(thisTotal);
	});
	//``````````````````````````````````````````````
	$('._deposit').each(function(i){
		row_id=$(this).parent().parent().attr('id')
		thisDeposit=$(this).val();
		if (thisDeposit=='undefined' || thisDeposit==''){
			thisDeposit=0;
		}
		thisQty=$('#qty_'+row_id).val();
		if (thisQty!='undefined' && thisQty!=''){
			totQty += parseInt(thisQty);
			tot_deposit+=parseFloat(thisDeposit)*parseInt(thisQty);
		}
       	//``````````````````````````````````````````````
        if(accumHTML != '') accumHTML += "\n";
        thisItem=$('#wine_name_'+row_id).val();
        thisId=$('#wine_id_'+row_id).val();
        thisPrice=$('#price_'+row_id).val();
        if(thisQty > 0 && thisPrice > 0){
            accumHTML += '<input type="hidden" name="item_name_'+itemnum+'" value="'+thisItem+'" />'+"\n";
            accumHTML += '<input type="hidden" name="item_number_'+itemnum+'" value="'+thisId+'" />'+"\n";
            accumHTML += '<input type="hidden" name="amount_'+itemnum+'" value="'+thisPrice+'" />'+"\n";
            //accumHTML += '<input type="hidden" name="amount_'+itemnum+'" value="0.01" />'+"\n";
            accumHTML += '<input type="hidden" name="quantity_'+itemnum+'" value="'+thisQty+'" />'+"\n";
            itemnum++;
        }
	});
	//``````````````````````````````````````````````
	
	// Calc Shipping by Kyle. 
	// $20+HST for first case of 12
	// $10+HST for additional
	// UPDATE: This is WRONG apparently,
	// $20 for first case of 12
	// $10 for additional
	// HST is already factored into bottle price
	// HST is only to be calulated on the shipping cost, not bottling fee as well
	
	
	//alert("Total: " + totQty + "\n Shipping: " + tot_deposit);
	if($("#shipping_type").val() == 2) {
		var Quantity = totQty;
		var TotalShipping = 0;
		for(var i = 12; i <= Quantity; i+=12) {
			if(i == 12) TotalShipping += 20;
			else  TotalShipping += 10;
		}
		tot_deposit += TotalShipping;
	} else {
		TotalShipping = 0;
	}
	
	/********************/
	
	
    $('#itemlist').html(accumHTML);
	$('#total').val(((tot_total*100)/100).toFixed(2));
	$('#deposit').val((parseInt(tot_deposit*100)/100).toFixed(2));
	$('#hst').val((TotalShipping*0.12).toFixed(2));
	$('#gtotal').val(((tot_deposit+tot_total)+(TotalShipping*0.12)).toFixed(2));
	
	$('#handling_cart').val($('#deposit').val());
	$('#tax_cart').val($('#hst').val());

	// Check
	//
	if(totQty % 12 !== 0) {
		$("#gtotal").css("background-color", "#FF0000");
		cansubmit = false;
		$("#qty_err").html("*Bottle quanity must be divisible by 12");
	} else {
		$("#gtotal").css("background-color", defaultbg);
		cansubmit = true;
		$("#qty_err").html("");
	}

	quantity_total = totQty;
}

function DoAction(){
	if ($('#action').val()=='submit' && ValidateForm()){
		AddEmail();
		SubmitForm();
	}
}

function AddEmail() {
	$.get('ajax_funcs/process.email.php', {
		email: $("#email").val(),
		firstname: $("#first_name").val(),
		lastname: $("#last_name").val()
	});
}

function ValidateForm(){
	var bCont=true;
    var jumpto='';
    var phone=$('#phone_number').val().split('-');
	if( bCont && $('#gtotal').val()=='0.00' ){ bCont=false; alert('Please select some wine to order');}
	if( bCont && $('#first_name').val()=='' ){ bCont=false; alert('Please type in your first name'); jumpto = '#first_name';}
	if( bCont && $('#last_name').val()=='' ){ bCont=false; alert('Please type in your last name'); jumpto = '#last_name'; }
	if( bCont && $('#email').val()=='' ){ bCont=false; alert('Please type in your email address'); jumpto = '#email'; }
	if( bCont && $('#address1').val()=='' ){ bCont=false; alert('Please type in your mailing address'); jumpto = '#address1'; }
	if( bCont && $('#city').val()=='' ){ bCont=false; alert('Please type in your city'); jumpto = '#city'; }
	if( bCont && $('#state').val()=='' ){ bCont=false; alert('Please type in your province/state'); jumpto = '#state'; }
	if( bCont && $('#zip').val()=='' ){ bCont=false; alert('Please type in your postal/ZIP code'); jumpto = '#zip'; }
	if( bCont && $('#shipping_type').val() == 0) { bCont=false; alert('Please select a shipping type'); jumpto = '#shipping_type'; }
	if( bCont && $('#country').val()=='' ){ $('#country').val('Canada'); }
	if( bCont && $('#phone_number').val()=='' ){ bCont=false; alert('Please type in your phone number'); jumpto = '#phone_number'; }
	if( bCont && phone.length < 2 ){ bCont=false; alert('Please type in a valid phone number (xxx-xxx-xxxx or xxx-xxxx)'); jumpto = '#phone_number'; }
    if(jumpto != '') $(jumpto).focus();
	return(bCont);
}

function SubmitForm(){
    var phone=$('#phone_number').val();
    var paypal_phone=phone.split('-');
    $('#night_phone_a').val(paypal_phone[0].substring(0, 3));
    if(paypal_phone.length > 1) $('#night_phone_b').val(paypal_phone[1].substring(0, 3));
    if(paypal_phone.length > 2) $('#night_phone_c').val(paypal_phone[2].substring(0, 4));
	if(cansubmit == true) document.getElementById('wineorderform').submit();
	else alert("The amount of bottles you are attempting to order is not divisible by 12. You currently have " + quantity_total + " bottles selected so far.");
}

function SubmitForm2(){
	var json='';
	var ctr=0;
    var wine_id=0;
	//`````````````````````````````````````````````````````
	json+='"order":[';
	$('._orderrow').each(function(i){
		wine_id=$(this).attr('id');
		if ($('#qty_'+wine_id).val()>0){
			json+='{"wine_id":"'+wine_id+'","price":"'+$('#price_'+wine_id).val()+'","qty":"'+$('#qty_'+wine_id).val()+'"},';
			ctr++;
		}
	});
	if (ctr>0){
		json=json.substr(0,json.length-1)+'],';
	}else{
		json+='],';
	}
	//`````````````````````````````````````````````````````
	json+='"first_name":"'+escape($('#first_name').val())+'",';
	json+='"last_name":"'+escape($('#last_name').val())+'",';
	json+='"email":"'+escape($('#email').val())+'",';
	json+='"address":"'+escape($('#address1').val())+'",';
	json+='"city":"'+escape($('#city').val())+'",';
	json+='"state":"'+escape($('#state').val())+'",';
	json+='"zip":"'+escape($('#zip').val())+'",';
	json+='"country":"'+escape($('#country').val())+'",';
	json+='"phone_number":"'+escape($('#phone_number').val())+'",';
	json+='"special_instructions":"'+escape($('#special_instructions').val())+'",';
	//`````````````````````````````````````````````````````
	json+='"total":"'+$('#total').val()+'",';
	json+='"deposit":"'+$('#deposit').val()+'",';
	json+='"tax":"'+$('#tax').val()+'",';
	json+='"gtotal":"'+$('#gtotal').val()+'"';
	//`````````````````````````````````````````````````````
	json+='';
	json='{'+json+'}';
	//`````````````````````````````````````````````````````

	$.ajax({
		type: "POST",
		url: "ajax_funcs/process.order.php",
		data: "json="+json,
		success: function(ajax_return){
			//alert( ajax_return );
			if (ajax_return!='0'){
				$('#order_form').slideUp('slow',function(){
					$('#order_form').html('<center><p>Thank you. Your order has been successfully send to us.</p><div style="width:640px; height: 480px; background-color:#FFFFFF; border:1px solid #333333; overflow:auto;"><pre>'+ajax_return+'</pre></div></center>');
					$('#order_form').slideDown('slow');
				});
			}
		}
	});
}

function process() {
	return false;
}

