/******************************************************
*	STRING PROTOTYPING	ballyhoos.com.au 2008
**************************************************** */

//	trim string value
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g, '');
};

String.prototype.rtrim = function(chars){
	chars = chars || "\\s";
	return this.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
/*
String.prototype.ltrim = function(chars){
	chars = chars || "\\s";
	return this.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
*/
//	encode string value for url parsing
String.prototype.encode = function(){
	return encodeURIComponent(this);
};

//	trim get var value from passed href url
String.prototype.get = function(variable, retAsURLVar, includeHashPointer){
	//	cleans
	var v = variable.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+ v +"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( this );
	if( results === null ){
		return false;
	}else{
		if( retAsURLVar ){
			if( results[1].indexOf("#") && !includeHashPointer ){
				return "&"+ v +"="+ results[1].split("#")[0].encode();
			}
			return "&"+ v +"="+ results[1].encode();	
		}
		return results[1];
	}
};
//	this extracts the self doucment value from a url string
String.prototype.urlself = function(retExt, extension){
	var selfpage = "index";
	if( !extension ) extension = ".php";
	if( this.indexOf(extension) !== -1 ){
		selfpage = this.substring(this.lastIndexOf("/") + 1, this.indexOf(extension));
	}
	return selfpage + ((retExt) ? extension : "");
};

//	counts total words in string
String.prototype.wordCount = function()
{
	var count = 0;
	var a = this.replace(/\s/g, " ").split(" ");
	for(var i = 0; i < a.length; i++) {
		 if (a[i].length > 0) {
		 	count++;
		 }
	}
	return count;
};

//	decodes json, same as ajax function decodeJson()
String.prototype.json = function()
{
	return eval('('+ this +')');
};


String.prototype.email = function()
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   	return ( !reg.test(this) ? false : true ); 
};

String.prototype.stripHTML = function()
{
	// What a tag looks like
	var matchTag = /<(?:.|\s)*?>/g;
	// Replace the tag
	return this.replace(matchTag, "");
};

/******************************************************
*	ARRAY PROTOTYPING	ballyhoos.com.au 2008
**************************************************** */

Array.prototype.max = function()
{
	var maxNo = 0;
	for (var i = 0; i < this.length; i++){
		if( parseInt(this[i]) > maxNo) {
			maxNo = parseInt(this[i]);	
		}
	}
	return maxNo;
};



