var listPaymentDevices = {};
var submtChkoutFrm=false;

var giftWindowVisible=false;
var giftFromDefault="";

var msgErrorQuantity = "HACK: Please enter a valid quantity!";
/*
var msgMinQuantity = "HACK: You need at least one";
var msgMaxQuantity = "HACK: You can only order: ";
var msgNaNQuantity = "HACK: That's not a number";
var msgWholeQuantity = "HACK: Only whole numbers";
*/

var maxGiftMessageLength = 500;
var maxProductQuantity = 100;
var unitProductPrice = 0;
var unitWowSavings = 0;
var COF = false;
var cofIndex = -1;

var is_ie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;

$(document).ready(function(){

	// Call Clear Inputs for form fields
	$('input.clearinput').each(function() {
		clearDefault($(this));
	});
	// Page defaults
	if (!isCounting) showTimeLeft();

    /*
	$("#accountCopyBox").change(function(){
		toggleAcctCopy();
	})*/
	// Select payment device from radio button

	$("#checkoutForm input[name=paymentMethod]").click(function() {
		$(".selectME").remove();
		$("select").css('display','block');
		$('select option:first-child').attr("selected", "selected");

		var errObj = $(".errCont");
		if(errObj.length) {
			setTimeout(function() {
				$(errObj).remove();
				throwErr(0, 0);
				$('.regform').removeAttr("style");
			}, 300);
		}
    	$("select").custSelect();
		selectPaymentDevice();
	});

	$("#checkoutForm #add-new-card").click(function() {
		$("#ccnew").attr('checked', true);
		$("#purchaseDealCreditCopy, #purchaseDealDebitCopy").hide();
		selectPaymentDevice();
	});

	$("#checkoutForm #cancel-new-card").click(function() {

		$("#checkoutForm")[0].reset();
		$(".selectME").remove();
		$("select").css('display','block');
		$('select option:first-child').attr("selected", "selected");

		var errObj = $(".errCont");
		if(errObj.length) {
			setTimeout(function() {
				$(errObj).remove();
				throwErr(0, 0);
				$('.regform').removeAttr("style");
			}, 300);
		}
    	$("select").custSelect();
		$("#purchaseDealCreditCopy, #purchaseDealDebitCopy, #paymentDevice").hide();
		defaultPaymentDevice();
	});
	
	if($("#checkoutForm input[name=paymentMethod]").length) $("input[name=paymentMethod]").addClass('regform');
});

function switchProcessButton() {
	//$("#purchaseDeal").addClass('purchaseDeal-process').html('PROCESSING <img src="https://s.aolcdn.com/art/paidservices/anim_processing.gif" width="30" height="30" />');
	if(is_ie)
	{	
		window.onbeforeunload = (function(){
			$("#purchaseDeal").css("background-image", "none");
			$("#purchaseDeal").css("background-image", "url(https://s.aolcdn.com/os/GPS/images/bg_purchase-butt2.gif)");
			$("#duplicatePurchase").css("background-image", "none");
			$("#duplicatePurchase").css("background-image", "url(https://s.aolcdn.com/os/GPS/images/bg_purchase-butt2.gif)");
		});
	}
	$("#purchaseDeal").addClass('purchaseDeal-process').val('');
	$("#purchaseDeal").attr('disabled', true);
	$("#duplicatePurchase").addClass('purchaseDeal-process').val('');
	$("#duplicatePurchase").attr('disabled', true);
}
function revertProcessButton() {
	$("#purchaseDeal").removeClass('purchaseDeal-process').val('PLACE ORDER');
	$("#purchaseDeal").attr('disabled', false);
	$("#duplicatePurchase").removeClass('purchaseDeal-process').val('CONTINUE');
	$("#duplicatePurchase").attr('disabled', false);
}

function initCopyFirstLastName() {
	$("#createAccount #firstName").blur(function () {
		var fname = $("#firstName").val();
		if (fname) {
			var cfirst = $("#firstNameOnCard").val();
			if ((!cfirst) || (cfirst.length == 0)) {
				$("#firstNameOnCard").val(fname);
				$("#firstNameOnCard").blur();
			}
			//alert(fname + " " + cfirst);
		}	
	});
	$("#createAccount #lastName").blur(function () {
		var lname = $("#lastName").val();
		if (lname) {
			var clast = $("#lastNameOnCard").val();
			if ((!clast) || (clast.length == 0)) {
				$("#lastNameOnCard").val(lname);
				$("#lastNameOnCard").blur();
			}
			//alert(lname + " " + clast);
		}	
	});
}

