if(typeof __i2rd_initted == 'undefined') {
  __i2rd_initted = true;
  
if(typeof Array.prototype.push == 'undefined') { // note: incomplete impl.
	Array.prototype.push=function(i){if(i){this[this.length]=i;}};
}
if(typeof Array.prototype.pop == 'undefined') { // note incomplete impl.
	Array.prototype.pop=function() {
	  if(this.length==0){return;}
      var i, n = this.length - 1;
	  i=this[n];
	  delete this[n];
      this.length = n;
	  return i;
	};
}
Array.prototype.pushAll = function(list) { 
	for(var h = 0, hb = list.length; h < hb; h++) {
		this.push(list[h]);
	}
};
if(typeof String.prototype.trim == 'undefined') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
  };
}

// in prototype.js also - replace by mutation event in future
if(typeof __i2rd_domupdate_event == 'undefined') { 
	__i2rd_domupdate_event = "i2rd:domupdate";
	__i2rd_domupdate_handlers = [];
	__i2rd_domupdate_fire = function(element, evt) {
		var i, h, args = [];
		if(evt) {args.push(evt);}
		for(i=0;(h=__i2rd_domupdate_handlers[i]);i++){
			try {h.apply(element,args);}catch(e){}
        }
	};
}
var log4js={}; // stubs
log4js.logger={};
log4js.logger.log=function(msg){if(typeof console != 'undefined' && console.log)console.log(msg);};
log4js.logger.debug=log4js.logger.info=log4js.logger.warn=log4js.logger.error=log4js.logger.log;

if (typeof i2rd == 'undefined') {window.i2rd = {};} // expose

/**
 * Returns true if browser is Microsoft Internet Explorer 
 * and returns false for other browsers.
 * @see http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
 */
