// AjaxRequest Class
//   :: Purpose: provides a simple way to handle an Ajax request. Updates AjaxData to add error handling through the Modal Box
//   :: Required Files:
//         js.frameworks.prototype.*
//         js.application.controls.Utility - Browser()
//         js.application.controls.Utility - Modal()

var AjaxRequest=Class.create({initialize:function(a,b,c){if(c){this.callPostAjax(a,b,c)}else{this.setPoststring(a);this.callGetAjax(b)}},callGetAjax:function(c){var d=this.showError.bind(this);new Ajax.Request(this.url,{method:'get',onSuccess:function(a){try{var b=a.responseText.evalJSON();if(b.ERROR){d(b)}else{if(c)c(b)}}catch(err){d(err)}},onFailure:function(a){d(a)}})},callPostAjax:function(c,d,e){var f=this.showError.bind(this);new Ajax.Request(c,{method:'post',parameters:e,onSuccess:function(a){try{var b=a.responseText.evalJSON();if(b.ERROR){f(b)}else{if(d)d(b)}}catch(err){f(err)}},onFailure:function(a){f(a)}})},showError:function(a){if(a.DEBUG==1){var b=new Element('div');b.insert(a.MESSAGE);b.insert(new Element('br'));b.insert(a.CLASS);b.insert(new Element('br'));b.insert(a.LINE);new Modal.Alert(b).openBox()}else{if(a.MESSAGE){new Modal.Alert(a.MESSAGE).openBox()}else if(a.message){new Modal.Alert(a.message).openBox()}else if(a.status){new Modal.Alert(a.status).openBox()}else{new Modal.Alert('Unknown Error').openBox()}}},setPoststring:function(a){this.url=a+'&requestId='+this.getRandom()},getRandom:function(){return Math.floor(Math.random()*1000000)}});

// Ajax.Responders.register Method
//   :: Purpose: adds abort method to Ajax.Request
//   :: Required Files:
//			js.frameworks.prototype
Ajax.Responders.register({onCreate:function(a){RequestHolder.push(a);Ajax.activeRequestCount++},onComplete:function(a){Ajax.activeRequestCount--;if(Ajax.activeRequestCount<0){Ajax.activeRequestCount=0}},onFailure:function(){Ajax.activeRequestCount--},onException:function(){Ajax.activeRequestCount--}});

/*
onCreate----
if($('center-rail').select('div.bar-loader').length == 0){
			this.pageLoader = new Modal(new Element('div',{'class':'bar-loader','style':'width:215px'}).update('Loading... Please Wait.'),{'dropzone':'center-rail','blockbackground':true,'showclose':false});
			this.pageLoader.openBox();
		}
onComplete----
if($('center-rail').select('div.bar-loader').length > 0 && Ajax.activeRequestCount == 0){
			this.pageLoader.closeBox();
		}
*/

// Ajax.Request.prototype.abort Method
//   :: Purpose: adds abort method to Ajax.Request
//   :: Required Files:
//			js.frameworks.prototype
Ajax.Request.prototype.abort=function(){this.transport.onreadystatechange=Prototype.emptyFunction;this.transport.abort();Ajax.activeRequestCount--};


// Loader Class
//   :: Purpose: provides a site wide Loader Class
//   :: Required Files:
//			js.frameworks.prototype
//			js.application.controls.Utility - Browser()
//			js.application.controls.Utility - Modal()
var Loader=Class.create({initialize:function(a){this.parent=$(a);this.setElement()},open:function(){try{this.setDimensions();this.setOffset();this.parent.appendChild(this.element)}catch(err){alert(err.message())}},close:function(){try{this.element.remove()}catch(err){}},reset:function(){this.close();this.open()},setDimensions:function(){this.dimensions=this.parent.getDimensions();this.element.setStyle({'height':this.dimensions.height+'px','width':this.dimensions.width+'px'})},setElement:function(){this.element=new Element('div',{'class':'box_loader'});this.element.appendChild(this.loaderImage=new Element('div',{'class':'box_loader_image_wrapper'}));this.loaderImage.appendChild(new Element('div',{'class':'box_loader_image'}).update('Loading. Please Wait...'))},setOffset:function(){this.offset=this.parent.positionedOffset();this.element.setStyle({'top':this.offset.top+'px','left':this.offset.left+'px'});var a=((this.dimensions.height*.3)>75)?50:this.dimensions.height*.3;this.loaderImage.setStyle({'top':a+'px','left':((this.dimensions.width/2)-120)+'px'})}});


