﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference path="prototype\prototype.js" />
/// <reference path="jquery\jquery-1.3.2.vsdoc2.js" />

var categoriesListLoaded = false;
var brandsListLoaded = false;

function pageLoad(sender, args) {
    var hmeCategories = $find('hmeCategories');
    var hmeBrands = $find('hmeBrands');

    if(hmeCategories)
        hmeCategories.add_showing(renderCategoriesList);

    if (hmeBrands)
        hmeBrands.add_showing(renderBrandsList);

    var cartFrame = $get('up_container');
    if(cartFrame)
        $addHandler(cartFrame, 'onload', cartDetailVisibility);
}

function renderCategoriesList(sender, args) {
    if (!categoriesListLoaded) {
        CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderCategoriesList(renderCategoriesListComplete);
    }
}

function renderCategoriesListComplete(result) {
    var categoriesListLoading = $get("categoriesListLoading");
    var pnlCategoriesList = $get("pnlCategoriesList");

    pnlCategoriesList.innerHTML = result;

    categoriesListLoading.style.display = "none";
    pnlCategoriesList.style.display = "block";

    categoriesListLoaded = true;
}

function renderBrandsList(sender, args) {
    if (!brandsListLoaded) {
        CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderBrandsList(renderBrandsListComplete);
    }
}

function renderBrandsListComplete(result) {
    var brandsListLoading = $get("brandsListLoading");
    var pnlBrands = $get("pnlBrands");

    pnlBrands.innerHTML = result;

    brandsListLoading.style.display = "none";
    pnlBrands.style.display = "block";

    brandsListLoaded = true;
}

//-- Global settings ------------------------------

function TastoInvio(e) {
    evt = (e) ? e : window.event;
    var type = evt.type;
    var pK = e ? e.which : window.event.keyCode;
    if (evt.keyCode == 13) {
        Login();
    }
}

// Toggle the visibility of enduser prices
// Show / Hide Page header
function ShowHideEndUserPrices(showEndUserPricesID, buttonID) {
    var show = false;

    var showEndUserPrices = $(showEndUserPricesID);
    var button = $(buttonID);

    // old value
    show = (null != showEndUserPrices.value && "true" == showEndUserPrices.value);

    // new value in hidden control
    showEndUserPrices.value = !show;

    if (show) {
        button.innerHTML = "Solo prezzi enduser";
                
    }
    else {
        button.innerHTML = "Mostra prezzi CDC";
    }
    ShowHideEndUserPricesRefresh(showEndUserPrices.value);    
    
    PageMethods.SetOnlyEndUserPricesStatus(!show);
}

function ShowHideEndUserPricesRefresh(showOnlyEndUser) {
    show = (null != showOnlyEndUser && "true" == showOnlyEndUser);
    
    var visibilityFlag = 'visible';
    if (show) {
        visibilityFlag = 'hidden';
    }
    //alert(visibilityFlag);
    $$('.showHideEndUserPrices').each(function(node) { node.style.visibility = visibilityFlag; });       
}

// Change the currently selected Cash & Carry
function changeCurrentCashCarry(cc)
{
    PageMethods.SetCashCarry(cc, changeCurrentCashCarry_Success);
    return true;
}

function changeCurrentCashCarry_Success(result)
{
    UpdateProductQuantities();
}

function UpdateProductQuantities()
{
    var itemsOdd = new Array();
    var itemsEven = new Array();
    
    var spans = $$('.ccQty');
    
    for(var i = 0; i < spans.length; i++)
    {
        var ccSpan = spans[i];
        ccSpan.innerHTML = "<img src='/CdcPoint/Images/ajax-loader.gif' height='12' width='12' />";

        var allCcSpanId = "allCc" + ccSpan.id.substr(2, 5);
        var allCcSpan = $get(allCcSpanId);
        if (allCcSpan != null)
            allCcSpan.innerHTML = "<img src='/CdcPoint/Images/ajax-loader.gif' height='12' width='12' />";

        var item = {
            ProductID: ccSpan.id.substr(2, 5),
            QtyControlID: ccSpan.id,
            Quantity: 0,
            AllCcQtyControlID: allCcSpanId,
            AllCcQuantity: 0
        };
        
        if (i % 2 == 0)
            itemsEven.push(item);
        else
            itemsOdd.push(item);
        
        ccSpan = null;
        allCcSpan = null;
    }
    spans = null;

    if (itemsOdd.length > 0) {
        try {
            CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.GetCashAndCarryQuantities(itemsOdd, GetCashAndCarryQuantities_Success);
        }
        catch(e) {}
    }

    if (itemsEven.length > 0) {
        try {
            CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.GetCashAndCarryQuantities(itemsEven, GetCashAndCarryQuantities_Success);
        }
        catch (e) { }
    }
}

