DEBUG=false;

// This is a global hashmap of id to objects;
var _globalBindings_ = new Array();

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

var SUCCESS = "0";

function Onorex()
{
}

Onorex.extend = function(subClass, baseClass) 
{
   function inheritance() {}
   inheritance.prototype = baseClass.prototype;
   subClass.prototype = new inheritance();
   subClass.prototype.constructor = subClass;
   subClass.baseConstructor = baseClass;
   subClass.superClass = baseClass.prototype;
}

function getRadioSelectedValue(radio, defaultValue)
{
	for(var i=0; i<radio.length; i++)
	{
		if (radio[i].checked) return radio[i].value;
	}
	return defaultValue;
	// return (""!=radio.value.trim())?radio.value:defaultValue;
}

function isSuccessResult(a)
{
	return ((a!=null) && (a.resultCode==SUCCESS));
}

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

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

/*
is this a valid email format?
*/
function isEmailValid(emailAddress)
{
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(emailAddress) == false) {
      return false;
   }
   return true;
}

numberToShortDayString = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
numberToLongDayString = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

numberToShortMonthString = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
numberToLongMonthString = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

function formatDay(date)
{
	return numberToLongDayString[date.getDay()]+" "+numberToShortMonthString[date.getMonth()]+" "+date.getDate()+", "+date.getFullYear();
}

function convertToAMPMFormat(date)
{
	var hh = date.getHours();
	var ampm = 'AM';
	if ( hh >=12 ) 
	{
		hh = date.getHours()-12;
		ampm = 'PM';
	}
	else 
	{
		hh = date.getHours();
		ampm = 'AM';
	}
	var ret = new Array();
	ret[0] = hh;
	ret[1] = ampm;
	return ret;
}

function formatPersonName(firstName, lastName, title)
{
	var name="";
	if(firstName!=null && lastName!=null)
		name += firstName + " " + lastName;
	else
		if(firstName!=null)
			name += firstName;
		else if(lastName!=null)
			name +=lastName;
	if (!isUndefined(title) && !onorex.isEmpty(title)) name += ", " + title;
	return name;
}

function removeAllChildrenOfElement(element)
{
	if ( (null!=element) 
		&& (typeof element)!='undefined' 
		&& (typeof element.childNodes[0])!='undefined' 
		)
	{
	
	while (element.firstChild) 
 	{
		//The list is LIVE so it will re-index each call
    	element.removeChild(element.firstChild);
	}

		//var len = element.childNodes.length;
		//for(var h=0; h<len; h++)
			//element.removeChild(element.childNodes[h]);
	}
}

