$(document).ready(function() {
  
  $('#contractor-gallery-preview .arrow-left').click(function() {
    
    var cur = $('#contractor-gallery-preview .current');
    
    // if it exists then get it's index
    if (cur && cur.length > 0) {
      
      var prev = cur.prev();
      if(prev && prev.length > 0) {
        
        imageAnimate(prev, cur, true);
        
        $('#contractor-gallery-preview .caption').text(prev.children('img').attr('alt'));
        
        var cur_id = prev.children('img').attr('class');
        
      } else {
        
        var last = cur.parent().children(':last');
        if(last && last.length > 0) {
          
          imageAnimate(last, cur, true);
          
          $('#contractor-gallery-preview .caption').text(last.children('img').attr('alt'));
        }
        var cur_id = last.children('img').attr('class');
      } 
    }
    
    var cur_id = cur_id.substring(5);
    var link = $('#contractor-gallery-preview .frame').parent('a');
    link.attr('href', link.attr('href').replace(/\d+/, cur_id));
    return false;
    
  });
  
  $('#contractor-gallery-preview .arrow-right').click(function() {
    
    var cur = $('#contractor-gallery-preview .current');

    // if it exists then get it's index
    if (cur && cur.length > 0) {
      
      var next = cur.next();
      if(next && next.length > 0) {
        
        imageAnimate(next, cur, false);
        
        $('#contractor-gallery-preview .caption').text(next.children('img').attr('alt'));
        var cur_id = next.children('img').attr('class');
        
      } else {
        
        var first = cur.parent().children(':first');
        if(first && first.length > 0) {
          
          imageAnimate(first, cur, false);
          
          $('#contractor-gallery-preview .caption').text(first.children('img').attr('alt'));
          
        }
        var cur_id = first.children('img').attr('class');
      } 
    }
    
    var cur_id = cur_id.substring(5);
    var link = $('#contractor-gallery-preview .frame').parent('a');
    link.attr('href', link.attr('href').replace(/\d+/, cur_id));    
    return false;    
  });
  
});

function imageAnimate(toAdd, toRemove, left){
//  toAdd.addClass('current').children('img').hide().fadeIn(700);
//  toRemove.removeClass('current').children('img').fadeOut(700).hide();

  if (left) {
    toAdd.addClass('current').children('img').css({left: 170}).animate({left: 0}, 500);
    toRemove.children('img').animate({left: -170}, 500, function() { $(this).parent().removeClass('current') });    
  } else {
    toAdd.addClass('current').children('img').css({left: -170}).animate({left: 0}, 500);
    toRemove.children('img').animate({left: 170}, 500, function() { $(this).parent().removeClass('current') });    
  }
}

