var LOADING		= '<img src="'+SITE_URL+'images/loading.gif" class="loading" />';

/**
 * Allows me to reset forms :)
 */
$.fn.extend({
	reset: function() {
		return this.each(function() {
			$(this).is('form') && this.reset();
		});
	}
});

$(document).ready(function() {
	// Add the odd class to every other table row
	$("tr:nth-child(odd)").addClass("odd");
	
	// Make the "label" for form fields appear in the field
	// Do this by making the label the title of the input
	/*
	$('input[title]').each(function() {
		if($(this).val() === '') {
			$(this).val($(this).attr('title'));
		}
		
		$(this).focus(function() {
			if($(this).val() === $(this).attr('title')) {
				$(this).val('').addClass('focused');
			}
		});
		
		$(this).blur(function() {
			if($(this).val() === '') {
				$(this).val($(this).attr('title')).removeClass('focused');
			}
		});
	});
	*/
	
	////////////////////////
	// Sitewide listeners //
	////////////////////////
	
	/**
	 * Used to show/hide help in the sidebar
	 * Sidebar help should be in the form:
	 * <div class="sidebar-help">
	 * 		<span><a href="#">Help</a></span>
	 * 		<div class="hidden">
	 * 			Content of the help 
	 * 		</div>
	 * </div>
	 */
	$('.sidebar-help a:first').click(function(event) {
		event.preventDefault();
		
		var div = $(this).parent().parent().find('div:first');
		if(div.is(':visible')) {
			div.addClass('hidden');
		} else {
			div.removeClass('hidden');
		}
	});
	
	/**
	 * This makes all the help in the sidebar visible by default
	 * To hide it by default, delete this function of comment out the body of it
	 */
	$('.sidebar-help').each(function() {
		var div = $(this).find('div:first').removeClass('hidden');
	});
	
	// There will be lots of places with more info hidden but preloaded
	// The text will change to the content of the title tag when we click on it
	$('a.show-more').live('click', function(event) {
		event.preventDefault();
		
		var oldText = $(this).text();
		var newText = $(this).attr('title');
		$(this).next('.hidden.more').removeClass('hidden');
		$(this).text(newText).removeClass('show-more').addClass('hide-more').attr('title', oldText);
		
		// If we didn't specify a title, we remove what is now an empty link
		if($(this).text() == '') $(this).remove();
	});
	$('a.hide-more').live('click', function(event) {
		event.preventDefault();
		
		var oldText = $(this).text();
		var newText = $(this).attr('title');
		$(this).next('.more').addClass('hidden');
		$(this).text(newText).removeClass('hide-more').addClass('show-more').attr('title', oldText);
	});
	
	// To add a datepicker, add the class datepicker to the input
//	$('input.datepicker').datepicker({
//		changeMonth: true,
//		changeYear: true,
//		dateFormat: 'dd-mm-yy'
//	});
	
	$('input.datepicker').live('click', function() {
		$(this).datepicker({
			showOn:'focus',
			changeMonth: true,
			changeYear: true,
			dateFormat: 'dd-mm-yy'
		}).focus();
	});
	
	/**
	 * Listen out for chain events
	 * In this case, any select which has a class "chain_user"
	 * It will load a dropdown with all the users in that account beneath it 
	 */
	$('select.chain_user').change(function() {
		// First, we need the account ID
		// Leave now if this is not set (They selected the empty item at the top)
		var account_id = $(this).val();
		if(account_id == '') return false;
		
		// Initialise any objects we need now or later
		// Create these now as $(this) will not be the real this in the response
		var parent = $(this).parent();
		var next = parent.next();
		
		// By default, the drop down that we create has the name user_id
		// We can change this by using the attr child of the parent
		var child_name =  $(this).attr('child');
		if(child_name == null) child_name = 'user_id';
		
		// We need to put a loading gif in place of where the users drop down will be
		// We need to make sure we don't already have an AJAX loaded dropdown
		// otherwise we could end up with several - Disaster!
		if(next.hasClass('loaded-via-ajax')) {
			next.html(LOADING+' Loading users');
		} else {
			var p = new jQuery('<p class="loaded-via-ajax">'+LOADING+' Loading users</p>');
			parent.after(p);
			// We need to update what "next" is so that it works within the AJAX response
			next = parent.next();
		}
		
		// Now use AJAX to fetch a dropdown with all the users
		$.ajax({
			type: 'GET',
			url: SITE_URL+'account/ajax/get_users_dropdown/'+account_id+'/'+child_name,
			success: function(response) {
				next.html(response);
			}
		});
	});
	
	/**
	 * These are used for the linked resources
	 * All it does  it get what the page would give you
	 * And sticks it in a qTip
	 * We also need to be sure we prevent the click event actually do anything!
	 */
	$('#linked-resources a').click(function(event) {event.preventDefault()});
	$('#linked-resources a').each(function() {
		$(this).qtip({
			content: {
				url: $(this).attr('href')
			},
			position: {
				corner: {
					target: 'bottomMiddle',
					tooltip: 'topRight'
				}
			},
			show: {
				when: 'click',
				solo: true
			},
			hide: 'unfocus',
			style: {
				tip: true, // Create speech bubble tip at the set tooltip corner above
				textAlign: 'left',
				name: 'cream',
				width: {
					min: 400,
					max: 400
				}
			}
		});
	});
	
	
	
	
	
	//////////////////////
	// Ticket listeners //
	//////////////////////
	$('#tickets-page form#add-task').submit(function(event) {
		event.preventDefault();
		
		// Get the input textfield
		var input = $(this).find('input[name$=task]');
		
		// Check it actually has some content (aka non empty string)
		if(input.val().length == 0) return;
		
		// Fire off an AJAX request to add it to the database
		$.ajax({
			type: 'POST',
			data: $(this).serialize(),
			url: SITE_URL+'tickets/ajax/add_task'
		});
		
		// Create the list item
		var li = jQuery('<li><span>'+input.val()+'</span></li>');
		// Append it to the end of the pending list
		li.prependTo('ul.task-list');
		// Reset the form back to its original state
		// Maybe not the most elegant way of doing it, but it works!
		$(this).each(function() {
			this.reset();
		});
	});
	
	$('#tickets-page form#add-comment').submit(function(event) {
		event.preventDefault();
		
		// Fire off an AJAX request to add it to the database
		$.ajax({
			type: 'POST',
			data: $(this).serialize(),
			url: SITE_URL+'tickets/ajax/add_ticket_comment',
			success: function (response) {
				// This will cause the parent request to redirect to itself
				// Basically, load the new comment on success
				window.location.href = window.location.href;
			}
		});
		
		// Reset the form back to its original state
		// Maybe not the most elegant way of doing it, but it works!
		$(this).each(function() {
			this.reset();
		});
	});
	
	$('#tickets-page ul.task-list li input').change(function(event) {
		var tmp = $(this).parent().find('span').html(LOADING);
		
		$.ajax({
			type: 'GET',
			url: SITE_URL+'tasks/ajax/mark_task_done/'+$(this).attr('name').substring(5),
			success: function() {
				tmp.parent().remove();
			}
		});
	});
	
	/////////////////////////
	// Dashboard Listeners //
	/////////////////////////
	$('#dashboard-page table#projects a.details').click(function(event) {
		event.preventDefault();
		
		// If we already have the details for this project
		// We just need to hide them
		// Otherwise we need to fetch them from the server and load them
		// This is done by checking if the next row has the class "details"
		
		// We need to get this reference now, as it won't work in the success of the AJAX call
		var tr = $(this).parent().parent();
		
		if(tr.next().hasClass('details')) {
			tr.next().remove();
		} else {
			// Make an AJAX request to get all the information for this project
			// We need to extract the project ID from the URL
			var parts = $(this).attr('href').split('/');
			var project_id = parts[parts.length-1];
			
			tr.after(jQuery('<tr><td colspan="4">'+LOADING+'</td></tr>'));
			
			$.ajax({
				type: 'GET',
				url: SITE_URL+'project/ajax/get_project_dashboard_details/'+project_id,
				success: function(response) {
					// This will remove the loading gif, which we'll replace with the actual data
					// Sure we could change the contents of this row, but for the time being, this is easier
					tr.next().remove();
					tr.after(jQuery('<tr><td colspan="4">'+response+'</td></tr>').addClass('details'));
					$('#project-'+project_id+'-details').tabs();
				},
				error: function(response) {
					tr.next().remove();
					tr.after(jQuery('<tr><td colspan="4">Sorry, something went wrong</td></tr>').addClass('details'));
				}
			});
		}
	});
	
	////////////////////
	// Time Listeners //
	////////////////////
	$('#time-page form#add-time').submit(function(event) {
		event.preventDefault();
		$.ajax({
			type: 'POST',
			data: $(this).serialize(),
			url: SITE_URL+'time/ajax/add_entry',
			success: function(response) {
				var row = jQuery(response);
				// Append it to the end of the pending list
				row.prependTo('table.time-list');
				
				// If we have more then 10 rows we need to remove the last one
				// -3 as we have 2 for the heading and one row for the total
				var length = $('table.time-list tr').length-3;
				if(length > 10) {
					$('table.time-list tr:last').prev().remove();
				}
				
				// We now need to update the sum at the bottom
				 $('table.time-list tr').each(function(index) {
					 if(index != 0 && index != 1 && index != 12) {
						 console.log($(this).find('.time').attr('class').substring(5));
					 }
				 });
			}
		});
		
		$(this).reset();
	});
	
	////////////////////
	// Task Listeners //
	////////////////////
	$('#tasks-page table.task-list input').live('change', function(event) {
		$.ajax({
			type: 'GET',
			url: SITE_URL+'tasks/ajax/mark_task_done/'+$(this).attr('name').substring(5),
			error: function() {
				$('#global-status').addClass('error').text('Sorry, an error occured').pause(5000).fadeOut(500).attr('style', '');
			}
		});
		// We need to add/remove the completed class from the task
		// As this sets the faded colour and strike through
		var td = $(this).parent().next();
		if(td.hasClass('completed')) td.removeClass('completed');
		else td.addClass('completed');
	});
	
	$('#tasks-page form#add-task').submit(function(event) {
		event.preventDefault();
		
		// Get the input textfield
		var input = $(this).find('input[name$=task]');
		
		// Check it actually has some content (aka non empty string)
		if(input.val().length == 0) return;
		
		// Fire off an AJAX request to add it to the database
		$.ajax({
			type: 'POST',
			data: $(this).serialize(),
			url: SITE_URL+'tasks/ajax/add_task',
			success: function(response) {
				var row = jQuery(response);
				// Append it to the end of the pending list
				row.prependTo('table.task-list');
			}
		});
		
		// Reset the form back to its original state
		// Maybe not the most elegant way of doing it, but it works!
		$(this).each(function() {
			this.reset();
		});
	});
	
	/////////////////////////
	// Milestone Listeners //
	/////////////////////////
	$('#milestones-page ul.milestones input').live('change', function() {
		var item = $(this);
		var li = item.parent();
		var parent = item.parent().parent();
		
		var milestone_id = item.attr('name').substring(14, 15);
		$.ajax({
			url: SITE_URL+'milestones/ajax/complete_milestone/'+milestone_id,
			success: function(response) {
				if(response == '1') {
					// This thing has been completed
					li.removeClass('overdue').remove().appendTo('ul.completed').addClass('complete');
				} else {
					li.removeClass('complete').remove().appendTo('ul.upcoming');
				}
			}
		});
	});
	
	////////////////////
	// File listeners //
	////////////////////
	$('#files-page form#add-comment').submit(function(event) {
		event.preventDefault();
		
		// Fire off an AJAX request to add it to the database
		$.ajax({
			type: 'POST',
			data: $(this).serialize(),
			url: SITE_URL+'files/ajax/add_comment',
			success: function (response) {
				// This will cause the parent request to redirect to itself
				// Basically, load the new comment on success
				window.location.href = window.location.href;
			}
		});
		
		// Reset the form back to its original state
		// Maybe not the most elegant way of doing it, but it works!
		$(this).each(function() {
			this.reset();
		});
	});
	
	//////////////////////////
	//    Misc listeners    //
	// Need to be organised //
	//////////////////////////
	
	$('img.priority').live('click', function () {
		// Get the priority based on the image path
		var src = $(this).attr('src');
		var segments = src.split('/');
		var priority = segments[segments.length-1].split('.')[0].substring(9);
		
		// Now we need to move it to the next one up, so
		// low -> medium
		// medium -> high
		// high -> low
		if(priority == 'low') priority = 'medium';
		else if (priority == 'medium') priority = 'high';
		else if (priority == 'high') priority = 'low';
		
		// Build up the new image path and swap it
		src = SITE_URL+'images/priority-'+priority+'.gif';
		$(this).attr('src', src);
		
		// Now we need to update the priority for this task in the database
		// The image also has an ID task_priority_XX
		var task_id = $(this).attr('id').split('_')[2];
		$.ajax({
			type: 'GET',
			url: SITE_URL+'tasks/ajax/change_priority/'+task_id
		});
	});
	
	/*
	$('h1#project-name').qtip({
		content: {url: SITE_URL+'project/ajax/list_projects_tooltip'},
		hide: {when: 'unfocus', fixed: true},
		position: {corner: {target: 'bottomMiddle', tooltip: 'topRight'}, adjust: {x: 10}},
		style: {width: {min: 240, max: 240}}
	});
	*/
	shortcut.add('n', function() {
		$('#create-new-overlay').overlay({
			api: true
		}).load();
	});
	
	shortcut.add('ctrl+ ', function() {
		$('#quick-command-overlay').overlay({
			api: true
		}).load();
		$('#quick-command-overlay input').focus();
	});
	
	$('form#quick-command').submit(function(event) {
		event.preventDefault();
		
		// Process the form
		$.ajax({
			type: 'POST',
			data: $(this).serialize(),
			url: SITE_URL+'ajax/quick_command',
			success: function(response) {
				// If we get nothing back, we're donw
				if(response == '') return false;
				
				// We may need to redirect the user
				// Can't do this in the PHP as that's a seperate request
				if(response.substring(0, 4) == 'http') {
					console.log("redirect");
					window.location = response; 
				} else {
					$('#global-status').removeClass('hidden').addClass('success').html(response); //.pause(5000).fadeOut(500).attr('style', '');
				}
			}
		});
		
		// Close the overlay and clear the text field for next time
		$('#quick-command-overlay').overlay({api: true}).close();
		$(this).reset();
	});
	
	// Check if the status is visible (on page load) and if so, hide it after a few seconds
	if($('#global-status').hasClass('error')) {
		$('#global-status').pause(5000).fadeOut(500).attr('style', '');
	}
	
	/**
	 * A generic way to add overlays to the application
	 * This is used for overlays which load content from another page
	 * Create links in the form
	 * <a href="target" class="overlay-trigger" rel="#dynamic-overlay">Link text</a>
	 * 
	 * Target is the page to load in the overlay
	 * The class and rel need to be set as above
	 * This is the this function gets triggered and it can find the div to load into
	 */
	$('a.overlay-trigger[rel]').overlay({
		onBeforeLoad: function() {
			// The following part is to make the overlay use a slightly differant page
			// We want to call the ajax equivalent of this function
			// So instead of xyz/create, we want xyz/ajax/create
			var href = this.getTrigger().attr('href').substring(SITE_URL.length);
			var href_parts = href.split('/');
			var controller = href_parts[0];
			var segments = href_parts.slice(1);
			var new_uri = SITE_URL+controller+'/ajax/'+segments.join('/');
			
			var wrap = this.getContent();
			wrap.load(new_uri);
		}
	});
	
	
	
	$('#dev-page #date').change(function() {
		$.ajax({
			url: SITE_URL+'dev/dates/date/'+$('#date').val(),
			success: function(response) {
				$('#timestamp').val(response);
			}
		});
	});
	$('#dev-page #timestamp').change(function() {
		$.ajax({
			url: SITE_URL+'dev/dates/timestamp/'+$('#timestamp').val(),
			success: function(response) {
				$('#date').val(response);
			}
		});
	});
	
	
	
	
	///////////
	// Links //
	///////////
	$('a.trigger-link').live('click', function(event) {
		event.preventDefault();
		var parent = $(this).parent().parent();
		
		parent.find('.link').slideToggle();
		if(parent.find('.new').is(':visible')) parent.find('.new').slideToggle();
	});
	$('a.trigger-new').live('click', function(event) {
		event.preventDefault();
		var parent = $(this).parent().parent();
		
		parent.find('.new').slideToggle();
		if(parent.find('.link').is(':visible')) parent.find('.link').slideToggle();
	});
	
	$('input#query-files').live('keyup', function() {
		var query = $(this).val();
		if(query == '') return false;
		var results = $(this).next();
		
		$.ajax({
			url: SITE_URL+'links/ajax/file/'+query,
			success: function(response) {
				results.html(response);
			}
		});
	});
	
	$('input#query-tasks').live('keyup', function() {
		var query = $(this).val();
		if(query == '') return false;
		var results = $(this).next();
		
		$.ajax({
			url: SITE_URL+'links/ajax/task/'+query,
			success: function(response) {
				results.html(response);
			}
		});
	});
	
	$('input#query-tickets').live('keyup', function() {
		var query = $(this).val();
		if(query == '') return false;
		var results = $(this).next();
		
		$.ajax({
			url: SITE_URL+'links/ajax/ticket/'+query,
			success: function(response) {
				results.html(response);
			}
		});
	});
});