// HoverBox Class
//   :: Purpose: provides a hover box that displays pre-formatted data
//   :: Date: 
//   :: Required Files:
//         js.frameworks.prototype.*
function HoverBox(){this.boxId;this.landingDiv;this.boxdata;this.top;this.left;HoverBox.prototype.init=function(a,b,c){this.boxId=b;this.boxdata=c;this.setLandingDiv(a);this.positionBox(a);this.addToDom(this.createBoxHtml());this.createDraggable()};HoverBox.prototype.createDraggable=function(){new Draggable(this.boxId,{handle:'hd',constraint:'',snap:false,revert:false,ghosting:false,mode:'absolute'})};HoverBox.prototype.setLandingDiv=function(a){this.landingDiv=a.element().up('.geo_data').id};HoverBox.prototype.getParent=function(){return'.popup'};HoverBox.prototype.positionBox=function(a){var b=a.findElement(this.getParent());var c=b.getDimensions();var d=b.viewportOffset();var e=d.left+c.width/2;var f=d.top+c.height/2;if(a.pointerX()<e){this.left=c.width-250}else{this.left=20}this.top=100};HoverBox.prototype.addToDom=function(a){a.style.top=this.top+'px';a.style.left=this.left+'px';$(this.landingDiv).appendChild(a)};HoverBox.prototype.createBoxHtml=function(){var a=new Element('div',{'class':'hoverbox','id':this.boxId});var b=new Element('div',{'class':'hoverbox-wrapper'});var c=new Element('div',{'class':'tr'}).update('\u00a0\u00a0\u00a0\u00a0\u00a0');var d=new Element('div',{'class':'tl'}).update('\u00a0\u00a0\u00a0\u00a0\u00a0');var e=new Element('div',{'class':'br'}).update('\u00a0\u00a0\u00a0\u00a0\u00a0');var f=new Element('div',{'class':'bl'}).update('\u00a0\u00a0\u00a0\u00a0\u00a0');var g=new Element('div',{'class':'hd'}).update(this.getBoxTitle());g.style.cursor='move';var h=new Element('div',{'class':'ml'});var i=new Element('div',{'class':'mr'});var j=new Element('div',{'class':'hoverbox-content'});j.appendChild(this.getBoxContent());i.appendChild(j);i.appendChild(f);i.appendChild(e);h.appendChild(i);b.appendChild(c);b.appendChild(d);b.appendChild(g);b.appendChild(h);a.appendChild(b);return a};HoverBox.prototype.getBoxTitle=function(){return'Box Title'};HoverBox.prototype.getBoxContent=function(){return'Box Content'}}


