$(document).ready(function() {
	$('.conferma_elimina').click(function(e) {
		var msg = $(this).attr('rel');
		if (msg.length > 0) {
			return confirm(msg);
		} else {
			return confirm('Sicuro di voler eliminare?');
		}
	});
});

function checkUsername(form) {
	var user = $('#username').val();
	var idUtente = $('#idUtente').val();
	$.post('checkUsername', 'username='+user+'&idUtente='+idUtente, function(data) {
		if (data == '1')
			form.submit();
		else {
			$.gritter.add({
				title: 'Errore',
				text: 'Username gi&agrave; utilizzato!',
				image: IMAGE_URL+'delete.gif',
				sticky: true
			});
		}
	});
	return false;
}

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function name2url(stringa, toModify) {
	$.post('name2url', 'testo='+stringa, function(data) {
		$(toModify).attr('value', data);
	});
}

function updateTableHeader() {
	$(document).ready(function() {
		$('.FirstRow').children('td').each(function() {
			var id = $(this).attr('id');
			if (trim(id) != '') {
				var matchs = id.match(/^([^-]*)(-(asc|desc))?/);
				id = matchs[1];
				var order = matchs[3];
				var defaultOrder = ($(this).attr('defaultOrder')) ? $(this).attr('defaultOrder') : 'asc';
				var link = location.href.split(/^([^\?]*)(\?.*)?$/)[1]+'?orderby='+id+'-'+defaultOrder;
				if (order) {
					$(this).append('&nbsp;<img src="'+IMAGE_URL+'arrow_'+order+'.png" alt="'+order+'" class="order_img" />');
					if (order == 'asc') {
						link = link.replace(/(-asc)/, '-desc');
					}
					if (order == 'desc') {
						link = link.replace(/(-desc)/, '-asc');
					}
				}
				$(this).css('cursor', 'pointer');
				$(this).attr('title', 'Ordina');
				$(this).click(function() {
					location.href = link;
				});
			}
		});
	});
}

function changeId(oldId, newId) {
	$(document).ready(function() {
		$('#'+oldId).attr('id', newId);
		updateTableHeader();
	});
}

$(document).ready(function() {
	updateTableHeader();
});
