
var order = {
	
	initialised: false,
	
	validateFields: null,
	
	setValidateFields: function() {
		
		this.validateFields = 
			[
				{	name:'name',			required:true,	regex:''	},
				{	name:'lastname',			required:true,	regex:''	},
				{	name:'address1',		required:true,	regex:''	},
				{	name:'city',			required:true,	regex:''	},
				{	name:'state',			required:true,	regex:''	},
				{	name:'postcode',		required:true,	regex:/^\d{3,4}$/	},
				{	name:'phone',			required:true,	regex:''	},
				{	name:'email',			required:true,	regex:/^.+@.+\..+$/	},
				{	name:'email-confirm',	required:true,	regex:new RegExp('^'+ $('#email').val() + '$')	}
			];
		
		//if ( $("#remember").attr("checked") == true )
		if (userLogin && userLogin.initialised && userLogin.loggedIn === false)
		{
			this.validateFields.push( ( { name: 'password', 	required:true, regex:'' } ) );
		}
	},
	
	validateForm: function() {
		
		var anyFilled = false;
		
		$(".qty").each( function( e ) {
			
			if ( parseFloat( $(this).val() ) > 0 )
			{
				anyFilled = true;
			}
		});
		
		debug.log("filled?", anyFilled);
		
		if ( !anyFilled )
		{
			alert( "You haven't selected any products!" );
			return false;
		}
		
		var shippingConfirm = $("#shipping_confirm").attr("checked");
		debug.log("shipping?", shippingConfirm);
		
		if ( !shippingConfirm )
		{
			alert( "You must accept the delivery charge.");
			return false;
		}
		
		this.setValidateFields();
		
		var fields = this.validateFields;
		var formValid = true;
		var focus = false;
		var field = null;
		
		for (var i in fields) {
			field = fields[i];
			el = $('#'+field.name);
			debug.log(el.attr("id"));
			
			if(field.required && el.val().length==0) {
				formValid=false;
				el.addClass('invalid');
				if(!focus) {
					el.focus();
					focus = true;
				}
			} else {
				if(field.regex!='') {
					if(el.val().length>0 && !el.val().match(field.regex)) {
						formValid=false;
						el.addClass('invalid');
						if(!focus) {
							el.focus();
							focus = true;	
						}
					} else {
					el.removeClass('invalid');
					
					}
					
				} else {
					el.removeClass('invalid');
				}
			
			}
		}
		if(!formValid)
			alert( "You must fill in all required fields.");
		debug.log(formValid);
		return formValid;
	},
	
	populateForm: function( addressData ) {
		
		$.each( addressData, function( key, value ) {
			
			if ( value )
			{
				$("#" + key).val( value );
				
				if ( key == 'email' )
				{
					$("#email-confirm").val( value );
				}
			}
		});
	},
	
	blankForm: function() {
		
		$(':input','#myform')
			.not(':button, :submit, :reset, :hidden')
			.val('')
			.removeAttr('checked')
			.removeAttr('selected');
	},
	
	showHidePassword: function() {
		
		if ( $("#remember").attr("checked") == false )
		{
			$(".password-section").hide();
		}
		else
		{
			if ( userLogin && userLogin.initialised && userLogin.loggedIn )
			{
				$(".password-section").hide();
			}
			else
			{
				$(".password-section").show();
			}
		}
	},
	
	connectEvents: function() {
		
		$("#sendOrderButton").click(function(e) {
			
			e.preventDefault();
			debug.log("submitting order", order.orderForm);
			order.orderForm.trigger("submit");
		});
		
		this.orderForm.keydown( function( e ) {
			
            // Enter pressed?
            if (e.which == 10 || e.which == 13) {
    			e.preventDefault();
    			//order.orderForm.trigger("submit");
            }
        });
		
		this.orderForm.submit( function( e ) {
			
			//e.preventDefault();
			return order.validateForm();
		});
		
		$("#remember").click( function( e ) {
			
			order.showHidePassword()
		});
		
		$(".qty").each( function( e ) {
			$(this).removeAttr('disabled');
			$(this).change(updateProductList);
			$(this).focus( function ( e ) {
			
				if ( $(this).val() == "Qty" )
				{
					$(this).val("");
				}
			})
		});
		
		function updateProductList(ev) {
			$('#your-order').empty();
			$("input.qty").each(function(i) {
				
				var partial = parseInt($(this).prev().prev().val());
				var thisVal = $(this).val();
				
				if (partial === NaN) {
					partial = 0;
				}
				
				// Check if they're allowed to have partial quantities
				if (partial === 0 && thisVal.match(/[0-9]+/)) {
					
					// If not and they've attempted to order less than 1, set it to 1
					$(this).val(parseInt(thisVal) > 0 ? parseInt(thisVal) : 1);
				}
				
				if($(this).val().match(/[0-9]+/) && $(this).val()>0) {
					$('#your-order').append("<div style='width:400px;'>"+$(this).val()+" "+$(this).parents('.item-container').find('.product_title').text()+" @ "+$(this).parents('.item-container').find('.price-detail').text()+"</div>");
				}
				
				// Find the next element, which should be the div
				$(this).next().next().empty();
				
				if (parseFloat($(this).val()) > 0)
				{
					var value = ($(this).val()) * parseFloat($(this).prev().val());
					
					$(this).next().next().html($(this).val()+" x "+$(this).prev().val()+" = $"+value.toFixed(2));
				}
			});
		}
		
		$(".qty").each( function( e ) {
			
			$(this).blur( function ( e ) {
			
				if ( $(this).val() == "" )
				{
					$(this).val("Qty");
				}
			})
		});
		
		updateProductList();
	},
	
	closeDialog: function() {
		
		$('#lightBoxContainer').remove();
		$('#lightBoxOutside').remove();
		$('#lightBoxInside').remove();
		$('#lightBoxCloseBox').remove();
		$("#popupCart").hide();
	},
	
	showModal: function() {
		
		$(document.body).prepend(
			'<div id="lightBoxContainer" onclick="return false;"><div id="lightBoxOutside" onclick="return order.closeDialog();"></div></div>'
			);
		$("#popupCart").show();
	},
	
	init: function() {
		
		this.orderForm = $("#orderForm");
		
		this.connectEvents();
		
		this.showModal();
		
		this.initialised = true;
	}
};


