var sandstorm = sandstorm || {}

// swipe event should be listened for here as well.

sandstorm.Pipe = function (target, delegate) {
    this.delegate = delegate;
    this.target = target;
    this._currentPage = 1;
    this.rightArrow = target.find(".right-arrow.arrow-button");
    this.leftArrow = target.find(".left-arrow.arrow-button");
    this.counter = target.find(".counter > span");
    this.list = target.find("> ul");
    this.scrollview = null;
    this.animateToX = 0;
    this.cellWidth = parseInt(this.list.find('li:first').width(), 10);
    this.userInteractionEnabled = true;

    if (this.target.hasClass('two-up')) {
        this.perPage = 2;
    }
    else if (this.target.hasClass('three-up')) {
        this.perPage = 3;
    }
    else {
        this.perPage = 1;
    }

    this.totalPages = Math.ceil(this.list.children().length / this.perPage);

    this.updatePageText();

    var scope = this;

    if (this.totalPages > 1) {
        if (this.shouldHideShowArrows()) {
            this.rightArrow.show();
            this.leftArrow.hide();
        }

        this.rightArrow.click(function () {
            scope.next()
        });

        this.leftArrow.click(function () {
            scope.previous();
        });

        if ($.browser.webkit) {
            this.scrollview = new sandstorm.scrollview.HorizontalScrollView(this.list[0], {
                "pageWidth": this.scrollDistance(),
                "totalPages": this.totalPages,
                "delegate": this
            });

        }
        this.counter.parent().show();
    }
    else {
        if (this.shouldHideShowArrows()) {
            this.rightArrow.hide();
            this.leftArrow.hide();
        }

        this.counter.parent().hide();
    }
}



sandstorm.Pipe.prototype.shouldHideShowArrows = function()
{
	return true;
}

sandstorm.Pipe.prototype.scrollViewShouldChangePage = function(scrollView, nextPage, totalPages)
{
	if(nextPage < 0) return false;
	if(nextPage >= totalPages) return false;
	
	return true;
}

sandstorm.Pipe.prototype.scrollViewDidChange = function(scrollView)
{
	this.setCurrentPage(this.scrollview.pageNumber + 1);
    this.updatePageText();
    if (this._currentPage == 1) 
    {
		if(this.shouldHideShowArrows())
		{
			this.leftArrow.hide();
			this.rightArrow.show();
		}
    }
    else if (this._currentPage == this.totalPages) 
    {
		if(this.shouldHideShowArrows())
		{
			this.leftArrow.show();
			this.rightArrow.hide();
		}
    }
    else 
    {
		if(this.shouldHideShowArrows())
		{
			this.leftArrow.show();
			this.rightArrow.show();
		}
    }
}
/*
sandstorm.Pipe.prototype.onTouchComplete = function()
{
	//if(isNaN(this.scrollview.pageNumber)) this.scrollview.pageNumber = 0;
	
	this.setCurrentPage(this.scrollview.pageNumber + 1);
    this.updatePageText();
    if (this._currentPage == 1) 
    {
		if(this.shouldHideShowArrows())
		{
			this.leftArrow.hide();
			this.rightArrow.show();
		}
    }
    else if (this._currentPage == this.totalPages) 
    {
		if(this.shouldHideShowArrows())
		{
			this.leftArrow.show();
			this.rightArrow.hide();
		}
    }
    else 
    {
		if(this.shouldHideShowArrows())
		{
			this.leftArrow.show();
			this.rightArrow.show();
		}
    }
}*/

sandstorm.Pipe.prototype.setCurrentPage = function(value)
{
	var oldValue = this._currentPage;
	this._currentPage = value;
	this.changePageDots(value - 1);
}

sandstorm.Pipe.prototype.changePageDots = function (page) {
    var dotsList = this.target.find(".paging-dots ul li");
    if (dotsList.length == 0) return;
    dotsList.removeClass("selected");
    dotsList.eq(page).addClass("selected");
    if (this.delegate.onPageDotsChangeDelegate) {
        this.delegate.onPageDotsChangeDelegate(this);
    }
}

sandstorm.Pipe.prototype.gotoPage = function(value,time)
{
	time = time ? time : 0;
	if (this.userInteractionEnabled) 
    {
        // value is a 0 based index, pages numbers start at 1
        value = value + 1;
        if (value <= this.totalPages && value > 0) 
        {
        
            this.animateTo(-this.scrollDistance() * (value - 1), time);
            
            this.setCurrentPage(value); // modified above to fix 0 based offset
            this.updatePageText();
            
            if (this._currentPage == 1) 
            {
				if(this.shouldHideShowArrows())
				{
					this.leftArrow.hide();
					this.rightArrow.show();
				}
            }
            else if (this._currentPage == this.totalPages) 
            {
				if(this.shouldHideShowArrows())
				{
					this.leftArrow.show();
					this.rightArrow.hide();
				}
            }
            else 
            {
				if(this.shouldHideShowArrows())
				{
					this.leftArrow.show();
					this.rightArrow.show();
				}
            }
        }
    }
}

sandstorm.Pipe.prototype.shouldGotoNextPage = function()
{
	return this._currentPage < this.totalPages;
}

