$("input, select").live('change', function() {
	var cViewVal = $('#ClassicView').val();
	var gcAmountVal = $('#giftcard_amnt').val();
	if(typeof cViewVal=='undefined' && typeof gcAmountVal=='undefined')
		updateBuyButton();
});

// These 3 functions moved here from ProductPageJquery.js so that they work with quick view as well as product page
function validateOrderForm(Parameter, a) { // set alert to false to supress alert boxes.
	alt = typeof(a) != 'undefined' ? a : true;
	Parameter = typeof(Parameter) != 'undefined' ? Parameter : $('#qty');
	var valid = true;
	var custYes = $('#custYes').attr('checked');
	var validationType = '';
	var q=parseInt(Parameter.val());
	var reInt = new RegExp(/^-?\d+$/);
	var qvAdd = $('#QuickViewAdd').val();
	
	if($("#size").val()==""){
		if(alt) { alert('You must select a size.'); }
		valid = false;
		return valid;
	}
	
	if($("#color").val()==""){
		if(alt) { alert('You must select a color.'); }
		valid = false;
		return valid;
	}
	
	if (!reInt.test(q) || q<1 || q>98) {
		if(alt) { alert('Invalid Quantity'); }
		Parameter.val(0);
		valid = false;
		return valid;
	}
	
	if(bundleLength > 0) {
		validationType =  'bundle';
		var custBundle = $('input:radio[name=Bundle_Id]:checked').val();
		var msg = 'You selected Team Customization.  Please choose a customization style to continue.';
	} else if(packageLength > 0) {
		validationType = 'package';
		var custPackage = $('input:radio[name=Package_Name]:checked').val();
		var msg = 'You selected Customization.  Please choose a customization style to continue.';
	}
	
	if(custYes===false) {
		valid = true;
		return valid;
	} else if(custYes===true) {
		if(!custBundle && !custPackage) {
			if(alt) { alert(msg); }
			valid = false;
			return valid;
		} else {
			// Bundle Validation Checks
			if(validationType==='bundle') {
				for (var i=0; i < bundles.length; i++) {
					if(bundles[i].id == custBundle) {
						for (var j=0; j < bundles[i].modifiers.length; j++) {
							for (var k=0; k < bundles[i].modifiers[j].colors.length; k++) {
								var modifierId = 'bundle-' + bundles[i].id + '-modifier-' + j + '-color-option-' + k;
								if($('#'+modifierId).val()=='') {
									if(alt) {alert('You must select a fill color.'); }
									$('#'+modifierId).focus();
									valid = false;
									return valid;
								} else {
									// color was chosen, check out the roster
									var rosterId = 'roster-' + bundles[i].id;
									if ($('#'+rosterId).length>0) {
										var validName = null;
										var validNumber = null;
										var nameElem = null;
										var numberElem = null;
										
										// Iterate through each div of inputs
										//ORIG: $('#'+rosterId+' > .player > .player_inputs').each(function() {
										$('#'+rosterId+' > .player').each(function() {
											validName = null;
											validNumber = null;
											nameElem = null;
											numberElem = null;
											
											// Validate name inputs
											//ORIG: $(this).find('.player_field > input.name').each(function(i) {
											$(this).find('input.name').each(function(i) {
												validName = authenticateNameNoMsg($(this).val());
												if(validName===false) {
													nameElem = $(this);
												}
											});
											
											// Validate number inputs
											//ORIG: $(this).find('.player_field > input.number').each(function(i) {
											$(this).find('input.number').each(function(i) {
												validNumber = authenticateNumberNoMsg($(this).val());
												if(validNumber===false) {
													numberElem = $(this);
												}
											});
											
											// Require either name or number to be valid and filled in
											if((validName===null || validName===false) && validNumber===false) {

												if($('#'+rosterId).css('display')=='none') {
													toggleRoster(bundles[i].id);
												}
												
												if(nameElem===null) {
													if(alt) {alert('You must enter a Number for your customized item.');}
													$(numberElem).focus();
												} else {
													if(alt) {alert('You must enter either a Name and/or a Number for your customized item.');}
													$(nameElem).focus();
												}
												valid = false;
												return valid;
											}
										});
									}
								}
							}
						}
					}
				}
			} 
			// BEGIN Package Validation Checks
			else if(validationType==='package') {
				var validName = null;
				var validNumber = null;
				var nameElem = null;
				var numberElem = null;
				
				// Iterate through each customization input - make sure at least one is entered
				$('div.custInputs:visible').find('.name, .number').each(function(i) {
					if($(this).attr('class')=='name'){
						validName = authenticateNameNoMsg($(this).val());
						if(validName===false) {
							nameElem = $(this);
						} else {
							return false;
						}
					} else if($(this).attr('class')=='number'){
						validNumber = authenticateNumberNoMsg($(this).val());
						if(validNumber===false) {
							numberElem = $(this);
						} else {
							return false;
						}
					}
					
					// Require either name or number to be valid and filled in
					if((validName===null || validName===false) && validNumber===false) {
						if(nameElem==null) {
							if(alt) {alert('You must enter a Number for your customized item.'); }
							$(numberElem).focus();
							valid = false;
						} else {
							if(alt) {alert('You must enter at least a Name or Number for your customized item.'); }
							$(nameElem).focus();
							valid = false;
						}
					}
				});
				
				if(valid===false)
					return valid;
				
				// Iterate through patch radios and make sure one is selected
				var patchRadioChecked = null;
				var patchRadioExists = false;
				var patchRadioDisplay = $('.custPatchIcon').css('display');
				$('.Modifier').each(function() {
					if($(this).attr('type')=='radio') {
						patchRadioExists = true;
						if($(this).attr('checked')==true)
							patchRadioChecked = 1;
					}
				});
				
				if(patchRadioChecked==null && patchRadioExists===true && patchRadioDisplay=='block') {
					if(alt) {alert('Please make a Patch, Icon or Flag selection.'); }
					valid = false;
					return valid;
				}
			} // END Package Validation Checks
			return valid;
		}
	}
	return valid;
}

