var api = null;
var realIndex = 0;
$(document).ready(function() {
	
	
	
	$('#imgSmall img').click(function() {
		
			var wrap = $('#imgWrap').fadeTo('fast', 0.5);
			var big_img = $(this).attr('target');		
		    $('#bigImg').attr('src', big_img);
		    wrap.fadeTo('fast', 1);
		
		    realIndex = $(this).attr('id');
		    
		/* Change to grey small image */
		   
		
		$('#imgSmall img').each(function (i) {
			this.src = $(this).attr('rel');
		    $(this).attr('active', '0');
		});
		
		$(this).attr('active', '1'); 
		
		
	    $(this).attr({
	    	src: $(this).attr('rev')
	    });
	    	
	});	
	
	
	//give all images an id
	var id = 0
	$('#imgSmall img').each(function() {
		this.id = id;
		id++;
	});
	
	
	
	$('#imgSmall img').hover(
		function () {
			
			element = $(this);

			if( element.attr('active') != 1){
				element.attr({
			    	src: $(this).attr('rev')
				 });
			}
		}, 
		function () { 
			
			element = $(this);
			if(element.attr('active') != 1){
				$(this).attr({
				    	src: $(this).attr('rel')
				 });
			}
		}	      		
		);
	
	
	  $("a[rel]").overlay({ 
		  
	        expose: 'white', 
	        effect: 'apple', 
	 
	        onBeforeLoad: function() { 
	 
	            // grab wrapper element inside content 
	            var wrap = this.getContent().find("#overflowContentWrap"); 
	 
	            // load the page specified in the trigger 
	            wrap.load(this.getTrigger().attr("href")); 

	        } 
	 
	    });

	    // initialize scrollable 
	   $("#imgSmall").scrollable({    	
	    	size:5,
	    	next : '.none',
	    	prev : '.none'
	   
		});
	   
	   
	   api = $("#imgSmall").data("scrollable");
	   
		
		$('#imgSmallWrap .next').click (function() {
			next();
		});

		$('#imgSmallWrap .prev').click (function() {
			prev();
		});
		
	
});



function next () {
	
	realIndex++;
		
	element = api.getItems()[realIndex];
	var wrap = $('#imgWrap').fadeTo('fast', 0.5);
	var big_img = $(element).attr('target');		
	$('#bigImg').attr('src', big_img);
	wrap.fadeTo('fast', 1);  
	  
	if(realIndex > 2){
		api.next(500);
	}
	
	
		
	$('#imgSmall img').each(function (i) {
		this.src = $(this).attr('rel');
	    $(this).attr('active', '0');
	});
	
	$(element).attr('active', '1'); 
	$(element).attr({
		 src: $(element).attr('rev')
	});
	
	
}

function prev () {
	
	realIndex--;
	
	element = api.getItems()[realIndex];
	var wrap = $('#imgWrap').fadeTo('fast', 0.5);
	var big_img = $(element).attr('target');		
	$('#bigImg').attr('src', big_img);
	wrap.fadeTo('fast', 1);  
	  
	if(realIndex < api.getItems().size()-3){
		api.prev(500);
	}
	
	$('#imgSmall img').each(function (i) {
		this.src = $(this).attr('rel');
	    $(this).attr('active', '0');
	});
	
	$(element).attr('active', '1'); 
	$(element).attr({
		 src: $(element).attr('rev')
	});
	
	
}

