/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	GENERIC METHODS
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

var createElementWithName = ( function(){
  try {
    var el = document.createElement( '<div name="foo">' );
    if( el.tagName !== 'DIV' || el.name !== 'foo' ){
      throw 'create failed';
    }
    return function( tag, name ){
      return document.createElement( '<' + tag + ' name="' +
        name + '"></' + tag + '>' );
    };
  }catch( e ){
    return function( tag, name ){
      var el = document.createElement( tag );
      el.setAttribute( 'name', name );
      return el;
    };
  }
})();

function isNumeric(testStr) {
	var isValid = true;
	var validChars = "0123456789";
	var character;

	if ( typeof(testStr) != "undefined" && testStr != null && testStr != "" ) {
		for (i = 0; i < testStr.length && isValid; i++) {
			character = testStr.charAt(i);
			if (validChars.indexOf(character) == -1) {
				isValid = false;
			}
		}
	}
	else {
		isValid = false;
	}

	return isValid;
}

function IsLessThan(strElementValue, strLessThanValue, strElementType) {
    if (strElementType == "integer") {
        strElementValue = strElementValue * 1;
        strLessThanValue = strLessThanValue * 1;
    }
    if (strElementType == "real") {
        strElementValue = strElementValue * 1;
        strLessThanValue = strLessThanValue * 1;
    }
    if (strElementType == "date") {
        if (strElementValue.indexOf("-", 0) == -1) {
            chrSep = "/";
        } else {
            chrSep = "-";
        }
        intFirstSep = strElementValue.indexOf(chrSep);
        intMonth = strElementValue.substring(0, intFirstSep) * 1;
        strElementValue = strElementValue.substring(intFirstSep + 1, strElementValue.length);
        intSecondSep = strElementValue.indexOf(chrSep);
        intDay = strElementValue.substring(0, intSecondSep) * 1;
        strElementValue = strElementValue.substring(intSecondSep + 1, strElementValue.length);
        intYear = strElementValue.substring(0, strElementValue.length) * 1;
        intFirstSep = strLessThanValue.indexOf(chrSep);
        intCompareMonth = strLessThanValue.substring(0, intFirstSep) * 1;
        strElementValue = strLessThanValue;
        strElementValue = strElementValue.substring(intFirstSep + 1, strElementValue.length);
        intSecondSep = strElementValue.indexOf(chrSep);
        intCompareDay = strElementValue.substring(0, intSecondSep) * 1;
        strElementValue = strElementValue.substring(intSecondSep + 1, strElementValue.length);
        intCompareYear = strElementValue.substring(0, strElementValue.length) * 1;
        if (intYear > intCompareYear) {
            return false;
        }
        if ((intYear == intCompareYear) && (intMonth > intCompareMonth)) {
            return false;
        }
        if ((intYear == intCompareYear) &&
            (intMonth == intCompareMonth) && (intDay >= intCompareDay)) {
            return false;
        }
        return true;
    }
    if (strElementValue <= strLessThanValue) {
        return true;
    } else {
        return false;
    }
}

function openWindow(address, width, height, features) {
	/* Find out what features need to be enable
	 *
	 */
	if(features)
		features = features.toLowerCase();
	else
		features = "";

	var toolbar = (features == "all" ? 1 : 0);
	var menubar = (features == "all" ? 1 : 0);
	var location = (features == "all" ? 1 : 0);
	var directories = (features == "all" ? 1 : 0);
	var status = (features == "all" ? 1 : 0);
	var scrollbars = (features == "all" ? 1 : 0);
	var resizable = (features == "all" ? 1 : 0);

	if(features != "all") {
		//split features
		var feature = features.split(",");
		for(i = 0; i < feature.length; i++)
		{
		 	if(feature[i] == "toolbar")
			   toolbar = 1;
			else if(feature[i] == "menubar")
			   menubar = 1;
			else if(feature[i] == "location")
			   location = 1;
			else if(feature[i] == "directories")
			   directories = 1;
			else if(feature[i] == "status")
			   status = 1;
			else if(feature[i] == "scrollbars")
			   scrollbars = 1;
			else if(feature[i] == "resizable")
			   resizable = 1;
		}

	}
	features = "toolbar=" + toolbar + ",";
	features += "menubar=" + menubar + ",";
	features += "location=" + location + ",";
	features += "directories=" + directories + ",";
	features += "status=" + status + ",";
	features += "scrollbars=" + scrollbars + ",";
	features += "resizable=" + resizable;

	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',"' + features + '"');
	//newWindow.focus();
}

