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

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

function isArray (obj) {
	//obj.constructor.toString().indexOf(”Array”) != -1;
	return obj instanceof Array;
}

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

/**
 * Handle the standardish return values form a PuppetStrings AJAX call
 * Assumes:
 * 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=flash-messages for messages
 * Messages are output in div class=message
 * Override to change the default behaviour
 * @param msg
 */
function showMessage(msg) {
	console.log("Message: "+msg);
	var msgsDiv = get('flash-messages');
	if (!msgsDiv) {
		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').not(".ajaxed")) {
		$(f).addClass('ajaxed');
		$(f).ajaxForm();
	}
}


/**
 * Ajax form handling
 */

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


/**
 * Sanity check for results from JQuery. Did we get any?
 * @param x jquery array
 * @param num (optional) expected number 
 */
function $sanity(x, num) {	
	if (x && x.length) {
		if (!num && x.length!=0) return;
		if (x.length==num) return;
	}
	if (x.length) {
		console.log("JQuery failure: wrong number of elements found.");
	} else {
		console.log("JQuery failure: no elements found.");
	}
	if (alertedAlready) return;
	alert("JQuery selection failure");
	alertedAlready = true;
}
var alertedAlready;

/** Collect functions to be called when adding new html to a page */
console.log("Defining ajaxifyFunctions");
var ajaxifyFunctions = [];
/** Called when new html has been inserted to wire up the ajax widgets */
function ajaxify() {
	console.log("ajaxify");
	for(var i=0; i<ajaxifyFunctions.length; i++) {
		var fn = ajaxifyFunctions[i];
		console.log("..."+fn.name);
		try {
			fn();
		} catch(err) {
			console.log("ERROR "+err);
		}
	}				
}

// add as=person-id field to all forms
function asWho() {
	var asi = $("input[name='as']:first");
	if ( ! asi) return;
	var as = $(asi).val();
	if ( ! as) {
		console.log("no as value from "+asi);
		return;
	}
	$("form").each(function() {		
		var form = $(this);
		// hack: avoid the search form
		if (form.attr("method") && form.attr("method").toLowerCase()=="get") return;
		var fasi = $("input[name='as']:first", form);
		if ( ! fasi || ! fasi.val()) {			
			form.append("<input type='hidden' name='as' value='"+as+"'>");
		}
	});
}
ajaxifyFunctions.push(asWho);

// lengthen urls
ajaxifyFunctions.push(function (){$.longurlplease();});

$(document).ready(function(){
	ajaxify();
 });
