/**
 * jQuery zslider
 * 
 * Copyright (c) 2010 Žilvinas Kuusas (zilvinas.kuusas.lt)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 0.1
 * @category visual
 * @package jquery
 * @subpakage ui.zslider
 * @author Žilvinas Kuusas <zilvinas@kuusas.lt>
**/

jQuery.fn.zslider= function(options){
	/* 
	* Default settings 
    */
	var settings = {
		speed: 'normal',
		timeout: 2000,
    	next: '#zslider-next',
		prev: '#zslider-prev'
	};
	
	/*
	* Do not modify
	*/
	var timer;
	var scroller;
	var currentItem = 0;
	var childWidth = 0;
	var childrenTotal = 0;
	var scrollerWidth = 0;
	
	settings = jQuery.extend(settings, options || {});
	
	
	var startTimer = function() {
		timer = setInterval(function(){ nextItem(); }, settings.timeout);
	};
	
	var stopTimer = function() {
	    clearInterval(timer);
	};
	
	var nextItem = function() {
	    currentItem += 1;
	    
	    if (currentItem >= childrenTotal)
	    {
	       currentItem = 0;
	    }

        animate();
	};
	
	var prevItem = function() {
    	currentItem -= 1;
    	
    	if (currentItem < 0)
    	{
    	   currentItem = childrenTotal - 1;
    	}
    	
        animate();
	};
	
	var animate = function() {
        scroller.animate({'marginLeft': -currentItem * childWidth + 'px'}, settings.speed);
	};
	
	/* 
	* Wrapping all passed elements
	*/
	return this.each(function() {	
    	var _this = jQuery(this);
    	var child = _this.children(":first");
//    	childWidth = parseInt(child.css('width')) + parseInt(child.css('marginLeft')) + parseInt(child.css('marginRight')) + parseInt(child.css('paddingLeft')) + parseInt(child.css('paddingRight'));
        childWidth = parseInt(_this.css('width'));

    	childrenTotal = parseInt(_this.children().length);
        scrollerWidth = childrenTotal * childWidth;
        
        _this.children().css('float', 'left');
        _this.css('overflow', 'hidden');
        _this.html('<div class="zscroller">' + _this.html() + '</div>');
        
        scroller = _this.find(".zscroller");
        scroller.css('width', scrollerWidth + 'px');
           
        startTimer();
        
        scroller.hover(function(){
            stopTimer();
        }, function(){
            startTimer();
        });
        
        $(settings.next).hover(function(){
            stopTimer();
        }, function(){
            startTimer();
        });
        
        $(settings.prev).hover(function(){
            stopTimer();
        }, function(){
            startTimer();
        });
        
        $(settings.next).click(function(){
            nextItem();
            return false;
        });
        
        $(settings.prev).click(function(){
            prevItem();
            return false;
        });
	});
};
