/* JavaScript for global utilities.
 * ===================================================================
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307 USA
 * ===================================================================
 * $Id: util.js,v 1.6 2005/08/23 06:29:08 matt Exp $
 * ===================================================================
 */

var DEFAULT_LANG = 'en';
var webContext = '/ieat'; // default context
var myLang = 'en_US'; // default lang

/**
 * Get a JavaScript message variable for a given language.
 *
 * This method will attempt to return the variable
 * associated with 'key' and 'lang'. The 'lang' format
 * can be 'en_US' or just 'en'. If the variable is found
 * it's value is returned, otherwise an empty string
 * is returned.
 *
 * If 'params' is passed, it should be an array of String
 * objects, which will be substituted into the message
 * value by index, starting at 1, with brace delimiters.
 * For example "The {1} value is required" along
 * with an array ['name'] would result in the message
 * "The name value is required."
 *
 * This is a crude way to store internationalized messages
 * for JavaScript functions.
 *
 * GLOBAL VARIABLE: myLang
 *
 * @param key the JavaScript variable name, without langugage
 * @param lang the desired language (optional)
 * @param params an array of parameter values
 */
function getMessage(key,lang,params) {
	if ( !lang ) {
		lang = myLang;
	} else {
		if ( typeof(lang) != 'string' ) {
			if ( lang.length ) {
				// already an array
				params = lang;
			} else {
				params = new Array();
				params[0] = lang;
			}
			lang = myLang;
		}
	}
	if ( !lang ) {
		alert("! Language not available");
		return '';
	}
	var res;
	if ( eval('typeof ' +key+'_'+lang) != 'undefined' ) {
		res = eval(key+'_'+lang);
	} else {
		var idx = lang.indexOf('_')
		if ( idx > 0 ) {
			if ( eval('typeof ' +key+'_'+lang.substring(0,idx)) != 'undefined' ) {
				res = eval(key+'_'+lang.substring(0,idx));
			}
		}
	}
	if ( !res ) {
		res = '';
	} else if ( params ) {
		var i = 0;
		for ( i = 0; i < params.length; i++ ) {
			res = res.replace(new RegExp('\\{'+(i+1)+'\\}','g'),params[i]);
		}
	}
	return res;
}

function removeChildren(node) {
	if ( !node ) return;
	while ( node.hasChildNodes() ) {
		node.removeChild(node.firstChild);
	}
}

function replaceAttribute(node,attributeName,matchValue,replaceValue) {
	// NOTE nodeType 1 == Node.ELEMENT_NODE in sane browsers
	if ( node.nodeType == 1 && node.getAttribute(attributeName) != null ) {
		var attributeValue = node.getAttribute(attributeName);
		var re = new RegExp(matchValue);
		attributeValue = attributeValue.replace(re,replaceValue);
		node.setAttribute(attributeName,attributeValue);
	}
	if ( node.hasChildNodes() ) {
		var child = node.firstChild;
		while ( child != null ) {
			replaceAttribute(child,attributeName,matchValue,replaceValue);
			child = child.nextSibling;
		}
	}
}

function findNodeWithAttributeValue(node,attributeName,matchValue) {
	// NOTE nodeType 1 == Node.ELEMENT_NODE in sane browsers
	if ( node.nodeType == 1 && node.getAttribute(attributeName) != null ) {
		var attributeValue = node.getAttribute(attributeName);
		var re = new RegExp(matchValue);
		if ( attributeValue.search(re) >= 0 ) {
			return node;
		}
	}
	if ( node.hasChildNodes() ) {
		for ( var child = node.firstChild; child != null; child = child.nextSibling ) {
			var n = findNodeWithAttributeValue(child,attributeName,matchValue);
			if ( n != null ) {
				return n;
			}
		}
	}
}

/**
 * Event handler to trim <textarea> elements.
 * 
 * This handler exists because browsers seem to freak out with XHTML 
 * <textarea/> tags (without any content). Forms can install this 
 * handler on all <textarea> objects by calling the 
 * installTextAreaFocusHandler() method below.
 */
function focusTrimTextArea(event) {
	if ( event.target && event.target.value && event.target.value.search(/^\s+$/) == 0 ) {
		event.target.value = '';
	}
}

/**
 * Sets the 'onfocus' handler for all <textarea> objects to the 
 * focusTrimTextArea method.
 */
function installTextAreaFocusHandler() {
	var textAreaNodes = document.getElementsByTagName('textarea');
	if ( textAreaNodes ) {
		for ( var i = 0; i < textAreaNodes.length; i++ ) {
			textAreaNodes.item(i).onfocus = focusTrimTextArea;
		}
	}
}

/**
 * Initialize <a rel="popup|..." popup links.
 * 
 * Adapted from http://www.sitepoint.com/print/xhtml-strict-popups
 * 
 * This allows us to code links without JS popups, but add popup
 * support to links dynamically as needed.
 */
function popupWindows() {
	if ( !document.getElementsByTagName ) { 
		// bummer, no support. links will open in window, not popup
		return; 
	}

	var scrW = screen.availWidth; 
	var scrH = screen.availHeight; 
	var anchors = document.getElementsByTagName("a"); 
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i]; 
		var rel = anchor.getAttribute("rel"); 
		if ( !(rel && rel.indexOf("popup|") == 0) ) {
			// not a popup link, skip
			continue;
		}
		var linkDest = anchor.getAttribute("href"); 
		var relSplit = rel.split("|"); 
		var windowAttributes = ""; 

		if (relSplit[1] > scrW) { 
			pW = scrW - 10; 
		} else { 
			pW = relSplit[1]; 
		} 
		if (relSplit[2] > scrH) { 
			pH = scrH - 40; 
		} else { 
			pH = relSplit[2]; 
		} 
		scrX = (scrW - pW - 10) * .5; 
		scrY = (scrH - pH - 30) * .5; 
		var windowAttributes = "width=" + pW + ",height=" + pH + ",left=" + scrX + ",top=" + scrY + ",screenX=" + scrX + ",screenY=" + scrY; 
		windowAttributes += ",location=" + relSplit[4] + ",resizable=" + relSplit[4] + ",scrollbars=" + relSplit[4]; 
		anchor.onclick = popupWin(linkDest,windowAttributes);
	} 
}

function popupWin(link,attribs) {
	return function(event) {
		window.open(link,'winPopup',attribs);
		return false;
 	}
}

if ( !window.console ) {
	// mock console.log in browsers without native support
	var console = {
		log : function(o) {
			// ignore
		}
	};
}

var XwebLocale = new XwebLocaleClass();
$(document).ready(function() {
	// look for our context path in the head/@profile attribute
	$('head').each(function() {
		var profile = $(this).attr('profile');
		if ( profile ) {
			var myContext = profile.match(/^(.*)\/profile.txt\?lang=(.*)$/);
			if ( myContext ) {
				webContext = myContext[1];
				myLang = myContext[2];
			}
		}
	});
	$.getJSON(webContext + '/messages.json',
		function(data){
			XwebLocale.initJson(data);
		});
});
