/*global self, bookmarkPage, $ */

// define namespace
var Avr = {};

Avr.searchBlur = function () {
    // Loose the focus on the search field when the mouse is over the language select (from header)
    $('#header .cssdropdown').first().mouseover(function () {
        $('#qbox').blur();
    });
};

/**
 * @class Avr.tabs
 * Base class for tabs.
 * @constructor
 */
Avr.tabs = function (container) {
    this.container = container;
    this.init();
};

Avr.tabs.prototype = {
/**
 * @CONFIG
 */
    /**
     * The HTML element that contains all the tabs.
     * @type {JQuery Element} 
     */
    container: null,

/**
 * @PUBLIC
 */    
    /**
     * The current tab element.
     * @type {JQuery Element} 
     */
    currentTab: null,
    
    /**
     * Flag that allows the URL hash change when a user clicks on a tab.
     * @type {Boolean} 
     */
    changeHash: null,
    
    /**
     * JQuery selector that will retrieve all the tabs.
     * @type {String} 
     */
    tabSelector: '.tabs-header a',
    
    /**
     * JQuery selector that will retrieve all the content containers.
     * @type {String} 
     */
    tabContentSelector: '.tabs-content',
        
    /**
     * Add click event for all the tabs. Also show initial tab (based on href hash)
     * @return {void} 
     */
    init: function () {
        var that = this, tabs = $(this.tabSelector, this.container), startTabId, startTab;
        
        $('#content').attr('style', 'zoom: 1');
        
        // bind a click event
        if (tabs.length > 1) {
            tabs.bind('click', function (e) {
                return that.onClick.call(that, this, e);
            });
        } else {
            tabs.one('click', function (e) {
                return that.onClick.call(that, this, e);
            });
        }
        
        //hide all tabs content
        tabs.each(function (idx, elem) {
            that.hideTab(elem);
        }); 

        // select the initial tab
        startTabId = document.location.hash.substring(1);
        if (startTabId.length) {
            startTab = $(this.tabSelector + "[href=#" + startTabId + "]", this.container);
            if (startTab.length) {
                startTab.trigger('click');
            } else {
                tabs.eq(0).trigger('click');
            }
        } else {
            tabs.eq(0).trigger('click');
        }
        
        this.changeHash = true;
    },
    
    /**
     * Called when a user clicks a tab.
     * @return {boolean} 
     */
    onClick: function (node, e) {
        if (this.currentTab) {
            this.hideTab(this.currentTab);
        }
    
        this.currentTab = $(node, this.container);
        this.showTab(this.currentTab);
        
        $('#content').attr('style', 'zoom:1');
        return false;
    },
    
    /**
     * Hide a specific tab.
     * @param {JQuery Element}
     * @return {void} 
     */
    hideTab: function (tab) {
        $(this.tabSelector + '.active', this.container).removeClass('active');
        var id = '#c' + $(tab).attr("href").substring(1);
        $(id).hide();
    },
    
    /**
     * Show a specific tab.
     * @param {JQuery Element}
     * @return {void} 
     */
    showTab: function (tab) {
        var id = $(tab).attr("href").substring(1), newUrl;
        $(tab).addClass('active');
        
        if (this.changeHash) {
            newUrl = window.location.href.replace(window.location.hash, '') + "#" +  id;
            document.location.replace(newUrl);
        }
        
        $('#c' + id).show();
    }
};

/**
 * JQuery selector that will retrieve all the tab groups.
 * @type {String}
 * @static
 */
Avr.tabs.containerCls = '.tabs';

/**
 * Find all the tab groups in the page.
 * @return {void}
 * @static
 */
Avr.tabs.initTabsOnPage = function () {
    $(Avr.tabs.containerCls).each(function (ids, elem) {
        var tabs = new Avr.tabs(elem);
    });
};

/**
 * Init the header search box 
 * @return {void}
 * @static
 */
Avr.searchboxInit = function () {
    var qbox = $("#qbox");
    if (!qbox.length) {
        return false;
    }
    
    qbox.bind('click', function () {
        qbox.val('');
    });
    qbox.autocomplete("/search/frontendSc/autocomplete", 
    {
        "minChars": 1, 
        "width": '173px', 
        "selectFirst": false, 
        "scroll": false
    }).result(function () {
        qbox.get(0).form.submit(); 
    });
};

/**
 * Actions for the footer icons (Recomend and Print)
 * @return {void}
 * @static
 */
Avr.footerActions = function () {
    $("#footer-icon-bookmark").click(function () {
        bookmarkPage(document.title, location.href);
        return false;
    });
                
    $("#footer-icon-drucken").click(function () {
        self.print();
        return false;
    });
};

/**
 * Product chooser init if one is found on the page
 * @return {void}
 * @static
 */
Avr.productChooserInit = function () {
    var cnt = $('.ateaserbox-trybuy-box'), prefix = '#';
    if (!cnt.length) {
        return false;
    } else if (cnt.length > 1) {
        prefix = '.';
    }

    cnt.each(function (idx) {
        var selectorsCnt, selectors, _that = this;

        // show the selector container
        selectorsCnt = $(prefix + "selectors", this).show();
        
        // set the initial price
        $('.price', selectorsCnt).html($('.entry:visible .price', this).html());
        
        selectors = $("select", selectorsCnt);
        selectors.bind('change', function () {
            var idx = '', i, visibleContainer;
            for (i = 0; i < selectors.length; i += 1) {
                if (idx.length) {
                    idx += "-";
                }
                
                idx += selectors.eq(i).attr("name") + selectors.eq(i).val();
            }
            
            $(".entry", _that).hide();
            visibleContainer = $(prefix + idx, _that).show();
            $('.price', selectorsCnt).html($('.price', visibleContainer).html());
            
        });
    });
};