/********************************************************
 Positioning
********************************************************/
function findPosition(obj) 
{
	if (DEBUG) alert('findPosition()');
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/********************************************************/

function scale(/*long*/ originalWidth, /*long*/ originalHeight, /*int*/ destWidth, /*int*/ destHeight)
{
	ret = new Array();
	w = destWidth;
	h = destHeight;
    thumbRatio = destWidth / destHeight;
    imageRatio = originalWidth / originalHeight;
    if (thumbRatio < imageRatio) 
    {
      h = destWidth/imageRatio;
    } else {
      w = destHeight*imageRatio;
    }
    ret[0] = parseInt(w);
    ret[1] = parseInt(h);
	return ret;
}

/********************************************************/

function isIE()
{
	return (navigator.userAgent.indexOf("MSIE")>=0);
}

function getSourceEvent(windowEvent)
{
	var e;
	if ((typeof windowEvent)=='undefined') //IE
		e = window.event;
	else // Other
		e = windowEvent;
	
	return e;
}

function getSourceElement(windowEvent)
{
	var srcElement;
	if ((typeof window.event)=='undefined') // !IE
		srcElement = windowEvent.target;
	else // IE
		srcElement = window.event.srcElement;
	
	return srcElement;
}

/********************************************************/
function /*boolean*/ isImage(/*String*/ filename)
{
	var ret = false;
	var pos = filename.lastIndexOf(".");
	var fileExtension = filename.substring(pos+1);
	fileExtension = fileExtension.toLowerCase();
	return fileExtension!=null && 
	   (fileExtension=="jpg"
	   || fileExtension=="jpeg"
	   || fileExtension=="png"
	   || fileExtension=="gif"
	   || fileExtension=="bmp"
	   ) ;
}
/********************************************************/

/********************************************************/
function formatTime(date)
{
  var curTime;
  if((typeof date)!='undefined' && date!=null) {
  	var curHour = date.getHours()
  	var curMin = date.getMinutes()
  	var curAMPM = " AM"
  	var curTime = ""
  	if (curHour >= 12){
    	curHour -= 12
    	curAMPM = " PM"
    }
  	if (curHour == 0) curHour = 12
  	curTime = curHour + ":" 
    	+ ((curMin < 10) ? "0" : "") + curMin
    	+ curAMPM
  }
  return curTime;  
}

/********************************************************/
function formatTimeSeconds(date)
{
  var curHour = date.getHours()
  var curMin = date.getMinutes()
  var curSec = date.getSeconds()
  var curAMPM = " AM"
  var curTime = ""
  if (curHour >= 12){
    curHour -= 12
    curAMPM = " PM"
    }
  if (curHour == 0) curHour = 12
  curTime = curHour+":" 
    + ((curMin < 10) ? "0" : "")+curMin+":"+curSec
    + curAMPM

  return curTime;
}

/********************************************************/
function formatDate(date)
{		
  if((typeof date)!='undefined' && date!=null) {
	  var month = date.getMonth()
	  var year = date.getYear()
	  var day = date.getDate()
	  if(day<10) day = "0" + day
	  if(year<1000) year+=1900
	  return numberToShortMonthString[month] + "-" + day + "-" + (year+"").substring(2,4)
  } else {
  	return "";
  }
} 
            
/********************************************************/
function random()
{
	return (Math.random()*500 + "" + (new Date()).getTime()).replace(/\./g, '');
}
/********************************************************/

function bindObject(id, toObject)
{
	_globalBindings_[id] = toObject;
}

function getObject(id)
{
	return _globalBindings_[id];
}

/********************************************************/

//this function will get the current/computed style in IE and Moz/FF 
function getStyle(obj,cAttribute)
{ 
	var ret = '';
	//if IE 
	if (obj.currentStyle)
	{
		ret=eval('obj.currentStyle.'+cAttribute) 
	}else{ 
		//if Mozilla/FF 
		ret=eval('document.defaultView.getComputedStyle(obj, null).'+cAttribute) 
	} 
	return ret;
} 

/********************************************************/
function getValue(someObject, defaultValue)
{
	return ((null!=someObject) && (typeof someObject)!='undefined')?someObject:defaultValue;
}

/********************************************************/

function $(elementID)
{
	return document.getElementById(elementID);
}

function value(elementID, defaultValue)
{
	var e = document.getElementById(elementID);
	if (isUndefined(e)) return defaultValue;
	else return e.value;
}
/********************************************************/

function getFullWebsiteUrl(/*long*/ serverPort, scheme, serverName, contextPath, url)
{
	var ret = "";
	if (null==url) return ret;
	var p="";
	if (80!=serverPort && (443!=serverPort) ) p=":"+serverPort;
	ret = scheme+"://"+serverName+p+contextPath+"/"+url;
	
	return ret;
}

/********************************************************/

/*String*/ function getFullPropertyList(/*Object*/ object)
{
	var property_list;
	for (prop in object)
	{
	   property_list += prop + "\n";
	}
	return property_list;
}

/********************************************************/
var _executeWhenReadyCache_ = new Array();
function executeWhenReadyCeasePoll(elId)
{ 
    clearTimeout(_executeWhenReadyCache_['poll'+elId]);
}

function executeWhenReadyStartPoll(elId, callback)
{
    _executeWhenReadyCache_['poll_'+elId] = setTimeout(function(){executeWhenReady(elId,callback)},50);  
}        

function executeWhenReadyCleanUp(elId,callback) 
{
    executeWhenReadyCeasePoll(elId);    
    callback();
}  

function executeWhenReady(elId, callback) 
{ 
    if (document.getElementById && setTimeout) 
	{
      var el = document.getElementById(elId);
      if (el) {            
         executeWhenReadyCleanUp(elId, callback);
      } else {
         executeWhenReadyStartPoll(elId, callback);
      }
    }
}
/********************************************************/
// the object
function onorex() {}
// the static methods
onorex.getElementsByClass = function (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;
};

onorex.jsonToData = function(json)
{
	var ret = new Array();
	var rows = -1;
	var names = new Array();
	for (var i=0; i < json.feed.entry.length; i++) {
		var entry = json.feed.entry[i];
		if (entry.gs$cell.col == 1) rows++;
		if (rows==0) {
			names[entry.gs$cell.col] = entry.content.$t;
		}
		else {
			if (entry.gs$cell.col == 1) {
				n = new Array();
				ret[rows-1] = n;
			}
			n[names[entry.gs$cell.col]] = entry.content.$t;
		}
	}
	return ret;
}

onorex.jsonEditGridToData = function(sheet)
{
	var ret = new Array();
	var rows = -1;
	var names = new Array();
	for (var i=0; i < 20; i++) {
		var cell = sheet.row[0].cell[i];
		if (!onorex.isUndefined(cell)) names[i] = cell.value;
		else break;
	}
	var idx = 0;
	for (var i=1; i < 200; i++) {
		if ( onorex.isUndefined(sheet.row[i]) ) break;
		ret[idx] = new Array();
		for(var j=0; j<names.length; j++) {
			var cell = sheet.row[i].cell[j];
			if (!onorex.isUndefined(cell) && !onorex.isUndefined(cell.value) ) ret[idx][names[j]] = cell.value.trim();
			else ret[idx][names[j]] = "";
		}
		idx++;
	}
	return ret;
}


onorex.getRequestParameter = function(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

onorex.isEmpty = function(someString)
{
	if (null==someString)
	{
		return true;
	}
	else if ( (typeof someString)=='undefined' )
	{
		return true;
	}
	else if ( someString.trim().length<=0 )
	{
		return true;
	}
	return false;
}

onorex.isUndefined = function(a)
{
	return ( ((typeof a)=='undefined') || (null==a));
}

onorex.getParentElementByTagName = function(srcElement, tagName, max)
{
	var count = 0;
	while ((srcElement.tagName.toUpperCase()!=tagName.toUpperCase()) || (max==count))
	{
		srcElement = srcElement.parentNode;
		count++;
	}
	return srcElement;
}

onorex.isEmail = function(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;
	return true					
}

onorex.URLEncode = function(url)
{
	// 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 < url.length; i++ ) {
		var ch = url.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;
};

onorex.URLDecode = function(url)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < url.length) {
       var ch = url.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (url.length-2) 
					&& HEXCHARS.indexOf(url.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(url.charAt(i+2)) != -1 ) {
				plaintext += unescape( url.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + url.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};