function launchPopup(event) {
	event.preventDefault();
	openWindow(this.href, 740, 600, 'scrollbars'); 
}

function printText(elId) {
	var href = "/static/checkout/print_popup.htm?passedText=" + elId;
	openWindow(href, 740, 600, 'scrollbars');	
}

function doZipFocus(component) {
	var searchVal = component.value;
	if (searchVal == "Enter ZIP Code") {
		component.value = "";
	}
}

function doZipBlur(component) {
	var searchVal = component.value;
	if (searchVal == '') {
		component.value = "Enter ZIP Code";
	}
}

function doCouponFocus(component) {
	var searchVal = component.value;
	if (searchVal == "Enter Code") {
		component.value = "";
	}
}

function doCouponBlur(component) {
	var searchVal = component.value;
	if (searchVal == '') {
		component.value = "Enter Code";
	}
}

function currentDate() {
	var d = new Date();
	var date = d.getDate();
	if( date < 10) date = "0" + date;
	var month = d.getMonth() + 1;
	if( month < 10) month = "0" + month;
	var year = d.getFullYear();
	return month + "/" + date + "/" + year;
}

/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	FORM VALIDATION
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

function addError(key, errorText) {
	$(key).addClass("form-field-error");
	$(key+" .error").html(errorText);
}

function removeErrors() {
	$(".form-field-error div.error").html("");
	$(".form-field-error").removeClass("form-field-error");
}

function validateFirstName(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a first name.";
	else
		return "";
}

function validateLastName(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a last name.";
	else
		return "";
}

function validateBillingAddress(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a billing address.";
	else
		return "";
}

function validateCity(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a city.";
	else
		return "";
}

function validateState(val) {
	var state = jQuery.trim(val);
	if (state == "")
		return "Please enter a state.";
	else if( state == "FL")
		return "We're sorry, we cannot complete your order online. For products that will be used in Florida, please contact the Customer Care Plan department at 1-800-637-2007.";
	return "";
}

function validateAccepted(el) {
	if( $(el).is( ":checked")) {
		return ""
	}
	return "You must agree to the terms and conditions to proceed";
}

function validateZip(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a ZIP Code.";
	else if (!isNumeric(val) || val.length != 5 )
		return "Please enter a valid ZIP Code.";
	else if(zipFlag == "true")
		return "Please enter a valid ZIP Code.";
	else
		return "";
}

function validatePhone(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a phone number.";
	else
		return "";
}


function validateEmail(val) {
	val = jQuery.trim(val);
	if (val.length == 0)
		return "Please enter an email address.";
	else if (val.indexOf("@") <= 0 || val.indexOf(" ") > -1 || val.length < 5)
		return "Please enter a valid email address.";		
	else
		return "";
}

function validateConfirmEmail(valConfirm,valOriginal) {
	valConfirm = jQuery.trim(valConfirm);
	valOriginal = jQuery.trim(valOriginal);
	if (valOriginal == 0)
		return "Please enter an email address.";
	else if (valConfirm.length == 0)
		return "Please confirm your email address.";
	else if (valConfirm != valOriginal)
		return "Please enter a valid email address.";		
	else
		return "";
}

function validateCreditCardName(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter name on the card.";
	else
		return "";
}

function validateCreditCardType(val) {
	if (jQuery.trim(val).length == 0)
		return "Please select a payment method.";
	else
		return "";
}

function validateCreditCardNumber(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a credit card number.";
//commented out since rule doesn't apply for AMEX or Panasonic Direct
//	else if (jQuery.trim(val).length != 16)
//		return "Please enter a valid credit card number.";
	else if($("#pay_cctype select").val() == "AMEX") {
		if(jQuery.trim(val).length != 15) 
			return "The Card Number must be 15 characters long.";
		else
			return "";
	} else if(jQuery.trim(val).length != 16) 
		return "The Card Number must be 16 characters long.";
	else if (!isNumeric(val))
		return "Please enter a valid credit card number.";
	else
		return "";
}

function validateCardMonth(val) {
	if (jQuery.trim(val).length == 0)
		return "Please select an expiration month.";
	else
		return "";
}

function validateCardYear(val) {
	if (jQuery.trim(val).length == 0)
		return "Please select an expiration year.";
	else
		return "";
}

