var SspLightbox = {
	
	selectionLimit : 12,
	container : null,
	galleries : null,
	
	init : function () {
		this.container = $("#bigpics");
		if (this.container.length === 0) { return; }
		this.galleries = this.container.find(".gallery");
		if (this.galleries.length === 0) { return; }
		this.setGalleryBehaviours();
	},
	
	setGalleryBehaviours : function () {
		_this = this;
		this.galleries.each(function() {
			var nodes = $(this).find(".images li");
			var nodeCount = nodes.length;
			var nodeClass = "page-";
			var currentPage;
		
			nodes.each(function(i) {
				i++;
				currentPage = Math.ceil((i) / _this.selectionLimit);
				$(this).addClass(nodeClass + currentPage);
				if (i > _this.selectionLimit) {
					$(this).hide();
				}
			});
			
			currentPage = 1;
			var pageCount = Math.ceil(nodeCount / _this.selectionLimit);
			var paging = "<div class=\"gallery-paging\">";
			paging += _this.getPaging(pageCount, currentPage);
			paging += "</div>";
			$(this).append(paging);
			_this.enableLightbox($(this));
		});
		this.setPagingBehaviours();
	},
	
	setPagingBehaviours : function () {
		_this = this;
		var paging = this.container.find(".gallery-paging");
		paging.click(function(e) {
			var obj = $(e.target);
			if (!obj.hasClass("active")) { return; }
			var action = obj.hasClass("previous") ? "previous" : "next";
			var gallery = obj.parents(".gallery");
			var nodes = gallery.find(".images li");
			var nodeCount = nodes.length;
			var pageCount = Math.ceil(nodeCount / _this.selectionLimit);
			var currentPage = nodes.filter(":visible:first").attr("class").split("-")[1];
			if (action == "previous") {	
				currentPage--;
			} else {
				currentPage++;
			}
			nodes.filter(":visible").fadeOut(function() {
				nodes.filter(".page-" + currentPage).fadeIn();
				gallery.find(".gallery-paging").html(_this.getPaging(pageCount, currentPage));
				_this.enableLightbox(gallery);
			});
		});
	},
	
	getPaging : function (pageCount, currentPage) {
		var markup = "<div class=\"page\">" + currentPage + "/" + pageCount + "</div>";
		var prevClass = "pager previous ";
		prevClass += (currentPage > 1) ? "active" : "disabled";
		var nextClass = "pager next ";
		nextClass += (pageCount > currentPage) ? "active" : "disabled";
		markup += "<div class=\"" + prevClass + "\">Previous</div>";
		markup += "<div class=\"" + nextClass + "\">Next</div>";
		return markup;
	},
	
	enableLightbox : function (gallery) {
		var activeNodes = gallery.find(".images li");
		activeNodes.find('a[@rel*=flipbox]').lightBox();
	}
};

$(document).ready(function() {
	SspLightbox.init();
});