// DataTable Class
//   :: Purpose: a table that displays pre-formatted data in a scrollable format
//   :: Date: 
//   :: Required Files:
//         js.frameworks.prototype.*
function DataTable(){this.width;this.height=400;this.tableWidth;this.columnData;DataTable.prototype.init=function(a,b,c,d){try{this.setWidth(d);this.columnData=b;$(c).appendChild(this.formatData(a))}catch(err){alert('DataTable: '+err.message)}};DataTable.prototype.setWidth=function(a){var b=new Number(a);if(b=='NaN'){throw'width is not a number';}else{this.width=b.valueOf();this.tableWidth=this.width-15}};DataTable.prototype.formatData=function(r){var a=document.createDocumentFragment();if(r.recordcount==0){var b=new Element('p').update('No data available.');a.appendChild(b)}else{a.appendChild(this.formatHeader());a.appendChild(this.formatBody(r))}return a};DataTable.prototype.formatHeader=function(){var a=new Element('table',{'width':'auto','cellpadding':'0','cellspacing':'0','border':'0','style':'padding:0 15px 0 0'});var b=new Element('tbody');var c=new Element('tr');for(var i=0;i<this.columnData.length;i++){if(i==this.columnData.length-1){var d=new Element('th',{'width':this.columnData[i].width,'align':this.columnData[i].align,'style':'0 20px 0 0'}).update(this.columnData[i].header)}else{var d=new Element('th',{'width':this.columnData[i].width,'align':this.columnData[i].align}).update(this.columnData[i].header)}c.appendChild(d)}b.appendChild(c);a.appendChild(b);return a};DataTable.prototype.formatBody=function(r){if(r.recordcount>10){var a=new Element('div',{'style':'overflow:auto;overflow-x:hidden;height:'+this.height+'px;width:'+this.width+'px'});a.appendChild(this.formatRows(r));return a}else{return this.formatRows(r)}};DataTable.prototype.formatRows=function(r){var a=new Element('table',{'width':this.tableWidth,'cellpadding':'0','cellspacing':'0','border':'0'});var b=new Element('tbody');var i;for(i=0;i<r.recordcount;i++){var c=new Element('tr',{'class':this.getRowClass(i+1)});var t;var z=this.columnData.length;for(t=0;t<z;t++){var d=this.columnData[t].name;var e=eval('r.data.'+d+'[i]');var f;if(!this.columnData[t].type){f='num'}else{f=this.columnData[t].type};if(t==z-1){var g=new Number(this.columnData[t].width).valueOf()+20;var h=new Element('td',{'width':g,'align':this.columnData[t].align,'style':'0 20px 0 0'})}else{var h=new Element('td',{'width':this.columnData[t].width,'align':this.columnData[t].align})}if(this.columnData[t].secondary){var j=this.columnData[t].secondary;var k=eval('r.data.'+j+'[i]');var l=this.formatColumn(e,f,k)}else{var l=this.formatColumn(e,f)}c.appendChild(h.update(l))}b.appendChild(c)}a.appendChild(b);return a};DataTable.prototype.formatColumn=function(a,b,c){if(b=='num'){return this.formatNum(a)}else if(b=='date'){return this.formatDate(a)}else if(b=='percent'){return this.formatPercent(a)}else if(b=='weight'){return this.formatWeight(a)}else if(b=='decimal'){return this.formatDecimal(a)}else{return a}};DataTable.prototype.formatNum=function(a){var b=new Number(a);if(b=='NaN'){return a}else{return addCommas(a)}};DataTable.prototype.formatDecimal=function(a,b){if(!b){b=1};var c=new Number(a);if(c=='NaN'){return a}else{c.toFixed(b)}tempstr=new String(c);x=tempstr.split('.');if(!x[1]){x[1]=''};if(x[1].length!=b){var d=b-x[1].length;var q;for(q=0;q<d;q++){x[1]=x[1]+'0'}};return addCommas(x[0]+'.'+x[1])};DataTable.prototype.formatPercent=function(a){return addCommas(a)+' %'};DataTable.prototype.formatWeight=function(a){return addCommas(a)+' lbs.'};DataTable.prototype.formatDate=function(a){var b;if(a.search('00:00:00')!=-1){b=convertJsonDate(a).format('m/d/yyyy')}else{b=convertJsonDate(a).format('m/d/yyyy')+' '+convertJsonDate(a).format('shortTime')}return b};DataTable.prototype.getRowClass=function(a){if(a%2==1){return''}else{return'alt'}}}