Avr.phoneSwitchLang = function (select, config) {
    select = select.first().children().first();
    if (select && config.lang && config.code) {
        // Set the language text
        select.html(config.lang);
        
        // Get the widget langauage code (en, de). We will use it to hide the visible phone number
        var currentLang = select.attr('class').replace('flag-', '');
        
        // Set the new classes to the select
        select.removeClass();
        select.addClass('flag-' + config.code);
        
        // Switch the phone numbers
        $('.phone-' + currentLang).hide();
        $('.phone-' + config.code).show();
    }
};

Avr.phoneInit = function () {
    var phoneSelect = $('.teaserbox-phone .select-fake'), phoneList, initialCode, initialLang;
    
    if (!phoneSelect.length) {
        return;
    }

    phoneList = phoneSelect.next();
    
    // Based on GeoIP, set the default country
    if ($.cookie) {
        initialCode = $.cookie('country');
    }

    if (!initialCode) {
        initialCode = 'de';
    }
    initialCode = initialCode.toLowerCase();
    initialLang = $('.flag-' + initialCode, phoneList).html();

    Avr.phoneSwitchLang(phoneSelect, {
        lang: initialLang,
        code: initialCode
    });
   
    
    phoneSelect.mouseover(function (e) {
        phoneList.attr('style', 'display: inherit');
    });
    
    phoneList.click(function (e) {
        var target = $(e.target);
        if (!target.attr('class').match(/flag-/)) {
            return true;
        }
        
        Avr.phoneSwitchLang(phoneSelect, {
            lang: target.html(),
            code: target.attr('class').replace('flag-', '')
        });
        
        phoneList.hide();
        
        e.preventDefault();
        e.stopPropagation();
    });

    phoneList.mouseleave(function (e) {
        phoneList.hide();
    });
};

Avr.priceSelectorInit = function (appErrors) {
    var cnt = $('.priceselector-box')
    if (!cnt.length) {
        return;
    }
    cnt.each(function (){
        function formSubmit () {
            if (contactBtn.is(':visible')) {
                return false;
            }
        }

        function showError(errorText) {
            //hide the price
            priceCnt.text('');
            yearlyPriceCnt.text('');
            swapButtons(contactBtn, buyBtn);
            vat.css('visibility', 'hidden');
        }
        
        function initButtons() {
            var widths, changeDisplay = false;
            if (contactBtn.css('display') === 'none') {
                contactBtn.css({
                    'position': 'absolute',
                    'visibility': 'hidden',
                    'display': 'block'
                });

                changeDisplay = true;
            }

            widths = {
                tryBtn: tryBtn.width(),
                buyBtn: buyBtn.width(),
                contactBtn: contactBtn.width()
            }
            
            var maxWidth = Math.max(widths.tryBtn, widths.buyBtn, widths.contactBtn);
            maxWidth = Math.min(maxWidth, selectorsCnt.width() / 2);
            
            contactBtn.css({
                'position': '',
                'visibility': ''
            });
            
            if (changeDisplay) {
                contactBtn.css('display', 'none');
            }
            
            if (cnt.hasClass('no-resize') === true) {
                return;
            }

            $.each([tryBtn, contactBtn, buyBtn], function (idx, bElem)  {
                if (bElem.width() > maxWidth) {
                    return;
                }
                
                var padding = 0;
                bElem.find(':first-child').each(function (idx, elem) {
                    var $elem = $(elem), ePadding = $elem.padding();
                    padding += ePadding.left + ePadding.right;
                    $elem.width(maxWidth - padding);
                });
            });
        }

        function swapButtons(showBtn, hideBtn) {
            if (showBtn) {
                showBtn.show();
            }

            if (hideBtn) {
                hideBtn.hide();
            }
        }

        function getNewPrice() {
            if (ajaxCall && ajaxCall.abort) {
                ajaxCall.abort();
            }
            
            var users_no, params;
            
            if (!data || !data.url || !data.product_id) {
                return false;
            }
            
            if (!runtime || !users) {
                return false;
            }
            
            users_no = users.val();
            if (isNaN(users_no)) {
                users.addClass('xinput-error');
                timeout = setTimeout(function () { 
                    showError(errors.nan); 
                }, 200);
                return false;
            } else if (users_no > parseInt(data.max, 10) || users_no < parseInt(data.min, 10)) {
                users.addClass('xinput-error');
                timeout = setTimeout(function () { 
                    showError(errors.minMax); 
                }, 200);
                return false;
            } else {
                users.removeClass('xinput-error');
                errorContainer.css('visibility', 'hidden');
                swapButtons(buyBtn, contactBtn);
                vat.css('visibility', '');
                clearTimeout(timeout);
            }
            
            params = {
                users: users_no,
                runtime: runtime.val(),
                url: data.url,
                product_id: data.product_id
            };
            
            ajaxCall = Avr.priceSelectorUpdate(params, priceCnt, yearlyPriceCnt, errorContainer);
            return true;
        }

        var cnt = $(this), selectorsCnt = $(".selectors", cnt), runtime, users,
            data, priceCnt, yearlyPriceCnt, timeout, 
            errorContainer = $('.error-text', cnt), ajaxCall, vat = $('.vat', cnt), 
            form = $('form', cnt).submit(formSubmit), errors,
            buyBtn = $('.buy', cnt), contactBtn = $('.contact', cnt), tryBtn = $('.try', cnt);

        errors = $.parseJSON(appErrors);
        initButtons();

        // show the selector container
        selectorsCnt.show();
        $('.refresh', selectorsCnt).hide();

        runtime = $('.runtime', selectorsCnt).change(getNewPrice);
        users = $('.users.atext', selectorsCnt);
        if (!users.length) {
            users = $('.users', selectorsCnt).change(getNewPrice);
        } else {
            users.keyup(getNewPrice);
        }

        data = $.parseJSON($('.data', cnt).val());
        priceCnt = $('.fixed-price', selectorsCnt);
        yearlyPriceCnt = $('.yearly-price', selectorsCnt);
   
    });
};