function GetCashAndCarryQuantities_Success(results)
{
    var spans = results.toArray();
    for (var i = 0; i < results.length; i++)
    {
        var item = results[i];
        
        var span = $(item.QtyControlID);
        if (span != null)
        {
            span.innerHTML = String.format('{0}&nbsp;pz', item.Quantity);
        }
        span = null;

        var allCcSpan = $(item.AllCcQtyControlID);
        if (allCcSpan != null) {
            allCcSpan.innerHTML = String.format('{0}&nbsp;pz', item.AllCcQuantity);
        }
        allCcSpan = null;
        
        item = null;
    }
    spans = null;
}

function UpdateProductPrices(filterProp1, filterProp2, filterProp3, filterProp4, destinationUrlBase) {
    var loadingImage = "<img src='/CdcPoint/Images/ajax-loader.gif' height='12' width='12' />";
    
    var PromoControlID = null;
    var DiscountControlID = null;
    var Filt1ControlID = null;

    var itemsOdd = new Array();
    var itemsEven = new Array();
    var spans = $$('.cdcPrice');

    for (var i = 0; i < spans.length; i++) {
        var priceSpan = spans[i];
        priceSpan.innerHTML = loadingImage;
        
        PromoControlID = priceSpan.id.replace("price", "promo");
        var promoSpan = $get(PromoControlID);
        if (promoSpan != null) {
            promoSpan.innerHTML = loadingImage;
        }
        promoSpan = null;

        DiscountControlID = priceSpan.id.replace("price", "disc");
        var discSpan = $get(DiscountControlID);
        if (discSpan != null) {
            discSpan.innerHTML = loadingImage;
        }
        discSpan = null;

        Filt1ControlID = priceSpan.id.replace("price", "filt1");
        var filtDiv = $get(Filt1ControlID);
        if (filtDiv != null) {
            filtDiv.innerHTML = loadingImage;
        }
        filtDiv = null;

        var item = {
            PriceControlID: priceSpan.id,
            CatalogName: priceSpan.attributes["cat"].value,
            ProductID: priceSpan.attributes["pid"].value,
            DiscountedPrice: '',
            DiscountPercentage: '',
            PromoInfo: '',
            Filt1: '',
            Filt2: '',
            Filt3: '',
            Filt4: ''
        };

        if (i % 2 == 0)
            itemsEven.push(item);
        else
            itemsOdd.push(item);

        priceSpan = null;
    }
    spans = null;

    if (itemsOdd.length > 0) {
        try {
            CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.GetProductPrices(filterProp1, filterProp2, filterProp3, filterProp4, destinationUrlBase, itemsOdd, UpdateProductPrices_Success);
        }
        catch (e) { }
    }

    if (itemsEven.length > 0) {
        try {
            CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.GetProductPrices(filterProp1, filterProp2, filterProp3, filterProp4, destinationUrlBase, itemsEven, UpdateProductPrices_Success);
        }
        catch (e) { }
    }
}

