//VALIDATION METHODS
var Validate =
{
	//TO AUTO-ENTER TEST CUSTOMER INFORMATION UPON SUBMIT: ENTER test IN THE SHIPTO_COMPANYNAME FIELD
	SubmitHandler: function(event)
	{
		if ($("#shipto_companyName").val() == "test")
		{
			$("#ShippingOptions").val("60");
			$("#shipto_custFirstName").val("Test");
			$("#shipto_custLastName").val("Cust");
			$("#shipto_custName").val($("#shipto_custFirstName").val() + " " + $("#shipto_custLastName").val());
			$("#shipto_Addr1").val("3393 HIll Ave");
			$("#shipto_Addr2").val("Ste 1");
			$("#shipto_City").val("Ogden");
			$("#shipto_State").val("UT");
			$("#shipto_Zip").val("84403");
			$("#shipto_DaytimePhone").val("8015555555");
			$("#shipto_EveningPhone").val("8016666666");
			$("#shipto_EmailAddr").val("m@m.com");
			$("#confirm_shipto_EmailAddr").val("m@m.com");

			Calc.UpdateBillTo();
			
			/*
			$("#ccNum").val("5211969444285");
			if($("#testcard").val() == true) $("#ccNum").val("5454545454545454");
			$("#ccexp").val("12/20");
			$("#cvv2").val("123");
			*/
			
			$("#specialInstructions").val("Special Instructions are this:  This is a test order");
		}

		//Make sure the hidden billto and shipto fields are set based on entered values
		$("#billto_custName").val($("#billto_custFirstName").val() + ' ' + $("#billto_custLastName").val());
		$("#shipto_custName").val($("#shipto_custFirstName").val() + ' ' + $("#shipto_custLastName").val());

		//IF FORM MEETS VALIDATION REQUIREMENTS, REMOVE THE DISABLED ATTRIBUTE FROM ANY CONTRAL THAT IS DISABLED(THIS ALLOWS THE FIELD TO BE
		//INCLUDED IN THE POST).  THEN POST THE PAGE TO THE SERVER
		if(Validate.FormIsValid())
		{
			//Double check all coupons applied to the order
			Coupon.VerifyAppliedCoupons({submitting: true});

			//Generate cloud delivery fields
			Cloud.Storage.GenerateCloudFields();
			
			//Stop the submit event
			event.preventDefault();

			//Refresh calculations
			var tax = Helpers.Tax.GetTaxAmount({ recalculateTax: true});
			var discount = Orderform.GetDiscountTotal();
			Calc.Subtotal = (Calc.ItemTotal + Calc.ShippingPrice - Math.abs(discount));
			
			//update the total
			$("#total_val").val(Calc.Subtotal + Calc.Tax);
			$('#order_confirmation').click();
		} else {
			return false;
		}
	},

	OrderConfirmation: function() {
		var terms = $('#order_terms_confirmed:checked');
		if (terms.size() == 0) {
			alert('You must agree to the terms and conditions!');
			return;
		}
		
		var referralSource = $('[name="survey_referral_source"]:checked');
		if (referralSource.size() == 0) {
			alert('Please let us know how you heard about us!');
			return;
		}
		
		var referralSourceText = referralSource.attr('data-text');
		if (referralSourceText == 'Other' && $.trim($('#survey_referral_other').val()) == '') {
			alert('Please describe how you heard about us!');
			return;
		}
		
		var orderForm = $('#orderform');
		$('#fancybox_order_confirmation :input').each(function() {
			$(this).clone().appendTo(orderForm);	
		})
				
		Validate.FinalSubmit();
	},
	
	FinalSubmit: function(options) {
		var options = (options) ? options : {};
		var defaults = { 
			generate_tran_fields: true 
		};
		
		/* merge defaults and options, without modifying defaults */
		var settings = $.extend({}, defaults, options);		
		
		if (_larsenDigital.data.submit_attempts > 3) {
			alert('There was a problem processing your order!');
			return;
		}
		
		_larsenDigital.data.submit_attempts += 1;
		
		//Enable fields
		var myform = $('form');
		var disabled = $(':disabled');
		disabled.removeAttr('disabled');

		//Generate iTransact fields
		if (settings.generate_tran_fields) {
			Orderform.GenerateTranFields();		
		}
		
	    $.ajax({ 
	    	async: false,
	        url: "/order/order-init.php?ms="+(new Date().getTime()),
	        type: "POST",
	        data: myform.serialize(),
	        datatype: "json",
	        success: function(response, textStatus, jqXHR) 
	        {
				var stagingId = 0;
				try {
					stagingId = response.order.order_staging_id;
				} catch(err) {};
				if (stagingId == 0 || isNaN(stagingId)) {
					Validate.FinalSubmit({ generate_tran_fields: false });
					return;
				}
	        	var qs = '?sid='+stagingId;

	        	//If it's a cash order bypass iTransact
	        	var transactionType = $('input[name=transaction_type]:checked').val();
	        	if (transactionType == 'cash') {
	        		window.document.location.href = '/order/newworkorder.php' + qs;
	        		return;
	        	}
	        	
				var retAddr = $('#ret_addr');
				var newAddr = retAddr.attr('base_value') + qs;
				retAddr.val(newAddr);
				
	        	//the order data has been saved in the session
	        	//submit the form
				$('form').get(0).submit();
	        },
	        error: function(jqXHR, textStatus, errorThrown) {
	        	//console.log(textStatus + ': ' + errorThrown);
	        }
	    });		
	},
	
	//VALIDATION RULES GO HERE
	FormIsValid: function()
	{
		if($("#videofiles").attr("checked") && $("#movie_harddrive").val() == "harddrive_none" && !$("#videooptions_pixorial").attr("checked"))
		{
			alert("You need to choose a hard drive for your AVI Files\r\n or check Pixorial");
			$("#movie_harddrive").focus();
			return false;
		}
		
		var video_tape_hard_drive_selected = false;
		$("input[name=video_hard_drive]").each(function()
		{
			if($(this).attr("checked"))
				video_tape_hard_drive_selected = true;
		});
		
		var videoStorageOptions = ['Playable DVD for TV', 'Pixorial', 'Video Files Saved to Disc', '16GB Thumb Drive', 'Video Files Saved to Hard Drive'];
		var videoStorageOptionChecked = $('#video_pixorial,#video_to_dvd,#video_to_data_dvd,#video_to_16gbthumbdrive,#video_to_file').filter(':checked');
		if (videoStorageOptionChecked.size() == 0) {
			alert("If you are ordering video tape services you must have one of the following video tape storage options selected:\n\n"+videoStorageOptions.join('\n'));
			return false;
		}
		
		var atleastone = false;
		$(".calc-media").each(function()
		{
			if($(this).val() > 0)
			{
				atleastone = true;
			}
		});
		
		var movieStorageOptions = ['Playable DVD for TV', 'Pixorial', 'Mp4 Video Files Saved to Disc', 'Blu-Ray', 'Mp4 Saved to Thumb Drive', 'Mp4 Saved to Hard Drive'];
		var movieStorageOptionChecked = $('#dvd,#videooptions_pixorial,#videooptions_savedtodisc,#bluray,#videooptions_16gbthumbdrive,#videofiles').filter(':checked');
		if (movieStorageOptionChecked.size() == 0) {
			alert("If you are ordering movie film services you must have one of the following movie film storage options selected:\n\n"+movieStorageOptions.join('\n'));
			return false;
		}
				
		var cassettes_done = true;
		
		$(".taperow").each(function()
		{
			if($(this).val() == 0)
			{
				cassettes_done = false;
			}
		});
		
		if(!cassettes_done)
		{
			alert("Some Cassette tapes still have options that need to be selected.");
			return false;
		}
		else if($("#estfootage").val() == 0 && Calc.MoviePrice > 0)
		{
			alert("Please enter number of Movie Reels sizes");
			return false;
		}
		else if(estft > 0 && !$("#videooptions_savedtodisc").attr("checked") && !$("#videofiles").attr("checked") && !$("#videooptions_16gbthumbdrive").attr("checked") && !$("#bluray").attr("checked") && !$("#dvd").attr("checked") && !$("#videooptions_pixorial").attr("checked"))
		{
			alert("For your Movie Films please choose an option in Step 2");
			return false;
		}
		//else if($("#video_qty").val() > 0 && !$("#video_to_dvd").attr("checked") && !$("#video_to_file").attr("checked"))
		//{
		//	alert("Please choose either DVD or Video Files for your Video Tapes");
		//	return false;
		//}
		else if($("#video_to_file").attr("checked") && !(video_tape_hard_drive_selected || $("#video_pixorial").attr("checked")))
		{
			alert("Please choose a hard drive or Pixorial Upload for your Video Tape Video Files");
			return false;
		}
		else if(!atleastone && Calc.Qty() > 0 && !Helpers.Media.IsHDSelected() && Helpers.Media.IsMediaRequired())
		{
			alert("You haven't selected how you want your scanned images delivered.\n\nPlease input a DVD quantity, select a \"Hard Drive\", or select a \"Download & Cloud\" option.");
			return false;
		}
		else if($("#ShippingOptions").val() == "59")
		{
			alert("You must choose a shipping option.");
			$("#ShippingOptions").focus();
			return false;
		}
		else if($("#shipto_custFirstName").val() == "" || $("#shipto_custLastName").val() == "")
		{
			alert("Please enter a first and last name");
			$("#shipto_custName").focus();
			return false;
		}
		else if($("#shipto_Addr1").val() == "")
		{
			alert("Please enter an address");
			$("#shipto_Addr1").focus();
			return false;
		}
		else if($("#shipto_City").val() == "")
		{
			alert("Please enter a city");
			$("#shipto_City").focus();
			return false;
		}
		else if($("#shipto_State").val() == "")
		{
			alert("Please select a state");
			$("#shipto_State").focus();
			return false;
		}
		else if($("#shipto_Zip").val() == "")
		{
			alert("Please enter a zip code");
			$("#shipto_Zip").focus();
			return false;
		}
		else if($("#shipto_DaytimePhone").val() == "" && $("#shipto_EveningPhone").val() == "")
		{
			alert("Please enter a daytime or evening phone number");
			$("#shipto_custname").focus();
			return false;
		}
		else if($("#shipto_EmailAddr").val() == "")
		{
			alert("Please enter an email address");
			$("#shipto_EmailAddr").focus();
			return false;
		}
		else if($("#shipto_EmailAddr").val() != $("#confirm_shipto_EmailAddr").val())
		{
			alert("Ship to email addresses do not match");
			$("#shipto_EmailAddr").focus();
			return false;
		}
		else if (!($("#billTo").attr("checked")))
		{
			if($("#billto_custFirstName").val() == "" || $("#billto_custLastName").val() == "")
			{
				alert("Please enter a first and last name");
				$("#billto_custName").focus();
				return false;
			}
			else if($("#billto_Addr1").val() == "")
			{
				alert("Please enter an address");
				$("#billto_Addr1").focus();
				return false;
			}
			else if($("#billto_City").val() == "")
			{
				alert("Please enter a city");
				$("#billto_City").focus();
				return false;
			}
			else if($("#billto_State").val() == "")
			{
				alert("Please select a state");
				$("#billto_State").focus();
				return false;
			}
			else if($("#billto_Zip").val() == "")
			{
				alert("Please enter a zip code");
				$("#billto_Zip").focus();
				return false;
			}
			else if($("#billto_DaytimePhone").val() == "" && $("#billto_EveningPhone").val() == "")
			{
				alert("Please enter a daytime or evening phone number");
				$("#billto_custname").focus();
				return false;
			}
			else if($("#billto_EmailAddr").val() == "")
			{
				alert("Please enter an email address");
				$("#billto_EmailAddr").focus();
				return false;
			}
			else if($("#billto_EmailAddr").val() != $("#confirm_billto_EmailAddr").val())
			{
				alert("Bill to email addresses do not match");
				$("#billto_EmailAddr").focus();
				return false;
			}
		}
		
		/*
		else if($("#ccNum").val() == "")
		{
			alert("Please enter a credit card number");
			$("#ccNum").focus();
			return false;
		}
		else if($("#cvv2").val() == "")
		{
			alert("Please enter a CVV2/CID code");
			$("#cvv2").focus();
			return false;
		}
		*/
		
		var cloudAuthRequired = Cloud.Storage.isAuthRequired();
		if (Calc.Total > 0 && cloudAuthRequired) {
			alert('You have requested delivery to a cloud storage provider but haven\'t authorized Larsen Digital to access any cloud storage solutions providers!');
			return;
		}
		
		/*
		var cloudDeliverySelected = Helpers.CloudDelivery.IsSelected();
		if (Calc.Total > 0 && cloudDeliverySelected) {
			var cloudSolutionAuthorized = Cloud.Storage.isAuthorized();
			if (!cloudSolutionAuthorized) {
				alert('You have requested delivery to a cloud storage provider but haven\'t authorized Larsen Digital to access any cloud storage solutions providers!');
				return;
			}
		}
		*/		
		
		return true;
	}
};