﻿/*
 * ----------------------------------------------------------------------------
 * GENERAL VALIDATION FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */

function CheckBoxMustBeChecked_SetHiddenField() {
    var checkbox = $("[id$=btnTermsAndConditions]");
    if (checkbox.attr('checked')) {
        $("[id$=txtTermsAndConditionsChecked]").val('true');
    }
    else {
        $("[id$=txtTermsAndConditionsChecked]").val('false');
    }
}


function CheckBoxValidator_MustBeChecked(source, args) {
    args.IsValid = ($("[id$=txtTermsAndConditionsChecked]").val() == 'true');
}


function CheckSavedAddress_ClientValidate(sender, args) {

    var ddl = $("SELECT[ID$='ddlSavedAddress']");

    //if the dropdownlist is disabled then we do not want to validate it, just return true
    if (ddl.attr('disabled') == true) {
        args.IsValid = true;
    }
    else {
        //ddl.val() (holds the values of the selectedvalue)

        //if the first item in the list is chossen then do not proceed
        if (ddl.attr("selectedIndex") <= 0) {
            args.IsValid = false;
        }
        else {
            args.IsValid = true;
        }
    }

}

// Sets up the alert label in the HeaderMessageDisplay control.
function ShowAlert(message) {
    var pnl = $("*[ID$='pnlHeaderMessage']");
    pnl.removeAttr("style");
    pnl.attr("style", "display:block;");
    pnl.addClass("headerMessageDisplay");

    var msgPnl = $("*[ID$='_pnlMessage']");
    msgPnl.removeAttr("style");
    pnl.attr("style", "display:block;");
    pnl.addClass("alert");

    var label = $("SPAN[ID$='lblMessageToDisplay']");

    label.text(message);
}

// Clears the alert label in the HeaderMessageDisplay control.
function ClearAlert() {
    var pnl = $("*[ID$='_pnlHeaderMessage']");
    pnl.removeAttr("style");
    pnl.removeAttr("class");
    pnl.attr("style", "display:none;");

    var msgPnl = $("*[ID$='_pnlMessage']");
    msgPnl.removeAttr("style");
    msgPnl.removeAttr("class");
    msgPnl.attr("style", "display:none;");

    var label = $("SPAN[ID$='lblMessageToDisplay']");

    label.text("");
}


// Validates the page with the default validation group (i.e. 'HeaderMsg')
function ValidatePage() {
    return ValidatePageGroup('HeaderMsg');
}


// Validates the page against the given validation group.
function ValidatePageGroup(vGroup) {

    ClearAlert();

    var inputValid = Page_ClientValidate(vGroup);

    //set the hidden field so that we know to cause a post back on the dropdownlist
    $("*[ID$='hfCauseValidation']").val(!inputValid);

    // upnlHeaderMessage that should not be changed)
    var pnl = $("*[ID$='_pnlHeaderMessage']");

    var divValidationSummary;

    if (vGroup === 'HeaderMsg') {
        divValidationSummary = $("*[ID$='_vsErrors']");
    }
    else if (vGroup === 'HeaderMsg2') {
        divValidationSummary = $("*[ID$='_vsErrors2']");
    }
    else if (vGroup === 'HeaderMsg3') {
        divValidationSummary = $("*[ID$='_vsErrors3']");
    }

    if (!inputValid) {
        pnl.removeAttr("class");
        pnl.addClass("headerMessageDisplay");
        pnl.slideDown();

        divValidationSummary.removeAttr("style");
        divValidationSummary.removeAttr("class");
        divValidationSummary.addClass("alert");

        if (typeof (Page_Validators) != "undefined") {

            for (var index = 0; index < Page_Validators.length; index++) {
                if (!Page_Validators[index].isvalid && Page_Validators[index].validationGroup == vGroup) {
                    $('#' + Page_Validators[index].controltovalidate).addClass('form_error');
                }
                else if (Page_Validators[index].isvalid) {
                    $('#' + Page_Validators[index].controltovalidate).removeClass('form_error');
                }

            }
        }
    }
    else {
        pnl.removeAttr("class");
        pnl.slideUp();
        
        divValidationSummary.removeAttr("style");
        divValidationSummary.removeAttr("class");
    }

    //IE6, the alert image needs to be fixed

    return inputValid;
}

