function message(field, msg) {
	alert(msg);
	field.select();
	field.focus();
}

function toggleLoading() {
	$('.loading').toggle();
}

function confirmDelete(type, id) {
	if (confirm('Do you really want to delete this ' + type + '? This action cannot be undone.')) {
		if (type == 'band') {
			var reason = prompt('Please enter a reason for deleting this band, for future reference.');
			if (reason) {
				location.href = URL_SITE + type + '/delete/id/' + id + '?reason=' + reason;
			}
		} else {
			location.href = URL_SITE + type + '/delete/id/' + id;
		}
		return true;
	}
	return false;
}

// check for session for ajax/json calls
function jsonFormCheck(result) {
	$('.loading').hide();
	if (result.noSession) {
		if (result.json) {
			//window.location.reload();
			alert('Oops, your session appears to have expired! Please reload the page and try again.');
		} else {
			alert('An internal server error has occurred. Please try again later.');
		}
		return false;
	}
	return true;
	/*if (result.json) { 
		if (result.noSession) {
			window.location.reload();
			return false;
		}
		return true;
	} else { // Json value not present: an exception occurred and the json object cannot be parsed
		alert('An internal server error has occurred. Please try again later.');
		return false;
	}*/
}

function outputErrors(errors, formId) {
	removeMessage(formId);
	// Display the error block
	var errorContainer = $("#errorBlock" + formId.replace('#', ''));
	if (errorContainer.length > 0) {
		errorContainer.empty();
		$(formId + ' .errorField').removeClass('errorField');
	} else {
		errorContainer = $('<div id="errorBlock' + formId.replace('#', '') + '" class="ui-state-error ui-corner-all" style="padding: 0pt 0.7em; max-width:600px;"></div>');
	}
	
	for(errorField in errors) {
		if (errors[errorField]) {
			errorContainer.append('<p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"/>' + errors[errorField] + '</span></p>');
		}
		$("input[name='"+errorField+"']").addClass("errorField");
	}
	$(formId).prepend(errorContainer);
	errorContainer.show();
}

function removeErrors(formId) {
	$('#errorBlock' + formId.replace('#', '')).remove();
	$(formId + ' .errorField').removeClass('errorField');
}

function outputMessage(message, formId) {
	// Remove the error block if present
	removeErrors(formId);
	/*var errorContainer = $("#errorBlock" + formId.replace('#', ''));
	if (errorContainer.length > 0) {
		errorContainer.empty();
		errorContainer.remove();
	}*/
	// Display the message block
	var messageContainer = $("#messageBlock" + formId.replace('#', ''));
	if (messageContainer.length > 0) {
		messageContainer.empty();
	} else {
		messageContainer = $('<div id="messageBlock' + formId.replace('#', '') + '" class="ui-state-highlight ui-corner-all" style="padding: 0pt 0.7em; margin-top: 20px; max-width:600px;"></div>'); 
	}
	messageContainer.append('<p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-info"/> ' + message + '</p>');
	$(formId).prepend(messageContainer);
	messageContainer.show();
}

function removeMessage(formId) {
	// Remove the message block if present
	var messageContainer = $("#messageBlock" + formId.replace('#', ''));
	if (messageContainer.length > 0) {
		messageContainer.remove();
	}
}

function addRoleLine(roleInfo) {
	// add row to role list
	var newRow = $('#editLineup_' + roleInfo.typeId + ' tr.roleListTemplateRow').clone();
	newRow.removeClass();
	$('#roleTemplateRow', newRow).attr('id', 'role_' + roleInfo.roleId);
	$('#templateRoleTable', newRow).attr('id', 'roleTable_' + roleInfo.artistId + '_' + roleInfo.typeId);
	if (roleInfo.canEditLineup) {
		$('.templateDeleteRole', newRow).get(0).onclick = function () { deleteRole(roleInfo.roleId); return false; };
		$('.templateAddRole', newRow).get(0).onclick = function() { addRole(roleInfo.artistId, roleInfo.lineupId, roleInfo.typeId); return false; };
		$('input[name="templateDesc"]', newRow).attr({name: 'desc[' + roleInfo.lineupId + '][' + roleInfo.roleId + ']', value: roleInfo.roleDesc }).autocomplete(roles);
		$('input[name="templateDateFrom"]', newRow).attr({name: 'dateFrom[' + roleInfo.lineupId + '][' + roleInfo.roleId + ']', value: roleInfo.dateFrom });
		$('input[name="templateDateTo"]', newRow).attr({name: 'dateTo[' + roleInfo.lineupId + '][' + roleInfo.roleId + ']', value: roleInfo.dateTo });
	} else {
		$('#templateDesc', newRow).html(roleInfo.roleDesc);
		$('#templateDateFrom', newRow).html(roleInfo.dateFrom ? roleInfo.dateFrom : '?');
		$('#templateDateTo', newRow).html(roleInfo.dateTo ? roleInfo.dateTo : 'present');
	}
	newRow.attr('id', 'roleList_' + roleInfo.artistId);
	newRow.appendTo('#editLineup_' + roleInfo.typeId);
	$('.noArtists').remove();
}

