//
// TODO:
// - This all needs to be objectified, so it doesn't pollute the global namespace. Otherwise, all functions need a common prefix.

$(function() {
	$('#display_form input[type="button"]').each(function() {
		$(this).click(function() {
			toggle_display($(this));
		});
	});
	// Reset the counter to the number of tickets currently visible...
	update_items_count();
	
	// Enable DND on the Backlog Table
	try {
		enableDnD('backlog');
	} catch(err) {} // just want to swallow it
});

function update_items_count() {
	try {
		var total_items = eval($('#total_items').text());
		var hidden_items = $('table#backlog tbody tr:hidden').length;
		$('#items_count').text(total_items - hidden_items);
	} catch (err) {
		// it is not a number
	}
}

function toggle_display(button) {
	// set display option server-side, send a JSON call to the server
	var args = Object();
	var num_items = 0;
	args['my_tickets'] = button.attr('name') == 'my_tickets';
	args['closed_tickets'] = button.attr('name') == 'closed_tickets';
	var action = (button.hasClass('down') && button.attr('id') == 'my-tickets')
			|| (!button.hasClass('down') && button.attr('id') == 'closed-tickets') ? 'show'
			: 'hide';
	url = encodedURLFromComponents('json', 'tickets', 'backlog', action);
	$.ajax({
		type : 'POST',
		url : url,
		processData : true,
		contentType : 'application/json',
		dataType : 'json',
		data : JSON.stringify(args),
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			// XMLHttpRequest.responseText contains what was delivered
			alert('textStatus:' + textStatus + 'errorThrown:' + errorThrown
					+ 'status:' + XMLHttpRequest.status);
		},
		success : function(data, textStatus) {
			if (data) {
				// TODO: may be blink the moved row or something...
			}
		}
	});
	if (button.attr('id') == 'my-tickets') {
		// we need to check now if the show closed is also pressed
		var closed = $('#closed-tickets').hasClass('down');
		var tickets = $('table#backlog tr.notuser');
		if (button.hasClass('down')) {
			// It was already selected, so if it has been pressed is a show
			button.val('Show my tickets');
			if (closed) {
				tickets = tickets.filter('.closed .done');
			}
			tickets.show();
		} else {
			button.val("Show everybody's tickets");
			tickets.hide();
		}
	} else if (button.attr('id') == 'closed-tickets') {
		var mine = $('#my-tickets').hasClass('down');
		var tickets = $('tr.closed, tr.done');
		if (button.hasClass('down')) {
			// It was already selected, so we need to hide the closed tickets
			button.val('Show closed tickets');
			tickets.hide();
		} else {
			button.val('Hide closed tickets');
			if (mine) {
				tickets = tickets.filter('tr:not(.notuser)');
			}
			tickets.show();
		}
	}
	// toggle class style
	button.toggleClass('down');
	update_items_count();
}

/**
 * Gets the Backlog Name from the current URL
 * 
 * @return a Backlog Object with name and scope
 */
function getBacklogNameAndScope() {
	 return buildBacklogFromURL(window.location.pathname, window.location.search);
}

function buildBacklogFromURL(path, rawQueryString) {
	var backlog = {name: null, scope: null};
	
	var backlogURLPrefix = '/backlog/';
	var interestingPath = path.split(backlogURLPrefix)[1];
	var pathComponents = interestingPath.split("/");
	backlog.name = decodeURIComponent(pathComponents[0]);
	
	var queryString = new Querystring(rawQueryString);
	if (queryString.contains("bscope"))
		backlog.scope = queryString.get("bscope");
	else if (pathComponents.length > 1)
		backlog.scope = decodeURI(pathComponents[1]);
	return backlog;
}


/**
 * Updates the position in the row, so when saved the position is updated
 * 
 * @param table:
 *            the table
 * @param row:
 *            the row
 * @return
 */
function onRowDrop(table, row) {
	var ticketID = $(row).attr('id');
	var newPositionIndex = findNewPositionIndexForTicket(ticketID, table);
	if (newPositionIndex === -1)
		return;
	
	notifyServerAboutPositionChange(ticketID, newPositionIndex);
}

function findNewPositionIndexForTicket(ticketID, table) {
	var rows = table.tBodies[0].rows;
	for (i = 0; i < rows.length; i++) {
		if ($(rows[i]).attr('id') == ticketID) {
			return i;
		}
	}
	return -1;
}

function notifyServerAboutPositionChangeURL(aBacklog) {
	return encodedURLFromComponents('json', 'backlogs', aBacklog.name, aBacklog.scope);
	
}

function notifyServerAboutPositionChange(ticketID, newPositionIndex) {
	// We found the row, the position is i, and we can send the change
	var backlog = getBacklogNameAndScope();
	var json_url = notifyServerAboutPositionChangeURL(backlog);
	var jsonRequestData = {
		"ticket" : ticketID,
		"to_pos" : newPositionIndex
	};
	$.ajax( {
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			// XMLHttpRequest.responseText contains what was delivered
			alert('textStatus:' + textStatus + 'errorThrown:' + errorThrown
					+ 'status:' + XMLHttpRequest.status);
		},
		success : function(data, textStatus) {
			if (data) {
				// TODO: may be blink the moved row or something...
			}
		},
		url : json_url,
		contentType : 'application/json', // what I'm sending
		dataType : 'json', // what I'm expecting
		type : 'POST',
		processData : true,
		data : JSON.stringify(jsonRequestData)
	});
}
 
function onRowStart(table, row) {
	$(row).addClass("dragging");
}

function enableDnD(table) {
	var dnd_loaded = false;
	dnd_loaded = (typeof jQuery.tableDnD === "object");
	if (dnd_loaded === true) {
		$('table#' + table).tableDnD( {
			enable: true,
			// onDragStart : onRowStart,
			onDrop : onRowDrop,
			onDragClass : "dragging"
		});
	}
}

function disableDnD(table) {
	$('table#' + table).tableDnD({
		enable: false,
		onDragClass: "false"
	});
}
