/**
 * Provides helper methods for product compare elements.
 */

/**
 * Java-script extension methods to support format string like in C#
 * Sample: var a = 'this is {0}'.format('something')
 */
String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};;
/*exported PasswordHelper */
'use strict';

/**
 * Provides helper methods for password elements. Currently one method available for toggling of 
 * password element view mode (plain and masked).
 */
var PasswordHelper = (function ($) {

    function PasswordHelper() {
    }

    /**
     * Toggles between masked or plain password views
     */
    PasswordHelper.prototype.TogglePasswordView = function(inputId) {

        var input = $('#' + inputId)[0];

        if (input && input.type) {
            if (input.type === 'password') {
                input.type = 'text';
                $('#' + inputId).parent('.input-group').children('span').children('button').html('<i class="fa fa-eye-slash"i>');
                return;
            }
            if (input.type === 'text') {
                input.type = 'password';
                $('#' + inputId).parent('.input-group').children('span').children('button').html('<i class="fa fa-eye"></i>');
                return;
            }
        }

    };

    return PasswordHelper;

})(jQuery);

angular.module('shared').factory('PasswordHelper', function () {
    return window.passwordHelper || new PasswordHelper();
});

;
/*exported CookieHelper */
'use strict';

/**
 * Provides methods for cookie functions. Currently only one method available that reads specified cookie's value
 */

var CookieHelper = (function() {

    function CookieHelper() {
        
    }

    /**
     * Returns the value of a cookie specified by name input parameter
     */
    CookieHelper.prototype.ReadCookie = function(name) {
        var nameEq = name + '=';
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEq) === 0) {
                return c.substring(nameEq.length, c.length);
            }
        }
        return null;
    };

    return CookieHelper;

})();;
/*exported Autoship */
/*global CookieHelper:false */
'use strict';

/**
 * Provides auto-ship dialog methods for initializing, showing and extend link
 */
var Autoship = (function ($) {

    function Autoship() {
    }

    Autoship.IsDialogOpen = false;

    Autoship.prototype.InitPauseDialog = function(customerCultureNameCookie, okButtonCaption, closeButtonCaption, specificDateId, autoShipResumeDateHiddenId, dateElementId, resumeLinkId) {

        try {

            var cookieHelper = new CookieHelper();
            var javascriptCulture = cookieHelper.ReadCookie(customerCultureNameCookie).substring(0, 2);

            if ($.ui && $.ui.dialog) {

                var dialogbuttonOpts = {};

                var stringOk = okButtonCaption;
                if ($.ui.dialog.regional[javascriptCulture] !== undefined) {
                    stringOk = $.ui.dialog.regional[javascriptCulture].ok;
                }

                var stringClose = closeButtonCaption;
                if ($.ui.dialog.regional[javascriptCulture] !== undefined) {
                    stringClose = $.ui.dialog.regional[javascriptCulture].close;
                }
                dialogbuttonOpts[stringOk] = function() {
                    if ($(this).find('#' + specificDateId)[0].checked) {
                        $('#' + autoShipResumeDateHiddenId)[0].value = $(this).find('#' + dateElementId)[0].value;
                    }

                    $(this).dialog('close');
                    Autoship.IsDialogOpen = true;
                    $('#' + resumeLinkId)[0].click();
                };

                dialogbuttonOpts[stringClose] = function() {
                    $(this).dialog('close');
                };


                $('#dialog').dialog({
                    modal: true,
                    autoOpen: false,
                    closeOnEscape: true,
                    resizable: true,
                    close: function() {
                        Autoship.IsDialogOpen = false;
                    },
                    width: 400,
                    open: function() {
                    },

                    buttons: dialogbuttonOpts
                });
            }
            $('.datetime').datepicker($.ui.datepicker.regional[javascriptCulture]);
        } catch (e) {

        }

    };

    Autoship.prototype.PauseAutoShipPopup = function() {
        if (Autoship.IsDialogOpen) {
            return true;
        } else {
            $('#hfAutoShipResumeDate').val('');
            $('#dialog').dialog('open');
            Autoship.IsDialogOpen = true;
            return false;
        }
    };

    Autoship.prototype.PauseAutoShipExtend = function() {
        $('#hfAutoShipResumeDate').val($('#date0')[0].value);
        $('#ResumeAutoShipLink').click();
        return false;
    };

    return Autoship;

})(jQuery);;
/*exported ValidationHelper */
'use strict';