// Browser Class
var Browser=Class.create({initialize:function(){this.setBrowser();this.setBody();this.setBodyDimensions();this.setScrollDimensions();this.setScrollOffset();this.setViewportDimensions()},destroy:function(){this.destroyListeners()},listen:function(a){this.createListeners(a)},stopListening:function(){this.destroyListeners()},reInit:function(){this.initialize()},getBodyDimensions:function(){return this.bodyDimensions},getBrowser:function(){return this.browser},getBrowserName:function(){return this.browser.name},getBrowserVersion:function(){return this.browser.version},getScrollDimensions:function(){return this.scrollDimensions},getScrollHeight:function(){return this.scrollDimensions.height},getScrollWidth:function(){return this.scrollDimensions.width},getScrollOffset:function(){return this.scrollOffset},getScrollOffsetLeft:function(){return this.scrollOffset.left},getScrollOffsetTop:function(){return this.scrollOffset.top},getViewportDimensions:function(){return this.viewportDimensions},getViewportHeight:function(){return this.viewportDimensions.height},getViewportWidth:function(){return this.viewportDimensions.width},scrollElement:function(a){this.reInit()},resizeElement:function(a){this.reInit()},createListeners:function(a){if(a){this.boundResizeObserver=a.resizeElement.bindAsEventListener(a);this.boundScrollObserver=a.scrollElement.bindAsEventListener(a)}else{this.boundResizeObserver=this.resizeElement.bindAsEventListener(this);this.boundScrollObserver=this.scrollElement.bindAsEventListener(this)}Event.observe(window,'resize',this.boundResizeObserver);Event.observe(window,'scroll',this.boundScrollObserver)},destroyListeners:function(){Event.stopObserving(window,'resize',this.boundResizeObserver);Event.stopObserving(window,'scroll',this.boundScrollObserver)},setBody:function(){if(this.browser.name=="IE"){var a=document.body.id;a=(a.length>0)?a:this.rand();document.body.id=a;this.bodyElement=$(a)}else{this.bodyElement=document.body}},setBodyDimensions:function(){this.bodyDimensions=new Object();if(this.browser.name=="IE"){this.bodyDimensions.height=document.body.scrollHeight+20;this.bodyDimensions.width=document.body.scrollWidth+20}else{this.bodyDimensions.height=document.documentElement.getHeight();this.bodyDimensions.width=document.documentElement.getWidth()}},setBrowser:function(){this.browser={};for(browser in Prototype.Browser){if(Prototype.Browser[browser]){this.browser.name=browser.toUpperCase();break}}var a=navigator.userAgent;var b,indexSpace,version;if(a.indexOf("Chrome/")>-1){b=a.indexOf("Chrome/")+7;version=a.substr(b);indexSpace=version.indexOf(" ");this.browser.version=version.substr(0,indexSpace)}else if(a.indexOf("MSIE ")>-1){b=a.indexOf("MSIE ")+5;version=a.substr(b);indexSpace=version.indexOf(" ")-1;this.browser.version=version.substr(0,indexSpace)}else if(a.indexOf("Firefox/")>-1){b=a.indexOf("Firefox/");version=a.substr(b);version=version.split("/");this.browser.version=version[1]}else if(a.indexOf("Version/")>-1){b=a.indexOf("Version/")+8;version=a.substr(b);indexSpace=version.indexOf(" ");this.browser.version=version.substr(0,indexSpace)}},setScrollDimensions:function(){this.scrollDimensions=new Object();this.scrollDimensions.height=document.body.scrollHeight+20;this.scrollDimensions.width=document.body.scrollWidth+20},setScrollOffset:function(){this.scrollOffset=(this.parent)?this.parent.cumulativeScrollOffset():this.bodyElement.cumulativeScrollOffset()},setViewportDimensions:function(){this.viewportDimensions=new Object();if(this.browser.name=="IE"){this.viewportDimensions.height=document.documentElement.clientHeight;this.viewportDimensions.width=document.documentElement.clientWidth}else{this.viewportDimensions.height=window.innerHeight;this.viewportDimensions.width=window.innerWidth}},rand:function(){return'body_'+Math.floor(Math.random()*11)}});

