//<![CDATA[
/* Mootools Class Occlude */
//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.
MooTools.More={version:"1.2.3.1"};Class.refactor=function(b,a){$each(a,function(e,d){var c=b.prototype[d];if(c&&(c=c._origin)&&typeof e=="function"){b.implement(d,function(){var f=this.previous;
this.previous=c;var g=e.apply(this,arguments);this.previous=f;return g;});}else{b.implement(d,e);}});return b;};Class.Mutators.Binds=function(a){return a;
};Class.Mutators.initialize=function(a){return function(){$splat(this.Binds).each(function(b){var c=this[b];if(c){this[b]=c.bind(this);}},this);return a.apply(this,arguments);
};};Class.Occlude=new Class({occlude:function(c,b){b=document.id(b||this.element);var a=b.retrieve(c||this.property);if(a&&!$defined(this.occluded)){this.occluded=a;
}else{this.occluded=false;b.store(c||this.property,this);}return this.occluded;}});Element.implement({tidy:function(){this.set("value",this.get("value").tidy());
},getTextInRange:function(b,a){return this.get("value").substring(b,a);},getSelectedText:function(){if(this.setSelectionRange){return this.getTextInRange(this.getSelectionStart(),this.getSelectionEnd());
}return document.selection.createRange().text;},getSelectedRange:function(){if($defined(this.selectionStart)){return{start:this.selectionStart,end:this.selectionEnd};
}var e={start:0,end:0};var a=this.getDocument().selection.createRange();if(!a||a.parentElement()!=this){return e;}var c=a.duplicate();if(this.type=="text"){e.start=0-c.moveStart("character",-100000);
e.end=e.start+a.text.length;}else{var b=this.get("value");var d=b.length-b.match(/[\n\r]*$/)[0].length;c.moveToElementText(this);c.setEndPoint("StartToEnd",a);
e.end=d-c.text.length;c.setEndPoint("StartToStart",a);e.start=d-c.text.length;}return e;},getSelectionStart:function(){return this.getSelectedRange().start;
},getSelectionEnd:function(){return this.getSelectedRange().end;},setCaretPosition:function(a){if(a=="end"){a=this.get("value").length;}this.selectRange(a,a);
return this;},getCaretPosition:function(){return this.getSelectedRange().start;},selectRange:function(e,a){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,a);
}else{var c=this.get("value");var d=c.substr(e,a-e).replace(/\r/g,"").length;e=c.substr(0,e).replace(/\r/g,"").length;var b=this.createTextRange();b.collapse(true);
b.moveEnd("character",e+d);b.moveStart("character",e);b.select();}return this;},insertAtCursor:function(b,a){var d=this.getSelectedRange();var c=this.get("value");
this.set("value",c.substring(0,d.start)+b+c.substring(d.end,c.length));if($pick(a,true)){this.selectRange(d.start,d.start+b.length);}else{this.setCaretPosition(d.start+b.length);
}return this;},insertAroundCursor:function(b,a){b=$extend({before:"",defaultMiddle:"",after:""},b);var c=this.getSelectedText()||b.defaultMiddle;var g=this.getSelectedRange();
var f=this.get("value");if(g.start==g.end){this.set("value",f.substring(0,g.start)+b.before+c+b.after+f.substring(g.end,f.length));this.selectRange(g.start+b.before.length,g.end+b.before.length+c.length);
}else{var d=f.substring(g.start,g.end);this.set("value",f.substring(0,g.start)+b.before+d+b.after+f.substring(g.end,f.length));var e=g.start+b.before.length;
if($pick(a,true)){this.selectRange(e,e+d.length);}else{this.setCaretPosition(e+f.length);}}return this;}});Element.implement({measure:function(e){var g=function(h){return !!(!h||h.offsetHeight||h.offsetWidth);
};if(g(this)){return e.apply(this);}var d=this.getParent(),b=[],f=[];while(!g(d)&&d!=document.body){b.push(d.expose());d=d.getParent();}var c=this.expose();
var a=e.apply(this);c();b.each(function(h){h();});return a;},expose:function(){if(this.getStyle("display")!="none"){return $empty;}var a=this.style.cssText;
this.setStyles({display:"block",position:"absolute",visibility:"hidden"});return function(){this.style.cssText=a;}.bind(this);},getDimensions:function(a){a=$merge({computeSize:false},a);
var d={};var c=function(f,e){return(e.computeSize)?f.getComputedSize(e):f.getSize();};if(this.getStyle("display")=="none"){d=this.measure(function(){return c(this,a);
});}else{try{d=c(this,a);}catch(b){}}return $chk(d.x)?$extend(d,{width:d.x,height:d.y}):$extend(d,{x:d.width,y:d.height});},getComputedSize:function(a){a=$merge({styles:["padding","border"],plains:{height:["top","bottom"],width:["left","right"]},mode:"both"},a);
var c={width:0,height:0};switch(a.mode){case"vertical":delete c.width;delete a.plains.width;break;case"horizontal":delete c.height;delete a.plains.height;
break;}var b=[];$each(a.plains,function(g,f){g.each(function(h){a.styles.each(function(i){b.push((i=="border")?i+"-"+h+"-width":i+"-"+h);});});});var e={};
b.each(function(f){e[f]=this.getComputedStyle(f);},this);var d=[];$each(a.plains,function(g,f){var h=f.capitalize();c["total"+h]=0;c["computed"+h]=0;g.each(function(i){c["computed"+i.capitalize()]=0;
b.each(function(k,j){if(k.test(i)){e[k]=e[k].toInt()||0;c["total"+h]=c["total"+h]+e[k];c["computed"+i.capitalize()]=c["computed"+i.capitalize()]+e[k];}if(k.test(i)&&f!=k&&(k.test("border")||k.test("padding"))&&!d.contains(k)){d.push(k);
c["computed"+h]=c["computed"+h]-e[k];}});});});["Width","Height"].each(function(g){var f=g.toLowerCase();if(!$chk(c[f])){return;}c[f]=c[f]+this["offset"+g]+c["computed"+g];
c["total"+g]=c[f]+c["total"+g];delete c["computed"+g];},this);return $extend(e,c);}});(function(){var a=Element.prototype.position;Element.implement({position:function(r){if(r&&($defined(r.x)||$defined(r.y))){return a?a.apply(this,arguments):this;
}$each(r||{},function(t,s){if(!$defined(t)){delete r[s];}});r=$merge({relativeTo:document.body,position:{x:"center",y:"center"},edge:false,offset:{x:0,y:0},returnPos:false,relFixedPosition:false,ignoreMargins:false,allowNegative:false},r);
var b={x:0,y:0};var h=false;var c=this.measure(function(){return document.id(this.getOffsetParent());});if(c&&c!=this.getDocument().body){b=c.measure(function(){return this.getPosition();
});h=true;r.offset.x=r.offset.x-b.x;r.offset.y=r.offset.y-b.y;}var q=function(s){if($type(s)!="string"){return s;}s=s.toLowerCase();var t={};if(s.test("left")){t.x="left";
}else{if(s.test("right")){t.x="right";}else{t.x="center";}}if(s.test("upper")||s.test("top")){t.y="top";}else{if(s.test("bottom")){t.y="bottom";}else{t.y="center";
}}return t;};r.edge=q(r.edge);r.position=q(r.position);if(!r.edge){if(r.position.x=="center"&&r.position.y=="center"){r.edge={x:"center",y:"center"};}else{r.edge={x:"left",y:"top"};
}}this.setStyle("position","absolute");var p=document.id(r.relativeTo)||document.body;var i=p==document.body?window.getScroll():p.getPosition();var o=i.y;
var g=i.x;if(Browser.Engine.trident){var l=p.getScrolls();o+=l.y;g+=l.x;}var j=this.getDimensions({computeSize:true,styles:["padding","border","margin"]});
if(r.ignoreMargins){r.offset.x=r.offset.x-j["margin-left"];r.offset.y=r.offset.y-j["margin-top"];}var n={};var d=r.offset.y;var e=r.offset.x;var k=window.getSize();
switch(r.position.x){case"left":n.x=g+e;break;case"right":n.x=g+e+p.offsetWidth;break;default:n.x=g+((p==document.body?k.x:p.offsetWidth)/2)+e;break;}switch(r.position.y){case"top":n.y=o+d;
break;case"bottom":n.y=o+d+p.offsetHeight;break;default:n.y=o+((p==document.body?k.y:p.offsetHeight)/2)+d;break;}if(r.edge){var m={};switch(r.edge.x){case"left":m.x=0;
break;case"right":m.x=-j.x-j.computedRight-j.computedLeft;break;default:m.x=-(j.x/2);break;}switch(r.edge.y){case"top":m.y=0;break;case"bottom":m.y=-j.y-j.computedTop-j.computedBottom;
break;default:m.y=-(j.y/2);break;}n.x=n.x+m.x;n.y=n.y+m.y;}n={left:((n.x>=0||h||r.allowNegative)?n.x:0).toInt(),top:((n.y>=0||h||r.allowNegative)?n.y:0).toInt()};
if(p.getStyle("position")=="fixed"||r.relFixedPosition){var f=window.getScroll();n.top=n.top.toInt()+f.y;n.left=n.left.toInt()+f.x;}if(r.returnPos){return n;
}else{this.setStyles(n);}return this;}});})();Element.implement({isDisplayed:function(){return this.getStyle("display")!="none";},toggle:function(){return this[this.isDisplayed()?"hide":"show"]();
},hide:function(){var b;try{if("none"!=this.getStyle("display")){b=this.getStyle("display");}}catch(a){}return this.store("originalDisplay",b||"block").setStyle("display","none");
},show:function(a){return this.setStyle("display",a||this.retrieve("originalDisplay")||"block");},swapClass:function(a,b){return this.removeClass(a).addClass(b);
}});
/* ApplicationGUI (still needed for public site?) */
//eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('8 V=F 1d({1e:{},\'1f\':1g,\'1h\':0,1i:k(){},1j:k(a){6(a.j!=""){a.p(\'1k-1l\')}},1m:k(a,b,c){8 d=(c||$(a).h(\'n\')==\'q\'?\'W\':\'q\');$(a).G(\'n\',d);$(b).G(\'X\',(d==\'q\'?\'Y\':\'10\'))},1n:k(a,b,c,d){8 e=($r(d)?\' \'+d:\'\');8 f=(c||!$(a).1o(\'t\')?\'t\':\'\');$(a).1p((!c||f==\'\'?\'t\':\'\'),f);$(b).G(\'X\',(f==\'t\'?\'Y\'+e:\'10\'+e))},1q:k(a,b){6($(a)&&$(a).1r==\'1s\'&&$(b).h(\'n\')==\'H\'){8 c=$(b).I;8 d=$$(\'#\'+a+\' 1t[n=H]\');11(8 i=0;i<d.J;i++){6(d[i].h(\'n\')==\'H\'&&(d[i].h(\'l\')).u(/^\\w+?K\\w+?K\\w+?$/)){d[i].I=c;8 e=d[i].h(\'l\').L(/12/,\'13\');6($(e)){(c?$(e).M(\'v\'):$(e).p(\'v\'))}}}}},1u:k(a){8 b=($(a).h(\'l\')).L(/12/,\'13\');(a.I?$(b).M(\'v\'):$(b).p(\'v\'))},\'N\':[\'14\',\'15\'],\'O\':[\'16\',\'P\'],1v:k(a,b){8 c=o;8 d=$(a).1w;11(8 i=0;i<d.J;i++){8 e=d[i];6($(e).h(\'y\')){8 f=$(e).h(\'y\');6($(e).h(\'j\')!=\'\'&&f.1x()!=\'P\'){6(c.N.z(f)){c.Q($(e),f)}R 6(c.O.z(f)){c.S($(e),f)}}6(c.N.z(f)){$(e).17(\'18\',k(){c.Q(o,o.19(\'y\'))})}R 6(c.O.z(f)){$(e).17(\'18\',k(){c.S(o,o.19(\'y\'))})}}6(b&&$(e).h(\'n\')&&($(e).h(\'n\')).u(/W|q/i)){F 1y($(e).h(\'l\'))}}},Q:k(a,b,c){6($(a)&&$r(b)){8 d=$(a);1a(b){B\'14\':6(d.j.J>=7){d.j.u(/(\\d{1})?\\D?(\\d{3})?\\D?(\\d{3})\\D?(\\d{4})(\\s?x\\s?\\d+)?$/);d.j=(m.$1!=\'\'?m.$1+\'.\':\'\')+(m.$2!=\'\'?m.$2+\'.\':\'\')+m.$3+\'.\'+m.$4+($r(m.$5)?m.$5:\'\')}C;B\'15\':d.j=(d.j.T()==\'\'?0:d.j);d.j=d.j.L(/[^\\d|\\.]/g,\'\');8 e=d.j.1z();6(!1A(e)){d.j=e.1B(2)}C}}},S:k(a,b){8 c=1C;6($(a)&&$r(b)){8 d=$(a);1a(b){B\'16\':6(d.j.T()!=\'\'&&!d.j.u(/\\b[A-1b-9.K%-]+@[A-1b-9.-]+\\.[A-Z]{2,4}\\b/i)){c=U}C;B\'P\':6(d.j.T()==\'\'){c=U}C}6(c===U){d.1D(\'#1E\',\'#1F\');6($(d.h(\'l\')+\'E\')){$(d.h(\'l\')+\'E\').M(\'1c\')}}R{6($(d.h(\'l\')+\'E\')){$(d.h(\'l\')+\'E\').p(\'1c\')}}}1G c}});8 1H=F V();',62,106,'||||||if||var|||||||||get||value|function|id|RegExp|type|this|removeClass|password|defined||none|match|selected|||format|contains||case|break||_label|new|set|checkbox|checked|length|_|replace|addClass|formats|tests|required|format_field|else|test_field|trim|false|ApplicationGUI|text|html|Show||Hide|for|_cb|_row|phone|currency|email|addEvent|blur|getAttribute|switch|Z0|red|Class|options|tab_index|500|dialogs|initialize|unerror_field|login|error|unhide_field|unhide_element|hasClass|swapClass|cb_checkall|tagName|FORM|input|cb_checkone|format_form|elements|toLowerCase|DataInput|toFloat|isNaN|toFixed|true|highlight|E64D4D|fff|return|appGui'.split('|'),0,{}));
/* DataInput */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('e u=v w({D:[E,F,w.G],H:[\'k\',\'l\',\'m\',\'n\',\'g\'],4:{\'7\':\'x-h\',\'6\':\'I\',\'y\':\'\'},3:J,K:\'L\',M:\'1.0.0\',N:8(a,b){5($o(a)==\'z\'&&!$O(b)){b=a;a=a[\'p\'];P b[\'p\']}2.3=$(a);5(2.A()){Q 2.A}2.R((b||{\'y\':2.3.f}));2.3.S({\'B\':2.k,\'T\':2.l,\'U\':2.m,\'V\':2.n,\'g\':2.g});2.3.C(2.4.6)},k:8(){5(2.3.9(\'q\')==\'x\'){e a=2.3.9(\'c\');e b=2.3.f;2.3.C(2.4.7);5(a!=b||(a==\'\'&&b==\'\')){2.3.h();2.3.r(2.4.6)}s{2.3.W(0,0)}}},l:8(){5(2.3.9(\'q\')==\'h\'){5(2.3.9(\'c\')==\'\'||2.4.X==0){5(2.3.9(\'q\')==\'h\'){2.3.4[0].Y=Z}2.3.j(2.4.7,2.4.6)}s{2.3.r(2.4.6)}}},m:8(){5(2.3.9(\'c\')==\'\'){2.3.t(\'c\',2.3.f);2.3.j(2.4.7,2.4.6)}s{2.3.r(2.4.7)}},n:8(){5(2.3.9(\'c\')==2.3.f){2.3.j(2.4.6,2.4.7);2.3.t(\'c\',\'\')}},g:8(){2.3.t(\'c\',2.3.f);2.3.j(2.4.7,2.4.6);2.3.B()}});e 10=8(){11(e i=0;i<d.12;i++){v u(($o(d[i])==\'3\'?d[i]:($o(d[i])==\'z\'?$(d[i][\'p\']):$(d[i]))))}};',62,65,'||this|element|options|if|offClass|onClass|function|get|||value|arguments|var|defaultValue|datareset|select||swapClass|focused|changed|blured|keydowned|type|elem|tag|removeClass|else|set|DataInput|new|Class|input|message|object|occlude|focus|addClass|Implements|Options|Events|Occlude|Binds|gray|null|property|MavInputHint|version|initialize|defined|delete|return|setOptions|addEvents|change|blur|keydown|selectRange|selectedIndex|selected|true|create_data_inputs|for|length'.split('|'),0,{}));
/* MavDialog */
var MavDialog = new Class({
	Implements: [Options, Events],
	Binds: ['clickClose', 'show'],
	options: {
		'autoShow': true,
		'buttons': null,
		'cancel': null,
		'cancelAutoClose': true,
		'cancelClass': 'cancel-button',
		'cancelImageClass': 'dialog-image-button',
		'cancelText': 'Cancel',
		'cancelDestroy': true,
		'callback': null,
		'center': true,
		'clickCloses': false,
		'defaultButtons': true,
		'dialogClass': 'mav-dialog',
		'draggable': false,
		'fxOptions': {},
		'footer': null,
		'footerClass': 'mav-dialog-footer',
		'force': false,
		'height': 'auto',
		'loadingMessage': 'loading...',
		'message': null,
		'messageAreaClass': 'mav-dialog-message',
		'messageBoxClass': 'mid-float-box',
		'noTitleClass': 'mav-no-title',
		'noFooterClass': 'mav-no-footer',
		'ok': null,
		'okAutoClose': true,
		'okClass': 'ok-button',
		'okImageClass': 'dialog-image-button',
		'okText': 'OK',
		'okDestroy': true,
		'parent': null,
		'requestQuery': '',
		'shadeClass': 'mavdialog-shade',
		'styles': {},
		'title': null,
		'titleBarClass': 'mav-dialog-title',
		'titleClose': true,
		'titleCloseClass': 'mav-icon-button md-closer',
		'titleCloseTitle': 'Close Dialog',
		'titleTextClass': 'md-title-text',
		'url': null,
		'useFx': true,
		'width': '400'
/*		,'onComplete': $empty(),
		'onClose': $empty(),
		'onHide': $empty(),
		'onRequest': $empty(),
		'onShow': $empty()*/
	},

	/*'delayedShow': false,
	'dialog': null,
	'drag': null,
	'footer': null,
	'fx': null,
	'grabbed': null,
	'grabbedHide': null,
	'message': null,
	'parent': null,
	'request': null,
	'tabIdx': 0,
	'titlebar': null,*/

	initialize: function(_opts) {
		this.setOptions(_opts);
		var dialogNum = Math.ceil(Math.random() * 10000);
		this.dialogId = 'mavd' + dialogNum + '_dialog';

		if ($(this.dialogId + '_dialog')) { return null; }

		this.request = new Request({
			'url': '',
			'onSuccess': this.urlRequest.bind(this),
			'onFailure': this.errorMessage.bind(this)
		});

		this.tabidx = dialogNum;
		this.parent = $((this.options.parent || document.body));

		this.generate();
	},
	
	destruct: function() {

	},
	
	generate: function() {
		var dialog_styles = $merge({'display':'none', 'width':this.options.width.toInt()+'px'}, this.options.styles);

		this.dialog = new Element('div', {
			'id': this.dialogId, 
			'class': this.options.dialogClass,
			'opacity': (this.options.useFx ? 0 : 1),
			'styles': dialog_styles
		}).inject(this.parent);

		this.fx = this.options.useFx ? new Fx.Tween(this.dialog, $merge({
			'duration': '300'
		}, this.options.fxOptions)) : null;

		// dialog box sections and borders
		var db_message = new Element('div', {
			'class': this.options.messageBoxClass
		}).inject(this.dialog);
		
		// dialog box title
		if (this.options.title !== false) {
			this.titlebar = new Element('div', {
				'id': this.dialogId + '_title',
				'class': this.options.titleBarClass
			}).inject(db_message);

			new Element('span', {'class':this.options.titleTextClass, 'html': this.options.title}).inject(this.titlebar);

			if (this.options.titleClose != false) {
				new Element('span', {
					'id':this.dialogId + '_closer',
					'class': this.options.titleCloseClass,
					'title': this.options.titleCloseTitle
				}).inject(this.titlebar).addEvent('click', this.close.bind(this));
			}
		}


		// dialog box message
		this.message = new Element('div', {
			'id': this.dialogId + '_message', 
			'class': this.options.messageAreaClass + (this.options.title === false ? ' ' + this.options.noTitleClass : '') + (this.options.footer === false ? ' ' + this.options.noFooterClass : '')
		}).inject(db_message).setStyle('height', (this.options.height=='auto'?'auto':this.options.height.toInt()+'px'));

		if ($defined(this.options.url)) {
			this.request.options.url = this.options.url;
			this.request.send((this.options.requestQuery || ''));
			this.setMessage(this.options.loadingMessage);

			if (this.options.autoShow) { this.delayedShow = true; }
		} else if ($defined(this.options.message)){ this.setMessage(this.options.message); }


		// dialog footer
		if (this.options.footer !== false) {
			this.footer = new Element('div', {
				'id': this.dialogId + '_footer',
				'class': this.options.footerClass
			}).inject(db_message);

			new Element('div', {'class': 'foot-wrap'}).inject(this.footer);
			new Element('div', {'class': 'clear'}).inject(this.footer);

			if ($type(this.options.buttons) == 'array') {
				for(var i=0; i<this.options.buttons.length; i++) {
					(this.injectButton(this.options.buttons[i])).inject(this.footer.firstChild, 'top');
				}
			}

			// TODO: this could be much cleaner, yes?
			// default ok button
			if (this.options.ok !== false && this.options.defaultButtons !== false) {
				(this.injectButton({
					'text': this.options.okText,
					'class': this.options.okClass,
					'imageClass': this.options.okImageClass,
					'action': ($type(this.options.ok) == 'function' ? this.options.ok : null),
					'autoClose': this.options.okAutoClose
				})).inject(this.footer.firstChild, 'top');
			}
			// default cancel button
			if (this.options.cancel !== false && this.options.defaultButtons !== false) {
				(this.injectButton({
					'text': this.options.cancelText,
					'class': this.options.cancelClass,
					'imageClass': this.options.cancelImageClass,
					'action': ($type(this.options.cancel) == 'function' ? this.options.cancel : null),
					'autoClose': this.options.cancelAutoClose
				})).inject(this.footer.firstChild, 'top');
			}
		}

		// set dialog to draggable
		if (this.options.draggable && this.titlebar) {
			this.drag = new Drag.Move(this.dialog, {handle: this.titlebar});
		}

		if (this.options.clickCloses || ((this.options.title == false || this.options.titleClose == false) && (this.options.footer == false))) {
			$(document.body).addEvent('mousedown', this.clickClose);
		}

		// set the tab index for the dialog. Needs to be set so buttons tab correctly.
		this.setTabindex();
		this.fireEvent('complete');

		// execute onComplete function, if present.
		if (this.options.autoShow && !this.request.running) { this.show(); }
	},

	// TODO: is this the best way to handle this? probably not.
	buttonOptions: {
		'text': '',
		'position': 'right',
		'imageClass': 'image-button',
		'class': '',
		'action': $empty(),
		'autoClose': true,
		'tabindex': null
	},

	injectButton: function(_opts) {
		var opts = $merge(this.buttonOptions, _opts);
		var bid = this.dialogId + '_btn_' + (opts.text || Math.ceil(Math.random() * 10000)).replace(/\W/g, '').toLowerCase();
		var button = new Element('div', {
			'class': 'go' + opts['position'] + ' ' + opts['imageClass'] + ' ' + opts['class']
		});

		var b_link = new Element('a', { 'id': bid, 'href': 'javascript:void(0)', 'html': opts.text }).inject(button);
		if ($defined(opts.tabindex)) { b_link.set('tabindex', opts.tabindex); }
		if ($type(opts.action) == 'function') { button.addEvent('click', opts.action.bind(this)); }
		if (opts.autoClose) { button.addEvent('click', this.close.bind(this)); }

		return button;
	},

	setMessage: function(_message) {
		var message = ($type(_message) == 'function' ? _message() : _message);

		if ($type(message) == 'element') {
			this.grabbed = message.getParent();
			if (this.grabbed != null) {
				this.grabbedHide = (message.hasClass('none') ? {'class':'none'} : (message.getStyle('display') == 'none' ? {'style':'display:none'} : {}));
				if ($defined(this.grabbedHide['class'])) { message.removeClass('none'); }
				else if ($defined(this.grabbedHide['style'])) { message.setStyle('display', ''); }
				this.message.grab(message);
			} else {
				message.inject(this.message);
			}
		} else {
			this.message.set('html', message);
		}
		
		if (this.delayedShow) { 
			this.delayedShow = false;
			this.show();
		}
	},
	
	// TODO: To be used by improper HTMLElement or URL request...
	errorMessage: function(_error) {
		
	},

	// TODO: verify that all elements that take tabindex have been included.
	setTabindex: function() {
		var tabbed = ['a','select','input','textarea','button','label'];
		this.tabidx = this.tabidx.toInt();

		$(this.dialogId + '_message').getElements('*').each(function(_elem, _idx) {
			if (tabbed.contains(_elem.get('tag')) && _elem.get('tabindex') != -1) {
				_elem.set('tabindex', (++this.tabidx));
			}
		}, this);
		
		if ($(this.dialogId + '_footer')) {
			var footer_links = $(this.dialogId + '_footer').getElements('*');
			(footer_links.reverse()).each(function(_elem, _idx) {
				if (tabbed.contains(_elem.get('tag')) && _elem.get('tabindex') != -1) {
					_elem.set('tabindex', (++this.tabidx));
				}
			}, this);
		}
	},

	urlRequest: function(_response) {
		this.setMessage(_response);
		this.fireEvent('request');
	},

	toggleShade: function(_show) {
		if (!$('mavdialog_shade')) { new Element('div', {'id':'mavdialog_shade', 'class':this.options.shadeClass, 'opacity':'0.5'}).inject(document.body); }
		$('mavdialog_shade').setStyle('display', (_show === true ? 'block' : 'none'));
	},

	show: function() {
		if (this.options.force) {
			var shade_requests = ($(document.body).retrieve('shade_requets') || 0).toInt();
			$(document.body).store('shade_requests', (++shade_requests));
			this.toggleShade(this.options.force);
		}

		this.dialog.setStyle('display', '');
		if (this.options.center !== false) { this.screen_center(); }
		this.fireEvent('show');

		if (this.options.useFx) {
			this.fx.start('opacity', 0, 1);
		}
	},

	hide: function() {
		this.dialog.setStyle('display', 'none');
		this.fireEvent('hide');
	},

	clickClose: function(e) {
		var is_dialog = false;
		$(e.target).getParents('div').each(function(_elem) {
			if (!is_dialog && $(_elem).get('id') == this.dialogId) {
				is_dialog = true;
			}
		}, this);

		if (!is_dialog) { this.close(); }
	},

	close: function() {
		if (this.options.useFx) {
			this.fx.start('opacity', 1, 0).chain(this.finishClose.bind(this));
		} else { this.finishClose(); }
	},

	finishClose: function() {
		if ($(this.dialog)) {
			if (this.options.force) {
				var shade_requests = ($(document.body).retrieve('shade_requests')).toInt();
				$(document.body).store('shade_requests', (--shade_requests));
			}

			if ($defined(this.grabbed)) {
				if ($defined(this.grabbedHide['class'])) { this.message.firstChild.addClass('none'); }
				else if ($defined(this.grabbedHide['style'])) { this.message.firstChild.setStyle('display', 'none'); }
				this.grabbed.grab(this.message.firstChild);
			}

			this.dialog.dispose();
			if (this.options.force && shade_requests == 0) { this.toggleShade(); }

			this.fireEvent('close');
			
			this.destruct();
			$(document.body).removeEvent('mousedown', this.clickClose);
		}		
	},

	screen_center: function() {
		this.dialog.position('center', (this.parent || null));
	}
});