function fnSwitchProductDetailsTabs(index) {
    var details = $("#pnlDetails");
    var about = $("#pnlAbout");
    var ingredients = $("#pnlIngredients");
    var nutrition = $("#pnlNutrition");
    var disclaimer = $("#pd_disclaimer");
    removeActiveClass();


    var detailsTab = $('.details_tabs');

    switch (index) {
        case 1:
            detailsTab.find("*[ID$='details_tab']").find('a').attr("class", "active");
            details.show();
            about.hide();
            ingredients.hide();
            nutrition.hide();
            disclaimer.hide();
            break;
        case 2:
            detailsTab.find("*[ID$='about_tab']").find('a').attr("class", "active");
            details.hide();
            about.show();
            ingredients.hide();
            nutrition.hide();
            disclaimer.show();
            break;
        case 3:
            detailsTab.find("*[ID$='ingredients_tab']").find('a').attr("class", "active");
            details.hide();
            about.hide();
            ingredients.show();
            nutrition.hide();
            disclaimer.show();
            break;
        case 4:
            detailsTab.find("*[ID$='nutrition_tab']").find('a').attr("class", "active");
            details.hide();
            about.hide();
            ingredients.hide();
            nutrition.show();
            disclaimer.show();
            break;
    }
}


function removeActiveClass() {
    var detailsTab = $('.details_tabs');
    detailsTab.find("*[ID$='details_tab']").find("a").removeAttr("class", "active");
    detailsTab.find("*[ID$='about_tab']").find("a").removeAttr("class", "active");
    detailsTab.find("*[ID$='ingredients_tab']").find("a").removeAttr("class", "active");
    detailsTab.find("*[ID$='nutrition_tab']").find("a").removeAttr("class", "active");
}