function ValidateCustomizationNew(Parameter, a) {
	//alert('got to old func');
	alt = typeof(a) != 'undefined' ? a : true;
	Parameter = typeof(Parameter) != 'undefined' ? Parameter : $('#qty');
	//if(typeof(Parameter)!='undefined')
	//var clubCookie = Get_Cookie('Club');
	//alert('clubCookie: '+clubCookie);
	//return false;
	
	var valid = true;
	var multi_add = $('#MultiAdd').val();
	//var teamCust = $('input:radio[name=bundle-customization]:checked').val();
	var custYes = $('#custYes').attr('checked');
	var nameVisible = $('.name').parent().parent().css('display');
	var numVisible = $('.number').parent().parent().css('display');
	var someEmptyPlayerFlag = 0;
	var invalidPlayerNum = 0;
	var playerInputId = '';
	var q=parseInt(Parameter.val());
	var reInt = new RegExp(/^-?\d+$/);
	
	if(multi_add=='0') {
		if($("#size").val()==""){
			if(alt) { alert('You must select a size.'); }
			//e.preventDefault();
			valid = false;
			return valid;
		}
		
		if($("#color").val()==""){
			if(alt) { alert('You must select a color.'); }
			//e.preventDefault();
			valid = false;
			return valid;
		}
	}
	
	if (!reInt.test(q) || q<1 || q>98) {
		if(alt) { alert('Invalid Quantity'); }
		Parameter.val(0);
		valid = false;
		return valid;
	}
	
	if(multi_add=='0')
	{
		if (clubCookie!='' && clubCookie!=null && custYes===false) {
			if(alt) { alert("You must add Team Customization to this product."); }
			//$('input[name=bundle-customization]:eq(0)').click();
			valid = false;
			return valid;
		}
		else if (custYes===true) {
			$(".roster > .player > input").each(function(){
				if ($(this).val()==''){
					someEmptyPlayerFlag = 1;
					if (playerInputId=='')
						playerInputId = $(this).attr('id');
				}
				else if ($(this).attr('class')=='number') {
					var playerNum = parseInt($(this).val());
					if (!reInt.test(playerNum) || playerNum < 0) {
						invalidPlayerNum = 1;
						if (playerInputId=='')
							playerInputId = $(this).attr('id');
					}
				}
			});
			
			if(invalidPlayerNum==1) {
				if(alt) { alert("Numbers can only contain the numbers 0-9.."); }
				//document.getElementById(playerInputId).focus();
				$('#'+playerInputId).focus();
				valid = false;
				return valid;
			}
			else if(someEmptyPlayerFlag==1) {
				if(alt) { alert("You must enter the customization details (name/number) for each item."); }
				//document.getElementById(playerInputId).focus();
				$('#'+playerInputId).focus();
				valid = false;
				return valid;
			} else {
				valid = true;
				return valid;
			}
		} else {
			valid = true;
			return valid;
		}
	} else if (multi_add=='1') {
		if(CheckCustomizationQuantity_multi() && removeEmptyFormElements_matrix()){ // version to remove empty form elements
			valid = true;
			return valid;
		} else {
			valid = false;
			return valid;
		}
	}
}

