//            $(".scrollerWrapper").contentScroller({
//                scrollEnabled: true,
//                scrollInterval: 8000,
//                navButtonsWidth: '0px',
//                navButtonNext: 'scrollNext', //The id of the Next button
//                navButtonPrev: 'scrollPrev', //The id of the Prev button
//                navPanel: 'scrollerNavPanel' //The Scroller additional navigation panel
//            });

jQuery.fn.contentScroller = function(options)
{
    var settings = {
        navButtonsWidth:     "15px",
        
        scrollEnabled:       false,
        scrollInterval:      "1000"
        
    };
    settings = jQuery.extend(settings, options);
    return this.each(function() {
        var currentDOMObject    = this;
        var scrollerName        = 'ContentScrollerInstance' + Math.round((Math.random()*9000)+1);    
        curScrollerElement  = new contentScroller(settings, currentDOMObject, scrollerName)        
    });
};

function contentScroller(settings, currentDOMObject, scrollerElementName) {
    this.settings   = settings;
    this.rootDivId  = scrollerElementName;    
    
    this.createInitialLayout(currentDOMObject);    
    this.setInitialHandlers();
    
    var curContentScrollerObj = this;
    
    if(settings['scrollEnabled']) {
        this.intervalId = setInterval(function(){curContentScrollerObj.scrollThreePositionsLeft();}, settings['scrollInterval']);
    }
    
    

}

contentScroller.prototype.createInitialLayout = function(currentDOMObject) {
    //returnt the constants:
    //this.rootDiv
    //this.innerBlock
    //this.navButtonPrev
    //this.navButtonNext
    
    //Initial settings
    this.width      = $(currentDOMObject).width();
    this.height     = $(currentDOMObject).height();    
    this.entriesCount  = 0;
    this.entriesLength = 0;
    
    //Copying the content of the scrolled block
    var entriesArr   = new Array();
    var portionWidth = 0;
    $(currentDOMObject).find('div.product_block').each(function (){
        portionWidth += parseInt($(this).width());
        entriesArr.push($(this).clone());
    });
    this.portionWidth = portionWidth;
    this.portionCount = entriesArr.length;
    
    //Replacing the HTML element with the own wrapper
    $(currentDOMObject).replaceWith('<div id="'+this.rootDivId+'" class="contentScroller_wrapper" style="width:'+this.width+'px; min-height:'+this.height+'px;"></div>');
    this.rootDiv = $('#'+this.rootDivId);
    
    //Placing navigation buttons & inner block to the wrapper
    var innerBlockWidth = this.width - 2*parseInt(this.settings['navButtonsWidth']);
    var navButtonsWidth = this.settings['navButtonsWidth'];
    $('<div class="contentScroller_next" style="width: '+navButtonsWidth+';min-height:'+this.height+'px;height:'+this.height+'px;"></div>').appendTo(this.rootDiv);    
    $('<div class="contentScroller_data" style="width: '+innerBlockWidth+'px;min-height:'+this.height+'px;height:'+this.height+'px;"></div>').appendTo(this.rootDiv);    
    $('<div class="contentScroller_prev" style="width: '+navButtonsWidth+';min-height:'+this.height+'px;height:'+this.height+'px;"></div>').appendTo(this.rootDiv);
    
    //Reinserting the scrolled block content to the created div
    $('<div class="contentScroller_inner"</div>').appendTo(this.rootDiv.find('.contentScroller_data'));
    this.innerBlock    = this.rootDiv.find('.contentScroller_inner');
    this.navButtonPrev = this.rootDiv.find('.contentScroller_prev');
    this.navButtonNext = this.rootDiv.find('.contentScroller_next');
    var totalWidth = 0;
    var isContentEnoughSpace = false;
    for (var j=0; j<5; j++) {
        var curPortionEntry = $('<div class="contentScroller_innerPortion"></div>');
        curPortionEntry.appendTo(this.innerBlock);
        var portionWidth = 0;
        for (var i=0; i<entriesArr.length; i++) {
            curEntry = $('<div class="contentScroller_innerEntry"></div>');
            curEntry.appendTo(curPortionEntry)            
            entriesArr[i].appendTo(curEntry);
            //Important string! the entry should be cloned again.
            entriesArr[i] = entriesArr[i].clone();
            totalWidth +=parseInt(curEntry.width());
            portionWidth +=parseInt(curEntry.width());
        }
        if (innerBlockWidth >= this.portionWidth) {
            break;
        }
        
    }
    
    this.innerBlock.css('width', totalWidth+'px');
    if (innerBlockWidth < this.portionWidth) {
        this.innerBlock.css('left', -2*this.portionWidth+'px');
    }
    
    var curContentScrollerObj = this;
    
    //Inserting the Interval handlers
    if(this.settings['scrollEnabled']) {
        this.rootDiv.bind("mouseenter",function(){
            if (curContentScrollerObj.intervalId) {
                clearInterval(curContentScrollerObj.intervalId);
                curContentScrollerObj.intervalId = null;
            }
        }).bind("mouseleave",function(){            
            curContentScrollerObj.intervalId = setInterval(function(){curContentScrollerObj.scrollThreePositionsLeft();}, curContentScrollerObj.settings['scrollInterval']);   
            //$('#status').text(curContentScrollerObj.intervalId);
        });
    }
    
    //Inserting the Interval handlers if external navigation panel enabled
    if(this.settings['scrollEnabled']) {
        if(this.settings['navPanel']) {
            $("#"+this.settings['navPanel']).bind("mouseenter",function(){
                if (curContentScrollerObj.intervalId) {
                    clearInterval(curContentScrollerObj.intervalId);
                    curContentScrollerObj.intervalId = null;
                }
            }).bind("mouseleave",function(){            
                curContentScrollerObj.intervalId = setInterval(function(){curContentScrollerObj.scrollThreePositionsLeft();}, curContentScrollerObj.settings['scrollInterval']);   
                //$('#status').text(curContentScrollerObj.intervalId);
            });
        }
    }    
}