/**
 * Provides methods for adding validation classes and setting jQuery validation defaults (for show errors, highlight and un-highlight events)
 */

var ValidationHelper = (function($) {

    function ValidationHelper() {
    }

    ValidationHelper.prototype.AddValidationClasses = function() {
        $('span.field-validation-valid, span.field-validation-error').addClass('help-block');
        $('div.form-group').has('span.field-validation-error').addClass('has-error');
        $('div.validation-summary-errors').has('li:visible').addClass('alert alert-block alert-danger');
    };

    ValidationHelper.prototype.SetJQueryValidatorDefaults = function() {

        jQuery.validator.setDefaults({
            showErrors: function(errorMap, errorList) {
                this.defaultShowErrors();

                // destroy tool-tips on valid elements
                $('.' + this.settings.validClass)
                    .tooltip('destroy');

                // add/update tool-tips 
                for (var i = 0; i < errorList.length; i++) {
                    var error = errorList[i];

                    $('#' + error.element.id)
                        .tooltip({ trigger: 'focus' })
                        .attr('data-original-title', error.message);
                }
            },

            highlight: function(element, errorClass, validClass) {
                if (element.type === 'radio') {
                    this.findByName(element.name).addClass(errorClass).removeClass(validClass);
                } else {
                    $(element).addClass(errorClass).removeClass(validClass);
                    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
                }
            },

            unhighlight: function(element, errorClass, validClass) {
                if (element.type === 'radio') {
                    this.findByName(element.name).removeClass(errorClass).addClass(validClass);
                } else {
                    $(element).removeClass(errorClass).addClass(validClass);
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                }
            }

        });
    };

    return ValidationHelper;

})(jQuery);;
/*exported MenuHelper */
'use strict';

/**
 * Provides menu helper methods. The current available method ensures stacking of menus will not happen when 
 * in small screen mode e.g. if account is clicked and then a product category is clicked, account disappears 
 * as opposed to displaying both at the same time
 */

var MenuHelper = (function ($) {

    function MenuHelper() {
    }

    MenuHelper.prototype.PreventStacking = function() {

        $('.container button').click(function() {
            var $target = $($(this).data('target'));
            if (!$target.hasClass('in')) {
                $('.container .in').removeClass('in').height(0);
            }
        });

    };

    return MenuHelper;

})(jQuery);;
/*exported SearchUIHelper */
'use strict';

/**
 * Provides a method for initializing header's search elements
 */

var SearchUIHelper = (function($) {

    function SearchUIHelper() {
    }

    SearchUIHelper.prototype.InitHeaderSearchButton = function(searchButtonId, searchInpubId, searchRootRelId, ignoreSearchPhrase) {

        $('#' + searchButtonId).click(function(e) {
            var val = $.trim($('#' + searchInpubId).val());
            var rootRel = $('#' + searchRootRelId).val();

            if (val !== '' && val.toLowerCase() !== ignoreSearchPhrase.toLowerCase()) {
                //Can not turn off Ajax on chnagePage method, have to use window.location to get clean load.(WWang) 
                val = val.replace('+', '%2B').replace('/', '%2F').replace('\\', '%5C').replace('&', '%26');
                window.location.href = rootRel + 'search/' + encodeURIComponent(val) + '.aspx';
            }

            e.preventDefault();
            return false;
        });

    };

    return SearchUIHelper;

})(jQuery);;
/*exported PictureFillHelper */
'use strict';