/*
 * ----------------------------------------------------------------------------
 * WEIGHT AND QUANTITY RELATED FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 
function fnFormatNum(expr, decplaces) {
    var str = "" + Math.round(eval(expr) * Math.pow(10, decplaces))
    while (str.length <= decplaces)
    { str = "0" + str; }
    var decpoint = str.length - decplaces
    return str.substring(0, decpoint) + "." + str.substring(decpoint, str.length);
}

function fnSetListingQuantity(id, qty) {
    var qtyCtrl = document.getElementById(id);
    if (qtyCtrl != null) {
        qtyCtrl.value = parseInt(qty);
    }
};

function fnGetListingQuantity(id) {
    var qtyCtrl = document.getElementById(id);
    return qtyCtrl.value;
};

function fnListingPlusWithUpdate(id, updatePriceControl, basePrice) {
    // decrement the Quantity
    fnpl(id);
    // get price
    var price = parseFloat(basePrice);
    if (price > 0) {
        // calculate total
        var total = fnFormatNum(($get(id).value) * price, 2);
        if (total != null) {
            // set the price
            fnDetailSetTotalPrice(updatePriceControl, total);
        }
    }
}

function fnListingMinusWithUpdate(id, updatePriceControl, basePrice) {
    // decrement the Quantity
    fnmi(id);
    // get price
    var price = parseFloat(basePrice);
    if (price > 0) {
        // calculate total
        var total = fnFormatNum(($get(id).value) * price, 2);
        if (total != null) {
            // set the price
            fnDetailSetTotalPrice(updatePriceControl, total);
        }
    }
}

function fnDetailSetTotalPrice(id, total) {
    $('#pnlDetails').find("*[ID$='" + id + "']").text("€" + total);
}
function fnplx(pid) {
    var productRow = $('#' + pid);
    var tb = productRow.find("*[ID$='tbQuantity']");
    fnpl(tb.attr('id'));
}
// increment the Quantity(fnlistingplus)
function fnpl(id) {
    var quant = parseInt($get(id).value);
    if (parseInt(quant) >= 999) {
        fnSetListingQuantity(id, 999);
    }
    else {
        fnSetListingQuantity(id, quant + 1);
    }
};
function fnmix(pid) {
    var productRow = $('#' + pid);
    var tb = productRow.find("*[ID$='tbQuantity']");
    fnmi(tb.attr('id'));
}
// decrement the Quantity ( fnlistingminus)
function fnmi(id) {
    var element = $get(id);
    var quant = parseInt(element.value);
    if (parseInt(quant) > 1) {
        fnSetListingQuantity(id, parseInt(quant) - 1);
    }
};
function fnListingMinusChoice(id) {
    var element = $get(id);
    var quant = parseInt(element.value);
    if (parseInt(quant) > 1) {
        fnSetListingQuantity(id, parseInt(quant) - 1);
    }
    else {
        fnSetListingQuantity(id, 0);
    }
};
//
function fnListingChangeQuantity(id) {
    fnSetListingQuantity(id, parseInt(fnGetListingQuantity(id)));
    fnValidateQuantityRange(id);
};
//
function fnValidateQuantityBlur(id) {
    if (parseInt(fnGetListingQuantity(id)) == 0) {
        fnSetListingQuantity(id, "1");
    } else {
        if (fnGetListingQuantity(id) == "") {
            fnSetListingQuantity(id, "1");

        }
        fnSetListingQuantity(id, parseInt(fnGetListingQuantity(id)));
    }
};
//
function fnValidateQuantityRange(id) {
    if (isNaN(fnGetListingQuantity(id))) 
    {
        fnSetListingQuantity(id, "1");
    }
    else 
    {
        if (parseInt(fnGetListingQuantity(id)) > 999) 
        {
            fnSetListingQuantity(id, "999");
        }
        else 
        {
            if (parseInt(fnGetListingQuantity(id)) < 0) 
            {
                fnSetListingQuantity(id, "0");
            }
        }
    }
};

function fnWeightPlusWithUpdate(id, increment, updatePriceControl, basePrice) {
    fnWeightPlus(id, increment);
    var price = fnFormatNum(parseFloat($get(id).value) * parseFloat(basePrice), 2);
    var element = $get(updatePriceControl);
    element.innerHTML = "$" + price;
}

function fnWeightMinusWithUpdate(id, increment, updatePriceControl, basePrice) {
    fnWeightMinus(id, increment);
    var price = fnFormatNum(($get(id).value) * parseFloat(basePrice), 2);
    var element = $get(updatePriceControl);
    element.innerHTML = "$" + price;
}

function fnWeightPlus(id, increment) {
    var element = $get(id);
    var qty = parseFloat(element.value) + parseFloat(increment);
    fnSetPopupWeight(id, qty);
    //fnPopupValidateWeightRange(id);
    //fnPopupValidateWeightBlur(id);
};
function fnWeightMinus(id, decrement) {
    var element = $get(id);
    var qty = parseFloat(element.value) - parseFloat(decrement);
    fnSetPopupWeight(id, qty);
    //fnPopupValidateWeightRange(id);
    //fnPopupValidateWeightBlur(id);
};
function fnPopupValidateWeightRange(id) {
    if (isNaN(fnGetPopupWeight(id))) {
        fnSetPopupWeight(id, "1.00");
    } else {
        if (parseFloat(fnGetPopupWeight(id)) > 999) {
            fnSetPopupWeight(id, "999.00");
        } else {
            if (parseFloat(fnGetPopupWeight(id)) < 0) {
                fnSetPopupWeight(id, "0.00");
            }
        }
    }
};
function fnPopupValidateWeightBlur(id) {
    if (parseFloat(fnGetPopupWeight(id)) <= 0) {
        fnSetPopupWeight(id, "1.00");
    } else {
        if (fnGetPopupWeight(id) == "") {
            fnSetPopupWeight(id, "1.00");
        }
    }
};
//This function is not used here but is called from core QuantityPlusMinusDouble.cs
function fnPopupWeightChange(id, labelToUpdate) {
    //fnPopupValidateWeightRange(id);
    //updateWeightDisplay(id, labelToUpdate);
};



function fnGetPopupWeight(id) {
    var element = $get(id);

    element = element.value;

    if (element.substring(element.length - 1, element.length) == ".") {
        element += "0";
    }

    return element;
};
function fnSetPopupWeight(id, qty) {
    var element = $get(id);
    element.value = fnFormatNum(qty, 2);
};

//
function IncrementWeightUpdate(id, increment, updatePriceControl) {
    fnWeightPlus(id, increment);
    updateWeightDisplay(id, updatePriceControl);
}

//
function DecrementWeightUpdate(id, increment, updatePriceControl) {
    fnWeightMinus(id, increment);
    updateWeightDisplay(id, updatePriceControl);
}


function IncrementPriceAddNote(id, labelToUpdate) {

    var clientId = $("#pnl_AddnoteClientId").val();
    var popup = $("#" + clientId);

    fnpl(id);
    var q = $get(id).value;

    var price = $("#" + popup._PopupControlID).find("*[ID$='hfPopupPrice']").val();

    price = fnFormatNum(parseFloat(q) * parseFloat(price), 2);

    $("#" + popup._PopupControlID).find("#" + labelToUpdate).text("$" + price);
}


function DecrementPriceAddNote(id, labelToUpdate) {
    var clientId = $("#pnl_AddnoteClientId").val();
    var popup = $("#" + clientId);

    fnmi(id);

    var q = $get(id).value;

    var price = $("#" + popup._PopupControlID).find("*[ID$='hfPopupPrice']").val();
    price = fnFormatNum(parseFloat(q) * parseFloat(price), 2);
    $("#" + popup._PopupControlID).find("#" + labelToUpdate).text("$" + price);
}


function updateWeightDisplay(valueControlID, updatePriceControl) {
    var clientId = $("#pnlChooseWeightClientID").val();
    var popupContainer = $("#" + clientId);


    var q = $get(valueControlID).value;
    var pid = "";
    var row = "";

    if (popupContainer != null) {
        pid = popupContainer.find("*[ID$='hfProductId']").val();

        var dotPosition = q.indexOf(".")
        //If input any invalid charater or input more than 2 digits,reset the quantity
        if (isNaN(q) || parseFloat(q) <= 0 || q == "" || parseFloat(q) > 999 ) {
            q = "1.00";

            if (pid != null && pid != undefined) {
                row = $("#" + pid);
            }
            //If it is in shopping basket or active order listing,roll back to the original quantity entered by the user
            if (row != null && row != undefined) {
                if (row.find("*[ID$='hfWeightedQuantity']").val() != undefined) {
                    q = row.find("*[ID$='hfWeightedQuantity']").val();
                }
                else if (row.find("*[ID$='lblItemSelectedQuantity']") != null &&
                    row.find("*[ID$='lblItemSelectedQuantity']") != undefined &&
                    row.find("*[ID$='lblItemSelectedQuantity']").text() != "") {
                    var s = row.find("*[ID$='lblItemSelectedQuantity']").text();

                    q = fnFormatNum(parseFloat(s.trim().substring(1, s.length - 2)), 2);
                }
                else {
                    var itemDivID = pid + "_minibasketitem";
                    var itemDiv = $("#" + itemDivID);
                    if (itemDiv.length != 0) {
                        q = itemDiv.find("INPUT[ID$='hfQuantity']").val();
                    }
                }
            }



            //If it is in product listing roo back to 1.00
            popupContainer.find("*[ID$='tbQuantityDouble']").val(q);
        }
        if (q.substring(dotPosition + 1, q.length).length > 2) {
            popupContainer.find("*[ID$='tbQuantityDouble']").val(fnFormatNum(parseFloat(q), 2));
        }


        if (q < 1) {
            popupContainer.find("#weightInGrammes").show().text((q * 16) + " Oz");
            //$("#" + popup._PopupControlID).find("*[ID$='lblcurrentSelectedWeight']").hide();
        }
        else {
            popupContainer.find("#weightInGrammes").hide();
            //$("#" + popup._PopupControlID).find("*[ID$='lblcurrentSelectedWeight']").show();
        }

        var price = popupContainer.find("*[ID$='hfPopupPrice']").val();
        price = fnFormatNum(parseFloat(q) * parseFloat(price), 2);
        popupContainer.find("#" + updatePriceControl).text("$" + price);

        popupContainer.find("*[ID$='lblItemSelectedQuantity']").text(" x " + q + " lb");
    }

}







/*
 * ----------------------------------------------------------------------------
 * TOOLTIP RELATED FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */

function ShowTip(text) {

    var toolTipText;
    var textArr = text.split('#');

    if (textArr.length == 1) {
        toolTipText = "<p>" + textArr[0] + "</p>";
    }
    else {
        toolTipText = "<h2>" + textArr[0] + "</h2>";

        for (var i = 1; i < textArr.length; i++) {
            toolTipText += "<p>" + textArr[i] + "</p>";
        }
    }

    //Tip('<div class="tooltip">' + toolTipText + '</div>', 400,10, PADDING, 9);
}









// Change the save changes button in the basket to be a loading icon when the user hits save changes.
function UnBindBasketSaveChanges() {

    var hdnUrlPath = $("*[ID$='hfSiteUrlWithTheme']").val();

    var btnSaveChangesTop = $("*[ID$='btnUpdateBasketTop']");
    var imgSaveChangesTop = $("#imgUpdateBasketTop");

    var btnSaveChangesBottom = $("*[ID$='btnUpdateBasketBottom']");
    var imgSaveChangesBottom = $("#imgUpdateBasketBottom");

    btnSaveChangesTop.removeAttr("onclick");

    btnSaveChangesTop.unbind();
    btnSaveChangesTop.bind("click", function() {
        return false;
    });

    imgSaveChangesBottom.attr("src", hdnUrlPath + "/images/anim_processing.gif");

    imgSaveChangesBottom.mouseover(function() {
    $(this).attr("src", hdnUrlPath + "/Images/anim_processing.gif");
    });

    imgSaveChangesBottom.mouseout(function() {
    $(this).attr("src", hdnUrlPath + "/Images/anim_processing.gif");
    });

    btnSaveChangesBottom.removeAttr("onclick");

    btnSaveChangesBottom.unbind();
    btnSaveChangesBottom.bind("click", function() {
        return false;
    });
}