contentScroller.prototype.setInitialHandlers = function() {
    //Initilize the events logics of the plugin. Such as navigation keys etc.
    var curContentScrollerObj = this;
    
    var innerBlockWidth = parseInt(this.rootDiv.find('.contentScroller_data').width());
    if (this.portionWidth <= innerBlockWidth) {
        return;
    }
    
    this.leftItem = 0;
    
    this.navButtonPrev.addClass('contentScroller_navActive');
    this.navButtonNext.addClass('contentScroller_navActive');
    
    this.registeredAnimation = false;
    
    //Disabling the scrolling in a way, if external navigation panel enabled
    if (this.settings['navButtonNext']) {
        $("#"+this.settings['navButtonNext']).click(function (){
            if (!curContentScrollerObj.registeredAnimation) {
                curContentScrollerObj.registerAnimation();
                curContentScrollerObj.scrollOnePositionLeft();
                //curContentScrollerObj.scrollThreePositionsRight();
            }
        });
    }    
    if (this.settings['navButtonPrev']) {
        $("#"+this.settings['navButtonPrev']).click(function (){
            if (!curContentScrollerObj.registeredAnimation) {
                curContentScrollerObj.registerAnimation();
                curContentScrollerObj.scrollOnePositionRight();            
                //curContentScrollerObj.scrollThreePositionsLeft();
            }
        });
    }
    
    this.navButtonPrev.click(function (){
        if (!curContentScrollerObj.registeredAnimation) {
            curContentScrollerObj.registerAnimation();
            curContentScrollerObj.scrollOnePositionLeft();
            //curContentScrollerObj.scrollThreePositionsRight();
        }
    });    
    this.navButtonNext.click(function (){
        if (!curContentScrollerObj.registeredAnimation) {
            curContentScrollerObj.registerAnimation();
            curContentScrollerObj.scrollOnePositionRight();            
            //curContentScrollerObj.scrollThreePositionsLeft();
        }        
    });
}

