(function () {
    $.fn.infiniteCarousel = function () {
        function repeat(str, n) {
            return new Array( n + 1 ).join(str);
        }
        
        return this.each(function () {
            // magic!
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(9999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first')
                
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth),
                currentPage = 1,
                pages = Math.ceil($items.length / visible);
                
            /* TASKS */
            
            // 1. pad the pages with empty element if required
            if ($items.length % visible != 0) {
                // pad
                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
                $items = $slider.find('> li');
            }
            
            // 2. create the carousel padding on left and right (cloned)
            $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
            $items = $slider.find('> li');
            
            // 3. reset scroll
            $wrapper.scrollLeft(singleWidth * visible);
            
            // 4. paging function
            function gotoPage(page) {
                var dir = page < currentPage ? -1 : 1,
                    n = Math.abs(currentPage - page),
                    left = singleWidth * dir * visible * n;
                
                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 750, function () {
                    // if page == last page - then reset position
                    if (page > pages) {
                        $wrapper.scrollLeft(singleWidth * visible);
                        page = 1;
                    } else if (page == 0) {
                        page = pages;
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                    }
                    
                    currentPage = page;
                });
            }
            
            // 5. insert the back and forward link
            $wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>');
            
            // 6. bind the back and forward links
            $('a.back', this).click(function () {
                gotoPage(currentPage - 1);
                return false;
            });
            
            $('a.forward', this).click(function () {
                gotoPage(currentPage + 1);
                return false;
            });
            
            $(this).bind('goto', function (event, page) {
                gotoPage(page);
            });
            
            // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
            $(this).bind('next', function () {
                gotoPage(currentPage + 1);
            });
        });
    };
})(jQuery);


