/**
 * @projectDescription	NYLS Web Upload Tool
 *
 * @author	Jesse Cooke, Swipht Technologies
 * @version		1.0	
 */

/**
  * Fires when the document is loaded and ready to be manipulated.
  * @memberOf	JQuery
  */
$(document).ready(function() {
	
	// XHTML Strict 1.0 doesn't allow target="_blank" on a link, so set it programatically.
	$("a[rel*='external']").click(function(e) {
		this.target = '_blank';
	});

	$('#forgot_password').click(function(e) {
		e.preventDefault();
		if ($('#user_name').val().length == 0) {
			alert('Please enter your username.');
			$('#user_name').focus();
		} else {
			$('#loading').show();
			$.ajax({
				url: '/forgot/password',
				type: 'POST',
				data: { user_name: $('#user_name').val() },
				success: function(response) {
					forgottenPasswordMessage('#password_sent');
				},
				error: function(response) {
					forgottenPasswordMessage('#password_not_sent');
				},
				complete: function(response) {
					$('#loading').hide();
				}
			});
		}
	});
	
	/**
	  *	Creates a modal dialog when user clicks 'Add Folder' link.
	  *	See http://docs.jquery.com/UI/Dialog
	  */
	$('#add_directory').click(function(event) {
		// Stop the click from doing what the HTML element wants.
		event.preventDefault();
		
		// Unhide the div we'll use for the UI.
		$("#add_directory_dialog").show();
		
		// Open the dialog.
		$("#add_directory_dialog").dialog({
		
			open: function() {
				// These 2 lines add a class to the buttons in the dialog so we can style them.
				// You'll see this in most dialog usages.
				$('.ui-dialog-buttonpane button:first').addClass('ok-button');
				$('.ui-dialog-buttonpane button:last').addClass('cancel-button');
			},
			
			close: function() {
					// Destroy the dialog so the button classes don't get messed up if a user opens another dialog.
				    $(this).dialog("destroy"); 
			},
			
			buttons: { 
				"Ok": function() {
					// Create the AJAX request to make the directory.
					$.ajax({
						type: "POST",
						url: "/create/dir",
						data: 'name=' + $('#new_directory_name').val(),
						success: function(){
							document.location = '/';
						}
				 	});
				}, 
				
				"Cancel": function() { 
				    $(this).dialog("destroy"); 
				} 
			},
			
			overlay: { 
				opacity: 0.5, 
				background: "black" 
			},
			
			modal: true, 
			resizable: false,
			draggable: false,
			width: 400
		});
	});
	
	/**
	  *	Creates a modal dialog when user clicks 'Add Files' link.
	  *	Allows the user to upload up to 10 files at a time.
	  */
	$('#add_files').click(function(event) {
		event.preventDefault();
		
		$("#upload_files_dialog").show();
		
		$("#upload_files_dialog").dialog({
		
			open: function() {
				embedUploadFlash();
			},
			
			close: function() {
					$('#loading').show();
					document.location = '/';
			},
			
			overlay: { 
				opacity: 0.5, 
				background: "black" 
			},
			
			modal: true,
			resizable: false,
			draggable: false,
			width: 500,
			height: 500
		});
	});
	
	
	/**
	  *	Creates a modal dialog when user clicks 'Delete' link.
	  *	Alerts if no files were created. 
	  */
	$('#delete').bind('click', function(event) {
		event.preventDefault();
		var delete_items = [];
		var items = $(".action-checkbox:checked").each(function() {
			delete_items.push($(this).val());
		});
		var delete_param = 'paths=' + delete_items.join(',');
		if (items.length > 0) {
			$.ajax({
				type: "DELETE",
				url: "/delete",
				data: delete_param,
				success: function(){
					document.location = '/';
				}
		 	});
		} else {
			alert("Please select something to delete.");
		}
	});
	
	/**
	  *	Event delegation is used to fire off the clicks used to browse directories.
	  *	Don't need to rebind new elements this way.
	  */
	$('#content').click(function(e) {
		var el = $(e.target);
		if ( el.is('a.list') ) {
			e.preventDefault();			
			$.ajax({
				type: "get",
				url: el.attr('path'),
				success: function(data, textStatus){
					$('#entries table tbody').html(data);
					$('#delete').css('background-position', '0 -403px');
				}
			});
		} else if (el.parent().hasClass('rename')) {
			var path =  el.parent().attr('path');
			var filename = el.parent().attr('filename');
			e.preventDefault();
			$('#rename_path_dialog').dialog({
				open: function() {
					$('.ui-dialog-buttonpane button:first').addClass('ok-button');
					$('.ui-dialog-buttonpane button:last').addClass('cancel-button');
					$('#rename_path_dialog').show();
					$('#old_path').text(filename);
				},

				close: function() {
					$(this).dialog("destroy");
				},

				buttons: {
					"Ok": function() {
						var newPathName = $('#new_path_name').val();
						if (newPathName.length > 0) {
							$.ajax({
								type: "PUT",
								url: '/rename',
								data: { old_path: path, new_path: newPathName },
								success: function() {
									document.location = '/';
								}
							});
						}
					},
					"Cancel": function() {
						$(this).dialog("destroy");
					}
				},
				overlay: {
					opacity: 0.5,
					background: "black"
				},
				modal: true,
				resizable: false,
				draggable: false,
				width: 400
			});
		} else if (el.is(':checkbox.action-checkbox')) {
			var all = $('.action-checkbox').length;
			var checked = $('.action-checkbox:checked').length;
			
			var somethingChecked = (checked <= all && checked != 0)
			
			var bgPos =(somethingChecked) ? '0 -80px' : '0 -403px';

			$('#delete').css('background-position', bgPos);
		}
	});
	
	/**
	  *	Binds the 'Settings' link to display modal dialog so user can edit their own setttings.
	  *	The user attribute of the settings link will only be created server-side if the user is not an admin.
	  */
	$('#settings[user]').bind('click', function(event) {
		event.preventDefault();
		var userId = $(this).attr('user');
		editUserDialog('/users/edit/' + userId);
	});

	
	// If we're on '/users'
	if($('#user_table').length > 0) {
	
		// Set up the table with the jTPS grid plugin.
		$('#user_table').jTPS( {perPages:[10,25,50,'ALL'],scrollStep:1,scrollDelay:30} );		
		
		// Bind all checkboxes to do an AJAX PUT
		$('#user_table :checkbox').bind('change', function() {
			var el = $('#'+this.id);
			var value = this.value;
			var checked = this.checked;
			var row = $('#row_'+value);
			// The action is either toggling wether the user is an admin or active.
			var action = (this.id.match(new RegExp('^admin'))) ? 'admin' : 'active';
			$.ajax({
				type: "PUT",
				url: '/users/activate/' +  action,
				data: { id: value, checked: checked },
				success: function(response){
					var re = new RegExp('^success');
					if (response.match(re)) {
						row.effect('highlight', {}, 1000);
					}
					else {
						// Highlight to red if an error happens and revert the checkbox.
						row.animate({ backgroundColor: '#f00'}, 1000).animate({ backgroundColor: '#f4f5f6'}, 1000);
						el.attr('checked', !active);
					}
				}
			});		
		});
		
		$('#user_table .delete-link').bind('click', function(event) {
			event.preventDefault();
			var id = $(this)[0].id;
			$("#delete_link_dialog").show();
			$("#delete_link_dialog").dialog({
			
				open: function() {
					$('.ui-dialog-buttonpane button:first').addClass('ok-button');
					$('.ui-dialog-buttonpane button:last').addClass('cancel-button');
				},
				
				close: function() {
						$(this).dialog("destroy"); 
				},
				
				buttons: { 
					"Delete": function() {
						$.ajax({
							type: "delete",
							url: '/users/delete',
							data: { id: id },
							success: function(data, textStatus){
								$('#row_'+id).remove();
								$(this).dialog("destroy");
							}
						});
						$(this).dialog("destroy");				
					}, 
					"Cancel": function() { 
						$(this).dialog("destroy"); 
					} 
				},
				
				overlay: { 
					opacity: 0.5, 
					background: "black" 
				},
				
				modal: true, 
				resizable: false,
				draggable: false,
				width: 400,
				height: 150
			});
		});

	
	$('#users #add_user').bind('click', function(event) {
		event.preventDefault();
		$('#add_user_dialog').dialog({
			open: function() {
				$('#add_user_dialog').load('/users/new').show();
				$('.ui-dialog-buttonpane button:first').addClass('create-button');
				$('.ui-dialog-buttonpane button:last').addClass('cancel-button');
			},

			close: function() { 
				$(this).dialog("destroy");
				$('#user_errors').html('').hide();
			},

			buttons: {
				"Create": function() {
					var data = $('#create_user_form').serialize();
					$.ajax({
						type: "post",
						url: '/users',
						data: data,
						success: function(response) {
							var re = new RegExp('^success');
							if (response.match(re)) {
								document.location = '/users';
							}
							else {
								$('#user_errors').html(response).effect('highlight', {}, 1000);								
							}						
						}
					});					
				},
				"Cancel": function() { 
					$(this).dialog("destroy");
					$('#user_errors').html('').hide();
				}
			},

			overlay: {
				opacity: 0.5,
				background: "black"
			},
			
			modal: true,
			resizable: false,
			draggable: false,
			width: 500,
			height: 600
		});
	});

	$('#users .edit-link').bind('click', function(event) {
		event.preventDefault();
		var url = this.href;
		editUserDialog(url);
	});
	
	$('#user_cancel_button').bind('click', function(event) { event.preventDefault(); document.location = '/users'; } );
	
  if($('#total_number_files').length > 0) {
    $.ajax({
      type: "get",
      url: '/total_number_files',
      success: function(data, textStatus){
        $('#total_number_files').text(data);
      }
    });
  }		
	}
	
	// Using event delegation, capture mouseovers on the #entries table
	$('#entries').bind('mouseover', function(e) {
		var el = $(e.target);
		if (el.hasClass('is-directory-false')) {
			// get the href for the actual file
			var href = el.find('a:not(.rename)').attr('href');
			// generate a new id
			var newId = href.replace(/:|\/|\./g,'_');
			// place the id on the span
			el.find('span.clippy').attr('id', newId);
			
			// if clippy is not already present, embed it.
			if (el.find('object').length == 0) {
				embedClippy('http://archive.citylaw.org'+href.replace('download/uploads/',''), newId);
			}
		}
	});
	
});
// End $(document).ready