//validate expiration date - should be set dynamically
var date= new Date();
var strCurrentDate = (date.getMonth() + 1) + "/01/" + date.getFullYear();
function validateCardDate(expMonth,expYear) {
	var strExpDateSelected = expMonth + "/01/" + expYear;
	if (IsLessThan(strExpDateSelected, strCurrentDate, "date"))
		return "The selected expiration date has passed.  Please select a valid expiration date.";
	else
		return "";
}

function validateCreditCardCCV(val) {
	if($("#pay_cctype select").val() == "GE") {
		document.frmPayment.ccv.value = "";
		return "";

	}else if (jQuery.trim(val).length == 0)
		return "Please enter a CCV code.";
//commented out since rule doesn't apply for AMEX or Panasonic Direct
//	else if (jQuery.trim(val).length != 3)
//		return "Please enter a valid CCV code.";
else if($("#pay_cctype select").val() == "AMEX") {
		if(jQuery.trim(val).length != 4) 
			return "The CCV code must be 4 characters long.";
		else
			return "";
	} else if(jQuery.trim(val).length != 3) 
		return "The CCV code must be 3 characters long.";
	else if (!isNumeric(val))
		return "Please enter a valid CCV code.";
	else
		return "";
}

function validateGiftCardNumber(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a gift card number.";
	else if (jQuery.trim(val).length != 15)
		return "The Gift Card Number must be 15 characters long..";
	else if (!isNumeric(val))
		return "Please enter a valid gift card number.";
	else
		return "";
}

function validateGiftCardPIN(val) {
	if (jQuery.trim(val).length == 0)
		return "Please enter a PIN number.";
	else if (jQuery.trim(val).length != 4)
		return "The Gift Card Pin must be 4 characters long.";
	else if (!isNumeric(val))
		return "Please enter a valid PIN number.";
	else
		return "";
}

/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	CONFIGURE A PRODUCT METHODS
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

var planDetailsOpen = -1; //tracks which care plan is active

function selectCarePlan(event) {
	if (planDetailsOpen >= 0) {
		//a different plan is open, so turn that button off first
		$("#selectPlan_"+planDetailsOpen).attr("src","/static/checkout/images/buttons/choose.gif");
		$("#ccpDetails_"+planDetailsOpen).toggleClass("nobox").toggleClass("box-blue");
	}

	event.preventDefault();
	var el = null;
	if (this.nodeName == "A")
		el = this.childNodes[0];
	else
		el = this;

	$(el).attr("src","/static/checkout/images/buttons/selected.gif");
	var key = $(el).attr("id").split("_");
	var index = key[1];
	$("#ccpDetails_"+index).toggleClass("nobox").toggleClass("box-blue");
	$("#ccp_TC").slideDown("normal");
	location.href = "#customer_care_plan";
	planDetailsOpen = index;
	$("#itemId_ccp").val(
	  $("#itemId_ccp_" + index).val()
	);
}

function stateSelect() {
}

function invalidPlan(type) {
	var errorText = "";
	var hasErrors = false;

	var stateOfResidence = "";
	if( "ccp" == type) {
		var stateOfResidence = $("#state_ccp").val();
		errorText = validateState( stateOfResidence);
		if( "" != errorText) {
			addError( "#configure_state_ccp", errorText);
			hasErrors = true;
		}
	}

	errorText = validateAccepted( "#accept_" + type);
	if( "" != errorText) {
		addError( "#configure_accept_" + type, errorText);
		hasErrors = true;
	}
	return hasErrors;
}

function submitPlan(type, event) {
	event.preventDefault();

	var typeName = "plan";
	if( "ccp" == type) {
		typeName = "Customer Care Package";
	} else if( "install" == type) {
		typeName = "Service Plan";
	}

	removeErrors();
    if( invalidPlan( type)) {
    	location.href = "#" + type + "_TC";
    	return;
    }

	var catEntryId=$("#itemId_" + type).val();
	var purchaseDate = currentDate();
	var modelNumber = $("#modelNumber_1").val();

	document.frmOptionAdd.catEntryId.value = catEntryId;
	document.frmOptionAdd.purchasePlace.value = "PanasonicDirect"
	document.frmOptionAdd.purchaseDate.value = purchaseDate;
	document.frmOptionAdd.modelNumber.value = modelNumber;
	document.frmOptionAdd.submit();
}
function submitCcp(event) {
	return submitPlan("ccp", event);
}
function submitInstall(event) {
	return submitPlan("install", event);
}

