//onerror=handleErr;
function handleErr(msg,url,l){
if(url=='javascript:void(0)') return true;
var txt="";
txt="There was an error on this page.\n\n";
txt+="Error: " + msg + "\n";
txt+="URL: " + url + "\n";
txt+="Line: " + l + "\n\n";
txt+="Click OK to continue.\n\n";
//alert(txt);
return true;
}
window._functions=[];
_log = function(){}; if(window.console) { if(typeof window.console.log !== 'unknown')  _log=console.log; }

// Figure out what browser is being used
bUserAgent = navigator.userAgent.toLowerCase();
browser = {
	safari: /webkit/.test(bUserAgent),
	opera: /opera/.test(bUserAgent),
	msie: /msie/.test(bUserAgent) && !/opera/.test(bUserAgent),
	mozilla: /mozilla/.test(bUserAgent) && !/(compatible|webkit)/.test(bUserAgent)
};// Check to see if the W3C box model is being used
boxModel = !browser.msie || document.compatMode == "CSS1Compat";

function $(id){
	elem=null;
	if (id==undefined ){elem=document;}
	else {elem = document.getElementById(id);}
//	if (elem==null) alert('Cannot find element "'+id+'"');
return elem;
}
function chr(nr) { return String.fromCharCode(nr);}
function asc(str){ return str.charCodeAt(0);}

function getWindowSize(hw) {
	var myWidth = 0, myHeight = 0;
	if( browser.msie ) {
		if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = parseInt(document.documentElement.clientWidth);
			myHeight = parseInt(document.documentElement.clientHeight);
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = parseInt(document.body.clientWidth);
			myHeight = parseInt(document.body.clientHeight); 
		}
	}else if( window.innerWidth && window.innerHeight ) {
		myWidth = parseInt(window.innerWidth);
		myHeight = parseInt(window.innerHeight);
	}
    margH=xval(getWindowStyle('marginTop'))+xval(getWindowStyle('marginBottom'));
    margH+=xval(getWindowStyle('paddingTop'))+xval(getWindowStyle('paddingBottom'));
    margW=xval(getWindowStyle('marginLeft'))+xval(getWindowStyle('marginRight'));
    margW+=xval(getWindowStyle('paddingLeft'))+xval(getWindowStyle('paddingRight'));

	if (hw=="h")	{ myHeight= myHeight-margH;	return myHeight	}
	else 			{ myWidth=myWidth-margW; return myWidth		}
}



function getWindowOffset(hw) {
	if (hw==undefined) hw="h"
	if (hw=='h'){
	    margH=xval(getWindowStyle('marginTop'))+xval(getWindowStyle('marginBottom'));
	    margH+=xval(getWindowStyle('paddingTop'))+xval(getWindowStyle('paddingBottom'));
	    return margH;
	}else{	    
	    margW=xval(getWindowStyle('marginLeft'))+xval(getWindowStyle('marginRight'));
	    margW+=xval(getWindowStyle('paddingLeft'))+xval(getWindowStyle('paddingRight'));
	    return margW;
	}
}
function getWindowStyle(styleAttr) {  
  ws=''
  try { // potentially dangerous code goes here
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    ws=document.defaultView.getComputedStyle(document.body,"")[styleAttr] ;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    ws=document.body.currentStyle[styleAttr];
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
		ws=document.body.currentStyle[styleAttr];  }
   }catch(e){} 
   return ws
}
function getElemStyle(elm, styleProp) {
	if ( typeof(elm)=="string" ){
    var elem = document.getElementById(elm);}
    else {elem=elm}
        
    if (elem.currentStyle) {
        ret= elem.currentStyle[styleProp];
    } else if (window.getComputedStyle) {
        ret= document.defaultView.getComputedStyle(elem,"")[styleProp] ;
    }
  
    return ret
}