function authenticateNameNoMsg(input) {
	var Regex = new RegExp("^[A-Za-z .-]+$");
	if( !input.match( Regex ) ) {
		return false;
	} else {
		return true;
	}
}

function authenticateNumberNoMsg(input) {
	var Regex = new RegExp("^[0-9]+$");
	if( !input.match( Regex ) ) {
		return false;
	} else {
		return true;
	}
}

function updateBuyButton(){
var val=validateBuyButton();
	if(val){
		$("#purchase").animate({marginRight: '15px'}, 300);
		$("#buyNow").fadeTo(300,1);
	} else {
	$("#purchase").animate({marginRight: '5px'}, 300);
		$("#buyNow").fadeTo(300,0.4);
	}
}

function validateBuyButton() {
	var valid=true;
	var gcAmount = $('#giftcard_amnt').val();
	
	//valid = validateOrderForm($('#qty'), false);
	
	if(gcAmount!=null) {
		//alert('yes1');
		valid = validate_GiftCardForm();
	} else if (typeof(clubCookie)!=="undefined" && clubCookie!='' && clubCookie!=null && virtClubProd==1) {
		//alert('yes2');
		valid = ValidateCustomizationNew($('#qty'), false);
	} else {
		//alert('yes3');
		valid = validateOrderForm($('#qty'), false);
	}
	
	if(valid===false) {
		return false;
	}

	//if($("#size").val()=="" || $("#color").val()==""){
	//	return false;
	//}
	return valid;
}

// BEGIN GIFTCARD FUNCTIONS
function set_GiftCardModifierVectorLength() {
	// Variable to hold Vector Length Value
	var vecLen = "";
	// Get Current Card Type Radio Button value
	var cardType = $("#sizeValue").val();
	if (cardType == "3755")
		vecLen = "4";
	else
		vecLen = "3";
	// Set hidden form field to new vector length value
	$("#giftcard_vector_length").val(vecLen);
	// Return value of vecLen
	return vecLen;
}

function set_GiftCardModifierOtherHiddens() {
	// Get Updated Vector Length Value for loop
	var vecLength = $("#giftcard_vector_length").val();
	var textNameId = "";
	var textNameVal = "";
	var userValuesId = "";
	var nameNumCombsId = "#name_number_coms";
	var nameNumCombsVal = "";
	
	// Set hidden name / value pairs
	for (var i=0; i < vecLength; i++) {
		textNameId = "#t" + i;
		userValuesId = "#u_v" + i;
		
		textNameVal = $(textNameId).val();
		if (textNameVal != "") {
			nameNumCombsVal += textNameVal;
				if (i < vecLength-1)
					nameNumCombsVal += ":";
		}
		
		$(userValuesId).val(textNameVal);
	}
	
	$(nameNumCombsId).val(nameNumCombsVal);
	var testing = 'nameNumCombsVal: ' + $(nameNumCombsId).val();

	return true;
}

