//Variables - used for displaying localized messages
var sInvalidQuantity = "Please enter a valid quantity";
var sSelectAValue = "Please choose a value.";
var sFillOutAllCOAFields = "";

/**
 * Validates if the input field is numeric
 * 
 * @param sText
 * @return
 */
function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

/**
 * Validates the email address
 * @param emailStr
 * @return
 */

function isValid() {
 var email=document.form1.t1.value;
 if (email.indexOf(' ')==-1 
      && 0<email.indexOf('@')
      && email.indexOf('@')+1 < email.length
 ) return true;
 else jAlert ('Invalid email address!');
 return false;
}

/**
 * Validates the email address
 * @param emailStr
 * @return
 */
function emailCheck (emailStr) {
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
	    jAlert("Email address seems incorrect (check @ and .'s)");
	    return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	if (user.match(userPat)==null) {
	    jAlert("The username doesn't seem to be valid.");
	    return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	      for (var i=1;i<=4;i++) {
	        if (IPArray[i]>255) {
	            jAlert("Destination IP address is invalid!");
	        return false;
	        }
	    }
	    return true;
	}
	var domainArray=domain.match(domainPat);
	if (domainArray==null) {
		jAlert("The domain name doesn't seem to be valid.");
	    return false;
	}
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if ((domArr[domArr.length-1] != "info") &&
	    (domArr[domArr.length-1] != "name") &&
	    (domArr[domArr.length-1] != "arpa") &&
	    (domArr[domArr.length-1] != "coop") &&
	    (domArr[domArr.length-1] != "aero")) {
	        if (domArr[domArr.length-1].length<2 ||
	            domArr[domArr.length-1].length>3) {
	                jAlert("The address must end in a three-letter domain, or two letter country.");
	                return false;
	        }
	}
	if (len<2) {
	   var errStr="This address is missing a hostname!";
	   jAlert(errStr);
	   return false;
	}
	return true;
}

/**
 * Loads iframe / modal
 */
function fancyBoxLoad(email, siteId) {
	var url = '/newsletter/newsletter_signup.jsp' + '?emailSignUp=' + email + '&mlid=' + siteId;
	$.fancybox(
			
	        { 'href': url }, 
	        {
	            'width': 570,
	            'height': 420,
	            'overlayShow': true,
	            'type': 'iframe'
	        }
	    );

}

function UPTvalidateform(formName,siteID)
{
	var email = formName.emailSignUp.value;
	if (emailCheck(email))  
	{
	   	fancyBoxLoad(email, siteID);
		return true;	
	}
	else
	{
		return false;
	}
}
/** Function to clear default form text **/
function doClear(theText) {
    if (theText.value == theText.defaultValue) {
        theText.value = "";
    }
}

/**
 * Called when a product is added to a cart.  It displays
 * the product and quantity added.
 * 
 * @return
 */
function showEmailAFriendPopup() {
	$.fancybox(
	        { 'href': '/products/email_a_friend_popup.jsp' }, 
	        {
	            width: 560,
	            height: 400,
	            overlayShow: true,
	            type: 'iframe',
	            showCloseButton: true
	        }
	    );
}

function showHideFormFields(el, div1, addressDiv, addressForm, qasFlag) {
    var submitAction = "return qasVerify('" + addressDiv + "', true, '" + addressForm + "');"
 
    if ($(el).val() == "") {
        $('#' + div1).show();
        
        if (qasFlag == true) {
            $('#' + addressDiv).attr("onSubmit", submitAction);
        }
    } else {
        $('#' + div1).hide();
        
        if (qasFlag == true) {
            $('#' + addressDiv).attr("onSubmit", "");
        }
    }
}

function showHidePaymentFields(el, div1, div2, div3, addressDiv, addressForm, qasFlag) {
    var submitAction = "return qasVerify('" + addressDiv + "', true, '" + addressForm + "');"

    if ($(el).val() == "") {
        $('#' + div1).show();
        $('#' + div2).show();
        $('#' + div3).hide();

        if (qasFlag == true) {
            $('#' + addressDiv).attr("onSubmit", submitAction);
        }
    } else {
        $('#' + div1).hide();
        $('#' + div2).hide();
        $('#' + div3).show();
        
        if (qasFlag == true) {
            $('#' + addressDiv).attr("onSubmit", "");
        }
    }
}

function renameCVV(el, divNewCVV, divExistingCVV, divActive, divInactive) {
    if ($(el).val() == "") {
        $('#' + divNewCVV).attr(divActive);
        $('#' + divExistingCVV).attr(divInactive);
    } else {
        $('#' + divNewCVV).attr(divInactive);
        $('#' + divExistingCVV).attr(divActive);
    }
}

function closePopup(url) {

	if(url != null) {
		parent.window.location.href = url;
	}
	parent.$.fancybox.close();
	return false;
}