function initQuantityCheck() {
	$("#checkoutForm #quantity").change(function () { validateQuantity(); });
}

function submitCheckoutForm() {
	switchProcessButton();
	submtChkoutFrm=true;
	if (validateCheckoutForm()) {
		if (!checkDuplicateSub)
		{
			//$('#purchaseDeal').attr("href", "#");
			//$('#cancelCheckoutPage').hide();
			$('#checkoutWarning').show();
			checkDuplicateSub = false;
			document.getElementById("cardType").disabled=false;
			document.getElementById("cardNumber").disabled=false;
			submitForm("#checkoutForm");//submitFormAJAX("#checkoutForm",  resultCheckout);
		}
		else
		{
			checkDuplicateSub = false;
			revertProcessButton();
			$('#errorBox').hide();
			$('#duplicateWarningBox').show();
			$('#checkoutBody').hide();
			$( 'html, body' ).animate( { scrollTop: 0 }, 0 );
		}
	}
	else
	{
		revertProcessButton();
	}
}

function validateCheckoutForm() {
	returnCode=false;
	paymentDeviceDiv = $('#paymentDevice');

	$(".regform:not(:disabled)").each(function () {
		thisElemt = $(this).attr('id');
		parentFrmId = $(this).parents('form:first').attr('id');
		if(paymentDeviceDiv.is(":hidden")) {
			if(paymentDeviceDiv.find('#'+thisElemt).length) {
				return;
			} else {
				if(!$("#checkoutForm input[name=paymentMethod]:checked").val() && (thisElemt != "iagree")) {
					errMsg = "Please select a form of payment from the list above, or click the \"Add New\" link to use a different form of payment.";
					throwErr("creditCards", errMsg, parentFrmId);
					returnCode=true;
					return false;
				}
			}
		}
		if((thisElemt != "email") || (thisElemt == "email" && (($.trim($(this).val()) == "example: email@domain.com") || ($.trim($(this).val()) == ""))))
		{
			fieldValidate(this, parentFrmId);
			var rcType = typeof returnCode;
			if(rcType == 'string') returnCode=1;
			 if(returnCode) {
				if($('#' +errorField).is(":hidden"))
				{
					 errorField = errorField + "_custom";
				}
				var errorInput = $("#"+parentFrmId+" #"+errorField)
				setTimeout(function() {
					errorInput.focus();
				}, 40);
				return false;
			 }
		}
	});
	
	if(!returnCode)
	{
		fieldValidate($('#email'), parentFrmId);
		var rcType = typeof returnCode;
		if(rcType == 'string') returnCode=1;
		 if(returnCode) {
			 if($('#' +errorField).is(":hidden"))
			{
				 errorField = errorField + "_custom";
			}
			var errorInput = $("#"+parentFrmId+" #"+errorField)
			setTimeout(function() {
				errorInput.focus();
			}, 40);
			return false;
		 }
	}
	return (!returnCode)?true:false;
}

function defaultPaymentDevice() {
	if (cofIndex != -1)
	{
		$("#checkoutForm input[name=paymentMethod]").eq(cofIndex).attr('checked', true);
	}
	else
	{
		$("#checkoutForm input[name=paymentMethod]").eq(-2).attr('checked', true);
	}
	selectPaymentDevice();
}

function selectPaymentDevice() {
	
	var selected = $("input[name=paymentMethod]:checked")
	var index = $("input[name=paymentMethod]").index(selected);
	
	if ((listPaymentDevices.obiInstruments) && (index < listPaymentDevices.obiInstruments.length)) 
	{
		$("#paymentDevice").hide();
		$("input[name=cardActivityType]").val("");
		/*
		if(listPaymentDevices.obiInstruments[index].expired==false)
		{
			$("#paymentDevice").hide();
			document.getElementById("cardType").disabled=false;
			document.getElementById("cardNumber").disabled=false;
		}
		else
		{
			document.getElementById("cardType").disabled=true;
			document.getElementById("cardNumber").disabled=true;
			$("#paymentDevice").show();
			$("input[name=cardActivityType]").val("edit");
			COF = false;
		}
		*/
		if(listPaymentDevices.obiInstruments[index].obiPaymentMethodId == "COF")
		{
			$("input[name=cardActivityType]").val("add");
			COF = true;
		}
		else
		{
			COF = false;
		}
		setPaymentDeviceForm(listPaymentDevices.obiInstruments[index]);
		showCreditDebitCopy(listPaymentDevices.obiInstruments[index].cardType.toLowerCase());
		selected.focus();
	} 
	else
	{
		if (listPaymentDevices.obiInstruments && listPaymentDevices.obiInstruments.length > 0)
		{
			setPaymentDeviceForm(null);
		}
		document.getElementById("cardType").disabled=false;
		document.getElementById("cardNumber").disabled=false;
		$("#paymentDevice").show();
		$("input[name=cardActivityType]").val("add");
		COF = false;
	}
}