sandstorm.Pipe.prototype.next = function()
{
	if (this.userInteractionEnabled) 
    {
        if (this.shouldGotoNextPage()) 
        {
			var scope = this;
			this.setCurrentPage(this._currentPage + 1);
			this.updatePageText();
			
            //this.userInteractionEnabled = false;
            /*
             this.list.animate({"left": "-=" + this.scrollDistance() + "px", "useTranslate3d": true}, function(){
             scope.animationComplete();
             })
             */

			var page = this._currentPage == 1 ? 0 : (this._currentPage - 1)
			var targetPosition = ((this.perPage * this.cellWidth) * page ) * -1;
			this.animateTo(targetPosition, 500);
			
			//this.animateTo(this.leftPos() - this.scrollDistance(), 500);
			
			if (this.leftArrow.is(":visible") == false) 
			{
				if(this.shouldHideShowArrows())
				{
					this.leftArrow.show();
				}
            }
            
            if (this._currentPage == this.totalPages) 
            {
				if(this.shouldHideShowArrows())
				{
					this.rightArrow.hide();
				}
            }
        }
        else 
        {
			if(this.shouldHideShowArrows())
			{
				this.rightArrow.hide();
			}
        }
    }
}

sandstorm.Pipe.prototype.shouldGotoPreviousPage = function()
{
	return this._currentPage > 1;
}

sandstorm.Pipe.prototype.previous = function()
{
	if (this.userInteractionEnabled) 
    {
		if (this.shouldGotoPreviousPage()) 
        {
			var scope = this;
			this.setCurrentPage(this._currentPage - 1);
			this.updatePageText();
			
			var page = this._currentPage == 1 ? 0 : (this._currentPage - 1)
			var targetPosition = ((this.perPage * this.cellWidth) * page ) * -1;
			this.animateTo(targetPosition, 500);
			
			//alert(this.leftPos());
			//this.animateTo(this.leftPos() + this.scrollDistance(), 500);
			
            if (this._currentPage == 1) 
            {
				if(this.shouldHideShowArrows())
				{
					this.leftArrow.hide();
				}
            }
            
            if (this.totalPages > 1 &&
            this._currentPage >= 1 &&
            this.rightArrow.is(":visible") == false) 
            {
				if(this.shouldHideShowArrows())
				{
					this.rightArrow.show();
				}
            }
        }
    }
}
/*
sandstorm.Pipe.prototype.leftPos = function()
{
    var leftPos = this.list[0].style.left.replace('px', '');
    leftPos = leftPos ? leftPos : 0;
    
	if (sandstorm.application.currentDevice.platform != sandstorm.useragent.devicePlatform.WindowsMobile) 
    {
    	var xPropStr = this.list.css("-webkit-transform");
        var tempArr = xPropStr.split(",");
        var xTransform = tempArr[4];
        xTransform = xTransform ? xTransform : 0;
    	leftPos = xTransform;
    }    
	return parseInt(leftPos, 10);
}
*/

sandstorm.Pipe.prototype.scrollDistance = function()
{
    if (typeof this.pageSize == 'undefined') 
    {
        //var cellWidth = parseInt(this.list.find('li:eq(0)').css('width'), 10);
        this.pageSize = this.cellWidth * this.perPage;
    }
    return this.pageSize;
    
}

sandstorm.Pipe.prototype.animationComplete = function()
{
    this.userInteractionEnabled = true;
}


sandstorm.Pipe.prototype.updatePageText = function()
{
	if (this.counter) 
    {
        this.counter.text(this._currentPage + "/" + this.totalPages);
    }
}

sandstorm.Pipe.prototype.clearWebKitTransition = function(position)
{
		// Get the computed style object.
		var style = document.defaultView.getComputedStyle(this.list[0], null);

		// Computed the transform in a matrix object given the style.
		var transform = new WebKitCSSMatrix(style.webkitTransform);

		// Clear the active transition so it doesn’t apply to our next transform.
		this.list[0].style.webkitTransition = '';

		// Set the element transform to where it is right now.
		this.list[0].style.webkitTransform = 'translate3d(' + position + 'px, 0, 0)';
}

sandstorm.Pipe.prototype.animateTo = function(xPosition, duration, callback)
{
	var lastXTarget = this.animateToX; // will be used to clear any WebKit transition if we get there.
	this.animateToX  = xPosition;
	duration = duration != undefined ? duration : 0;
    
    if (!$.browser.webkit) 
    {
    	
		if (duration != 0) 
        {
        	this.list.animate({
                left: xPosition,
                "useTranslate3d": true
            }, duration);
        	
        }
        else 
        {
            this.list.css({
                "left": xPosition
            });
        }
    }
    else 
    {
		this.clearWebKitTransition(lastXTarget);
		if(duration > 0)
		{
			this.list[0].style.webkitTransition = '-webkit-transition-delay now';
			this.list[0].style.webkitTransition = '-webkit-transform ' + duration + 'ms ';
		}
		this.list[0].style.webkitTransform = 'translate3d(' + xPosition + 'px, 0, 0)';
    }
	
	if (callback) 
	{
		var target = this.list[0];
		var scope = this;
		this.list[0].addEventListener("webkitTransitionEnd", function()
		{
			return function()
			{
				callback(scope);
				target.removeEventListener("webkitTransitionEnd", arguments.callee);
			}
		}())
	}
	
	
	/*
	this.userInteractionEnabled = false;
	var scope = this;
	setTimeout(function(){
		scope.userInteractionEnabled = true;
	}, duration)
	*/
}

