var crsl = $('#imgCarousel'),
	crslLength = $('li', crsl).length,
	backArw = $('.lArw', crsl),
	fwrdArw = $('.rArw', crsl);
backArw.data('d', -1);
fwrdArw.data('d', 1);
function setArwStatus(s) {
	$('.arw', crsl).each(
		function() {
			if (s == true)
				$(this).addClass('inactive');
			else
				$(this).removeClass('inactive');
		}
	);
}
$('.arw', crsl).click(
	function() {
		if (!$(this).hasClass('inactive')) {
			setArwStatus(true);
			var currIdx = $('li', crsl).index($('li.current', crsl)),
				nextIdx = currIdx + $(this).data('d');
			nextIdx = nextIdx < 0 ? crslLength - 1 : nextIdx >= crslLength ? 0 : nextIdx;
				
			$('li:eq('+currIdx+')', crsl).fadeOut(450,
				function() {
					$(this).removeClass('current').removeAttr('style');
					$('li:eq('+nextIdx+')', crsl).hide().addClass('current').fadeIn(450, function() { setArwStatus(false) }).removeAttr('style');
				}
			);
		}
		return !1;
	}
);

var Gallery = function(range, bImg) {
	this.gall = range;
	this.img = bImg;
	this.imgs = [];
	this.curIdx = 0;
	this.nextIdx = 1;
	this.init();
}

$.extend(Gallery.prototype, {
	init: function() {
		var self = this;
		this.createArray();
		this.img.bind('click', function() { self.showImg(self.nextIdx); });
		$('a', this.gall).bind('click',
			function() {
				$(this).parent().addClass('next');
				self.showImg(this.idx);
				return !1;
			}
		);
	},
	createArray: function() {
		var self = this;
		$('a', this.gall).each(
			function(i) {
				this.idx = i;
				self.imgs.push($(this).attr('href'));
			}
		);
		this.total = this.imgs.length;
		console.log(this.imgs);
	},
	showImg: function(idx) {
		var self = this,
			newImg = new Image();
		$('img', this.img).css('visibility', 'hidden');
		this.showLoader();
		newImg.onload = function() {
			var img = $('<img src="'+ self.imgs[idx] +'" />');
			$('img', self.img).remove();
			img.hide().appendTo(self.img).fadeIn(550, function() { self.hideLoader(); }).removeAttr('style');
			self.update();
		}
		newImg.src = this.imgs[idx];
		this.curIdx = idx;
		this.nextIdx = idx + 1 >= this.total ? 0 : idx + 1;
	},
	showLoader: function() {
		this.img.addClass('loading');
	},
	hideLoader: function() {
		this.img.removeClass('loading');
	},
	update: function() {
		$('li', this.gall).removeClass();
		$('li:eq('+this.curIdx+')', this.gall).addClass('current');
	}
});