/**
 * Add To Cart: Function to do some quick client side validation that
 * the form fields have been completed prior to having the server
 * validate the data.
 * 
 * @param curForm
 * @return
 */
function validateAddToCartForm(curForm) {
	var formIsValid = true;
	
	//Get the Id for the form
	var idField = curForm.elements["ADD_CART_ITEM_ARRAY<>form_field_id"].value;
	var qtyField = curForm.elements["ADD_CART_ITEM_ARRAY<>quantity"];
	formIsValid = isQuantityValid(qtyField);
	
	if(!formIsValid) {
		var qtyFieldId = '#' + "qty_" + idField;
		$(qtyFieldId).addClass("err");
		jAlert(sInvalidQuantity);
	}
	
	return formIsValid;
}

/**
 * Function to display a message about the validation warnings.
 * 
 * @param msg
 * @return
 */
function fancyAlert(msg) {    
	jQuery.fancybox({        
		'modal' : true,        
		'content' : "<div>"+msg+"<br /><input type=\"button\" onclick=\"jQuery.fancybox.close();\" value=\"Ok\"></div>"    });
}


/**
 * Function to switch tabs on the product details page
 * @param panelId
 * @return
 */
function showProductDetailPanel (panelId) {
	$("#productTabPanels .panel").hide();
	$("#productTabs .tab").removeClass("selected");
	$("#productTabPanels #" + panelId).show();
	$("#productTabs #" + panelId + "_tab").addClass("selected");
	return false;
}

var skuDetails = [];

/**
 * This is an object that is used to store the sku serving size, serving size
 * display and price so that we can dynamically update the display values when a
 * user selects the values in the drop down. 
 */
function dynamicServingProductData(pservingSize, pServingSizeDisplay, pPrice, pDefault) {
	this.servingSize = pservingSize;
	this.servingSizeDisplay = pServingSizeDisplay;
	this.price = pPrice;
	this.isDefault = pDefault;
}

function setDefaultAttributeVal() {
	var options = $('#select_1')[0].options;
	var defaultSelection = null;
	for(var i in skuDetails) {
		if(skuDetails[i].isDefault) {
			defaultSelection = skuDetails[i];
			break;
		}
	}
	
	if(defaultSelection == null) {
			return;
	}
	
	var optionsLength = options.length;
	for(var i=0; i<optionsLength; i++) {
		if(options[i].value == defaultSelection.servingSize) {
			$("#select_1")[0].selectedIndex = i;
			updateSkuDisplayWithValues(defaultSelection);
		}
	}
}

/**
 * Locates the object containing the updated data
 */
function updateSkuDisplay(pSelect) {
	var selectedIndex = pSelect.selectedIndex;
	var selectedValue = pSelect.options[selectedIndex].value;
	for(var i in skuDetails) {
		if(skuDetails[i].servingSize == selectedValue) {
			updateSkuDisplayWithValues(skuDetails[i]);
			break;
		}
	}
}
/**
 * Updates the user interface with the details
 */
function updateSkuDisplayWithValues(pSkuDetails) {
	$('#productPrice').html(pSkuDetails.price);
	$('#productServingSize').html(pSkuDetails.servingSizeDisplay);
}

/**
 * Updates the total for the gift certificate.  Currently only one currency
 * code is being used, so we will hard code the $. 
 */
function updateCOATotalAmount(qtyField, listPrice, currencyCode) {
	var qty = qtyField.value;
	var total = listPrice * qty;
	var display = '$' + total.toFixed(2);
	
	//Get the div
	var currentDiv = $(qtyField).closest('div[class=productFunctionBoxwrapper]');
	var amountField = currentDiv.find("span[class=coaTotal]");
	$(amountField).html(display);
}

/**
 * Function for removing a COA row
 * @param deleteButton
 * @return
 */
var removeCOA = (function removeCOARow() {
	var currentDiv = $(this).closest('div[class=productFunctionBoxwrapper]');
	currentDiv.remove();          
	resizeRows();
});

/**
 * Function for adding a COA row
 * @return
 */
function addCOARow() {
	var container = $('#productFunctionBoxes');
	var element = $("div[class=productFunctionBoxwrapper]").first();
	var newElement = element.clone();
	//Need to clear out the quantity
	var qtyElement = newElement.find("input[name=ADD_CART_ITEM_ARRAY<>quantity]")[0];
	qtyElement.value = "1";
	
    $(qtyElement).keypress(function (e)  { 
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
          return false;
        } 
    });

    //Need to update the Total Price
	var priceElement = newElement.find("input[name=ADD_CART_ITEM_ARRAY<>tempPrice]")[0];
	var amountField = newElement.find("span[class=coaTotal]");
	var display = '$' + (qtyElement.value * priceElement.value).toFixed(2);
	$(amountField).html(display);

	//Need to clear out the recipient
	newElement.find("input[name=ADD_CART_ITEM_ARRAY<>ATR_Line_COA_Recipient]")[0].value = "";
	
	//Need to add the delete option
	var deleteContainer = $('#removeBtn');
	var deleteAElement = deleteContainer.find("a[class=removeBtnLnk]");
	var newDeleteElement = deleteAElement.clone();
	
	var deleteTd = newElement.find("td[class=deleteCOA]");
	$(newDeleteElement).click(removeCOA);
	newDeleteElement.appendTo(deleteTd);
	
	newElement.appendTo(container);

  resizeRows();
}