MavDialog.Confirm = new Class({
	Extends: MavDialog,

	initialize: function(_opts) {
		var opts = $merge(_opts, {
			'cancel':false,
			'titleClose':false,
			'message': this.buildMessage.bind(this, _opts.message),
			'ok': this.closeAction.bind(this, true),
			'cancel': this.closeAction.bind(this, false)
		});
		this.parent(opts);
	},
	
	buildMessage: function(_msg) {
		var message_box = new Element('div');
		new Element('div', {'class':'mav-icon-button confirm-icon goleft'}).inject(message_box);
		new Element('div', {'class':'mav-alert-msg goleft', 'html': _msg}).inject(message_box);
		new Element('div', {'class':'clear'}).inject(message_box);
		
		return message_box;
	},
	
	closeAction: function(_confirmed) {
		this.close();

		if (this.options.useFx && $defined(this.options.callback)) {
			// bah.
			this.fx.start('opacity', 1, 0).chain(this.finishClose.bind(this)).chain(this.options.callback(_confirmed));
		} else {
			this.finishClose();
			if ($defined(this.options.callback) && $type(this.options.callback) == 'function') {
				this.options.callback(_confirmed);
			}
		}
	}
});

MavDialog.Prompt = new Class({
	Extends: MavDialog,

	initialize: function(_opts) {
		var opts = $merge(_opts, {
			'cancel':false,
			'titleClose':false,
			'message': this.buildMessage.bind(this, _opts.message),
			'ok': this.closeAction.bind(this),
			'cancel': this.closeAction.bind(this, false),
			'onComplete': function() {
				var text_elem = this.dialogId + '_prompted';
				window.setTimeout(function() { $(text_elem).focus(); }, 310);
			}
		});
		this.parent(opts);
	},

	buildMessage: function(_msg) {
		var message_box = new Element('div');
		new Element('div', {'class':'mav-icon-button prompt-icon goleft'}).inject(message_box);
		var msg_display = new Element('div', {'class':'mav-alert-msg goleft'}).inject(message_box);

		new Element('div', {'html': _msg}).inject(msg_display);
		new Element('input', {
			'id': this.dialogId + '_prompted',
			'type':'text', 
			'class': 'mav-prompt-input'
		}).inject(msg_display);

		new Element('div', {'class':'clear'}).inject(message_box);

		return message_box;
	},
	
	closeAction: function(_canceled) {
		this.close();
		
		var prompt_value = (_canceled === false ? null : $(this.dialogId + '_prompted').get('value'));
		if (this.options.useFx && $defined(this.options.callback)) {
			// bah.
			this.fx.start('opacity', 1, 0).chain(this.finishClose.bind(this)).chain(this.options.callback(prompt_value));
		} else {
			this.finishClose();
			if ($defined(this.options.callback) && $type(this.options.callback) == 'function') {
				this.options.callback(prompt_value);
			}
		}
	}
});

