﻿//
// needed for pre-load
//
function recordAnalyticsForAdd(pId, firstItem, price) {
    var s = s_gi(s_account);
    s.linkTrackVars = 'products,events';
    if (firstItem) {
        s.linkTrackEvents = 'scAdd,scOpen,event23';
        s.events = 'scAdd,scOpen,event23';
    }
    else {
        s.linkTrackEvents = 'scAdd,event23';
        s.events = 'scAdd,event23';
    }
    s.products = ';' + pId + ';;;event23=' + price;
    s.tl(this, 'o', 'Add to Cart');
}

//
// capable of DELAY load
//

// utility string functions

function strTrim(s) {
	// Remove leading spaces and carriage returns
	while (s.substring(0, 1) == ' ') {
		s = s.substring(1, s.length);
	}
    // Remove trailing spaces and carriage returns
	while (s.substring(s.length - 1, s.length) == ' ') {
		s = s.substring(0, s.length - 1);
	}
	return s;
}

function trimString(str) {
  return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function replace(string,text,by) {
   // Replaces text with by in string
   var strLength = string.length, txtLength = text.length;
   if ((strLength == 0) || (txtLength == 0)) {
      return string;
   }
   var i = string.indexOf(text);
   if ((!i) && (text != string.substring(0, txtLength))) {
      return string;
   }
   if (i == -1) {
      return string;
   }
   var newstr = string.substring(0, i) + by;
   if (i + txtLength < strLength) {
      newstr += replace(string.substring(i + txtLength, strLength), text, by);
   }
   return newstr;
}

// functions called from events, mostly 'onclick' and 'onkeyup'

function openWindow(address, width, height,features)
{
	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 openZipCodeWindow() {
	// url_zipcode is defined in common_js.jsp
	openWindow(url_zipcode, 300, 200, "menubar=no, location=no, directories=yes, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no");
}

function confirmWindow(url, text) {
	if (confirm(text)) {
		window.go = url;
		window.location = url;
	}
}

function doSearchFocus(component) {
	var searchVal = component.value;//document.searchForm.keyword.value;
	if (searchVal == "Product Name or Item #") {
		//document.searchForm.keyword.value = "";
		component.value = "";
	}
    return true;
}
	
function doSearchBlur(component) {
	var searchVal = component.value;//document.searchForm.keyword.value;
	if (strTrim(searchVal) == '') {
		//document.searchForm.keyword.value = "enter keyword or item #";
		component.value = "Product Name or Item #";
		return false;
	}
	return true;
}

function doZipFocus(component) {
    var zipVal = component.value;
    if (zipVal == "Enter Zip Code") {
        component.value = "";
    }
    return true;
}

function doZipBlur(component) {
    var zipVal = component.value;
    if (strTrim(zipVal) == '') {
        component.value = "Enter Zip Code";
        return false;
    }
    return true;
}

function setQuantity(index){
	var quantityArray = $("select[id*=qty]");
	if (quantityArray != null && quantityArray[index] != null && quantityArray[index].value == ""){
		$(quantityArray[index]).val("1");
	}
	var itemArray =  $("input[id*=itemNumber]");
	if (itemArray && itemArray[index] != null && itemArray[index].value == ""){
		$(quantityArray[index]).val("");
	}
}

function redirectOpener(url, setOpenerFocus, closeWindow) {
	window.opener.location = url;
	if ((setOpenerFocus != null) && (setOpenerFocus)) {
		window.opener.focus();
	}
	if ((closeWindow != null) && (closeWindow)) {
		window.close();
	}
}

// Returns the number of allowed characters remaining for a field.
// If the length of the field exceeds the total number of allowed
// characters the value will be truncated to the total allowed.

function getCharactersRemaining(field, totalCharacters) {
     var len = 0;
     if (field != null) {
       len = field.value.length;
     }
     if (len > totalCharacters) {
       field.value = field.value.substring(0, totalCharacters);
       len = totalCharacters;
     }
     return (totalCharacters - len);
}

function updateRemainingCharacters(field, displayElement, totalCharacters) {
	var remainingCharacters = getCharactersRemaining(field, totalCharacters);
	if (displayElement != null) {
	  displayElement.innerHTML = remainingCharacters;
	}

	return remainingCharacters;
}

function showHideDetails(targetId){
    if(document.getElementById) {
	    if(document.getElementById(targetId)) {
		    var target = document.getElementById(targetId);
		    if (target.className == "hide") {
		        target.className = "show";
		    }else{
			    target.className = "hide";
		    }
	    }
    }
}

function showDetails(targetId){
	if(document.getElementById) {
		if(document.getElementById(targetId)) {
			var target = document.getElementById(targetId);
			target.className = "show";
		}
	}
}

function hideDetails(targetId){
	if(document.getElementById) {
		if(document.getElementById(targetId)) {
		    var target = document.getElementById(targetId);
		    if (target.className == "show") {
			    target.className = "hide";
		    }
		}
	}
}

// AJAX calls
function addItemToCart(buttonObject, pId) {
    //Get the quantity based on the pId...
    var pQuantity = $("#qty_" + pId).val();

    //Check if a zip code is already set
    szZipSet = $("#IS_ZIP_CODE_SET").val();
    if ("true" != szZipSet) {
        $("input[name=productId]").val(pId);
        $("input[name=quantity]").val(pQuantity);

        showZipCodeLayer();
        return;
    }

    //Hide previous add to cart
    if ($(buttonObject).prev() && $(buttonObject).prev().attr("type") == "addedMesg") {
        $(buttonObject).prev().remove(); //remove added message
    }

    //Hide the button
    $(buttonObject).hide();

    $("<p class='processing add-cart' type='processing'>Processing...</p>").insertBefore($(buttonObject));

    var addPath = "/addToCart.ashx?productId=" + pId + "&quantity=" + pQuantity;
    $.ajax({
        type: "GET",
        url: addPath,
        cache: false,
        success: function(data) {
            if ($(buttonObject).prev() && $(buttonObject).prev().attr("type") == "processing") {
                $(buttonObject).prev().remove(); //remove processing message
            }

            //Determine if the persistent cart is present on the page or not
            var bPersistentCartPresent = $("#PersistentCartContents").length > 0;

            retData = eval("(" + trimString(data) + ")");
            if (retData.itemAdded != null) {
                if (!bPersistentCartPresent) {
                    $("<p class='addedCartAjax' type='addedMesg'>Item added to cart.</p>").insertBefore($(buttonObject));
                }
                else {
                    $("#PersistentCartContents").replaceWith(retData.htmlCart);
                }
                recordAnalyticsForAdd(pId, retData.firstItem, retData.price);
            }
            else if (retData.outOfStock != null) {
                $("#stock_info").html(retData.outOfStock);
                $("#stock_info").show();
                $("<p class='msg_availability' type='addedMesg'>" + retData.outOfStock + "</p>").insertBefore($(buttonObject));
            }
            else {
                $("<p class='addedCartAjax' type='addedMesg'>Could not add item to your cart</p>").insertBefore($(buttonObject));
            }

            $(buttonObject).show();
        }
    });
}

function addItemToFavorites(pId, pIsRecipeItem) {
    //Hide the add button
    $("#ImageAddToFavorites_" + pId).hide();

    var addPath = "/account/addToFavorites.ashx?productId=" + pId + "&IsRecipeItem=" + pIsRecipeItem;
    $.ajax({
        type: "GET",
        url: addPath,
        cache: false,
        success: function(data) {
            //Show the remove button
            $("#ImageRemoveFromFavorites_" + pId).show();

            //Show the burst for a favorite (need to hide the past purchase if both would be present)
            $("#myFav_" + pId).show();
            $("#pastPurchase_" + pId).hide;
        }
    });
}

function removeItemFromFavorites(pId) {
    //Hide the add button
    $("#ImageRemoveFromFavorites_" + pId).hide();

    var addPath = "/account/removeFromFavorites.ashx?productId=" + pId + "&IsRecipeItem=" + pIsRecipeItem;
    $.ajax({
        type: "GET",
        url: addPath,
        cache: false,
        success: function(data) {
            //Show the remove button
            $("#ImageAddToFavorites_" + pId).show();

            //Hide the burst. show the past purchase if present
            $("#myFav_" + pId).hide();
            $("#pastPurchase_" + pId).show();
        }
    });
}

// ZipCode layer calls

function toggleSelects(hide) {
	if (hide == true)
		$('select').addClass("invisible");
	else
		$('select').addClass("visible");
}

function centerInViewport(el) {
	//centers el in the viewport (ie6 only), other browsers use fixed positioning in the css
   var vpTop = document.documentElement.scrollTop;
	var vpHeight = document.documentElement.clientHeight;
	var vpYCenter = vpTop + (vpHeight/2);
	el.css({top:vpYCenter+"px"});
}

function showZipCodeLayer(){
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		$("#overlayMask").width($(document).width());
		$("#overlayMask").height($(document).height());
		toggleSelects(true);
		centerInViewport($("#overlayPanel"));
		$(window).scroll(function () {
			centerInViewport($("#overlayPanel"));
		 });
		}
	$("#overlayMask").show();
	$("#overlayPanel").show();
	$("#zipCodeLayerField").focus();
}
function showRegistrationCompleteLayer() {
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
        $("#overlayMask").width($(document).width());
        $("#overlayMask").height($(document).height());
        toggleSelects(true);
        centerInViewport($("#RegoverlayPanel"));
        $(window).scroll(function() {
        centerInViewport($("#RegoverlayPanel"));
        });
    }
    $("#overlayMask").show();    
    $("#RegoverlayPanel").show();

}
function hideRegLayer() {
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
        toggleSelects(false);
        $(window).unbind('scroll');
    }
    $("#regOverlayMask").hide();
    $("#RegoverlayPanel").hide();
}
function hideZipCodeLayer(){
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		toggleSelects(false);
		$(window).unbind('scroll');
	}
	$("#overlayMask").hide();
	$("#overlayPanel").hide();
}