function getAllOffsets(elm, styleAttr) {
alert('getAllOffsets is disabled');
//return 1;
	if ( typeof(elm)=="string" ){
    var elem = document.getElementById(elm);}
    else {elem=elm}
    
    hasParent=true;
    allM= 0;//xval(getElementStyle(elem,styleAttr));
    
    while (hasParent) {
	    try  {
	      elem= elem.parentNode;
	      allM=allM + xval(getElemStyle(elem,styleAttr));
	    }catch (e)  {
	     hasParent=false;
	    } 
    }

    return allM;
}
/* attach/detach Event for IE and FireFox */
function linkEvent(obj, eventName, eventHandler){
if(eventHandler==undefined&&!browser.msie) alert( 'linkEvent reqires 3 params: \n obj: '+obj+ '\n eventName: '+ eventName+ ' \n  eventHandler: '+ eventHandler);
if(eventName.substring(0,2)!=='on')  eventName='on'+eventName;
    if (obj){
        if (obj.addEventListener){
            if (eventName.substring(0,2)=='on'){
                eventName=eventName.substring(2,eventName.length);
            }
            obj.removeEventListener(eventName, eventHandler, false);
            obj.addEventListener(eventName, eventHandler, false);
        } else if (obj.attachEvent) {
        	obj.detachEvent(eventName, eventHandler)
            obj.attachEvent(eventName, eventHandler)
        }
    }
}
function unlinkEvent(obj, eventName, eventHandler){
    if (obj){
        if (obj.removeEventListener){
            if (eventName.substring(0,2)=='on'){
                eventName=eventName.substring(2,eventName.length);
            }
            obj.removeEventListener(eventName, eventHandler, false);
        } else if (obj.attachEvent) {
            obj.detachEvent(eventName, eventHandler)
        }
    }
}
function linkEventPreserve(obj, eventName, eventCode){    
	if(eventName.substring(0,2)!=='on') eventName='on'+eventName;
    var oldBody = obj.getAttribute(eventName)+'';    
    if (oldBody!=='null'){
    	if(oldBody.like('*'+eventCode+'*')) return;
    	if(oldBody.like('function*')) oldBody = "("+oldBody+")()";
    	eventCode += oldBody;
    }
    obj[eventName] = new Function ('event', eventCode );    
}

function attachOnLoad (callback) {

	if(document.attachEvent) {		
		window.attachEvent('onload',callback);			
	}else{		
		window.addEventListener('DOMContentLoaded',callback,false);	
	}	
}
//focusElement
function linkChangeFocus(scope){
  var all = scope.getElementsByTagName('*');  
  for (var i = 0; i < all.length; i++) {
    var functionBody = 'window.focusElement = this;window.onChangeFocus();';
    var oldOnFocus = all[i].getAttribute('onfocus')+'';    
    if (oldOnFocus){
    	if(oldOnFocus.like('*window.focusElement*')) continue;
    	if(oldOnFocus.like('function*')) oldOnFocus = "("+oldOnFocus+")()";
    	functionBody += oldOnFocus;
    }
    all[i].onfocus = new Function ('event', functionBody);    
  }
}
attachOnLoad( function(){ 
  window.focusElement = document.body;
  linkChangeFocus(document.body)
} ) ;
window.execOnChangeFocus= new Array() ;
window.onChangeFocus = function(){	
	if(window.execOnChangeFocus.length==0) return
	for (var i = 0; i < window.execOnChangeFocus.length; i++){
	 func=window.execOnChangeFocus[i]+'';
	 if(func.isFunction()) eval(func)
	} 
}
function focusIsIn(elem){
	el=window.focusElement;
	while (el){
		if(elem==el) {
			return true
		}
		el=el.parentNode
	}
	return false
}
function mouseEvent(elm, event){	
	var p =absolutePosition(elm);
	event.targetX=event.clientX-p.x
	event.targetY=event.clientY-p.y
	
	var par = elm
	while( par = par.parentNode ){
		if(par.scrollLeft) event.targetX += par.scrollLeft
		if(par.scrollTop) event.targetY += par.scrollTop
	}
	return event
}
function xval(expr){
	if (!isNaN(expr*1)) {return expr*1}
	
	if(expr.split!==undefined){ //is string
		nInt=expr.split('.')[0].replace(/\D/gi,'')
		nDec= expr.split('.')[1]
		if(nDec!==undefined){
			number=nInt+'.'+nDec.replace(/\D/gi,'');
		}else{
			number=nInt;
		}
	}else{
		number=expr
	}
	if (isNaN(number*1)) {return 0} else{return number*1}

}
function getChildNodes(element, attribute, value) {
    var ar = new Array();
    if(typeof element == 'string') element=$(elementId)
    var ac = element.childNodes;
    for (var c=0; c<ac.length; c++) 
    	if (value? (ac[c][attribute] == value) : (ac[c][attribute])) ar.push(ac[c]);
    return ar;
}
function getChildren(elementId, attribute, value) {
    var ar = new Array();
    var ac = document.getElementById(elementId).getElementsByTagName('*');
    //var ac = document.getElementById(elementId).childNodes;
    for (var c=0; c<ac.length; c++) 
    	if (value? (ac[c][attribute] == value) : (ac[c][attribute])) ar.push(ac[c]);
    return ar;
/* Sample
var col1 = getChildren(my_element, className, menuitem);
var col2 = getChildren(my_element, nodeName, IMG);
var col3 = getChildren(my_element, onclick);
The third parameter (value) is optionalif undefined the function will return any element with specified attributename, regardless value.
*/
}
function getChildrenMatch(elementId, attribute, value) {
    var ar = new Array();
    var ac = document.getElementById(elementId).getElementsByTagName('*');
    for (var c=0; c<ac.length; c++) 
    	if (value? (ac[c][attribute].match(value) ) : (ac[c][attribute])) ar.push(ac[c]);
    return ar;
}
//onselectstart works only in IE. to prevent text mouse selection:
function disableSelection(target){
if(target==null)return
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}

	ch = target.getElementsByTagName('DIV')
	for (var i =0;i< ch.length;i++)	{
//		console.log('ch['+i+']',ch[i],ch[i].tagName);
		target=ch[i]
			
			if (typeof target.onselectstart!="undefined") //IE route
				target.onselectstart=function(){return false}
			else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
				target.style.MozUserSelect="none"
			else //All other route (ie: Opera)
				target.onmousedown=function(){return false}
		
	} 
}