function cancelCcp(event) {
	event.preventDefault();
	removeErrors();
	if (planDetailsOpen >= 0) {
		//a different plan is open, so turn that button off first
		$("#selectPlan_"+planDetailsOpen).attr("src","/static/checkout/images/buttons/choose.gif");
		$("#ccpDetails_"+planDetailsOpen).toggleClass("nobox").toggleClass("box-blue");
	}
	$("#ccp_TC").slideUp("normal");
	planDetailsOpen = -1;
}

var installDetailsOpen = -1; //tracks which installation plan is active

function selectInstallPlan(event) {
	if (installDetailsOpen >= 0) {
		//a different plan is open, so turn that button off first
		$("#selectInstall_"+installDetailsOpen).attr("src","/static/checkout/images/buttons/choose.gif");
		$("#installDetails_"+installDetailsOpen).toggleClass("nobox").toggleClass("box-blue");
	}

	event.preventDefault();
	var el = null;
	if (this.nodeName == "A")
		el = this.childNodes[0];
	else
		el = this;

	$(el).attr("src","/static/checkout/images/buttons/selected.gif");
	var key = $(el).attr("id").split("_");
	var index = key[1];
	$("#installDetails_"+index).toggleClass("nobox").toggleClass("box-blue");
	$("#install_TC").slideDown("normal");
	location.href = "#installation_service";
	installDetailsOpen = index;
	$("#itemId_install").val(
	  $("#itemId_install_" + index).val()
	);
}

function submitInstallation(event) {
	// this is the submit action for adding an installation service
	
}

function cancelInstall(event) {
	event.preventDefault();
	removeErrors();
	if (installDetailsOpen >= 0) {
		//a different plan is open, so turn that button off first
		$("#selectInstall_"+installDetailsOpen).attr("src","/static/checkout/images/buttons/choose.gif");
		$("#installDetails_"+installDetailsOpen).toggleClass("nobox").toggleClass("box-blue");
	}

	$("#install_TC").slideUp("normal");
	installDetailsOpen = -1;
}

var recommendedIndex = 1;//the tab index thats open by default 

function tabClick(event) {
	event.preventDefault();
	var key = $(this).attr("id").split("_");
	var index = key[1];
	$("#tabrow_"+recommendedIndex).removeClass("on");
	$("#tabcontent_"+recommendedIndex).hide();
	$("#tabrow_"+index).addClass("on");
	$("#tabcontent_"+index).show();
	recommendedIndex = index;
}

function addToCartClick(event) {
	event.preventDefault();
	var key = $(this).attr("id").split("_");
	var catEntryId = key[1];
	document.frmOptionAdd.catEntryId.value = catEntryId;
	document.frmOptionAdd.submit();
}

function proceedToCartClick(event) {
	var hasErrors = false;
	removeErrors();
	if (planDetailsOpen >= 0) {
		if( !invalidPlan( "ccp")) {
			addError( "#ccp_button_row", "Click Submit to add this care plan to your cart.<br>Or click Cancel if you do not need a care plan.");
		}
    	location.href = "#ccp_TC";
		return false;
	}
	if (installDetailsOpen >= 0) {
		if( !invalidPlan( "install")) {
			addError( "#install_button_row", "Click Submit to add this installation package to your cart.<br>Or click Cancel if you do not need installation.");
		}
    	location.href = "#install_TC";
		return false;
	}
    return true;
}

/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	SHOPPING CART
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

var exposedCarePlans;
var selectedCarePlanImage;

function updateCartItemClick(event) {
	event.preventDefault();
	var parse = $(this).attr("id").split("_");
	var row = parse[ 1];
	var quantity = $("#quantity_" + row).val();
	var orderItemId = $("#orderItemId_" + row).val();

	var dynamic_fields = $( ".dynamic_fields");
	dynamic_fields.empty();

	var input = createElementWithName( "input", "quantity_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", quantity);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "orderItemId_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", orderItemId);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	document.frmCartUpdate.submit();
}

function deleteCartItemClick(event) {
	event.preventDefault();
	var parse = $(this).attr("id").split("_");
	var row = parse[ 1];
	var orderItemId = $("#orderItemId_" + row).val();

	var dynamic_fields = $( ".dynamic_fields");
	dynamic_fields.empty();

	var input = createElementWithName( "input", "quantity_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", "0");
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "orderItemId_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", orderItemId);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	document.frmCartUpdate.submit();
}