// Modal Class
var Modal=Class.create({initialize:function(a,b){this.browserObj=new Browser();this.browser=this.browserObj.getBrowser();this.modalOpen=false;this.setSettings(b);this.setBody();this.setModalWrapper();this.setElement();if(a)this.setContent(a)},openBox:function(){if(!this.modalWrapper.visible()){if(this.modalOpen){this.setElement();this.setContent(this.storeContent)}this.browserObj.reInit();if(this.settings.keepcenter)this.browserObj.listen(this);this.setDimensions();if(this.settings.dropzone=="body"){this.bodyElement.insert({bottom:this.modalWrapper})}else{$(this.settings.dropzone).insert({bottom:this.modalWrapper})}this.modalWrapper.show();this.setOffset();this.modalOpen=true}try{$('content').hideSelects()}catch(err){}},closeBox:function(){this.modalWrapper.hide();this.modalWrapper.remove();this.element.remove();this.destroy();try{if(this.settings.showselects)$('content').showSelects()}catch(err){}},destroy:function(){this.browserObj.destroy();if(this.settings.showclose)this.closeButton.stopObserving('click')},isOpen:function(){return this.modalWrapper.visible()},resizeElement:function(a){this.browserObj.reInit();this.setDimensions();this.setOffset()},scrollElement:function(a){this.browserObj.reInit();this.setDimensions();this.setOffset()},createButtons:function(){var a=new Element('div');var b=new Element('a',{'href':'javascript:void(0)','class':'modal_button'}).update('<span>&nbsp;</span>Ok');b.observe('click',this.closeBox.bindAsEventListener(this,true));a.appendChild(b);a.appendChild(new Element('br',{'class':'clear'}));return a},setBody:function(){this.bodyElement=(this.browser.name=="IE")?this.setIEBody():document.body},setIEBody:function(){var a=document.body.id;a=(a.length>0)?a:this.rand();document.body.id=a;return $(a)},setContent:function(a){this.content=new Element('div',{'class':this.settings.modal_content_class});this.content.appendChild(a);if(this.settings.showclose){this.closeButton=new Element('a',{'href':'javascript:void(0)','class':this.settings.modal_close_class+' modal_png_hack'}).update('close');this.closeButton.observe('click',this.closeBox.bindAsEventListener(this));this.content.appendChild(this.closeButton)}if(this.settings.showbutton){this.content.appendChild(this.createButtons())}this.element.appendChild(this.content);this.storeContent=a},setDimensions:function(){if(this.settings.blockbackground){var a=this.browserObj.getBodyDimensions();var b=this.browserObj.getViewportDimensions();var c=(a.height>b.height)?a.height:a.height+(b.height-a.height);var d=(a.width>b.width)?a.width+(b.width):a.width;this.modalWrapper.style.height=c+'px';this.modalWrapper.style.width=d+'px'}},setElement:function(){this.element=new Element('div',{'class':this.settings.modal_class+' modal_png_hack'});if(this.settings.width!='auto'){this.element.setStyle({'width':this.settings.width})}else{this.element.style.whiteSpace='nowrap'}this.modalWrapper.appendChild(this.element);this.element.style.zIndex=10000},setModalWrapper:function(){this.modalWrapper=new Element('div',{'class':this.settings.modal_bg_class+' modal_png_hack','style':'display:none'})},setOffset:function(){var a=this.element.getWidth();var b=this.element.getHeight();var c=this.browserObj.getScrollOffsetTop();var d=this.browserObj.getScrollOffsetLeft();var e=Math.round(((this.browserObj.getViewportHeight()/2)-(b/2)+c),0);var f=Math.round(((this.browserObj.getViewportWidth()/2)-(a/2)+d),0);this.element.style.top=e+'px';this.element.style.left=f+'px'},setSettings:function(a){var b=this.defaultSettings();this.settings=new Object();if(a){for(prop in b){this.settings[prop]=(Object.isUndefined(a[prop]))?b[prop]:a[prop]}}else{this.settings=b}},defaultSettings:function(){return{'dropzone':'body','blockbackground':false,'clicktoclose':true,'keepcenter':true,'modal_class':'modal_box','modal_bg_class':'modal_bg','modal_close_class':'modal_box_close','modal_content_class':'modal_box_content','showclose':true,'showbutton':false,'showselects':true,'width':'auto'}},rand:function(){return'modal_'+Math.floor(Math.random()*11)}});

// Modal.Alert Class