/**
 * Provides helper methods for images generated by picturefill
 * 
 */
var PictureFillHelper = (function ($) {

    function PictureFillHelper() {
    }

   
    PictureFillHelper.prototype.InitPictureUrl = function () {

        $('picture').each(function () {


            if ($(this).children('[data-url]').length !== 0) {

                $(this).click(function () {
                  
                    var currSrc = $(this).find('img')[0].currentSrc;
                    var elementSelected = $('[srcset^="' + currSrc + '"]', this);
                    var windowPosition = elementSelected.attr('data-target');
                    if (windowPosition == '_blank') {
                        window.open(elementSelected.attr('data-url'));
                    }
                    else if (windowPosition == '_self') {
                        window.location.href = elementSelected.attr('data-url');
                    } else {
                        //do nothing
                    }
                });
            }
        });

    };

    return PictureFillHelper;

})(jQuery);



;
/*exported ProductBrowserHelper */
'use strict';

/**
 * Provides methods for initializing product browser accordion filter and search within elements.
 */

var ProductBrowserHelper = (function($) {

    function ProductBrowserHelper() {
    }

    ProductBrowserHelper.prototype.InitFilterAccordion = function() {

        $(window).bind('resize load', function() {
            if ($(this).width() < 767) {
                $('#filter-accordion').removeClass('in');
                $('#filter-accordion').addClass('out');
                $('#filter-accordion').addClass('collapse');

            } else {
                $('#filter-accordion').removeClass('out');
                $('#filter-accordion').removeClass('collapse');
                $('#filter-accordion').addClass('in');
            }
        });

    };

    ProductBrowserHelper.prototype.InitSearchWithinProductsButton = function(searchButtonId, searchInputId, searchTokenInputId, ignoreSearchPhrase) {

        $('#' + searchButtonId).click(function(e) {

            var val = $('#' + searchInputId).val().trim();
            var swToken = $('#' + searchTokenInputId).val();

            if (val !== '' && val.toLowerCase() !== ignoreSearchPhrase.toLowerCase()) {
                //Can not turn off Ajax on chnagePage method, have to use window.location to get clean load.(WWang) 
                val = val.replace('+', '%2B').replace('/', '%2F').replace('\\', '%5C').replace('&', '%26');
                window.location.href = swToken.replace('%7b0%7d', encodeURIComponent(val).replace('\'', '\\\''));
            }

            e.preventDefault();
            return false;

        });
    };

    return ProductBrowserHelper;

})(jQuery);;
/*exported CartHelper */
/*global BootstrapDialog:false */
'use strict';

/**
 * Provides general cart helper methods, e.g. toggling shipping cart display, adding to cart button and change cart event
 */

