/**
 * @author vsa
 */

 $(document).ready(function() {

 	// course gallery functions
	// get current image
	var currentImg = $('.coursegallery .currentimg');
	
	var thumbClick = function(){
		var id = this.id;
		var img = $(this);
		var currentId;
		// create an array of the img id's
		var arr = ['header1','header2','header3'];
		arr.forEach(
			function(element, index, array){
				// get current img
				var img = $('.coursegallery #' + element);
				// disable click event for all imgs
				// and remove the pointer cursor				
				img.unbind('click').css('cursor','default');
				// reset the 'on' thumbnail to default
				if (img.attr('src').indexOf('_on') != -1) {
					// set the current image id
					currentId = element;
					var newImg = img.attr('src').replace('_on', '');
					img.attr('src', newImg);
				}
			}
		);
		// set clicked thumbnail to 'on'
		var newImg = img.attr('src').replace('.jpg', '_on.jpg');
		img.attr('src', newImg);
		// fadeout the current img
		currentImg.animate({opacity: 0}, 200,
			function(){
				// replace the current image with the new one
				var oldImg = $('.coursegallery .currentimg img');
				newImg = oldImg.attr('src').replace(currentId, id);
				oldImg.attr('src', newImg);
				// fadein the new image
				currentImg.animate({opacity: 1.0}, 200,
					function(){
						// reset thumbnails images
						arr.forEach(
							function(element, index, array){
								// get img
								var img = $('.coursegallery #' + element);
								if (img.attr('src').indexOf('_on') == -1) {
									img.bind('click', thumbClick).css('cursor','pointer');
								}
							}
						);				
					}
				);
			}
		);
	}
	
	// init gallery
	function initGallery() {
		// create an array of the img id's
		var arr = ['header1','header2','header3'];
		// disable click event for all imgs
		arr.forEach(
			function(element, index, array){
				// get img
				var img = $('.coursegallery #' + element);
				// if the thumbnail is not the current image
				// set it up to change images
				if (img.attr('src').indexOf('_on') == -1) {
					img.css('cursor', 'pointer').bind('click', thumbClick);
				}
			}
		);
	}
	initGallery();
	
});