GManager = {
	Galleries: [],
	
	PerPage: 12,
	
	CurrentPage: 0,
	
	Pages: [],

	Admin: false,

	Proofing: false,

	prevPage: function(){
		var pageNum = GManager.CurrentPage - 1;
		GManager.switchPage(Math.max(0, pageNum));
		return false;
	},
	
	nextPage: function(){
		GManager.switchPage(GManager.CurrentPage + 1);
		return false;
	},
	
	switchPage: function(pageNum){
		if (!GManager.Pages[pageNum])
			return false;
		
		GManager.CurrentPage = pageNum;
		
		$(".nav-link.next-gallery")[GManager.Pages[pageNum + 1] ? 'show' : 'hide']();
		$(".nav-link.prev-gallery")[pageNum ? 'show' : 'hide']();

		var increment = 50;
		$(GManager.Pages).each(function(){
			$(this).stop().hide();
		});
		$(GManager.Pages).each(function(p){
			var show = (p==pageNum);
			if(show)
				$(this).css('opacity', 0).show().each(function(i){
					var $li = $(this);
					if(!i)
						$li.find('a').click();
					$li.oneTime( (i + 1) * increment, function(){
						$(this).fadeTo(400, 1);
					});
				})
		});
		return false;
	},
	
	saveGallery: function(f){
		var id = f.GalleryID.value;
		$.post(BASE_URL + 'admin/galleries/save/' + id + '.json', $(f).serialize(), function(response){
			if (response.success) {
				$('#galleryFormPopup').popup('hide');
				GManager.refreshGalleries();
			}
			else 
				alert(response.error);
		}, 'json');
	},
	
	saveGallerySort: function(){
		$.post(BASE_URL + 'admin/galleries/save_sort.json', $('.galleries').sortable('serialize'), function(response){
			if(response.success)
				GManager.refreshGalleries();
			else
				alert('Gallery sorting could not be saved.');
		}, 'json');
	},

	saveImageSort: function(){
		$.post(BASE_URL + 'admin/images/save_sort.json', $('.thumb-list').sortable('serialize'), function(response){
			if(response.success)
				GManager.refreshGalleries($(".thumb-list").attr('galleryID'));
			else
				alert('Image sorting could not be saved.');
		}, 'json');
		return false;
	},

	deleteGallery: function(galleryID){
		if(!confirm("Are you sure you want to delete this gallery?"))return;
		$.post(BASE_URL + 'admin/galleries/delete/' + galleryID + '.json', {}, function(response){
			if (response.success) {
				GManager.refreshGalleries();
			}
			else 
				alert(response.error);
		}, 'json');
	},
	
	editGallery: function(galleryID){
		var params = {
			Proofing : GManager.Proofing
		};
		var id = galleryID ? galleryID : "";
		$.post(BASE_URL + 'partial/admin/galleries/edit/' + id, params, function(data){
			var options = {
				closeButton:true,
				center: true,
				overlay: true,
				shadow: true,
				zIndex: 999,
				draggable: true,
				width: 300
			};
			$('#galleryFormPopup').html(data).popup(options).popup('show');
		});
		return false;
	},
	
	refreshGalleries: function(){

		var galleryID = null;
		if(arguments.length)
			galleryID = arguments[0];

		$('.loading').show();
		$('.ajax-gallery-login').hide();
		$(".thumb-list").html("");
		$("#image-edit").hide();
		$('.main-image').hide();
		
		var params = {
			Proofing: GManager.Proofing
		};
		
		if(!GManager.Admin && GManager.Proofing)
			params.Password = $('.ajax-gallery-login [name=password]').val();
		
		$.post(BASE_URL + 'galleries.json', params, function(response){
			if (response.error) {
				alert(response.error);
				$('.ajax-gallery-login').show();
				$('.loading').hide();
				return;
			}

			GManager.Galleries = response.galleries ? response.galleries : [];

			$('.galleries').html("");

			$(GManager.Galleries).each(function(i){
				var $galleryItem = $('<li>');
				$galleryItem.appendTo('.galleries');
				$galleryItem.get(0).images = this.images;

				if(!i)
					$galleryItem.addClass("first");

				var $galleryLink = $('<a href="#" />')
					.appendTo($galleryItem)
					.html(this.Label + '')
					.bind('click', function(){
						GManager.galleryClick(this.gallery.GalleryID);
						return false;
					});
				$galleryLink.get(0).gallery = this;

				if (GManager.Admin) {
					$galleryItem.attr('id', 'g_' + this.GalleryID);

					$('<input class="button-secondary action" type="button" value="Edit" />').appendTo($galleryLink).click(function(e){
						GManager.editGallery(this.parentNode.gallery.GalleryID);
						stopEventPropagation(e);
					});

					$('<input class="button-secondary action" type="button" value="x" />').appendTo($galleryLink).click(function(e){
						GManager.deleteGallery(this.parentNode.gallery.GalleryID);
						stopEventPropagation(e);
					});
				}
			});

			if (typeof galleryID != 'number' && typeof galleryID != 'string')
				$('.galleries li a:first').click();
			else if((typeof galleryID == 'number' || typeof galleryID == 'string'))
				GManager.galleryClick(galleryID);

			if (GManager.Admin){
				$('.galleries').sortable({
					tolerance: 'pointer',
					delay:5,
					revert:true
				});
			}
		}, 'json');
	},

	galleryClick: function(gID){
		var gallery;
		$(GManager.Galleries).each(function(){
			gallery = this;
			if (this.GalleryID == gID)
				return false;
		});
		
		$(".thumb-list").html("");
		
		GManager.Pages = [];
		var pageNum = -1;
		$(gallery.images).each(function(i){
			var $li = $('<li class="thumb-div" id="i_' + this.ImageID + '">').css('opacity', 0).appendTo(".thumb-list");

			var $imageLink = $('<a class="thumbnail" href="#" />');
			$imageLink.bind('click', GManager.thumbClick).appendTo($li).hover(
				function(){
					$(this).stop();
					$(this).fadeTo(300, .6);
				},
				function(){
					$(this).stop();
					$(this).fadeTo(300,1);
				}
			);
			
			var $img = $('<img />');
			$img.bind('load', function(){
				if(this.image.ScrollTop)
					$(this.parentNode).scrollTop(this.image.ScrollTop);
				if(this.image.ScrollLeft)
					$(this.parentNode).scrollLeft(this.image.ScrollLeft);
			});

			$imageLink.get(0).image = this;
			$img.get(0).image = this;
			
			$img.appendTo($imageLink).attr('src', BASE_URL + this.ThumbSrc);
			
			if(isInt(i/GManager.PerPage) || !GManager.Pages.length){
				pageNum++;
				GManager.Pages.push([]);
			}
			
			GManager.Pages[pageNum].push($li.get(0));
		});
		
		GManager.switchPage(0);
		
		if (GManager.Admin) {
			var iframe = $('<iframe src="' + BASE_URL + 'admin/images/upload?GalleryID=' + gID + '" allowtransparency="yes" scrolling="no" frameborder="0" />')
				.css({
					'border': '0px solid #fff',
					'height': "120px"
				});
			
			var options = {
				closeButton: true,
				center: true,
				overlay: true,
				shadow: true,
				zIndex: 999,
				width:400,
				draggable: true
			};
			$("#image-form-popup").html(iframe).popup(options);
			
			$(".thumb-list").attr('galleryID', gID);
			
			$(".thumb-list").sortable({
				placeholder: 'thumb-div',
				revert: true,
				cursor: 'move',
				delay:5
			});
		}
		return false;
	},
	
	thumbClick: function(){
		var image = this.image;
		
		if (GManager.Admin){
			$("#image-edit").show();
			
			var f = document.imageEditForm;
			f.ImageID.value = image.ImageID;
			f.GalleryID.value = image.GalleryID;
			f.Label.value = image.Label;
			f.Color.value = image.Color;
			f.ScrollLeft.value = image.ScrollLeft;
			f.ScrollTop.value = image.ScrollTop;
			
			var $thumbDiv = $("<div />").addClass('thumb-div');
			var $imageDiv = $('<div />').addClass('thumbnail').appendTo($thumbDiv);
			var $imageThumb = $('<img />').appendTo($imageDiv).bind('load', function(){
				if(this.image.ScrollTop)
					$(this.parentNode).scrollTop(this.image.ScrollTop);
				if(this.image.ScrollLeft)
					$(this.parentNode).scrollLeft(this.image.ScrollLeft);
			});

			$imageThumb.get(0).image = image;
			$imageThumb.attr('src', BASE_URL + image.ThumbSrc);
			
			$('.thumb-scroll').html($thumbDiv);
			
			$imageDiv.get(0).f = f;
			$imageDiv.dragScroll();
			
			$imageDiv.get(0).endDrag = function(){
				this.f.ScrollTop.value = $(this).scrollTop();
				this.f.ScrollLeft.value = $(this).scrollLeft();
			};
		}
		
		var newColor = image.Color;
		var newSrc = BASE_URL + image.Src;
		var $newImg = $('<img />')
			.bind('load', function(){
				$('.loading').hide();
				$('.main-image').stop().show();
				$('.ajax-galleries .blackdiv').css('background-color', 'transparent');
				var $img = $('.main-image img');
				$img.stop().fadeTo(350, 0, function(){
					var sizes = {};
					if($newImg.outerWidth())
						sizes.width = $newImg.outerWidth();
					if($newImg.outerHeight())
						sizes.height = $newImg.outerHeight();

					$newImg.hide();
					changeColor(newColor);

					$('.main-image').animate(sizes, 400, function(){
						$img.stop().show().attr('title', image.Label).attr('src', newSrc).fadeTo(350, 1, function(){
							$('.ajax-galleries .blackdiv').css('background-color', '#000');
						});
						$newImg.remove();
					});
				});
			});
		$newImg.css({'opacity' : 0, 'position' : 'absolute'}).prependTo('.galleries').attr('src', newSrc);
		
		return false;
	},

	deleteImage: function(imageID){
		if(!confirm("Are you sure you want to delete this image?"))return;
		$.post(BASE_URL + 'admin/images/delete/' + imageID + '.json', {}, function(response){
			if (response.success) {
				GManager.refreshGalleries($(".thumb-list").attr('galleryID'));
			}
			else 
				alert(response.error);
		}, 'json');
	},
	
	updateImage: function(f){
		var id = f.ImageID.value;
		$.post(BASE_URL + 'admin/images/save/' + id + '.json', $(f).serialize(), function(response){
			if(response.success)
				GManager.refreshGalleries(f.GalleryID.value);
			else 
				alert(response.error);
		}, 'json');
	}
};

$(function(){
	$('.show-image-popup').click(function(){
		$("#image-form-popup").popup('show');
		return false;
	});

	$('.save-thumb-order').click(GManager.saveImageSort);

	$(document).bind('mousedown', stopRightClick);
	$(document).bind('contextmenu', stopRightClick);

	$(".prev-gallery")
		.click(GManager.prevPage)
		.bind('mouseover', function(){
			$('img', this).attr('src', BASE_URL + 'images/left_button.png');
		})
		.bind('mouseout', function(){
			$('img', this).attr('src', BASE_URL + 'images/left_button_trans.png');
		});

	$(".next-gallery")
		.click(GManager.nextPage)
		.bind('mouseover', function(){
			$('img', this).attr('src', BASE_URL + 'images/right_button.png');
		})
		.bind('mouseout', function(){
			$('img', this).attr('src', BASE_URL + 'images/right_button_trans.png');
		});
});