function exposeCarePlans(event) {
	event.preventDefault();
	removeErrors();
	if (this.nodeName == "A")
		el = this.childNodes[0];
	else
		el = this;
	var key = $(el).attr("id").split("_");
	var type = key[1];
	var index = key[2];
	if( exposedCarePlans) {
		$(exposedCarePlans).slideUp("normal");
	}
	exposedCarePlans = "#cartAddOn_" + type + "_" + index;
	$(exposedCarePlans).slideDown("normal");
	location.href = exposedCarePlans;
}

function selectPlanCart(event) {
	event.preventDefault();
	var el = null;
	if (this.nodeName == "A")
		el = this.childNodes[0];
	else
		el = this;

	if( selectedCarePlanImage) {
		$(selectedCarePlanImage).attr( "src", "/static/checkout/images/buttons/choose.gif");
	}
	selectedCarePlanImage = el;
	$(el).attr("src","/static/checkout/images/buttons/selected.gif");
	var key = $(el).attr("id").split("_");
	var type = key[1];
	var cartRow = key[2];
	var planRow = key[3];
	$("#itemIdSelected_" + cartRow).val(
	  $("#itemId_" + type + "_" + cartRow + "_" + planRow).val()
	);
}

function cancelPlanCart(event) {
	event.preventDefault();
	removeErrors();
	if (this.nodeName == "A")
		el = this.childNodes[0];
	else
		el = this;
	var key = $(el).attr("id").split("_");
	var type = key[1];
	var index = key[2];
	exposedCarePlans = "#cartAddOn_" + type + "_" + index;
	$(exposedCarePlans).slideUp("normal");
	exposedCarePlans = null;
}

function submitPlanCart(event) {
	event.preventDefault();
	if (this.nodeName == "A")
		el = this.childNodes[0];
	else
		el = this;
	var key = $(el).attr("id").split("_");
	var type = key[1];
	var cartRow = key[2];

	var typeName = "plan";
	if( "ccp" == type) {
		typeName = "Customer Care Package";
	} else if ("install" == type) {
		typeName = "Service Plan";
	}
	var errorText = "";
	var hasErrors = false;
	removeErrors();

    if( "ccp" == type) {
		var stateOfResidence = $("#state_" + type + "_" + cartRow).val();
		errorText = validateState( stateOfResidence);
		if( "" !== errorText) {
			addError( "#cart_state_" + type + "_" + cartRow, errorText);
			hasErrors = true;
		}
	}

	var itemId=$("#itemIdSelected_" + cartRow).val();
	if( "" == itemId) {
		errorText = "Select the " + typeName + " which you would like to purchase";
		hasErrors = true;
		addError( "#cart_selected_" + type + "_" + cartRow, errorText);
	}	

	errorText = validateAccepted( "#accept_" + type + "_" + cartRow);
	if( "" != errorText) {
		addError( "#cart_accept_" + type + "_" + cartRow, errorText);
		hasErrors = true;
	}

    if( hasErrors) {
     	return;
	}
	
	var ownerOrderItemId = $("#orderItemId_" + cartRow).val();
	var modelNumber = $("#modelNumber_" + cartRow).val();
	var purchaseDate = currentDate();

	var dynamic_fields = $( ".dynamic_fields");
	dynamic_fields.empty();

	var input = createElementWithName( "input", "quantity_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", "1");
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "catEntryId_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", itemId);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "ownerOrderItemId_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", ownerOrderItemId);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "purchasePlace_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", "PanasonicDirect");
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "purchaseDate_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", purchaseDate);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	input = createElementWithName( "input", "modelNumber_1");
	input.setAttribute("type", "hidden");
	input.setAttribute("value", modelNumber);
	input.setAttribute("class", "dynamic");
	dynamic_fields.append(input);

	if( "ccp" == type) {
		input = createElementWithName( "input", "stateOfResidence_1");
		input.setAttribute("type", "hidden");
		input.setAttribute("value", stateOfResidence);
		input.setAttribute("class", "dynamic");
	}
	
	dynamic_fields.append(input);
	document.frmCartUpdate.submit();
}

/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	BILLING & SHIPPING INFO
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

