var Gallery = function(url) {
	this.initialize(url);
};

Gallery.prototype = {
	bigPhoto : null,
	bigPhotoCnt : null,
	bigPhotoCntH : 0,
	bigPhotoCntW : 0,
	bigPhotoCntR : 0,
	galleries : null,
	galleriesList : null,
	images : null,
	imagesList : null,
	categoriesList : null,
	downloadImages : null,
	downloadImagesList : null,

	loadedGalleries : null,
	categoryGalleries : null,
	loadedImages : null,

	selectedGalleryId : null,
	forcedImageId : 0,

	nextImageId : 0,
	prevImageId : 0,

	prevHash : null,
	prevGal : null,
	prevCat : null,

	initialized : false,
	initialize : function(url) {
		var _g = this;
		this.imagesList = $('#gall-list').empty().jcarousel( {
			initCallback : function(jc, state) {
				if (state == 'init') {
					_g.images = jc;

					jc.buttonPrev.add(jc.buttonNext).mouseenter(function() {
						var _this = $(this);
						if (_this.attr('disabled') != 'true') {
							_this.addClass('hover');
						}
					}).mouseleave(function() {
						$(this).removeClass('hover');
					});
				}
			},
			itemLoadCallback : function(jc, state) {
				if (_g.initialized) {
					for ( var i = jc.first; i <= jc.last; i++) {
						if (jc.has(i))
							continue;

						_g.createGalleryItem(i);
					}
				}
			},
			visible : 5,
			scroll : 5,
			size : 0
		});

		this.galleriesList = $('.inne-galerie').empty().jcarousel( {
			initCallback : function(jc, state) {
				if (state == 'init') {
					_g.galleries = jc;

					jc.buttonPrev.add(jc.buttonNext).mouseenter(function() {
						var _this = $(this);
						if (_this.attr('disabled') != 'true') {
							_this.addClass('hover');
						}
					}).mouseleave(function() {
						$(this).removeClass('hover');
					});
				}
			},
			itemLoadCallback : function(jc, state) {
				if (_g.initialized) {
					for ( var i = jc.first; i <= jc.last; i++) {
						if (jc.has(i))
							continue;

						_g.createCategoryItem(i);
					}
				}
			},
			visible : 5,
			scroll : 5,
			size : 0
		});

		this.categoriesList = $('#nav-pozostale');
		
		this.downloadImages = $('.pobierz-zdj');
		this.downloadImagesList = this.downloadImages.find('ul');

		this.bigPhotoCnt = $('.opis .img').css( {
			'overflow' : 'hidden'
		});
		this.bigPhotoCntH = this.bigPhotoCnt.height();
		this.bigPhotoCntW = this.bigPhotoCnt.width();
		this.bigPhotoCntR = this.bigPhotoCntW / this.bigPhotoCntH;

		var prev = $('a.prev').click(function(event) {
			event.preventDefault();
			_g.selectImage(_g.prevImageId);
		});

		$('a.next').click(function(event) {
			event.preventDefault();
			_g.selectImage(_g.nextImageId);
		}).add(prev).mouseenter(function() {
			$(this).addClass('hover');
		}).mouseleave(function() {
			$(this).removeClass('hover');
		});
		;

		this.initialized = true;

		var _g = this;
		$.get(url, null, function(data, status) {
			data = $(data);
			data.find('categories > category').each(
					function() {
						var _this = $(this);
						var cat = $('<li>').append(
								$('<a>').text(_this.attr('name'))
										.click(
												function(event) {
													event.preventDefault();
													_g.selectCategory(_this
															.attr('id'));
												}).attr('href', '')).attr('id',
								'cat_' + _this.attr('id'));
						_g.categoriesList.append(cat);
					});

			_g.loadedGalleries = data.find('items > item');

			var prevGal = null;
			var prevCat = null;
			var loadByHash = function() {
				var hash = location.hash;

				if (hash.length > 0 && hash.charAt(0) == '#') {
					hash = hash.substring(1);
				}
				var ids = hash.split(',', 2);

				var loadNewest = true;
				var selectedGallery = null;

				if (ids.length && ids[0].length) {
					selectedGallery = _g.loadedGalleries.filter('#' + ids[0]);
					if (selectedGallery.length) {
						loadNewest = false;

						if (ids.length == 2) {
							var id = parseInt(ids[1]);
							if (!isNaN(id)) {
								_g.forcedImageId = id;
							}
						}
					}
				}

				if (loadNewest) {
					selectedGallery = _g.loadedGalleries.eq(0);
				}

				_g.selectCategory(selectedGallery.attr('mmphotocat'));
				_g.selectGallery(selectedGallery.attr('id'), loadNewest);
			};
			loadByHash();
			setInterval(function() {
				if (this.prevHash != location.hash) {
					this.prevHash = location.hash;
					loadByHash();
				}
			}, 200);
		}, 'xml');
	},

	selectCategory : function(categoryId) {
		if (categoryId != this.prevCat) {
			this.prevCat = categoryId;
			this.categoriesList.find('li.active').removeClass('active');
			this.categoriesList.find('li#cat_' + categoryId).addClass('active');
			this.categoryGalleries = this.loadedGalleries
					.filter('[mmphotocat=' + categoryId + ']');

			this.galleries.size(this.categoryGalleries.length);
			this.galleries.reset();
		}
	},

	createCategoryItem : function(itemIdx) {
		var _g = this;
		var gal = _g.categoryGalleries.eq(itemIdx - 1);
		gal.jcIdx = itemIdx;

		var item = $('<a>').click(function(event) {
			event.preventDefault();
			_g.selectGallery(gal.attr('id'));
		}).mouseenter(function() {
			$(this).addClass('hover');
		}).mouseleave(function() {
			$(this).removeClass('hover');
		}).attr('href', location.pathname + '#' + gal.attr('id') + ',0');

		var thumb = $('<img>').load(function() {
			_g.correctThumb($(this), 'span');
			$(this).fadeTo(500, 1);
		}).css( {
			opacity : 0
		});

		item.append($('<span>').addClass('thumb').append(thumb));

		item.append($('<span>').addClass('sp-txt').text(
				gal.find('title').text()));

		item.append($('<span>').addClass('link').text(gal.find('info').text()));

		_g.galleries.add(itemIdx, item);

		thumb.attr('src', gal.find('thumb').text());
	},

	selectGallery : function(galleryId, newest) {
		if (galleryId != this.prevGal) {
			this.prevGal = galleryId;
			var _g = this;
			var gal = this.loadedGalleries.filter('#' + galleryId);

			$.get(gal.attr('url'), null, function(data, status) {
				data = $(data);

				_g.selectedGalleryId = galleryId;

				document.title = data.find('gallery > pageTitle').text();
				$('#nav-page').replaceWith(
						$(data.find('gallery > breadcrumb').text()));
				$('.gal-nazwa').html(data.find('gallery > title').text());
				$('.img-opis').html(data.find('gallery > description').text());

				_g.loadedImages = data.find('gallery > images > image').each(
						function(idx) {
							$(this).attr('jcIdx', idx + 1);
						});

				_g.images.size(_g.loadedImages.length);
				_g.images.reset();
				_g.selectImage(_g.forcedImageId, newest);
				_g.forcedImageId = 0;
			}, 'xml');
		} else {
			this.selectImage(this.forcedImageId, newest);
			this.forcedImageId = 0;
		}
	},

	createGalleryItem : function(itemIdx) {
		var _g = this;
		var img = _g.loadedImages.filter('[jcIdx=' + itemIdx + ']');

		var item = $('<a>').click(function(event) {
			event.preventDefault();
			_g.selectImage(img.attr('id'));
		}).mouseenter(function() {
			$(this).addClass('hover');
		}).mouseleave(function() {
			$(this).removeClass('hover');
		}).attr(
				'href',
				location.pathname + '#' + _g.selectedGalleryId + ','
						+ img.attr('id'));

		var thumb = $('<img>').load(function() {
			_g.correctThumb($(this), 'span');
			$(this).fadeTo(500, 1);
		}).css( {
			opacity : 0
		});

		item.append($('<span>').append(thumb));

		_g.images.add(itemIdx, item);

		var desc = img.find('description').text();
		thumb.attr( {
			'src' : img.find('thumb').text(),
			'alt' : desc,
			'title' : desc
		});
	},

	selectImage : function(imageId, newest) {
		var _g = this;
		
		if (!this.bigPhoto) {
			this.bigPhoto = $('<img>').load(
					function() {
						var _h = _g.bigPhoto.height();
						var _w = _g.bigPhoto.width();
						var _ratio = _w / _h;

						if (_ratio < _g.bigPhotoCntR) {
							_g.bigPhoto.height(_g.bigPhotoCntH);
						} else {
							_g.bigPhoto.width(_g.bigPhotoCntW);
							_g.bigPhoto.css( {
								'paddingTop' : (_g.bigPhotoCntH - _g.bigPhoto
										.height()) / 2
							});
						}
						
						_g.bigPhoto.fadeTo(500, 1);
					});
			this.bigPhotoCnt.append(this.bigPhoto);
		}
		
		var img = this.loadedImages.filter('#' + imageId);
		var idx = parseInt(img.attr('jcIdx'));

		this.imagesList.find('li.active').removeClass('active');
		this.images.scroll(idx - 2);
		this.images.get(idx).addClass('active');

		var prevImageIdx = idx - 1;
		if (prevImageIdx < 1)
			prevImageIdx = this.loadedImages.length;
		this.prevImageId = this.loadedImages.filter(
				'[jcIdx=' + prevImageIdx + ']').attr('id');

		var nextImageIdx = idx + 1;
		if (nextImageIdx > this.loadedImages.length)
			nextImageIdx = 1;
		this.nextImageId = this.loadedImages.filter(
				'[jcIdx=' + nextImageIdx + ']').attr('id');

		this.bigPhoto.stop().fadeTo(500, 0, function() {
			var desc = img.find('description').text();
			_g.bigPhoto.css( {
				'paddingTop' : 0
			}).width('').height('').attr( {
				'src' : img.children('url').text(),
				'alt' : desc,
				'title' : desc
			});
			
			_g.downloadImagesList.empty();
			var files = img.find('file');
			if (files.length) {
				files.each(function() {
					var _this = $(this);
					var a = $('<a>').attr('href', _this.find('url').text()).text(_this.find('description').text());
					$('<li>').append(a).appendTo(_g.downloadImagesList);
				});
				_g.downloadImages.css('visibility', 'visible');
			} else {
				_g.downloadImages.css('visibility', 'hidden');
			}
		});

		if (!newest) {
			this.prevHash = '#' + this.selectedGalleryId + ',' + imageId;
			location.hash = this.prevHash;
		}

	},

	correctThumb : function(img, container) {
		var _h = img.height();
		var _w = img.width();
		var _ratio = _w / _h;
		var _cnt = img.closest(container);
		var _cntH = _cnt.outerHeight();
		var _cntW = _cnt.outerWidth();
		var _cntRatio = _cntW / _cntH;

		if (_ratio < _cntRatio) {
			img.width(_cntW);
		} else {
			img.height(_cntH);
		}
	}
};

