/*---[ Details ]---------------------------------------
Global Javascript Scripts
-------------------------------------------------------*/

//(function($){

/* jQuery Pre-Document Load
-------------------------------------------------------*/
/*
 * Add class to html element for styling hook
 * i.e. 'h1 { color: red; }, .js-active h1 { color: blue; }' will display accordingly if javascript is active
 */
$('html').addClass('js-active');


/* jQuery Document Load
-------------------------------------------------------*/
var overlays = null;
var count = 0;
$(document).ready(function(){
	$('table tbody').find('tr:odd').addClass('alt');
	$('dl').find('dd:even,dt:even').addClass('alt');

	var div = document.createElement('div');
	div.setAttribute('id','inlay');
	div.setAttribute('class','simple_overlay content');
	$("#header").append(div);
	$('#inlay, #feedback').hide();


	/* sort out the slidedown inlay */
	$('a[rel=#inlay], a[rel=#feedback]').click(function() {
		var self = $(this);
		var url  = self.attr('href') + '.ajax';

		$(self.attr('rel')).load(url, function() {
			//$(this).slideDown();
			hijackForms();
			ajaxElementSetup();
			$(this).slideDown();
		});

		return false;
	});

	var overlayConfig = {
		onBeforeLoad: function() {
			var anchor = this.getTrigger();
			var url = anchor.attr('href') + '.ajax';
			$(anchor.attr('rel')).load(url);
		},
		expose: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.9
		},
		closeOnClick: false,
		onLoad: function() {
			// hijack forms
			hijackForms();
			ajaxElementSetup();
		}
	};

	/* autofocus on login box */
	$("div.entry form #fm_email").focus();



	/* Sort out the ajax overlays */
	overlays = $("a[rel=#overlay]").overlay(overlayConfig);

	// edit hovers for client information
	$('dd:has(.action)').find('.action').hide().end().hover(function() {
		$(this).find('.action').show();
	}, function() {
		$(this).find('.action').hide();
	});

	var reapplyOverlay = function() {
		//$(this).find("a[rel=#overlay]").overlay(overlayConfig);
		overlays = $("a[rel=#overlay]").overlay(overlayConfig);
	};

	$('table[datasrc]').raTable({
		cellFilter: function(event, object, property, value) {
			switch(property) {
				case 'job':
					return '<a href="/quote/view/' + object.id + '">' + value + '</a>';
				case 'description':
					return '<p>' + value + '</p>';

				case 'activity':
				case 'name':
					return '<a href="/' + object.type + '/' + (object.type == 'user' ? 'profile' : 'view') + '/' + object.id + '">' + value + '</a>';

				case 'task': // need to re map #overlay
					return '<a href="/task/view/' + object.id + '">' + value + '</a>';

				case 'getProjectName':
					return '<a href="/project/view/' + object.project_id + '">' + object.project + '</a>';

				case 'getClient.name':
				case 'getClientName':
					return '<a href="/client/view/' + object.client_id + '">' + object.client + '</a>';

				case 'getContact.name':
					return '<a href="' + object.contact_link + '">' + object.contact + '</a>';

				case 'email':
					return '<a href="mailto:' + value + '">' + value + '</a>';

				case 'getOwner':
					return object.creator;

				case 'est_hours':
					return object.estimated_hours;

				case 'getAssigned.name':
				case 'getAssignedTo':
					return '<a href="' + object.assigned_to_link + '">' + object.assigned_to + '</a>';

				case 'getTasksRemaining':
					return object.tasks;

				case 'time':
					return object.hours_booked;

				case 'getTask.task':
					return '<a href="' + object.task_link + '">' + object.task + '</a>';

				case 'getUser.name':
					return '<a href="' + object.user_link + '">' + object.user + '</a>';

				case 'getNote':
					return object.note;
			}

			return value;
		},
		rowFilter: function(event, index, row) {
			if(row.type != 'task')
				return row;

			if(row.done == 'yes')
				row.cssClass = 'task-complete';

			return row;
		}
	});
});


/**
 * Setup elements on the ajax pages - call once on load and once after ajax load
 */
function ajaxElementSetup() {
	// close on click of cancel button
	$(".simple_overlay form a.cancel-button").click(function() {
		closeAll(false);
		return false;
	});

	// focus first element
	// $(".simple_overlay form input:first").focus(); // this fails as the first input element is almost always a hidden id field
	/*$(".simple_overlay form input, .simple_overlay form textarea, .simple_overlay form select").each(function() {
		if(this.type != "hidden") {
			this.focus();
			return false;
		}
	});*/

	/* turn the time input into a slider */
	// insert it after the input element
	$('#time_slider').insertAfter('#fm_time');
	$('#time_slider').slider({
		range: "max",
		min: 1,
		max: 24,
		step: 0.25,
		value: $("#fm_time").val(),
		slide: function(event, ui) {
			$("#fm_time").val(ui.value);
		}
	});

	/* add datepickers */
	$('#fm_day').datepicker({
		dateFormat: 'yy-mm-dd'
	});

	// crm
	$('#fm_due_datetime').datepicker({
		dateFormat: 'yy-mm-dd'
	});
	$('#fm_done_datetime').datepicker({
		dateFormat: 'yy-mm-dd'
	});
	$('#ui-datepicker-div').css('z-index','20001');
}

/**
 * Called when any overlays closes
 *
 */

function closeFunction(reload) {
	if (reload) {
		window.location.reload();
	}
}

/**
 * Deals with form ajax response
 *
 */
function sortAjaxResponse(responseText, statusText) {
	$(".simple_overlay").each(function() {
		$(this).empty();
	});
	$(".simple_overlay").html(responseText);

	// hijack forms
	hijackForms();
	// change the elements
	ajaxElementSetup();

	// the rev=owner attribute is assigned to the close button, if it's available close the overlay
	if($('.simple_overlay a[rev=owner]').length > 0) {
		window.setTimeout(function() {
			// special case for the timesheet
			if ($("form").attr('action')=='/time/updatetimesheet') {
				closeAll(false);
				taskAjaxCall();
			}
			else {
				closeAll(true);
			}

		}, 500);
	}
}

/**
 * Hijacks the form in the overlay and submits via ajax
 *
 */
function hijackForms() {
	// hijack the forms <button
	$(".simple_overlay form").submit(function() {
		// disable the form submit button
		var button = $('.buttons').children('[type="submit"]');
		button.attr('disabled',true);
		button.toggleClass('disabled');

		var options = {
	        success:	sortAjaxResponse // post-submit callback
	    };
		url = $(this).closest('form').attr('action');
		data = $(this).closest('form').serialize();

		$.ajax({
		  type: 'POST',
		  url: url,
		  data: data,
		  success: sortAjaxResponse,
		  dataType: 'html'
		});

		return false;
	});
}

/**
 * Using the api flag of overlay returns the *last* overlay to be instantiated so trying to close the overlay
 * in functions outside of the config object causes some very odd behaviour, hence this doesn't use the api
 * functionality but closes all overlays based on the jQuery object returned
 */
function closeAll(reload) {
	overlays.each(function() {
		var overlay = $(this).data('overlay');

		if(overlay) {
			overlay.reload = reload;
			overlay.close();
		}
	});

	$('#inlay').slideUp();
	$('#feedback').slideUp();
	closeFunction(reload);
}


//})(jQuery); // end jquery namespace