function validateZipCode(formName) {
    var zipCode = document.forms[formName != null ? formName : "zipCodeForm"].zipCode.value;
    zipCode = strTrim(zipCode);
    if (zipCode.length == 0) {
	    return 1; // missing
    }

    if (zipCode.length == 5) {
	    if (!isNaN(zipCode)) {
		    return 0; // valid
	    }
    } else if (zipCode.length > 5) {
	    if(zipCode == 'Enter ZIP Code'){
		    return 1; // missing
	    }
	    if (zipCode.charAt(5) == '-') { // Make sure the sixth char is a '-'
		    zipCode = zipCode.replace("-", "");
		    if (zipCode.length == 9 && !isNaN(zipCode)) {
			    return 0; // valid
		    }
	    }
    }
    return 2; // invalid ZIP code
}

var isProcessingZipCodeData = false; //Prevents multiple submission of same form

function processData(formName) {
	if(isProcessingZipCodeData){
		return false;
	}
	isProcessingZipCodeData = true;
	var errorCode = 0;
	if(formName == ""){
		formName = null;
	}
	errorCode = validateZipCode(formName);
	if (errorCode == 1) // missing ZIP code
	{
		showZipCodeError("Please enter a ZIP code.");
	} else if (errorCode == 2) // invalide ZIP code
	{
		showZipCodeError("Please enter a valid ZIP code.");
	} else if(errorCode == 0){
		var hasError = false; // fix for case: we open the schwans site from a link in the email or something like that
		try {
			if (window.opener) {
				window.opener.document.getElementsByName("zipCode")[0].value = document.forms[formName != null ? formName : "zipCodeForm"].zipCode.value;
				window.opener.submitData();
				window.close();
				isProcessingZipCodeData = false;
				return false;
			}
		} catch (e) {
			hasError = true;
		}
		if (hasError || window.opener == null) {
			document.forms[formName != null ? formName : "zipCodeForm"].submit();
			isProcessingZipCodeData = false;
			return true;
		}
	}
	isProcessingZipCodeData = false;
	return false;
}