Modal.Alert=Class.create(Modal,{createButtons:function(){var a=new Element('div');var b=new Element('a',{'href':'javascript:void(0)','class':'modal_button'}).update('<span>&nbsp;</span>OK');b.observe('click',this.closeBox.bindAsEventListener(this));a.appendChild(b);return a},setContent:function(a){this.content=new Element('div',{'class':this.settings.modal_content_class+' '+this.settings.modal_alert_class});if(typeof a!="object")a=new Element('div').update(a);this.content.appendChild(a);this.content.appendChild(this.createButtons());if(this.settings.showclose){this.closeButton=new Element('a',{'href':'javascript:void(0)','class':this.settings.modal_close_class+' modal_png_hack'}).update('close');this.closeButton.observe('click',this.closeBox.bindAsEventListener(this));this.content.appendChild(this.closeButton)}this.content.appendChild(new Element('br',{'style':'clear:both'}));this.element.appendChild(this.content);this.element.style.zIndex=this.settings.z_index;this.storeContent=a},defaultSettings:function(){return{'dropzone':'body','blockbackground':false,'clicktoclose':false,'keepcenter':true,'modal_class':'modal_box','modal_bg_class':'modal_bg','modal_alert_class':'modal_alert','modal_close_class':'modal_box_close','modal_content_class':'modal_box_content','showclose':true,'showselects':true,'width':'300px','z_index':10000}}});


// Modal.Confirm

Modal.Confirm=Class.create(Modal,{initialize:function($super,content,settings,callback){$super(content,settings);this.callback=callback},closeBox:function(event,reply){this.modalWrapper.remove();this.element.remove();this.destroy();if(this.callback){this.callback(reply)}try{$('content').showSelects()}catch(err){}Event.stop(event)},destroy:function(){this.browserObj.destroy();if(this.settings.showclose){this.closeButton.stopObserving('click')}},createButtons:function(){var buttons=new Element('div');var okButton=new Element('a',{'href':'javascript:void(0)','class':'modal_button'}).update('<span>&nbsp;</span>Yes');okButton.observe('click',this.closeBox.bindAsEventListener(this,true));buttons.appendChild(okButton);var cancelButton=new Element('a',{'href':'javascript:void(0)','class':'modal_button'}).update('<span>&nbsp;</span>No');cancelButton.observe('click',this.closeBox.bindAsEventListener(this,false));buttons.appendChild(cancelButton);return buttons},setContent:function(content){this.content=new Element('div',{'class':this.settings.modal_content_class+' '+this.settings.modal_confirm_class});if(typeof content!="object"){content=new Element('div').update(content)}this.content.appendChild(content);this.content.appendChild(this.createButtons());if(this.settings.showclose){this.closeButton=new Element('a',{'href':'javascript:void(0)','class':this.settings.modal_close_class+' modal_png_hack'}).update('close');this.closeButton.observe('click',this.closeBox.bindAsEventListener(this));this.content.appendChild(this.closeButton)}this.content.appendChild(new Element('br',{'style':'clear:both'}));this.element.appendChild(this.content);this.storeContent=content},defaultSettings:function(){return{'dropzone':'body','blockbackground':true,'clicktoclose':false,'keepcenter':true,'modal_class':'modal_box','modal_bg_class':'modal_bg','modal_confirm_class':'modal_confirm','modal_close_class':'modal_box_close','modal_content_class':'modal_box_content','showclose':false,'width':'300px'}}});


// Modal.Info

Modal.Info = Class.create(Modal,{

	defaultSettings: function(){
		return {
			'dropzone':'body',
			'blockbackground':true,
			'clicktoclose':true,
			'keepcenter':true,
			'modal_class':'modal_box',
			'modal_bg_class':'modal_bg',
			'modal_close_class':'modal_box_close',
			'modal_content_class':'modal_box_content',
			'showclose':true,
			'showbutton':false,
			'showselects':true,
			'width':'auto'
		}
	}

});


function fixedEncodeURIComponent (str) {  
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');  
}

// Date Functions

Date.prototype.convertTo12=function(h){if(h>12){h-=12}else if(h==0){h=12}return h};

Date.prototype.toMaskString=function(a){var b='';var c=Date.maskReplace;for(var i=0,len=a.length;i<len;i++){var d=a.charAt(i);if(c[d]){b+=c[d].call(this)}else{b+=d}}return b};

Date.maskReplace={m:function(){return this.getMonth()+1},M:function(){return((this.getMonth()+1)<10)?'0'+(this.getMonth()+1):this.getMonth()+1},d:function(){return this.getDate()},D:function(){return(this.getDate()<10?'0':'')+this.getDate()},y:function(){return this.getFullYear().toString().substring(2,4)},Y:function(){return this.getFullYear()},h:function(){return this.convertTo12(this.getHours())},H:function(){var h=this.convertTo12(this.getHours());return(h<10)?'0'+h:h},z:function(){var h=this.getHours();return(h<10)?'0'+h:h},i:function(){return this.getMinutes()},I:function(){return(this.getMinutes()<10)?'0'+this.getMinutes():this.getMinutes()},P:function(){return(this.getHours()<12)?'AM':'PM'}};