var CartHelper = (function($, bsd) {

    var localization;
    var cartAppId;
    var cartModalId;
    var cartSmallBadgeId;
    var cartLargeBadgeId;
    var addToCartButtonIdPrefix;
    var productAppId;


    function CartHelper(localizations, constants) {
        localization = localizations;
        cartAppId = constants.CartAppId;
        productAppId = constants.ProductAppId;
        cartModalId = constants.CartModalId;
        cartSmallBadgeId = constants.CartSmallBadgeId;
        cartLargeBadgeId = constants.CartLargeBadgeId;
        addToCartButtonIdPrefix = constants.AddToCartButtonIdPrefix;
    }

    CartHelper.prototype.ToggleShopingCart = function() {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope.$root && scope.$root.isCartEmpty && scope.$root.isCartEmpty()) {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' + localization.CartEmpty + '</h2>',
                buttons: [{ label: 'Close', action: function(dialogItself) { dialogItself.close(); } }],
                onshown: function(dialogRef) {
                    window.setTimeout(function() {
                        if (dialogRef && dialogRef.close) {
                            dialogRef.close();
                        }
                    }, 2000);
                },
            });
            return false;
        }

        scope.showCart();
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.AddToCart = function(itemId, productId, hasPersonalization, autoship, quantity, enableItemSelection) {
        var scope = angular.element('#' + cartAppId).scope();
        scope.addToCart({
            itemId: itemId,
            hasPersonalization: hasPersonalization,
            productId: productId,
            Quantity: quantity,
            Autoship: autoship,
            enableItemSelection: enableItemSelection
        }).then(
            function () {
                var pScope = angular.element('#' + productAppId).scope();

                if (pScope && pScope.productData) {
                    pScope.productData.selectedItem.triggerAddToCartEffect = !pScope.productData.selectedItem.triggerAddToCartEffect;
                    pScope.$apply();
                }

                var idSelector = '.' + addToCartButtonIdPrefix + productId;
                var btn = $(idSelector);
                btn.removeClass('btn-add-to-cart');
                btn.addClass('btn-success');
                btn.text(localization.Added);
                window.setTimeout(function () { btn.text(localization.AddAnother); }, 2000);


            },
            function (error) {
                if (error !== 'cancel') { //if we canceled - we do not show any error message
                    bsd.show({
                        title: '',
                        message: '<h2 class="text-center fade-text">' + localization.CannotAddToCart + '</h2>',
                        buttons: [
                            {
                                label: 'Close',
                                action: function(dialogItself) {
                                    dialogItself.close();
                                }
                            }
                        ]
                    });
                }
            });
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.OnCartChanged = function(cartData) {
        updateScoppingCartItemsCount(cartData);
        changeAddToCartButtonToAddedToCart(cartData);
    };

    function updateScoppingCartItemsCount(cartData) {
        var value = cartData.totalItemsCount;
        $('#' + cartSmallBadgeId).text(value);
        $('#' + cartLargeBadgeId).text(value);
    }

    function changeAddToCartButtonToAddedToCart(cartData) {
        
        var pScope = angular.element('#' + productAppId).scope();
        var pScopeUpdated = false;
        angular.forEach(cartData.items, function (v) {
            var productId = v.ProductId;
            var isInTheCart = v.isDeleted !== true;
            var idSelector = '.' + addToCartButtonIdPrefix + productId;
            var btn = $(idSelector);
            if (isInTheCart === true) {
                // if text is - added - do not it will change automatically to add another so do not do anything
                if (btn.text() !== localization.Added) {
                    btn.removeClass('btn-add-to-cart');
                    btn.addClass('btn-success');
                    btn.text(localization.AddAnother);
                }
            } else {
                btn.removeClass('btn-success');
                btn.addClass('btn-add-to-cart');
                btn.text(localization.AddToCart);
            }

            if (pScopeUpdated === false && isInTheCart === true && pScope && pScope.productData && pScope.productData.selectedItem && pScope.productData.id === productId) {
                pScope.productData.selectedItem.IsInCart = true;
                pScope.$apply();
                pScopeUpdated = true;
            }
        });

        if (pScopeUpdated === false && pScope && pScope.productData && pScope.productData.selectedItem) {
            pScope.productData.selectedItem.IsInCart = false;
            pScope.$apply();
        }
    }

    return CartHelper;

})(jQuery, BootstrapDialog);;
/*exported productCompare */
'use strict';

/**
 * Provides helper methods for product compare elements.
 */

