var PREVIEW = true;

@baseTemplate


jQuery(function ($) {
    'use strict';
    var panels = $('@_accordion.selector @_accordion.content.selector').parent();
    panels.on('show.bs.collapse', function () {
        var actives = panels.filter('.in');

        $(this).prev().children('a').addClass('active');
        actives.prev().children('a').removeClass('active');

        if (actives && actives.length) {
            var hasData = actives.data('bs.collapse');
            if (!hasData || !hasData.transitioning) {
                actives.collapse('hide');
                if (!hasData) actives.data('bs.collapse', null);
            }
        }
    });
    panels.on('hidden.bs.collapse', function () {
        $(this).prev().children('a').removeClass('active');
    });
});


if (PREVIEW) {
    jQuery(function ($) {
        var scripts = $('head script[src*="bootstrap"]'),
        //showMsg = null;//$.cookie('showbootstrapduplicatemessage');
            matches = document.cookie.match(new RegExp(
                "(?:^|; )" + 'showbootstrapduplicatemessage'.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
            )),
            showMsg = matches ? decodeURIComponent(matches[1]) : undefined,
            count = 0;

        scripts.each(function(key, script) {
            var src = $(this).attr('src');
            if (src.search(/templates.*js\/jui/) != -1)
                return true;
            count++;
        });

        if (count > 1 && !showMsg) {
            $('body').prepend('<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert">&times;</button><span>' +
                '<strong>Warning!</strong> <br /> You have several conflicting bootstrap.js files loaded on the site. Various unexpected issues in site functionality may arise.<br />'
                + 'Please have a look to the following article <a href="http://answers.themler.io/articles/82654/bootstrap-conflicts" target="_blank">Bootstrap conflicts</a> on how to disable all additional bootstrap.js files.</span></div>');
            document.cookie = "showbootstrapduplicatemessage=true; path=/";
        }
    });
}