// Approve a band/review submission
function approve(form) {
	if (confirm('Award ' + form.points.value + ' points to this submission?')) {
		form.action = form.action + '/status/approve';
		form.submit();
	}
}

// Reject a band/review submission
function reject(form) {
	if (form.ptsRemove.value && (isNaN(form.ptsRemove.value) || form.ptsRemove.value < 0)) {
		alert('Please enter a valid number of points (positive integer) to remove, or leave it blank.');
		$('#ptsRemove').addClass("errorField");
		form.ptsRemove.select();
		form.ptsRemove.focus();
		return false;
	}
	var reasons = document.getElementsByName('reason');
	var checked = false;
	for (var i = 0; i < reasons.length; i++) {
		if (reasons[i].checked) {
			checked = true;
		}
	}
	if (!checked) {
		alert('You must choose a reason before proceeding with the rejection of the submission.');
	} else {
		form.action = form.action + '/status/reject';
		form.submit();
	}
}

// Review editing form for mods
function editReview() {
	var link = $(this);
	var reviewId = link.attr('id').substr(11);
	var reviewText = $('#reviewText_' + reviewId);
	if (link.html() == 'edit') { // clicked "edit"
		link.html('save').after('<a class="reviewEdit" id="reviewCancel_' + reviewId + '" href="javascript:;" onclick="cancelEditReview(' + reviewId + ');">cancel</a>');
		reviewText.hide().after('<textarea name="editedReview" id="reviewTextbox_' + reviewId + '" rows="20" cols="90">' + reviewText.html().replace(/<br>/g, "") + '</textarea>');
		$('#reviewTextbox_' + reviewId).focus();
	} else { // clicked "save"
		saveEditedReview(reviewId);
	}
}
function saveEditedReview(reviewId) {
	if (confirm("Save your changes to this user review?")) {
		$('.loading').show();
		$.post(URL_SITE + 'review/ajax-save-edited/json/1', { 'reviewId' : reviewId, 'reviewText' : $('#reviewTextbox_' + reviewId).val() }, function(result) {
			if (jsonFormCheck(result)){
				$('#reviewText_' + reviewId).html(result.reviewComment);
				$('.loading').hide();
				cancelEditReview(reviewId);
			}
		}, 'json'
		);
	}
}
function cancelEditReview(reviewId) {
	$('#reviewEdit_' + reviewId).html('edit');
	$('#reviewCancel_' + reviewId).remove();
	$('#reviewTextbox_' + reviewId).remove();
	$('#reviewText_' + reviewId).show();
}

function selectIndieLabel(checkbox) {
	var checkFlag = ($(checkbox).is(':checked')) ? true : false;
	if (checkFlag) {
		$("#labelChoice").hide();
		$("#label").html('Independent');
		$("#labelId").val(0);
	} else {
		$("#labelChoice").show();
		$("#label").html('...');
		$("#labelId").val('');
	}
}

// Toggle rejection form
/*function preReject() {
	var button = $('#btnPreReject');
	var rejectionMessage = $('#rejection');
	rejectionMessage.toggle();
	//button.val(rejectionMessage.is(':visible') ? 'cancel' : 'reject');
	button.html(rejectionMessage.is(':visible') ? 'Cancel' : 'Reject');
}*/

// Delete a review
function deleteForever(reviewId) {
	if (confirm('This will delete the review permanently, and the user will not be notified.\nUse this to get rid of obvious trolls, not the typical bad/n00b review, otherwise click "reject". Continue?')) {
		location.href = URL_SITE + 'review/delete/id/' + reviewId;
	}
}

function createGrid(tableOrId, nbrPerPage, ajaxUrl, extraOptions) {
	var table = null;
	if(typeof tableOrId == "string") {
		table = $(tableOrId);
	}
	else {
		table = tableOrId;
	}
	
	if(ajaxUrl == undefined) {
		ajaxUrl = null;
	}
	
	var options = {
					 bAutoWidth: false,
					 bFilter: false,
					 bLengthChange: false,
					 bProcessing: true,
					 bServerSide: ajaxUrl != null,
					 iDisplayLength: nbrPerPage,
					 sAjaxSource: URL_SITE + ajaxUrl,
					 sPaginationType: 'full_numbers',
					 sDom: 'ipl<"block_spacer_5"><"clear"r>f<t>rip',
					 oLanguage: { 
					 	sProcessing: 'Loading...',
					 	sEmptyTable: 'No records to display.',
					 	sZeroRecords: 'No records found.'
					 },
					 "fnDrawCallback": autoScrollUp
				};
	
	if(typeof extraOptions == "object") {
		for(var key in extraOptions) {
			options[key] = extraOptions[key];
			// Merge the auto scroll-up callback with any user-defined callback
			if (key == 'fnDrawCallback') {
				var callback = options[key];
				options[key] = function(o) {
					autoScrollUp(o);
					callback(o);
				}
			}
		}
	}
	return table.dataTable(options);
}

