﻿
function initVars()
{
    currentItem = 1;
    targetXPos = 0;
    Xpos = 0;
    panelSpeed = .3;
    scrollButtons = true;
    
    innerContainer = $('.relatedInnerContainer');
    target = $('#scroller');
    Item = $('#scroller > li');
    
    marginWidth = parseInt(removePx(Item.css("margin-left")));
    ItemWidth = parseInt(removePx(Item.css("width")));
    totalItems = Item.length;
    
    innerContainerWidth = parseInt(removePx(innerContainer.css("width")));
    scrollerWidth = totalItems*(ItemWidth+marginWidth)+marginWidth;
    scrollDistance = scrollerWidth - innerContainerWidth;
    
    visibleAmount = Math.floor(innerContainerWidth / (ItemWidth+marginWidth));
    maxCurrentItem = totalItems - (visibleAmount - 1);
    
    target.css( "width", scrollerWidth );
    
    if( totalItems <= visibleAmount )
    {
		$('.related > span').addClass("inactive");
		$('.related > span').addClass("inactive");
		scrollButtons = false;
    }
}

function removePx(strParam)
{
    result = strParam.replace("px", "");
    
    return result;
}

function goTheFrame()
{
    if( Xpos > targetXPos || Xpos < targetXPos )
    {
        newXpos = Xpos - ((Xpos-targetXPos) * panelSpeed);
        
        if( Math.abs(targetXPos-newXpos) < .5 )
        {
            newXpos = targetXPos;
        }

        target.css("left", newXpos);
        Xpos = newXpos;
    }
}

function scroll(scrollAmount, scrollBoolean)
{
    if(scrollBoolean)
    {
		currentItem += scrollAmount;
	    
		if( currentItem > maxCurrentItem )
		{
			currentItem = 1;
		}
	    
		if( currentItem < 1 )
		{
			currentItem = maxCurrentItem;
		}
	}
	else
	{
		if( scrollAmount > maxCurrentItem)
		{
			scrollAmount = maxCurrentItem;
		}
		
		currentItem = scrollAmount;
	}
	
	newLeftXpos = -((currentItem-1)*(ItemWidth+marginWidth));	
	targetXPos = newLeftXpos;
}


    
$(document).ready(function ()
{
    initVars();
    setInterval("goTheFrame()", 20);
    
    $(".stepLeft").click(function ()
	{
		if(scrollButtons)
		{
			scroll(-1, true);
		}
	});
	    
	$(".stepRight").click(function ()
	{
		if(scrollButtons)
		{
			scroll(1, true);
		}
	});

});