function UpdateProductPrices_Success(results) {
    var PromoControlID = null;
    var DiscountControlID = null;
    var Filt1ControlID = null;
    var Filt2ControlID = null;
    var Filt3ControlID = null;
    var Filt4ControlID = null;
    
    var spans = results.toArray();

    for (var i = 0; i < results.length; i++) {
        var item = results[i];

        var priceSpan = $(item.PriceControlID);
        if (priceSpan != null) {
            priceSpan.innerHTML = String.format('{0}', item.DiscountedPrice);
        }
        priceSpan = null;

        DiscountControlID = item.PriceControlID.replace("price", "disc");
        var discSpan = $(DiscountControlID);
        if (discSpan != null) {
            discSpan.innerHTML = String.format('{0}', item.DiscountPercentage);
        }
        discSpan = null;

        PromoControlID = item.PriceControlID.replace("price", "promo");
        var promoSpan = $(PromoControlID);
        if (promoSpan != null) {
            promoSpan.innerHTML = String.format('{0}', item.PromoInfo);
        }
        promoSpan = null;

        var filtDiv = null;

        Filt1ControlID = item.PriceControlID.replace("price", "filt1");
        filtDiv = $get(Filt1ControlID);
        if (filtDiv != null) {
            filtDiv.innerHTML = String.format('{0}', item.Filt1);
        }

        Filt2ControlID = item.PriceControlID.replace("price", "filt2");
        filtDiv = $get(Filt2ControlID);
        if (filtDiv != null) {
            filtDiv.innerHTML = String.format('{0}', item.Filt2);
        }

        Filt3ControlID = item.PriceControlID.replace("price", "filt3");
        filtDiv = $get(Filt3ControlID);
        if (filtDiv != null) {
            filtDiv.innerHTML = String.format('{0}', item.Filt3);
        }

        Filt4ControlID = item.PriceControlID.replace("price", "filt4");
        filtDiv = $get(Filt4ControlID);
        if (filtDiv != null) {
            filtDiv.innerHTML = String.format('{0}', item.Filt4);
        }

        filtDiv = null;

        item = null;
    }

    spans = null;
}

function searchCategories(phrase, pnlId) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderSearchCategoriesResults(phrase, search_success, search_failure, pnlId);
}

function searchBrands(phrase, pnlId) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderSearchBrandResults(phrase, search_success, search_failure, pnlId);
}

function searchExactMatch(phrase, pnlId) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderSearchExactMatchResults(phrase, search_success, search_failure, pnlId);
}

function searchSingleWord(phrase, pnlId) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderSearchSingleWordResults(phrase, search_success, search_failure, pnlId);
}

function searchFreeText(phrase, pnlId) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderSearchFreeTextResults(phrase, search_success, search_failure, pnlId);
}

function search_success(result, pnlId) {
    var pnl = $get(pnlId);
    pnl.innerHTML = result;
}

function search_failure(error, pnlId) {
    var pnl = $get(pnlId);
    pnl.innerHTML = error.get_message();
}

//-- Cart -------------------------------------------------

function refreshFrame() {
    var cartContainer = $('up_container');
    
    $('basketMenuLoading').style.display = '';
    cartContainer.style.display = 'none';
    cartContainer.src = "/CdcPoint/CartPopUp.aspx";
}

function cartDetailVisibility() {
    $('up_container').style.display = '';
    $('basketMenuLoading').style.display = 'none';
}

function AddProductToCart(catalogName, productID, tbxQuantityID, btnAddToCardID) {
    var tbxQuantity = $get(tbxQuantityID);
    var btnAddToCart = $get(btnAddToCardID);

    try {
        btnAddToCart.style.visibility = 'hidden';
        
        var qty = '0';
        if (tbxQuantity.value) {
            qty = tbxQuantity.value;
            tbxQuantity.value = '';
        }
        CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.AddToBasket(catalogName, productID, qty, AddProductToCart_Success, AddProductToCart_Failure, btnAddToCardID);
    }
    catch (e) {alert(e); }
}

function AddProductToCart_Success(result, btnAddToCardID) {
    var btnAddToCart = $get(btnAddToCardID);
    
    if (result != null) {
        var popup = $find('mpeNotifyAddedToCart');
        var label = $get('lblNotifyAddedToCart');
        
        label.innerHTML = result.Message;
        popup.show();
        btnAddToCart.style.visibility = 'visible';
        if (result.Added) {
            UpdateBasketInfos(result.ProductCount);
        }
        setTimeout('CloseAddToCartNotification();', 2500);
    }
}