function enableSelection(target){

	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=""
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect=""	
	else //All other route (ie: Opera)
		target.onmousedown=""

	ch = target.getElementsByTagName('DIV')
	for (var i =0;i< ch.length;i++)	{
//		console.log('ch['+i+']',ch[i],ch[i].tagName);
		target=ch[i]

		if (typeof target.onselectstart!="undefined") //IE route
			target.onselectstart=""
		else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
			target.style.MozUserSelect=""	
		else //All other route (ie: Opera)
			target.onmousedown=""
	} 

}

if(window.Event) Event.prototype.keyCode=Event.which;
function keycode(e){
	if(window.event)  // IE	
		keynum = e.keyCode;
	else if(e.which)  // Netscape/Firefox/Opera		
		keynum = e.which;	
return keynum;
}

function stopEvent(e){
	if(browser.msie){
	  e.returnValue = false;
	  e.cancelBubble = true;
	}else{
	  e.preventDefault();
	  e.stopPropagation();
	}
}

String.prototype.like = function(String2,wildcard){
	if (wildcard==undefined) wildcard="*";
	String1=this.toLowerCase()
	String2=String2.toLowerCase()
	var Items, Pos;
	Items = String2.split(wildcard);
	if (Items.length == 1)	return(String1 == String2);
	
	Pos = 0;
	for (var Count=0; Count<Items.length; Count++)	{
		if (Count == 0)		{
			if ((Pos = String1.indexOf(Items[Count], Pos)) != 0)
			return(false);
		}else{
			if ((Pos = String1.indexOf(Items[Count], Pos)) == -1)
			return(false);
		}
		Pos = Pos + Items[Count].length;
	}
	return(true);
}

String.prototype.isNumber = function(){	return (parseInt(this).toString()!=='NaN');}
String.prototype.val = function(){		return xval(this)}
String.prototype.replaceLastChar = function(str){	return this.substr(0,this.length-1) + str }

String.prototype.isFunction = function(){
	var funcName = this.split("(")[0];	
	var isFunc = eval("typeof " + funcName + " == 'function'")
	return isFunc
/*	
	if(window._functions[funcName]===true) return true;
	if(window._functions[funcName]===false) return false;
	
	var isFunc = true
	ident='';
	idents = funcName.split(".");	
	for (var i = 0; i < idents.length-1; i++)	{
	 ident += idents[i] ;
	 if (i!==idents.length-2)  ident += '.';	 
	} 
	if(ident) if (!eval(ident)) isFunc = false;
	if (isFunc && ident.isNumber() ) isFunc = false
	if(isFunc) isFunc = eval("typeof " + funcName + " == 'function'")
	window._functions[funcName]=isFunc;
	return isFunc;	
*/
}

String.prototype.titleCase = function(){	
	var parts = this.split(' '); var str='';
	for (var i = 0; i < parts.length; i++){
	 str += parts[i].substr(0,1).toUpperCase() + parts[i].substr(1,parts[i].length-1) 
	 if(i < parts.length-1) str+=' '
	} 
	return str
}