var productCompare = (function ($) {

    function productCompare() {

    }

    var onclickRemove = function() {
        // Unchecked the compare check box
        var idProd = this.id.toString();
        var prodCheckbox = document.getElementById('checkbox-ProdId-' + idProd);
        if (prodCheckbox) {
            prodCheckbox.checked = false;
        }

        //clean up container
        var node = this.parentNode;
        while (node.hasChildNodes() >= 1) {
            node.removeChild(node.firstChild);
        }

        updateProductArray();
    };

    var addCompareProduct = function(Id, n) {

        //create the product image thumb
        var imgThumb = document.createElement('img');
        imgThumb.setAttribute('src', window.rootRel + 'ImageHandler.axd?ownerTable=Products&ownerId=' + Id + '&width=90&height=60&constraint=4&interpolate=7&async=false');
        imgThumb.className = 'compare-product-image';
        imgThumb.id = 'img-CompareProdId-' + Id;

        //create the remove button
        var imgRemove = document.createElement('img');
        imgRemove.setAttribute('src', window.rootRel + 'Content/images/btn-close.gif');
        imgRemove.setAttribute('alt', 'Remove product');
        imgRemove.className = 'compareclose';
        imgRemove.id = Id;
        imgRemove.onclick = onclickRemove;

        //append to container
        var compContainer = $('#compareContainer' + n);
        compContainer.html('<div class="imgDiv"><a class="compareContainer"></a></div>');
        var compContainerImg = compContainer.find('.compareContainer');
        compContainerImg.append(imgThumb);
        compContainer.append(imgRemove);

        return true;
    };

    var updateProductArray = function() {
        var ids = '';
        var compareContainer = $('#compare-product-container > .items-listDiv > .items-list > li > div > a');
        compareContainer.children().each(function() {
            var prod = $(this);
            var id = prod.attr('id');
            if (id.indexOf('img-CompareProdId-') >= 0) {
                var prodId = prod.attr('id').replace('img-CompareProdId-', '');
                ids += '|' + prodId;
            }
        });
        ids = ids.substring(1);

        var idTemp = ids.split('|');
        var compBut = $('#btnCompareProducts');
        var compLink = $('.compareLink');

        if (idTemp.length > 1) {

            compBut.attr('onclick', 'pCompare.CompareProdView("' + ids + '");return false;');
            compLink.each(function() {
                $(this).attr('onclick', 'pCompare.CompareProdView("' + ids + '");return false;');
            });
        } else {
            compBut.attr('onclick', 'window.BootstrapDialog.alert("' + window.res.ProductCompareError + '");return false;');
        }
        $.cookie('previousPage', window.location.href, { path: '/' });
        $.cookie('prodCompIDs', ids, { path: '/' });

        if (ids === '') {
            $('#compare-product-container').hide();
        } else {
            $('#compare-product-container').show();
        }

    };

    productCompare.prototype.ProductComparisonInit = function() {
        var idProdTemp = $.cookie('prodCompIDs');
        if (idProdTemp) {
            var idProd = idProdTemp.split('|');

            var k = 1;
            for (var i in idProd) {
                var n = parseInt(i) + 1;
                var Id = idProd[n - 1];
                if (Id > 0) {
                    addCompareProduct(Id, k);
                    $('#checkbox-ProdId-' + Id).attr('checked', true);
                    k++;
                }
            }
        }

        updateProductArray();
    };

    productCompare.prototype.check_checkBox = function(Id) {
        var obj = document.getElementById('checkbox-ProdId-' + Id);
        if (!obj.checked) {
            obj.checked = true;
        } else {
            obj.checked = false;
        }
        this.onclick_CheckboxCompare(obj);
    };

    productCompare.prototype.onclick_CheckboxCompare = function(obj) {
        var productLimit = 4;
        var idProd = obj.id.toString().replace('checkbox-ProdId-', '');
        if (obj.checked === true) {
            var success = false;
            for (var n = 1; n <= productLimit; n++) {
                var compContainer = $('#compareContainer' + n);
                if ($.trim(compContainer.html()) === '' || $.trim(compContainer.find('.compareContainer').html()) === '') {
                    success = addCompareProduct(idProd, n);
                    break;
                }
            }

            if (!success) {
                obj.checked = false;
                window.BootstrapDialog.alert(window.res.ProductCompareOverLimit.format(productLimit));
            }

        } else {
            $('#img-CompareProdId-' + idProd).parent().parent().parent().empty();
        }

        updateProductArray();
    };

    productCompare.prototype.CompareProdView = function(ids) {
        window.location.href = window.rootRel + 'ProductCompare/' + ids;
    };

    return productCompare;
})(jQuery);;