function AddProductToCart_Failure(error, btnAddToCardID) {
    alert(error);
    var btnAddToCart = $get(btnAddToCardID);
    btnAddToCart.style.visibility = 'visible';
}

function CloseAddToCartNotification() {
    var popup = $find('mpeNotifyAddedToCart');
    if(popup != null)
        popup.hide();
}

function UpdateBasketInfos(productCount) {
    var lblHeaderCurrentCartProducts = $get('lblHeaderCurrentCartProducts');
    if (lblHeaderCurrentCartProducts)
        lblHeaderCurrentCartProducts.innerHTML = productCount;
}

function SetCurrentBasketNoClose(basketName) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.SetCurrentBasket(basketName, SetCurrentBasketNoClose_Success);
}

function SetCurrentBasket(basketName) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.SetCurrentBasket(basketName, SetCurrentBasket_Success);
}

function SynchronizeBasketName() {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.SynchronizeBasketName();
}

function SetCurrentBasket_Success(result) {
    if (result.Set) {
        var lblHeaderCurrentCartName = window.parent.document.getElementById('lblHeaderCurrentCartName');
        if (lblHeaderCurrentCartName)
            lblHeaderCurrentCartName.innerHTML = result.CartName;
        
        var lblHeaderCurrentCartProducts = window.parent.document.getElementById('lblHeaderCurrentCartProducts');
        if (lblHeaderCurrentCartProducts)
            lblHeaderCurrentCartProducts.innerHTML = result.ProductCount;

        var imgClose = window.parent.document.getElementById('ctl00_cdcHeader_cdcBasket_imgClose');

        if (imgClose.dispatchEvent) {
            var e = document.createEvent("MouseEvents");

            e.initEvent("click", true, true);
            imgClose.dispatchEvent(e);

        }

        else {
            imgClose.click();

        }
        
//        
//        if (imgClose != null) {
//            imgClose.click();
//            //imgClose.onclick();
//           
//            
//        }
            
    }
    else alert("Carrello non impostato");
}

function SetCurrentBasketNoClose_Success(result) {
    if (result.Set) {
        var lblHeaderCurrentCartName = window.parent.document.getElementById('lblHeaderCurrentCartName');
        if (lblHeaderCurrentCartName)
            lblHeaderCurrentCartName.innerHTML = result.CartName;

        var lblHeaderCurrentCartProducts = window.parent.document.getElementById('lblHeaderCurrentCartProducts');
        if (lblHeaderCurrentCartProducts)
            lblHeaderCurrentCartProducts.innerHTML = result.ProductCount;      
    }
    else alert("Carrello non impostato");
}

function setBasketNameEditStatus(editing) {
    var pnlBasketNameView = $get("pnlBasketNameView");
    var pnlBasketNameEdit = $get("pnlBasketNameEdit");
    var pnlBasketNameActionsView = $get("pnlBasketNameActionsView");
    var pnlBasketNameActionsEdit = $get("pnlBasketNameActionsEdit");

    if (pnlBasketNameEdit != null && pnlBasketNameView != null && pnlBasketNameActionsView != null && pnlBasketNameActionsEdit != null) {
        pnlBasketNameView.style.display = (editing) ? 'none' : 'block';
        pnlBasketNameActionsView.style.display = (editing) ? 'none' : 'block';
        pnlBasketNameEdit.style.display = (editing) ? 'block' : 'none';
        pnlBasketNameActionsEdit.style.display = (editing) ? 'block' : 'none';
    }
}

function btnRename_Click() {
    setBasketNameEditStatus(true);
}

function btnCancel_Click() {
    setBasketNameEditStatus(false);
}

function ddlBasketList_SelectedIndexChanged(linkButtonId) {
    var lb = $get(linkButtonId);
    if (lb != null) lb.click();
}

// -- Promo Codes --------------------
function allIn() {
    var checkAll = $$("input[id$='chkAll']");

    checkAll.checked = true;
    selectAllPromoCodes(checkAll);
}

