// common.js
// -- common functions blah blah blah


//-- capitalize the first letter of every word in a sentence
//	t: 						the text to be capitalized
//	forceList:		a comma-delimited list of items to force to a particular case
//	ignoreForce:	boolean value to allow the ignoring of the upper/lower force lists
//	-note- the forceList modifies a global value,
//	which means the list will remain in place for subsequent uses
//	until a new list is passed.  Passing a new list of an empty string 
//	clears the list out.
function capWord(t,oneTimeForceList,ignoreGlobalForce,globalForceList){
	if(typeof globalForceList == "string"){
		if (globalForceList == ""){ //clear out the global list
			globalCapWordForceList = null;
		}else{
			globalCapWordForceList = globalForceList;
		}
	}
	if (typeof t == "string" && t != ""){	//is there some text to work with here?
		var ga = [];
		if (oneTimeForceList){
			ga = oneTimeForceList.split(",");
		}else if(globalCapWordForceList && !ignoreGlobalForce){
			ga = globalCapWordForceList.split(",");
		}
		//dom.alert("<br>" + t);
		t = t.toLowerCase().replace(/\b[a-z]/g,function ($1){return $1.toUpperCase();});
		//handle the forced list
		if (ga.length > 0){			
			for (var i = 0; i<ga.length; i++){
				var rx = new RegExp("\\b" + ga[i] + "\\b", "gi");
				t = t.replace(rx,ga[i]);
			}
		}
		//dom.alert("<br>" + t);
	}
	
	return t;
}
var globalCapWordForceList;

function trim(s){
	return s.replace(/^\s*|\s*$/g,"");
}


//-- create currency from a numeric value
function formatCurrency(num) {
	if (num || num==0){
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)){
			num = "0";
		}
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10){
			cents = "0" + cents;
		}
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
			num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
		}
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	}else{
		return null;
	}
}

function formatPhone(num){
	if (num && num.toString().length == 10){
		return '(' + num.substring(0,3) + ') ' + num.substring(3,6) + '-' + num.substring(6)
	}else{
		return null;
	}

}
//-- the generic reference tool
//	pass any length list of items, by ID or reference, and get an array back of references
//	pass a single item can be used instead of document.getElementById();
//	e.g. $('foo'); vs. document.getElementById('foo'); 
function $xx() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string'){
			element = document.getElementById(element);
		}
		if (arguments.length == 1){
			return element;
		}
		elements.push(element);
	}
	return elements;
}

//-- object creator from delimited string
//	pass a delimited string with major and minor delimiters to
//	return an associative array with property/value references
//	var ar = parseDict("a:1|b:2|c:3","|",":");
//	alert(ar["a"]); //outputs 1
function parseDict(t,majorDelim,minorDelim){
	var a = new Object();
	if(t){
		var majorAry = t.split(majorDelim);
		for(var i=0;i<majorAry.length;i++){
			var minorAry = majorAry[i].split(minorDelim);
			var n = minorAry[0];
			var v = minorAry[1];
			a[n] = v;
			//dom.alert("a[" + n +"]=" + v + "<br/>",true);
		}
		//a.length = majorAry.length;
		return a;
	}
	return null;
}

// --------------------- handle events -----------------------		
// add an event handler to any object
// cross-browser event handling for IE5+, NS6 and Mozilla
// Originally By Scott Andrew
// usage addEvent(window,"load",foo,false);
function addEvent(evObj, evType, fn, useCapture) {
	var obj = $(evObj);
	if (!obj){
		console.info("addEvent error - object doesn't exist: args(",evObj, evType,")");
		return null;
	}
	var result;
	if (obj.addEventListener) {
	  obj.addEventListener(evType, fn, useCapture);
	  result = true;
	} else if (obj.attachEvent) {
	  var r = obj.attachEvent('on' + evType, fn);
	  result = r;
	} else {
	  obj['on' + evType] = fn;
	  result = true;
	}
	cacheEvent.add(obj, evType, fn, useCapture);
	return result;
}
	
// Remove an event from the object
function removeEvent (obj, evType, fn){
	if (obj.removeEventListener){
		obj.removeEventListener(evType,fn,true);
		return true;
	}else if (obj.detachEvent) {
		obj.detachEvent('on' + evType, fn);
	}else{
		obj["on" + evType] = null;
	}
}
	
// Stop an event from bubbling
function stopEvent(e){
	e || window.event;
	if (e.stopPropagation){
		e.stopPropagation();
		e.preventDefault();
	}else if(typeof e.cancelBubble != "undefined"){
		e.cancelBubble = true;
		e.returnValue = false;
	}
	return false;
}

/*	cacheEvent is a barely modified version of EventCache
		It uses an anonymous function 
		to create a hidden scope chain.
		found here: http://novemberborn.net/javascript/event-cache
------------------------------------------------------------- */
var cacheEvent = function(){
	var listEvents = [];
	
	return {
		listEvents : listEvents,
	
		add : function(node, sEventName, fHandler, bCapture){
			listEvents.push(arguments);
		},
	
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				
				/* From this point on we need the event names to be prefixed with 'on" */
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				
				item[0][item[1]] = null;
			};
		},
		list:function(){
			var i, item;
			console.info ("---- eventCache.list: " + listEvents.length + "------");
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				console.info(item);
			};
		}
	};
}();
//addEvent(window,"unload",cacheEvent.flush);


// --------------------- manage your cookies -----------------------		
// create, read and erase cookies

//create a cookie - use decimals for partial days
function createCookie(name,value,days){
	if (days)	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

//read a cookie value - will also look for sub-level matches
function readCookie(name){		
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++){
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	//did not find a top-level match, apparently, try for sub-matches name=value&
	var fc = unescape(document.cookie);
	var vStart = fc.indexOf(nameEQ);
	if (vStart > 0){
		var vEnd = fc.length;
		var ampPos = fc.indexOf("&",vStart)>0?fc.indexOf("&",vStart):null;
		var scPos = fc.indexOf(";",vStart)>0?fc.indexOf(";",vStart):null;
		if (ampPos && scPos){ vEnd = ampPos<scPos?ampPos:scPos;	}
		if (ampPos && !scPos){ vEnd = ampPos; }
		if (!ampPos && scPos){ vEnd = scPos; }
		//alert(vEnd);
		return fc.substring((vStart+nameEQ.length),vEnd);
	} 
	return null;
}

//erase a cookie
function eraseCookie(name){
	createCookie(name,"",-1);
}


//generic function to create a "request" object containing querystring variables
location.request = location.search.substr(1).split('&');
for (var i=0,len=location.request.length;i<len;i++){
	var pair = location.request[i].split('=');
	location.request[pair[0]]=unescape(pair[1]);
	location.request[pair[0].toLowerCase()]=unescape(pair[1]);
}

/*
if (!window.console || !console.firebug){
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i){
        window.console[names[i]] = function() {}
	}
}
*/