function toggleDeliveryAddress() {
	if ($('#shiptobilling').is(':checked')) {
		//roll up form and ship to billing address
		//might also need to clear values upon integration?

		$("#shipToNewAddress").slideUp("normal");
	
	} else {
		//roll down the form
	
		$("#shipToNewAddress").slideDown("normal");
	}
}

function errorsInBillingForm() {
	var hasErrors = false;
	var errorText = "";

	errorText = validateFirstName($("#bFirst input").val());
	if (errorText != "") {
		addError("#bFirst", errorText);
		hasErrors = true;
	}

	errorText = validateLastName($("#bLast input").val());
	if (errorText != "") {
		addError("#bLast", errorText);
		hasErrors = true;
	}

	errorText = validateBillingAddress($("#bAddress input").val());
	if (errorText != "") {
		addError("#bAddress", errorText);
		hasErrors = true;
	}

	errorText = validateCity($("#bCity input").val());
	if (errorText != "") {
		addError("#bCity", errorText);
		hasErrors = true;
	}

	errorText = validateZip($("#bZip input").val());
	if (errorText != "") {
		addError("#bZip", errorText);
		hasErrors = true;
	}

	errorText = validatePhone($("#billphone1").val());
	if (errorText != "") {
		addError("#bPhone", errorText);
		hasErrors = true;
	}
	errorText = validatePhone($("#billphone2").val());
	if (errorText != "") {
		addError("#bPhone", errorText);
		hasErrors = true;
	}
	errorText = validatePhone($("#billphone3").val());
	if (errorText != "") {
		addError("#bPhone", errorText);
		hasErrors = true;
	}

	var email = $("#bEmail input").val();
	errorText = validateEmail(email);
	if (errorText != "") {
		addError("#bEmail", errorText);
		hasErrors = true;
	}

	errorText = validateConfirmEmail($("#bConfirmEmail input").val(), email);
	if (errorText != "") {
		addError("#bConfirmEmail", errorText);
		hasErrors = true;
	}

	return hasErrors;
}

function errorsInShippingForm() {
	var hasErrors = false;
	var errorText = "";

	errorText = validateFirstName($("#sFirst input").val());
	if (errorText != "") {
		addError("#sFirst", errorText);
		hasErrors = true;
	}

	errorText = validateLastName($("#sLast input").val());
	if (errorText != "") {
		addError("#sLast", errorText);
		hasErrors = true;
	}

	errorText = validateBillingAddress($("#sAddress input").val());
	if (errorText != "") {
		addError("#sAddress", errorText);
		hasErrors = true;
	}

	errorText = validateCity($("#sCity input").val());
	if (errorText != "") {
		addError("#sCity", errorText);
		hasErrors = true;
	}

	errorText = validateZip($("#sZip input").val());
	if (errorText != "") {
		addError("#sZip", errorText);
		hasErrors = true;
	}

	errorText = validatePhone($("#txtShipPhone").val());
	if (errorText != "") {
		addError("#sPhone", errorText);
		hasErrors = true;
	}
	errorText = validatePhone($("#txtShipPhone2").val());
	if (errorText != "") {
		addError("#sPhone", errorText);
		hasErrors = true;
	}
	errorText = validatePhone($("#txtShipPhone3").val());
	if (errorText != "") {
		addError("#sPhone", errorText);
		hasErrors = true;
	}

	return hasErrors;
}

var reShipToPo = /.*(?:(?:p\W*o\W*(:?b\W*)*)|(?:box))\w*\W+\w*\d|^\W*p\W*o(?:b(?:ox)?\W*)?$/gi;
function errorShipToPO( addressField) {
	var hasErrors = false;
	var errorText = "";
	var addressLine = $( addressField + " input").val();
	if( addressLine.match( reShipToPo)) {
		addError( addressField, "Cannot ship to a PO Box. Please select a different ship to address.");
		hasErrors = true;
	}
	return hasErrors;
}

function validateBilling(event) {
	event.preventDefault();
	removeErrors();//reset messaging
	var hasErrors = false;

	$("#billAddressError").hide();//reset
	$("#shipAddressError").hide();
	if (errorsInBillingForm()) {
		$("#billAddressError").show();
		hasErrors = true;
	}

	if (!$('#shiptobilling').is(':checked')) {
		if (errorsInShippingForm()) {
			$("#shipAddressError").show();
			hasErrors = true;
		}
		if( errorShipToPO( "#sAddress")) {
			hasErrors = true;
		}
		if( errorShipToPO( "#sAddress2")) {
			hasErrors = true;
		}
		if ($('#txtShipZip').attr("disabled") == true)
		{
			alert("Please wait, Calculating Shipping....");
			hasErrors = true;
		}
	} else {
		if( errorShipToPO( "#bAddress")) {
			hasErrors = true;
		}
		if( errorShipToPO( "#bAddress2")) {
			hasErrors = true;
		}
		if ($('#billzip').attr("disabled") == true)
		{
			alert("Please wait, Calculating Shipping....");
			hasErrors = true;
		}
	}

	if (!hasErrors) {
		proceed();
	}
}