function selectAllPromoCodes(sender) {
    $$("table[id$='gvPromocodes'] >tbody >tr >td >input:checkbox").each(function(node) {
        node.checked = sender.checked;
        addPromoCode(node);
    });
}

function addPromoCode(sender) {
    var promoCode = String.format("|{0}", $(sender).next('label').innerText.strip());
    var appliedPromoCodes = $$("input[id$='hfAppliedPromoCodes']")[0];

    $(appliedPromoCodes).value = $(appliedPromoCodes).value.replace(promoCode, "");
    
    if (sender.checked) {
        $(appliedPromoCodes).value = String.format("{0}{1}", appliedPromoCodes.value, promoCode);
    }
}

// -- Configurator selection checkboxes --------------------

function countSelectedItems() {
    var selectedItems = 0;

    var qtys = $$('.ItemQty');
    for (i = 0; i < qtys.length; i++) {
        selectedItems += parseInt(qtys[i].value);
    }

    return selectedItems;
}

function imgUp_OnClick(image, maxItems, tbxQtyID) {
    var selectedItems = countSelectedItems();

    if (selectedItems >= maxItems) {
        alert(String.format("E' possibile inserire al massimo {0} elementi di questo tipo.", maxItems));
        var tbxQty = $get(tbxQtyID);
        tbxQty.value = parseInt(tbxQty.value) - 1;
    }
}

function gotoStep(url, checkForSelectedItems) {
    var pids = "";
    var qty = 0;
    
    var qtys = $$('.ItemQty');
    for (i = 0; i < qtys.length; i++) {
        qty = parseInt(qtys[i].value);
        if (qty > 0) {
            if (pids.length > 0) pids += ",";
            pids += qtys[i].value + qtys[i].attributes["pid"].value;
        }
    }

    if (checkForSelectedItems && pids.length < 1) {
        alert('Selezionare almeno un elemento dalla lista.');
    }
    else {
        location.href = url + "&pid=" + pids;
    }
}

// -- Products List comparison checkboxes -----------------

function ComparisonCheckBox_OnClick(checkBox, inputHiddenID, catalog, pid)
{
    var done = false;
    
    if (checkBox != null)
    {
        if (checkBox.checked)
        {
            done = AddToComparisonList(inputHiddenID, catalog, pid);
            if (!done) checkBox.checked = false;
        }
        else
            done = RemoveFromComparisonList(inputHiddenID, catalog, pid);
    }
        
    return done;
}

function RemoveFromSelectionList(inputHiddenID, catalog, pid) {
    var done = false;
    
    var inputHidden = $get(inputHiddenID);
    if (inputHidden != null) {
        var itemToRemove = createComparisonToken(catalog, pid);
        var items = inputHidden.value.split(',');
        inputHidden.value = '';
        for (var i = 0; i < items.length; i++) {
            if (items[i] + ',' == itemToRemove)
                items[i] = '';

            if (items[i] != '')
                inputHidden.value += items[i] + ',';
        }
        done = true;
    }
    return done;
}

function AddToComparisonList(inputHiddenID, catalog, pid)
{
    // questo valore deve essere considerato minore di una unita'
    // es. se voglio 5 prodotti comparabili inserire 4
    var maxComparableProducts = 4;
    var done = false;
    var inputHidden = $get(inputHiddenID);
    if (inputHidden != null)
    {
        if (ComparisonListCount(inputHidden) <= maxComparableProducts)
        {
            inputHidden.value += createComparisonToken(catalog, pid);
            done = true;
        }
        else
        {
            alert(String.format("Non è possibile confrontare più di {0} prodotti alla volta.", maxComparableProducts + 1));
        }
    }

    return done;
}

function RemoveFromComparisonList(inputHiddenID, catalog, pid)
{
    var done = false;
    var inputHidden = $get(inputHiddenID);
    if (inputHidden != null)
    {
        var itemToRemove = createComparisonToken(catalog, pid);
        var items = inputHidden.value.split(',');
        inputHidden.value = '';
        for (var i=0; i < items.length; i++)
        {
            if (items[i] + ',' == itemToRemove)
                items[i] = '';

            if (items[i] != '')
                inputHidden.value += items[i] + ',';
        }
        done = true;
    }
    return done;
}

