/**************************************
 * Don't change anything from here on
 * if you don't know what you're doing.
 * Otherwise the earth might disappear
 * in a large black hole. We'll blame you!
 **************************************/

/*******************************************************************************
 * ON DOCUMENT READY
 */
jQuery(document).ready(function () {

    /**
     *  FIX ACCORDIONS AUTO COLLAPSE
     *  collapse only on load, then remove toggle class
     */
    $('.collapse-auto-toggle-xs').on('hidden.bs.collapse', function (e) {
        console.log(this);
        $(this).removeClass('collapse-auto-toggle-xs');
    })

    /**
     * CHECK BREAKPOINT ON SCREEN RESIZE
     */
    /**
     * CHECK BREAKPOINT ON SCREEN RESIZE
     */
    jQuery(window).resize(function () {
        setTimeout(function () {
            var c = jQuery(".collapse.collapse-auto-toggle-xs");
            if (jQuery.isXs()) {
                c.collapse('hide')
            } else {
                c.collapse('show')
            }
        }, 0)
    }.debounce(500))
        .resize();

    /**
     * BOOTSTRAP SELECT
     * @see http://silviomoreto.github.io/bootstrap-select/
     */
    if (!MSIE || MSIE > 8) {
        jQuery("select")
            .addClass('selectpicker show-menu-arrow')
            .hide();
        jQuery(".ms-options select")
            .attr('data-style', 'btn-secondary')
            .each(function () {
                var self = jQuery(this);
                if (parseInt(self.val()) > 0) {
                    self.addClass('select_option_selected');
                }
            });
        if (isMobileDevice()) {
            jQuery(".selectpicker")
                .selectpicker('mobile');
        }
    }

    /**
     * ANCHOR ANIMATION
     * slide to id by hash
     */
    jQuery(".move").bind("click", function(e) {
        var z = jQuery(this).get(0).hash,
            o = jQuery(z);

        if (o.length == 0)
            return true;

        e.preventDefault();
        jQuery("html, body").animate({
            scrollTop : o.offset().top - 80
        }, 500);
    });

    /**
     * "Back to Top" LINK
     * Only enable if the document has a long scroll bar.
     * Note the window height + offset.
     */
    var backToTopSelector = jQuery("#back-to-top");
    var backToTopVisibilityOffset = 100;
    if ((jQuery(window).height() + backToTopVisibilityOffset) < jQuery(document).height()) {
        backToTopSelector.removeClass('hidden').affix({
            offset: {top: backToTopVisibilityOffset}
        });
        backToTopSelector.click(function (e) {
            e.preventDefault();
            jQuery("html, body").animate({scrollTop: 0}, 'slow');
        });
    }

    /**
     * SWITCHES
     */
    jQuery(".switch-area").each(function (area) {
        var thisSwitchArea = jQuery(this),
            visibleSwitchItems = parseInt(thisSwitchArea.data('visible-items'));
        if (visibleSwitchItems < 1) {
            visibleSwitchItems = 1;
        }
        thisSwitchArea.addClass('switch-area-' + area + ' switch-items-show-' + visibleSwitchItems);
        if (!thisSwitchArea.hasClass('switch-disabled')) {
            var thisSwitchChildren = thisSwitchArea.find(".switch-items").children();
            if (thisSwitchChildren.length > visibleSwitchItems) {
                thisSwitchArea.addClass('switch-enabled');
                thisSwitchChildren.each(function (item) {
                    var thisSwitchItem = jQuery(this);
                    if (item >= visibleSwitchItems) {
                        thisSwitchItem.addClass('switch-default-hidden switch-item switch-item-' + item);
                    } else {
                        thisSwitchItem.addClass('switch-default-visible switch-item switch-item-' + item);
                    }
                });
                thisSwitchChildren.siblings(".switch-default-hidden").wrapAll('<div class="switch-toggle" style="display:none;"></div>');
                thisSwitchArea.find(".switch-button").click(function () {
                    var self = jQuery(this);
                    thisSwitchArea.toggleClass('switch-bounce');
                    thisSwitchArea.find(".switch-toggle").slideToggle('fast', function () {
                        thisSwitchArea.toggleClass('switch-bounce-finish');
                        self.blur();
                    });
                });
            } else {
                thisSwitchArea.addClass('switch-disabled');
            }
        } else {
            thisSwitchArea.addClass('switch-disabled-by-class');
        }
    });

    /**
     * LOGIN PASSWORD TOGGLE
     */
    var accountSwitch = function (type) {
        type = type || 'register';
        jQuery('.visible-switch-account').show();
        switch (type) {
            case 'register':
                jQuery('.visible-guest-account').hide();
                break;
            default:
                jQuery('.visible-register-account').hide();
        }
    };
    jQuery('#guest-account')
        .change(function () {
            accountSwitch(jQuery(this).val());
        })
        .change();

    /**
     * FORM REQUIRED MARK
     */
    jQuery("label:contains('\*')").html(function (_, html) {
        return html.replace(/(\*)/g, '<span class="required">$1</span>');
    });

    /**
     * CHECKOUT
     */
    var listGroupItems = jQuery("#checkout .list-group-item");
    if (listGroupItems.length) {
        var setListGroupActive = function (t) {
            listGroupItems.removeClass('active');
            t.closest(".list-group-item").addClass('active');
        };

        // highlight by preselected
        setListGroupActive(listGroupItems.find(".selected:last"));

        // highlight by click
        listGroupItems.addClass('cursor-pointer').click(function () {
            var radio = jQuery(this).find("[name='selected_shipping'], [name='selected_payment']");
            
            radio.prop('checked', true);
            
            listGroupItems
                .not(this)
                .find(".collapse.in")
                .collapse('hide');

            setListGroupActive(radio);
        });

        // highlight by change
        listGroupItems.find("[name='selected_shipping'], [name='selected_payment']").change(function () {
            setListGroupActive(jQuery(this));
        });
    }

    /**
     * TOOLTIPS
     */
    var isTouchDevice = true === ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
    if (!isTouchDevice) {
        jQuery("#header .header-info [title]").tooltip({
            placement: 'bottom'
        });
        jQuery('[data-toggle="tooltip"]').tooltip({
            container: 'body'
        });

        jQuery('[data-toggle="popover"]').popover({
            trigger: "hover",
            container: 'body',
            html: true
        });
    }

    /**
     * VISUAL FORM VALIDATION
     *
     * Visual validation for required fields
     * @author 8works, Jens Albert
     * @version 2.0
     */
    setTimeout(function () {
        jQuery(".form-group label:contains('*'), .form-group .label:contains('*'), .form-group .form-required")
            .each(function () {
                var label = jQuery(this),
                    formGroup = label.closest(".form-group"),
                    input = formGroup.find("input, textarea");

                if (!input.parent(".bs-searchbox").length) {
                    label.addClass('control-label');
                    input.addClass('form-control');

                    input.on('blur', function () {
                        var self = jQuery(this),
                            selfFormGroup = self.closest(".form-group"),
                            selfFormControl = selfFormGroup.find(".form-control");

                        if (!self.val().length) {
                            selfFormGroup.removeClass('has-success').addClass('has-error');
                            selfFormControl.addClass('animated shake');
                        } else {
                            selfFormGroup.removeClass('has-error').addClass('has-success');
                            selfFormControl.removeClass('animated shake');
                        }
                    });
                }
            });
    }, 10);

    /**
     * IMAGE RESPONSIVE HELPER
     */
    jQuery("img.img-responsive").removeAttr('width').removeAttr('height');

    /**
     * VERTICAL HELPER LINK HELPER
     * Removes link html whitespaces because of wrong underline by onmouseover
     */
    jQuery("a.vertical-helper").each(function () {
        jQuery(this).html(jQuery.trim(jQuery(this).html()));
    });

    /**
     * IE 9- placeholder fix
     */
    if (MSIE && MSIE <= 9) {
        jQuery("[placeholder]").each(function () {
            var form = jQuery(this),
                placeholder = jQuery.trim(form.attr('placeholder')),
                value = jQuery.trim(form.attr('value'));
            if (value == '' && placeholder != '') {
                form.attr('value', placeholder);
                form.focus(function () {
                    var form = jQuery(this);
                    if (jQuery.trim(form.attr('value')) == placeholder) {
                        form.attr('value', '');
                    }
                });
            }
        });
    }

    /**
     * CAROUSEL PRODUCT SLIDER
     */
    var productSliderElement = jQuery('.productCarousel');
    if (productSliderElement.length != 0) {
        productSliderElement.owlCarousel({
            itemsCustom: [
                [0, 1],
                [480, 2],
                [768, 3],
                [992, 4]
            ],
            navigation: true,
            lazyLoad: true,
            slideSpeed: 800,
            paginationSpeed: 800,
            pagination: false,
            scrollPerPage: true,
            addClassActive: true,
            navigationText: ['', ''],
            afterUpdate: function (t) {
                var target = jQuery(t),
                    id = target.attr('id');

                if (typeof id != 'undefined' && id != '') {
                    equalizeListingHeights(' #' + id);
                }
            }
        });
    }

    /**
     * LIGHT GALLERY
     */
    var lightGalleryElement = jQuery(".lightgallery");
    if (lightGalleryElement.length != 0) {
        lightGalleryElement.lightGallery({
            selector: 'a',
            download: false,
            mode: 'lg-lollipop',
            hideBarsDelay: 99999999,
            mouseWheel: false
        });
    }

    /**
     * Prevent dropdown toggle on self click
     */
    jQuery(".dropdown-menu").click(function (e) {
        e.stopPropagation();
    });
});

/**
 * EQUALIZE HEIGHTS
 */
(function () {
    equalizeListingHeights();

    //checkout progress bar
    if ((!MSIE || MSIE > 8) && typeof window.opera == 'undefined') {
        jQuery(function () {
            jQuery("#checkout .progress-bar").matchHeight(false);
        });
    }
})();
