/*
 * CP Banner Rotator Javascript
 */

if ("undefined" === typeof (Cloverpoint)) {
    var Cloverpoint = {};
}

Cloverpoint.BannerCountTracker = (function() {
    
    // Private static
    var itemCount = 0;
    var loadedCount = 0;
    
    return function() {
        this.setCount = function (value) {
            itemCount = value;
        };
        this.getCount = function () {
            return itemCount;
        };
        this.setLoadedCount = function (value) {
            loadedCount = value;   
        };
        this.getLoadedCount = function () {
            return loadedCount;  
        };
        this.incLoadedCount = function() {
            loadedCount++;  
        };
    }
})();

Cloverpoint.BannerCallbacks = {
    initBanner : function() {
        var bannerCB = this;
        //console.log("Cloverpoint.BannerCallbacks.initBanner()");
        // JCarousel Plugin
        $('#carousel').jcarousel({
            vertical: true,     // display vertical carousel
            scroll: 1,          // auto scroll
            auto: 5,            // the speed of scrolling
            animation: 400,     // speed of the animation
            wrap: 'circular',       // go bck to the top when reach last item
            initCallback: bannerCB.initCallback,   // extra called back function
            itemFirstInCallback: bannerCB.firstItemCallback    //
        });

        // Front page Carousel - Initial setup
        // Set all the item to full opacity
        $('div#cp-banner-slideshow-carousel a img').css({'opacity': '1.0'});
        
        // Add hover and click event to each of the item in the carousel
        $('div#cp-banner-slideshow-carousel li a').hover(
            function() {
                // check to make sure the item is not selected
                if (!$(this).has('span').length) {
                    // reset all the item's opacity to 50%
                    //$('div#cp-banner-slideshow-carousel li a img').stop(true, true).css({'opacity': '0.5'});
                    
                    // adjust the current selected item to full opacity
                    //$(this).stop(true, true).children('img').css({'opacity': '1.0'});
                }
            },
            function () {
                // on mouse out, reset all the items back to 50% opacity
                //$('div#cp-banner-slideshow-carousel li a img').stop(true, true).css({'opacity': '0.5'});
                
                // reactivate the selected item by loop through them and look for the one
                // that has the span arrow
                $('div#cp-banner-slideshow-carousel li a').each(function() {
                    // found the span and reset the opacity back to full opacity
                    //if ($(this).has('span').length) $(this).children('img').css({'opacity': '1.0'});
                });
            }
        ).click(function() {
            // remove the span.arrow
            //$('span.arrow').remove();
            
            // append it to the current item
            //$(this).append('<span class="arrow"></span>');
            
            // remove the active class from the slideshow main
            $('div#cp-banner-slideshow-main li').removeClass('active');
            
            // display the main image by appending active class to it
            $('div#cp-banner-slideshow-main li.' + $(this).attr('rel')).addClass('active');
            
            return false;
        });
    },
    firstItemCallback: function (carousel, item, index) {
        // Get the count of items
        var banHandler = new Cloverpoint.BannerCountTracker();
        var currentCount = banHandler.getCount();

        //console.log("Carousel current item is: " + $(item).find('a').attr('rel') + " at index: " + index + " and count is: " + currentCount);
        
        
        // Get the current index using string manipulation
        var strReplace = $(item).find('a').attr('rel');
        var num = strReplace.replace(/\D/g,'');
        //console.log("Strings is: " + strReplace + ", but num is: " + num);
        
        /* so we want to change the current image +1, but also make sure
           we are not out of bounds, if we are, reset to beginning */
        if (num == 1) { // if we are at low range, loop back to top.
            num = currentCount;
        } else if (num < currentCount+1) {  // if num is less than current count+1
            num--;
        } else {    // if num is past currentCount 
            num = 1;
        }
        
        // remove the active class, which hides an element
        $('div#cp-banner-slideshow-main li.active').removeClass('active');
        
        
        $('div#cp-banner-slideshow-main li.' + 'p' + num).addClass('active');
    },
    initCallback: function (carousel) {
        // Pause autoscrolling if the user moves with the cursor over the clip.
        // resume otherwise
        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });
    }
}


$(document).ready(function() {    
    var loadedFlag = false;

    $('#cp-banner-slideshow-container div#cp-banner-slideshow-main').hide();
    $('#cp-banner-slideshow-container div#cp-banner-slideshow-carousel').hide();

    var itemLength = $('#carousel').children().length;
    var bannerHandler = new Cloverpoint.BannerCountTracker();
    bannerHandler.setCount(itemLength);
    
    var bannerCB = Cloverpoint.BannerCallbacks;

    $('#cp-banner-slideshow-gallery img').each(function() {
        var bannerHandlerLoc = new Cloverpoint.BannerCountTracker();
        var bannerCBLoc = Cloverpoint.BannerCallbacks;
        //console.log("iterating through image id: " + this.src);
        $(this).load(function() {
            //console.log("Image Loaded!");
            //$('#cp-banner-slideshow-gallery').trigger("load");
            bannerHandlerLoc.incLoadedCount();
            if (bannerHandlerLoc.getLoadedCount() == bannerHandlerLoc.getCount()) {
                //console.log("loading banner");
                //$("#cp-banner-preloader").fadeOut('fast');
                $('#cp-banner-preloader-container').fadeOut().children().fadeOut();
                $('#cp-banner-slideshow-container div#cp-banner-slideshow-main').fadeIn();
                $('#cp-banner-slideshow-container div#cp-banner-slideshow-carousel').fadeIn();
                bannerCBLoc.initBanner();
            }
        });
        $(this).error(function() {
            //console.log("Image is not loaded!");
        });
        // Cached images
        if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) > 6)) {
            //console.log("cached images");
            //$(this).load();
            $(this).trigger("load");
        }
    });
  
});
