if (document.all) Node = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3 };

var MyUtils = {
    truncate: function(element, length){
        var element = $(element);
        return element.update(element.innerHTML.truncate(length));
    },
    updateAndMark:function(element, html, className){
        return $(element).update(html).addClassName(className);
    },
    replaceClassName:function(element, _old, _new) {
		var aggr = (_old instanceof Array) ? $A( _old ) : $A( [ _old ] );
		aggr.each(function(x){ element.removeClassName(x); });
		return element.addClassName( _new );
    }
};
Element.addMethods( MyUtils );

var HILITE    = 'hilite1'
	,HILITE2  = 'hilite2'
	,NORMAL   = 'contrast1'
	,CONTRAST = 'contrast2'
	,POINTER  = 'pointer'
	,DEFAULT  = 'default'
	,SELECTED = 'selected'
	,MOUSEOVER= 'mouseover'
	,MOUSEOUT = 'mouseout'
	,MOUSEMOVE= 'mousemove'
	,MOUSEUP  = 'mouseup'
    ,SPECIALKEYS={_CMD_:0x01,_ALT_:0x02,_CTRL_:0x04,_SHIFT_:0x08,_ESC_:0x10,   CMDKEY:0x5B, ESCKEY:0x1B, SHIFTKEY:0x10,CTRLKEY:0x11,ALTKEY:0x12,FFCMDKEY:0xE0};