var general = {

    // OnLoad functions
    init: function () {
        this.bubbleEvt();
    },

    bubbleEvt: function () {

        if ($(".roi-wrapper").length > 0) {
            var startSlidedPos = $.cookie('comaroundRoiUsers');
            var startSlidedPosLi;
            if (startSlidedPos != null)
                startSlidedPosLi = $("ul.roi-values li").filter(function (index) {
                    return $(this).text() == startSlidedPos;
                });
            else
                startSlidedPosLi = $(".initActive");

            var indexPos = $('.roi-values li').index(startSlidedPosLi);

            if (indexPos >= 0) {
                $('.slider').slider({ value: indexPos, create: function (event, ui) { general.fixAfterSlide(indexPos) },
                    slide: function (event, ui) {
                        general.fixAfterSlide(ui.value)
                    },
                    max: 12
                });
            } else {
                $('.slider').slider({
                    slide: function (event, ui) {
                        general.fixAfterSlide(ui.value)
                    },
                    max: 12
                });
            }
        }




        $('#rightcol-form #contour input[type=text], #rightcol-form #contour textarea').focus(function () {

            $(this).parent().parent().find("label").hide();

        });

        $('#rightcol-form #contour input[type=text],#rightcol-form #contour textarea').blur(function () {
            if ($(this).val() == "")
                $(this).parent().parent().find("label").show();

        });

        if ($('#rightcol-form #contour legend').html()) {
            $('#rightcol-form #contour legend').after("<p>" + $('#rightcol-form #contour legend').html() + "</p>");
        }


        general.equalHeight($('.startpage-col-three-bg .col'));


        if ($('.main-content').height() < 450) {
            $('.content-container').height('380px')
        }

        if ($('ul.menu').length > 0) {
            $('ul.menu li.selected a, .menu li.selected span, ul.menu li.expanded a, .menu li.expanded span').each(function () {
                if ($(this).height() < 20) {
                    //$(this).prepend('<br />')
                }
            });
        }

        /*
        $( ".content img, .sidebar img, .three-col img" ).each(							   
        function() {
        if($(this).parent("a").hasClass("video-flv")) {
        var top = ($(this).height()/2)-30;
        var left = ($(this).width()/2)-30;
        $(this).wrap('<span style="width:'+$(this).width()+'px; height:'+$(this).height()+'px" class="img-wrapper '+ this.className +'" />');
        this.className="";
        $(this).parent(".img-wrapper").append('<span class="play-button" style="top:'+top+'px; left:'+left+'px"></span><span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>');
        } else {
        $(this).wrap('<span style="width:'+$(this).width()+'px; height:'+$(this).height()+'px" class="img-wrapper '+ this.className +'" />');
        this.className="";
        $(this).parent(".img-wrapper").append('<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>');					
        }
        });	*/

        general.addLinkIcon();

        if ($('.content-rotator').is(':empty') && $('.header-block').length > 0) {
            $('.content-rotator').css('height', '100px')
        }

        $('.articlepage .main-content tr:odd').addClass('row-color')
        $('.articlepage .main-content div.report table tr:odd').removeClass('row-color')

        if ($('.speech-bubble-content').length > 0) {
            $('.articlepage .main-content blockquote p').css('margin-top', '0px')
        }

        //fixes on layout .listpage.extended page with margin-bottom on images
        if ($('.listpage.extended ul.list li').length > 0) {

            $('.listpage.extended ul.list li').each(function (index) {

                var $imgElm = $(this).find('img');
                var $parElm = $(this).find('p');
                var $headlineElm = $(this).find('h2');

                var heightDiff = ($parElm.height() + $headlineElm.height()) - $imgElm.height()

                if (heightDiff < 5) {
                    $imgElm.css('margin-bottom', '10px');
                } else {
                    if ($imgElm.height() < 50) {
                        $imgElm.css('margin-bottom', (($parElm.height() - $headlineElm.height() + 50) / 1.5) + 'px')
                    } else {
                        $imgElm.css('margin-bottom', (($parElm.height() - $headlineElm.height() + 20) / 1.5) + 'px')
                    }
                }

                //if <li> does not contains any image set paragraf to spec width
                if ($imgElm.length == 0) {
                    $parElm.width('575px')
                    $headlineElm.width('575px')
                }
            });

        }

        general.equalHeightBlurbFollowLink();

        general.makeElementALink($('.listpage:not(.extended) ul.list li'));

        //prettyPhoto
        $("a.youtube-layer").prettyPhoto({
            theme: 'facebook',
            opacity: 0.60,
            wmode: 'opaque',
            hideflash: true
        });

    },

    fixAfterSlide: function (pos) {
        $('.roi-values li').removeClass('active');
        var pos = pos + 1;

        var bgpos;
        var bubblePos;


        if ($(".roi-wrapper").hasClass("medium")) {
            bgpos = -714 + ((pos - 1) * 16);
            bubblePos = -25 + ((pos - 1) * 15.5);

        } else if ($(".roi-wrapper").hasClass("small")) {
            bgpos = -714 + ((pos - 1) * 18);
            bubblePos = -30 + ((pos - 1) * 16);
        } else {
            bgpos = -714 + ((pos - 1) * 60);
            bubblePos = 68 + ((pos - 1) * 60);
        }


        $(".ui-slider").css("background-position", bgpos);
        $('.roi-values li:nth-child(' + pos + ')').addClass('active');

        $(".bubble").css("left", bubblePos);
        var totusers = $(".roi-values li.active").html();
        $(".roi-users").html(totusers);
        general.updateRoiVals($(".roi-values li.active").html());
        $.cookie('comaroundRoiUsers', totusers, { path: '/', secure: false });
        $("#contour input[type=text]:last").not("#rightcol-form #contour input[type=text]:last").attr("value", totusers);
    },

    updateRoiVals: function (u) {

        var saveM = "0";
        var saveY = "0";
        var days = "0";
        var percentage = "0";
        var users = u.replace(" ", "") * 1;

        switch (users) {
            case selection[0].replace(" ", "") * 1:
                saveM = savemonthly[0];
                saveY = saveyearly[0];
                days = daysvalue[0];
                percentage = percentagesave[0];
                break;
            case selection[1].replace(" ", "") * 1:
                saveM = savemonthly[1];
                saveY = saveyearly[1];
                days = daysvalue[1];
                percentage = percentagesave[1];
                break;
            case selection[2].replace(" ", "") * 1:
                saveM = savemonthly[2];
                saveY = saveyearly[2];
                days = daysvalue[2];
                percentage = percentagesave[2];
                break;
            case selection[3].replace(" ", "") * 1:
                saveM = savemonthly[3];
                saveY = saveyearly[3];
                days = daysvalue[3];
                percentage = percentagesave[3];
                break;
            case selection[4].replace(" ", "") * 1:
                saveM = savemonthly[4];
                saveY = saveyearly[4];
                days = daysvalue[4];
                percentage = percentagesave[4];
                break;
            case selection[5].replace(" ", "") * 1:
                saveM = savemonthly[5];
                saveY = saveyearly[5];
                days = daysvalue[5];
                percentage = percentagesave[5];
                break;
            case selection[6].replace(" ", "") * 1:
                saveM = savemonthly[6];
                saveY = saveyearly[6];
                days = daysvalue[6];
                percentage = percentagesave[6];
                break;
            case selection[7].replace(" ", "") * 1:
                saveM = savemonthly[7];
                saveY = saveyearly[7];
                days = daysvalue[7];
                percentage = percentagesave[7];
                break;
            case selection[8].replace(" ", "") * 1:
                saveM = savemonthly[8];
                saveY = saveyearly[8];
                days = daysvalue[8];
                percentage = percentagesave[8];
                break;
            case selection[9].replace(" ", "") * 1:
                saveM = savemonthly[9];
                saveY = saveyearly[9];
                days = daysvalue[9];
                percentage = percentagesave[9];
                break;
            case selection[10].replace(" ", "") * 1:
                saveM = savemonthly[10];
                saveY = saveyearly[10];
                days = daysvalue[10];
                percentage = percentagesave[10];
                break;
            case selection[11].replace(" ", "") * 1:
                saveM = savemonthly[11];
                saveY = saveyearly[11];
                days = daysvalue[11];
                percentage = percentagesave[11];
                break;

            default: break;

        }

        $(".roival1").html(saveM);
        $(".roival2").html(saveY);
        $(".roival3").html(days);
        $(".roival4").html(percentage);
    },




    equalHeight: function (group) {
        tallest = 0;
        group.each(function () {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    },

    addLinkIcon: function (e) {
        // Add pdf icons to pdf links
        $("a[href$='.pdf']").before('<span class="pdf"></span>&nbsp;').addClass("link-icon");

        // Add ppt icons to ppt links
        $("a[href$='.ppt'], a[href$='.pptx']").before('<span class="powerpoint"></span>&nbsp;').addClass("link-icon");

        // Add txt icons to document links (doc, rtf, txt)
        $("a[href$='.doc'], a[href$='.docx'], a[href$='.txt'], a[href$='.rft']").before('<span class="txt"></span>&nbsp;').addClass("link-icon");

        // Add zip icons to Zip file links (zip, rar)
        $("a[href$='.zip'], a[href$='.rar']").before('<span class="zip"></span>&nbsp;').addClass("link-icon");

        // Add email icons to email links
        $("a[href^='mailto:']").after('<span class="email"></span>&nbsp;').addClass("link-icon");

        //Add external link icon to external links - 
        $('a').not("a[href^='mailto:'], .arrow-link a, a.blurb-follow-link-content, .addthis_toolbox a, .column a, a[href^='javascript:']").filter(function () {
            //Compare the anchor tag's host name with location's host name
            //If linked to youtube, "youtube-layer" classname is added, else "external" classname is added
            if ('www.youtube.com' == this.hostname || 'youtube.com' == this.hostname) {

                $(this).addClass("youtube-layer");

                if ($(this).children().is('img')) {

                    var ElmFloat = $(this).children('img').css('float');

                    var ElmPaddingTop = $(this).children('img').css('padding-top');
                    var ElmPaddingRight = $(this).children('img').css('padding-right');
                    var ElmPaddingBottom = $(this).children('img').css('padding-bottom');
                    var ElmPaddingLeft = $(this).children('img').css('padding-left');

                    var ElmMarginTop = $(this).children('img').css('margin-top');
                    var ElmMarginRight = $(this).children('img').css('margin-right');
                    var ElmMarginBottom = $(this).children('img').css('margin-bottom');
                    var ElmMarginLeft = $(this).children('img').css('margin-left');

                    $(this).css({ float: ElmFloat,
                        clear: ElmFloat,
                        paddingTop: ElmPaddingTop,
                        paddingRight: ElmPaddingRight,
                        paddingBottom: ElmPaddingBottom,
                        paddingLeft: ElmPaddingLeft,
                        marginTop: ElmMarginTop,
                        marginRight: ElmMarginRight,
                        marginBottom: ElmMarginBottom,
                        marginLeft: ElmMarginLeft
                    })

                    $(this).children('img').css({ float: 'none',
                        padding: '0',
                        margin: '0'
                    })

                    var imageHeight = $(this).children('img').height()
                    var $imageMovieIconLayer = jQuery('<span/>', {
                        className: 'image-movie-icon-layer',
                        width: $(this).children('img').width(),
                        height: $(this).children('img').height()
                    })
                    var $movieIcon = jQuery('<span/>', {
                        className: 'movie-icon'
                    })

                    $(this).children('img').wrap($imageMovieIconLayer).before($movieIcon)
                }

            } else if (this.hostname !== location.hostname) {
                $(this).after('<span class="external"></span>&nbsp;').addClass("link-icon");
            }
        });
    },

    equalHeightBlurbFollowLink: function (e) {
        var highestCol = Math.max($('.blurb-follow-link1 p').height(), $('.blurb-follow-link2 p').height());
        $('.blurb-follow-link-content p').height(highestCol);
    },

    makeElementALink: function (e) {
        $(e).click(function () {
            window.location = $(this).find("a:first").attr("href");
        });

        /*general class clickable that with status, title & hover*/
        $(e).hover(function () {
            $(this).attr("title", $(this).find("a:first").attr("title"));
            $(this).addClass("hover");
        }, function () {
            $(this).removeClass("hover");
        });
    }

}

$(document).ready(function(){
	
    // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL 
    var autoscrolling = false;
    
    $('.customer-carousel').infiniteCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = false;
    });
    
    setInterval(function () {
        if (autoscrolling) {
            $('.customer-carousel').trigger('next');
        }
    }, 7000);
	
	
	general.init();	
});