frameObj=''

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

String.prototype.trim = function() {	return this.replace(/^\s+|\s+$/g,"");}
String.prototype.ltrim = function() {	return this.replace(/^\s+/,"");}
String.prototype.rtrim = function() {	return this.replace(/\s+$/,"");}
  
	
function cloneObject(what){
	for (var i in what){
		if (typeof what[i] == 'object')
			this[i] = new cloneObject(what[i]);
		else
			this[i] = what[i];
	}
}

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');//'
	str=str.replace(/\"/g,'\\"');	
	str=str.replace(/\0/g,'\\0');
	str=str.replace(/\r/g,'<nl>');
		
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');//"
	str=str.replace(/\\\\/g,'\\\\');
//	str=str.replace(/\\t/gi,'\t')
//	str=str.replace(/\\n/gi,'\n')
//	str=str.replace(/\\r/gi,'\r')
//	str=str.replace(/\\0/g,'\0');
	str=str.replace(/<nl>/gi,'\r\n');
return str;
}


function extender( ){
	
	this.name 	= null;
	this.elem 	= null;
	this.clasa 	= this.extender.clasa;
	
	var id 	= this.extender.id ;	
	this.id= id;
	
	this.name 	= id;
	this.elem 	= $(id);
	if(!this.elem ) this.elem 	= this;	
	
	//find parent id and control id
	spos = this.id.lastIndexOf(".");
	this.controlId 	= this.id.substr(spos+1);
	this.frameDot 	= this.id.substring(0,spos);
	this.parentId=this.frameDot;
	if(this.frameDot)this.frameDot+='.';

	this.top 	= function(top)		{ if (top==undefined) 	{var d = this.elem.style.top.val(); return (d?d:this.elem.offsetTop); }; this.elem.style.top= top ; this.updPosition();  } ;	
	this.left 	= function(left)	{ if (left==undefined) 	{var d = this.elem.style.left.val(); return (d?d:this.elem.offsetLeft); }; this.elem.style.left= left ;	this.updPosition();	} ;	
	this.width 	= function(width)	{ if (width==undefined) {var d = this.elem.style.width.val(); return (d?d:this.elem.offsetWidth); }; if (width<0) return; this.elem.style.width= width ; this.fireResize(); 	} ;	
	this.height = function(height)	{ if (height==undefined){var d = this.elem.style.height.val(); return(d?d:this.elem.offsetHeight);}; if (height<0) return; this.elem.style.height= height ;this.fireResize(); };
	
	this.visible 	= function(visible)	{ if (visible==undefined) return (this.elem.style.visibility=='visible'); this.elem.style.visibility= visible ? 'visible':'hidden';	} ;
	this.position = function(position){ if (position==undefined) return this.elem.style.position; this.elem.style.position= position ;} ;
	
	this.updPosition	  = function(){ if(this.position()=='relative'||this.position()=='absolute') return;
	if (this.elem.style.left && this.elem.style.top && this.position()!=='relative'){ this.position('absolute')} else {this.position('relative')};	}
	
	this.fireResize	  = function(){
	//	setWindow()
		if(this.id)raiseEvent(this.id+'.resize') ;
	}

	this.refresh	= function(){ 	
		var h=this.elem.style.height
		var w=this.elem.style.width
		var t=this.elem.style.top
		var l=this.elem.style.left
		refreshCtl (this.clasa, this.controlId , this.parentId);
		if($(this.id)) this.elem 	= $(this.id);
		if(t) this.elem.style.top=t
		if(l) this.elem.style.left=l
		if(w) this.elem.style.width=w
		if(h) this.elem.style.height=h
		this.updPosition();
		setTimeout(this.fireResize,1000)
	} ; 
	
	this.controls=function(clasa){		
		var ar = new Array();
		for (var i in this){
			if (this[i] !== null) {
				if (typeof this[i] == 'object' && this[i].clasa!==undefined) {
					if((clasa==undefined||this[i].clasa==clasa)){
						//_log(this[i]);
						ar.push(this[i]);
					}					
				}
			}
		}
		return ar;
	}
}
window.controls=function(clasa){
	var ar = new Array();
	for (var i in window){		
		if (window[i] !== null) {
			if (typeof window[i] == 'object' ) {
				try { // potentially dangerous code goes here 
					if(this[i].clasa && (clasa==undefined||window[i].clasa==clasa)){
//						_log('found',window[i]);
						ar.push(window[i]);
					}					
				}catch(e){} 
			}
		}
	}
	return ar;
}
function setWindow(){
	window._height = getWindowSize('h')-2;
	window._width = getWindowSize('w')-2;	
	window.height=function(){	return window._height	}	
	window.width=function(){	return window._width 	}
}

