jQuery(document).ready(function() {
	
	var disableLinks = false;
	
	//global ajax error handler
	jQuery(document).ajaxError(function() {
		toggleAjaxLoading();
	});
	
	//add a new gallery to the gallery list
	jQuery('#addNewGallery').click(function() {

		var titleInput =  jQuery('input[name=gallery_title]');
		
		if(titleInput.val() != "") {
            toggleAjaxLoading();
			jQuery.ajax({ url: options.Ajax_Url, data: { action: 'newgallery', title: titleInput.val() }, type: 'post', success: function(data) {
				
				var res = wpAjax.parseAjaxResponse(data, 'ajax-response');
				var msg = getResponseMessage(res);
                
				if(!res.errors) {
					jQuery('#galleryList').append('<li><input value="'+ titleInput.val() + '" type="text" name="galleryTitles[]" readonly="readonly" /><a class="delete" href="#" title="Delete gallery"></a></li>');
					titleInput.val('');
					showSuccessBox(msg);
				}
				else {
					alert(msg);  
				}
				
				toggleAjaxLoading();
			  }
			});
		}
		else {
			alert("Please enter a gallery title");
		}
		
		return false;
	});
	
	//delete a gallery
	jQuery('#galleryList li .delete').live('click', function(evt){
		if(disableLinks) {
			return false;
		}
		var item = jQuery(evt.currentTarget).parent();
		var r = confirm("You are going to delete this gallery: "+ item.find('input').val() +".\nAll albums and images inside the gallery will be also deleted!\n\nAre you sure?");
		if(r) {
			toggleAjaxLoading();
			jQuery.ajax({ url: options.Ajax_Url, data: { action: 'deletegallery', title: item.find('input').val() }, type: 'post', success: function(data) {
				var res = wpAjax.parseAjaxResponse(data, 'ajax-response');
				var msg = getResponseMessage(res);
				
				item.remove();
				
				if(!res.errors) {
					showSuccessBox(msg);
				}
				else {
					alert(msg);
				}

				toggleAjaxLoading();
			  }
			});
		}
		
		return false;
	});
	
	jQuery('#deleteGalleries').click(function() {
		
		if(jQuery('#galleryList').children().size() == 0) {
			alert('You have no galleries to delete!');
			return false;	
		}
		
		var r = confirm("You are going to delete all galleries.\nAll albums and images inside the galleries will be also deleted!\n\nAre you sure?");
		
		if(r) {
			toggleAjaxLoading();
		
			jQuery.ajax({ url: options.Ajax_Url, data: { action: 'deletegalleries' }, type: 'post', success: function(data) {
				var res = wpAjax.parseAjaxResponse(data, 'ajax-response');
				var msg = getResponseMessage(res);
							
				if(!res.errors) {
					jQuery('#galleryList').empty();
					showSuccessBox(msg);
				}
	  
				toggleAjaxLoading();
			  }
			});
		}

		return false;
	});
	
	//disable all links
	if(jQuery(document).find('.fg-disable-links').length) {
		disableLinks = true;
		jQuery('.fg-disable-links').find('object, .button-secondary, .button-primary').unbind().die().fadeTo(0, 0.5);
		return false;
	};
});