/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	PAYMENT
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

function exposeGiftCards() {
	document.frmPayment.moreGiftCard.value = "Y";
	$("#additionalGiftCards").slideDown("normal");
	$("#exposeGiftCards").hide();
}


function errorsInPaymentForm() {
	var hasErrors = false;
	var errorText = "";

	errorText = validateCreditCardName($("#pay_ccName input").val());
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#pay_ccName", errorText);
		hasErrors = true;
	}

	errorText = validateCreditCardType($("#pay_cctype select").val());
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#pay_cctype", errorText);
		hasErrors = true;
	}

	errorText = validateCreditCardNumber($("#pay_ccnumber input").val());
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#pay_ccnumber", errorText);
		hasErrors = true;
	}
	if($('#cardtype').val()=="GE") {
		if(jQuery.trim($("#cboFinanceType").val()).length == 0 ) {
			//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
			//Live person code commented @RFS10180
			addError("#divFinanceInfo", "Please select a Financing Option");
			$("#cboFinanceType").focus();
			hasErrors = true;
		}
		else {
			document.frmPayment.financingOption.value = $("#cboFinanceType").val();
		}
		var intExpMonthIndex,intExpYearIndex;
		intExpMonthIndex = "12";
		intExpYearIndex = "4";
		document.frmPayment.creditCardExpMonth.value = document.frmPayment.creditCardExpMonth[intExpMonthIndex].value;
		document.frmPayment.creditCardExpYear.value = document.frmPayment.creditCardExpYear[intExpYearIndex].value;
		
	}
	var cardMonth = $("#creditCardExpMonth").val();
	var cardYear = $("#creditCardExpYear").val();
	errorText = validateCardMonth(cardMonth);
	if (errorText != "")
		errorText += "<br />";
	errorText += validateCardYear(cardYear);
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#pay_ccdate", errorText);
		hasErrors = true;
	} else {
		errorText = validateCardDate(cardMonth,cardYear);
		if (errorText != "") {
			//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
			//Live person code commented @RFS10180
			addError("#pay_ccdate", errorText);
			hasErrors = true;
		}
	}

	errorText = validateCreditCardCCV($("#pay_ccv input").val());
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#pay_ccv", errorText);
		hasErrors = true;
	}

	return hasErrors;
}

function errorsInGiftCardForm(gcIndex) {
	var hasErrors = false;
	var errorText = "";

	errorText = validateGiftCardNumber($("#giftCardNum" + gcIndex + " input").val());
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#giftCardNum" + gcIndex, errorText);
		hasErrors = true;
	}

	errorText = validateGiftCardPIN($("#giftCardPIN" + gcIndex + " input").val());
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#giftCardPIN" + gcIndex, errorText);
		hasErrors = true;
	}

	var cardMonth = $("#rbtCrd" + gcIndex + "ExpMon").val();
	var cardYear = $("#rbtCrd" + gcIndex + "ExpYr").val();
	errorText = validateCardMonth(cardMonth);
	if (errorText != "")
		errorText += "<br />";
	errorText += validateCardYear(cardYear);
	if (errorText != "") {
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#giftCardDate" + gcIndex, errorText);
		hasErrors = true;
	} else {
		errorText = validateCardDate(cardMonth,cardYear);
		if (errorText != "") {
			//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
			//Live person code commented @RFS10180
			addError("#giftCardDate" + gcIndex, errorText);
			hasErrors = true;
		}
	}

	return hasErrors;
}