//window resize event
linkEvent(window,"resize",function(){  
							setWindow();
							raiseEvent('window.resize')  
							});

attachOnLoad( function(){ 
			setWindow();
			raiseEvent('window.resize') ;
			//setTimeout(function(){raiseEvent('window.resize')},100);
			window.loaded=true;
		} ) ;


function getStyleClass (className) {
  var re = new RegExp("\\." + className + "$", "gi");
  if (document.all) {
    for (var s = 0; s < document.styleSheets.length; s++)
      for (var r = 0; r < document.styleSheets[s].rules.length; r++)
        if (document.styleSheets[s].rules[r].selectorText.search(re) != -1) {
          return document.styleSheets[s].rules[r].style;
        }
  }
  else if (document.getElementById) {
    for (var s = 0; s < document.styleSheets.length; s++)
      for (var r = 0; r < document.styleSheets[s].cssRules.length; r++)
        if (document.styleSheets[s].cssRules[r].selectorText.search(re) != -1) {
          document.styleSheets[s].cssRules[r].sheetIndex = s;
          document.styleSheets[s].cssRules[r].ruleIndex = s;
          return document.styleSheets[s].cssRules[r].style;
        }
  }
  else if (document.layers)
    return document.classes[className].all;

  //alert('getStyleClass returns null for selector:'+className)
  return null;
}  
function getStyleClassProperty (className, propertyName) {
  var styleClass = getStyleClass(className);
  if (styleClass)
    return styleClass[propertyName];
  else 
    return null;
}

function createStyleTag(styleDef){
//alert(styleDef)
	var ss1 = document.createElement('style');	
	ss1.setAttribute("type", "text/css");
	if (ss1.styleSheet) {   // IE
	    ss1.styleSheet.cssText = styleDef;
	} else {                // the world
	    var tt1 = document.createTextNode(styleDef);
	    ss1.appendChild(tt1);
	}
	var hh1 = document.getElementsByTagName('head')[0];
	hh1.appendChild(ss1);
}
function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // *     example 1: number_format(1234.5678, 2, '.', '');    returns 1: 1234.57     
	if(number.split!==undefined){ //is string
		number=xval(number)
	}

    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) : "");
}


// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
};
if (!Array.prototype.pop) {
	Array.prototype.pop = function array_pop() {
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
};
Array.prototype.remove = function(from, to) {
	/* Array Remove - By John Resig (MIT Licensed)
	array.remove(1); // Remove the second item from the array
	array.remove(-2);// Remove the second-to-last item from the array
	array.remove(1,2);// Remove the second and third items from the array
	array.remove(-2,-1);// Remove the last and second-to-last items from the array
*/	  var rest = this.slice((to || from) + 1 || this.length);
	  this.length = from < 0 ? this.length + from : from;
	  return this.push.apply(this, rest);
};
Array.prototype.uniqueAdd = function(value) {
	var found = false;
	for (var i = 0; i < this.length; i++) if (this[i]==value) found=true
	if(!found) this.push(value) 
}
Array.prototype.uniqueExists = function(value) {
	var found = false;
	for (var i = 0; i < this.length; i++) if (this[i]==value) found=true
	return found;
}
Array.prototype.find = function(searchStr) {
	//http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}

Array.prototype.multiSort = function(index,ascend, asDate){
	if(ascend==undefined) ascend =true;	
	
	this.sort(function (a,b) {
	a = a[index];
	b = b[index];
	if(asDate) {a = numDate(a);b = numDate(b)}
	
	if(ascend)
		return a == b ? 0 : (a < b ? -1 : 1)
	else
		return a == b ? 0 : (a < b ? 1 : -1)
	}
	)
} 


function getSelection(textareaElement) {
// Cross Browser selectionStart/selectionEnd Copyright (c) 2005-2007 KOSEKI Kengo
/* 			USAGE	:
var s = getSelection(document.getElementById("textAreaId"));

alert("start:" + s.start + ", end:" + s.end);
*/
    this.element = textareaElement;
	this.create = function() {
		sd=this.element.style.display;
		if(sd=='none') this.element.style.display='block';
	    if (document.selection != null && this.element.selectionStart == null) {
	        return this._ieGetSelection();
	    } else {
	        return this._mozillaGetSelection();
	    }
	    
	}
	
	this._mozillaGetSelection = function() {
	    return { 
	        start: this.element.selectionStart, 
	        end: this.element.selectionEnd 
	    };
	}
	
	this._ieGetSelection = function() {
	    this.element.focus();
	
	    var range = document.selection.createRange();
	    var bookmark = range.getBookmark();
	
	    var contents = this.element.value;
	    var originalContents = contents;
	    var marker = this._createSelectionMarker();
	    while(contents.indexOf(marker) != -1) {
	        marker = this._createSelectionMarker();
	    }
	
	    var parent = range.parentElement();
	    if (parent == null || parent.type != "textarea") {
	        return { start: 0, end: 0 };
	    }
	    range.text = marker + range.text + marker;
	    contents = this.element.value;
	
	    var result = {};
	    result.start = contents.indexOf(marker);
	    contents = contents.replace(marker, "");
	    result.end = contents.indexOf(marker);
	
	    this.element.value = originalContents;
	    range.moveToBookmark(bookmark);
	    range.select();
	
	    return result;
	}
	
	this._createSelectionMarker = function() {
	    return "##SELECTION_MARKER_" + Math.random() + "##";
	}
	
	return this.create();
}

function absolutePosition(elem, relElem) {
	if(relElem==undefined) relElem = document.body;
	var curleft = curtop = 0;
	if (elem.offsetParent) {
		do {
			if(elem==relElem) break;
			curleft += elem.offsetLeft;
			curtop += elem.offsetTop;

			if(elem!==document.body){
				curleft -= elem.scrollLeft;
				curtop -= elem.scrollTop;
			}
//			log(elem.id,elem.offsetLeft, elem.offsetTop, curleft,curtop);
	
		} while (elem = elem.offsetParent );
	}
return { x:curleft , y:curtop }
}

function present(ob){  alert( describe(ob))}

function describe(ob){
	var str='';
	var obv='';
	if(ob==window) str = 'window '+chr(13);
	else if(ob==document) str = 'document '+chr(13);
	str+=typeof ob + chr(10);
	for (var i in ob){
		if(typeof ob[i]=='string' || typeof ob[i]=='number') obv=ob[i]; else obv='';
		str+= i  + chr(9)+ ' is ' + typeof ob[i] + ' ' + obv +chr(13)+chr(10);	
	}
	return str;
}
function smallScreen(){
	var ifr=parent.document.getElementById('baseFrame')
	if(!ifr) return
	ifr.style.width=240;
	ifr.style.height=250;
	ifr.frameBorder="yes";
}
function linkEventsFrame(scope){
	if( typeof scope.load =='function') 		scope.load();
	scopeId = (scope==window) ? 'window': (scope.id==undefined?'window':scope.id);
	scopeId+=".";
	
	linkWindowEvent(scopeId+'keydown');
	linkWindowEvent(scopeId+'keyup');
	linkWindowEvent(scopeId+'keypress');
	linkWindowEvent(scopeId+'mousedown');
	linkWindowEvent(scopeId+'mousemove');
	linkWindowEvent(scopeId+'mouseup');	
}
function linkWindowEvent(eventFunc,eventName){
	if(eventName==undefined) eventName = eventFunc.split('.')[1];
	var evF = new Function("event","event=event?event:window.event;"+eventFunc+"(event)");			
	if( eval("typeof "+eventFunc) =='function') 	{linkEvent( document , eventName , evF )}
}


attachOnLoad( function(){ 
	if(!parent.srvLoginCheck)	{ //check that this is not a iframe
		loginCheck()
	}else{
		parent.loginCheck()
	}
	});
function replaceElement(newElem,oldElem){	oldElem.parentNode.replaceChild(newElem,oldElem) }      

function setBorderStyle(elm,bStyle){
	elm.style.borderTopStyle=bStyle;
	elm.style.borderLeftStyle=bStyle;
	elm.style.borderRightStyle=bStyle;
	elm.style.borderBottomStyle=bStyle;
}
function enableCrossDomain(){
	try {
	    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	   } catch (e) {
	    alert("Cannot enable Cross Domain: Permission UniversalBrowserRead denied.");
	   }
}
function setEvent(objName, evName, args){ 	//used in generated javascript html code
	if (args==undefined) args='';
	return " if(window."+objName+"_"+evName+") try {"+objName+"_"+evName+"("+args+");}catch(e){} "
//	return " if(window."+frameObj+objName+"_"+evName+") "+frameObj+objName+"_"+evName+"("+args+");"
	
}
function raiseEvent(eventFunc,args){			//used in javascript code
												// raiseEvent('myctl_click',['abc'])	-	 args passed as array
	if (eventFunc.isFunction())	{
		if(args==undefined){
			return eval(eventFunc+'()')
		}else{
			var func = eval(eventFunc);
			return func.apply(this,args)
		}
	}else{
		return 
	}
}
function loadScript(file){
	src= ''+file;
	var x = document.getElementsByTagName("script"); 
	for( var i=0; i < x.length; i++) {
    	if (x[i].src) {	if(x[i].src==src) return }
	}

	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = src;
	document.body.appendChild(script);

}
function refreshCtl (clsName, ctlName, frameName){

	var srv = new xhttp();
	srv.reset();
	srv.requestFile='index.php';	
	srv.setVar('refreshCtl', ctlName);
	srv.setVar('refreshCtlFrame', frameName);	
	srv.setVar('refreshClsName', clsName);
		
	srv.method='POST';
	srv.runAJAX(); 
	
	
	if(frameName=='') {elem = ctlName }else {elem = frameName+'.'+ctlName};
	element = $(elem);
	if(!element) throw "refreshCtl couldn't find element";
	parentN = element.parentNode;

	var tmpWrap = document.createElement('span');
	tmpWrap.innerHTML = srv.response;
	tmpWrap.id=ctlName+'_refreshwrap'		
	tmpWrap = parentN.appendChild(tmpWrap);
	
	newCtl = getChildren(tmpWrap.id, 'id', ctlName)[0];

	element.innerHTML = newCtl.innerHTML 
	
	tmpWrap.innerHTML=''	
	parentN.removeChild(tmpWrap);
	
	//theElem = parentN.replaceChild(newCtl, element);
		
	//execute all scripts	
	var x = element.getElementsByTagName("script"); 
	for( var i=0; i < x.length; i++) {		
		if (!x[i].src) {  eval(x[i].text); }
	}
	raiseEvent(ctlName+'._init')	

}
function addControl (className, ctlProps, parentElem){
	if(parentElem==undefined) parentElem = document.body;
	
	var srv = new xhttp();
	srv.reset();
	srv.requestFile='index.php';	
	srv.setVar('addControl', className);
	srv.setVar('ctlProps', ctlProps);
		
	srv.method='POST';
	srv.runAJAX(); 
	
	if(typeof parentElem ==='string') parentElem=$(parentElem)
	if(!parentElem) throw "addControl couldn't find parent element";

	var elem = document.createElement('span');
	elem.innerHTML = srv.response;
	elem = parentElem.appendChild(elem)
	
		
	//execute all scripts	
	var x = elem.getElementsByTagName("script"); 
	for( var i=0; i < x.length; i++) {		
		if (!x[i].src) {  
			eval(x[i].text); 
		}else{
			var s = new xhttp();
			s.requestFile=x[i].src
			s.runAJAX(); 
			try { // potentially dangerous code goes here
			eval(s.response)
			 }catch(e){} 
			
		}
	}


}
function clsAjaxCall(clsName, objId, method ){
		var srv = new xhttp();
		srv.reset();
		srv.requestFile='index.php';	
		srv.setVar('classAjax', clsName);
		
		srv.setVar('oid', objId);
		srv.setVar('function', method);

		srv.method='POST';
		return srv; 
}

function loginCheck(){	
	if(!window.srvLoginCheck)	{
		window.srvLoginCheck = new xhttp();
		window.srvLoginCheck.setVar('include', 'loginCheck');
		window.srvLoginCheck.method='GET';
	}
	window.srvLoginCheck.runAJAX(); 
	
	var splitResponse=window.srvLoginCheck.xmlhttp.responseText.split(',');
	var timeOut=splitResponse[0]
	var uid=splitResponse[1]
	var loginText = 'Logout'
	if(timeOut.match(/\D/)) {
		uid='logged-out';
		timeOut=-1;	
		var loginText = 'Login'	
	}	
	if(uidEl=$('userid'))	uidEl.innerHTML=uid;
	if(loEl=$('logout'))	loEl.innerHTML=loginText;
	
	timeOut=parseInt(timeOut)
	if(timeOut==1) alert('You are on hold !');
	
	if(timeOut>0){
		if(window.loginCheckTimeout)clearTimeout(window.loginCheckTimeout);
		window.loginCheckTimeout= setTimeout("loginCheck()",timeOut*1000*0.7);
	}
	
	return timeOut;
	
}
function _syslogout(){
	var srv = new xhttp();
	srv.requestFile='index.php';	
	srv.setVar('include', 'loginCheck');	
	srv.setVar('logout', 'true');
	srv.method='GET';
	srv.runAJAX(); 

	document.location.reload();
}

function pointInBox(x,y, t,l,w,h){
	var xInRange = (x>=l && x<=(l+w))
	var yInRange = (y>=t && y<=(t+h))
	return (xInRange && yInRange)
}
function boxOverlap(t1,l1,w1,h1,t2,l2,w2,h2){
	var a1 = pointInBox(l1, t1, t2,l2,w2,h2)
	var a2 = pointInBox(l1, t1+h1, t2,l2,w2,h2)
	var a3 = pointInBox(l1+w1, t1, t2,l2,w2,h2)
	var a4 = pointInBox(l1+w1, t1+h1, t2,l2,w2,h2)

	var b1 = pointInBox(l2, t2, t1,l1,w1,h1)
	var b2 = pointInBox(l2, t2+h2, t1,l1,w1,h1)
	var b3 = pointInBox(l2+w2, t2, t1,l1,w1,h1)
	var b4 = pointInBox(l2+w2, t2+h2, t1,l1,w1,h1)
	
	var c1 = (l1<l2 && l1+w1>l2+w2 && t1>t2 && t1+h1<t2+h2 )
	var c2 = (l2<l1 && l2+w2>l1+w1 && t2>t1 && t2+h2<t1+h1 )
	
	return (a1||a2||a3||a4||b1||b2||b3||b4 ||c1 ||c2)
}
function report(reportName){
		var url = 'http://'+window.location.hostname+'?include=reportview&dest=I&reportName='+reportName

		repWindow = window.open(url ,reportName, 'toolbar=0,location=0,status=0')
		repWindowTitle = reportName ;
		repWindow.document.title = repWindowTitle
		repWindow.onload=function(){this.document.title = repWindowTitle}
		setTimeout(function(){repWindow.document.title = repWindowTitle},1000)
}
function openPopup(href, name, props){
	if(name==undefined) name='popup'
	var url=''
	if(href.href){
		url = href.href
	}else{
		if(href.match(/http:/,'i')){
			url = href
		}else{
			url = 'http://'+window.location.hostname+href
		}
	}
	var pwin = window.open(url ,name, props)
	pwin.focus()

}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]{2,4})+$/;
if (!filter.test(email)) return false;
return true
}

// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ){
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
            (
                    // Delimiters.
                    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

                    // Quoted fields.
                    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

                    // Standard fields.
                    "([^\"\\" + strDelimiter + "\\r\\n]*))"
            ),
            "gi"
            );

//"
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;


    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec( strData )){

            // Get the delimiter that was found.
            var strMatchedDelimiter = arrMatches[ 1 ];

            // Check to see if the given delimiter has a length
            // (is not the start of string) and if it matches
            // field delimiter. If id does not, then we know
            // that this delimiter is a row delimiter.
            if (
                    strMatchedDelimiter.length &&
                    (strMatchedDelimiter != strDelimiter)
                    ){

                    // Since we have reached a new row of data,
                    // add an empty row to our data array.
                    arrData.push( [] );

            }


            // Now that we have our delimiter out of the way,
            // let's check to see which kind of value we
            // captured (quoted or unquoted).
            if (arrMatches[ 2 ]){

                    // We found a quoted value. When we capture
                    // this value, unescape any double quotes.
                    var strMatchedValue = arrMatches[ 2 ].replace(
                            new RegExp( "\"\"", "g" ),
                            "\""
                            );
//"
            } else {

                    // We found a non-quoted value.
                    var strMatchedValue = arrMatches[ 3 ];

            }


            // Now that we have our value string, let's add
            // it to the data array.
            arrData[ arrData.length - 1 ].push( strMatchedValue );
    }

    // Return the parsed data.
    return( arrData );
}
