/*
* Last Modified: 28/02/08
*
* javaBase library
* A small library with DOM and Ajax functions.
*
* AUTHOR		Kieron (info@kd3sign.co.uk)
* VERSION		0.6.0
*/

var JSBASE = {

	//
	// DOM
	//
	getElementsByClassName: function(c) {
		var e = ( document.getElementsByTagName ) ? document.getElementsByTagName("*") : false ;
		if(e) {
			var i = 0;
			var a = Array();
			for( var x = 0; x < e.length; x++ ) {
				if( e[x].className == c ) {
					a[i] = e[x];
					i++
				}
			}
			return a;
		} else {
			return false;
		}
	},
	
	getEl: function(e) {
		if( document.e ) {
			return document.e
		} else {
			return ( document.getElementById ) ? document.getElementById(e) : false ;
		}
	},
	
	submitIt: function(e) {
		return ( document.forms[e] ) ? document.forms[e].submit() : false ;
	},
	
	removeIt: function(e) {
		var parent = e.parentNode;
		return parent.removeChild(e);
	},
	
	insertIt: function(n,r) {
		r.parentNode.insertBefore(n,r);
		return n;
	},
	
	addEvent: function( o, e, f ) {
		if(o) {
			if( o.addEventListener ) o.addEventListener(e, f, false );
			else if( o.attachEvent ) o.attachEvent( 'on'+e , f);
		}
	},
	
	removeEvent: function( o, e, f ) {
		if(o) {
			if( o.removeEventListener ) o.removeEventListener( e, f, false );
			else if( o.detachEvent ) o.detachEvent( 'on'+e, f );
		}
	},

	stopEvent: function(e) {
		if (e.stopPropagation) e.stopPropagation();
		else e.cancelBubble = true;

		if (e.preventDefault) e.preventDefault();
		else e.returnValue = false;
	},
	
	getEventEl: function(e) {
		var targ;
		if (!e) {
			var e = window.event;
		}
		if (e.target) {
			targ = e.target;
		} else if (e.srcElement) {
			targ = e.srcElement;
		}
		if (targ.nodeType == 3) {// defeat Safari bug
			targ = targ.parentNode;
		}
		return targ;
	},
		
	createElement: function(e) {
		return document.createElement(e);
	},
	
	//
	// Browser
	//
	reFresh: function() {
		return window.location.reload( false );
	},
	
	bookmarksite: function(n,u) {
		if (document.all) {
			window.external.AddFavorite(u, n);
		} else if (window.sidebar) {
			window.sidebar.addPanel(n, u, "");
		}
	},
	
	historyBack: function() {
		window.location = history.back(1);
	},
	
	isIe: function() {
		return ( navigator.userAgent.indexOf("MSIE") != -1 ) ? true : false ;
	},
	
	fileSize: function() {
		if (!document.fileSize) {
			return;
		}
		return ( document.fileSize ) * 1 ;
	},
	
	setCookie: function ( name, value, seconds ) {  
		if ( typeof( seconds ) != 'undefined' ) {  
			var date = new Date();  
			date.setTime( date.getTime() + ( seconds*1000 ) );  
			var expires = "; expires=" + date.toGMTString();  
		} else {  
			var expires = "";  
		}  
		document.cookie = name+"="+value+expires+"; path=/";  
	},
	
	getCookie: function( name ) {  
		name = name + "=";  
		var carray = document.cookie.split(';');  
		
		for( var i=0; i < carray.length; i++ ) {  
			var c = carray[i];  
			while (c.charAt(0)==' ') c = c.substring(1,c.length);  
				if (c.indexOf(name) == 0) return c.substring(name.length,c.length);  
		}  
		return null;  
	}, 
	
	deleteCookie: function( name ) {  
		this.setCookie( name , "" , -1 );  
	},
	
	urlencode: function(clearString) {
		var output = '';
		var x = 0;
		var regex = /(^[a-zA-Z0-9_.]*)/;
		
		clearString = clearString.toString();

		while (x < clearString.length) {
			var match = regex.exec(clearString.substr(x));
			if (match != null && match.length > 1 && match[1] != '') {
				output += match[1];
				x += match[1].length;
			} else {
				if (clearString[x] == ' ') {
					output += '+';
				} else {
					var charCode = clearString.charCodeAt(x);
					var hexVal = charCode.toString(16);
					output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
				}
				x++;
			}
		}
		return output;
	},
	
	urldecode: function(encodedString) {
		var output = encodedString;
		var binVal, thisString;
		var myregexp = /(%[^%]{2})/;
		while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') {
			binVal = parseInt(match[1].substr(1),16);
			thisString = String.fromCharCode(binVal);
			output = output.replace(match[1], thisString);
		}
		return output;
	},

	//
	// Input
	//
	isNumeric: function( sText ) {
		var ValidChars = "0123456789";
		var Char;
		for (i = 0; i < sText.length; i++) {
			Char = sText.charAt(i);
			if (ValidChars.indexOf(Char) == -1) {
				return false;
			}
		}
		return true;
	},
	
	isValidEmail: function(s) {
	   return (s.indexOf(".") > 2) && (s.indexOf("@") > 0);
	},
	
	removeChar: function( haystack , needle ) {
		var cString = '';
		for (i=0; i < haystack.length; i++) {
			if(needle != haystack.charAt(i)) cString += haystack.charAt(i); }
		return cString;
	},
	
	formatAsMoney: function(a) {
		a -= 0;
		a = (Math.round(a*100))/100;
		return (a == Math.floor(a)) ? a + '.00' : ( (a*10 == Math.floor(mnt*10)) ? a + '0' : a);
	},

	//
	// Ajax
	//	
	xmlhttpRequest: function() {
		var xmlhttp = false;
		
		var XMLHttpFactories = [
			function () {return new XMLHttpRequest()},
			function () {return new ActiveXObject("Msxml2.XMLHTTP")},
			function () {return new ActiveXObject("Msxml3.XMLHTTP")},
			function () {return new ActiveXObject("Microsoft.XMLHTTP")}
		];
		
		for ( var i=0;i<XMLHttpFactories.length;i++ ) {
			try {
				xmlhttp = XMLHttpFactories[i]();
			}
			catch (e) {
				continue;
			}
			break;
		}
		return xmlhttp;
	},
	
	fetchUrl: function( u , callback ) {
		if(!u) return;
		var req = this.xmlhttpRequest();
		if (!req) return;
		
		req.open("GET", u, true);
		req.onreadystatechange = function() {
			if( callback ) callback(req);
		}
		if (req.readyState == 4) return;
		req.send( null );
	},
	
	postRequest: function( p , u , callback ) {
		var req = this.xmlhttpRequest();
		if (!req) return;
		
		req.open( "POST" , u , true );
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.onreadystatechange = function() {
			if( callback ) callback(req);
		}
		if (req.readyState == 4) return;
		req.send( p );

	},
	
	openWindow: function(u, w, h) {
		// Window ID
		var win_time = new Date();
		var win_id = win_time.getTime();
		
		// Overlay
		var overlay_el = this.createElement("div");
		overlay_el.className = "overlay";
		overlay_el.setAttribute("id", "overlay_"+win_id );
		
		var client_width = this.getPageSize();
		var client_height = this.getPageSize();

		this.setStyle( overlay_el , "height" , client_width[1]+"px" );
		this.setStyle( overlay_el , "width" , client_width[0]+"px" );
		
		// Add overlay to page
		var page = document.getElementsByTagName("body");
		
		this.setStyle( overlay_el , "opacity" , "0.3" );
		this.insertIt( overlay_el , page[0].childNodes[0] );
		
		// Popup
		var popup_el = this.createElement("div");
		popup_el.className = "popup";
		popup_el.setAttribute("id", "popup_"+win_id );
		
		this.setStyle( popup_el , "height" , h+"px" );
		this.setStyle( popup_el , "width" , w+"px" );
		
		this.valignElement( popup_el );
		this.alignElement( popup_el );
		
		// Close Button
		var close_btn = this.createElement("div");
		close_btn.className = "close_button";
		close_btn.innerHTML = "Close";
		
		this.addEvent( close_btn , "click" , function() { 
			JSBASE.close_popup(win_id); 
		} );
		popup_el.appendChild( close_btn );
		
		
		// iframe
		var iframe_el = this.createElement("iframe");
		iframe_el.setAttribute("src", u );
		iframe_el.setAttribute("frameborder", "0");
		iframe_el.setAttribute("scrolling", "auto");

		this.setStyle( iframe_el , "height" , ( h - 22 )+"px" );
		this.setStyle( iframe_el , "width" , ( w - 2 )+"px" );
		
		popup_el.appendChild( iframe_el );
		
		// Add popup to page
		this.insertIt( popup_el , page[0].childNodes[0] );
					
	},
	
	close_popup: function(id) {
		if( document.getElementById && document.getElementsByTagName)
		{
			var page = document.getElementsByTagName('body');
			
			var popup = document.getElementById( 'popup_'+id );
			var overlay = document.getElementById( 'overlay_'+id );
			
			page[0].removeChild( popup );
			page[0].removeChild( overlay );
		}
	},
	
	//
	// Layer Control
	//
	valignElement: function(e) {
		var elHeight = e.style.height.split('px');
		
		var array_page_size = this.getWindowSize();
		var st = this.getScrollTop();
		
		var offSetSize = parseFloat( elHeight[0] ) / 2;
		e.style.top = ( ( ( array_page_size[1] / 2 ) - offSetSize ) + st ) +'px';
	},
	
	alignElement: function(e) {
		var elWidth = e.style.width.split('px');
		var array_page_size = this.getWindowSize();		
		var offSetSize = parseFloat( elWidth[0] ) / 2;
		e.style.left = ( ( array_page_size[0] / 2 ) - offSetSize ) +'px';
	},
	
	setStyle: function( e , p , v ) {
		if ( p == 'opacity' ) {
			if (window.ActiveXObject) {
				e.style.filter = "alpha(opacity=" + v*100 + ")";
			}
			e.style.opacity = v;
		} else {
			e.style[p] = v;
		}
	},

	//
	// Dimensions
	//
	getInnerWidth: function() {
		var x ,y;
		if ( self.innerHeight ) // all except Explorer
		{
			x = self.innerWidth;
			y = self.innerHeight;
		}
		else if ( document.documentElement && document.documentElement.clientHeight ) // Explorer 6 Strict Mode
		{
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
		}
		else if ( document.body ) // other Explorers
		{
			x = document.body.clientWidth;
			y = document.body.clientHeight;
		}
		return[x, y];
	},

	getScrollingOffset: function() {
		var x,y;
		if ( self.pageYOffset ) // all except Explorer
		{
			x = self.pageXOffset;
			y = self.pageYOffset;
		}
		else if ( document.documentElement && document.documentElement.scrollTop ) // Explorer 6 Strict
		{
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		}
		else if ( document.body ) // all other Explorers
		{
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		}
		return[x, y];
	},

	getPageHeight: function() {
		var x,y;
		var test1 = document.body.scrollHeight;
		var test2 = document.body.offsetHeight
		if (test1 > test2) // all but Explorer Mac
		{
			x = document.body.scrollWidth;
			y = document.body.scrollHeight;
		}
		else // Explorer Mac;
			 //would also work in Explorer 6 Strict, Mozilla and Safari
		{
			x = document.body.offsetWidth;
			y = document.body.offsetHeight;
		}
		return[x, y];
	},

	getScrollTop: function() {
		var t;
		if (document.documentElement && document.documentElement.scrollTop) {
			t = document.documentElement.scrollTop;
		} else if (document.body) {
			t = document.body.scrollTop;
		}
		return t;
	},
	
	getWindowSize: function() {
		var window_width, window_height;
		if (self.innerHeight) {	
			window_width = self.innerWidth;
			window_height = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { 
			window_width = document.documentElement.clientWidth;
			window_height = document.documentElement.clientHeight;
		} else if (document.body) { 
			window_width = document.body.clientWidth;
			window_height = document.body.clientHeight;
		}	
		return [window_width, window_height];
	},

	getPageSize: function() {
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
	
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
	
		return [pageWidth,pageHeight,windowWidth,windowHeight];
	},
	
	//
	// Arrays
	//
	isArray: function(o) {
		return ( typeof( o.length ) == "undefined" ) ? false : true ;
	},
	
	arrayMap: function( func , haystack ) {
		if( this.isArray( haystack ) ) {
			for ( i = 0; i < haystack.length; i++ ) {
				if( func ) func( haystack[i] );
			}
		} else {
			if( func ) {
				func( haystack );
			}
		}
	}
	
};



