/* Reference Article:
Dustin Diaz:
http://www.dustindiaz.com/top-ten-javascript/
*/
var CommonJs = true;
/* addEvent: simplified event attachment */
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);

/* window 'load' attachment */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

/* grab Elements from the DOM by className */
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;
}

/* toggle an element's display */
function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/* Array prototype, matches value in array: returns bool */
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

/* get, set, and delete cookies */
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";
}



//======================================================================


var ClickBtn = function( btnId/*string*/, returnValue/*boolean*/ ){
    var btnCtrl = GetObj(btnId);
    
    if (!btnCtrl) return false;

    if(returnValue==null)returnValue = false;
    
    if (btnCtrl.dispatchEvent) {
        //check if this is an href link
        var linkHref = btnCtrl.getAttribute("href");

        //get event for the normal click functionality
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        btnCtrl.dispatchEvent(e);

        //incase of an link, trigger the link
        if (linkHref) {
            location.href = linkHref;
        }
    }
    else {
        btnCtrl.click();
    }

    return returnValue;
}

//function is used for asp.net button controls
var DoServerClick = function( btnObjId/*string*/, eventArgument/*string*/, returnValue/*boolean*/ ){
    if(btnObjId==null) return false;
    if(eventArgument==null) eventArgument = '';
    if(returnValue==null) returnValue = false;
    
    //alert("DoServerClick: " +    btnObjId + ", eventArgument: " + eventArgument +", returnValue: " + returnValue + ", __doPostBack: " + (__doPostBack!=null) + ", onClick: " + (GetObj(btnObjId).click!=null) );
    //this is more of a firefox workarround -- firefox can't seem to handle btn.click() - so use the asp.net submit form method if it exists
    if(__doPostBack!=null){
        __doPostBack( btnObjId, eventArgument );         
    }
    else ClickBtn(btnObjId,returnValue);
    
    return returnValue;
}

function CheckIfHitEnter( e, btnObjId/*string*/, doServerClick/*boolean*/ ){
    
    
    //TraceObject("caller", e ); //if (window.event && window.event.keyCode == 13){     
    
    if (e && e.keyCode == 13){     
        //alert("CheckIfHitEnter: " +    btnObjId + ", doServerClick: " + doServerClick +", __doPostBack: " + __doPostBack  );
        if(doServerClick) DoServerClick(btnObjId,'',false);
        else ClickBtn(btnObjId);
        
        return false;
    }
    return true;
}

function GetObj(objId){
    return GetObjRef(objId); 
}

function GetObject(objId){
    return GetObjRef(objId); 
}

//Support for older browser types
if(document.all && !document.getElementById) {
    document.getElementById = function(id) {
         return document.all[id];
    }
}

function GetMxObj(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);
    }
}

/* quick getElement reference */
function GetObjRef() {
	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;
}

function TraceObject(title, obj, writeToObj, showKeysOnly ){
    if( title==null ) title = "INFO";
    if( obj==null )return ( title + ": NULL OBJ" );
    if(showKeysOnly==null)showKeysOnly = false;
    
    var line = "";
    var columnCount = 0;
    
    for( var index in obj ){
        try{
            if(showKeysOnly){
                if(columnCount>3){
                    columnCount = 0;
                    line += "\n";
                }
                
                if( columnCount>0 ){
                    line += ",  ";
                }
                
                line += "key: " + index;
                
                ++columnCount;
            }
            else line += "key("+line.length+"): " + index + ", value: "+ obj[index] + "\n";
        }catch(exception){ var dummy = 1;}
    }
    
    if( writeToObj!=null ){
        if( writeToObj.value!=null ) writeToObj.value = title + "("+line.length+"):\n" + line;
        if( writeToObj.innerText!=null ) writeToObj.innerText = title + "("+line.length+"):\n" + line;
        if( writeToObj.innerHTML!=null ) writeToObj.innerHTML = "<textarea>" + title + "("+line.length+"):\n" + line + "</textarea>";        
    } 
    alert(title + "("+line.length+"):\n" + line);
}

var TraceObj = TraceObject;

var Client = {   
    viewportWidth: function() {     
        return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);   
    },   
    viewportHeight: function() {     
        return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);  
    },      
    viewportSize: function() {     
        return { width: this.viewportWidth(), height: this.viewportHeight() };  
    } 
}; 


//======================================================================
function ToDateTimeString( value, showMilliseconds ){
    if(!IsDate(value)) value = new Date();
    
    var output = "";
    
    output += value.getDate().toString() + "/";
    output += (value.getMonth()+1).toString() + "/";
    output += value.getFullYear().toString();
    output += " ";
    output += value.getHours().toString() + ":";
    output += value.getMinutes().toString() + ":";
    output += value.getSeconds().toString();
    if(showMilliseconds) output += ":" + value.getMilliseconds().toString();
    
    return output;
}

function ToDateString( value ){
    if(!IsDate(value)) value = new Date();
    
    var output = "";
    
    output += value.getDate().toString() + "/";
    output += (value.getMonth()+1).toString() + "/";
    output += value.getFullYear().toString();
    
    return output;
}

function ToTimeString( value, showMilliseconds ){
    if(!IsDate(value)) value = new Date();
    
    var output = "";
  
    output += value.getHours().toString() + ":";
    output += value.getMinutes().toString() + ":";
    output += value.getSeconds().toString();
    if(showMilliseconds) output += ":" + value.getMilliseconds().toString();
    
    return output;
}