(function ($) {
    window.themeVirtuemart = {};

    window.themeVirtuemart.addToCart = function (product) {

        var buyButtons = $('.add_to_cart_button');
        if (product) {
            buyButtons = product.find('.add_to_cart_button');
        }
        buyButtons.filter(function() {
            return '#' === $(this).attr('href');
        }).click(function (e) {
                e.preventDefault();
                var link = $(this),
                    formClone = $(this).parent('.product').clone(),
                    vmsiteurl = link.attr('data-vmsiteurl'),
                    vmlang = link.attr('data-vmlang'),
                    success = link.attr('data-vmsuccessmsg'),
                    carts = $('div[data-cart-position]'),
                    cartCustomFields = $('.product-field[data-cart-attribute="1"] *[name]'),
                    cloneCartCustomFields = cartCustomFields.clone(),
                    cart, position, style, id, url, datas;

                if (formClone.length) {
                    cartCustomFields.each(function(i) {
                        var element = this;
                        cloneCartCustomFields.eq(i).val($(element).val());
                    });
                    formClone.append(cloneCartCustomFields);
                    datas = formClone.serialize();
                    url = vmsiteurl + 'index.php?option=com_virtuemart&nosef=1&view=cart&task=addJS&format=json' + vmlang;
                    $.getJSON(url, datas, function(datas, textStatus) {
                        link.html(success);
                        if (carts.length > 0) {
                            carts.each(function () {
                                position = $(this).attr('data-cart-position') || '';
                                style = $(this).attr('data-style') || '';
                                id = $(this).attr('data-id') || '';
                                currentTemplate = $(this).attr('data-template') || '';
                                cart = $(this);
                                if ('' !== position) {
                                    url = vmsiteurl + 'index.php';
                                    (function(url, style, cart ) {
                                        $.ajax({
                                            url: url,
                                            type : 'get',
                                            data: {
                                                tmpl : 'modrender',
                                                template : currentTemplate,
                                                modulename : 'mod_virtuemart_cart',
                                                modulestyle : style,
                                                moduleid : id,
                                                is_preview : PREVIEW ? 'on' : 'off'
                                            },
                                            dataType: 'html',
                                            success: function (data) {
                                                if (data)
                                                    cart.replaceWith(data);
                                            },
                                            error: function (xhr, status) {}
                                        });
                                    })(url, style, cart);
                                }
                            });
                        }
                    });
                }
                return false;
            });
    }

    window.themeVirtuemart.setProductTypeFacade = function(event) {
        window.themeVirtuemart.setProductType(event.data.productItem);
    }

    window.themeVirtuemart.setProductType = function(product) {
        'use strict';
        var prices = product.find('.product-prices'),
            form = product.find('form.product'),
            virtuemart_product_id = product.find('input[name="virtuemart_product_id[]"]');

        if (!prices.length) {
            return false;
        }

        var formClone = form.clone(),
            cartCustomFields = $('.product-field[data-cart-attribute="1"] *[name]', product),
            cloneCartCustomFields = cartCustomFields.clone();

        cartCustomFields.each(function(i) {
            var element = this;
            cloneCartCustomFields.eq(i).val($(element).val());
        });
        formClone.append(cloneCartCustomFields);
        var datas = formClone.serialize();
        datas = datas.replace("&view=cart", "");

        prices.fadeTo("fast", 0.75);
        $.ajax({
            type: "POST",
            cache: false,
            dataType: "json",
            url: window.vmSiteurl + "index.php?&option=com_virtuemart&view=productdetails&task=recalculate&format=json&nosef=1" +
                window.vmLang + (virtuemart_product_id.length ? '&virtuemart_product_id=' + virtuemart_product_id.val() : ''),
            data: datas
        }).done(
            function (data, textStatus) {
                prices.fadeTo("fast", 1);
                // refresh price
                for (var key in data) {
                    var value = data[key];
                    if (key !== 'messages' && value !== 0) {
                        prices.find("span."+key).show().html(value);
                    }
                }
            }
        );

        return false; // prevent reload
    };

    window.themeVirtuemart.product = function(items) {
        'use strict';
        items.each(function() {
            var productItem     = $(this),
                quantityForm    = productItem.find('input[name="quantity[]"]'),
                plus            = productItem.find('.quantity-plus'),
                minus           = productItem.find('.quantity-minus'),
                quantityInput   = productItem.find('.quantity-input'),
                form            = productItem.find('form.product');

            productItem.children().eq(0).attr('data-updating-content', true);

            var Ste = parseInt(quantityForm.val());
            if(isNaN(Ste)){
                Ste = 1;
            }

            plus.click(function(event) {
                var Qtt = parseInt(quantityInput.val());
                if (!isNaN(Qtt)) {
                    quantityInput.val(Qtt + Ste);
                    quantityForm.val(Qtt + Ste);
                    window.themeVirtuemart.setProductType(productItem);
                }
                event.stopImmediatePropagation();

            });

            minus.click(function(event) {
                var Qtt = parseInt(quantityInput.val());
                if (!isNaN(Qtt) && Qtt>Ste) {
                    quantityInput.val(Qtt - Ste);
                    quantityForm.val(Qtt - Ste);
                } else {
                    quantityInput.val(Ste);
                    quantityForm.val(Ste);
                }
                window.themeVirtuemart.setProductType(productItem);
                event.stopImmediatePropagation();
            });

            quantityInput.bind('click blur submit', function (e) {
                var me = $(this);
                e.preventDefault();
                if(me.is('input')) {
                    var remainder = this.value % me.attr("step"),
                        quantity = this.value;

                    if (remainder != 0) {
                        if(!isNaN(me.attr("step"))) alert(me.attr("data-errStr").replace("%s", me.attr("step")));
                        if(quantity != remainder && quantity>remainder){
                            this.value = quantity - remainder;
                        } else {
                            this.value = me.attr("step");
                        }
                        quantityForm.val(this.value);
                        return false;
                    }
                    return true;
                }
                return true;
            });

            quantityInput.keyup(function(event) {
                quantityForm.val(parseInt(quantityInput.val()));
                window.themeVirtuemart.setProductType(productItem);
                event.stopImmediatePropagation();
            });

            form.each(function() {
                var form = $(this),
                    select = form.find('select:not(.no-vm-bind)'),
                    selectOutForm = $('.product-field[data-cart-attribute="1"] select:not(.no-vm-bind)', productItem),
                    radio = form.find('input:radio:not(.no-vm-bind)'),
                    radioOutForm = $('.product-field[data-cart-attribute="1"] input:radio:not(.no-vm-bind)', productItem),
                    virtuemart_product_id = form.find('input[name="virtuemart_product_id[]"]').val();

                $(select).off('change', window.themeVirtuemart.setProductTypeFacade);
                $(select).on('change', {productItem : productItem}, window.themeVirtuemart.setProductTypeFacade);
                $(selectOutForm).off('change', window.themeVirtuemart.setProductTypeFacade);
                $(selectOutForm).on('change', {productItem : productItem}, window.themeVirtuemart.setProductTypeFacade);

                $(radio).off('change', window.themeVirtuemart.setProductTypeFacade);
                $(radio).on('change', {productItem : productItem}, window.themeVirtuemart.setProductTypeFacade);
                $(radioOutForm).off('change', window.themeVirtuemart.setProductTypeFacade);
                $(radioOutForm).on('change', {productItem : productItem}, window.themeVirtuemart.setProductTypeFacade);
            });

        });
    }
})(jQuery);