i2rd.isIE=!+'\v1'; 
i2rd.getConfigMap=function(el) {
	if (typeof el == 'string')
		el = document.getElementById(el);
	if (!el) return {};
	var e = el.childNodes, b = {};
	for (var n=0, mx=e.length; n<mx; n++) b[e[n].className] = e[n].innerHTML;
	return b;
};
i2rd.xmlToString=function(xml) {
    var str = '';
    if(typeof xml != 'string') {
        var i,ib;
        if(xml.xml) {
            for (i=0,ib=xml.childNodes.length;i<ib;i++){str+=xml.childNodes[i].xml;}
        } else {
            var xs = new XMLSerializer();
			for (i=0,ib=xml.childNodes.length;i<ib;i++) {str+=xs.serializeToString(xml.childNodes[i]);}
        }
    } else {str = xml;}
    return str;
};
i2rd.scriptRX=new RegExp('<script[^>]*>([\\S\\s]*?)<\/script>', 'gim');
/** Returns an object with properties html and scripts. */
i2rd.stripScripts=function(html){
    return {
        html:html.replace(i2rd.scriptRX, ''),
        scripts:(function(){
            var m=[],i,arr;
            while( (arr = i2rd.scriptRX.exec(html)) ){
                if(arr[1]){m[m.length]=arr[1].replace(/^\s*<!\[CDATA\[/, '').replace(/\]\]>\s*$/, '');}
            }
            return m;
        })()
    }; 
};
i2rd.createElement=function(tag) {
	var ns, de = document.documentElement;
	ns = (de ? de.namespaceURI : false);
	if (ns) { return document.createElementNS(ns, tag);} 
	else { return document.createElement(tag); }
};
i2rd.getBody=function(w) {
    var doc = (w || window).document;
   return (doc.body || doc.getElementsByTagName("body")[0]); 
};
i2rd.getElementsByTagName=function(tn, start) {
    start = start || document;
    var r = [], els = start.getElementsByTagName(tn);
    if(!els || els.length==0){els=start.getElementsByTagName(tn.toUpperCase());}
    r.pushAll(els);
    return r;
};
// Simple event handling helpers
// http://dean.edwards.name/weblog/2005/10/add-event/
i2rd.addEvent=function(el, type, handler) {
	if(type == __i2rd_domupdate_event) {
		__i2rd_domupdate_handlers.push(handler);
	} else if (el.addEventListener) {
		el.addEventListener(type, handler, false);
	} else {
		if (!handler.$$guid){handler.$$guid=i2rd.addEvent_guid++;}
		if (!el.events){el.events={};}
		var handlers = el.events[type];
		if (!handlers) {
			handlers = el.events[type] = {};
			if (el["on" + type]) {
				handlers[0] = el["on" + type];
			}
		}
		handlers[handler.$$guid] = handler;
		el["on" + type] = i2rd.handleEvent;
	}
};
i2rd.removeEvent=function(el, type, handler) {
	if(type==__i2rd_domupdate_event) {
		var hl=[];
		for(i=0;(h=__i2rd_domupdate_handlers[i]);i++){if(h!==handler){hl.push(h);}}
		__i2rd_domupdate_handlers=hl;
	} else if (el.removeEventListener) {
		el.removeEventListener(type, handler, false);
	} else {
		if (el.events && el.events[type]) {
			delete el.events[type][handler.$$guid];
		}
	}
};
// a counter used to create unique IDs
i2rd.addEvent_guid=1;
// Internal event methods follow.
i2rd.handleEvent=function(event) {
	var i, hl, rv = true;
	event = event || i2rd.fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	hl = this.events[event.type];
	for (i in hl) {
		this.$$handleEvent=hl[i];
		if (this.$$handleEvent(event)==false){rv = false;}
	}
	return rv;
};
i2rd.fixEvent=function(event) {
	event.preventDefault = i2rd.fixEvent_preventDefault;
	event.stopPropagation = i2rd.fixEvent_stopPropagation;
	return event;
};
i2rd.fixEvent_preventDefault=function() {this.returnValue = false;};
i2rd.fixEvent_stopPropagation=function() {this.cancelBubble = true;};
i2rd.getAjaxTransport=function() {
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	return null;
};
i2rd.bind=function(m, caller) {
	var args = [], _m=m,obj=caller;
	if(arguments && arguments.length>2) {
		for(var i=2;i<arguments.length;i++){args[i - 2]=arguments[i];}
	}
	return function() {	
		for(var i=0;i<arguments.length;i++) {args[args.length] = arguments[i];}
		_m.apply(obj, args);
      };
};
i2rd.bindAsEventListener=function(m, caller) {
	var args = [], _m=m,obj=caller;
	if(arguments && arguments.length>2) {
		for(var i=2;i<arguments.length;i++){args[i - 2]=arguments[i];}
	}
	return function(evt) {
			for(var i=0;i<arguments.length;i++) {args[args.length] = arguments[i];}
			_m.apply(obj, [evt || window.event].concat(args));
		};
};
i2rd.eventElement=function(evt) {
	var e = evt || window.event;
	return (e.target || e.srcElement);
};
i2rd.getInnerText=function(el) {
	if (typeof el=="string"){return el;}
	var cn,i,str="",children=el.childNodes;
	for(i=0;(cn=children[i]);i++) {
		switch (cn.nodeType) {
			case 1: str += i2rd.getInnerText(cn); break;
			case 3:
			case 4:  str += cn.nodeValue; break;
		}
	}
	return str;
};
i2rd.mousex=0;
i2rd.mousey=0;
i2rd.mousetrack=false;
i2rd.updateLoc=function(evt) {
	var x=0,y=0;
	if (evt.pageX) {
		x = evt.pageX;
		y = evt.pageY;    
	} else if (evt.clientX) {
        var de = document.documentElement;
		x = evt.clientX + de.scrollLeft;
	    y = evt.clientY + de.scrollTop;
	} else { // For recent mozilla - may break things
		x = evt.screenX;
		y = evt.screenY;
	}
	i2rd.mousex = x;
	i2rd.mousey = y;
};
i2rd.getMouseCoord=function(evt) {
	if(!i2rd.mousetrack) {
		i2rd.mousetrack = true;
        if( (evt = evt || window.event)) {i2rd.updateLoc(evt);}
		i2rd.addEvent(document, 'mousemove', i2rd.updateLoc);
        setTimeout(function(){i2rd.mousetrack=false;i2rd.removeEvent(document, 'mousemove', i2rd.updateLoc);}, 
            120000);
	}
    return {x:i2rd.mousex, y:i2rd.mousey};
};
i2rd.addClassName=function(el,cn){
  var cn = cn.trim();
  if (!i2rd.hasClassName(el,cn))
    el.className = ((el.className || '') + ' ' + cn).trim();
};
i2rd.removeClassName=function(el,cn){
  if (!i2rd.hasClassName(el,cn)) return;
  el.className = (el.className || '').replace(RegExp("(^|\\s+)" + cn.trim() + "(\\s+|$)",'g'), ' ').trim();
};
i2rd.hasClassName=function(el,cn){
  var cur = (el.className || '');
  return cur == cn || (RegExp('\\b'+cn+'\\b').test(cur));
};
/** Gets the value of the specified cookie.
 * @param name  Name of the desired cookie.
 * @return Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
i2rd.getCookie=function (name) {
    var p,b,dc = document.cookie;
    if(!dc) {return null;}
    p=name+"=";
    b=dc.indexOf("; "+p);
    if (b==-1) {
        b=dc.indexOf(p);
        if(b!=0){return null;}
    } else {b+=2;}
    var e = document.cookie.indexOf(";", b);
    if(e==-1){e=dc.length;}
    return unescape(dc.substring(b+p.length, e));
};
/**
 * Sets a Cookie with the given name and value.
 * @param name    Name of the cookie
 * @param value   Value of the cookie
 * @param expires (Optional)  Expiration date of the cookie (default: end of current session)
 * @param path (Optional) Path where the cookie is valid (default: path of calling document)
 * @param domain (Optional) Domain where the cookie is valid
 *              (default: domain of calling document)
 * @param secure (Optional) Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
i2rd.setCookie=function (name, value, expires, path, domain, secure) {
    document.cookie=name+"="+escape(value)+
        ((expires)?"; expires="+expires.toGMTString():"")+
        ((path)?"; path="+path : "")+
        ((domain)?"; domain="+domain:"")+
        ((secure)?"; secure" : "");
};
/**
* Delete a Cookie with the given name.
* @param name the name of the cookie.
* @param path optional path of the cookie.
*/
i2rd.deleteCookie=function(name, path, domain) {
    document.cookie=name+"; expires=Thu, 01-Jan-1970 00:00:01 GMT"+
        ((path)?"; path="+path:"")+
        ((domain)?"; domain="+domain:"");
};
i2rd.lastFocus=null;
i2rd.focusListener=function(evt) {
    var el, lf=i2rd.lastFocus;
	if(lf){lf.className=lf.className.replace("focused", "");}
	evt=evt||window.event;
    el=evt.target||evt.srcElement;
	i2rd.lastFocus=el;
	el.className=el.className+" focused";
};
// http://developer.mozilla.org/en/docs/DOM:window.open
i2rd.owfDefault={
    menubar : false,
    location : false,
    toolbar : false,
    scrollbars : true,
    statusbar : false
    /*
    ,dependent : null,
    dialog : null,
    resizable : null
    */
};
/**
 * Open a new window.
 * @param {Object} url the URL of the window.
 * @param {Object} name the optional name of the window.
 * @param {Object} dim the optional dimensions of the window. Must have x and y prop.
 * @param {Object} features the optional features. Map of feature => boolean || null. See owfDefault.
 * @param {Object} pbMesg the optional popup blocked message.
 * @param {Event} evt optional event. 
 */
