(function($){
    var defaults = {
        data: null,
        startIndex: 0,
        endIndex: 0,
        speed: 500,
        autoScroll: true,
        autoScrollTimeout: false,
        autoScrollPause: 5000
    };
    var options = {};
    var currentIndex = 0;

    var $_iVouch = null;
    var $_iVouchStats = null;
    var $_iVouchScroll = null;
    var $_iVouchReviews = null;
    var $_iVouchReviewsList = null;
    var $_iVouchFooter = null;

    $.fn.iVouch = function(iVouchOpts){
        options = $.extend(defaults, iVouchOpts);
        $.fn.iVouchLoading.stop();

        options.endIndex = options.data.reviews;
        options.startIndex = Number(Math.floor(Math.random() * options.endIndex));
        currentIndex = options.startIndex;

        $_iVouch = $('.ivouch_content');
        $_iVouchStats = $('.ivouch_stats');
        $_iVouchScroll = $('.ivouch_scroll');
        $_iVouchReviews = $('.ivouch_reivews');
        $_iVouchReviewsList = $('#ivouch_reviews_list');
        $_iVouchFooter = $('.ivouch_controls');

        $.fn.updateDOM.iVouchStats();
        $.fn.updateDOM.iVouchFooter();

        // Attach our controls
        $('#ivouch_prev').bind('click', {d: 'p'}, mouseClickHandle);
        $('#ivouch_next').bind('click', {d: 'n'}, mouseClickHandle);
        $_iVouch.bind('mousewheel', mouseWheelHandle);

        $.each(options.data, function(k, v){
            var k, v;
            if (k != 'reviews' && k != 'vouches' && k != 'stars') createReview(k, v);
        });

        $.fn.iVouchLoading.stop();
        $_iVouchStats.css('display', 'block');
        $_iVouchReviews.css('display', 'block');
        $_iVouchFooter.css('display', 'block');
        fixHeight();
        scroll(currentIndex);
    };

    $.fn.iVouchLoading = {
        isLoading: true,
        start: function(){
            $.fn.iVouchLoading.run();
        },

        run: function(){
            if ($.fn.iVouchLoading.isLoading) $("#ivouch_icn").fadeTo(500, 0.20).fadeTo(500, 1.0, $.fn.iVouchLoading.run);
        },

        stop: function(){
            $.fn.iVouchLoading.isLoading = false;
            $.fn.iVouchLoading.clear();
        },

        clear: function(){
            $('.ivouch_load').css('display', 'none');
        }
    };

    $.fn.updateDOM = {
        iVouchStats: function(){
            var iVouchReviews = 0,
                iVouchVouches = 0,
                iVouchStars = 0;

            if (options.data.reviews) iVouchReviews = options.data.reviews;
            if (options.data.vouches) iVouchVouches = options.data.vouches;
            if (options.data.stars) iVouchStars = options.data.stars;

            $($_iVouchStats.children('.vouches').get(0)).html(iVouchVouches + ' Vouches');
            $($_iVouchStats.children('.reviews').get(0)).html(iVouchReviews + ' Reviews');
        },

        iVouchFooter: function(){
            $($_iVouchFooter.children('span').get(0)).html((currentIndex + 1) + ' of ' + options.endIndex);
        }
    };

    function mouseClickHandle(event){
        var event;

        if (event.data.d == 'p') scroll('prev', true);
        if (event.data.d == 'n') scroll('next', true);
        return false;
    };

    function mouseWheelHandle(event, delta){
        var event, delta;

        if (delta > 0) scroll('prev', true);
        if (delta < 0) scroll('next', true);
        return false;
    };

    function createReview(i, d){
        var i, d, titleCut = '';
        if (d.title.length > 23) titleCut = '...';

        var reviewDateF = new Date(parseInt(d.date)*1000);
        $_iVouchReviewsList.append('<li id="ivouch_side_review_' + i + '"><a http://www.ivouch.com' + d.url + '" target="_blank" class="title">' + ucWords(d.title.substr(0, 23)) + titleCut + '</a><br /><span class="date">' + reviewDateF.getMonth() + '/' + reviewDateF.getDay() + '/' + reviewDateF.getFullYear() + ' by ' + ucWords(d.author) + '</span><br /><p class="review">' + d.text.substr(0, 400) + '... <a href="http://www.ivouch.com' + d.url + '" target="_blank">Read Full &raquo;</a></p></li>');
    };

    function scroll(d, c){
        var d, c, nextIndex = false;
        if (c){options.autoScroll = false;clearTimeout(options.autoScrollTimeout);}

        if (Number(d)){
            if (d < currentIndex) nextIndex = parseInt(currentIndex - 1)
            if (d > currentIndex) nextIndex = parseInt(currentIndex + 1);
            if (d == currentIndex) nextIndex = parseInt(currentIndex);
        }else{
            if (d == 'prev') nextIndex = parseInt(currentIndex - 1);
            if (d == 'next') nextIndex = parseInt(currentIndex + 1);
        }

        if (nextIndex < 0) nextIndex = (options.endIndex - 1);
        if (nextIndex > (options.endIndex - 1)) nextIndex = 0;
        currentIndex = nextIndex;
        $.fn.updateDOM.iVouchFooter();

        var $nextReview = $('#ivouch_side_review_' + nextIndex);
        $_iVouchReviewsList.animate({top: '-' + $nextReview[0].offsetTop + 'px'}, {queue:false, duration:500, complete:fixHeight});

        if(options.autoScroll) options.autoScrollTimeout = setTimeout(function(){scroll('next');}, options.autoScrollPause);
    };

    function fixHeight(){
        var $currentReview = $('#ivouch_side_review_' + currentIndex);
        $_iVouchScroll.animate({height: $currentReview.height() + 'px'}, {queue:false, duration:200});
    };

    function ucWords(str){return (str+'').replace(/^(.)|\s(.)/g,function ($1){return $1.toUpperCase();});};
})(jQuery);