/**
 * Javascript function to resize outer rows.
 * @return
 */
function resizeRows () {
	$(".row1").each(function(index) {
    $(this).attr("style", "");
  });

	
	if ($(".row1").length > 0) {
		$(".row1").equalHeight();
	} 
}

/**
 * Preliminary javascript function to validate the user input prior to sending
 * the form to the server.
 * @return
 */
function validateCOAAddToCartForm(currentForm) {
	//want to loop through all of the lines and confirm that there are entries 
	//in each
	
	var formIsValid = true;
	var qtyField = currentForm.elements["ADD_CART_ITEM_ARRAY<>quantity"];
	var recipientField = currentForm.elements["ADD_CART_ITEM_ARRAY<>ATR_Line_COA_Recipient"];
	
	if(qtyField.length == null) {
		formIsValid = isQuantityValid(qtyField);
	} else {
		var numItems = qtyField.length;
		for(var i=0; i<numItems; i++) {
			var curQtyField = qtyField[i];
			formIsValid = isQuantityValid(curQtyField);
			if(!formIsValid) {
				break;
			}
		}
	}
	
	if(formIsValid) {
		if(recipientField.length == null) {
			//There is only one field
			if(recipientField == null || recipientField.value == "") {
				formIsValid = false;
			}
		} else {
			for(var i=0; i<numItems; i++) {
				var curField = recipientField[i];
				if(curField == null || curField.value == "") {
					formIsValid = false;
					break;
				}
			}

		}

	}
	
	
	if(!formIsValid) {
		fancyAlert(sFillOutAllCOAFields);
	}
	
	return formIsValid;
}

/**
 * Confirms that the quantity is not null, not empty and greater than 0.
 */
function isQuantityValid(fieldQty) {
	var isValid = true;
	if(fieldQty != null && fieldQty.value != "" && IsNumeric(fieldQty.value)) {
		isValid = fieldQty.value > 0;
	} else {
		isValid = false;
	}
	return isValid;
}

function openNextAccordian(nextTabId, currentTabEditLink) {
    var accordianId = "#" + nextTabId;
	$(accordianId).trigger("click");
    if(currentTabEditLink != null) {
        var currentEditId = "#" + currentTabEditLink;
        $(currentEditId).show();
    } 
}

function openDesignAMenu(uri) {
    if(uri == null) {
    	uri = designAMenuURL;
    }
	var myBGColor = document.bgColor;
    document.body.disabled = true;
    document.bgColor = "#cccccc";
    var myWinOptions = "dialogHeight: 800px; dialogWidth: 1000px; location: No; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No;";
    window.showModalDialog(uri, null, myWinOptions);
    document.bgColor = myBGColor;
    document.body.disabled = false;
    
    var damRefresh = document.getElementById("refresh_shopping_cart");
    
    if(damRefresh != null) {
        damRefresh.submit(); 
    } else {
        document.refresh_shopping_cart.submit(); 
    }
}

function directToConverge(navToPage, searchKeyword) {
	var convergeForm = document.forms["go_to_converge"];
	convergeForm["page"].value = navToPage;
	if(searchKeyword != null) {
		convergeForm["keyword"].value = searchKeyword;
	}
	convergeForm.submit();
}
function checkSearchType() {
	var searchTypeField = document.getElementById("inp-search-site-mini-dropdown");
	if(searchTypeField.value == "CONTENT") {
		//Need to send them to the converge site
		directToConverge("search", document.getElementById("inp-search-site-mini-keywords").value);
		return false;
	} 
	return true;
}

function removeEditLinks(currIndex){
	for(var i=currIndex; i< $(".editLink").length; i++){
		$(".editLink a").eq(i).hide();
	}
}
/*
*   Function to change QAS form field IDs with the correct names.  Required for
*   pages with multiple address verifications, such as in checkout and
*   account create on Wholesale.
*/
function changeQASIDNames (prefix) {
    
    $("[id^=" + prefix + "]").each(function(){
        var id = $(this).attr('id');
        var newId = id.substr(id.indexOf("-") + 1);
        $(this).attr('id', newId);
	});
}

function opendetailwindow(uri) {
    var mywindow = window.open(uri, "mywindow", "status=0,toolbar=0,height=600,width=550,resizable=1,location=0,scrollbars=1", false);
}
function n() { }