/*
	Date Format 1.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT license
	With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat=function(){var f=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,timezoneClip=/[^-+\dA-Z]/g,pad=function(a,b){a=String(a);b=parseInt(b)||2;while(a.length<b)a="0"+a;return a};return function(b,c){if(arguments.length==1&&(typeof b=="string"||b instanceof String)&&!/\d/.test(b)){c=b;b=undefined}b=b?new Date(b):new Date();if(isNaN(b))throw"invalid date";var e=dateFormat;c=String(e.masks[c]||c||e.masks["default"]);var d=b.getDate(),D=b.getDay(),m=b.getMonth(),y=b.getFullYear(),H=b.getHours(),M=b.getMinutes(),s=b.getSeconds(),L=b.getMilliseconds(),o=b.getTimezoneOffset(),flags={d:d,dd:pad(d),ddd:e.i18n.dayNames[D],dddd:e.i18n.dayNames[D+7],m:m+1,mm:pad(m+1),mmm:e.i18n.monthNames[m],mmmm:e.i18n.monthNames[m+12],yy:String(y).slice(2),yyyy:y,h:H%12||12,hh:pad(H%12||12),H:H,HH:pad(H),M:M,MM:pad(M),s:s,ss:pad(s),l:pad(L,3),L:pad(L>99?Math.round(L/10):L),t:H<12?"a":"p",tt:H<12?"am":"pm",T:H<12?"A":"P",TT:H<12?"AM":"PM",Z:(String(b).match(timezone)||[""]).pop().replace(timezoneClip,""),o:(o>0?"-":"+")+pad(Math.floor(Math.abs(o)/60)*100+Math.abs(o)%60,4)};return c.replace(f,function(a){return(a in flags)?flags[a]:a.slice(1,a.length-1)})}}();

// Some common format strings
dateFormat.masks={"default":"ddd mmm d yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoFullDateTime:"yyyy-mm-dd'T'HH:MM:ss.lo"};

// Internationalization strings
dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thr","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]};

// For convenience...
Date.prototype.format=function(a){return dateFormat(this,a)}

function convertJsonDate(a){var b=a.substr(0,10).split('-'),c=a.substr(11,8).split(':');if(b.length!=3&&c.length!=3){ throw('Not a JSON formatted date'); };return new Date(b[0],b[1]-1,b[2],c[0],c[1],c[2]);}

function addCommas(a){a+='';x=a.split('.');x1=x[0];x2=x.length>1?'.'+x[1]:'';var b=/(\d+)(\d{3})/;while(b.test(x1)){x1=x1.replace(b,'$1'+','+'$2')}return x1+x2}

function expand(a){var b;b=document.getElementById(a).style;if(b.display=="none"){b.display="block"}else{b.display="none"}return}

function checkUncheckAll(a){var b=a.form,z=0;for(z=0;z<b.length;z++){if(b[z].type=='checkbox'&&b[z].name!='checkall'){b[z].checked=a.checked}}}

function getViewportDimensions(){var a=0,intW=0;if(self.innerHeight){a=window.innerHeight;intW=window.innerWidth}else{if(document.documentElement&&document.documentElement.clientHeight){a=document.documentElement.clientHeight;intW=document.documentElement.clientWidth}else{if(document.body){a=document.body.clientHeight;intW=document.body.clientWidth}}}return{height:parseInt(a,10),width:parseInt(intW,10)}}

function rand(a,b){var c=arguments.length;if(c==0){a=0;b=2147483647}else if(c==1){throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');}return Math.floor(Math.random()*(b-a+1))+a}

function getCheckedValue(a){var b=a.length;var c;for(var i=0;i<b;i++){if(a[i].checked==true){c=a[i].value}}return c}

var IEVersion=function(){var a=999;if(navigator.appVersion.indexOf("MSIE")!=-1)a=parseFloat(navigator.appVersion.split("MSIE")[1]);return a}

Element.addMethods({hideSelects:function(b){try{if(Prototype.Browser.IE&&IEVersion()<7){b.select('select').each(function(a){a.hide()})}}catch(err){}},showSelects:function(b){try{if(Prototype.Browser.IE&&IEVersion()<7){b.select('select').each(function(a){a.show()})}}catch(err){}}});

// Cookie Functions

/**
 * Author : Lalit Patel
 * Website: http://www.lalit.org/lab/jsoncookies
 * License: Apache Software License 2
 *          http://www.apache.org/licenses/LICENSE-2.0
 * Version: 0.5
 * Updated: Jan 26, 2009 
 */