function showZipCodeError(message){
	var isZipCodeLayerMode = true;
	try{isZipCodeLayerMode = $("#overlayPanel").css("display") == "block" ? true : false;}catch(e){}
	if(isZipCodeLayerMode){
		try{$("#zipcodeLayerError")[0].innerHTML = message;}catch(e){}
		try{$("#zipcodeLayerError").show();}catch(e){}
	}else{
		try{$("#errorMessage")[0].innerHTML = message;}catch(e){}
		try{$("#divError").show();}catch(e){}
	}
}
    
function hideErrorMessage() {
	var isZipCodeLayerMode = true;
	try {isZipCodeLayerMode = $("#overlayPanel").css("display") == "block" ? true : false;} catch(e) {}
	if (isZipCodeLayerMode) {
		try{$("#zipcodeLayerError")[0].innerHTML = "";}catch(e){}
		try{$("#zipcodeLayerError").css("class","hide");}catch(e){}
		document.zipCodeForm.zipCode.value = "";
		document.zipCodeForm.zipCode.maxLength = 5;
	} else {
		try{$("#errorMessage")[0].innerHTML = "";}catch(e){}
		try{$("#divError").hide();}catch(e){}
		document.DeliveryModuleForm.zipCode.value = "";
		document.DeliveryModuleForm.zipCode.maxLength = 5;
	}
}