MavDialog.Alert = new Class({
	Extends: MavDialog,

	initialize: function(_opts) {
		var opts = $merge(_opts, {
			'cancel':false,
			'titleClose':false,
			'message': this.buildMessage.bind(this, _opts.message)
		});
		this.parent(opts);
	},

	buildMessage: function(_msg) {
		var message_box = new Element('div');
		new Element('div', {'class':'mav-icon-button alert-icon goleft'}).inject(message_box);
		new Element('div', {'class':'mav-alert-msg goleft', 'html': _msg}).inject(message_box);
		new Element('div', {'class':'clear'}).inject(message_box);
		
		return message_box;
	}
});


MavDialog.MediaBox = new Class({
	Extends: MavDialog,	
	mOptions: {
		'autoShow': true,
		'footerClass': 'media-footer',
		'defaultButtons': false,
		'title': false,
		'force': true,
		'messageBoxClass':'',
		'dialogClass': 'mav-dialog-media',
		'noTitleClass':'',
		'noFooterClass':'',
		'titleClose':false,
		'clickCloses': true,
		'media': '',
		'buttons': [{
			'text': 'Close',
			'class': 'media-close-button close-icon'
		}]
	},
	mediaFormats: [/\.jpe?g$/i, /\.gif$/i, /\.png$/i],

	initialize: function(_opts) {
		this.mOptions = $merge(this.mOptions, _opts);
		this.mOptions['message'] = new Element('img').inject(document.body);

		if ($defined(this.mOptions.media)) {
			this.mOptions['message'].set('src', this.mOptions.media).addEvent('load', this.finishInit.bind(this));
		}
	},

	finishInit: function() {
		var iSize = this.mOptions['message'].getSize();
		this.mOptions['width'] = (iSize.x + 38) + 'px';
		this.mOptions['height'] = (iSize.y) + 'px';
		this.mOptions['message'].addClass('none');

		this.setOptions(this.mOptions);
		var dialogNum = Math.ceil(Math.random() * 10000);
		this.dialogId = 'mavd' + dialogNum + '_dialog';

		this.request = {'running':false};
		if ($(this.dialogId + '_dialog')) { return null; }

		this.tabidx = dialogNum;
		this.parent = $((this.options.parent || document.body));

		this.generate();
	}
});
// shortcut method
var MavMediaBox = function(_media) { new MavDialog.MediaBox({'media': _media}); };
/* String Element Extensions */
String.implement({strip_tags: function() { return (this.stripScripts()).replace(/<\/?[^>]+>/gi, ''); },reverse: function() { return ((this.split('')).reverse()).join(''); },lcfirst: function() { return this.replace(/\b([A-Z])/, function(_s) { return _s.toLowerCase(); }); },ucfirst: function() { return this.replace(/\b([a-z])/, function(_s) { return _s.toUpperCase(); }); },ltrim: function() { return this.replace(/^\s*/, ''); },rtrim: function() { return this.replace(/\s*$/, ''); },nl2br: function() { return (this.replace(/\r/g, '')).replace(/\n/g, '<br />'); },br2nl: function() { return (this.replace(/\r/g, '')).replace(/<br \/>/g, "\n"); }, number_format: function(_decs, _dpt, _thsep) {var str = String((this.toFloat()).toFixed(_decs || 2));str = (str.reverse()).replace(/((?:\d(?!\d+?\.)(?=\d)){3})/g, "$1" + (_thsep || ','));return (str.replace(/\./, (_dpt || '.'))).reverse();}});
Element.implement({swapClass:function(_remove,_add){this.removeClass(_remove).addClass(_add);}});
//]]>