Avr.priceSelectorUpdate = function (obj, container, savePriceContainer, errorContainer) {
    var url = obj.url;
    if (!url) {
        return false;
    }
    
    delete obj.url;
    
    return $.ajax({
        url: url,
        cache: false,
        type: "POST",
        dataType: 'json',
        data: (obj),
        success: function (data) {
            if (container) {
                container.text(data.price);
            }
            
            if (savePriceContainer) {
                savePriceContainer.text(data.yearly_price);
            }
        }
    });
};

Avr.stagingArea = {
    callbackQueue: {},
    stagingTimeout: null,
    stagingDelay: null,
    stagingStop: null,
    init: function (delay) {
        var clickInProgress = false, controllers;

        if (!delay) {
            delay = 10;
        }
        Avr.stagingArea.stagingDelay = delay * 1000;
        controllers = $(".staging-nav-new, .staging-nav-bg");
        if (!controllers.length) {
            return;
        }

        controllers.show();
        Avr.stagingArea.stagingTimeout = requestTimeout(function () { 
            Avr.stagingArea.nextSlide(); 
        }, Avr.stagingArea.stagingDelay);
       
        $('.staging-nav-new .title').each(function (idx, elem) {
            $(elem).click(function (e) {
                if (clickInProgress) {
                    return false;
                }
                
                clickInProgress = true;
                requestTimeout(function () {
                    clickInProgress = false;
                }, 500);

                var activeSlide, currentIdx, newIdx;
                if (!Avr.stagingArea.stagingStop) {
                    activeSlide = $(".slide:visible");
                    if (activeSlide.length !== 0) {
                        currentIdx = activeSlide.attr('id').replace('s', '');
                    } else {
                        currentIdx = 1;
                    }

                    newIdx = idx + 1;
                    if (newIdx > currentIdx) {
                        Avr.stagingArea.nextSlide(newIdx);
                    } else if (newIdx < currentIdx) {
                        Avr.stagingArea.prevSlide(newIdx);
                    }
                }

                return false;
            });
        });
    }, 
    
    nextSlide: function (idx, autoload) {
        var activeSlide, next, img, maxIdx, imgNode, activeButton;

        if (Avr.stagingArea.stagingStop && !autoload) {
            return false;
        }

        Avr.stagingArea.stagingStop = 1;
    
        if (Avr.stagingArea.stagingTimeout) {
            clearRequestTimeout(Avr.stagingArea.stagingTimeout);
        }

        activeSlide = $("#staging .slide:visible");
        if (!activeSlide.length) {
            return false;
        }

        if (!idx) {
            maxIdx = $('#staging .slide').length;
            
            idx = parseInt(activeSlide.attr('id').replace('s', ''), 10);
            idx += 1;
            if (idx > maxIdx) {
                idx = 1;
            }
        }

        next = $('#s' + idx);
        img = next.find("img[asrc]");
        if (!img.length || activeSlide.get(0) === next.get(0)) {
            return false;
        }

        if (img.attr('src') === '' || /dummy.gif/.test(img.attr('src'))) {
            // load the slide image
            img.attr('src', img.attr('asrc'));
            
            // test to see if the image was loaded from cache
            imgNode = img.get(0);
            
            if (imgNode.readyState !== 'complete' && imgNode.readyState !== 4) {
                img.load(function () {
                    Avr.stagingArea.nextSlide(idx, true);
                });    
                
                return;
            }
        }
        //$(".slide:visible").fadeOut('fast').next().fadeIn('slow',function(){stagingStop = 0;}).end().appendTo('#staging');
        
        Avr.stagingArea.runCallbacks(idx, 'before');
        next.show("slide", {direction: "right", easing: "easeOutExpo"}, 1200, function () {
            Avr.stagingArea.stagingStop = 0;
            Avr.stagingArea.runCallbacks(idx, 'after');
        }).end().appendTo('#staging');
        
        activeSlide.hide("slide", { direction: "left", easing: "easeOutExpo" }, 1200);
        
        activeButton = $('.staging-nav-new .active');
        activeButton.removeClass('active');
        $('#b' + next.attr('id')).addClass('active');
        
        Avr.stagingArea.stagingTimeout = requestTimeout(function () { 
            Avr.stagingArea.nextSlide(); 
        }, Avr.stagingArea.stagingDelay);
    },
    
    prevSlide: function (idx, autoload) {
        var activeSlide, maxIdx, prev, img, imgNode, activeButton;
        if (Avr.stagingArea.stagingStop && !autoload) {
            return false;
        }

        Avr.stagingArea.stagingStop = 1;
        
        if (Avr.stagingArea.stagingTimeout) {
            clearRequestTimeout(Avr.stagingArea.stagingTimeout);
        }
        
        activeSlide = $(".slide:visible");
        if (!activeSlide.length) {
            return false;
        }

        if (!idx) {
            maxIdx = $('#staging .slide').length;
            
            idx = parseInt(activeSlide.attr('id').replace('s', ''), 10);
            idx -= 1;
            if (idx === 0) {
                idx = maxIdx;
            }
        }
        
        prev = $('#s' + idx);
        img = prev.find("img[asrc]");
        if (!img.length || activeSlide.get(0) === prev.get(0)) {
            return false;
        }

        if (img.attr('src') === '') {
            // load the slide image
            img.attr('src', img.attr('asrc'));
            
            // test to see if the image was loaded from cache
            imgNode = img.get(0);
            
            if (imgNode.readyState !== 'complete' && imgNode.readyState !== 4) {
                img.load(function () {
                    Avr.stagingArea.prevSlide(idx, true);
                });    
                
                return;
            }
        }
        
        //$(".slide:visible").fadeOut('fast').nextAll(":last-child").prependTo('#staging').fadeIn('slow',function(){stagingStop = 0;});
        Avr.stagingArea.runCallbacks(idx, 'before');
        prev.prependTo('#staging').show("slide", { direction: "left", easing: "easeOutExpo" }, 1200, function () {
            Avr.stagingArea.stagingStop = 0;
            Avr.stagingArea.runCallbacks(idx, 'after');
        });
        activeSlide.hide("slide", { direction: "right", easing: "easeOutExpo"}, 1200);
        
        activeButton = $('.staging-nav-new .active');
        activeButton.removeClass('active');
        $('#b' + prev.attr('id')).addClass('active');
        
        Avr.stagingArea.stagingTimeout = requestTimeout(function () { 
            Avr.stagingArea.nextSlide(); 
        }, Avr.stagingArea.stagingDelay);
    },

    addCallback: function (step, when, callback, scope) {
        step = parseInt(step, 10);
        var stack = Avr.stagingArea.callbackQueue;
        if (!stack[step]) {
            stack[step] = {
                before: [],
                after: []
            };
        }
        
        if (typeof callback === 'function' && stack[step] && stack[step][when]) {
            stack[step][when].push([callback, scope]);
        }
    },

    runCallbacks: function (step, when) {
        var i, l, cbks, cbk, stack = Avr.stagingArea.callbackQueue; 
        if (stack[step] && stack[step][when]) {
            cbks = stack[step][when];
            for (i = 0, l = cbks.length; i < l; i += 1) {
                cbk = cbks[i];
                cbk[0].apply(cbk[1] ? cbk[1] : this);
            }
        }
    }
    
};