function setPaymentDeviceForm(obiInstrument) {

	
	$('.regform').removeAttr("style");
    $('.errCont').remove();	

	if (obiInstrument) {
		$("input[name=contactMechId]").val(obiInstrument.contactMechId);
		$("input[name=paymentMethodId]").val(obiInstrument.paymentMethodId);
		$("input[name=obiPaymentMethodId]").val(obiInstrument.obiPaymentMethodId);
		$("input[name=cardOnFileFlag]").val(obiInstrument.cardOnFileFlag);

		$("input[name=firstNameOnCard]").val(obiInstrument.firstNameOnCard);
		$("input[name=lastNameOnCard]").val(obiInstrument.lastNameOnCard);
		setDropDownValue("select[name=cardType]", obiInstrument.cardType); //$("select[name=cardType]").val(obiInstrument.cardType);
		$("input[name=cardNumber]").val(obiInstrument.cardNumber);
		setDropDownValue("select[name=expMonth]", obiInstrument.expMonth); //$("select[name=expMonth]").val(obiInstrument.expMonth);
		setDropDownValue("select[name=expYear]", obiInstrument.expYear); //$("select[name=expYear]").val(obiInstrument.expYear);
		$("input[name=cardSecurityCode]").val("");
		$("input[name=billToAddress1]").val(obiInstrument.billToAddress1);
		$("input[name=billToAddress2]").val(obiInstrument.billToAddress2);
		$("input[name=billToCity]").val(obiInstrument.billToCity);
		setDropDownValue("select[name=billToStateProvinceGeoId]", obiInstrument.billToStateProvinceGeoId); //$("select[name=billToStateProvinceGeoId]").val(obiInstrument.billToStateProvinceGeoId);
		$("input[name=billToPostalCode]").val(obiInstrument.billToPostalCode);
		$("input[name=countryGeoId]").val(obiInstrument.countryGeoId);
	} else {
		$("input[name=contactMechId]").val("");
		$("input[name=paymentMethodId]").val("");
		$("input[name=obiPaymentMethodId]").val("");
		
		$("input[name=firstNameOnCard]").val("");
		$("input[name=lastNameOnCard]").val("");
		setDropDownValue("select[name=cardType]", ""); //$("select[name=cardType]").val("");
		$("input[name=cardNumber]").val("");
		setDropDownValue("select[name=expMonth]", ""); //$("select[name=expMonth]").val("");
		setDropDownValue("select[name=expYear]", ""); //$("select[name=expYear]").val("");
		$("input[name=cardSecurityCode]").val("");
		$("input[name=billToAddress1]").val("");
		$("input[name=billToAddress2]").val("");
		$("input[name=billToCity]").val("");
		setDropDownValue("select[name=billToStateProvinceGeoId]", ""); //$("select[name=billToStateProvinceGeoId]").val("");
		$("input[name=billToPostalCode]").val("");
		$("input[name=countryGeoId]").val("");
	}
	
}

function setDropDownValue(dropdown, value) {
	
	var found = false;
	if(!value)
	{
		value = "";
	}
	$.each($(dropdown).children("option"), function() {
			if ((this.value) && (this.value.toLowerCase() == value.toLowerCase())) {
				this.selected = true;
				found = true;
			}
			else
				this.selected = false;
	});
	if (!found) $(dropdown).children("option").first().attr("selected", "true");
	//$(dropdown).children("option[value=" + value.toLowerCase() + "]").attr("selected", "true");
}

function toggleAcctCopy(){
	/*
	if(document.getElementById("accountCopyBox").checked == true)
	{
		document.getElementById("firstNameOnCard").disabled=true;
		document.getElementById("lastNameOnCard").disabled=true;
	}
	else
	{
		document.getElementById("firstNameOnCard").disabled=false;
		document.getElementById("lastNameOnCard").disabled=false;
	}
	*/	
}

function copyAcctInfo(){
	
	if(document.getElementById("accountCopyBox").checked == true)
	{
		if(document.getElementById('firstName').value != null)
		{
			$("input[name=firstNameOnCard]").val(document.getElementById('firstName').value);
		}
	
		if(document.getElementById('lastName').value != null)
		{
			$("input[name=lastNameOnCard]").val(document.getElementById('lastName').value);
		}
	}
	return;
}
