jQuery(function() { 

$('#pictures').livequery(function() {

	if($('#profileId').html() == null)
		startSlideShow();
});

function startSlideShow() {
	$.post('fish-profiles-data.php', { cmd: 'start_slide_show' }, function(data) { $('#pictures').crossSlide({fade: 1},data); }, 'json');
}

/*
	var pics = [];
	$('.thumbnail').each(function() { 
		var path = $(this).attr('src'); 
		var img_path = path.substr(0, path.lastIndexOf('-')) + '-800.jpg';	
		pics.push(img_path);
	});
	var picsjson = [];
	ct = 0;
	for(var i = 0; i < pics.length; i++) {
	
		if(ct % 2 == 0)
			var pic = { src: pics[i], from: 'top left 1.0x', to: 'bottom right 1.0x', time: 4};
		else
			var pic = { src: pics[i], from: 'bottom right 1.0x', to: 'top left 1.0x', time: 4};		
		picsjson.push(pic);
		ct++;
	}
	$('#previewPic').crossSlide({speed:45, fade: 1},picsjson);
}
*/

    $('#addButton').livequery('click', function() { $('#profile').load('fish-profiles-data.php', {cmd: 'edit', id: -1, out: 'js'}).hide().fadeIn('slow'); });
    $('#editButton').livequery('click', function() { $('#profile').load('fish-profiles-data.php', {cmd: 'edit', id: $('#profileId').html(), out: 'js'}).hide().fadeIn('slow'); });
    $('#viewEditButton').livequery('click', function() { $('#pendingProfile').load('fish-profiles-data.php', {cmd: 'print_pending', id: $('#profileId').html(), out: 'js'}).hide().fadeIn('slow'); $(this).fadeOut(); });    
    $('#hideEditButton').livequery('click', function() { $('#viewEditButton').fadeIn(); $('#pendingProfile').fadeOut().empty(); });    
    $('#commentButton').livequery('click', function() {  $('#comment').load('fish-profiles-data.php', {cmd: 'comment', id: $('#profileId').html(), out: 'js'}).hide().fadeIn('slow');  });    
    $('#commentCancelButton').livequery('click', function() {  $('#comment').fadeOut().empty(); });    
    $('#commentSaveButton').livequery('click', function() { 
    	if($('input[name=comment_vote]:checked').val() != '1' && $('input[name=comment_vote]:checked').val() != '0')
    		alert("Please select either the approve or disapprove radio button.");
	else if($('#comment_text').val().length < 10)
		alert("Please elaborate on why you voted the way you did (10 characters required).");
	else
		$('#comment').load('fish-profiles-data.php', {cmd: 'save_comment', id: $('#profileId').html(), vote: $('input[name=comment_vote]:checked').val(), text: $('#comment_text').val(), out: 'js'}).hide().fadeIn('slow');
			
    });   
    $('#changesAcceptButton').livequery('click', function() { 
		    if(confirm("Are you sure you want to accept these changes?")) {
 			    $('#profile').load('fish-profiles-data.php', {cmd: 'confirm_accept', id: $('#profileId').html(), profile_name: $('#commonName').val(), out: 'js'}).hide().fadeIn('slow');
			    $('#pendingProfile').fadeOut().empty();
		    }
    });
    $('#changesRejectButton').livequery('click', function() { $('#comment').load('fish-profiles-data.php', {cmd: 'reject', id: $('#profileId').html(), out: 'js'}).hide().fadeIn('slow'); });
    $('#rejectCancelButton').livequery('click', function() {  $('#comment').fadeOut().empty(); });    
    $('#rejectConfirmButton').livequery('click', function() { 
		    if($('#reject_text').val().length < 20) {
			    alert("Please provide a more substantive message to the user who submitted the changes.");
			    return;
		    }
		    if(confirm("Are you sure you want to reject these changes and send the private message to the user?")) {
			    $('#profile').load('fish-profiles-data.php', {cmd: 'confirm_reject', id: $('#profileId').html(), profile_name: $('#commonName').val(), text: $('#reject_text').val(), out: 'js'}).hide().fadeIn('slow');
			    $('#pendingProfile').fadeOut().empty();
		    }
    });
  
    $('#cancelButton').livequery('click', function() { $('#profile').load('fish-profiles-data.php', {cmd: 'print', id: $('#profileId').html(), out: 'js'}).hide().fadeIn('slow'); });
    $('#profileForm').livequery(function() { $(this).ajaxForm(); });
	/*
    $('#saveButton').livequery('click', function() { $('#profile').load('fish-profiles-data.php', 
    	{cmd: 'save', 
	id: $('#profileId').html(), 
	common_name: $('#common_name').val(),
	scientific_name: $('#scientific_name').val(),	
	care_difficulty: $('#care_difficulty').val(),
	
	url: $('#url').val(),
	family_name: $('#family_name').val(),
	colors: $('#colors').val(),
	water_type: $('#water_type').val(),
	
	temperament:  $('#temperament').val(),
	description: $('#description').val(),
	origin: $('#origin').val(),	
	diet: $('#diet').val(),		
	size_min: $('#size_min').val(),	
	size_max: $('#size_max').val(),	
	min_temp: $('#min_temp').val(),	
	max_temp: $('#max_temp').val(),	
	ph: $('#Ph').val(),	
	kh: $('#Kh').val(),		
    	out: 'js'
    	}).hide().fadeIn('slow'); });
		
	*/
	
$('.flickrImg').bind('click', function() {
if(confirm('Add pic?')) {
	$.post('fish-profiles-data.php', {cmd: 'upload_picture_flickr', imgUrl: $(this).attr('src'), profileUrl: $(this).attr('profileURI'), profileId: $(this).attr('profileId'), commonName: $(this).attr('commonName')}, function(data) { 		
	// reload approved pictures
	$('#pictures').load('fish-profiles-data.php', {cmd: 'refresh_pictures', id: $('#profileId').html()}).hide().fadeIn('slow');
 });
} else {
	alert('no');
}
});
	
$('#water_type').livequery('change', function() {
	if($('#profileId').html() != -1) {
	
		if($('#water_type').val() == $('#startingWaterType').html()) {
			$('#categoryDiv').load('fish-profiles-data.php', {cmd: 'update_categories', Water_Type: $('#water_type').val(), Category: $('#startingCategory').html() });	
		} else {
			$('#categoryDiv').load('fish-profiles-data.php', {cmd: 'update_categories', Water_Type: $('#water_type').val() });
		}
	} else {
		$('#profile').load('fish-profiles-data.php', {cmd: 'edit', id: '-1', waterType: $('#water_type').val() });		
	}
});
	
$('#care_difficulty').livequery('change', function() {
	$('#careDifficultyBlurb').load('fish-profiles-data.php', {cmd: 'update_care_difficulty_blurb', care_difficulty: $('#care_difficulty').val(), water_type: $('#water_type').val() });
});
	
$('#saveButton').livequery('click', function() { 

	if($('#common_name').val()  == '' || $('#scientific_name').val()  == '' || $('#care_difficulty').val()  == '' || $('#family_name').val()  == '' || $('#temperament').val()  == '' || $('#description').val()  == '' || $('#origin').val()  == '' || $('#diet').val()  == '' || $('#size_min').val()  == '' || $('#size_max').val()  == '') {
		alert('Please make sure you have filled out all fields before proceeding.');
		return;
	}
	
	$.post('fish-profiles-data.php', {cmd: 'is_logged_in'}, function(data) {
		if(data != 1) {
			alert('It appears your session timed out while you were editing the profile. Please open a new browser tab and login again before submitting the profile.');
			return;
		} else {	
			$.post('fish-profiles-data.php', {
				cmd: 'save', 
				
				id: $('#profileId').html(), 
				common_name: $('#common_name').val(),
				scientific_name: $('#scientific_name').val(),	
				care_difficulty: $('#care_difficulty').val(),
				family_name: $('#family_name').val(),
				colors: $('#colors').val(),
				category: $('#category').val(),
				water_type: $('#water_type').val(),
				description: $('#description').val(),
				origin: $('#origin').val(),	
				water_quality: $('#water_quality').val(),
				min_tank_size: $('#min_tank_size').val(),

				temperament:  $('#temperament').val(),
				diet: $('#diet').val(),		
				size: $('#size').val(),			
				
				position: 		$('#position').val(),
				lighting: 		$('#lighting').val(),
				growth_rate: 	$('#growth_rate').val(),
				
				out: 'js'
				},
				function(data) {
					if(data == 'added') {
						alert('Thank you for adding the ' + $('#common_name').val() + ' profile! You will receive a pm when a member of the team has had a chance to review it.');
						window.location.href = 'http://www.tropicalfishkeeping.com/profiles/';
					} else {
					$('#profile').html(data).hide().fadeIn('slow');
					}
				}
			);
		}
	});
});
 
/*
	$('#imageUpload').fileUpload({
		'uploader': 'uploadify/uploader.swf',
		'script': 'fish-profiles-data.php',
		'folder': 'fish-pictures',
		'cancelImg': 'uploadify/cancel.png',
		'auto': true,
		'scriptData': {cmd: 'utest', securitytoken: SECURITYTOKEN}, 
		onComplete: function (evt, queueID, fileObj, response, data) {
			alert("Successfully uploaded: "+response);
		}
	});    
*/

$('#trashPresent').livequery(function() {

$('.thumbnail').livequery(function() {
	$('.thumbnail').draggable({ revert: true });
});

$('#trashCan').livequery(function() {
	$('#trashCan').droppable({
			drop: function(event, ui) {
				if(!confirm("Are you sure you want to delete this picture?")) {
					return;
				}
				$.post('fish-profiles-data.php', {cmd: 'delete_picture', pictureId: $(ui.draggable).attr('picId')}, function(data) { 
					$(ui.draggable).effect('explode');			

					// reload approved pictures
					//$('#pictures').load('fish-profiles-data.php', {cmd: 'refresh_pictures', id: $('#profileId').html()}).hide().fadeIn('slow');
				});
			}})
});

}); //if trashpresent

$('.thumbnail').livequery('mouseenter', function() { 
	var path = $(this).attr('src'); var new_path = path.substring(0, path.indexOf('-160.jpg')) + '-300.jpg'; 
	if($('#previewPicture').length == 0) 
		$('#previewPictureDiv').append('<img id="previewPicture" />');
	$('#previewPicture').attr('src', new_path); 
});

$('.thumbnail').livequery('click', function() { if($('#fullPicture').length == 0) return; var path = $(this).attr('src'); var new_path = path.substring(0, path.indexOf('-160.jpg')) + '-800.jpg'; $('#fullPictureInstructions').html('Click the image below to close it.'); $('#fullPicture').attr('src', new_path); } );
$('#fullPicture').livequery('click', function() { $(this).attr('src', 'media/graphics/spacer.gif'); $('#fullPictureInstructions').empty(); window.location.hash = "#top"});


    	$('#viewPendingPicturesButton').livequery('click', function() { $('#pendingPictures').load('fish-profiles-data.php', {cmd: 'show_pending_pictures', id: $('#profileId').html(), out: 'js'}).hide().fadeIn('slow'); $(this).fadeOut(); });    

		$('#viewPendingPicturesCancelButton').livequery('click', function() { $('#pendingPictures').fadeOut(function() { $(this).empty(); $('#viewPendingPicturesButton').fadeIn(); }); });

    	$('.approvePendingPictureButton').livequery('click', function() { var id = $(this).attr('picture'); jQuery.post('fish-profiles-data.php', {cmd: 'approve_picture', picture_id: id, common_name: $('#common_name').val(), url: $('#url').val(), profile_id: $('#profileId').html()}, function(data) {
		// reload approved pictures
		$('#pictures').load('fish-profiles-data.php', {cmd: 'refresh_pictures', id: $('#profileId').html()}).hide().fadeIn('slow');
		// Close pending box if no more pictures are pending
		if(data == '-1') { 
			$('#pendingPictures').fadeOut(function() { $(this).empty(); });
		} 
		else $('#approvePicture' + id).fadeOut(); 
		}); 
	});    
    	
	$('.rejectPendingPictureButton').livequery('click', function() { var id = $(this).attr('picture'); $('#pictureApprovalButtons' + id).fadeOut(); $('#rejectPictureReason' + id).html('Reason to show user:<br/><textarea id="rejectReason' + id + '" cols="40"></textarea><br/><input class="rejectPendingPictureConfirmButton" picture="' + id + '" type="button" value="Reject"> <input class="rejectPendingPictureCancelButton" picture="' + id + '" type="button" value="Cancel">').hide().fadeIn(); });
	$('.rejectPendingPictureCancelButton').livequery('click', function() { var id = $(this).attr('picture'); $('#pictureApprovalButtons' + id).fadeIn(); $('#rejectPictureReason' + id).fadeOut(function() { $(this).empty(); }); });
	$('.rejectPendingPictureConfirmButton').livequery('click', function() { var id = $(this).attr('picture'); 
			if($('#rejectReason' + id).val().length < 10) {
				alert('Please elaborate on your reason for rejecting the picture.');
				return;
			}
	if(confirm("Are you sure?")) { jQuery.post('fish-profiles-data.php', {cmd: 'reject_picture', picture_id: id, reason: $('#rejectReason' + id).val(), common_name: $('#common_name').val(), url: $('#url').val(), profile_id: $('#profileId').html()}, function(data) { if(data == '-1') { $('#pendingPictures').fadeOut(function() { $(this).empty(); }); } else $('#approvePicture' + id).fadeOut(); }); } });    

	$('#imageUploadButton').livequery(function() {
	new AjaxUpload('imageUploadButton', {action: 'fish-profiles-data.php', name: 'image_file',
			data: { securitytoken: SECURITYTOKEN, cmd: 'upload_picture', profile_id: $('#profileId').html(), profile_url: $('#url').val(), common_name: $('#commonName').val() },         
		onSubmit : function(file , ext) {
			if (! (ext && /^(jpg|JPG|JPEG|jpeg)$/.test(ext))){
				// extension is not allowed
				alert('Error: You must upload a .jpg image.');
				// cancel upload
				return false;
			}
			$('#ajaxLoaderGraphic').html('<img src="ajax-loader.gif">').hide().fadeIn('slow');
		},
		onComplete: function(file, response) { 
			$('#ajaxLoaderGraphic').fadeOut('slow', function(){ $(this).empty();} );
			if($('#viewPendingPicturesButton').attr("disabled") == true) {
				$('#viewPendingPicturesButton').attr("disabled", "");
			}
			$('#viewPendingPicturesButton').click();	
		}
	});
	});
});