Avr.htmlSubmenu = {
    initTooltips: function (id, maxposition) {
        var container = $('#' + id), tooltipContainer, menuLinks;
        tooltipContainer = $('.menu-tooltips-container', container);
        menuLinks = $('.menu-link', container);

        menuLinks.mouseover(function (e) {
            Avr.htmlSubmenu.toggleTooltip(Avr.htmlSubmenu.getId(this), tooltipContainer, 1, $(this), maxposition);
        });
       
        menuLinks.mouseout(function (e) {
            Avr.htmlSubmenu.toggleTooltip(Avr.htmlSubmenu.getId(this), tooltipContainer, 0);
        });
    },

    getId: function (elem) {
        var id = parseInt($(elem).attr('id').replace(/mdi/, ''), 10);
        return id;
    },

    toggleTooltip: function (id, tooltipContainer, show, link_elem, maxposition) {
        var tooltip = $('#mdit' + id, tooltipContainer), height, offset;
        if (show && tooltip.css('position') !== 'relative') {
            offset = link_elem.position();
            height = parseInt(tooltip.css('height'), 10);
            if (maxposition && (offset.top + height) > maxposition) {
                offset.top -= offset.top + height - maxposition;
            }

            tooltip.css({
                'display': 'block',
                'position': 'relative',
                'top': offset.top 
            });
        } else if (show) {
            tooltip.show();        
        } else {
            tooltip.hide();
        }
    }
};

Avr.accordions = {
    init: function () {
        var accordions = $('.white-accordion'), titles;
        if (!accordions.length) {
            return false;
        }
        
        accordions.each(Avr.accordions.initAccordion);

    },

    initAccordion: function (idx, accordion) {
        var titles = $('.accordion-option-title', accordion), openIdx = 0;
    
        titles.each(function (idx, element) {
            if (idx !== 0) {
                Avr.accordions.closeTab($(this), idx, accordion);
            }
            
            $(element).click(function (e) {
                Avr.accordions.closeTab(titles.eq(openIdx), openIdx, accordion);
                openIdx = idx;
                Avr.accordions.click($(this), idx, accordion);
            });
        });
    },

    click: function (title, idx, parent) {
        if (title.hasClass('closed-option')) {
            return Avr.accordions.openTab(title, idx, parent);
        }
        
        return Avr.accordions.closeTab(title, idx, parent);
    },

    openTab: function (title, idx, parent) {
        title.removeClass('closed-option');
        $('.accordion-option-content', parent).eq(idx).show();
    },

    closeTab: function (title, idx, parent) {
        title.addClass('closed-option');
        $('.accordion-option-content', parent).eq(idx).hide();
    }
};

Avr.configureActions = function () {
    var buttons, buttonHeight, prevOffset, previousButton, head, style;
    buttons = $('.widget-options');
    buttonHeight = parseInt(buttons.eq(0).height(), 10);

    buttons.each(function (idx, elem) {
        var offset;
        elem = $(elem);
        offset = elem.offset();
        if (prevOffset && offset.top - prevOffset.top < buttonHeight && prevOffset.left === offset.left) {
            elem.parent().css('top', (-buttonHeight - offset.top + prevOffset.top) + 'px');
        }
        
        prevOffset = offset;
        previousButton = elem;
    });

    Avr.widgetTint.init(buttons);
    
    // insert specific stylesheet
    head = document.getElementsByTagName("head")[0]; 
    if (!head) {
        return;
    }
    style = document.createElement('link'); 
    style.type = 'text/css';
    style.rel = 'stylesheet';
    style.href = '/design/css/tint.css';

    head.appendChild(style);
    
};

Avr.widgetTint = {
    loaded: false,
    init: function (elems) {
        if (Avr.widgetTint.loaded || elems.length === 0) {
            return;
        }

        Avr.widgetTint.loaded = true;
        
        elems.each(function (idx, elem) {
            elem = $(elem);

            elem.mouseover(function () {
                elem.parents('.widget').addClass('tint');
            });

            elem.mouseout(function () {
                elem.parents('.widget').removeClass('tint');
            });
        });

    }
};

