/*
Neat Carousel
By James Mountford
*/
jQuery(document).ready(
  function(){
    
    //get instance of the carousel
    var carousel = jQuery("#carousel");
    
    //images that are visible at any one time
    var visibleimgs = 4;    
    var carouselimgwidth = parseInt(jQuery(".carouselimg").eq(0).outerWidth(true));
    var visibleimgwidth = visibleimgs*carouselimgwidth;
    
    //determine original carousel width
    var carouselwidth = 0;
    jQuery(".carouselimg").removeAttr("id");
    jQuery(".carouselimg", carousel).each(
      function(i){
        carouselwidth += parseInt(jQuery(this).outerWidth(true));
      }
    );
    
    //get amount of possible windows (visible blocks)
    var amountofblocks = carouselwidth/visibleimgwidth;
    
    //use amount of blocks to determine how many you can travel in one direction before jumping to either end
    
    //set the carousel width to account for a clone
    carousel.css({"width":carouselwidth*2 + "px"});
    
    //clone carousel contents
    var imgclone = jQuery(".carouselimg").clone();
    carousel.prepend(imgclone);
    
    var startposition = -carouselwidth;
    
    //set position of carousel to the centre
    carousel.css({"position":"absolute", "top" : "0px", "left" : startposition + "px"});
    
    //left arrow click
    jQuery(".carouselleft").click(
      function(e){
        e.preventDefault();
        //current left value
        var currentleft = parseInt(carousel.css("left"));
        //next left value
        var leftval = (currentleft+visibleimgwidth);
        if(currentleft == 0){
          carousel.css({"left":-(carouselwidth*2)+(visibleimgwidth*2)+"px"});
          leftval = -(carouselwidth*2)+(visibleimgwidth*3);
        }
        if(parseInt(carousel.css("left"))%visibleimgwidth==0){
          carousel.animate({"left":leftval+"px"}, 1000);
        }
      }
    );
    //right arrow click
    jQuery(".carouselright").click(
      function(e){
        e.preventDefault();
        //current left value
        var currentleft = parseInt(carousel.css("left"));
        //next left value
        var leftval = (parseInt(carousel.css("left"))-visibleimgwidth);
        if(currentleft == -(carouselwidth*2)+(visibleimgwidth*2)){
          carousel.css({"left":0+"px"});
          leftval = 0-visibleimgwidth;
        }
        if(leftval == (carouselwidth*3)-visibleimgwidth){
          leftval = 0;
        }
        if(parseInt(carousel.css("left"))%visibleimgwidth==0){
          carousel.animate({"left":leftval+"px"}, 1000);
        }
      }
    );
    
    jQuery(".carouselleft, .carouselright").hover(
      function(){
        if(!jQuery.browser.msie){
          jQuery(this).stop(true, true).animate({'opacity' : 0.7}, 200);
        }
      },
      function(){
        if(!jQuery.browser.msie){
          jQuery(this).stop(true, true).animate({'opacity' : 1}, 200);
        }
      }
    );
  }
);
