function validFile(fileName, fileTypes){
	fileName = fileName.toLowerCase();
	parts = fileName.split(".");
	fileType = "." + parts[parts.length-1];
	return (('.'+fileTypes.join(".")).indexOf(fileType) != -1);
}

function isInt(s){
	return parseInt(s,10)===s;
}

(function($){

	function changeColor(newColor){
		if(!newColor) newColor = '#fff';
		$('.wp-ajax-gallery-content').animate({ backgroundColor: newColor }, 800);
	//	$('.navigation a').animate({ color: newColor }, 800);
	}

	function catchClick(e){
		if (!e) var e = window.event;
		
		//check for right click
		if (e.which) rightclick = (e.which == 3);
		else if (e.button) rightclick = (e.button == 2);
		
		if(e.target.nodeName.toLowerCase()=='img'){
			e.cancelBubble = true;
			if (e.stopPropagation)
				e.stopPropagation();
			e.preventDefault();
			return false;
		}
	}

	$(function(){
		$('.show-image-popup').click(function(){
			$("#imageFormPopup").popup('show');
			return false;
		});
		
		$('.save-thumb-order').click(function(){
			$.post(pluginDir + 'includes/galleryForm.php', $('.thumbList').sortable('serialize'), function(data){
	
				GManager.refreshGalleries($(".thumbList").attr('galleryID'));
			});
			return false;
		});
		
		$(document).bind('mousedown', catchClick);
		$(document).bind('contextmenu', catchClick);
		
		$(".prev-gallery")
			.click(GManager.prevPage)
			.bind('mouseover', function(){
				$('img', this).attr('src', pluginDir + 'images/left_button.png');
			})
			.bind('mouseout', function(){
				$('img', this).attr('src', pluginDir + 'images/left_button_trans.png');
			});
			
		$(".next-gallery")
			.click(GManager.nextPage)
			.bind('mouseover', function(){
				$('img', this).attr('src', pluginDir + 'images/right_button.png');
			})
			.bind('mouseout', function(){
				$('img', this).attr('src', pluginDir + 'images/right_button_trans.png');
			});
	});

GManager = {
	Galleries:[],
	
	PerPage : 12,
	
	CurrentPage : 0,
	
	Pages : [],
	
	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(p){
			$(this).stop().hide();
		});
		$(GManager.Pages).each(function(p){
			var show = (p==pageNum);
			if(show)
				$(this).css('opacity', 0).show().each(function(i){
					$li = $(this);
					if(!i)
						$li.find('a').click();
					$li.oneTime( (i + 1) * increment, function(){
						$(this).fadeTo(400, 1);
					});
				})
		});
		return false;
	},
	
	Admin : false,
	
	Proofing : false,
	
	saveGallery : function(f){
		$.post(pluginDir + 'includes/galleryForm.php',$(f).serialize(),function(data){
			if (data == "true") {
				$('#galleryFormPopup').popup('hide');
				GManager.refreshGalleries();
			}
			else 
				alert(data);
		});
	},
	
	saveGallerySort : function(){
		$.post(pluginDir + 'includes/galleryForm.php',$('.galleries').sortable('serialize'),function(data){
			GManager.refreshGalleries();
		})
	},
	
	deleteGallery : function(galleryID){
		if(!confirm("Are you sure you want to delete this gallery?"))return false;
		$.post(pluginDir + 'includes/galleryForm.php',{action:'delete',GalleryID:galleryID},function(data){
			if (data == "true") {
				GManager.refreshGalleries();
			}
			else 
				alert(data);
		});
	},
	
	editGallery : function(galleryID){
		var params = {
			GalleryID : galleryID ? galleryID : "",
			Proofing : GManager.Proofing
		}
		$.post(pluginDir + 'includes/galleryForm.php', 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(galleryID){
		$('.loading').show();
		$('.ajax-gallery-login').hide();
		$(".thumbList").html("");
		$("#imageEdit").hide();
		$('.mainImage').hide();
		
		var params = {
			Proofing : GManager.Proofing
		}
		
		if(!GManager.Admin && GManager.Proofing)
			params.Password = $('.ajax-gallery-login [name=password]').val();
		
		$.post(pluginDir + 'json/galleries.php', params, function(data){
			if (data.Error) {
				alert(data.Error);
				$('.ajax-gallery-login').show();
				$('.loading').hide();
				return false;
			}
				
			GManager.Galleries = data.Galleries ? data.Galleries : [];
			
			$('.galleries').html("");
			
			$(GManager.Galleries).each(function(i){
				var $galleryItem = $('<li />').appendTo('.galleries');
				
				$galleryItem.get(0).Images = this.Images;
				
				if (!i) 
					$galleryItem.addClass("first");
				
				var $galleryLink = $('<a href="#" />').appendTo($galleryItem).text(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 (!i && typeof galleryID != 'number' && typeof galleryID != 'string') 
					$galleryLink.click();
				else 
					if ((typeof galleryID == 'number' || typeof galleryID == 'string') && this.GalleryID == galleryID) 
						GManager.galleryClick(galleryID);
			});
				
			if (GManager.Admin){
				$('.galleries').sortable({
					tolerance: 'pointer',
					delay:5,
					revert:true
				});
			}
		},'json');
	},

	galleryClick :function(gID){
		var gallery;
		var allowed = true;
		$(GManager.Galleries).each(function(){
			gallery = this;
			if (this.GalleryID == gID)
				return false;
		});
		
		$(".thumbList").html("");
		
		GManager.Pages = [];
		var pageNum = -1;
		$(gallery.Images).each(function(i){
			var $li = $('<li class="thumbDiv" id="i_' + this.ImageID + '">').css('opacity', 0).appendTo(".thumbList");
			var $imageLink = $('<a class="thumbNail" href="#" />').bind('click', GManager.thumbClick).appendTo($li).hover(
				function(){
					$(this).stop();
					$(this).fadeTo(300, .6);
				},
				function(){
					$(this).stop();
					$(this).fadeTo(300,1);
				}
			);
			
			var $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', '/' + this.ImageDir + 'thumbs/' + this.FileName);
			
			if (isInt(i/GManager.PerPage)) {
				pageNum++;
				GManager.Pages.push([]);
			}
			
			GManager.Pages[pageNum].push($li.get(0));
		});
		
		GManager.switchPage(0);
		
		if (GManager.Admin) {
			var iframe = $('<iframe src="' + pluginDir + 'includes/imageForm.php?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
			};
			$("#imageFormPopup").html(iframe).popup(options);
			
			$(".thumbList").attr('galleryID', gID);
			
			$(".thumbList").sortable({
				placeholder: 'thumbDiv',
				revert: true,
				cursor: 'move',
				delay:5
			});
		}
		return false;
	},
	
	thumbClick : function(){
		var image = this.image;
		
		if (GManager.Admin){
			$("#imageEdit").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('thumbDiv');
			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', '/' + image.ImageDir + 'thumbs/' + image.FileName);
			
			$('.thumbScroll').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 = '/' + image.ImageDir + image.FileName;
		var $newImg = $('<img />')
			.bind('load', function(){
				$('.loading').hide();
				$('.mainImage').stop().show();
				$('.wp-ajax-galleries .blackdiv').css('background-color', 'transparent');
				$('.mainImage img').stop().fadeTo(350, 0, function(){
					changeColor(newColor);
					
					var sizes = {};
					if($newImg.outerWidth())
						sizes.width = $newImg.outerWidth();
					if($newImg.outerHeight())
						sizes.height = $newImg.outerHeight();
					
					$('.mainImage').animate(sizes, 400, function(){
						$('img', this).stop().show().attr('src', newSrc).fadeTo(350, 1, function(){
							$('.wp-ajax-galleries .blackdiv').css('background-color', '#000');
						});
						$newImg.remove();
					});
				});
			});
		$newImg.css({'opacity' : 0, 'position' : 'absolute'}).prependTo('.wp-ajax-gallery-content').attr('src', newSrc);
		
		return false;
	},

	deleteImage : function(imageID){
		if(!confirm("Are you sure you want to delete this image?"))return false;
		$.post(pluginDir + 'includes/imageForm.php',{action:'delete',ImageID:imageID},function(data){
			if (data == "true") {
				GManager.refreshGalleries($(".thumbList").get(0).gID);
			}
			else 
				alert(data);
		});
	},
	
	updateImage: function(f){
		$.post(pluginDir + 'includes/imageForm.php', $(f).serialize(), function(data){
			if (data == "true") 
				GManager.refreshGalleries(f.GalleryID.value);
			else 
				alert(data);
		});
	}
}
	
})(jQuery);