/*
 * standard.js: Perform standard transformations on a page
 * This is normally included in all pages by header.vm
 * Requires jQuery, jQueryForm
 */

// STATUS: Buggy! - ajaxifyForm

/** Shorthand for document.getElementById() */
// Mostly use $('#'+id) instead, but this is more reliable
function get(id) {
	return document.getElementById(id);
}

/**
 * Add in a crude console.log() if FireBug is not present 
 */
var console;
if (console == undefined) {
	console = new Object();
}
if (console.log == undefined) {
	document.write("\n<div id='substitute-console' style='display:none;'></div>\n");
	console.log = function(obj) {
		var con = document.getElementById('substitute-console');
		if (con) con.innerHTML = con.innerHTML + "<p>"+obj+"</p>";
		else alert(obj);
	};
}

/**
 * Handle the standardish return values form a PuppetStrings AJAX call
 * Assumes:
 * There is a div with id=messages for messages
 * 
 * Message-adding is done by showMessage() and showErrorMessage().
 * Override these to change the default behaviour
 */
function handleAjaxResponse(response) {
	var error = response["error"];
	var msg = response["message"];
	var callme = response["callme"];
	if (error) {		
		showErrorMessage(error);
	}
	if (msg) {
		showMessage(msg);
	}
	if (callme) callme();
}
function showErrorMessage(error) {
	alert(error);
}
/**
 *Assumes:
 * There is a div with id=messages for messages
 * Override to change the default behaviour
 * @param msg
 */
function showMessage(msg) {
	var msgsDiv = get('messages');
	if (!msgsDiv) {
		console.log(msg);
		return;
	}
	msgsDiv.innerHTML += "<div class='message'>"+msg+"</div>";
}

/**
 * Status: not used
 * Take any form with the 'ajaxify' class and make
 * any change to it instantly apply and submit
 * Also hide the submit button
 * TODO provide "saving/saved" notifications to the user 
 **/
function ajaxifyForms() {
	for(var f in $('.ajaxify')) {
		$(f).ajaxForm();
	}
}


/**
 * Assumes all throbbers act together. I'm not sure about this.
 */
var throbberIsOn = false;

function turnOnThrobber() {
	$('.throbber').each( function() {
		$(this).html("<img src='/static/images/throbber.gif' />");
	});
	throbberIsOn = true;
}

function turnOffThrobber() {
	$('.throbber').each( function() {
		$(this).html("<img src='/static/images/throbber-off.gif' />");
	});
	throbberIsOn = false;
}

function toggleThrobber() {
	if (throbberIsOn) {
		turnOffThrobber();
	} else {
		turnOnThrobber();
	}
}

/**
 * Ajax form handling
 */

// The ajax call failed: display the error message and re-enable
// the button.
function fail(response, form) {
	alert('AJAX call failed: ' + response['error']);
	$(':submit', form).removeAttr('disabled');
}

$(document).ready(function(){
	// ajaxifyForms();
 });