Avr.oneClickCSS = {
    cls: null,
    icons: null,
    
    init: function (cls) {
        Avr.oneClickCSS.initMenuLinks(cls);
        Avr.oneClickCSS.initIcons();

        if (!cls) {
            return true;
        }
        Avr.oneClickCSS.update(cls);
    },

    update: function (cls) {
        Avr.oneClickCSS.setCls(cls);
        Avr.oneClickCSS.updateMenuLinks();
        Avr.oneClickCSS.updateIcons(cls);

        if (cls) {
            Avr.oneClickCSS.showIcons();
        } else {
            Avr.oneClickCSS.hideIcons();
        }
    },

    setCls: function (cls) {
        if (cls) {
            Avr.oneClickCSS.cls = cls;
        } else {
            Avr.oneClickCSS.cls = null;
        }
    },
    
    initIcons: function () {
        $(document.body).append('<div id="oneclicktooltip" class="teaserbox-yellow-tooltip"><div class="body"><div class="content" style="text-align: center;"></div></div><div class="teaserbox-grey-border"><div class="arrow">&nbsp;</div><b class="rounded-corner-tl"></b><b class="rounded-corner-tr"></b><b class="rounded-corner-bl"></b><b class="rounded-corner-br"></b></div></div>');
        
        Avr.oneClickCSS.icons = $('.widget-oneclick-link');
        Avr.oneClickCSS.icons.click(Avr.oneClickCSS.click);
        Avr.oneClickCSS.icons.tooltip({
            tip: '#oneclicktooltip',
            position: ['bottom', 'right'], 
            predelay: 500, 
            effect: 'fade',
            onBeforeShow: function (e) {
                var trigger = this.getTrigger(), tipTxt = (trigger.hasClass('widget-oneclick-remove') ? 'Remove' : 'Add') + ' <strong>' + Avr.oneClickCSS.cls + '</strong> class ' + (trigger.hasClass('widget-oneclick-remove') ? 'from' : 'to') + ' this widget.';
                $('#oneclicktooltip .content').html(tipTxt);
            }
        });
        
        Avr.widgetTint.init(Avr.oneClickCSS.icons);
    },

    updateIcons: function (cls) {
        Avr.oneClickCSS.icons.each(function (idx, elem) {
            var widgetContainer;

            elem = $(elem);
            widgetContainer = $(elem).parents('.widget');

            if (widgetContainer.hasClass(cls)) {
                elem.addClass('widget-oneclick-remove');
            } else {
                elem.addClass('widget-oneclick-add');
            } 
        });
    },

    showIcons: function () {
        Avr.oneClickCSS.icons.show();
    },

    hideIcons: function () {
        Avr.oneClickCSS.icons.hide();
    },
    
    initMenuLinks: function (cls) {
        var linkoff = $('#oneclick-off'), linkon = $('#oneclick-on');
        if (!cls) {
            linkon.parent().show();
        }
        
        linkoff.click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            $.ajax({
                url: this.href,
                success: function () {
                    Avr.oneClickCSS.update();
                }
            });
        });
    
    },

    updateMenuLinks: function () {
        var offlink = $('#oneclick-off'), onlink = $('#oneclick-on');

        if (Avr.oneClickCSS.cls) {
            onlink.parent().hide();
            offlink.parent().show();
        } else {
            onlink.parent().show();
            offlink.parent().hide();
        }
    },

    click: function (e) {
        var link = $(this);
        
        e.preventDefault();
        e.stopPropagation();
 
        if (link.hasClass('widget-oneclick-add')) {
            Avr.oneClickCSS.addClass(link);
        } else {
            Avr.oneClickCSS.removeClass(link);
        }
    },

    addClass: function (link) {
        var widgetContainer = link.parents('.widget');
        Avr.oneClickCSS.updateWidget(link[0].href, 'add', parseInt(link[0].id.replace(/w/, ''), 10), function () {
            widgetContainer.addClass(Avr.oneClickCSS.cls);
            link.removeClass('widget-oneclick-add');
            link.addClass('widget-oneclick-remove');
        });

    },

    removeClass: function (link) {
        var widgetContainer = link.parents('.widget');
        Avr.oneClickCSS.updateWidget(link[0].href, 'remove', parseInt(link[0].id.replace(/w/, ''), 10), function () {
            widgetContainer.removeClass(Avr.oneClickCSS.cls);
            link.removeClass('widget-oneclick-remove');
            link.addClass('widget-oneclick-add');
        });
    },

    updateWidget: function (url, action, version_id, callback) {
        $.ajax({
            url: url,
            data: {
                'action': action,
                'version': version_id
            },

            success: function (data, textStatus, jqXHR) {
                if (data && callback) {
                    callback();
                }
            }
        });
    }
};

Avr.messagingBoard = {
    messages: null, 
    intId: null, 

    init: function (delay) {
        if (!delay) {
            delay = 10;
        }

        Avr.messagingBoard.intId = setInterval(
            Avr.messagingBoard.next, delay * 1000
        );
    },

    next: function () {
        var current, next;
        
        if (!Avr.messagingBoard.messages) {
            Avr.messagingBoard.messages = $('.messaging-board-container .body p');

            if (Avr.messagingBoard.messages.length === 0) {
                clearInterval(Avr.messagingBoard.intId);
            }
        }

        current = Avr.messagingBoard.messages.filter(':visible');
        current.fadeOut();

        next = current.next('p');
        if (!next.length) {
            next = Avr.messagingBoard.messages.get(0);
        }
        $(next).fadeIn();
    }
};

Avr.gaw = {
    _trackEvent: function (name, action, actionId, id) {
        if (typeof _gaq === 'undefined' || !_gaq || !_gaq.push) {
            return false;
        }
        _gaq.push(['_trackEvent', name, action, actionId, id]);
    },
    
    _trackPageview: function (name) {
        if (typeof _gaq === 'undefined' || !_gaq || !_gaq.push) {
            return false;
        }

        if (name) {
            _gaq.push(['_trackPageview', name]);
        } else {
            _gaq.push(['_trackPageview']);
        }
    },

    trackBuyBtnExit: function () {
        var btnQuery = '.btn[href*="license\.avira\.com"][onclick*="rollupTracker._trackEvent("][onclick*="\'buy\'"],';
        btnQuery += '.btn[href*="cleverbridge\.com"][onclick*="rollupTracker._trackEvent("][onclick*="\'buy\'"]';
        
        $(btnQuery).each(function () {
            $(this).data('onclick', this.onclick);
            this.onclick = $.noop;
        }).click(function (e) {
            // for IE 7, block the click event
            if ($.browser.msie && 7 === parseInt($.browser.version, 10)) {
                var ev = window.event;
                ev.returnValue = false;
            }

            var func = $(this).data('onclick');
            if (func) {
                func();
            }
            //console.log('a');
            
            _gaq.push(['_link', this.href]);  
            return false;
        });
    },
    
    crossDomainLink: function (link) {
        if (typeof _gaq !== 'undefined' && link) { 
            _gaq.push(['_link', link.href]); return false; 
        }
    }
};