function update_GiftCard_color_menu() {
    var size = null;
	
	var gcForm = document.OrderByVariantSimple;
	var gcFormLen = gcForm.elements.length;
	var gcRadioLen = 0;
	
	for (var i = 0; i < gcFormLen; i++) {
		if (gcForm.elements[i].name == "AttributeValueId" && gcForm.elements[i].type == "radio") {
			gcRadioLen++;
			if (gcForm.elements[i].checked == true)
				size = gcForm.elements[i].value;
		}
	}

    if (document.getElementById('color')) {
      var c_el = document.getElementById('color');
      color = (c_el.options[c_el.selectedIndex].value == '') ? null: c_el.options[c_el.selectedIndex].value;
      c_el.length = 0;
    	c_el.options[0] = new Option('Choose', '');
    } else if (document.getElementById('selectedsinglecolor')) {
    	var c_el = document.getElementById('selectedsinglecolor');
      color = (c_el.value == '') ? null: c_el.value;
    }

    if (size == null) {
		alert("Please select a style.");
        return false;
    }

    for (var i in sProduct.Variants) {
        if (size == sProduct.Variants[i].Size_Value_Id && (sProduct.Variants[i].I >= 1 || sProduct.Variants[i].B >= 1 || sProduct.Variants[i].S >= 1)) {
            c_el.options[c_el.options.length] = new Option(sProduct.Variants[i].Color_Value, sProduct.Variants[i].Color_Value_Id);
        }
    }
}