// Auto scroll up when changing page in a table
var oldStart = 0;
function autoScrollUp(o) {
	if ( o._iDisplayStart != oldStart ) {
		var targetOffset = $('#' + o.sTableId).offset().top - 500;
		$('html,body').animate({scrollTop: targetOffset}, 100);
		oldStart = o._iDisplayStart;
	}
}

function insertAtCursor(myField, myValue) {
	myField.focus();
	//IE support
	if (document.selection) {
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
	$('#bandSearchPopup').dialog('close');
	$('#artistSearchPopup').dialog('close');
	$('#labelSearchPopup').dialog('close');
}

//// Reporting functions ////

// Open the report dialog
function popupReportDialog(objectType, objectId) {
	
	var dialog = $("#reportDialog");
	if (dialog.length == 0) {
		dialog = $("<div id='reportDialog' title='New report'></div>");
	}
	dialog.load(URL_SITE + "report/add/object/" + objectId + "/type/" + objectType);
	if (dialog.hasClass("ui-dialog-content")) {
		dialog.dialog("open");
	} else {
		dialog.dialog({ modal: true, width: 500, buttons: {Send: validateReport, Cancel: function() { dialog.dialog('close'); } } });
	}
}

// Validate the report submission
function validateReport()
{
	var form = $("#reportForm");
	if (form.length > 0) {
		var categoriesField = $("#report_category_id", form);
		var commentField = $("#comment", form);
		if (categoriesField.val() == 0) {
			//alert("Please select a report category.");
			outputErrors({report_category_id: "Please select a report category."}, '#reportForm');
		} else if (commentField.val() == "") {
			//alert("Please enter a comment explaining your reason for reporting this band!");
			outputErrors({comment: "Please enter a comment explaining your reason for reporting this band!"}, '#reportForm');
			commentField.focus();
		} else {
			if(form.attr("action").indexOf("notspam") == -1) form.attr("action",  form.attr("action") + "?notspam");
			form.ajaxSubmit({ beforeSubmit: toggleLoading, success: reportResult, dataType: "json" });
		}
	}
}

// Callback for the ajax report submission
function reportResult(response) {
	toggleLoading();
	if(response.isSuccess == true) {
		$("#reportForm").remove();
		$("#reportResult").show();
	}
	else {
		outputErrors(response.errors, "#reportForm");
	}
}

// Bound to an onclick event on an image link: zooms the image in the middle of the screen
function zoomImage(e) {
	if ($('#imageZoom_' + this.id).length == 0) {
        var title = (this.title) ? "<br />" + this.title : '';
        var imageZoom = $("<p class='imageZoom' id='imageZoom_" + this.id + "'><img src='"+ this.href +"' alt='" + title + "' /> "+ title +" [<a href='#' onclick='closeImage();' title='Close'>close</a>]</p>");
        $("body").append(imageZoom);
        var xOffset = (document.body.clientWidth / 2) - (imageZoom.width() / 2);
		//var yOffset = (document.body.clientHeight / 2) - (imageZoom.height() / 2); // doesn't work so well on long scrolling pages..
		var yOffset = 200;
        imageZoom.css("top", yOffset + "px").css("left", xOffset + "px");
	}
	$('#imageZoom_' + this.id).show("scale");
    return false;
}

function closeImage() {
	$('.imageZoom').hide();
}

// Show additional band notes/artist bio
function readMore(readMoreUrl, id) {
	var dialogId = "#readMoreDialog";
	if (id && id != 'undefined') {
		dialogId += id;
	}
	var dialog = $(dialogId);
	if (dialog.hasClass("ui-dialog-content")) {
		dialog.dialog("open");
	} else {
		dialog.load(URL_SITE + readMoreUrl).dialog({ width: 600, height: 400, buttons: { Close: function() { dialog.dialog('close'); } } });
	}
}

function toggleProfileMenu(e){
	var link = $(this);
	var username = link.text();
	var positions	=	{
		top:	e.pageY,
		left:	e.pageX
	};
	var menuId = username.replace(/ /g, '_') + '-' + Math.round(positions.top) + '-' + Math.round(positions.left);
	var toolMenu = $('#menu-' + menuId);
	// Create menu if it's not already loaded
	if (toolMenu.length == 0) {
		toolMenu = $('<div class="toolMenu" style="width: 300px;" id="menu-' + menuId + '"></div>');
		toolMenu.append(
             '<div id="' + menuId + '" class="toolMenu-content ui-corner-all displayNone">' +
             	'<a class="toolMenu-close ui-state-active" onclick="$(\'#' + menuId + '\').hide(\'slow\'); return false;" href="javascript:;"><span class="ui-icon ui-icon-closethick">close</span></a>' +
             	'<ul> ' +
                   '<li><a href="' + URL_SITE + 'users/' + username + '">Go to ' + username + '\'s profile</a></li>' +
                   '<li><a href="' + URL_SITE + 'user-reviews/' + username + '">Read ' + username + '\'s reviews</a></li>' +
                   '<li><a href="' + URL_SITE + 'collections/' + username + '">Check ' + username + '\'s collection</a></li>' +
                   '<li><a href="' + URL_SITE + 'user-bands/' + username + '">View bands added by ' + username + '</a></li>' +
                 '</ul>' +
             '</div>'
		).css({
			top:		positions.top,
			left:		positions.left,
			position:	"absolute"
		});	// position profile menu slightly below the profile link
        
		$("body").append(toolMenu);
	}
	// Show menu
	$('#' + menuId).show('slow');
	$("html").click(hideMenus);
	return false;
}

function toggleAlbumMenu(e){
	var link = $(this);
	var releaseId = link.attr('id');
	var positions	=	{
		top:	e.pageY,
		left:	e.pageX
	}
	var menuId = releaseId + '-' + Math.round(positions.top) + '-' + Math.round(positions.left);
	var toolMenu = $('#menu-' + menuId);
	// Create menu if it's not already loaded
	if (toolMenu.length == 0) {
		toolMenu = $('<div class="toolMenu" style="width: 300px;" id="menu-' + menuId + '"></div>');
		toolMenu.append(
             '<div id="' + menuId + '" class="toolMenu-content ui-corner-all displayNone">' +
             	'<a class="toolMenu-close ui-state-active" onclick="$(\'#' + menuId + '\').hide(\'slow\'); return false;" href="javascript:;"><span class="ui-icon ui-icon-closethick">close</span></a>' +
             	'<ul>' +
                   //'<li><a href="' + URL_SITE + 'release/clone/id/' + releaseId + '">Create another album version</a></li>' +
                   '<li><a href="' + URL_SITE + 'review/write/releaseId/' + releaseId + '">Write a review</a></li>' +
                   '<li><a href="#" onclick="$(\'#' + menuId + '\').hide(); return addToCollection(' + releaseId + ', 1);">Add to your collection</a></li>' +
                   '<li><a href="#" onclick="$(\'#' + menuId + '\').hide(); return addToCollection(' + releaseId + ', 3);">Add to your wanted list</a></li>' +
                   '<li><a href="#" onclick="$(\'#' + menuId + '\').hide(); return addToCollection(' + releaseId + ', 2);">Add to your trade list</a></li>' +
                   '<li><a href="' + URL_SITE + 'collection/owner-list/releaseId/' + releaseId + '">See who owns/wants this album</a></li>' +
              	'</ul>' +
             '</div>'
		).css({
			top:		positions.top,
			left:		positions.left,
			position:	"absolute"
		}); // position album menu slightly below the album link
        
		$("body").append(toolMenu);
	}
	// Show menu
	$('#' + menuId).show('slow');
	$("html").click(hideMenus);
	return false;
}

function addToCollection(releaseId, collectionType) {
	toggleLoading();
	$.getJSON(URL_SITE + 'collection/add/json/1/id/' + releaseId + '/type/' + collectionType, function(result) { 
		if (jsonFormCheck(result)) {
			if (result.success) {
				outputMessage(result.message, '#message');
			} else {
				outputErrors(result.errors, '#message');
			}
		}
	});
	return false;
}

function hideMenus(event) {
	if(!$(event.target).is(".toolMenu, .toolMenu *")) {
		$(".toolMenu-content").hide();
		$("html").unbind();
	}
}

function showHistoryDetails(e) {
	var historyId = $(this).attr('id');
	var details = $('#details' + historyId);
	if (details.length == 0) {
		var row = $(this).parent().parent();
		$("<tr />").append($("<td colspan='4' id='details" + historyId + "' />").load(URL_SITE + 'history/ajax-details/id/' + historyId)).insertAfter(row);
		$('#icon_' + historyId).removeClass('ui-icon-plus').addClass('ui-icon-minus');
	} else {
		details.toggle();
		if (details.is(':visible')) {
			$('#' + historyId).attr('title', 'Collapse');
			$('#icon_' + historyId).removeClass('ui-icon-plus').addClass('ui-icon-minus');
		} else {
			$('#' + historyId).attr('title', 'Expand');
			$('#icon_' + historyId).removeClass('ui-icon-minus').addClass('ui-icon-plus');
		}
	}
}

