/*
 * 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);
}

// js imports
var IMPORTS = {};
/**
 * TODO test! then use
 * Load and execute a script file - but only once.
 * @param url
 */
function importScript(url) {
	if (IMPORTS[url]) return;
	$.getScript(url);
	IMPORTS[url] = true;
}

function ClientGet(key) {
	var gc = getCookie(key);
	if (!gc) return gc;
	return eval(gc);
}
function ClientPut(key,value) {
	setCookie(key,""+value);	
}


var genIdCntr = 0;
/* Get or generate an ID */
function getId(elem, extractNameSelector) {
	elem = $(elem);
	if ( ! elem.attr('id')) {
		genIdCntr++;		
		var elemName = "";
		if (extractNameSelector) elemName = $(extractNameSelector, doc).text();
		if ( ! elemName) elemName = genIdCntr;
		// get the path but not the query
		var locn = ""+window.location;
		locn = locn.replace(/\?.*$/, "");		
		var id = "genId_"+elemName+"_"+locn;
		id = id.replace(/\W/g, "");		
		elem.attr('id', id);
	}
	return elem.attr('id');
}


/** A strong anti-hacking defence: strips out all html tags */
function clean(html) {
	if ( ! html) return ""; // possibly hiding bugs
	var txt = html.replace(/<[^>]+>/, "");
	return txt;
}

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

var DEBUG = (""+window.location).indexOf("debug") != -1;
 
/**
 * Add in a crude console.log() if FireBug is not present 
 */
if (console == undefined || ! console) {
	var console = new Object();
}
if (console.log == undefined) {
	$(document).append("<div id='substitute-console' style='display:none;'></div>");
	console.log = function(obj) {
		if (DEBUG) $('#substitute-console').show();
		var con = document.getElementById('substitute-console');
		if (con) con.innerHTML = con.innerHTML + "<p>"+obj+"</p>";
	};	
}

/**
 * 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["errors"];
	var msg = response["messages"];
	var callback = response["callback"];
	if (error) {		
		showErrorMessage(error);
	}
	if (msg) {
		showMessage(msg);
	}
	if (callback) callback();
}
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>";
}

/**
 * Ajax form handling
 */

// The ajax call failed: display the error message and (optional) re-enable
// the button.
function fail(response, form) {
	var err = ".";
	if (response['error']) err = ": "+response['error'];
	alert('Sorry, there was a problem'+err);
	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, selector) {	
	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: "+selector);
	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);
		}
	}				
}

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

// calendar popups
ajaxifyFunctions.push(function(){
	$('.DateField').datepicker({maxDate:0,
		showOn:'button',
		buttonImage:'/static/images/icons/silk/clock.png',
		buttonImageOnly:true});
});

// nav bar
$('a.nav').not('active').each(function() {
	var u = $(this).attr('href');
	var pth = ""+window.location;
	pth.replace(/https?:\/\/[a-zA-Z\-_0-9\.:]+\/([a-zA-Z\-_0-9])(\?.+)?/, "$1");
	console.log("Path", pth);
	if (pth == u) {
		$(this).addClass('active');
	}
});

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

