jQuery(document).ready(function () {
  // hide all but first image if we have js
  jQuery('.large-images li:not(:first)').hide();
  // show thumbnails if we have js
  jQuery('.small-images').show();
  // control the visibility of the control buttons
  //jQuery('.large-images img, .controls').bind("mouseenter", showControls).bind("mouseleave", hideControls);
  
  //hideControls();
  
  jQuery('.prev').bind("click", function() {
    prev();
    return false;
  });
  
  jQuery('.next').bind("click", function() {
    next();
    return false;
  });
  
  jQuery('.small-images a').bind("click", function() {
    display(jQuery(this).parent().attr('value'));
    location.href = 'gallery.php#gallery';
    return false;
  });
  
  jQuery('.scroll_left').bind("click", function(){
    moveCarousel('prev');
    return false;
  });
  
  jQuery('.scroll_right').bind("click", function(){
    moveCarousel('next');
    return false;
  });  
});

function prev() {
  var total = jQuery(".large-images li").length;
  var current = jQuery(".large-images li:visible").attr('value');
  if(current > 1) {
    display(parseInt(current)-1);
  } else {
    display(total);
  }
}

function next() {
  var total = jQuery(".large-images li").length;
  var current = jQuery(".large-images li:visible").attr('value');
  if(current < total) {
    display(parseInt(current)+1);
  } else {
    display(1);
  }
}

function display(num) {
  jQuery(".large-images li").hide();
  jQuery(".large-images li[value='"+num+"']").show();
  jQuery('.small-images a').removeClass('selected');
  jQuery(".small-images li[value='"+num+"'] a").addClass('selected');
}

function showControls() {
  jQuery('.controls').show();
}

function hideControls() {
  jQuery('.controls').hide();
}

function moveCarousel(direction) {
  $('.small-images').queue(function() { 
    var cellWidth = 420;
    var endStop = (Math.ceil($('.small-images a').length/4)*cellWidth)*-1;
    var marginLeft = $(this).css("marginLeft"); 
    if (direction == "next") {
      var newValue = (parseInt(marginLeft)-cellWidth);
      if(parseInt(newValue) <= endStop) {
        newValue = 0;
      }
    } else if (direction == "prev") {
      var newValue = (parseInt(marginLeft)+cellWidth);
      if(parseInt(newValue) > 0) {
        newValue = endStop+cellWidth;
      }
    }
    newValue = newValue+'px';
    $(this).animate( {marginLeft: newValue }, 700).dequeue(); 
  });
}