function CompareSelected(inputHiddenID)
{
    var inputHidden = $get(inputHiddenID);
    if (inputHidden != null)
    {
        if (ComparisonListCount(inputHidden) < 2)
        {
            alert("Selezionare almeno due prodotti da confrontare.");
        }
        else
        {
            document.location = "/CdcPoint/ProductComparison.aspx?ProductList=" + inputHidden.value;
        }
    }
}

function createComparisonToken(catalog, pid)
{
    return catalog + "|" + pid + ",";
}

function ComparisonListCount(inputHidden)
{
    var count = -1;
    if (inputHidden != null)
    {
        count = inputHidden.value.split(',').length - 1;
    }
    
    return count;
}

//-- Communication box management -------------------

function showCommunicationBox(commType, productCode) {
    var hidProductCode = $get(hidCommunicationProductCodeID);
    var hidCommunicationType = $get(hidCommunicationTypeID);
    var pnlCommunicationLoading = $get(pnlCommunicationLoadingID);
    var pnlCommunicationContent = $get(pnlCommunicationContentID);
    btnHiddenUpdatePanelTrigger = $get(btnHiddenCommUpdatePanelTriggerID);

    hidCommunicationType.value = commType;
    hidProductCode.value = productCode;

    pnlCommunicationLoading.style.display = 'block';
    pnlCommunicationContent.style.display = 'none';
    var popup = $find('mpeCommunicationPopUp');
    popup.show();
    btnHiddenUpdatePanelTrigger.click();
}

function closeCommunicationPopUp() {
    var popup = $find('mpeCommunicationPopUp');
    popup.hide();
}

//-- Cash & Carry Product Availability --------------

function showCnCProductAvailabilityPopUp(catalogName, productCode) {
    var hidCatalogName = $get(hidCncAvailabilityCatalogNameID);
    var hidProductCode = $get(hidCncAvailabilityProductCodeID);
    var pnlCnCAvailabilityLoading = $get(pnlCncAvailabilityLoadingID);
    var pnlCnCAvailabilityContent = $get(pnlCncAvailabilityContentID);
    btnHiddenUpdatePanelTrigger = $get(btnHiddenCnCUpdatePanelTriggerID);

    hidCatalogName.value = catalogName;
    hidProductCode.value = productCode;

    pnlCnCAvailabilityLoading.style.display = 'block';
    pnlCnCAvailabilityContent.style.display = 'none';
    var popup = $find('mpeProductAvailabilityPopUp');
    popup.show();
    btnHiddenUpdatePanelTrigger.click();
}

function closeCnCProductAvailabilityPopUp() {
    var popup = $find('mpeProductAvailabilityPopUp');
    popup.hide();
}

//-- Product Detail Preview --------------

function showProductDetailPreviewPopUp(catalogName, productCode) {
    CDC.CommerceSite.Web.UI.Services.CatalogAjaxHelper.RenderProductDetailPreview(productCode, catalogName, showProductDetailPreviewPopUpSuccess);

    var popup = $find('mpeProductDetailPreviewPopUp');
    popup.show();
}

function showProductDetailPreviewPopUpSuccess(result) {
    var pnlLoading = $get(pnlProductDetailPreviewLoading);
    var pnlContent = $get(pnlProductDetailPreviewContent);
    pnlContent.innerHTML = result;

    pnlLoading.style.display = "none";
    pnlContent.style.display = "block";
}

function closeProductDetailPreviewPopUp() {
    var popup = $find('mpeProductDetailPreviewPopUp');
    popup.hide();
}

//-- Utilities --------------------------------------

// Set the given value to the specified DropDownList
function setSelectedValue(ddlID, value)
{
    var ddl = $get(ddlID);
    if (ddl != null)
    {
        for (var i = 0; i < ddl.length; i++)
        {
            if (ddl.options[i].value == value)
            {
                ddl.selectedIndex = i;
                return true;
            }
        }
    }

    return false;
}

