//Fin Carousel
$(document).ready(function(){
	var bCar = document.getElementById('carousel');
	if(bCar==null)
		return;
    //global config	
	var a = $('#carousel .window .belt a'); //collect all panels	
	var aIndex = a.length; //calculate panels index
        var aW = elWidth(a[0]); //get panel width	
	var lastWidth = elWidth('#carousel .window'); //get carousel window width
        var aC = Math.floor(lastWidth / aW); //scrolls count
        var lastPosition = ((aW * aIndex) - lastWidth) + 8;
        
        $('#carousel .window').css({'overflow' : 'hidden'});
		
	//rollovers on carousel buttons    
      $(".opacify").fadeTo(1, 0.5);
      $(".opacify").hover(
        function () {
          $(this).fadeTo("fast", 1);
        },
        function () {
          $(this).fadeTo("normal", 0.5);
        }
      );
		
    //Resize event listener
    window.onresize = function(){    	    	
        if (lastWidth != elWidth('#carousel .window')){
            var curWidth = elWidth('#carousel .window');
            lastPosition = ((aW * aIndex) - curWidth) + 8;
            if (aC >= (aIndex - Math.floor(lastWidth / aW)) && lastWidth < curWidth){
                $("#carousel .window .belt").animate({"left": "-" + lastPosition + "px"}, "slow");
                aC = aIndex;
            }
            if (aC >= (aIndex - Math.floor(lastWidth / aW)) && lastWidth > curWidth){
                aC = aIndex - Math.floor((lastWidth - curWidth) / aW);
            }
            lastWidth = curWidth;                          
        }
    }
    //Element width getter
    function elWidth(elem){
	return $(elem).outerWidth(true);
    }
    //logic
    $("a.next").click(function(){            
        if (aC <= (aIndex -  2)){
            $("#carousel .window .belt").animate({"left": "-="+ aW + "px"}, "slow");
            aC += 1;            
        }
        else if (aC == (aIndex - 1)){
            $("#carousel .window .belt").animate({"left": "-" + lastPosition + "px"}, "slow");
            aC += 1;
        }else{
            $("#carousel .window .belt").animate({"left": "0px"}, "slow");
            aC = Math.floor(lastWidth / aW);
        }
		return false;
    });
 
    $("a.prev").click(function(){
		if (aC == Math.floor(lastWidth / aW)){
            $("#carousel .window .belt").animate({"left": "-" + lastPosition + "px"}, "slow");
            aC = aIndex;
        }else if(aC <= Math.floor(lastWidth / aW) + 1){
			$("#carousel .window .belt").animate({"left": "-8px"}, "slow");
            aC = Math.floor(lastWidth / aW);
		}else if (aC >= 2){
            $("#carousel .window .belt").animate({"left": "+="+ (aW + 8) + "px"}, "slow");
            aC -= 1;
        }else{
			$("#carousel .window .belt").animate({"left": "0px"}, "slow");
            aC = Math.floor(lastWidth / aW);
		}
		return false;
    });
});