var uiWidget = Class.create();
	uiWidget.prototype = {
	  initialize:          function( divID, title, baseTbl, refTbl, hdrCols, DOMObserver ) {
		this.body  				= divID;
		this.title 				= title;
		this.baseTbl 			= baseTbl;
		this.refTbl				= refTbl;
		this.hdrCols            = hdrCols;
		this.info 				= $H({});
		this.IXs                = $A([]);

		this.handler         =
		   { tracking:this.mouseTrackingHandler.bindAsEventListener(this)
			,   click:this.clickHandler        .bindAsEventListener(this)
            , mouseup:this.click2Handler       .bindAsEventListener(this)
			, keydown:this.keybdHandler        .bindAsEventListener(this)
            ,   keyup:this.keybd2Handler       .bindAsEventListener(this)
            ,    hide:this.hideToggle          .bindAsEventListener(this)
            ,  redraw:this.reDrawTbl           .bindAsEventListener(this)
            , showTbl:this.showTbl             .bindAsEventListener(this)
		   };

		this.handlerX = {
		  dblclick: 
		    document.body.on( 'dblclick',
		     (function(e) { var coord=[Event.pointerX(e), Event.pointerY(e)], K=SPECIALKEYS,
		                        target=e.element();
				e.stop();
				if (target.firstChild==undefined) return;

				var el = this.selectCols.find(function(v){return isHot(v.parentNode,coord);});
				if (! el) return;

				var parentEl = target.parentNode;

				/*alert(target.inspect()
					  +' | ' +
					  target.firstChild.nodeValue
					  +'\n\n'+
					  parentEl.inspect()
					  +' |\n  '+
					  this.selectCols[el.parentNode.attributes.getNamedItem('id').value].parentNode.firstChild.inspect()
					  +'\n\n'+
					  parentEl.firstChild.firstChild.nodeValue
								  +'['+ this.base.lit[this.base.IXs[
									   $A(parentEl.childNodes).find(function(v){return isHot(v,coord);}).attributes.getNamedItem('id').value]]
								  +']'
					 ); */

				var mode = (this.SPKeysMask & K._ALT_) && 1;
				this.getAthleteStats({arg:parentEl.firstChild.firstChild.nodeValue .concat(';',this.base.lit[this.base.IXs[$A(parentEl.childNodes).find(function(v){return isHot(v,coord);}).attributes.getNamedItem('id').value]]) .concat(';',mode)
									  ,dimensions:$A([600,500])
									  ,title:''.concat((mode) ? 'Career':'Season' ,' Stats: ' ,parentEl.firstChild.firstChild.nodeValue)
									  ,phpScript:'controller/runMyCannedQry.php'}); 

		    	parentEl.childElements()[0].removeClassName('selected');
		    	$('tb').fire('widget:showTbl');  

			  } ).bindAsEventListener(this)) };

		this.sortToggle 		= false;
		this.displToggle        = false;
		this.objClickDrag       = null;
		this.selected           = null;
		this.DOMObserver		= DOMObserver;
	
		this.remoteCntl			= new uiFilterWidget('left-container','Filter Report ...',{backgroundColor:'#000',color:'#888'}, this);
	
		this.showTbl();
		this.lastClicked        = 'athl';  // initial sort column is athl-name ...  this.sortCols[this.baseCols.athl].id;
		this.lastClickedIX      = this.sortCols.collect(function(v){return v.id;}).indexOf(this.lastClicked);

		DOMObserver.handler.each( function(o) { o.value.stop(); });
		DOMObserver.suspendTracking = true;
		this.attachEventHandlers();

	  }
	 ,showTbl:             function( clicked, toggleFlag) {
		var myCompare1 = function(v)   { return v.athl; };
		var myCompare2 = function(v,i) { var x    = v.times[ base.id.indexOf(clicked)-1 ];
										 var conv = []; 
							x.scan( /((\d+):)?(\d+\.\d{2})/
									,function(match) { var a = (match[2]===undefined) 
																? parseFloat(0) : parseFloat(Number(match[2])*60);
										a += parseFloat(match[3]);
										conv.push( a );
									 } );
							return (! conv.length) ? 1e9: conv[0]; }.bind(this); // sort nulls to the bottom ...	
		var	selection1 = function(v,prop,letter ) { return letter =='*' || v[prop].toLowerCase()==letter; };
		var selection2 = function(v,prop,bitFlag) { return (v[prop] & bitFlag); };
	
		var hdrCols    = $w(this.hdrCols);
		var base       = { 
					   // cols: {athl:?, m400:? ,m200:? ,m800:? ,m55:? ,m1500:? ,m100:?}
						    id: $w('athl    m400 m200 m800 m100 m1500 m55')
						  ,lit: $w('Athlete 400m 200m 800m 100m 1500m 55m')
						 };
		var IXs        = hdrCols.inject([],function(m,v,i){m.push(base.lit.indexOf(v)); return m;});
		var cols       = base.lit.inject({},function(m,v,i){m[base.id[i]]=hdrCols.indexOf(v); return m;});

		base.IXs  	   = IXs;
		base.cols      = cols;
		this.base      = base;

		// alert( base.lit.inject([],function(m,v,i){m[i]=base.id[i]+':'+hdrCols.indexOf(v); return m;}).join(' | ') );

		var myCompare  = (this.showTbl.arguments.length==0 || base.cols[clicked]==0) ? myCompare1:myCompare2;
		var hiliteThis = (this.showTbl.arguments.length==0 || base.cols[clicked]==0) ? 1 : base.cols[clicked]+1;

		switch ( this.remoteCntl.gender ) { case 1: gender = 'f'; break;
											case 2: gender = 'm'; break;
											default:gender = '*'; }
	
		// filter base array by button settings in the uiWidget.
		this.uiTbl = this.baseTbl.findAll(
		
					   function(obj) { var look = this.refTbl.find( function(v){return v['id']==obj['ageid'];} );
						   return (look) ? (selection1(obj,"gender",gender) && selection2(look,"mask",this.remoteCntl.ageGrpFlag)) : false; 
					   }.bind( this )

                     ).sortBy( myCompare ); 

	
		if ( this.showTbl.arguments.length<2 )								toggleFlag = true;

		if (toggleFlag && this.lastClicked && this.lastClicked==clicked)	this.sortToggle = !this.sortToggle; 
		else																this.sortToggle = false;
	
		if (this.sortToggle) 												this.uiTbl.reverse();


		/** ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **/
		var i=0, removeMe;
		var tblX= Builder.node(
		            'table',{id:'tb',rules:'all',border:'0',cellPadding:'3',cellSpacing:'2',title:"Seasonal Stats <DBL-CLICK>\nOR\nCareer Stats    <ALT-DBL-CLICK>\n\nwithin athlete's:\nname cell for full stat retrieval\nor\nevent column cell for selective stat retrieval"}
					,[ Builder.node( 'CAPTION', this.title )
					  ,Builder.node( 'THEAD'
									,[ Builder.node(
										 'TR', {className:'sky contrast1',id:-1}
										 ,[Builder.node(  'TH', {id:base.id[base.IXs[0]]} ,[ Builder.node( 'DIV', {style:'float:left' }, base.lit[base.IXs[0]] ) ] )
										   ,Builder.node( 'TH', {id:base.id[base.IXs[1]]} ,[ Builder.node( 'DIV', {style:'float:right'}, base.lit[base.IXs[1]] ) ] )
										   ,Builder.node( 'TH', {id:base.id[base.IXs[2]]} ,[ Builder.node( 'DIV', {style:'float:right'}, base.lit[base.IXs[2]] ) ] )
										   ,Builder.node( 'TH', {id:base.id[base.IXs[3]]} ,[ Builder.node( 'DIV', {style:'float:right'}, base.lit[base.IXs[3]] ) ] )
										   ,Builder.node( 'TH', {id:base.id[base.IXs[4]]} ,[ Builder.node( 'DIV', {style:'float:right'}, base.lit[base.IXs[4]] ) ] )
										   ,Builder.node( 'TH', {id:base.id[base.IXs[5]]} ,[ Builder.node( 'DIV', {style:'float:right'}, base.lit[base.IXs[5]] ) ] )
										  ] ) ] ) ] );
		var bodyX= Builder.node('TBODY');

		this.uiTbl.each( function(x) {
		  bodyX.appendChild( Builder.node('TR',{id:i++} 
										  ,[Builder.node(  'TD' ,{id:0}               ,x.athl     ) 
											,Builder.node( 'TD' ,{id:1,align:'right'} ,x.times[base.IXs[1]-1] ) 
											,Builder.node( 'TD' ,{id:2,align:'right'} ,x.times[base.IXs[2]-1] ) 
											,Builder.node( 'TD' ,{id:3,align:'right'} ,x.times[base.IXs[3]-1] ) 
											,Builder.node( 'TD' ,{id:4,align:'right'} ,x.times[base.IXs[4]-1] ) 
											,Builder.node( 'TD' ,{id:5,align:'right'} ,x.times[base.IXs[5]-1] ) 
										   ] ) ); } );
		tblX.appendChild( bodyX );

		if ((removeMe=$(this.body).firstChild)) $(this.body).removeChild( removeMe ); 
		$(this.body).appendChild( tblX ); // NOTE: obj.appendChild( obj.appendChild( obj2 ) ) FAILS !!!!!
		/** ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **/

		
		this.target	  = $('tb');
		this.bodyRows = this.target.select('tr');

		var x  = (this.sortToggle) ? 'downArrow':'upArrow';
		var y  = (this.showTbl.arguments.length==0 || base.cols[clicked]==0) ? 'right':'left';
		sortMe = '<img src ="data/assets/#.png" style="float:#;" />'
				  .gsub(/(.*)#(.png.*)#(.*)/, function(match) { return match[1] +x+ match[2] +y+ match[3]; });

		cssSel = 'table#tb tr > th:nth-child(' + hiliteThis + ')';
		$$(cssSel).each( function(el) { new Insertion.Bottom( el, sortMe );
										el.down('img').style.float = y; 
                         			  } );

		this.sortCols  = $A([]);
		this.selectCols= $A([]);	
		this.target.select('tr > th')           .each( (function(el){this.sortCols.push(el);}).bind( this ));
		$$('table#tb tr > td:first-child')      .each( (function(el){this.selectCols.push(el);}).bind(this) );
		$$('table#tb tbody > tr:nth-child(odd)').each(  function(el){el.addClassName('contrast2');} );

		cssSel = 'table#tb tr > td:nth-child(' + hiliteThis + ')';
		$$(cssSel).each( function(el) {el.addClassName('sky');} );

		this.target.setStyle( {tableLayout:'fixed', width:'100%'} ).addClassName('contrast1');
		this.SPKeysMask = 0x00;
	  }
	 ,attachEventHandlers: function()  {
										Event.observe(       document.body, 'mousemove'     ,this.handler['tracking'] );
										Event.observe(       document.body, 'mousedown'     ,this.handler['click'   ] );
										Event.observe(       document.body, 'mouseup'       ,this.handler['mouseup' ] );
										Event.observe(       document     , 'keydown'       ,this.handler['keydown' ] );
										Event.observe(       document     , 'keyup'         ,this.handler['keyup'   ] );
										Event.observe(       document.body, 'tbl:toggleHide',this.handler['hide'    ] );
										Event.observe(       document.body, 'widget:redraw' ,this.handler['redraw'  ] );
										Event.observe(       document.body, 'widget:showTbl',this.handler['showTbl' ] );
									   }
	 ,removeEventHandlers: function()  {
										Event.stopObserving( document.body, 'mousemove'     ,this.handler['tracking'] );
										Event.stopObserving( document.body, 'click'         ,this.handler['click'   ] );
										Event.stopObserving( document.body, 'mouseup'       ,this.handler['mouseup' ] );
										Event.stopObserving( document     , 'keydown'       ,this.handler['keydown' ] );
										Event.stopObserving( document     , 'keyup'         ,this.handler['keyup'   ] );
										Event.stopObserving( document.body, 'tbl:toggleHide',this.handler['hide'    ] );
										Event.stopObserving( document.body, 'widget:redraw' ,this.handler['redraw'  ] );
										Event.stopObserving( document.body, 'widget:showTbl',this.handler['showTbl' ] );
									   }
	 ,clickHandler:        function(e) { var selected, toggle, watchList, hClass, IXs, athl,
	 									 coord=[Event.pointerX(e), Event.pointerY(e)], K=SPECIALKEYS;

		if ((clicked=this.sortCols.detect( function(el){return isHot(el,coord);} ))) {
		  
		  this.showTbl(clicked.id);
		  		  
		  this.lastClicked   = clicked.id;
		  this.lastClickedIX = this.sortCols.collect(function(v){return v.id;}).indexOf(this.lastClicked);
		  this.selected      = null;

		  if (this.IXs.length) {this.reDrawTbl();}
		}

		else { // we've clicked somewhere within the tbl body...

		  if (! (this.SPKeysMask & (K._CMD_ | K._SHIFT_ | K._CTRL_))) {
		    if (this.hotCell && this.hotCell[1]==0)
		      this.selectCols.each( (function(v){v.parentNode.childNodes[this.lastClickedIX].addClassName('sky');}).bind(this) ); // Refresh hot-sort-col css class
/*
		    this.deHiliteALL(); // Refresh the display i.e. remove any hilites
			var parentEl=this.selectCols[this.selectCols.find(function(v){return isHot(v.parentNode,coord);}).parentNode.attributes.getNamedItem('id').value].parentNode;
			alert(parentEl.firstChild.firstChild.nodeValue
				  +'['+ this.base.lit[this.base.IXs[
					   $A(parentEl.childNodes).find(function(v){return isHot(v,coord);}).attributes.getNamedItem('id').value]]
				  +']');
			this.getAthleteStats({arg:parentEl.firstChild.firstChild.nodeValue .concat(';',this.base.lit[this.base.IXs[$A(parentEl.childNodes).find(function(v){return isHot(v,coord);}).attributes.getNamedItem('id').value]]) 
								  ,dimensions:$A([600,500])
								  ,title:'Seasonal Stats: '+parentEl.firstChild.firstChild.nodeValue
								  ,phpScript:'controller/runMyCannedQry.php'}); 
*/
		  }

		  if (! (this.SPKeysMask & K._SHIFT_) ) {
		    // {<Click> | <cmd>/<cntl> <Click>}
		    selected = this.clickDrag(coord);
		    if (selected != null) {

			  athl = selected.el.firstChild.nodeValue.split(', ');
			  this.remoteCntl.vu.innerHTML = '[ '.concat(selected.ix,' - ',athl[1],' ',athl[0],' ]');

		      this.objClickDrag = {enabled:false,begin:$H(selected),end:$H(selected)};
		      this.selected = selected; // ! relied on in mouseTrackingHandler !

			  if (this.SPKeysMask & (K._CMD_ | K._CTRL_)) { // <cntl>/<cmd>
  
				if ((ix=this.IXs.indexOf(selected.el.firstChild.nodeValue))==-1) { // unSelected | selected element ?
				  this.IXs.push(selected.el.firstChild.nodeValue);
  
				  selected.el.parentNode.childNodes[this.lastClickedIX].className='';
				}  
				
				else {
				  void this.IXs.splice(ix,1);

			 	  selected.el.removeClassName( SELECTED );
				  selected.el.parentNode.childNodes[this.lastClickedIX].addClassName('sky');
			    }
			  }
			  
			  else
			  if (! this.displToggle)
				this.IXs = $A([selected.el.firstChild.nodeValue]);

			  $('tb').fire('widget:redraw');
	  }	} } }
	 ,click2Handler:       function(e) { var selected, coord=[Event.pointerX(e) ,Event.pointerY(e)] ,el
	 										 ,K=SPECIALKEYS, ix, IXs;

		do { //10/29/10 2:14 PM
		
		  if ((el=this.sortCols.detect( function(el)  { return isHot(el,coord); } ))) { el.addClassName('attention');
		  																				break;
		  																			  }
		  
		  selected = this.clickDrag(coord);

		  if (! selected) {	this.deHiliteALL(); break; } // outside of select boundary - deSelect
		  
		  if (this.selected !== undefined && this.selected && selected.el != this.selected.el && this.SPKeysMask & K._SHIFT_) {
		  
			this.IXs.push(selected.el.firstChild.nodeValue);
			IXs = this.IXs.inject([],(function(m,v,i){m.push(this.selectCols.indexOf(this.selectCols.find(function(x){return x.firstChild.nodeValue==v;}))); return m;}).bind(this));
			var IXrange = [IXs.min(),IXs.max()];
		  
			this.IXs    = this.selectCols.slice(IXrange[0],IXrange[1]+1);
			this.IXs.each( (function(v){ v.addClassName( SELECTED ); 
										 v.parentNode.childNodes[this.lastClickedIX].className='';
									   } ).bind(this) );

			this.remoteCntl.vu.innerHTML = '';
			$('tb').fire('widget:redraw');
		  } 
		
		} while( 0 );
	    
	    this.objClickDrag = null;
	  }
	 ,reDrawTbl:           function(e) {
		var IXs = 
		      (typeof this.IXs[0] == 'object')
			  ? this.IXs
			  : this.IXs.collect((function(v){return this.selectCols.find(function(y){return y.firstChild.nodeValue == v;});}).bind(this));

		proj1 = this.selectCols.slice(0);
		IXs.each( function(z){ void proj1.splice(proj1.indexOf(z),1); } );


		toggle = false;

		IXs.each((function(v){ 
		  v.addClassName( SELECTED );
		  
		  if (this.displToggle) hClass = toggle ? CONTRAST:NORMAL;
		  else                  hClass = toggle ? HILITE2:HILITE ;
		  
		  v.parentNode.className = '';
		  v.parentNode.addClassName( hClass );

		  if (this.displToggle) v.parentNode.childNodes[this.lastClickedIX].addClassName('sky');
		  else                  v.parentNode.childNodes[this.lastClickedIX].className='';

		  toggle = ~toggle;
		
		}).bind(this));

		if (this.displToggle) proj1.each( function(el){el.parentNode.hide();} );
		
		else { toggle = false;

		  proj1.each( function(v){ hClass = toggle ? CONTRAST:NORMAL;
								   v.parentNode.className = '';
								   v.parentNode.addClassName( hClass );
								   toggle = ~toggle;
							     } );
		}

		this.IXs = IXs.collect(function(el){return el.firstChild.nodeValue;});
	  }
	 ,clickDrag:           function(coord) {

		do {
			 selected = this.selectCols.inject({},function(m,v,i){if (isHot(v,coord)){m['ix']=i+1; m['el']=v;} return m;});

			 if (! ($H(selected).keys().length)) { selected=null; break; }

			 if (! selected.el.hasClassName( SELECTED )) selected.el.addClassName( SELECTED );

		} while (0);

		return selected;
	  }
	 ,deHiliteALL:         function()  {
		this.selectCols.findAll( function(el){return el.hasClassName( SELECTED );} ).each(
			   (function(el) {el.removeClassName( SELECTED );
			      el.parentNode.childNodes[this.lastClickedIX].addClassName('sky');
			   }).bind(this) );
	  }
	 ,mouseTrackingHandler:function(e) {
	    var coord       = [Event.pointerX(e), Event.pointerY(e)];
		var lastHotCell = (this.hotCell instanceof Array)
					  		 ? this.bodyRows[this.hotCell[0]].childElements()[this.hotCell[1]]
					 		 : null;
		var hdrCols     = this.bodyRows[0].childElements();
		var cursor      = DEFAULT;
  		var innerHTML   = '';

		if (! isHot($(this.target),coord)) { // exit... we're outside of tbl boundary
		  if (this.DOMObserver.suspendTracking) {
			this.DOMObserver.handler.each( function(o) { o.value.start(); });
			this.DOMObserver.suspendTracking = false;
			this.remoteCntl.vu.innerHTML = innerHTML;

            hdrCols.each( function(el) { el.removeClassName('attention'); } );
		    this.hotCell = null;
		  }
		  return;
		}

		if (! this.DOMObserver.suspendTracking) { this.DOMObserver.handler.each( function(o) { o.value.stop(); });
		  										  this.DOMObserver.suspendTracking = true;
        										}


        hotRowIx     = this.bodyRows.indexOf(this.bodyRows.find( function(v){ return isHot(v,coord); } ) );		

		if (hotRowIx !=0) {
		  document.body.setStyle({cursor:cursor});
          hdrCols.each( function(el) { el.removeClassName('attention'); } );

		  if (hotRowIx<0) {
		    this.hotCell = null;
		    return;
		} }


		hotRow       = this.bodyRows[hotRowIx];
		hotRowCols   = hotRow.childElements();
        hotColIx     = hotRowCols.indexOf(hotRowCols.find( function(v){ return isHot(v,coord); } ) );
		hotEl        = hotRowCols[hotColIx];
		hotCell      = [hotRowIx,hotColIx];

		if (lastHotCell==hotEl) return;   // moving w/in same tbl cell ?


		this.hotCell = hotCell;

		if (hotRowIx==0) { /** within table column-header **/
		  cursor = POINTER;
          hdrCols.each( function(el) { el.removeClassName('attention'); } );
		  hotEl.addClassName('attention');
		} 
		else { /** within table body proper ... **/

		  if ( hotColIx>0 ) { /* hotEl.id>0   Zero-base index ...*/
			var tok = [];
			var s   = this.uiTbl[hotRow.id].dates[parseInt(this.base.IXs[hotEl.id]-1)];

			if (s) {
				s.scan(/(\d{4}_[A-Za-z]+\d{2})_(.*)/, function(m) {tok.push(m[1]); tok.push(m[2]);} );
				if (tok.length >0) innerHTML = '<h4>'+tok[0]+'</h4><h4>'+tok[1]+'</h4>';
		  } }


		  else { // hotColIx==0

			if (! this.objClickDrag) 
			  innerHTML = this.uiTbl[hotRow.id].ageid;
		    
		    else
		    if (!this.displToggle) {  
		      if (!this.SPKeysMask) {this.objClickDrag.enabled=true; this.objClickDrag.end=$H({ix:hotRowIx,el:hotCell});}
			  
		      cursor    = POINTER;
			  innerHTML = ' [ ' + this.uiTbl[this.objClickDrag.begin.get('ix')-1].athl
			  			 +' : ' + this.uiTbl[this.objClickDrag.end  .get('ix')-1].athl
			  			 +' ] ';

			  var IXs = $A([Number(this.selected.el.parentNode.id), Number(this.selectCols[hotCell[0]-1].parentNode.id)]);
			  var IXrange = [IXs.min(),IXs.max()];
			  
			  this.IXs = this.selectCols.slice(IXrange[0],IXrange[1]+1);
			  this.IXs.each((function(v){ v.addClassName( SELECTED ); 
										  v.parentNode.childNodes[this.lastClickedIX].className='';
										}).bind(this) );

			  $('tb').fire('widget:redraw');
		} } }

        document.body.setStyle({cursor:cursor});
		this.remoteCntl.vu.innerHTML = innerHTML;
	  }
	 ,keybdHandler:        function(e) { var mask, K = SPECIALKEYS;
		e.cmdKey=(e.keyCode==K.CMDKEY || e.keyCode==K.FFCMDKEY); e.escKey=(e.keyCode==K.ESCKEY);
		
		mask = K._CMD_*e.cmdKey + K._ALT_*e.altKey + K._CTRL_*e.ctrlKey + K._SHIFT_*e.shiftKey + K._ESC_*e.escKey;
		this.SPKeysMask |= mask;
		// this.remoteCntl.vu.innerHTML = 'keyCode= <' +e.keyCode+ '>';

		if (this.SPKeysMask & (K._CMD_ | K._CTRL_)) {
		  switch(e.keyCode) {
			case 0x48:
			  this.displToggle = !this.displToggle;
			  $('tb').fire('tbl:toggleHide');

			  break;
			default:
		  }
		}
	  }
	 ,keybd2Handler:       function(e) { var mask, K = SPECIALKEYS;
							 mask =  K._CMD_  *(e.keyCode==K.CMDKEY || e.keyCode==K.FFCMDKEY) 
								   + K._ALT_  *(e.keyCode==K.ALTKEY  ) 
								   + K._CTRL_ *(e.keyCode==K.CTRLKEY ) 
								   + K._SHIFT_*(e.keyCode==K.SHIFTKEY) 
								   + K._ESC_  *(e.keyCode==K.ESCKEY  );
/**
							 if (e.keyCode != 0x0d)
							   alert(e.keyCode+' | '+e.cmdKey+':'+e.altKey+':'+e.ctrlKey+':'+e.shiftKey+':'+e.escKey+': '+mask+'|'+this.SPKeysMask); 
**/
							 this.SPKeysMask ^= mask;
						   }
	 ,hideToggle:          function(e)  {

		this.IXs.collect((function(v){return this.selectCols.find(function(y){return y.firstChild.nodeValue == v;});}).bind(this))
		  .each( function(z) {z.addClassName( SELECTED )} );

	    this.selectCols.findAll(function(x){return ! x.hasClassName( SELECTED );})
	      .each( function(z) {z.parentNode.toggle();} );
	    
	    $('tb').fire('widget:redraw');
	  }
	 ,getAthleteStats:     function(custObj) {
		var       aObj = {dfltPortDimensions:custObj.dimensions, title:'<span class="attention2">'.concat(custObj.title,'</span>')};
		
		new Ajax.Request( custObj.phpScript
		    ,{method:'post' ,asynchronous:true ,evalJSON:true ,evalScripts:false ,parameters: $H({arg:custObj.arg}).toQueryString()
			,onComplete: function(transport) {
		var dimensions = aObj.dfltPortDimensions;
//transport.responseJSON.debug.scan(/.*/,alert);
		transport.responseJSON.singleton.scan( /<iframe\s+width="(\d+)"\sheight="(\d+)"/
		  ,function(m){ dimensions[0]=Number(m[1]); dimensions[1]=Number(m[2])+60; } );

		var     rows  = transport.responseJSON.singleton.split(';');

		var      IXs  = $A([]);
		var    Evnts  = [];
        transport.responseJSON.singleton.scan( /(?:\^)(.+?)(?:\^.*?\^;)/ ,function(m){Evnts.push(m[1]);});

		Evnts.uniq().each( function(Evnt) {

          var trailingFloat = /((\d+\:)*\d+\.\d+)(?!.*\d+\.\d+)/; // literal fmt compiles only once ...
		  var          coll = new RegExp(Evnt);		 
		  var        result = rows.inject( []
										  ,function(m,v,i){ var toks;
											 if (coll.test(v)) { 
											   toks=trailingFloat.exec(v)[0].split(':'); 
											   m.push({ix:i,mark: (toks.length>1) 
																  ? parseInt(toks[0])*60+parseFloat(toks[1])
																  : parseFloat(toks[0])}); 
											 }
											 return m; 
										   });

		  var      fldValue = /(jump|shot|discus|jav|throw)/i;
		  var        target = (fldValue.test(Evnt)) ? result.max( function(v){return v.mark;} )
		                                            : result.min( function(v){return v.mark;} );
		  if (result.length>1)
			IXs.push( result.find( function(v){ return (v.mark==target) ? true:false; } ).ix );

		} );


		var   colors = ['080','fc3','00bcec','b2d84f','ed762e'];
		var  snippet = '', last = '';
		var    color = 0; 
		var        k = 0;

		rows.each( function(r) { 
		  var tok    = r.split('^');
		  if (tok[1]!=last) {color=((color+1)<5) ? color+1:0;}
		  var cellTag = '<TD id="c2">';
		  if (IXs.length && (IXs.find(function(x){return (x==k);} ))>=0)
				{ 
				  cellTag = '<TD id="c2" style="font-size:140%">';
				  IXs.splice( IXs.indexOf(k) ,1 );
				}
		  snippet = snippet.concat('<TR id="r',k+1,'" style="color:#',colors[color],'">','<TD id="c0" class="smallcaps">',tok[0],'</TD>','<TD id="c1" class="smallcaps">',tok[1],'</TD>',cellTag,tok[2],'</TD>','</TR>');
		  last    = tok[1];
		  k++;
		});
		
		var out = '<table id="tb2" rules="all" border="2" cellpadding="10" width="99%">'.concat('<THEAD class="lime"><TR id="r0">','<TH id="h0">','DATE','</TH>','<TH id="h1">','EVENT','</TH>','<TH id="h2">','MARK','</TH>','</TR></THEAD><TBODY>',snippet,'</TBODY></table>');
 
		window.Shadowbox.open( { content: out
								,player: "html"
								,title:  aObj.title
								,width:  dimensions[0]
								,height: dimensions[1] });
 
	  } } ); }
	};
var uiFilterWidget = Class.create();
	uiFilterWidget.prototype = {
	  initialize: function( hostElem, title, settings, uiWidget ) {
		this.title 		 = title;
		this.settings    = settings;
		this.handler	 = $A([]);
		this.buttonList  = $A([]);
		this.hot		 = false;
		this.widget	 	 = uiWidget;  	// the Object, not the DOM element
		this.CAT		 = { FLAG_GENDER	:0x1, 	FLAG_AGEGRP		:0x2 				 }; 
		this.G 			 = { FEMALE			:0x1, 	MALE			:0x2, 	BOTH	:0x3 };
		this.G2			 = { FLAG_HS		:0x400,
							 FLAG_YOUNG		:0x200, FLAG_INTERMED	:0x100, // Note: these flags must be maintained 	
							 FLAG_YOUTH		:0x080, FLAG_SUBYOUTH 	:0x040, //       in chronological agegroup order
							 FLAG_MIDGET	:0x020, FLAG_SUBMIDGET	:0x010,
							 FLAG_BANTAM	:0x008,	FLAG_SUBBANTAMX	:0x004,
							 FLAG_SUBBANTAM :0x002, FLAG_PRIMARY	:0x001,
							 FLAG_ALL_AGES	:0x7ff  };
	
        // Set flags representing initial state of FilterWidget buttons
		this.gender		 = this.G.BOTH ;
		this.ageGrpFlag  = this.G2.FLAG_ALL_AGES;
	
		if (! $('header').readAttribute('whoami')) { // homepage does not have whoami attribute
		  $(hostElem).replace('<div id="left-container" class="column">'
							  +'<div id="uiFilterWidget"><h3>'+this.title+'</h3></div>'+'</div>');
		}
		else { // whoami attribute in populated w/ the meet identity
		  new Insertion.Top( hostElem, '<div id="uiFilterWidget"><h3>'+this.title+'</h3></div>' );
		}

		$(hostElem).setStyle({backgroundColor:'transparent'});
		this.host        = $('uiFilterWidget');
		this.host.setStyle({backgroundColor:settings.backgroundColor, color:settings.color});
		Element.addClassName(this.host,'uiFilterWidget'); // hang CSS hook ...
	
		var buttonList   = this.buttonList;

		buttonList.push( new uiButton(this, {id:1, color:'#f36'          ,label:'female'      ,clear:false, cat:this.CAT.FLAG_GENDER, mask:this.G.FEMALE}                                   ,true) );
		buttonList.push( new uiButton(this, {id:2, color:'#03c'          ,label:'male'        ,clear:false, cat:this.CAT.FLAG_GENDER, mask:this.G.MALE}                                     ,true) );
		buttonList.push( new uiButton(this, {id:3, color:'rgb(56,238,84)',label:'young'       ,clear:true,  cat:this.CAT.FLAG_AGEGRP, mask:this.G2.FLAG_YOUNG     | this.G2.FLAG_HS}        ,true) );
		buttonList.push( new uiButton(this, {id:4, color:'rgb(238,84,56)',label:'intermediate',clear:false, cat:this.CAT.FLAG_AGEGRP, mask:this.G2.FLAG_INTERMED}							,true) );
		buttonList.push( new uiButton(this, {id:5, color:'rgb(64,0,0)'   ,label:'youth'       ,clear:false, cat:this.CAT.FLAG_AGEGRP, mask:this.G2.FLAG_YOUTH     | this.G2.FLAG_SUBYOUTH}  ,true) );
		buttonList.push( new uiButton(this, {id:6, color:'rgb(0,64,0)'   ,label:'midget'      ,clear:true,  cat:this.CAT.FLAG_AGEGRP, mask:this.G2.FLAG_MIDGET    | this.G2.FLAG_SUBMIDGET} ,true) );
		buttonList.push( new uiButton(this, {id:7, color:'rgb(51,0,102)' ,label:'bantam'      ,clear:false, cat:this.CAT.FLAG_AGEGRP, mask:this.G2.FLAG_BANTAM    | this.G2.FLAG_SUBBANTAMX},true) );
		buttonList.push( new uiButton(this, {id:8, color:'#3c6'          ,label:'subbantam'   ,clear:false, cat:this.CAT.FLAG_AGEGRP, mask:this.G2.FLAG_SUBBANTAM | this.G2.FLAG_PRIMARY}   ,true) );
	
		new Insertion.Bottom(this.host, '<div id="viewPort"></div>');
		this.vu = $("viewPort");
		this.vu.clonePosition(this.host,{setLeft:true,setTop:false,setWidth:true,setHeight:false,offsetTop:192});
		this.vu.setStyle({backgroundColor:'#000',color:'#fc3',height:'32px',borderTop:'1px solid rgb(0,188,236)'
						  ,marginTop:'176px',fontSize:'10px',paddingTop:'4px'});
		this.vu.innerHTML = 'click/repeat-click category above to filter ...<br /> or click in report column heading to sort ...'
							+ '<br /> or mouse over event marks for meet info ...';
	
     // Wait until object is fully fleshed out, then define rounded corners ...
		var bgColor = ($('header').readAttribute('whoami')) ? '#0a0a0a' : 'transparent';
		Rounded("div#uiFilterWidget",bgColor,"rgb(0,188,236)"); 

		this.renderAllButtons();
		this.attachEventHandlers();
	  }
	 ,renderAllButtons: function() {this.buttonList.each( function(button){button.renderButtonState();} );}
/**	 ,mouseHandler: function(e) { var coord       =  [Event.pointerX(e), Event.pointerY(e)];	
		                          var coordinates = '['+coord[0]+','+coord[1]+']';
	 // See conflicting action in uiWidget's mouseTrackingHandler ...
	    this.vu.innerHTML = (Position.within(this.host, coord[0], coord[1])) ? coordinates :'';
	  } **/
	 ,attachEventHandlers: function() {
		/** %%%%%%%%%%%%%%%%%%%%%% Mousetrack to widget viewport %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		Event.observe( this.host, 'mouseover', this.mouseHandler.bindAsEventListener(  this  ));
		%%%%%%%%%%%%%%%%%%%%%%%%%% Mousetrack to widget viewport %%%%%%%%%%%%%%%%%%%%%%%%%%% **/
		Event.observe( this.host, 'mouseover'
		              ,(function(e) { if (this.hot) return;
						  this.hot          = true; 
						  this.vu.innerHTML = '';
						  this.widget.removeEventHandlers();
						  if (! this.widget.DOMObserver.suspendTracking) {															  
							this.widget.DOMObserver.handler.each( function(o) { o.value.stop(); });
							this.widget.DOMObserver.suspendTracking = true;
						  }
						}).bind( this ));
		Event.observe( this.host, 'mouseout'
		              ,(function(e) {
		                  if (isHot(this.host,[Event.pointerX(e),Event.pointerY(e)])) return;

						  this.hot          = false; 
						  this.vu.innerHTML = '';
						  this.widget.attachEventHandlers();

						  if (this.widget.DOMObserver.suspendTracking) {															  
							this.widget.DOMObserver.handler.each( function(o) { o.value.start(); });
							this.widget.DOMObserver.suspendTracking = false;
						  }
                        }).bind( this ));
	  }
	};
var uiButton = Class.create();
	uiButton.prototype = {
	  initialize: function( parent, settings, useDefaultStyling ) {
		this.parent   = parent;
		this.settings = settings;
	
		this.elID 	  = 'button_'+settings.id;
		new Insertion.Bottom( $(parent.host), '<div id="' +this.elID+ '"><div><h6>'+settings.label+'</h6></div></div>' );
		this.id = $(this.elID);
	
		Element.addClassName(this.id,'uiButton');
		Rounded("div#"+this.id.id,"#000",settings.color);
		if ( settings.clear ) {this.id.style.clear = 'left'; this.id.style.marginLeft='8px';}
	
		if (useDefaultStyling == true) this.applyDefaultStyling(settings.color);
	
		Event.observe( this.id ,'mouseup'   ,this.clickHandler.bindAsEventListener(this));
		Event.observe( this.id, 'mouseover' ,this.hoverHandler.bindAsEventListener(this));
		Event.observe( this.id, 'mouseout'  ,this.hoverNotHandler.bindAsEventListener(this));
	  }
	 ,clickHandler: function(e) { var el = Event.element(e).up('div.uiButton');
		var host = this.parent; // uiFilterWidget
		var CAT  = {FLAG_GENDER:0x1, FLAG_AGEGRP:0x2}; 
		var mask = this.settings.mask;		
		var cat  = this.settings.cat;
	
		if ( cat & CAT.FLAG_GENDER ) {
			if (host.gender !=host.G.BOTH  &&  host.gender !=mask)
				host.gender = mask;
			else
				host.gender ^= ((~mask) & 0x3);
		}
		else
		if ( cat & CAT.FLAG_AGEGRP ) {
	
			// if bOI (bitOfInterest) OFF, turn ON
			if (! (host.ageGrpFlag & mask) ) host.ageGrpFlag |= mask;
			else { // bOI is ON
				// if turning bOI OFF results in entire mask being OFF
				if (! (host.ageGrpFlag & ~mask)) host.ageGrpFlag = host.G2.FLAG_ALL_AGES;
				else
				if ( host.ageGrpFlag & ~mask)	host.ageGrpFlag = mask;
				else
				//  turn bit OFF
					host.ageGrpFlag &= ((~mask) & host.G2.FLAG_ALL_AGES);
		}	}
	
		host.widget.IXs=$A([]);
		host.widget.showTbl (host.widget.lastClicked, false);
		host.renderAllButtons();
	  }
	 ,hoverHandler: function(e) { e.stop();
	    document.body.setStyle( {cursor:POINTER} );
		this.id.down('h6').replaceClassName( ['smoke','bone'],'attention' );
		/** Use of Nifty (curvy corners) alters the landscape!
			- the DOM's DIV element nodes dissapear and are replaced by 'B' tagNamed elements ...
		**/
	  }
	 ,hoverNotHandler: function(e) { e.stop();
	    if (isHot( this.id,[Event.pointerX(e), Event.pointerY(e)] )) return;

	    document.body.setStyle( {cursor:DEFAULT} );
		this.renderButtonState();	
	  }
	 ,renderButtonState: function() {
		var flag = (this.settings.cat & this.parent.CAT.FLAG_GENDER) ? this.parent.gender:this.parent.ageGrpFlag;
		if ( flag & this.settings.mask) this.buttonDepressed();
		else
			this.applyDefaultStyling(this.settings.color);
	  }
	 ,applyDefaultStyling: function(color) {
		this.id.style.backgroundColor 	=  color;
		this.id.down('h6').replaceClassName('bone','smoke');
	  }
	 ,buttonDepressed: function() { this.id.down('h6').replaceClassName('smoke','bone'); }
	/**
	 ,applyDefaultStyling: function(color) {
		this.id.style.borderWidth 		= '3px';
		this.id.style.borderStyle 		= 'outset';
		this.id.style.borderColor 		= '#666';
		this.id.style.backgroundColor 	= '#333';
		this.id.style.color				=  color;
		this.id.style.paddingTop 		= '2px';
		this.id.style.paddingBottom 	= '2px';
		this.id.style.fontSize 			= (this.settings.label.length<7) ? '0.8em':'7.5px';
		this.id.style.paddingLeft 		= (this.settings.label.length<7) ?   '4px':'0px';
		this.id.style.paddingRight 		= (this.settings.label.length<7) ?     '0':'4px';
	  }
	 ,buttonDepressed: function() {
		this.id.style.borderStyle 		= 'inset';
		this.id.style.borderColor 		= '#555' ;
		this.id.style.backgroundColor 	= '#666' ;
	  }
	**/
	};
var uiTblElmt = Class.create();
	uiTblElmt.prototype = {
	  initialize: function( node ) {
		var split = node.firstChild.data.split(";");

		this.gender = split.shift(); // removes gender [ 1st field ]
		this.ageid  = split.shift(); // removes agegrp [ 2nd ... ]
		this.times  = split.filter(function(v,i){ return (((i+1) % 3)==0); });
		this.dates  = split.filter(function(v,i){ return (((i+2) % 3)==0); });
		this.events = split.filter(function(v,i){ return (((i+0) % 3)==0); });
	
		var toks    = node.attributes.getNamedItem("id").value.split(";");
		this.athl   = "".concat( toks[0], ", ", toks[1] );
	  }
	};

var DOMCollectable = {
  isHot:         function(el, coord) { return Position.within(el, coord[0], coord[1]); }
 ,push: 		 function(el)        { this.collection.push( el );   }
 ,pop : 		 function()          { return this.collection.pop(); }
 ,addItem:       function(obj)       { this.collection.push( obj );  }
 ,removeItem:    function(item) {
	var selection = function(v,prop,scalar)  { return v[prop] == scalar[prop]; };

	result = this.collection.inject( [], (function( out,v,i ) { if (selection(v,'el',this)) return [i]; }).bind(item) );
	return this.collection.splice(result[0],1);
  }
 ,findHot:       function(e) { return this.collection.detect( function(o) { return Position.within(o.el, Event.pointerX(e), Event.pointerY(e)); });}
};
var DOMObserver = Class.create();
	DOMObserver.prototype = {
	  initialize: function(framework,debug) { debug = debug || false;
		this._init.call(this,framework,debug);
	  }  
 	 ,toString: function(){ return this.me; }
	 ,_init: function(framework,debug) { 
		this.me 		     = 'DOMObserver';
		this.framework       = framework;
		this.TYPES		     = {BASE:0x1,IMAGE:0x2,XMRKR:0x4,JUMP:0x8,OTHER:0x10,GIFRAME:0x20,ALL:0x3f};	
		this.collection      = $A([]);
		this.lastActive	     = null;
		this.debug		     = debug;
        this.SPKeysMask      = 0x00;

		Object.extend( this, DOMCollectable );


		this.handler = $H({
          tracking:
            document.body.on( MOUSEMOVE,
			 (function(e) { 
				var hot=this.findHot(e); e.stop();
				if (hot && hot==this.lastActive) return;
				
				if (hot) { document.body.style.cursor = POINTER;
				  if (hot instanceof DocMarker
					  ||
					  hot instanceof DocGetIFrame) hot.mouseHandler();
				  this.lastActive = hot;
				}
				
				else {     document.body.style.cursor = DEFAULT;
				  if (this.lastActive instanceof DocMarker
					  || this.lastActive instanceof DocGetIFrame) this.lastActive.mouseHandler();
				  this.lastActive = null;
			  } }).bindAsEventListener(this))

		 ,click:
		    document.body.on( MOUSEUP,
		     (function(e) { 
				if ((clicked = this.findHot (e))) {
				  e.stop();
				  clicked.clickHandler();
				  this.lastActive = null;
			  } }).bindAsEventListener(this))

		 ,custom:
		    document.body.on( 'marker:vclick',
		     (function(e) {
		        this.collection.find(function(x){return x.el==Event.element(e);}).clickHandler();}).bind(this))

         ,keydown:
            document.on( 'keydown',
             (function(e) { var mask, K = SPECIALKEYS;
				e.cmdKey=(e.keyCode==K.CMDKEY || e.keyCode==K.FFCMDKEY);
				
				mask = K._CMD_*e.cmdKey + K._CTRL_*e.ctrlKey;
				this.SPKeysMask |= mask;
			
				if (this.SPKeysMask & (K._CMD_ | K._CTRL_)) {
				  switch(e.keyCode) {
					case 0x59:
							   customAjaxCall({arg:'survey' ,dimensions:$A([760,1938])
											   ,title:'VOTE ONCE ONLY !'
											   ,phpScript:'controller/getSingletonComponent.php'}); 
					  break;
					case 0x48:
					  $('DeBuG').toggle();
			
					  break;
					default:
				} } }).bindAsEventListener(this))

         ,keyup:
            document.on( 'keyup',
             (function(e) { var mask, K = SPECIALKEYS;
				mask =  K._CMD_  *(e.keyCode==K.CMDKEY || e.keyCode==K.FFCMDKEY) 
					  + K._CTRL_ *(e.keyCode==K.CTRLKEY ) ;
				this.SPKeysMask ^= mask;
			  }).bindAsEventListener(this))
		});
	  }
	};
var DocBase = Class.create();
	DocBase.prototype = {
	  initialize: function( el,observer ) {
		this._init.call(this,observer);
		this.el			 = el;
	  }
	 ,_init: function(observer) { // this.el to be defined within subclass ...
		this.me			 = 'DocBase';
		this.DOMObserver = observer;
		this.TYPES		 = {BASE:0x1,IMAGE:0x2,XMRKR:0x4,JUMP:0x8,OTHER:0x10,GIFRAME:0x20,ALL:0x3f};	
		this.type		 = this.TYPES.BASE;
	  } 
 	 ,toString: function(){ return this.me; }
	};
var DocImage = Class.create();
	DocImage.prototype     = Object.extend( new DocBase() ,{ 
	  initialize:function( el, observer ) {
		this._init.call(this,observer);
		this.me   = 'DocImage';
		this.type = this.TYPES.IMAGE;
		this.el	  = el.down('IMG');

		observer.addItem( this );
	  }
 	 ,toString: function(){ return this.me; }
	 ,clickHandler:function() { var attr; el = this.el.up('A');

		if ((attr=el.readAttribute("rel")) != null && attr.include("lightbox")) {
			var title = ((attr=el.readAttribute("title")) != null) ? attr:"";
	
			if (! this.DOMObserver.framework.match(/lightbox/))
			  window.Shadowbox.open( {content:el.up('div').innerHTML, title:title, player:"img", adapter:"prototype"} );
//			else
//			  window.lightBox.start( el );
	  } } } );
var DocJump = Class.create();
	DocJump.prototype      = Object.extend( new DocBase() ,{ 
	  initialize:function( el, observer ) {
		this._init.call(this,observer);
		this.me 	= 'DocJump';
		this.type	= this.TYPES.JUMP;
		this.el		= el;

		observer.addItem( this );
	  }
 	 ,toString: function(){ return this.me; }
	 ,clickHandler:function() {
		var content    = this.el.up().down('span').innerHTML;
		var dimensions = $A([550,400]);
		content.scan( /<iframe\s.+width="(\d+)"\sheight="(\d+)"/
			,function(m){ dimensions[0]=Number(m[1]); dimensions[1]=Number(m[2])+60; } );
		window.Shadowbox.open( { content: content
						,player: "html"
						,width:  dimensions[0]+320
						,height: dimensions[1]+128  } );
	  } } );
var DocGetIFrame = Class.create();
	DocGetIFrame.prototype = Object.extend( new DocBase() ,{ 
	  initialize:function( el, observer ) {
		this._init.call(this,observer);
		this.me 	= 'DocGIFrame';
		this.type	= this.TYPES.GIFRAME;
		this.el		= el;
		this.toggle = false;
		this.property = null;

		observer.addItem( this );
	  }
 	 ,toString: function(){ return this.me; }
	 ,mouseHandler:function() {

	 	if (this.toggle) this.el.style.color = this.property;

	 	else { 
	 	  this.property = this.el.style.color;
	 	  this.el.style.color = 'rgb(0,188,236)';
	 	}
	 	
	 	this.toggle = ~this.toggle;
	  }
	 ,clickHandler:function() {
		this.toggle         = false; 
		this.el.style.color = this.property;
		customAjaxCall( { arg:this.el.id 
		                 ,dimensions:$A([550,400])
					 	 ,title:this.el.down('span').innerHTML
						 ,phpScript:'controller/getSingletonComponent.php'} ); 
	  } } );
var DocMarker = Class.create();
	DocMarker.prototype    = Object.extend( new DocBase() ,{ 
/**   =========>> 
	  the declared custom event is fired on a fixed element: 
		the 1st descendant [li id="feedHead"] regardless of which [DocFold.]DocMarker is the triggering event. 
						   															
	  children[0].fire("marker:vclick"); // assumption: invoked only within a DocFold


	  alert(siblings.collect(function(v,k){return '\n'.concat(k+1,') ',v.getStyle('backgroundColor'));}));
	  this.DOMObserver.collection.find(function(x){return (x instanceof DocFold) && x.dna['foldEl']==foldEl;}).refresh('#800');

	  nodes.zip( width, function(v){ return {el:v[0], width:v[1]};} );
      =========>> **/
	  initialize:   function( el, observer ) {
		this._init.call(this,observer);
		this.me 	= 'DocMarker';
		this.type	= this.TYPES.XMRKR;
		this.el		= el;

		if ( el.tagName=='IMG' && el.readAttribute('rel')) {
  
			  var parent    =  el.up();
			  var chld1st   =  parent.down( 'p' );
			  var abbr      =  this.getFirst( chld1st.innerHTML, 2 );
			  this.dna      = {el:el ,parentHTML:parent.innerHTML ,targ:chld1st ,orig:chld1st.innerHTML ,trunc:abbr.out ,parentClassNames:parent.className};

			  chld1st.truncate( abbr.out.length );	  

			  var id        = el.readAttribute('rel')+'_'+observer.collection.findAll(function (x) {return (x instanceof DocMarker);}).length;
			  el.writeAttribute({ width:'28px', height:'28px', src:'data/assets/iMore.png', id:id });
			  el.setStyle({ marginLeft:'2px', marginTop:'-8px' });
			  el.addClassName('expand');
			  chld1st.nextSiblings().each( function(x) { if (x.id != el.id) x.hide(); });	// must follow id: attr assignment

		}
		observer.addItem( this );
	  }
 	 ,toString: function(){ return this.me; }
	 ,mouseHandler:  function() { var el;
		if ((el=this.el).hasClassName('expand')) {
		  el.writeAttribute( {src:el.readAttribute('src')
		    .sub( /(.*?)(\w+)(\.png)/
		  		 ,function(m){ return m[1]+ ((m[2].include('_')) ? 'iMore':'iMore_') +m[3]; } )} );
	  } }
	 ,clickHandler: function() { var seek;
		if ((seek=this.el.up('UL')) !== undefined 
			  && seek.firstDescendant().hasClassName('fold')) { // DocMarker within a DocFold
			var options  = {FULL_PORT:0x1,SHARE_PORT:0x2};
			options.mask = options.FULL_PORT;
		}
		else
			options = null;

		this.update( options );	
	  }
	 ,update:       function(options) {var dna=this.dna, el=this.el;
	
		var SB		 = window.Shadowbox;
			SB 		 = null;
		var me 		 = 'update:';
		var tax		 = 13.75;
		var expand	 = 'expand';
		var collapse = 'collapse';
		var x;
			
		if (el.hasClassName(expand))	{ //alert('[ COLLAPSED => EXPANDED ]\n DocMarker < DocFold: '+(options != null));
			if (SB)
				SB.open({content:    dna.parentHTML,
						 player:     "html",
						 title:      "",
						 height:     750,
						 width:      750
					   });
	
			if (options) { // DocMarker < DocFold
				if (options.FULL_PORT & options.mask) {
					var target   = el.up('LI');
					target.ancestors()[0].childElements().slice(1).invoke('hide');
					showTree( target );
					
					var el2   = dna.targ.up('div');
					var width = new Element.Layout(target.up().down()).get('width');

					// ooh... a function that returns a function !
					var aFunc = function(obj) {return function(memo,v) {memo[v]=obj.getStyle(v); return memo;};};
					this.propertiesMap = $A([ {fld:el2    ,prop:$w('backgroundColor color fontSize width float textAlign padding')}
					    					 ,{fld:target ,prop:['padding']}
					    				     ,{fld:el.up('li') ,prop:['backgroundColor']}
					    				   ]);
					this.propertiesMap.each(
						function(x){ x.savedProps = $H(x.prop.inject( {},aFunc(x.fld) )); });

					el2.setStyle({backgroundColor:'#000',color:'#ed762e',fontSize:'140%',width:width+'px',float:'left',textAlign:'justify',padding:'8px'});
			  		target.setStyle({padding:0});
			  		this.el.up('li').setStyle({backgroundColor:'transparent'}); // LI and div descendant dont align ... li backgroundColor frag showing thru ...
				}	
				else {
					dna.targ.up('UL').descendants().invoke('show');
			}	}
	
			else { dna.targ.nextSiblings().invoke('show'); 
				   if ($w(dna.parentClassNames).any(function(q){return q.match(/halfwidth/);})) { 
					   x = dna.el.up();
					   x.removeClassName('halfwidth');
					   if (x.hasClassName('tab48')) x.removeClassName('tab48');
				 } }

			el.replaceClassName( expand,collapse );
			dna.targ.update( dna.orig );
	
			el.writeAttribute(
				{src:el.readAttribute('src').gsub(/(.*?)\w+(\.png)/,'#{1}iLess#{2}')});
		}
		
		else
		if (el.hasClassName(collapse))	{ //alert('[ EXPANDED => COLLAPSED ]\n DocMarker < DocFold: '+(options != null));

			if (options) { // DocMarker < DocFold
				this.updateHelper();
				
				var aFunc = function(obj) {return function(v) {obj.style[v.key]=v.value;}; };
				this.propertiesMap.each( function(x){ x.savedProps.each( aFunc(x.fld) ); } );

				el.up('UL').firstDescendant().nextSiblings().invoke('show');
			}
			else { this.updateHelper(); }
			
		} else alert("EXCEPTION - element has no assigned ClassName"); }  	
	 ,updateHelper: function() { var dna=this.dna;

			dna.targ.update( dna.trunc );
			this.el.replaceClassName('collapse','expand');
			this.el.writeAttribute( {src:this.el.readAttribute('src').gsub(/(.*?)\w+(\.png)/,'#{1}iMore#{2}')} );
			dna.targ.nextSiblings().each( (function(el) { if (el.id != this.el.id) el.hide(); }).bind(this));
			dna.el.up().className = dna.parentClassNames;
	  }
	 ,isFoldMember: function() { var el;
	 	return (el = this.el.ancestors().detect( function(x){return 'UL'.include(x.tagName);} )) && el.firstDescendant().hasClassName("fold");}
	 ,getFirst:     function(text, n) {
		var k  = (this.getFirst.arguments.length==0) ? 2:n;
		
		if ( k==0 ) return {out:text, more:false};
		else {
		
			text = text.gsub( /([.?!]["\']?)\s/, '#{1}bRE@kH3re' );
	
			var sentences = text.split( 'bRE@kH3re' );
			k = ( k>sentences.length ) ? sentences.length:k;
			n = ( sentences.length>k ) ? sentences.length-k:0;
			var remaining = sentences.splice( k, n );
			var out = sentences.join(' ');
			var more = !(n==0);
			return {out:out, more:more};
	  } } } );
var DocFold = Class.create();
	DocFold.prototype 	   = Object.extend( new DocBase() ,{ 
	  initialize:function( el, observer, mode ) { // mode={x:0x1,o:0x2,mask:?}
		this._init.call(this,observer);
		this.me   = 'DocFold';
		this.type = this.TYPES.OTHER;

		var html  = '<img src="data/assets/#.png" width="28px" height="28px" />';
		if (mode.mask & mode.x) {
		  el.addClassName('collapse');
		  html = html.gsub(/(.*?)#(\.png.*)/i,'#{1}upArrow#{2}'  );
		}
		else { 
		  el.addClassName('expand')
		  html = html.gsub(/(.*?)#(\.png.*)/i,'#{1}downArrow#{2}');
		}

		new Insertion.Bottom( el, html );
		
		var img = el.down('img');
		img.setStyle( {position:'relative', top:'8px', left:'8px'} );
		
		this.el	 = img; // make the IMG the  W A T C H  element (rather than the LI)
		this.dna = {foldEl:el, foldHTML:el.innerHTML};
		this.refresh();

		observer.addItem( this );
		
	  }
 	 ,toString: function(){ return this.me; }
	 ,refresh:       function(color) { var container = this.dna.foldEl.up('div');
		inkColor = color || '#7e7e7e';

		Selector.findChildElements( container, [new Selector('ul:first-child>li:nth-child(odd)')] ).each(
			function(el) {el.style.backgroundColor	= '#00102c';
						  el.down().style.color		= inkColor;} );
		container.down(1).style.backgroundColor     = '#0f0f0f';
	
		Selector.findChildElements( container, [new Selector('ul:first-child>li:nth-child(even)')] ).each( 
			function(el) {el.style.backgroundColor	= '#4c4c2c';
						  el.down().style.color		= inkColor;} );

		Selector.findChildElements( container, [new Selector('ul:first-child>li:nth-child(3n+2)')] ).each( 
			function(el) {el.style.clear = 'left';} );

		if ((foldEl=this.dna.foldEl).hasClassName('collapse')) foldEl.siblings().invoke('hide');
	  }
	 ,clickHandler: function(e) { var foldEl = this.dna.foldEl;
	 							  var img    = this.el;
	 	
		if (foldEl.hasClassName('collapse')) {
			var el = foldEl.siblings().find(
				function(x){ 
				  var v=x.select('img[rel^="xMrKr"]');
				  return (v.length>0 && v[0].hasClassName('collapse')) ? true:false; 
				});
			if (el) { el.select('img[rel^="xMrKr"]')[0].fire("marker:vclick"); }
			
			foldEl.siblings().invoke('show');
			foldEl.replaceClassName( 'collapse','expand' );
	
			img.writeAttribute(
				{src:img.readAttribute('src').gsub(/(.*?)\w+(\.png)/,'#{1}downArrow#{2}')});
		}
		else { // hasClassName('expand')
			foldEl.replaceClassName( 'expand','collapse' );
			foldEl.siblings().invoke('hide');
	
			img.writeAttribute(
				{src:img.readAttribute('src').gsub(/(.*?)\w+(\.png)/,'#{1}upArrow#{2}')});
	} }	} );

var TogglePane = Class.create();
	TogglePane.prototype = {
	  initialize: function( fieldset, useDefaultStyling ) {
	  //
	  // Get references to the fieldset and its legend
	  //
	  this.fieldset = $(fieldset);
	  if (!this.fieldset)
		throw new Error('cannot locate fieldset ' + fieldset);
	  if (this.fieldset.tagName != 'FIELDSET')
		throw new Error('passed element must be a fieldset');
	
	  this.legend = this.fieldset.down('legend');	// getElementsByTagName('legend')[0];
	  if (!this.legend)
		throw new Error('cannot locate fieldset\'s legend');
	  //
	  // Add the tooglePane class to the fieldset
	  //
	  Element.addClassName(this.fieldset,'togglePane'); // hang CSS hook ...
	  //
	  // Set up the onclick handler for the legend
	  //
	  var fieldsetElement = this.fieldset;
	  this.legend.onclick = function() {
		$A(fieldsetElement.childNodes).each(
		  function(child) {
			if (child.nodeType == Node.ELEMENT_NODE &&
				child.tagName != 'LEGEND') {
			  Effect.toggle(child);
			}
		  }
		);
	  }
	  //
	  // Apply default styling to the legend if enabled
	  //
	  if (useDefaultStyling == true) this.applyDefaultStyling();
	}
	 ,applyDefaultStyling: function() {
		this.legend.style.borderWidth = '3px';
		this.legend.style.borderStyle = 'outset';
		this.legend.style.borderColor = '#666';
		this.legend.style.backgroundColor = '#333';
		this.legend.style.cursor = POINTER;
		this.legend.style.paddingTop = '1px';
		this.legend.style.paddingBottom = '1px';
		this.legend.style.paddingLeft = '18px';
		this.legend.style.paddingRight = '18px';
		this.legend.style.fontSize = '0.8em';
	  }
	};
var BrowserDetect = Class.create();
	BrowserDetect.prototype = {
	initialize: function() {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	
	};

function addCommonHandler( ) { var el;

	this.content   = 'content';
	this.spotlite  = 'active2';
	this.mouseover = 'mouseover';
	this.mouseout  = 'mouseout';
	this.mouseup   = 'mouseup';
	this.mousemove = 'mousemove';
	this.reset     = DEFAULT;
	this.pointer   = POINTER;
	this.uiWidget  = null;
	this.updater   = null;
	this.timer_id  = null;

	if (new BrowserDetect().browser == 'Explorer')
		{ this.mouseover='mouseenter'; this.mouseout='mouseleave'; }

	if (Prototype.Browser.IE) $('content').style.zIndex = 0;

	
	this.DOMObserver = new DOMObserver( this.framework, this.debug );

	$$('div[id~="content"] a[rel^="lightbox"]').each( 
	   (function(el) { new DocImage    (el,this); } ).bind(this.DOMObserver) );
	$$('div.youtube img').each( 
	   (function(el) { new DocJump     (el,this); } ).bind(this.DOMObserver) );
	$$('div.theButton').each( 
	   (function(el) { new DocGetIFrame(el,this); } ).bind(this.DOMObserver) );
	$$('img[rel^="xMrKr"]').each( 
	   (function(el) { new DocMarker   (el,this); } ).bind(this.DOMObserver) );
	$$('li[class~="fold"]').each( 
	   (function(el) { new DocFold     (el,this,{x:0x1,o:0x2,mask:0x2}); } ).bind(this.DOMObserver) );
//>>>
//>>>
//>>>                                              boolean shallow
    show(this.debug,'DOMObserver',this.DOMObserver,true);
//>>>                                              false fails, some lower level browser obj's toString method is undefined or fails
//>>>
//>>>

	if ((el=(! $('header').readAttribute('whoami')) && $('target'))) {

	  //var map = Builder.node('div' ,{id:'tArGeT',border:'2px dotted #f00',zIndex:999},[Builder.node('img',{src:'data/assets/floodshill.png'})]);
	  //$('container').appendChild(map).absolutize().clonePosition($('messageBd'),{setWidth:false,setHeight:false,offsetTop:160,offsetLeft:710}).hide();
  
	  Event.observe( el, MOUSEOVER, function(){ el.style.cursor = POINTER; 
	  								  //$('tArGeT').toggle(); el.select('p').each(function(x){x.toggle();});
	  								} ); 
	  Event.observe( el, MOUSEOUT , function(){ el.style.cursor = DEFAULT; 
	                                  //$('tArGeT').toggle(); el.select('p').each(function(x){x.toggle();}); 
	                                } ); 
	  Event.observe( el, MOUSEUP,  function(){ 
/*	                                           customAjaxCall({arg:'montclair-state' ,dimensions:$A([825,615])
													           ,title:'Carlisle Rd near Quarry Rd, Montclair St., Little Falls'
													           ,phpScript:'controller/getSingletonComponent.php'}); */
		  window.Shadowbox.open( { content: '<img src="data/assets/registrationFlyer_.png" />'
						  ,player: "html"
						  ,title:  "upcoming registration ..."
						  ,width:  402
						  ,height: 603 });
						 } );
	}
	

  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	var hObj = { map:[-1,-1], handler:null, flag:null };

	$('center').on( MOUSEOVER,
	  function(e,el) { if (hObj.handler) { hObj.handler.start(); return; }
    	hObj.flag    = (hObj.map.min() >0);
		hObj.handler = el.on( MOUSEMOVE,
			  function(e,el) { offsetX = Event.pointerX(e) - el.cumulativeOffset()[0];
	
				 el.style.cursor 
					= (hObj.flag && offsetX>hObj.map[0] && offsetX<hObj.map[1]) ? DEFAULT:POINTER;
	} ); } ); 

	$('center').on( MOUSEOUT ,function(e,el) { el.setStyle( {cursor:DEFAULT} ); 
											   hObj.handler.stop();
											 } ); 

	$('center').on( MOUSEUP 
					,function(e,el) { var    mode,
										  offsetX = Event.pointerX(e) - el.cumulativeOffset()[0];

					   if ( (hObj.map[0]*hObj.map[1]) <=0 ) {
					       if (offsetX > hObj.map.max()) mode=1;
					       else
					         mode=-1;
					   }
					   else
					   if (hObj.map.min()>0)  {
					       if ( offsetX>hObj.map[0] && offsetX<hObj.map[1] ) mode=0;
					   }
					   else
					       mode=-1;

					   this.mode = mode;
					   
					   if (mode!=0) {
									  customAjaxCall({arg:'bAnNeR' ,dimensions:$A([1250,800])
													  ,title:'Apparel'
													  ,phpScript:'controller/getSingletonComponent.php'}); 
									}
	} );
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


	$('calendar','standard1','standard2','standard3','reports').each ( (function( el ) { 
	   Event.observe( el, this.mouseup, 
		   (function(e) { var       el = Event.element(e),
		   					  userpick = el.identify();
		   	   			   		
			  if ( userpick=='calendar' ) {
											customAjaxCall({arg:'teamcalendar' ,dimensions:$A([805,615])
															,title:'TENTATIVE v.2'
															,phpScript:'controller/getSingletonComponent.php'}); 
			  							  }

			  else {
 
				if (! $('header').readAttribute('whoami')) { // home page
				  if (this.updater) { 
					  this.updater.stop();           // halt the slideshow
					  clearTimeout( this.timer_id ); // stop the queued fade out ...
				} }

				else { // results page
				  $$('div#filters').each(
					  function() {
						if (! this.savedHTML) this.savedHTML = new String($(this.content).innerHTML);
						$('resetButton').value = 'Redisplay Results';
						Form.Element.disable('processButton');
					  }.bind(this) );
				}

				if ( userpick=='reports' ) {
				  $('content').setStyle( {border:'1px solid rgb(0,188,236)',color:'rgb(178,216,79)',background:'#000 none',margin:'0 auto'} );
				  
				  if (this.uiWidget) {
					  $(this.content).update( '<div id="housing"></div>' );													
					  this.uiWidget.showTbl(this.uiWidget.lastClicked, false);

					  $('tb').fire('widget:redraw');
					  $$('#left-container div#uiFilterWidget').invoke('show');
					  $$('div.blackbox').invoke( 'hide' );
				  }

				  else { var reportTitle = el.firstChild.data;
				  
					  setInterimStatus('Processing ...');
					  new Ajax.Request( 'controller/performance_export.php'
									 ,{method:'post'
									   ,parameters: $H({arg:reportTitle}).toQueryString()
									   ,onComplete:handleSuccess.bind(this)
									   ,onFailure: handleFailure
									   ,evalScripts:false} );
				} }
 
				else {
				  
				  imgDocumentDisplayHandler.call( this,e );
				  $$('#left-container div#uiFilterWidget').invoke('hide');
			  }	}

	   }).bind(this) ); }).bind(this) );


	var rePosition = function() {
		   return (Prototype.Browser.IE)
					   ? function(y,zL,offsetTop){y.setStyle({top: offsetTop+'px' ,left: zL.get('margin-box-width')+'px'}).show();}
					   : function(y,zL,offsetTop,el){y.clonePosition(el,{ setWidth:false,setHeight:false,offsetLeft:zL.get('margin-box-width'),offsetTop:offsetTop} ).show();};
		   };
	
	$$('div#nav li.blackbox').each( // manage navbar level(n) drop downs ...
	  function(d1){ 
	    d1.on( MOUSEOVER,"li.blackbox", 
			   function(e,z){ e.stop();
				 var list,topDrop, el=z.down('ul'); 
				 list = el.down().ancestors().findAll(function(y){return y instanceof HTMLUListElement;});
				 // preemptive cancel of sticky drop-down
				    list.pop().childElements().findAll(
				    	function(x){return x.hasClassName('blackbox');}).each(function(x){x.down('ul').hide();});
				 topDrop = list.pop();
				 topDrop.setStyle({width:'380px'}).show();
				 if ( Prototype.Browser.IE && topDrop.select('li.blackbox').length) // unable to grab onto thru css ...
				 	topDrop.select('li.blackbox')[0].style.paddingTop='16px'; 
				 if (list.length>0) {
				   el = el.up();    		// LI.blackbox
				   list.reverse().each(     // UL
					 function(y) {
					   var zL= z.getLayout(), yDL= y.down().getLayout();
					   var offsetTop = parseInt( (yDL.get('margin-box-height')-zL.get('margin-box-height'))/4 );
					   				/* parseInt((yDL.get('margin-box-height')-y.measure('margin-box-height'))/2)
					   				   + parseInt((zL.get('margin-box-height')-yDL.get('margin-box-height'))/2); */
					   					
					   					
					   /**  alert(
								 'WebKit:  '+(Prototype.Browser.WebKit==true)
								+'\nGecko: '+(Prototype.Browser.Gecko ==true)
								+'\nIE:    '+(Prototype.Browser.IE    ==true)
								+'\nOpera: '+(Prototype.Browser.Opera ==true)

					   			+'\n\nviewport: '       +z .viewportOffset()
					   			+'\npositionedOffset: ' +z .positionedOffset()
					        	+'\ncumulativeOffset: ' +z .cumulativeScrollOffset()
					   			+'\ngetLayout: ['       +zL.get('left') +', '
					   			                        +zL.get('top')  +'] :: width: <'
					   			                        +zL.get('margin-box-width') +'>'
					   			
					   			+'\n\nDesc vOffset: <'  +   offsetTop   +'>'
					        );  **/

					   rePosition()(y,zL,offsetTop,el);

					   el = y.up();			// LI.blackbox
					 } );
				 } } );
	    d1.on( MOUSEOUT,"li.blackbox", function(e,z){ e.stop(); z.down('ul').hide(); } );
	} );
}
function imgDocumentDisplayHandler( e ) {

	var mode = -1,
	      id = Event.element(e).identify();

	if ( id=='center')    mode = (this.mode>0) ? 1: (this.mode<0) ? 0 :-1;  //remap from Observer set values
	else
	if ( id=='calendar')  mode = 2;
	else
	if ( id=='standard1') mode = 3;
	else
	if ( id=='standard2') mode = 4;
	else
	if ( id=='standard3') mode = 5;
	
	if ( mode > -1 ) {

		new Ajax.Updater( $('content'), 'view/showImageDocument.php',
					      {method:'post',
						   parameters: $H( {mode: mode} ).toQueryString(),
						   onComplete: jumpToFlyer.bind(this),
						   evalScripts:true}); 
}	}
function jumpToFlyer( ) {

	 $('content').setStyle( {background:'#000 none',border:'1px solid #fc3',margin:'0 auto'} );
	$$('div#nifty h1').each( 
		function( item ) {item.setStyle( {margin:'5px 30px', fontSize:'250%', color:'#fc3'} );} );		
	$$('div#nifty ul').each( 
		function( item ) {item.setStyle( {listStyleType:'none'} );} );
	$$('div#nifty a img').each(
		function( item ) { 
			var watch = this.DOMObserver;
			watch.addItem( {el:item, type:watch.TYPES.BASE} );

		    Event.observe( document.body, 'mouseup',
		    				function(e) { Event.stop( e );
								var coord = [Event.pointerX(e), Event.pointerY(e)];
								if (! isHot( item,coord )) return;

		    					
		    					// alert('PDF ClickHandler: '+item.up('a').readAttribute("href"));

								new Ajax.Request('controller/ftp_this.php'
				 					,{method:'post' ,asynchronous:true ,evalJSON:true ,evalScripts:false 
				 					 ,parameters: $H({arg:item.up('a').readAttribute("href")}).toQueryString()
									 ,onComplete: function(transport) { var local = transport.responseJSON;
													alert('FTP: '+local.arg+' | '+local.status);
												  }
									 });


							});
		}.bind( this ) );

	frameMe();
}
function handleSingletonJSONResponse( transport ) {
	var local = transport.responseJSON;

	window.Shadowbox.open( { content: local.singleton
					,player: "html"
					,title:  "Click destination point or use map controls ..."
					,height: 460
					,width:  400 } );
}
function frameMe( ) {
	if(!NiftyCheck())
		return;
	Rounded("div#nifty"   ,"#000000","#161616");
	Rounded("div#nifty li","#161616","#000000");

	var nifty 	 = $('nifty');
	var iWrap	 = $('iWrap');
	var theImage = iWrap.down('img');
	var xBox     = $("content").getWidth();

/**	document.observe("widget:kluge", function() { this.getDimensions(); }.bindAsEventListener(theImage) );
	theImage.fire("widget:kluge");
**/
	var scaleFactor  = 0.95;
	var width,hrzMargin;
	
	width=Math.round(xBox*0.95);
	hrzMargin=Math.round((xBox-width)/2);
	nifty.setStyle( {margin:'8px '+hrzMargin+'px', width:width, backgroundColor:'#161616'} );

	width=Math.round(width*0.90);
	hrzMargin=Math.round((nifty.getWidth()-width)/2);
	iWrap.setStyle( {margin:'12px '+hrzMargin+'px', width:width, backgroundColor:'#000', listStyleType:'none'} );
	var maxWidth = iWrap.getWidth();

	var fileInfo = [];
	/** unable to resolve a synchronization issue 
		- whereby a 2nd user interaction(enter) is needed in order to pick up the rescaled image's dimensions
		  so the workaround is to predetermine the originating image on the server-side,
		  and not rely on the client-side getDimension method ... **/
	var xImage	 = {};	// =theImage.getDimensions();

	theImage.id.scan( /(.*?)\?(\d+)X(\d+)/
				,function(match) { for (i=0; i<3; i++) {fileInfo.push( match[i+1] );} } );	
	xImage.width = fileInfo[1];
	xImage.height= fileInfo[2];
	if ( (xImage.width/maxWidth) > scaleFactor ) {
		var shrink=scaleFactor*maxWidth/xImage.width;

		var aspect = xImage.width / xImage.height;
		var nW = Math.round( xImage.width*shrink );
		var nH = Math.round( nW / aspect);
		xImage.width=nW; xImage.height=nH;
	}
	hrzMargin = (maxWidth-xImage.width) /2;
	theImage.setStyle(	{margin:'4px '+hrzMargin+'px', width:xImage.width+'px', height:xImage.height+'px'} );
}
function handleSuccess(transport) { 
	var uiTbl = $A([]);
	var uiRef1= $A([]); // agegroups
	var uiTitle=null;
	var debug = false;

	if ( typeof transport.responseXML  != 'undefined' && transport.responseXML  != null ) {
	   if ((docRoot= transport.responseXML.getElementsByTagName('STAT_Summary')[0])) {

		   $A(docRoot.getElementsByTagName('performances')).each( 
			   function(node) {
			   	   uiTitle = node.attributes.getNamedItem("id").value;
				   $A(node.getElementsByTagName('athletes')[0]. getElementsByTagName('athl')).each(
					   function(node) { uiTbl.push( new uiTblElmt( node ) ); } );
   
				   var mask = 0x1;
				   $A(node.getElementsByTagName('agegroups')[0]. getElementsByTagName('agegroup')).each(
					   function(node) { uiRef1.push( {id:node.attributes.getNamedItem("id").value, value:node.firstChild.data, mask:mask} ); mask <<= 1;} );
			   } );
	}   }

	if ( typeof transport.responseJSON != 'undefined' && transport.responseJSON != null ) {
	   var local = transport.responseJSON;
	   
	   debug = true;
	}


	$$('div.blackbox').invoke( 'hide' );
	$('right-container').hide();

	$('content').setStyle( {border:'1px solid rgb(0,188,236)',color:'rgb(178,216,79)',backgroundColor:'#000'} );
	new Insertion.Top( $('content'), '<div id="housing"></div>' );
	$('housing').setStyle({marginBottom:'4px'});

	this.uiWidget = new uiWidget('housing', uiTitle, uiTbl, uiRef1, this.ptblcols, this.DOMObserver);
	
	if (debug) { new Insertion.Top( $('content'), "<span>" +local.debug+ "</span>" ); setStatus( 'mode: DEBUG' ); }
	else
		setStatus( 'Report Created ...' );
}
function isHot( el, coord) { return Position.within(el, coord[0], coord[1]); }
function handleFailure( transport ) { 
	setStatus( 'Error retrieving response', true );
	alert('Error: ' + transport.statusText);
}
function getActivatedObject(e) { var obj = null;
	if ( !e )						obj = window.event.srcElement; 	// early version of IE
	else
	if (document.addEventListener)	obj = e.target;					// DOM Level 2
	else
	if (document.attachEvent)		obj = e.srcElement;				// IE7

	return obj;
}
function getRelatedTarget(e) {
	return ( !e ) ? null : (document.attachEvent) ? e.relatedTarget:e.toElement;
}
function setStatus( msg ) {
	var isError = typeof arguments[1]== 'boolean' && arguments[1];
	var status = $("status");
	var options = {
			startcolor: isError? '#880000' : '#008800',
			restorecolor: '#333333',
			duration: 3,
			afterFinish: (function() { this.update(this.defaultContent); }).bind(status) };
		
	status.update(msg);
	new Effect.Highlight( status, options);
}
function setInterimStatus( msg ) {
	var isError = typeof arguments[1]== 'boolean' && arguments[1];
	var status = $("status");
	var options = {
			startcolor: isError ? '#880000' : '#008800',
			endcolor: '#333333',
			duration: 4
		};
		
	status.update(msg);
	new Effect.Highlight( status, options);
}
function showTree(el) {
	el.show();
  	el.descendants().each( function(chld) {showTree(chld);} );
}
function show(debug,title,obj,shallow) { var dbg, shallow=(shallow===undefined) ? true:shallow;
  if (debug) { if ((dbg=$('DeBuG')) && dbg.hasClassName('nodisplay')) dbg.removeClassName('nodisplay');
  /** div#DeBuG is predefined in document's html - /includes/component_header_inc.php
       otherwise scroll bars wouldn't be active after dynamically added ... **/
  try { dbg.innerHTML = dbg.innerHTML.concat('<h4 class="bone">| ',title,' |</h4>',showObj(obj,shallow));
  } 
  catch (e) { alert(e.name+': '+e.message); }
} }
function showObj(obj,shallow,lvl,stack,onOff) { lvl=lvl || 0;  stack=stack || $A([]); shallow=(shallow===undefined) ? true:shallow; onOff = (onOff===undefined) ? false: onOff;
  var i,j,s,ix,flg,flg2, out='';
  var isPrimitive = function(o) { return (! (o && (typeof o)=='object')); };
  var isBrowserObj= function(o) { if (isPrimitive(o)) return false; 
					  var regex = new RegExp("(?:\\[object\\s)(.*?)(?=\\])","i");
					  return (regex.test(o) && regex.exec(o)[1].toLowerCase().indexOf('html')==0);
					};
/**					    var myRe1 = new RegExp("(?:function\\s)(.*?)(?=\\(\\))","i");
						switch ( (new BrowserDetect()).browser ) {
							case 'Safari':
							case 'Chrome':
							case 'Firefox':
								break;
							default:
						}
**/
  // test for simple/complex objects here ... handle primitives below !
  if (! isPrimitive(obj)) {
    flg=false;
	// 1st object is top-level entry of objectTree
	if (stack.length==0) {stack.push(obj); flg = true;}

	for (i in obj) { if (obj.hasOwnProperty(i)) { // walk tree, descendant objs handled recursively ...
		flg2=false;
//if (i.match(/handler/)) onOff=true;
		if ( obj[i] instanceof Array ) { //handle arrays first ... they're specials instances of objects
			out = out.concat('<br /><br />','<h4 class="attention2">Array</h4>');
			j = 0;
			$A(obj[i].slice(0)).each(
				function(o){ stack.push(o); out = out.concat( '<br /><h4 class="attention2">[',j,']: ',o,'</h4> ',showObj(o,shallow,lvl+1,stack) ); stack.pop(); j++; });
		}

		else {
		  if ( shallow && isBrowserObj(obj[i])) { // halt reflection of browser objects ...
			  out = out.concat('<br />',i,': <h4 class="attention">',obj[i],'</h4>');
		  }
  
		  else
		  if (! isPrimitive(obj[i])) { // manage callStack - require circular reference detection
			if (stack.find(function(q){return obj[i]===q;})) { // halt recursion on circular reference
			  out = out.concat('<br />',i,':<h4 class="bone"> ',obj[i],'</h4>');
			}
			else {
			  stack.push(obj[i]);
			  if (onOff) {alert('push: '+obj[i]+'\n|primitive? '+isPrimitive(obj[i])+'| |type? '+(typeof obj[i])+'|\n\n<'+stack.length+'>\n'+stack.join('\n'));}
			  out = out.concat('<br /><h4 class="sky">',i,'</h4>: ',showObj(obj[i],shallow,lvl+1,stack,onOff)); 
			  s = stack.pop();
              if (onOff) {alert('pop: '+s+'\n<'+stack.length+'>\n'+stack.join('\n'));}
		  } }
  
		  else { // a primitive ... plus null AND undefined
			  out = out.concat('<br />',i,': ',showObj(obj[i]));
    } } } }

    if (flg) {s = stack.pop();}
  }
  
  //  handle primitive types PLUS: {functions,null,undefined}
  else { var myRe1 = new RegExp('(?:function.*?\\()(.*?)(?=\\)\\s*{).','i');
	switch ( typeof obj ) {
		case 'string':
			out = obj;
			break;
		case 'number':
			out = parseInt(obj,10);
			break;
		case 'boolean':
			out = out.concat('<h4 class="attention">',obj,'</h4>');
			break;
		case 'function':
			out = (myRe1.test(obj) && myRe1.exec(obj)[1].length) 
				  ? out.concat('function<h4 class="lime">(',myRe1.exec(obj)[1],')</h4>')
				  : 'function()';
			break;
		case 'object':
			out = '<h4 class="attention2">null</h4>';
			break;
		default:
			out = '<h4 class="attention2">unknown/undefined</h4>';
  } }

  return out;
}
function customAjaxCall( custObj ) {
  var aFunc      = function(obj) {
					 return function(transport) {
							  var dimensions = obj.dfltPortDimensions;
							  transport.responseJSON.singleton.scan( /<iframe\s+width="(\d+)"\sheight="(\d+)"/
								  ,function(m){ dimensions[0]=Number(m[1]); dimensions[1]=Number(m[2])+96; } );

							  window.Shadowbox.open( { content: transport.responseJSON.singleton
											  ,player: "html"
											  ,title:  obj.title
											  ,width:  dimensions[0]
											  ,height: dimensions[1] });
							}; };

  var       aObj = {dfltPortDimensions:custObj.dimensions, title:custObj.title};
  var optionsObj = { method:'post' ,asynchronous:true ,evalJSON:true ,evalScripts:false 
                    ,parameters: $H({arg:custObj.arg}).toQueryString()
                    ,onComplete: aFunc(aObj)
                   };

  new Ajax.Request( custObj.phpScript, optionsObj );
}