function getEventSrc(e)
{
    if (window.Event) 
    {
        return e.target.nodeType == 1 ? e.target : e.target.parentNode; 
    }
    else
    {
        return event.srcelement;
    }
}

function FocusPwd(controllo, evt) {
    try {
        if (evt.keyCode != 9) {
            //alert(controllo);
            if (controllo.value.length == 8) {
                    var pwdtxt1 = document.getElementById("pwdtxt");
                    pwdtxt1.focus();   
            }
        }
    }
    catch (e) { }

}

//-- HP Top Config ----------------------------------------------

//-- Starter Kit----------------------------------------------


function isNumber(inputText) {
    var expression = /^[0-9]+$/;
    if (inputText.value.match(expression)) {
        return true;
    } else {
        return false;
    }
}

function DisableInput(id) {
    if ($J("input[id$='" + id + "']").length > 0)
      //  $J("input[id$='" + id + "']").attr('disabled', true);
       $J("input[id$='" + id + "']").attr('disabled', 'disabled');
}
function EnableInput(id) {
    if ($J("input[id$='" + id + "']").length > 0)
       // $J("input[id$='" + id + "']").attr('disabled', 'false');
         $J("input[id$='" + id + "']").removeAttr('disabled');
}
//validates if all the quantities of span elements are not visible
function AllQuantitesValid(id) {
    if ($J("span[id$='" + id + "']:visible").length == 0) {
        return true;
    }
    else {
        return false;
    }
}

//validate a textbox quantity
function ValidateTxtQuantity(elem) {
    var valid = true;
    var txtquantity = parseInt($J(elem).val());
    var maxquantity = parseInt($J(elem).parent().prev().find("span[id$='QtaMax']").html());
    var minquantity = parseInt($J(elem).siblings().find("span[id$='QtyMin']").html());
    if (!isNumber(elem)) {//verify if it's a number
        valid = false;
    }
    else {
        if (maxquantity < txtquantity || txtquantity < minquantity) {//verify if quantity is in our interval
            valid = false;
        }
    }
        if (valid == false) {
            alert("La quantita' inserita non rispetta i vincoli. Per quantita' maggiori passa al carrello superiore o ordina separatamente.");
           // $J(elem).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500);
            $J(elem).parent().find("span[id$='validateQuantity']").show();
           
        }
        else {
                $J(elem).parent().find("span[id$='validateQuantity']").hide();
        }
        //test is all the quantities are valid
        var alltxtvalids = AllQuantitesValid('validateQuantity');
    if (alltxtvalids == false) {//disable all the buttons
        DisableInput('btnRicalcola');
        DisableInput('btnAcquista');    
        DisableInput('btnCarrelloSup');
        DisableInput('btnCarrelloInf');        
    }
    else {//enable all the buttons
        EnableInput('btnRicalcola');
        EnableInput('btnAcquista');
        EnableInput('btnCarrelloSup');
        EnableInput('btnCarrelloInf');
    }
    if (valid == false)
        $J(elem).focus();
    return valid;
}

//-- END Starter Kit----------------------------------------------

//-- START HP TOP CONFIG -----------------------------------------
function ConfigureItem(baseurl, item) {
    var url = String.format('{0}?p={1}', baseurl, item);
    window.open(url, "hpConfigurator", "menubar=0,status=0,height=600,width=700");
}

function hptcGoToCheckout(checkoutUrl) {
    opener.location.href = checkoutUrl;
    window.close();
}

//-- START PSA CONFIG -----------------------------------------
function psaMenuUrl(id, devtype) {
    var url = String.format('http://wizard.2-power.com/index.html?id={0}&devtype={1}', id, devtype);
    window.open(url, "psaConfigurator", "menubar=0,status=0,scrollbars=1,height=600,width=700");    
}

function psaGoTo(url) {
    if (typeof (opener) !== "undefined")
    {
        opener.location.href = url;
        window.close();
    }
    else {
        window.location.href = url;
    }
    
}






//-- Notify script laoded to the script manager
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

