/* GLOBALS */

/* DEBUG */

// writes debug messages
var global_debug_messages = new Array();

function debug(text)
{
	var debug_el = document.getElementById('debug_messages');
	if (debug_el) {
		// write into existing element
		debug_el.innerHTML += "<li>"+text+"</li>";
	} else {
		// queue until element exists
		global_debug_messages.push(text);
	}
}

// for browsers that don't support console
//if(typeof(console) === 'undefined') {
//    var console = {}
//    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
//}

function log(msg) {
	console.log(msg)
}

/* NAVIGATION */

// Easy way to change pages
function go( where )
{
	window.location = where;
	return false;
}

function goBack( )
{
	history.back();
}

function goExternal( where )
{
	window.open( where );
	return false;
}

// Reload current page
function reloadPage() {
	window.location.replace( unescape(window.location.pathname) );
}

// Javascript's typeof operator needs some help most of the time. These are also handy as shortcuts...
function isBoolean(a) {
	return typeof a === 'boolean';
}
function isFunction(a) {
	return typeof a === 'function';
}
function isString(a) {
	return typeof a === 'string';
}
function isNull(a) {
	return typeof a === 'object' && !a;
}
function isArray(a) {
	return typeof a === 'object' && a instanceof Array;
}
function isNumber(a) {
	return typeof a === 'number' && isFinite(a);
}
function isObject(a) {
	return (typeof a === 'object' && a) || isFunction(a);
}
function isDate(a) {
	return typeof a === 'object' && a instanceof Array;
}

// Return the result of merging 2 objects. Properties in obj2 override those from obj1.
function mergeObjects(obj1, obj2) {
	var obj3 = new Object;
	var p;
	for (p in obj1) {
		if (obj1.hasOwnProperty(p)) {
			obj3[p]= obj1[p];
		}
	}
	for (p in obj2) {
		if (obj2.hasOwnProperty(p)) {
			if (typeof(obj3[p]) == 'object') {
				obj3[p] = mergeObjects(obj3[p], obj2[p]);
			} else {
				obj3[p] = obj2[p];
			}
		}
	}
	return obj3;
}

/* STRING FUNCTIONS */

// Capitalise first letter
function capitalise(text)
{
	if (!isString(text)) return text;
	return text.charAt(0).toUpperCase() + text.slice(1);
}

// Wow, JS must be the only language I've ever used with no builtin trim/strip
function trim(s) { 
	return s.replace(/^\s+|\s+$/g,''); 
}

function randomString() {
	return String((new Date()).getTime()).replace(/\D/gi,'');
}

// Popup delete confirmation
function confirmDelete(str)
{
	return confirm('This will remove ' + str + ' from the server. Are you sure?');
}

function getViewPort()
	// Copyright: Bryan Price 2007
	// From comment posted on http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
	// Public Domain assumed as code was provided freely with no license claim.
{
	// Opera uses clientWidth when zoomed
	var e = window, a = 'inner';
	if ( !( 'innerWidth' in window ) ) {
		a = 'client';
		e = document.documentElement || document.body;
	}
	return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
function getWinWidth() { return getViewPort().width; }
function getWinHeight() { return getViewPort().height; }

// Conversion / Formatting functions

function forceInt( val ) {
	val = val.replace(/[^0-9]+/g,'');
	return parseInt(val, 10) || 0;
}

function forceFloat( val ) {
	val = val.replace(/[^0-9.]+/g,'');
	return parseFloat(val) || 0.0;
}

// toMoney -- Convert to USD/AUD currency format
// Author:  SoftComplex / Tigra
// Web Site:  http://www.softcomplex.com/forum/viewthread_4465/
// License: Public Domain. http://www.softcomplex.com/forum/viewthread_1857/

function toMoney(n_value) {
	// if NaN (like POA) just show that
	if (isNaN(Number(n_value))) return n_value;

	// save the sign
	var b_negative = Boolean(n_value < 0);
	n_value = Math.abs(n_value);

	// round to 1/100 precision, add ending zeroes if needed
	var s_result = String(Math.round(n_value * 1e2) % 1e2 + '00').substring(0, 2);

	// separate all orders
	var b_first = true;
	var s_subresult;
	while (n_value >= 1) {
		s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);
		s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
		b_first = false;
		n_value = n_value / 1e3;
	}

	// add at least one integer digit
	if (b_first) s_result = '0.' + s_result;

	// apply formatting and return
	return b_negative ? '($' + s_result + ')' : '$' + s_result;
}

// Replace all occurrences in comma-seperated list 'from' with the ones in 'to' in 'string'
// Roughly emulates Coldfusion function of the same name
function replaceList(string, from, to) {  
    var fromArray = from.split(",");  
    var toArray = to.split(",");  

    var mapTable = {};  

    var lastVal = "";
    for(i = 0; i < fromArray.length; i++) {  
        lastVal = i < toArray.length ? toArray[i] : lastVal;  
        mapTable[fromArray[i]] = lastVal;
    }

    var re = new RegExp(fromArray.join("|"), "g");
    var str = string.replace(re, function(c) {
        return mapTable[c];
    });

    return str;  
};