Avr.businessForm = {
    firstStepInit: function (id, labelTxt) {
        $label = $('label[for="AFormModel_serial"]'), $input = $('#AFormModel_product'), origText = $label.text();
        
        if ($input.val() == id) {
            $label.text('').append(labelTxt);
        }
        
        $input.change(function () {
            if ($(this).val() == id) {
                $label.text('').append(labelTxt);
            } else {
                $label.text('').append(origText);
            }
        });
    },
    secondStepInit: function () {
        $('input[type="file"]').
            filter(function (idx) {
                return idx > 0;
            }).parents('.row').hide().end().end().
            change(function () {
                $(this).parents('.row').next('.row').show()
        });
    }
}

Avr.consumerForm = {
    fields: null,
    link: null,
    title: 'Avira Support Phone',
    dialogCnt: null,
    inquiryCombo: null,
    
    init: function (link, title) {
        var button, form;

        button = $('.phone-support');
        if (!button.length) {
            return false;
        }

        if (link) {
            Avr.consumerForm.link = link;
        }

        if (title) {
            Avr.consumerForm.title = title;
        }

        form = button.parents('form');
        Avr.consumerForm.fields = $('input:visible, select:visible', form);

        button.click(Avr.consumerForm.buttonClickHandler);
    },

    buttonClickHandler: function (form) {
        var fieldsData;
        if (Avr.consumerForm.checkForm()) {
            fieldsData = Avr.consumerForm.getForm();
            Avr.consumerForm.openModal(fieldsData);
        }

        return false;
    },

    openModal: function (values) {
        var ifr, qs = jQuery.param(values), link = Avr.consumerForm.link + '?' + qs;
        pm.bind('height', Avr.consumerForm.autoHeight);
        pm.bind('close', Avr.consumerForm.closeModal);

        ifr = '<div><iframe frameborder="0" name="resframe" id="popupIFrame" scrolling="yes" src="' + link + '" style="height:320px;width:680px;overflow:hidden; overflow-y:auto"></iframe></div>';
        Avr.consumerForm.dialogCnt = $(ifr).dialog({
            width: 700,
            modal: true,
            title: Avr.consumerForm.title,
            close: Avr.consumerForm.closeModal
        });

        Avr.consumerForm.dialogCnt[0].parentNode.className += ' amodal-rounded';
    },

    autoHeight: function (data) {
        var frame;

        if (data && data.height) {
            frame = $('#popupIFrame').height(data.height);
            Avr.consumerForm.dialogCnt.dialog('option', 'position', 'center');
        }
    },

    closeModal: function () {
        closeModal();
        pm.unbind('height', Avr.consumerForm.autoHeight);
        pm.unbind('close', Avr.consumerForm.closeModal);
        Avr.consumerForm.dialogCnt = null;
    },

    checkForm: function () {
        var fields = Avr.consumerForm.fields, foundErrors = [], errorSummaryCnt, i;
        fields.removeClass('error');

        $('.errorSummary').hide();

        if (!fields.eq(0).val()) {
            fields.eq(0).addClass('error');
            foundErrors.push(1);
        }
        
        if (!fields.eq(1).val() && !fields.eq(2).val()) {
            fields.eq(1).addClass('error');
            fields.eq(2).addClass('error');
            foundErrors.push(2);
        }
        
        if (foundErrors.length > 0) {
            errorSummaryCnt = $('.cErrorSummary');
            $('.error_message', errorSummaryCnt).hide();
            
            for (i = 0; i < foundErrors.length; i += 1) {
                $('.err' + foundErrors[i], errorSummaryCnt).show();
            }
            
            errorSummaryCnt.show();
            return false;
        }

        return true;
    },

    getForm: function () {
        var fields = Avr.consumerForm.fields, values = {};

        fields.each(function (idx, elem) {
            var name = elem.name.replace(/AFormModel\[(\w+)\]/ig, '$1'), value = $(elem).val();
            if (name && value) {
                switch (name) {
                    case 'email':
                        values.identifier = value;
                        values.type = 'EMAIL';
                        values.buttonSubmit = 1;
                        break;
                    case 'activation_code':
                        if (!values.type) {
                            values.identifier = value;
                            values.type = 'OTC';
                            values.buttonSubmit = 1;
                        }
                        break;
                    default:
                        values[name] = value;
                }
            }
        });

        return values;
    },

    secondStepInit: function () {
        $('input[type="file"]').
            filter(function (idx) {
                return idx > 0;
            }).parents('.row').hide().end().end().
            change(function () {
                $(this).parents('.row').next('.row').show()
        });

        this.inquiryCombo = $('#AFormModel_inquiry_type'); 
        
        //Remove "Choose..." option.
        $('option:first', this.inquiryCombo).remove();
       
        this.inquiryComboAction();
        this.inquiryCombo.change(this.inquiryComboAction);
    },
    
    inquiryComboAction: function (evt) {
        var technicalRelatedFieldsQuery = '#AFormModel_product, #AFormModel_category, #AFormModel_os, #AFormModel_other_av, #AFormModel_free_av';
        
        if ($(Avr.consumerForm.inquiryCombo).val() === '2') {
            $(technicalRelatedFieldsQuery).attr('disabled', 'disabled').parents('.row').hide();
        } else {
            $(technicalRelatedFieldsQuery).removeAttr('disabled').parents('.row').show();
        }
    }
};