function IsDate( value ){
    if( value==null ) return false;
    return ( value instanceof Date );
}

function ToJSDateTimeFormatString( value, showMilliseconds ){
    if(!IsDate(value)) value = new Date();
    
    var output = "new Date(";
    
    output += value.getFullYear().toString() + ","; 
    output += value.getMonth().toString() + ",";
    output += value.getDate().toString() + ",";    
    
    output += value.getHours().toString() + ",";
    output += value.getMinutes().toString() + ",";
    output += value.getSeconds().toString() + ",";
    if(showMilliseconds) output += value.getMilliseconds().toString();
    else output += "0";
    
    output += ")";
    return output;
}

//======================================================================

function URLEncode( value )
{
    if(value==null ) return "";
    
    //return escape(value);
    
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	
	var encoded = "";
	
	for (var i = 0; i < value.length; i++ ) {
		var ch = value.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
    
	return encoded;
};

function URLDecode( value )
{
    if(value==null ) return "";
    
    var plaintext = "";
    //return unescape(value);
    
       
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   
   
   var i = 0;
   while (i < value.length) {
       var ch = value.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (value.length-2) 
					&& HEXCHARS.indexOf(value.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(value.charAt(i+2)) != -1 ) {
				plaintext += unescape( value.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + value.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
  
   
    return plaintext;
};
//======================================================================
function HtmlEncode( s ) 
{
	var result = "";
	for (var j = 0; j < s.length; j++ ) {
		// Encode 25% of characters
		if (Math.random() < 0.25 
		|| s.charAt(j) == ':' 
		|| s.charAt(j) == '@'
		|| s.charAt(j) == '.') { 
			var charCode = s.charCodeAt(j);
			result += "&#";
			result += charCode;
			result += ";"
		} else {
			result += s.charAt(j);
		}
	}
	return result;
}

function UrlEncode( s ) 
{
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < s.length; i++ ) {
		// Encode 25% of characters
		if (Math.random() < 0.25) { 
			var charCode = s.charCodeAt(i);
			encoded += "%";
			encoded += HEX.charAt((charCode >> 4) & 0xF);
			encoded += HEX.charAt(charCode & 0xF);
		} else {
			encoded += s.charAt(i);
		}
	} // for
	return encoded;
}


function Obfuscate( value )
{	
    return UrlEncode(value);
};


//======================================================================

function GetMousePos() {
	var posx = 0;
	var posy = 0;
	var e = window.event;
	
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
	
	return { x:posx, y:posy };
}


//======================================================================

function getContainerPosition(containerObj) {
	// This function will return an Object with x and y properties
	var useWindow=false;
	var coordinates=new Object();
	var x=0,y=0;
	// Browser capability sniffing
	var use_gebi=false, use_css=false, use_layers=false;
	if (GetObj) { use_gebi=true; }
	else if (document.all) { use_css=true; }
	else if (document.layers) { use_layers=true; }
	// Logic to find position
 	if (use_gebi && document.all) {
		x=ContainerPosition_getPageOffsetLeft(containerObj);
		y=ContainerPosition_getPageOffsetTop(containerObj);
		}
	else if (use_gebi) {
		var o=GetObj(containerObj);
		x=ContainerPosition_getPageOffsetLeft(o);
		y=ContainerPosition_getPageOffsetTop(o);
		}
 	else if (use_css) {
		x=ContainerPosition_getPageOffsetLeft(containerObj);
		y=ContainerPosition_getPageOffsetTop(containerObj);
		}
	else if (use_layers) {
		var found=0;
		for (var i=0; i<document.anchors.length; i++) {
			if (document.anchors[i].name==containerObj) { found=1; break; }
			}
		if (found==0) {
			coordinates.x=0; coordinates.y=0; return coordinates;
			}
		x=document.anchors[i].x;
		y=document.anchors[i].y;
		}
	else {
		coordinates.x=0; coordinates.y=0; return coordinates;
		}
	coordinates.x=x;
	coordinates.y=y;
	return coordinates;
	}

// getContainerWindowPosition(containerObj)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named Container, relative to the window
function getContainerWindowPosition(containerObj) {
	var coordinates=getContainerPosition(containerObj);
	var x=0;
	var y=0;
	if (GetObj) {
		if (isNaN(window.screenX)) {
			x=coordinates.x-document.body.scrollLeft+window.screenLeft;
			y=coordinates.y-document.body.scrollTop+window.screenTop;
			}
		else {
			x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
			y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
			}
		}
	else if (document.all) {
		x=coordinates.x-document.body.scrollLeft+window.screenLeft;
		y=coordinates.y-document.body.scrollTop+window.screenTop;
		}
	else if (document.layers) {
		x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
		y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
		}
	coordinates.x=x;
	coordinates.y=y;
	return coordinates;
	}

// Functions for IE to get position of an object
function ContainerPosition_getPageOffsetLeft (el) {
	var ol=el.offsetLeft;
	while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
	return ol;
	}
function ContainerPosition_getWindowOffsetLeft (el) {
	return ContainerPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
	}	
function ContainerPosition_getPageOffsetTop (el) {
	var ot=el.offsetTop;
	while((el=el.offsetParent) != null) { ot += el.offsetTop; }
	return ot;
	}
function ContainerPosition_getWindowOffsetTop (el) {
	return ContainerPosition_getPageOffsetTop(el)-document.body.scrollTop;
	}
//=========================================================================================================//	