/* FROM: http://www.dustindiaz.com/top-ten-javascript/ */

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			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]);
				};
				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;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);


function getElementsByClass(searchClass,node,tag)
{
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++)
	{
		if ( pattern.test(els[i].className) )
		{
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};


function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}



function $() 
{
	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;
}


/* from: http://www.quirksmode.org/js/events_mouse.html */
function testLeaveDiv(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	if (tg.nodeName != 'DIV') return false;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg != tg && reltg.nodeName != 'BODY')
		reltg= reltg.parentNode
	if (reltg== tg) return false;
	// Mouseout took place when mouse actually left layer
	// Handle event
	return true;
}



function pageWidth()
{
	return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}
function pageHeight()
{
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;} function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;} function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}


function centerDiv(id,w,h)
{
		var top= ((pageHeight()-h)/2) > 0 ? ((pageHeight()-h)/2) : h;
		var left= ((pageWidth()-w)/2) > 0 ? ((pageWidth()-w)/2) : w;
		$(id).style.top=top+'px';
		$(id).style.left=left+'px';
		$(id).style.width=w+'px';
		$(id).style.height=h+'px';
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) 
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}


function sendEvent(swf,typ,prm)
{ 
	thisMovie(swf).sendEvent(typ,prm); 
}
function thisMovie(swf)
{
	if(navigator.appName.indexOf("Microsoft") != -1)
		return window[swf];
	else
		return document[swf];
}


/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
*
**/

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}





function number_format( number, decimals, dec_point, thousands_sep )
{
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

 
/* txt is text to display, opts are buttons objects with 'name' : function() */
function promptUser(txt,opts,title)
{
	var whiteout=document.createElement('div');
	whiteout.className='promptUserOverlay';

	// ugly hack for forcing document height:
	whiteout.style.height=(document.body.scrollHeight>document.body.offsetHeight?document.body.scrollHeight:document.body.offsetHeight)+'px';

	
	var popup=document.createElement('div');
	popup.className='promptUser';

	// add title if specified
	if (title)
	{
		var t=document.createElement('h1');
		t.innerHTML=title;
		popup.appendChild(t);
	}
	
	// add text	
	var t=document.createElement('p');
	t.innerHTML=txt;
	popup.appendChild(t);

	// add buttons
	var btnContainer=document.createElement('div');
	btnContainer.align='center';
	
	for (var name in opts)
	{
		var btn=document.createElement('input');
		btn.className='promptUserBtn';
		btn.type='button';
		btn.value=name;
		btn.callback=opts[name];
		btn.onclick=function()
		{
			//if (typeof(this.callback)=='function') this.callback(name);
			this.parentNode.parentNode.fadeOut(this);
		};
		btnContainer.appendChild(btn);
	}
	popup.appendChild(btnContainer);
	
	popup.state='open';
	popup.opacity=0;
		
	popup.fadeIn=function()
	{
		var me=this;
		
		if (this.opacity < 100) this.opacity+=10;
		
		this.style.opacity = (this.opacity / 100);
		this.style.MozOpacity = (this.opacity / 100);
		this.style.KhtmlOpacity = (this.opacity / 100);
		this.style.filter = "alpha(opacity=" + this.opacity + ")";
		
		if (this.opacity < 100 && this.state!='close') setTimeout(function(){ me.fadeIn(); }, 50);
	};

	popup.fadeOut=function(oBtn)
	{
		this.state='close';

		var me=this;
		
		if (this.opacity > 0) this.opacity-=10;
		
		this.style.opacity = (this.opacity / 100);
		this.style.MozOpacity = (this.opacity / 100);
		this.style.KhtmlOpacity = (this.opacity / 100);
		this.style.filter = "alpha(opacity=" + this.opacity + ")";
		
		if (this.opacity > 0)
		{
			setTimeout(function(){ me.fadeOut(oBtn); }, 50);
		}
		else
		{
			this.parentNode.removeChild(this.previousSibling);
			this.parentNode.removeChild(this);
			if (typeof(oBtn.callback)=='function') oBtn.callback();
		}
	};

	window.document.body.appendChild(whiteout);
	window.document.body.appendChild(popup);

	popup.fadeIn();
}



function addOption(id,text,val)
{
	var elOptNew = document.createElement('option');
	elOptNew.text = text;
	elOptNew.value = val;
	try
	{
		$(id).add(elOptNew, null); // standards compliant; doesn't work in IE
	}
	catch(ex)
	{
		$(id).add(elOptNew); // IE only
	}
}


function trace( msg )
{
	if( typeof( console ) != 'undefined' )
	{
		console.log( msg );
	}
}

function dump(obj)
{
	var txt='';
	for (var name in obj)
	{
		txt+=name+': '+obj[name]+"\n";
		if (typeof obj[name]=='object') txt+=dump(obj[name]);
	}
	return txt;
}


function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}


/* FROM: http://bytes.com/topic/javascript/answers/145532-replace-french-characters-form-input */
/* Modified by AGS to prototype native String functions */
/* (C)Stephen Chalmers
* Strips grave, acute & circumflex accents from vowels
*/

String.prototype.stripVowelAccent=function(str)
{
	var s=this;
	
	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
	/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
	/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
	/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];
	
	var repChar=['A','a','E','e','I','i','O','o','U','u'];
	
	for(var i=0; i<rExps.length; i++)
	s=s.replace(rExps[i],repChar[i]);
	
	return s;
}


function sortEngLC(a,b)
{
	a=a.toLowerCase().stripVowelAccent();
	b=b.toLowerCase().stripVowelAccent();
	return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
