$(document).ready(function() {

	//ajax start handler
	$('#loading').ajaxStart(function() {
  		$(this).show();
	});
	$('#loading').ajaxStop(function() {
  		$(this).hide();
	});
	
	/**********
		IMAGE SEARCHING
	**********/
	
	//tag suggest popup
	$('#tag').keyup(function() {
		
		//get x/y positions of textbox
		var x = this.offsetLeft;
		var y = this.offsetTop;
		
		$('#suggested_tags').css("top", y + 30);
		
		//if nothing in input, hide
		if (this.value.length <= 2) {
			$('#suggested_tags').hide();
			return false;
		}
		
		//alert(y);
		
		//get all tags and show div
		$.post('ajax_tag_suggest.php', {tag: this.value}, function(tags) {
			
			//clear tags list
			$('#suggested_tags').html('');
			
			//loop over each returned tag
			$.each(tags, function(key, value) {
				
				//add tag to suggested list
				$('#suggested_tags').append("<li><a href='#'>"+value+"</a></li>");
				
				//show or hide
				if (tags.length > 0)
					$('#suggested_tags').show();
				else
					$('#suggested_tags').hide();
			});
		}, "json");
	});
	
	//selecting a suggested tag
	$('#suggested_tags li a').live("click", function() {
		//get tag value
		var tag = $(this).html();
		
		//add tag to screen
		$('#tag_list').append("<li rel='"+tag+"'>"+tag+"<a href='#' rel='"+tag+"'><img src='/img/remove-icon.png' /></a></li>");		
		
		//send ajax request
		$.post('ajax_tag_select.php', {action: 'add', tag: tag}, function() {
			getThumbnails(1);
		});
		
		//hide tag suggest box
		$('#suggested_tags').hide();
		
		//clear tag input
		$('#tag').val('');
	});
	
	//removing a selected tag
	$('#tag_list li a').live('click', function() {	
		//get tag
		var tag = $(this).attr('rel');
		
		//remove from list
		$("#tag_list li[rel='"+tag+"']").remove();
		
		//send ajax request
		$.post('ajax_tag_select.php', {action: 'remove', tag: tag}, function() {
			getThumbnails(1);	
		});
	});
	
	//hover over group list
	$('#group_list li').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	//click group list
	$('#group_list li').click(function() {
		//remove group from filter
		if ($(this).hasClass('selected'))
		{
			$.post('ajax_group_select.php', {action: 'remove', group_id: $(this).attr('rel')}, function() {
				getThumbnails(1);
			});
			$(this).removeClass('selected');
		}
		else //add group to filter
		{
			$.post('ajax_group_select.php', {action: 'add', group_id: $(this).attr('rel')}, function() {
				getThumbnails(1);	
			});
			$(this).addClass('selected');
		}
	});
	
	//page navigation
	$('#thumbpages li a').live("click", function() {
		page = $(this).html();
		getThumbnails(page);
	});
	
	/**********
		IMAGE DETAILS
	**********/
	
	//add tag to image
	$('#add_tag').keyup(function(event) {
		//on enter key press
		if (event.keyCode == 13) {
			var tag = this.value.toLowerCase();
			
			if (tag.length > 2) {
				$.post('/ajax_add_tag.php', {image: $('#tag_image_id').val(), tag: tag}, function(data) {
					if (data.status == 'success') {
						$('#image_tags').append("<li rel='"+tag+"'>"+tag+"<a href='#' rel='"+tag+"'><img src='/img/remove-icon.png' /></a></li>");
						$('#add_tag').val('');
					} else {
						alert(data.error);	
					}
				}, "json");	
			} else {
				alert('A tag must be at least 3 characters long.');	
			}
		}	
	});
	
	//remove tag from image
	$('#image_tags li a').live("click", function() {
		//get the tag
		var tag = $(this).attr("rel");
		
		$.post('/ajax_delete_tag.php', {image: $('#tag_image_id').val(), tag: tag}, function(data) {
			if (data.status == 'success') {
				$('#image_tags li[rel='+tag+']').fadeOut('slow');
			} else {
				alert(data.error);	
			}
		}, "json");			
	});
	
	//add image to group
	$('#image_groups li.unselected').live('click', function() {
		//get the group
		var group = $(this).attr("rel");
		
		//add to database
		$.post('/ajax_add_group.php', {image: $('#group_image_id').val(), group: group}, function(data) {
			if (data.status == 'success') {
				$('#image_groups li[rel='+group+']').addClass("selected").removeClass("unselected");	
			} else {
				alert(data.error);
			}		
		}, "json");
	});
	
	//remove image from group
	$('#image_groups li.selected').live('click', function() {
		//get the group
		var group = $(this).attr("rel");
		
		//remove from database
		$.post('/ajax_delete_group.php', {image: $('#group_image_id').val(), group: group}, function(data) {
			if (data.status == 'success') {
				$('#image_groups li[rel='+group+']').removeClass("selected").addClass("unselected");	
			} else {
				alert(data.error);
			}
		}, "json");
	});
	
	//image upload
	$('#uploadimage').submit(function() {
		
		var errors = 0;
		
		var error_msg = "Some requireed data is missing, please complete highlighted fields.";
		
		//for each required input
		$("input[rel='required'], textarea[rel='required']").each(function() {
			if (this.value == "") {
				$(this).prev().addClass("form_error");
				errors++;
			} else {
				$(this).prev().removeClass("form_error");	
			}		
		});
		
		if (errors) {
			alert(error_msg);
			return false;			
		}
		else
			return true;
	});
	
	/**********
		USER DETAILS
	**********/
	
	//user search
	$('#u_search').keyup(function() {
		//if nothing in input, hide
		if (this.value.length <= 2) {
			$('#user_list').html("<li><a href='/users/'>Add new user</a></li>");
			return false;
		}
		
		//get all tags and show div
		$.post('/ajax_user_search.php', {user: this.value}, function(users) {
			
			//clear tags list
			$('#user_list').html('');

			//loop over each returned tag
			$.each(users, function(key, value) {
				//add tag to suggested list
				$('#user_list').append("<li><a href='/users/"+value+"'>"+key+"</a></li>");
			});
			$('#user_list').append("<li><a href='/users/'>Add new user</a></li>");
		}, "json");
	});
	
	//user save
	$('#userdetails').submit(function() {
		
		//has this form already been validated?
		if ($('#validated').val() == 1) {
			return true;	
		}
		
		//user id (if present)
		var user_id = $('#id').val();
		//user name
		var username = $('#username').val();
		
		var errors = 0;
		
		var error_msg = "Some requireed data is missing, please complete highlighted fields.\nPlease note passwords must be 6 characters or greater.";
		
		//for each required input
		$("input[rel='required']").each(function() {
			//if not password
			if (this.id != "p1" & this.id != "p2") {
				//see if value is present
				if (this.value == "") {
					$(this).prev().addClass("form_error");
					errors++;
				} else {
					$(this).prev().removeClass("form_error");	
				}
			} else { //if password
				//if new user
				if (user_id == "") {
					//see if password is present
					if (this.value == "" || this.value.length < 5) {
						$(this).prev().addClass("form_error");
						errors++;
					} else {
						$(this).prev().removeClass("form_error");	
					}					
				}
			}				
		});
		
		//check that passwords match
		if ( (user_id == "" && $('#p1').val() != $('#p2').val()) || ($('#p1').val().length > 0 && $('#p1').val() != $('#p2').val()) ) {
			errors++;
			error_msg = error_msg + "\n\n** Passwords do not match **";	
		}
		
		//check the current username is not in use
		var existing_user = '';
		$.get('/ajax_check_existing_user.php', {id: user_id, username: username}, function(n) {
			existing_user = n;
			if (existing_user == 1) {
				errors++;
				error_msg = error_msg + "\n\n** Username already in use **";	
			}
			if (errors) {
				alert(error_msg);
				return false;			
			} else {
				$('#validated').val(1);
				$('#userdetails').submit();		
			}
		});
		
		return false;
	});
	
	/**********
		GROUP DETAILS
	**********/
	
	//group search
	$('#g_search').keyup(function() {
		//if nothing in input, hide
		if (this.value.length <= 2) {
			$('#group_search').html("<li><a href='/users/'>Add new group</a></li>");
			return false;
		}
		
		//get all tags and show div
		$.post('/ajax_group_search.php', {group: this.value}, function(groups) {
			
			//clear tags list
			$('#group_search').html('');

			//loop over each returned tag
			$.each(groups, function(key, value) {
				//add tag to suggested list
				$('#group_search').append("<li><a href='/groups/"+value+"'>"+key+"</a></li>");
			});
			$('#group_search').append("<li><a href='/groups/'>Add new group</a></li>");
		}, "json");
	});
	
	//group save
	$('#groupdetails').submit(function() {
		
		//has this form already been validated?
		if ($('#validated').val() == 1) {
			return true;	
		}
		
		var errors = 0;
		
		var error_msg = "Some requireed data is missing, please complete highlighted fields.";
		
		//for each required input
		$("input[rel='required']").each(function() {
			if (this.value == "") {
				$(this).prev().addClass("form_error");
				errors++;
			} else {
				$(this).prev().removeClass("form_error");	
			}		
		});
		
		var existing_group = '';
		$.get('/ajax_check_existing_group.php', {groupid: $('#id').val(), groupname: $('#name').val()} , function(n) {
			existing_group = n;
			
			if (existing_group == 1) {
				errors++;
				error_msg = error_msg + "\n\n** Group name already in user **";	
			}
			
			if (errors) {
				alert(error_msg);
				return false;			
			} else {
				$('#validated').val(1);
				$('#groupdetails').submit();	
			}
		
		});
		
		return false;
	});
});

function getThumbnails(page) {
	
	if (page == "undefined")
		page = 1;
		
	$.post('query.php', {page: page}, function(data) {
				
		$('#showthumbs').html(data.html);
		
		if (data.num_pages > 1)
			$('#thumbpages').html(data.page_html).fadeIn();
		else
			$('#thumbpages').hide().html("");
		
	}, "json");
}