function update_GiftCardPrice() {
	//clearTimeout(pulse_events['price']);
	clearTimeout(pulse_events['gc_price']);
	var GiftCard_Amount = $('#giftcard_amnt').val();

	//var p_el = document.getElementById('price');
	//var p_el = $('#price');
	var gc_p_el = $('#gc_price');
	//p_el.style.visibility = 'visible';
	//p_el.css('visibility','visible');
	gc_p_el.css('visibility','visible');
	//p_el.show();

	// ending decimal
	if(GiftCard_Amount.charAt(GiftCard_Amount.length-1) == ".") {
		GiftCard_Amount += "00";
		$('#giftcard_amnt').val(GiftCard_Amount);
	}

	// dollar sign
	if(GiftCard_Amount.charAt(0) == "$") {
		GiftCard_Amount = GiftCard_Amount.substring(1,GiftCard_Amount.length);
		$('#giftcard_amnt').val(GiftCard_Amount);
	}

	if(GiftCard_Amount >= 5) {
		var pricing_copy = 'Price: $' + round_decimals(GiftCard_Amount, 2);
		var Current_Price = round_decimals(GiftCard_Amount, 2);
		$('#giftcard_amnt').val(round_decimals(GiftCard_Amount, 2));

		if(gc_p_el.html() != pricing_copy) {
			//p_el.css('visibility','hidden');
			gc_p_el.css('visibility','hidden');
			//p_el.hide();
			//p_el.innerHTML = pricing_copy;
			//p_el.html(pricing_copy);
			gc_p_el.html(pricing_copy);
			//pulse_events['price'] = setTimeout('pulse_value(\'price\', true, 3);', 500);
			pulse_events['gc_price'] = setTimeout('pulse_value(\'gc_price\', true, 3);', 500);
		}

		var giftCardToName				= $('#t0').val();
		var giftCardFromName			= $('#t1').val();
		var giftCardMessage				= $('#t2').val();
		var giftCardToEmail				= $('#t3').val();

		giftCardToName					= giftCardToName.replace(/'/, "\\'");
		giftCardToName					= giftCardToName.replace(/"/, "\\\"");
		giftCardFromName				= giftCardFromName.replace(/'/, "\\'");
		giftCardFromName				= giftCardFromName.replace(/"/, "\\\"");
		giftCardMessage					= giftCardMessage.replace(/'/, "\\");
		giftCardMessage					= giftCardMessage.replace(/"/, "\\\"");
		giftCardToEmail						= giftCardToEmail.replace(/'/, "\\'");
		giftCardToEmail						= giftCardToEmail.replace(/"/, "\\\"");
		
		return true;
	} else {
		alert("Gift Cards may be purchased \nfor a minimum amount of $5.00");
		$('#giftcard_amnt').val('5.00');
		$('#giftcard_amnt').focus();
		return false;
	}
}

function check_GiftCardToEmail() {
    // If they selected delivery by email so we need to check for email address
	var emailAddress = $("#t3").val();
    if (document.getElementById("sizeValue").value == "3755") { 
		if (emailAddress == "") {
			alert("You have selected to have this gift card delivered by email.\nPlease provide an email address for the recipient.");
			document.getElementById("t3").focus();
			return false;
		} 
		else if (!isValidEmailAddress(emailAddress)) {
			alert("The email address entered, " + emailAddress + ", is not valid.");
			document.getElementById("t3").focus();
			return false;
		} else {
			return true;
		}
    } else {
        return true;
    }
}

function check_GiftCardToFromNames() {
	var giftCardToName = $("#t0").val();		//document.getElementById('t0').value;
	var giftCardFromName = $("#t1").val();	//document.getElementById('t1').value;
	var replacement = "";
	
	// Replace colons with spaces
	replacement = replace_GiftCardColorCharacters(giftCardToName);
	$("#t0").val(replacement);
	
	replacement = replace_GiftCardColorCharacters(giftCardFromName);
	$("#t1").val(replacement);

	// If they selected delivery by email so we need to check for email address
	if (giftCardToName == "" || giftCardToName == " "){
		alert("You must enter both To and From names.");
		document.getElementById('t0').focus();
		return false;
	}
	else if (giftCardFromName == "" || giftCardFromName == " "){
		alert("You must enter both To and From names.");
		document.getElementById('t1').focus();
		return false;
	} else {
		return true;
	}
}

function check_GiftCardColor() {
	var cardColor = $("#color").val();
	if (cardColor == "") {
		alert("Please select a style.");
		$("#color").focus();
		return false;
	} else {
		return true;
	}
}

function check_GiftCardMessage() {
	var cardMessage = $("#t2").val();
	var replacement = "";
	// Replace colons with spaces
	replacement = replace_GiftCardColorCharacters(cardMessage);
	$("#t2").val(replacement);
	return true;
}

function replace_GiftCardColorCharacters(str) {
	var newStr  = '';
	var substr  = '';
	begin = false;
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < str.length; i++) {
		// copy non-whitespace characters
		if (str.charAt(i) != ' ' && str.charCodeAt(i) != 9) {
			// if the temporary string contains some whitespace characters, copy them first
			if (substr != '') {
				newStr += substr;
				substr = '';
			}
			newStr += str.charAt(i);
			if (begin == false) begin = true;
		}
		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (begin == true) substr += str.charAt(i);
	}
	var tempStr = newStr.replace(/:/g,"");
	return tempStr;
}

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals);
    var result2 = Math.round(result1);
    var result3 = result2 / Math.pow(10, decimals);
    return pad_with_zeros(result3, decimals);
}

function pad_with_zeros(rounded_value, decimal_places) {
    var value_string = rounded_value.toString();
    var decimal_location = value_string.indexOf(".");
    if (decimal_location == -1) {
        decimal_part_length = 0;
        value_string += decimal_places > 0 ? "." : "";
    } else {
        decimal_part_length = value_string.length - decimal_location - 1;
    }

    var pad_total = decimal_places - decimal_part_length;
    if (pad_total > 0) {
        for (var counter = 1; counter <= pad_total; counter++){
            value_string += "0";
        }
	}
    return value_string;
}

function validate_GiftCardForm() {
	if(!update_GiftCardPrice())
		return false;
	// if(!check_GiftCardColor())
	//	return false;
	if(!check_GiftCardToFromNames())
		return false;
	if(!check_GiftCardToEmail())
		return false;
	if(!set_GiftCardModifierVectorLength())
		return false;
	if(!check_GiftCardMessage())
		return false;
	if(!set_GiftCardModifierOtherHiddens())
		return false;

	return true;
}
// END GIFTCARD FUNCTIONS