Avr.track = function () {

    var xCookie, couponCookie, xData = {}, queryString = '', buttons;

    xCookie = $.cookie('passthrough');
    couponCookie = $.cookie('coupon');
    if (xCookie) {
        // Parse the JSON from cookie.
        try {
            xData = $.parseJSON(xCookie);
        } catch (err) {};
    }
    queryString += $.param(xData);

    if (couponCookie) {
        queryString += (queryString.length > 0 ? '&' : '') + 'coupon=' + couponCookie;
    }
    
    buttons = $('a.btn, a.btn-track').filter(function (idx) {
        if (this.href.match(/\.avira.com|cleverbridge.com/gi)) {
            return true;
        }
        return false;
    });
    
    buttons.attr('href', function (index, attr) {
        var result = attr;
        
        if (queryString) {
            if (result.indexOf('?') === -1) {
                result += "?" + queryString;
            } else {
                result += "&" + queryString;
            }
        }
        
        // Add x-origin web if there isn't an origin defined.
        if (result.indexOf('x-origin') === -1) {
            if (result.indexOf('?') === -1) {
                result += '?x-origin=web';
            } else {
                result += '&x-origin=web';
            }
        }
        
        return result;
    });

    $('form').each(function (idx, elem) {
        var $this = $(elem), action = $this.attr('action');
        if (!action || !action.match(/\.avira.com|cleverbridge.com/gi)) {
            return true;
        }

        $.each(xData, function (k, v) {
            $('<input>').attr({
                type: 'hidden',
                name: k,
                value: v
            }).appendTo($this);
        });
    });

};

Avr.OSRedirect = function ($os, $url) {
    var cookieOs = $os + '-os';
    cookieOs = cookieOs.toLowerCase();

    if (!$.cookie || !$.client || $.cookie(cookieOs) || $os !== $.client.os) {
        return false;
    }
    
    $.cookie(cookieOs, 1);
    window.location.replace($url);
};

Avr.InProductSetup = function () {
    $('#footer a, #header a, #tabs .teaserbox-grey .av_head a, .teaserbox-grey .av_avira a, .btn').filter(':visible').attr('target', '_blank');
};

Avr.AV12Intro = {
    container: null,
    phrases: null, 
    scene3: null,
    $word1: null,
    $word2: null,
    $word3: null,
    $word4: null,
    $util: null,
    
    init: function (phrases) {
        
        alreadySeen = 0;
        if ($.cookie) {
            alreadySeen = $.cookie('av12intro');
        }
        
        if ($.browser.msie && 7 === parseInt($.browser.version, 10)) {
            alreadySeen = '1';
        }

        if (alreadySeen === '1' || !phrases) {
            Avr.stagingArea.init(10); 
            return false;
        }
        
        $('.staging-area').height(482);
        this.container = $('#stagingAV12').show();
        this.phrases = phrases;

        this.start();
    },

    start: function () {
        var _this = this, loaded = true, $images = $('.box img', this.container);
        $images.each(function (idx, img) {
            if (img.complete !== true) {
                loaded = false;
            }

            if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
                loaded = false;
            }
        });

        if (!loaded) {
            setTimeout(function () { _this.start(); }, 500);
            return;
        }

        $('.box', this.container).show();

        this.scene3 = false;
        this.$word1 = $('#word1');
        this.$word2 = $('#word2');
        this.$word3 = $('#word3');
        this.$word4 = $('#word4');
        this.$util = $('#util-word');
        
        setTimeout(function () {
            _this.startScene1Av12();
        }, 500);
    },
    
    getWidth: function (word) {
        this.$util.html(word);
        return this.$util.width();
    },
    
    putPhrase: function (idx) {
        var _this = this, words = this.phrases[idx], wordNW = this.getWidth(words['word2']);
        this.$word2.animate({width: wordNW}, 200, function () {
            _this.$word2.html(words['word2']).animate({opacity: 1}, 500, function () {
                if (idx === _this.phrases.length - 1) {
                    requestTimeout(function () { _this.startScene3Av12(); }, 1500);
                    return false;
                }
        
                _this.animatePhrase(idx);
            });
            
            _this.$word4.hide().html(words['word4']).delay(200).fadeIn(500);
        });
    },

    animatePhrase: function (idx) {
        var timeout = 1500, _this = this;
        
        requestTimeout(function () {    
            _this.$word2.animate({opacity: 0}, 500, function () {
               _this.putPhrase(idx + 1);
            });
            _this.$word4.delay(250).fadeOut(500);
        }, timeout);
    },

    animateObjectAv12: function (id, marginTop, marginRight, marginBottom, marginLeft, durationParam, easingParam, widthObject, heightObject, delay) {    
        var _this = this, elem = id, properties = {
            top: marginTop,
            right: marginRight,
            bottom: marginBottom,
            left: marginLeft
        };
        
        // properties
        if(widthObject && heightObject) {
            properties = $.extend(properties, {
                width: widthObject,
                height: heightObject
            })
        }
        
        if (jQuery.type(id) === "string") {
            elem = $("#" + id);
        }
        
        if (delay) {
            elem = elem.delay(delay);
        }
        
        elem.animate(properties, {
            // options
            duration: durationParam,
            easing: easingParam,
            queue: true,
            complete: function() {
                // scene 2
                if(id == 'avLeft .avTop') {
                    $("#avLeft .avBottom").show();
                    $("#avRight .avTop").show();
                    
                    if (_this.scene3 === true) {
                        return;
                    }
                    
                    _this.animateAv12Text();
                } else if(id == 'av12Bar') {
                    $("#avLeft .avTop").fadeIn(100);
                    _this.animateObjectAv12("avLeft .avTop", 0, 0, 0, 200, 1000, "swing", "", "");
                    $("#avRight .avBottom").fadeIn(1500);
                }
            }
        });
    },

    animateAv12Text: function () {
        var _this = this;
        this.$word2.delay(1250).animate({opacity: 0}, 500, function () {
            _this.putPhrase(1);
        });
    },

    startScene1Av12: function () {
        this.animateObjectAv12("premiumBox", 20, 0, 0, 0, 150, "swing", "", "", 500);
        $("#bg").delay(500).fadeIn(1700);
        this.animateObjectAv12("suiteBox", 20, 0, 0, 0, 150, "swing", "", "", 575);
        this.animateObjectAv12("freeBox", 20, 0, 0, 0, 150, "swing", "", "", 650);
        this.animateObjectAv12("businessBox", 20, 0, 0, 0, 150, "swing", "", "", 725);
        this.animateObjectAv12("av12Bar", 0, 0, 0, 0, 1250, "swing", "888px", "142px", 2200);
        this.startScene2Av12();
    },

    startScene2Av12: function () {
        this.$word1.html(this.phrases[0]['word1']);
        this.$word2.html(this.phrases[0]['word2']);
        this.$word3.html(this.phrases[0]['word3']);
        
        $("#av12Scene1").delay(2200).fadeOut(500, function() {
            $("#av12Scene2").fadeIn(500);
        });
    },
    
    startScene3Av12: function () {
        var _this = this;
        $("#av12Scene2").fadeOut(500, function() {
            $("#av12TitleBig").fadeOut(500);
            _this.scene3 = true;
            _this.animateObjectAv12("av12Bar", -134, 0, 0, -4, 400, "swing", "490px", "142px");
            
            _this.animateObjectAv12("stagingAV12", 0, 0, 0, 0, 400, "swing", "888px", "250px", 250);
            _this.animateObjectAv12($('.staging-area'), 0, 0, 0, 0, 400, "swing", "888px", "250px", 250);
                
            $("#av12Scene3").delay(350).fadeIn(250, function () { 
                $('#stagingAV12').hide(); 
                $('.staging-area img').removeAttr('height');
                if ($.cookie) {
                    $.cookie('av12intro', 1);
                }
                Avr.stagingArea.init(10); 
            });
            
        });
    }

};