function checkGiftCardSequence() {

var strGiftCard1Number  = $("#rbtCrd1No").val();
var strGiftCard2Number  = $("#rbtCrd2No").val();
var strGiftCard3Number = $("#rbtCrd3No").val();
var strGiftCard4Number = $("#rbtCrd4No").val();
var isValidSeq = false;
		if(strGiftCard4Number!="") {
			if(strGiftCard1Number=="") {
				errorsInGiftCardForm(1);
			} else if(strGiftCard2Number=="") {
				errorsInGiftCardForm(2);
			} else if(strGiftCard3Number=="") {
				errorsInGiftCardForm(3);
			} else {
				isValidSeq=true;
			}
		}
		else if(strGiftCard3Number!="")
		{
			if(strGiftCard1Number=="") {

				errorsInGiftCardForm(1);
			} else if(strGiftCard2Number=="") {
				errorsInGiftCardForm(2);
			} else {
				isValidSeq=true;
			}
		} 
		else if(strGiftCard2Number!="")
		{
			if(strGiftCard1Number=="") {
				errorsInGiftCardForm(1);
					
			} else {
				isValidSeq=true;
			}
		}
		else //Irrespective of Card 1 existance or not, return true
		{
			isValidSeq=true;
		}
		return isValidSeq;
}


function useGiftCardOnly(){
	
	var usegiftcard = false;
	
	if (jQuery.trim($("#pay_ccName input").val()).length == 0 && jQuery.trim($("#pay_cctype select").val()).length == 0 && jQuery.trim($("#pay_ccnumber input").val()).length == 0  && jQuery.trim($("#pay_ccname input").val()).length == 0  
		&& jQuery.trim($("#creditCardExpMonth").val()).length == 0  && jQuery.trim($("#creditCardExpYear").val()).length == 0 && jQuery.trim($("#rbtCrd1No").val()).length > 0 ) {
		usegiftcard = true;
	}
	
	return usegiftcard;
}

function validatePayment(event) {
	event.preventDefault();
	removeErrors();//reset messaging
	var hasErrors = false;

	$("#paymentError").hide();//reset
	$("#giftCardError").hide();//reset
	if(useGiftCardOnly()){
		$("#paymentError").hide();//reset
		hasErrors=false;
	}
	else if (errorsInPaymentForm()) {
		$("#paymentError").show();
		hasErrors = true;
	}
	if(!validateGiftCards()) {
		hasErrors = true;
	}
	
	if (!hasErrors) {
		document.frmPayment.ccType.value=$('#cardtype').val();
		document.frmPayment.ccNumber.value=$('#txtCardNumber').val();
		document.frmPayment.ccExpMonth.value=$('#creditCardExpMonth').val();
		document.frmPayment.ccExpYear.value=$('#creditCardExpYear').val();
		document.frmPayment.submit();
	}
}


function validateGiftCards() 
{
	var isValid =true;
	if(!checkGiftCardSequence()){
		$("#giftCardError").show();
		isValid = false;
	}
	else {

	var giftCardIndex = 1;
	var strAllCards ="";
	if(jQuery.trim($("#rbtCrd"+giftCardIndex+"No").val()).length > 0) {
	strAllCards = $("#rbtCrd"+giftCardIndex+"No").val();
	}
	while (jQuery.trim($("#rbtCrd"+giftCardIndex+"No").val()).length > 0) {
		//only validate if a number has been entered
		$("#giftCardError").hide();
		
		

		if (errorsInGiftCardForm(giftCardIndex)) {
			$("#giftCardError").show();
			isValid = false;
		} else if(giftCardIndex > 1 && giftCardExists(giftCardIndex,strAllCards) ){
			
			$("#giftCardError").show();
			
		isValid = false;
		break;
	}
	strAllCards = strAllCards + "|" + $("#rbtCrd"+giftCardIndex+"No").val();
		giftCardIndex++;
	}
	}
	return isValid;
}

function giftCardExists(giftCardIndex,strAllCards) {
	var isGiftCardExists = false;
    $("#giftCardError").hide();
	var strGiftCardNumber = $("#rbtCrd"+giftCardIndex+"No").val();
	
	if(strAllCards.indexOf(strGiftCardNumber)!=-1) {
		alert("Gift Card " + strGiftCardNumber  +" is present more than once");
		$("#rbtCrd"+giftCardIndex+"No").focus();
		//lpSendData('page'+lpUnit+'_ErrorCounter',errorcounter++);
		//Live person code commented @RFS10180
		addError("#giftCardNum" + giftCardIndex,"Card number is present more than once");
		isGiftCardExists = true;
	}
	return isGiftCardExists;
}


/*-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
	GLOBAL ON DOM READY events
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ */

$(document).ready( function() {
	$(".launchPopup").click(launchPopup);
});