/**
  *	Shared function to manage edit user dialog.
  */
var editUserDialog = function(url) {
	$('#edit_user_dialog').dialog({
	
		open: function() {
			$('#edit_user_dialog').load(url).show();
			$('.ui-dialog-buttonpane button:first').addClass('update-button');
			$('.ui-dialog-buttonpane button:last').addClass('cancel-button');
		},
		
		close: function() {
			$(this).dialog('destroy');
			$('#user_errors').html('').hide();
		},
		
		buttons: {
			'Update': function() {
				var data = $('#update_user_form').serialize();
				$.ajax({
					type: 'put',
					url: url,
					data: data,
					success: function(response) {
						var re = new RegExp('^success');
						if (response.match(re)) {
							document.location = '/users';
						}
						else {
							$('#user_errors').html(response).effect('highlight', {}, 1000);
						}
					}
				});
			},
			'Cancel': function() {
				$(this).dialog('destroy');
				$('#user_errors').html('').hide();
			}
		},
		
		overlay: {
			opacity: 0.5,
			background: 'black'
		},
		
		modal: true,
		resizable: false,
		draggable: false,
		width: 500,
		height: 600

		
	});
};


var embedUploadFlash = function() {
	
	$.get('/token', function(data) {

		var flashvars = {
			uploadUrl: '/upload/' + data,
			backgroundColor: '#EDEFF1'
		};
		swfobject.embedSWF("ElementITMultiPowUpload2.swf", "upload_files_dialog", "450", "350", "9.0.0", "expressInstall.swf", flashvars);
	});
};

var embedClippy = function(href, id) {
	var flashvars = {text: href};
	var params = {bgcolor: '#F4F5F6'};
	swfobject.embedSWF("clippy.swf", id, "110", "14", "9.0.0", "expressInstall.swf", flashvars, params);
}

var forgottenPasswordMessage = function(id) {
	$(id).fadeIn();
	setTimeout(function() {
		$(id).fadeOut();
	}, 5000);
}