var CookieJar = Class.create();

CookieJar.prototype = {

	/**
	 * Append before all cookie names to differntiate them.
	 */
	appendString: "_PORTAL_",

	/**
	 * Initializes the cookie jar with the options.
	 */
	initialize: function(options) {
		this.options = {
			expires: 3600,		// seconds (1 hr)
			path: '',			// cookie path
			domain: '',			// cookie domain
			secure: ''			// secure ?
		};
		Object.extend(this.options, options || {});

		if (this.options.expires != '') {
			var date = new Date();
				date = new Date(date.getTime() + (this.options.expires * 1000));
			this.options.expires = '; expires=' + date.toGMTString();
		}
		if (this.options.path != '') {
			this.options.path = '; path=' + escape(this.options.path);
		}
		if (this.options.domain != '') {
			this.options.domain = '; domain=' + escape(this.options.domain);
		}
		if (this.options.secure == 'secure') {
			this.options.secure = '; secure';
		} else {
			this.options.secure = '';
		}
	},

	/**
	 * Adds a name values pair.
	 */
	put: function(name, value) {
		name = this.appendString + name;
		cookie = this.options;
		var type = typeof value;
		switch(type) {
		  case 'undefined':
		  case 'function' :
		  case 'unknown'  : return false;
		  case 'boolean'  : 
		  case 'string'   : 
		  case 'number'   : value = value.toString();
		}
		var cookie_str = name + "=" + escape(Object.toJSON(value));
		try {
			document.cookie = cookie_str + cookie.expires + cookie.path + cookie.domain + cookie.secure;
		} catch (e) {
			return false;
		}
		return true;
	},

	/**
	 * Removes a particular cookie (name value pair) form the Cookie Jar.
	 */
	remove: function(name) {
		name = this.appendString + name;
		cookie = this.options;
		try {
			var date = new Date();
			date.setTime(date.getTime() - (3600 * 1000));
			var expires = '; expires=' + date.toGMTString();
			document.cookie = name + "=" + expires + cookie.path + cookie.domain + cookie.secure;
		} catch (e) {
			return false;
		}
		return true;
	},

	/**
	 * Return a particular cookie by name;
	 */
	get: function(name) {
		name = this.appendString + name;
		var cookies = document.cookie.match(name + '=(.*?)(;|$)');
		if (cookies) {
			return (unescape(cookies[1])).evalJSON();
		} else {
			return null;
		}
	},

	/**
	 * Empties the Cookie Jar. Deletes all the cookies.
	 */
	empty: function() {
		keys = this.getKeys();
		size = keys.size();
		for(i=0; i<size; i++) {
			this.remove(keys[i]);
		}
	},

	/**
	 * Returns all cookies as a single object
	 */
	getPack: function() {
		pack = {};
		keys = this.getKeys();

		size = keys.size();
		for(i=0; i<size; i++) {
			pack[keys[i]] = this.get(keys[i]);
		}
		return pack;
	},

	/**
	 * Returns all keys.
	 */
	getKeys: function() {
		keys = $A();
		keyRe= /[^=; ]+(?=\=)/g;
		str  = document.cookie;
		CJRe = new RegExp("^" + this.appendString);
		while((match = keyRe.exec(str)) != undefined) {
			if (CJRe.test(match[0].strip())) {
				keys.push(match[0].strip().gsub("^" + this.appendString,""));
			}
		}
		return keys;
	}
};



// String Functions

String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,""); }