i2rd.openWindow=function(url, name, dim, features, pbMesg, evt) {
    name = name || '_blank';
    features = features || i2rd.owfDefault;
    pbMesg = pbMesg || 'Please disable any popup blockers for this site.';
    var fstr = '';
    for(var key in features) {
        var val = i2rd.getOWFeature(features, key);
        if(val!=null) {//NULL check, undefined/false means something else
            fstr +=','+key+'='+(val?'yes':'no');
        } 
    }
    if(dim) {
        if(dim.x && dim.x > 0){dim.x+=30;fstr+=',width='+dim.x;}
        if(dim.y && dim.y > 0){dim.y+=50;fstr+=',height='+dim.y;}
    }
    if(fstr.length > 0) {fstr = fstr.substring(1);}
    var nw = window.open(url, name, fstr);
    if(name != '_top' && name != '_parent' && name != '_self') {
        if(nw.opener != window) { // Should be nw == null ?
            alert(pbMesg);
        }
    }
    try {
        nw.focus();
        if(dim && dim.x && dim.y){
            if(dim.x > 0 && dim.y > 0){
                nw.resizeTo(dim.x, dim.y); // Only resize if both dimensions are known
            }
        }
    }catch(e){}
    evt = evt || window.event;
    if(evt){
        if(evt.preventDefault) {evt.preventDefault();}
        else {evt.canceBubble = true;}
    }
    return false;   
};
i2rd.getOWFeature=function(m, prop) {
    var val=m[prop];
    if(typeof val == 'undefined' ||  val==null){return null;}
    else{return !!val;}
};
/**
 * Iterate over the array and apply the passed function to each of the
 * individual items.
 * <p>
 * An optional filter may be passed as the third parameter which will only apply
 * the function to elements for which the filter returns true (or an object
 * which evaluates to true).
 * 
 * @param array
 *          The array or array-like object to iterate over.
 * @param fn(index,el,count)
 *          The function to apply to the matching elements. 'this' refers to the
 *          element.
 * @param filter(index,el,count)
 *          An optional filter to limit the elements the function applies to.
 *          'this' refers to the element.
 */
i2rd.each = function(array, fn, filter) {
  var ct = 0, all = (typeof filter !== 'function');
  for ( var i = 0, mx = array.length; i < mx; i++) {
    var el = array[i];
    if (all || filter.call(el, i, el, ct)) {
      fn.call(el, i, el, ct++);
    }
  }
};

// Setup the 'focus' listener and 'auto-submit' for appropriate form elements
i2rd.addEvent(window, 'load', function(){
	var i1,i2,fe1,f,el,fl=document.forms;
	if(typeof fl == 'undefined'){return;}
	for(f=null,i1=0;(f=fl[i1]);i1++) {
		el=f.elements;
		for(fe1=null,i2=0;(fe1=el[i2]);i2++){
            if(fe1.type == 'hidden') {continue;}
            i2rd.addEvent(fe1,'focus',i2rd.focusListener);
			if(fe1.type&&fe1.className&&fe1.type.match(/select.*/i)&&fe1.className.match(/.*autosubmitselect.*/i)){
                fe1.onchange=function(evt){this.form.submit();};
			}
		}
	}
});

} // End conditional eval.