jQuery(function($) {
    'use strict';
    window.themeVirtuemart.addToCart();
    var items = $('.vm-product-item');
    if (items.length) {
        window.themeVirtuemart.product(items);
        if (1 === items.length) {
            setInterval(function() {
                var item = items;
                var attr = item.children().eq(0).attr('data-updating-content');
                if (typeof attr === 'undefined') {
                    window.themeVirtuemart.addToCart(item);
                    window.themeVirtuemart.product(item);
                    $(window).resize();
                }
            }, 350);
        }
    }
});

jQuery(function ($) {
    'use strict';
    if (PREVIEW) {
        var search = $('form[name*="search"]');
        search.submit(function() {
            return false;
        });

        $('#form-login').submit(function() {
            return false;
        });
        var logout = $('#form-login > input[type*="submit"]');
        logout.attr('link-disable', true);

        $('#checkoutForm').submit(function() {
            return false;
        });
        var checkout = $('#checkoutFormSubmit');
        checkout.attr('link-disable', true);

        var removeLinks = $('.removelink').filter(function () {
            if((this.getAttribute('name') + '').indexOf('delete.') === 0) return true;
            else return false;
        });
        removeLinks.attr('link-disable', true);

        var versions = $('.edit.item-page a[title=\'Versions\']');
        versions.attr('link-disable', true);
    }
});

jQuery(function ($) {
    'use strict';
    var topHref = window.top.location.href,
        frames = window.top.frames,
        siteHref = '',
        updateHref = function (uri, key, value) {
            var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
            var separator = uri.indexOf('?') !== -1 ? "&" : "?";
            if (uri.match(re))
                return uri.replace(re, '$1' + key + "=" + value + '$2');
            return uri + separator + key + "=" + value;
        };

    if (frames && frames.length && topHref.indexOf('editor=1') !== -1 && topHref.indexOf('_templates') !== -1) {
        for(var i = 0; i < frames.length; i++) {
            var frameLocation = frames[i].location;
            try {
                if (frameLocation.host && frameLocation.href.indexOf('editor=1') == -1 && frameLocation.href.indexOf('_templates') == -1) {
                    siteHref = frames[i].location.href;
                    break;
                }
            } catch(e) {}
        }
        if (siteHref && siteHref.indexOf('is_preview') == -1) {
            siteHref = updateHref(siteHref, 'is_preview', 'on');
            var themeParts = topHref.match(/theme=([^&]+)/);
            if (themeParts)
                siteHref = updateHref(siteHref, 'template', themeParts[1])
            window.location.replace(siteHref);
        }
    }
});

// Fixing conflict Mootools.fx slide with Bootstap Carousel
if ('undefined' !== typeof jQuery && 'undefined' !== typeof MooTools) {
    Element.implement({
        slide: function (how, mode) {
            return this;
        },
        hide: function () {
            return this;
        },
        show: function () {
            return this;
        }
    });
}
