/*global window, cheersDrive, document, jQuery */

var cheersDrive = window.cheersDrive || {};

cheersDrive.enhancedPhotoGallery = {
	init: function () {
		jQuery('div.carPhotoGallery').each(function (i) {
			cheersDrive.enhancedPhotoGallery.enhanceGallery.call(this);
		});
	},
	
	enhanceGallery: function () {
		this.enahncedGallery = new cheersDrive.enhancedPhotoGallery.photoGallery(this);
	}
};

cheersDrive.enhancedPhotoGallery.photoGallery = function (photoGalleryContainerElement) {
	var that = this;
	this.$photoGalleryContainerElement = jQuery(photoGalleryContainerElement);
	this.$photoGalleryThumbNailList = jQuery(jQuery(photoGalleryContainerElement).find('div.thumbnails ul')[0]);
	this.photoCurrentlyDisplayed = this.$photoGalleryContainerElement.find('div.mainPhoto img')[0];
	var photoCurrentlyDisplayedSource = this.photoCurrentlyDisplayed.getAttribute('src');
	this.photoCurrentlyDisplayedSourceStub = photoCurrentlyDisplayedSource.substring(0, photoCurrentlyDisplayedSource.lastIndexOf('_') + 1);
	
	var handleClickEvents = function (event) {
		event.preventDefault();
		if (event.target.tagName.toLowerCase() === 'a') {
			that.changePhotoCurrentlyDisplayed(jQuery(event.target));
		}
	};
	this.$photoGalleryContainerElement.bind('click', handleClickEvents);
};

cheersDrive.enhancedPhotoGallery.photoGallery.prototype = {
	changePhotoCurrentlyDisplayed: function ($targetThumbnailLink) {
		var targetLink = $targetThumbnailLink.attr('href');
		var newPhotoNumber = targetLink.slice(targetLink.lastIndexOf('=') + 1);
		var newPhotoSource = this.photoCurrentlyDisplayedSourceStub + newPhotoNumber + '.jpg';
		
		var removeCurrentClassFromAllThumbs = function (i) {
			var $this = jQuery(this);
			if ($this.hasClass('current')) {
				$this.removeClass('current');
				return false;
			}
		};
		this.$photoGalleryThumbNailList.children('li').each(removeCurrentClassFromAllThumbs);
		
		$targetThumbnailLink.parent('li').addClass('current');
		this.photoCurrentlyDisplayed.setAttribute('src', newPhotoSource);
	}
};

/** @event */
jQuery(document).ready(function () {
	cheersDrive.enhancedPhotoGallery.init();
});