contentScroller.prototype.scrollOnePositionLeft = function() {
    var curElement = this.leftItem + this.portionCount;
    scrollValue = this.innerBlock.find('div.contentScroller_innerEntry:eq('+curElement+')').width();    
    this.leftItem++;
    if (this.portionCount == this.leftItem) {
        this.leftItem -= this.portionCount;
        //Replace the head to the tail
        curOffsetLeft = parseInt(this.innerBlock.css('left'));
        this.innerBlock.css('left', curOffsetLeft+this.portionWidth+'px');
    }
    this.innerBlock.animate({"left": "-="+scrollValue+"px"}, "fast");
}

contentScroller.prototype.scrollOnePositionRight = function() {
    var curElement = this.leftItem + this.portionCount;
    scrollValue = this.innerBlock.find('div.contentScroller_innerEntry:eq('+(curElement-1)+')').width();
    this.leftItem--;
    if (this.portionCount == -this.leftItem) {
        this.leftItem += this.portionCount;
        //Replace the tail to the head
        curOffsetLeft = parseInt(this.innerBlock.css('left'));
        this.innerBlock.css('left', curOffsetLeft-this.portionWidth+'px');
    }
    this.innerBlock.animate({"left": "+="+scrollValue+"px"}, "fast");
}


contentScroller.prototype.scrollThreePositionsLeft = function() {
    var curElement = this.leftItem + this.portionCount;
    scrollValue = this.innerBlock.find('div.contentScroller_innerEntry:eq('+curElement+')').width() +
                  this.innerBlock.find('div.contentScroller_innerEntry:eq('+(curElement+1)+')').width() +
                  this.innerBlock.find('div.contentScroller_innerEntry:eq('+(curElement+2)+')').width();
    this.leftItem+=3;    
    if (this.leftItem >= this.portionCount) {
        this.leftItem -= this.portionCount;
        //Replace the head to the tail
        curOffsetLeft = parseInt(this.innerBlock.css('left'));
        this.innerBlock.css('left', curOffsetLeft+this.portionWidth+'px');
    }
    this.innerBlock.animate({"left": "-="+scrollValue+"px"}, "slow");
}

contentScroller.prototype.scrollThreePositionsRight = function() {
    var curElement = this.leftItem + this.portionCount*2;
    scrollValue = this.innerBlock.find('div.contentScroller_innerEntry:eq('+(curElement-1)+')').width() +
                  this.innerBlock.find('div.contentScroller_innerEntry:eq('+(curElement-2)+')').width() +
                  this.innerBlock.find('div.contentScroller_innerEntry:eq('+(curElement-3)+')').width();
    
    this.leftItem-=3;
    
    if (-this.leftItem >= this.portionCount) {
        this.leftItem += this.portionCount;
        //Replace the tail to the head
        curOffsetLeft = parseInt(this.innerBlock.css('left'));
        this.innerBlock.css('left', curOffsetLeft-this.portionWidth+'px');
    }    
    this.innerBlock.animate({"left": "+="+scrollValue+"px"}, "fast");    
}



contentScroller.prototype.registerAnimation = function() {
    this.registeredAnimation  = true;
    this.navButtonPrev.removeClass('contentScroller_navActive');
    this.navButtonNext.removeClass('contentScroller_navActive');
    this.navButtonPrev.addClass('contentScroller_navInactive');
    this.navButtonNext.addClass('contentScroller_navInactive');
    
    var curContentScrollerObj = this;
    this.animationHandler    = setTimeout(function(){        
        curContentScrollerObj.registeredAnimation  = false;
        curContentScrollerObj.navButtonPrev.removeClass('contentScroller_navInactive');
        curContentScrollerObj.navButtonNext.removeClass('contentScroller_navInactive');
        curContentScrollerObj.navButtonPrev.addClass('contentScroller_navActive');
        curContentScrollerObj.navButtonNext.addClass('contentScroller_navActive');
    }, 200);
}