/* We have to use the livequery jQuery plugin 
 * because 'change' events do not bubble in IE like
 * they do in standards-compliant browsers. Microsoft
 * is incompetent.
 */



$(document).ready(function() {
	
	//Hide the no-js message and show the email wrapper:
	$('#no-javascript-error').addClass('hide');
	$('#upload-email-wrapper').removeClass('hide');
	
	
	/*Dialogs
	-----------------------------------------------------------------------------------------------*/
			
			//Invalid Email dialog
			$("#invalid-email-dialog").dialog({
						autoOpen: false,
						modal: true,
						buttons: {
							Ok: function() {
								$(this).dialog('close');
							}
						}
			});
			
			//Upload Rules dialog
			$("#upload-rules-dialog").dialog({
						autoOpen: false,
						modal: true,
						buttons: {
							Ok: function() {
								$(this).dialog('close');
							}
						}
			});
	
			//No-files-in-upload-queue dialog
			$('#no-photos-selected-dialog').dialog({
						autoOpen: false,
						modal: true,
						buttons: {
							Ok: function() {
								$(this).dialog('close');
							}
						}
			});
			
			
	//Verify email address:
	$('#email-input').livequery('change', function() {
		var email = $(this).val();	
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		if (!filter.test(email)) {
			$('#invalid-email-dialog').dialog('open');
		} else {
			$('#upload-email-wrapper').fadeOut("fast");
			setTimeout(function() { $('#upload-chooser').fadeIn(); }, 450);
		}
	});
	$('#email-go-button').livequery('click', function() {
		var email = $('#email-input').val();	
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		if (!filter.test(email)) {
			$('#invalid-email-dialog').dialog('open');
		} else {
			$('#upload-email-wrapper').fadeOut("fast");
			setTimeout(function() { $('#upload-chooser').fadeIn(); }, 450);
		}
	});
	
	
	
	//Show the rules dialog when the user clicks the 'rules' link
	$('#rules-link').click(function() {
		$('#upload-rules-dialog').dialog('open');
	});


	//Disable the upload button initially & tell it there's no files in the upload queue:
	$('#upload-start').addClass("ui-state-disabled");
	$('#upload-start').addClass("no-files-in-queue");
	
	
	//Enable the upload button when the user checks the "accept rules" checkbox:
	$('#upload-terms-checkbox').click(function() {
			if ( $(this).is(":checked") ) {	
				$('#upload-start').removeClass("ui-state-disabled");
				$('#upload-start').addClass("ui-state-default");			
			} else {			
				$('#upload-start').removeClass("ui-state-default");
				$('#upload-start').addClass("ui-state-disabled");
			}	
	});
	
	
	
	//Uploadify declaration:
	$('#file-input').fileUpload({ 
		'uploader':  'src/uploadify/uploader.swf', 
		'script':    'src/upload-do.php', 
		//'folder':    '/photos/photos',  //DO NOT USE THIS ATTRIBUTE: We supply the folder directly to the upload script via PHP.
		'cancelImg': 'src/uploadify/cancel.png', 
		'buttonText': 'Add Photos',
		'buttonImg': 'skin_images/upload-add-photo-buttons.jpg',
		'rollover': true,
		
		'multi': true,
		'simUploadLimit': 4,
		'sizeLimit': 4194304,
		'fileDesc': '*.jpg;*.jpeg',
		'fileExt': '*.jpg;*.jpeg',
		'displayData': 'percentage',
		
		'onComplete': function(event, queueID, fileObj, response, data) {			
			$.ajax ({
				type: "POST",
				url: "src/after-upload-tasks.php",
				data: {'photo_filename' : response},
				success: function(result) {
					$('#preview-container').prepend(result);
				}
			});
		},
		
		//custom init function to move the outputed Queue items after the parent element of the element that contains the add photo button.
		'onInit': function() {
			$('#file-input').css('display','none');
			if ($.browser.msie) {
				$('#file-input').after('<div id="' + $('#file-input').attr("id")  + 'Uploader"></div>');
				document.getElementById($('#file-input').attr("id")  + 'Uploader').outerHTML = flashElement;
			} else {
				$('#file-input').after(flashElement);
			}
			$('#file-input').parent().after('<div id="' + $('#file-input').attr('id') + 'Queue" class="fileUploadQueue"></div>');
			
			//returning false stops the default init function from firing:
			return false;
		},
		
		'onSelectOnce': function() {
			$('#upload-instructions').addClass('hide');
			$('#upload-start').removeClass('no-files-in-queue');
		}, 
		
		'onCancel': function(event, queueID, fileObj, data) {
			//Count the numer of files in the upload queue:
			var uploads = data.fileCount;
			
			//if there are no uploads left in the queue, display the instructions again:
			if (uploads == 0 ) {
				$('#upload-instructions').removeClass('hide');
				$('#upload-start').addClass('no-files-in-queue');
			}		
		},
		
		'onAllComplete': function(event, data) {
			$('#upload-greeting').html("Thanks for Sharing!");
			$('#original-greeting').addClass('hide');
			$('#caption-instructions').slideDown("fast");
				
			$('#upload-chooser').slideUp("fast");
			$('#preview-container').slideDown("fast");
		}	
	}); 
	
	
	//Upload button functionality:
	$('#upload-start').click(function() {
		
		//Count the numer of files in the upload queue:
		var uploads = $('.fileUploadQueueItem').length;
		
		//Proceed only if the "accept rules" checkbox is checked & there are files in the queue:	
		if(! $(this).hasClass("ui-state-disabled") && ! $(this).hasClass("no-files-in-queue") ) {
			
			//disable the "agree to terms" checkbox so the user can't change it
			$('#upload-terms-checkbox').attr('disabled', true);
			
			//pass email address to file upload function:
			$('#file-input').fileUploadSettings( 'scriptData', '&email=' + $('#email-input').val() );
		
			//start uploading:
			$('#file-input').fileUploadStart();
		
		} else if (! $(this).hasClass("ui-state-disabled") && $(this).hasClass("no-files-in-queue")) {
			
			//show the 'you didn't pick any photos' error message if there are no photos in the upload queue
			$('#no-photos-selected-dialog').dialog('open');
		}
	});
	
	
	//Clear-List button functionality: 
	$('#clear-uploads').click(function() {
		$('#file-input').fileUploadClearQueue();
		$('#upload-start').addClass("no-files-in-queue");
		$('#upload-instructions').removeClass('hide');
	});
	
	
	//Set database captions when the user enters them in our input fields:
	$('.upload-caption-input').livequery('change', function() {
		
			var caption = $(this).val();
			var initial_name = $(this).attr("id");
			var photo_id = initial_name.replace("upload_caption_", "");
		
			$.ajax ({
				type: "POST",
				url: "src/set-upload-caption-do.php",
				data: {'photo_id' : photo_id, 'caption' : caption}
			});		
	});
		
	
});