//
// Validation helpers
//
function hasInvalidValidators(controlId)
{
    for (ii = 0; ii < Page_Validators.length; ii++) {
        if (!Page_Validators[ii].isvalid) {
            if (Page_Validators[ii].controltovalidate == controlId) {
                return true;
            }
        }
    }
    return false;
}

/* Called when leave a form control and on submit, NOTE: base implementation SHOWS or HIDES the validator */       
function schwansValidatorUpdateDisplay(val) {

    // hide the multi control error
    if (typeof(schwansPage_hideErrors) != "undefined")
        schwansPage_hideErrors();

    if (val.display == "None" || val.display == "Static")
        return;

    var validator = $('#' + val.id);
    
    if (!validator.hasClass("schwans-error")) {
        if (!val.isvalid) {
            // show validator error
            validator.css("display", "inline");
        } else {
            // hide the validator error
            validator.css("display", "none");
        }
        return;
    }

    if (!val.isvalid) {
        //alert("Invalid " + val.id);            
        var validatorParent = validator.parent();
        var validatorLabel = validatorParent.prev();
        // show validator
        validator.css("display", "block");
        
        // set style around control
        validatorParent.addClass("middleformerror");
        // set style of corrisponding label
        validatorLabel.addClass("leftformerror");
        // show extra space in span table of label to make up for extra space the message adds
        validatorLabel.children("span").css("display", "block");
    } else {
        // hide the validator error
        validator.css("display", "none");
        
        // hide leftformerror and rightformerror if the control that belongs to the validator has no other invalid validators
        if (!hasInvalidValidators(val.controltovalidate))
        {
            var validatorParent = validator.parent();
            var validatorLabel = validatorParent.prev();
            // remove style around control
            validatorParent.removeClass("middleformerror");
            // remove style of corrisponding label
            validatorLabel.removeClass("leftformerror");
            // hide extra space in span table of label to make up for extra space the message adds
            validatorLabel.children("span").css("display", "none");
        }
    }
}