Avr.installerWidget = {
    container: null,
    steps: null,
    stepIdx: -1,
    delay: 5000,
    blockAnimation: false,
    init: function () {
        var _this = this;
        this.container = $('.staging-installer');
        this.steps = $('.liner li', this.container);
        
        this.container.mouseenter(function () {
            _this.removeHovering();
            _this.blockAnimation = true;
        });
        
        this.container.mouseleave(function () {
            _this.stepIdx = -1;
            _this.blockAnimation = false;
        });

        requestTimeout(function () {
            _this.next();
        }, this.delay);
    },

    next: function () {
        var _this = this;
        if (this.blockAnimation === false) {
            this.removeHovering();

            this.stepIdx += 1;
            if (this.stepIdx >= this.steps.length) {
                this.stepIdx = -1;
            }
            this.addHovering();
        }
        
        requestTimeout(function () {
            _this.next();
        }, this.delay);

    },

    removeHovering: function () {
        if (this.stepIdx == -1) {
            return;
        }
        
        var step = this.steps.get(this.stepIdx), $step = $(step);
        $(step).removeClass('hovered');
        $(".capture2", $step).stop(true, true).fadeOut("fast");
    },
    
    addHovering: function () {
        if (this.stepIdx == -1) {
            return;
        }
        var step = this.steps.get(this.stepIdx), $step = $(step);
        $(".capture2", $step).stop(true, true).fadeIn("slow");
        $step.addClass('hovered');
    }

}

/**
 * Behaves the same as setTimeout except uses requestAnimationFrame() where possible for better performance
 * @param {function} fn The callback function
 * @param {int} delay The delay in milliseconds
 */
window.requestTimeout = function(fn, delay) {
	if( !window.requestAnimationFrame      	&& 
		!window.webkitRequestAnimationFrame && 
		!window.mozRequestAnimationFrame    && 
		!window.oRequestAnimationFrame      && 
		!window.msRequestAnimationFrame)
			return window.setTimeout(fn, delay);
			
	var start = new Date().getTime(),
		handle = new Object();
		
	function loop(){
		var current = new Date().getTime(),
			delta = current - start;
			
		delta >= delay ? fn.call() : handle.value = requestAnimFrame(loop);
	};
	
	handle.value = requestAnimFrame(loop);
	return handle;
};

/**
 * Behaves the same as clearInterval except uses cancelRequestAnimationFrame() where possible for better performance
 * @param {int|object} fn The callback function
 */
window.clearRequestTimeout = function(handle) {
    window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) :
    window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value)	:
    window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value) :
    window.oCancelRequestAnimationFrame	? window.oCancelRequestAnimationFrame(handle.value) :
    window.msCancelRequestAnimationFrame ? msCancelRequestAnimationFrame(handle.value) :
    clearTimeout(handle);
};

// requestAnimationFrame() shim by Paul Irish
window.requestAnimFrame = (function() {
	return  window.requestAnimationFrame   || 
			window.webkitRequestAnimationFrame || 
			window.mozRequestAnimationFrame    || 
			window.oRequestAnimationFrame      || 
			window.msRequestAnimationFrame     || 
			function(/* function */ callback, /* DOMElement */ element){
				window.setTimeout(callback, 1000 / 60);
			};
})();

$(document).ready(function () {
    if ($.browser.msie) {
        Avr.searchBlur();
    }

    $('.red-stripe h2:empty').hide();
    
    Avr.tabs.initTabsOnPage();
    Avr.searchboxInit();
    Avr.footerActions();
    Avr.productChooserInit();
    Avr.phoneInit();
    Avr.accordions.init();
    Avr.track();
    //Avr.gaw.trackBuyBtnExit();
});