/*
 * ----------------------------------------------------------------------------
 * EMAIL/PASSWORD RELATED FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */


function ValidateEmailChanges(source, args) {
    var value = args.Value;
    args.IsValid = ValidateEmail(value);
}

function ValidateEmail(value) {
    // do length check.

    // do regex
    var exp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (exp.test(value) == true) {
        return true;
    }
    else {
        return false;
    }
}

function ValidatePasswordChanges(source, args) {
    var password = args.Value;
    args.IsValid = ValidatePassword(password);
}


function ValidatePassword(pass) {
    //Minimum length 6 chars, max 20 chars.
    //At least 1 uppercase or 1 number or special char
    var exp = /^.*(?=.{6,20})(?=.*[A-Z0-9\W]).*$/;
    if (exp.test(pass) == true) {
        return true;
    }
    else {
        return false;
    }
}



/*
 * ----------------------------------------------------------------------------
 * MISC UTILITY FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 
 

 
 
/********************************************
 * Determines how many characters the user has left in a given form input field.
 * Used in note popup and checkout delivery addr directions.
 *******************************************/
function numCharLeft(input, maxChars) {
    var numChars = input.value.length;

    if (numChars > maxChars) {
        input.value = input.value.substring(0, maxChars);

    }
}

function ParseBoolean(value) {
    if (value == null || value == undefined)
        return false;

    if (value == false)
        return false;
    else if (value == true)
        return true;

    if (isNaN(value)) {
        if (value == "true")
            return true;
        else
            return false;
    }
    else {
        if (value == 0)
            return false;
        else
            return true;
    }
}


function ResetScrollPosition() {

    $('#cntContentWrapper').scrollTo(0, 0);


   }

/********************************************
 * Given a file path, returns the entire URL by using the hfUrl hidden field.
 *******************************************/
function resolveURL(url) {
    return $("input[ID$='hfUrl']").val() + url;
}


// replaces the image name in an image path.
function switchImageName(imageFullPath, newImageName) {
    if (imageFullPath != "" && imageFullPath != undefined) {
        var arrPath = imageFullPath.split('/');
        arrPath[arrPath.length - 1] = newImageName;
        return arrPath.join('/');
    }

    return imageFullPath;
}


// Used in the CreditCard Screen to allow a unique radio button to be selected
// this method stems from the fact that an asp.net RadioButton cannot be used inside
// a databound control as the Gruopname will always be unique, therefore allowing all radio buttons 
// in the list to be selected together.
function SetUniqueRadioButton(nameregex, current, idOfDataItem, clientid) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }

    current.checked = true;

    $('.account_view').find("*[ID$='hfClickedRadio']").val(idOfDataItem);
    var btn = document.getElementById(clientid);
    if (btn) {
        btn.click();
    }
    ShowHideButtons();
}

function ShowHideButtons() {
    $('.account_view').find("*[ID$='btnSaveCard']").css("display", "block");
    $('.account_view').find("*[ID$='btnAddCard']").css("display", "none");
}

function doPostBackAsync(eventName, eventArgs) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
        prm._asyncPostBackControlIDs.push(eventName);
    }

    if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
        prm._asyncPostBackControlClientIDs.push(eventName);
    }


    __doPostBack(eventName, eventArgs);

}



function DisableButton(btnToBeDisabled) {
    btnToBeDisabled.unbind();
    btnToBeDisabled.click(function(event) {
        return false;
    });
}





function ResetBasketCheck() {


    var $productListing = $("*[ID$='upnlProductListing']");
    var $mini_trolley = $(".mini_trolley");

    //if the product listings are not shown and the mini basket is (i.e on the product details page)
    if (!$productListing.length && $mini_trolley.length) {

        var $fixed_minibasket = $(".fixed_minibasket");
        $fixed_minibasket.removeAttr("style");
        //remove scroll
    }

}