/******************************************************* 
*	2007 ballyhoos.com.au
*	contact scott@ballyhoos.com.au
*	DOM 
*
****************************************************** */
var dom = {
	
	we : window.event,
	
	/* get the obj that fired the event */
	getEventElement : function(e)
	{
		var obj = false;
		
		if(window.event && window.event.srcElement){
			obj = window.event.srcElement;
		}
		else if(e && e.target){
			obj = e.target;
		}
		if(!obj){
			return false;
		}else{
			return obj;
		}
	},
	
	/* add event listners to certin elements*/
	addEvent : function(obj, evType, fn, useCapture, fireOnce)
	{
		if( obj ){
			if( obj.addEventListener ){ // FF
				obj.addEventListener(evType,fn,useCapture);
				//if( fireOnce ) obj.removeEventListener(evType, arguments.callee, useCapture);	
			}
			else if(obj.attachEvent){ // IE
				obj.attachEvent("on" + evType, fn);
				//if( fireOnce ) obj.removeEvent("on" + evType, arguments.callee);	
			}
			else{
				obj['on' + evType] = fn;
			}
		}else{
			alert( "dom.addEvent() - object doesn't exist");
		}
		
		//if( )
		//		add this later when the add Event needs only to be fired once. as it will remove itself afterwards
		//	this.removeEventListener(evType,arguments.callee, useCapture);

	},
	
	removeEvent : function(obj, evType, fn, useCapture)
	{
		if( obj ){
			if( obj.addEventListener ){ // FF
				obj.removeEventListener(evType,fn, useCapture);
			}
			else if(obj.attachEvent){ // IE
				obj.detachEvent("on" + evType, fn);
			}
		}else{
			alert( "dom.addEvent() - object doesn't exist");
		}

	},
	
	
	/*******************************
	get an element by ID 
	***************************** */
	byId : function(id, obj)
	{
		if( !obj ){
			obj = document;
		}
		obj = obj.getElementById(id);
		if( !obj ){
			//alert( "dom.byId() :: "+ id + " doesn't exist");
			return false;
		}
		return obj;
	
	},
	
	
	/********************************************
	convert passed values to objs, if they exist
	****************************************** */
	setObjects : function(array)
	{
		var objArray = [];
		for (var i = 0; i < array.length; i ++) {
			var obj = dom.byId(array[i]);
			if( obj ){
				objArray.push(obj);
			}
		}
		return objArray;
	},
	
	
	/* **************************************
	test if anthing is an object
	************************************** */
	isObject : function(value)
	{
		if( value instanceof Object ){
			return true;
		}
		return false;
	},
	
	
	/* **************************************
	set passed values as an object if exists
	************************************** */
	mkObject : function(value)
	{
		if( typeof(value) == "string" ){
			return dom.byId(value);
		}else if(typeof(value) == "object"){
			return value;
		}
		
		return false;
	},


	byTag : function(tag, obj)
	{
		if(!obj) {obj = document;}
		
		return obj.getElementsByTagName(tag);
	},

	/* ************************************
	return all tags with this class, SINGLE VALUES ONLY CHANGE
	************************************* */
	byClass : function(classname, obj)
	{
		//	store found class objects
		var classObjs = [];
		if(!obj) {obj = document;}
		// get all elements under passed obj
		var elm = dom.byTag("*", obj);
				
		for (var e = 0; e < elm.length; e ++) {
			if(dom.hasClass(elm[e], classname)){
				classObjs.push(elm[e]);
			}
		}
		return classObjs;
	},
	
	
	/* ************************************
	get all values or class attribute
	************************************* */
	getClass : function(obj)
	{
		// tests for IE naming covention that differs from FF
		var classes = dom.hasAttr(obj, ((document.all) ? "className" : "class"), true);
		if( classes ){
			return classes.split(" ");
		}
		return false;
	},
	
	
	/* ************************************
	tests to see if class exists
	************************************* */
	hasClass : function(obj, classname)
	{
		var classes = dom.getClass(obj);
		if( dom.inArray( classname, classes ) ){
			return true;
		}
		return false;
	},


	/* ************************************
	swap a class with another valued class
	************************************* */
	swapClass : function(array, value, too)
	{
		for(var i = 0; i < array.length; i ++) {
			var obj =  dom.mkObject(array[i]);
			if( obj ){
				// get class values of element
				var classes = dom.getClass(obj); 
				//alert(classes);
				if( classes ){
					for(var c = 0; c < classes.length; c ++) {
						// replace if makes passed value
						if(classes[c] == value ) {classes[c] = too;}
					}
					obj.className = classes.join(" ");
				}
			}
		}
	},
	
	/* ************************************
	addes like this ["sss", "xxx"] as array
	************************************* */
	addClass : function(array, newClassName)
	{
		for(var i = 0; i < array.length; i ++) {
			var obj =  dom.mkObject(array[i]);
			if( obj ){
				if( !dom.hasClass(obj, newClassName) ){
					if(dom.hasAttr(obj, "class", true )){
						
						newClassName = dom.hasAttr(obj, "class", true) + " " + newClassName;		
					}
					obj.className = newClassName; 
				} 
			}
		}
	},
	
	
	/* ************************************
	this gets the elements computerized styles
	eg the styles within a class of CSS
	************************************* */
	cssStyle : function(obj, property, debug)
	{
		var objStyle;
		
		// IE
		if( obj.currentStyle ){
			objStyle = obj.currentStyle[property];
		}
		// FF and Co.
		else{
			try{
				objStyle = document.defaultView.getComputedStyle( obj, null ).getPropertyValue( property );
		 	}
			catch(e){
				return false; 
			}
		}
		return ( !debug ? objStyle : dom.debug(objStyle) );
	},


	hasAttr : function(obj, type, ret)
	{
		// typical MS IE bug, "for" will return NULL
		// this bug extends IE5 - IE 7, when will this end? 
		if( type == "for" && document.all ){
			return ( !obj.attributes["for"].nodeValue ? false : ((!ret) ? true : obj.attributes["for"].nodeValue)) ;
		}
		return ( !obj.getAttribute(type) ? false : ((!ret) ? true : obj.getAttribute(type))) ;
	},

	/* *********************************
	Create a Element within the DOM
	************************************/
	create : function(tag, id)
	{	
		var el = document.createElement(tag);
		if(id) el.id = id;
		return el;
	},

	
	/* *************************************************
	adds new node to certain area, node must be created
	***************************************************/	
	addNode : function( obj_id, node, option )
	{
		// { add:"after/before" , child: "first"  }
		var obj = dom.mkObject(obj_id);

		if( obj ){
			if( option && option.add ){
				if( option.add == "before"){
					obj.insertBefore( node, ((!option.child) ? obj.firstChild : obj.childNodes[option.child] ) );
				}else{
					//obj.childNodes[opt.add].appendChild(node);
				}
			}
			// append to end of elements in obj
			else{
				obj.appendChild( node );
			}
		}
	},

	
	/* ************************************
	array = specifying the ones to remove
			otherwise it will remove all
	************************************ */
	delNodes : function(obj, targeted)
	{
		if( obj && obj.hasChildNodes ){
			
			var nodes = obj.childNodes;
			/* removed required only */
			if( targeted ){
				for(var n = 0; n < nodes.length; n++) {
					
					/* make sure that the id is set within the tag to test againist */
					/* removes the #text nodes also with tagName check */
					if(nodes[n].tagName && dom.hasAttr(nodes[n], "id" )){

						/* do they exist in the removal array */
						if( dom.inArray(nodes[n].id, targeted ) ){
							obj.removeChild( nodes[n] );   
						}
					}
				}
			}
			/* remove all */
			else{
				while ( nodes.length >= 1 )
				{
					obj.removeChild( obj.firstChild );       
				} 
			}
		}
	},
	
	/* **********************************************
	*	deletes obj and childern nodes within
	********************************************** */
	delElement : function(obj)
	{
		if(obj){
			dom.delNodes( obj );
			obj.parentNode.removeChild( obj );
		}
	},
	
	/* **********************************************
	*	custom -find a parent by classname, 
	*	function will only return 'undefined' otherwise 
	*	due to cllections array not object array returned
	********************************************** */
	delParentByClass : function(obj, classname){
		
		if( dom.hasClass(obj, classname) ){
			dom.delElement(obj);
		}else{
			dom.delParentByClass(obj.parentNode, classname);
		};
	},
	
	getParentByTag : function(obj, tag)
	{
		if( obj.tagName.toLowerCase() == tag ){
			return obj;	
		}else{
			return dom.getParentByTag(obj.parentNode, tag);
		}
	},

	getParentByClass : function(obj, classname)
	{
		if( dom.hasClass(obj, classname) ){
			return obj;	
		}else{
			return dom.getParentByClass(obj.parentNode, classname);
		}
	},


	key : function(e)
	{
		if( !e ) {e = window.event;}
		return (e.keyCode ? e.keyCode : e.which);
	},
	
	
	/* **********************************************
	not really a dom event, but a very handy function
	********************************************** */
	inArray : function( value, array, retKeys )
	{
		var keys = [];
		
		for(var i = 0; i < array.length; i++) {
			if(array[i] == value){
				/* return the found keys, if set */
				if(retKeys){
					keys.push(i);
				}else{
					return true;
				}
			}
		}
		return (retKeys) ? keys : false;
	},
	
	isArray : function(obj)
	{
		return ( typeof(obj.length) == "undefined" ? false : true );
	},
	
	/* **********************************************
	collections and arrays are different, 
	does not handle HTML Collections
	alternatively use arraddto.concat(array)
	********************************************** */
	joinArrays : function(arrayAddTo, array)
	{
		var arr = array();
		if(array.length){
			for(var i = 0; i < array.length; i++) {
				arr.push(array[i]);
			}
		}
		return arrayAddTo;
	},

	
	/* **********************************************
	not really a dom event, but a very handy function
	********************************************** */
	getMargin : function(obj)
	{
		return (isNaN(parseInt(obj.style.marginLeft))) ? 0 : parseInt(obj.style.marginLeft);
	},
	
	
	debug : function(value)
	{
		var debug = dom.byId("debug");
		if( debug ){
			debug.innerHTML = debug.innerHTML + value + "<br />";
			
		}else{
			alert("no debug container");
		}
	},
	
	
	stop : function(e)
	{
		dom.stopProp(e);
		dom.cancel(e);
	},
	
	stopProp : function(e)
	{
		if(window.event && !window.event.cancelBubble){
			window.event.cancelBubble = true;
		}
		else if(e && e.stopPropagation){
			e.stopPropagation();
		}
		
	},
	
	cancel : function(e)
	{
		if(window.event && !window.event.returnValue){
			window.event.returnValue = false;
		}
		else if(e && e.preventDefault){
			e.preventDefault();
		}
	},
	
	//	make sure this is run after the obj is added to the dom.
	parseJS : function(obj, onloadFunc)
	{
		var str = "";
		var ff  = (navigator.userAgent.indexOf( "Firefox" ) == -1 ? false : true );
		//	Firefox automactically parses JS, stop it from executing twi</>ce.
		if( obj instanceof Object && !ff ){
			//	add javascript to DOM.
			var head = dom.byTag("head")[0];
			var script 	    = dom.create("script");
				script.type = "text/javascript";

			//	find script tags
			var tags = dom.byTag("script", obj);
			for(var s = 0; s < tags.length; s++){
				str += tags[s].innerHTML;
			}
			//	add js script to head to load the js.
			if( document.all ){
				script.text = str;
			}else{
				script.innerHTML = str;
			}
			head.appendChild(script);
		}else{
			//	add js file to the DOM dynamically.
			if( !dom.byId(obj) ){
				//	show loader
				//if( ajax.loader ) ajax.showLoader();
				var head      = dom.byTag("head")[0];
				var script 	  = dom.create("script", obj);
				script.type   = "text/javascript";
				script.src    = obj; 
				//dom.debug(obj);
				head.appendChild(script);
				//	load or execute based on requested file.
				if( onloadFunc ) {
					//	make sure that the object is passed to this function and not 'e'
					//	as js will take 'e' as the above 'script' obj, not the callbacked 'e' element.
					//	what to do when the iframe has finished on the server 
					if( document.all ){
						//	IE doesn't support onload, so we use the httpRequest
						script.onreadystatechange = function(){
							if( script.readyState == "complete" ) onloadFunc();
						}
					}else{
						script.onload = onloadFunc;
					}

					//dom.addEvent(script, "load", onloadFunc, false);
				}
			}else{
				if( onloadFunc ) { onloadFunc(); }	
			}
			
		}
		return obj;
	},
	
	//	this will dynamically add string html to the dom 
	//	of the passed object, meaning javascript will be executed
	parseHTML : function(obj, html, classname)
	{
		var d = dom.create("div");
		d.className = (classname ? classname : "");
		d.innerHTML = html;
		obj.appendChild(d);
		return d;
	},
	
	/* **********************************************
	get the dimensions of the body width, height
	********************************************** */
	bodyWidth : function()
	{
		return dom.bodyDimension("Width");
	},
	
	bodyHeight : function()
	{
		return dom.bodyDimension("Height");
	},
	
	bodyDimension : function( value )
	{
		var bod = document.body;
		if( bod.scrollHeight > bod.offsetHeight ) {// all but Explorer Mac
			return eval("bod.scroll" + value );
		}else{
			// Explorer Mac;
			//would also work in Explorer 6 Strict, Mozilla and Safari
			return eval("bod.offset" + value );
		}
	},
	
	
	/* **********************************************
	get the dimensions of the browser width, height
	********************************************** */
	browserWidth : function()
	{
		return dom.browserDimension("Width");
	},
	
	browserHeight : function()
	{
		return dom.browserDimension("Height");
	},
	
	browserDimension : function( value )
	{
		// all except Explorer
		if(self.innerHeight){
			return eval("self.inner" + value );
		}
		else if( document.documentElement && document.documentElement.clientHeight ){
			// Explorer 6 Strict Mode
			return eval("document.documentElement.client" + value );
		}
		else if( document.body ){
			// other Explorers
			return eval("document.body.client" + value );
		}
		return false;
	},
	
	/* **********************************************
	get object sizes
	********************************************** */
	getHeight : function( obj, retCharPx )
	{
		return obj.offsetHeight + ((retCharPx) ? "px" : "");
	},
	
	getWidth : function(obj, retCharPx )
	{
		return obj.offsetWidth + ((retCharPx) ? "px" : "");
	},
	
	
	/* **********************************************
	get the actual viewing display of the browser
	********************************************** */
	getPageHeight : function( returnPxChar )
	{
		var h = "";
		if( dom.bodyHeight() <  dom.browserHeight() ) {
			h = dom.browserHeight();
		}else{
			h = dom.bodyHeight();
		}
		return ( !returnPxChar ) ? h : h + "px";
	},
	
	getScrollDimensions : function()
	{
		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
		    //Netscape compliant
		    scrOfY = window.pageYOffset;
		    scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		    //DOM compliant
		    scrOfY = document.body.scrollTop;
		    scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		    //IE6 standards compliant mode
		    scrOfY = document.documentElement.scrollTop;
		    scrOfX = document.documentElement.scrollLeft;
		}
		return [ scrOfX, scrOfY ];
	}
}


/*
Random Numbers within a range
function randomNo(minimum,maximum) // lower bound and upper bound
 {
     return Math.floor((Math.random() * (maximum-minimum +1))+ minimum);
 }
 
 //Usage
 alert(randomNo(3,6));

onKeyUp="javascript:charsLeft(250, this, 'char1limit');"
function charsLeft(total, obj, target)
{
	var x = document.getElementById(target);
	if( obj.value.length == 0 ){
		x.innerHTML = "(Limit 250 Characters)";
	}
	else if( obj.value.length < total ){
		x.innerHTML = "You have "+ (total - obj.value.length) +" characters remaining";	
	}else{
		x.innerHTML = "<span style=\"color:red;\">You have reached the limit of this input box</span>";
		obj.value = obj.value.substring(0, total);
	}
	
}
*/




