﻿(function ($) {

    /* Create Arrays */
    var params = [],
        order = [],
        images = [],
        links = [],
        linksTarget = [],
        titles = [],
        interval = [],
        imagePos = [],
        appInterval = [],
        squarePos = [],
        hovers = [],
        clicks = [],
        reverse = [],
        container = null,
        expandingSpeed = null,
        collapsingSpeed = null,
        randomVal = Math.random();

    $.fn.adslider = $.fn.AdSlider = function (options) {


        // initializes
        function init(el) {

            container = $(el);
            order[el.id] = []; // order of square appereance
            images[el.id] = [];
            links[el.id] = [];
            linksTarget[el.id] = [];
            titles[el.id] = [];
            hovers[el.id] = [];
            clicks[el.id] = [];
            imagePos[el.id] = 0;
            squarePos[el.id] = 0;
            reverse[el.id] = 1;

            params[el.id] = $.extend({}, $.fn.adslider.defaults, options);

            parentSelector = $(params[el.id].parentSelector);

            if (parentSelector != null) {

                parentSelected = parentSelector;

                if (parentSelected != null && parentSelected.css("display") == "block") {
                    container.appendTo(parentSelected);
                }
                else {
                    return;
                }
            }


            // create images, links and titles arrays
            $.each($('#' + el.id).find("img"), function (i, item) {
                images[el.id][i] = $(item).attr('src');
                links[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('href') : '';
                linksTarget[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('target') : '';
                clicks[el.id][i] = $(item).attr('clicktrackingvalue');
                hovers[el.id][i] = $(item).attr('mouseouttrackingvalue');
                $('#' + el.id + ' img').parent().remove();
            });


            // set panel

            $(el).find(".content").css({
                'background-image': 'url(' + images[el.id][0] + ')',
                'width': params[el.id].width,
                'height': params[el.id].height,
                'position': 'relative',
                'background-position': 'top left'
            }).wrap("<div class='ad-slider' id='ad-slider-" + el.id + "' />");



            setFields(el);

            if (params[el.id].randomize)
                sortArrays(el);

            if (params[el.id].navigation)
                setNavigation(el);

            sliderSpeed(el);
            transition(el, 0);
            transitionCall(el);
            createAdUnit(el);
            createAnalyticsTracking(el);

            if (isIOS()) {
                pauseWhenClicked(el);
            }
            else if (params[el.id].pauseWhenCollapsed) {
                pauseWhenCollapsed(el);
            }


            container.show();
        }

        this.each(
        function () {
            init(this);
        });

    };

    // default values
    $.fn.adslider.defaults = {
        width: 544,
        // width of slider panel
        height: 81,
        // height of slider panel
        spw: 1,
        // squares per width
        sph: 1,
        // squares per height
        delay: 3000,
        // delay between images in ms
        sDelay: 30,
        // delay beetwen squares in ms
        opacity: 0.7,
        // opacity of title and navigation        
        effect: '',
        // straight
        navigation: true,
        // image buttons
        links: true,
        // show images as links 
        hoverPause: false,
        // pause on hover
        randomize: true,
        // randomize the advertisement
        pauseWhenCollapsed: true,
        // pause the advertisement when no one is hovering
        expandingSpeed: 600,
        // speed of the expanding 
        collapsingSpeed: 600,
        // speed of the collapsing 
        gaTrackingName: "slider",
        // name to track the google analytics by
        parentSelector: null
    };

    // sets the slider speed
    function sliderSpeed(el) {
        collapsingSpeed = params[el.id].collapsingSpeed;
        expandingSpeed = params[el.id].expandingSpeed;
    }

    // randomly sorts arrays
    function sortArrays(el) {
        images[el.id].sort(randomSort);
        links[el.id].sort(randomSort);
        titles[el.id].sort(randomSort);
        linksTarget[el.id].sort(randomSort);
        order[el.id].sort(randomSort);
        clicks[el.id].sort(randomSort);
        hovers[el.id].sort(randomSort);
    }

    // setups the navigation
    function setNavigation(el) {
        // image buttons
        $("<div id='ad-buttons-" + el.id + "' class='ad-buttons'></div>").appendTo($('#ad-slider-' + el.id));

        for (k = 1; k < images[el.id].length + 1; k++) {
            $('#ad-buttons-' + el.id).append("<a href='#' class='ad-button-" + el.id + "' id='ad-button-" + el.id + "-" + k + "'>" + k + "</a>");
        }

        $.each($('.ad-button-' + el.id), function (i, item) {
            $(item).click(function (e) {
                $('.ad-button-' + el.id).removeClass('ad-active');
                $(el).find(".content").addClass('ad-active');
                e.preventDefault();
                transition(el, i, true);
                transitionCall(el);
            })
        });

        $("#ad-buttons-" + el.id).css({
            'margin-left': -images[el.id].length * 15 / 2 - 5,
            'position': 'relative'
        });
    }

    // pauses when collapsed
    function pauseWhenCollapsed(el) {

        $(el).find(".unit").hover(function () { params[el.id].pause = false; })
                           .mouseout(function () { params[el.id].pause = true; });


        params[el.id].pause = true;
    }

    function pauseWhenClicked(el) {
        $(el).find(".ipadbtn").click(function () { params[el.id].pause = !params[el.id].pause });
    }


    // rRandom sorting function
    function randomSort() {
        return (0.5 - randomVal);
    }

    // squares positions
    function setFields(el) {

        tWidth = sWidth = parseInt(params[el.id].width / params[el.id].spw);
        tHeight = sHeight = parseInt(params[el.id].height / params[el.id].sph);

        counter = sLeft = sTop = 0;
        tgapx = gapx = params[el.id].width - params[el.id].spw * sWidth;
        tgapy = gapy = params[el.id].height - params[el.id].sph * sHeight;

        for (i = 1; i <= params[el.id].sph; i++) {
            gapx = tgapx;

            if (gapy > 0) {
                gapy--;
                sHeight = tHeight + 1;
            } else {
                sHeight = tHeight;
            }

            for (j = 1; j <= params[el.id].spw; j++) {

                if (gapx > 0) {
                    gapx--;
                    sWidth = tWidth + 1;
                } else {
                    sWidth = tWidth;
                }

                order[el.id][counter] = i + '' + j;
                counter++;

                if (params[el.id].links) $('#' + el.id).find(".content").append("<a href='" + links[el.id][0] + "' class='ad-" + el.id + "' id='ad-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></a>")
                else
                    $('#' + el.id).find(".content").append("<div class='ad-" + el.id + "' id='ad-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></div>");

                // positioning squares
                $("#ad-" + el.id + i + j).find(".content").css({
                    'background-position': -sLeft + 'px ' + (-sTop + 'px'),
                    'left': sLeft,
                    'top': sTop
                });

                sLeft += sWidth;
            }

            sTop += sHeight;
            sLeft = 0;

        }

      
        if (params[el.id].hoverPause) {
            $(el).find(".unit")
                    .mouseover(function () { params[el.id].pause = true; })
                    .mouseout(function () { params[el.id].pause = false; });
        }
        else {
            $(el).find(".unit")
                    .mouseover(function () { params[el.id].pause = false; })
                    .mouseout(function () { params[el.id].pause = false; });
        }

    };

    // transition call
    function transitionCall(el) {

        clearInterval(interval[el.id]);
        delay = params[el.id].delay + params[el.id].spw * params[el.id].sph * params[el.id].sDelay;
        interval[el.id] = setInterval(function () {
            transition(el)
        }, delay);

    }

    // transitions
    function transition(el, direction, clicked) {

        if (clicked == undefined)
            clicked = false;

        if (params[el.id].pause == true && clicked == false) return;

        effect(el);

        squarePos[el.id] = 0;
        appInterval[el.id] = setInterval(function () {
            appereance(el, order[el.id][squarePos[el.id]])
        }, params[el.id].sDelay);

        $(el).find(".content").css({
            'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')'
        });

        if (typeof (direction) == "undefined") imagePos[el.id]++;
        else
            if (direction == 'prev') imagePos[el.id]--;
            else
                imagePos[el.id] = direction;

        if (imagePos[el.id] == images[el.id].length) {
            imagePos[el.id] = 0;
        }

        if (imagePos[el.id] == -1) {
            imagePos[el.id] = images[el.id].length - 1;
        }

        $('.ad-button-' + el.id).removeClass('ad-active');
        $('#ad-button-' + el.id + "-" + (imagePos[el.id] + 1)).addClass('ad-active');
    };

    // expand ad
    function expandAd() {
        container.animate({
            'width': 558 + 'px'
        }, expandingSpeed,

        function () {
            container.removeClass('inactive').addClass('active');
            $('.arrow').removeClass('arrow-open').addClass('arrow-close');
        }
        );
    }

    // collapse ad
    function collapseAd() {
        container.animate({
            'width': container.data('myStartWidth') + 'px'
        }, collapsingSpeed,

        function () {
            $('.arrow').removeClass('arrow-close').addClass('arrow-open');

            if (container.hasClass('active')) {
                container.removeClass('active').addClass('inactive');
            }
        }
       );
    }

    // creates the ad Unit
    function createAdUnit(el) {

        container = $(el);

        var config = {
            over: expandAd,
            timeout: 1000,
            out: collapseAd
        },
            unit = container.find(".unit"),
            iPadBtn = container.find(".ipadbtn"),
            startWidth = container.outerWidth();
        container.data('myStartWidth', startWidth);

        if (isIOS() != null) {
            iPadBtn.show().bind("click mousedown", function (e) {
                if (container.hasClass('inactive')) {
                    expandAd();
                } else {
                    collapseAd();
                }
            });
        } else {
            iPadBtn.hide();
            container.hoverIntent(config);
        }

    }

    //Checks if the phone is IOS
    function isIOS() {
        return navigator.userAgent.toLowerCase().match(/iP(hone|ad)/i)
    }


    // setups up google analytics
    function createAnalyticsTracking(el) {
        $('.ad-' + el.id)
                .click(function () { trackPage(el, 'click') })
                .mouseout(function () { trackPage(el, 'hover') });
    }

    // track the click and hover event
    function trackPage(el, event) {
        pageTracker._trackEvent(params[el.id].gaTrackingName, event, clicks[el.id][imagePos[el.id]]);
    }

    // recalls on transitions
    function appereance(el, sid) {

        $('#ad-' + el.id + sid).attr('href', links[el.id][imagePos[el.id]]).attr('target', linksTarget[el.id][imagePos[el.id]]);

        if (squarePos[el.id] == params[el.id].spw * params[el.id].sph) {
            clearInterval(appInterval[el.id]);
            return;
        }

        $('#ad-' + el.id + sid).css({
            opacity: 0,
            'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')'
        });

        $('#ad-' + el.id + sid).animate({
            opacity: 1
        }, 300);
        squarePos[el.id]++;

    };

    // effects
    function effect(el) {
        order[el.id] = new Array();

        straight(el);

        reverse[el.id] *= -1;
        if (reverse[el.id] > 0) {
            order[el.id].reverse();
        }

    }

    // straight effect
    function straight(el) {
        counter = 0;
        for (i = 1; i <= params[el.id].sph; i++) {
            for (j = 1; j <= params[el.id].spw; j++) {
                order[el.id][counter] = i + '' + j;
                counter++;
            }

        }
    }

    function min(n, m) {
        if (n > m) return m;
        else
            return n;
    }

    function max(n, m) {
        if (n < m) return m;
        else
            return n;
    }

})(jQuery);


