/* javascript compressor */
	Ext.namespace('Ext.ux.form');

Ext.ux.form.Select = Ext.extend(Ext.form.ComboBox,  {
	
	selectValue : false,
	
	valueKey : 'value',
	
	textKey : 'text',
	
	initComponent : function(){
		this.mode 	= 'local';
		this.editable = false;
		this.hiddenName = this.name;
		this.name = this.hiddenField+'_display';
		this.triggerAction = 'all';
		this.store	= new Ext.data.SimpleStore({
			fields: [this.valueKey,this.textKey],
			data: this._createData(this.options)
		});
		this.valueField = this.valueKey;
		this.displayField = this.textKey;
		Ext.ux.form.Select.superclass.initComponent.call(this);
		this._selectValue();
	},
	
	_createData : function(data){
		var ar = [], tk = this.textKey, vk = this.valueKey;
		if( data ){
			Ext.each( data, function(item){
				if( !Ext.isArray(item) ){
					item = [item[vk],item[tk]];
				}
				ar[ar.length]=item;
			});
		}
		return ar;
	},
	
	clearOptions: function(){
		this.store.loadData([]);
	},
	
	setOptions: function(options, norender){
		this.store.loadData(this._createData(options));
		this._selectValue();
		this.fireEvent('setoptions', this, this.getValue() );
	},
	
	_selectValue : function(){
		var setValue = true;
		if( this.value ){
			this.store.each( function(item){
				if(item.get(this.valueKey)==this.value){
					this.setValue(this.value);
					setValue = false;
					return false;
				}
				return true;
			}, this);
		}
		if(setValue && this.store.getCount() > 0 ){
			this.selectIndex(0);
		}
	},
	
	addOption: function(option){
		var d = this._createData([options]);
		if(d[0]){
			this.store.add(d);
		}
	},
	
    insertOption: function(option,pos){
    	var d = this._createData([option]);
		if(d[0]){
			this.store.insert(pos,d);
		}
    },
	
	selectIndex : function(index,scrollIntoView){
		this.selectedIndex = index;
        
		var r = this.store.getAt(index);
		this.setValue(r.get(this.valueField));
		if( this.view ){
			this.view.select(index);
			if(scrollIntoView !== false){
				var el = this.view.getNode(index);
				if(el){
					this.innerList.scrollChildIntoView(el, false);
				}
			}
		}
	}
});

Ext.reg('ux-select', Ext.ux.form.Select );/**
 * $Id: my.joomla.js 376 2008-11-13 15:16:27Z fabrizim $
 * @copyright	Copyright (C) 2006 - 2007 Owl Watch Consulting Services, LLC. All rights reserved.
 * @license		see LICENSE file
 */

Ext.namespace("MY", "MY.joomla");

if( Ext.isGecko ){
    Ext.lib.Dom.getViewportWidth=function(){
        return document && document.documentElement ? document.documentElement.scrollWidth :
            self.innerWidth;
    };
}
// this is a fix for mootools - I'm pretty sure it has to do with
// the garbage collection when the document unloads
Ext.getDom = function(el){
    try{
        if(!el || !document){
            return null;
        }
        return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
    }catch(e){
        return null;
    }      
};

MY.joomla.Connector = function(){
	this.Itemid= "2";
	this.siteurl= this.cleanUrl('http://www.starimlini.com');
	this.ajaxurl= this.cleanUrl('http://www.starimlini.com/index2.php');
	this.option= 'com_tableboss';
	this.readyStack = [];
	this.isLegacy = new Boolean("");
	this.sections=null;
	this.user=null;
	this.events = {
		'ready':true,
		'logout':true
	};
};

Ext.extend( MY.joomla.Connector, Ext.util.Observable, {
	cleanUrl: function(url){
		var regex = /^http\:\/\/www/;
		if( regex.test(window.location.href) && !regex.test(url)){
			url = url.replace(/http\:\/\//, "http://www.");
		}else if( regex.test(url) && !regex.test(window.location.href)){
			url = url.replace( /http\:\/\/www/, "http://");
		}
		return url;
	},
	initialize: function( view, task ){
		this.request( {view:view,task:task,format:'raw',output:'json'},{
			callback: function(opts,success,xhr){
				if( success ){
					this.data = Ext.util.JSON.decode(xhr.responseText);
					if( this.data.sections ){
						this.sections = this.data.sections;
					}
					if( this.data.user ){
						this.user = this.data.user;
					}
				}
				this.ready = true;
				this.fireEvent('ready');
			},
			scope: this
		});
	},
	getParams: function( view, task, output, format, config ){
		var params = {
			no_html: 1,
			option: 'com_tableboss',
			view: view,
			task: task,
			format: format || 'raw',
			output: output || 'json',
			Itemid: this.Itemid
		};
		Ext.apply( params, config );
		return params;
	},
	getConnection: function(params){
		var config = {
			url: this.ajaxurl,
			method: 'POST',
			extraParams: Ext.apply( {
				no_html: 1,
				option: this.option,
				Itemid: this.Itemid
			},params || {})
		};
		var conn = new Ext.data.Connection(config);
		conn.on('beforerequest', function(){
			this.checkRequest.apply(this,arguments);
		}, this);
		conn.on('requestcomplete', function(){
			this.checkResponse.apply(this,arguments);
		}, this);
		return conn;
	},
	request: function(params, options){
		options = (!options || typeof options == "boolean") ? {} : options;
		var c = this.getConnection();
		options.params = params;
		c.request(options);
	},
	onReady: function( fn, scope ){
		if( this.ready ){
			var f=fn.createDelegate(scope);
			f();
			return;
		}
		this.on('ready',fn,scope);
		return;
	},
	
	checkResponse : function(conn,response,options){
		if(response.responseText.indexOf('<script>') == 0 ||
		   response.responseText.match(/^\s*<div\s*id="section/)
		){
			if( this.ajaxurl.indexOf('index3.php') ){
				this.fireEvent('logout');
				this.loginBox(response.responseText);
				this.lastReq = {
					conn: conn,
					response: response,
					options: options
				};
				throw 'Session Expired';
			}
		}
		return true;
	},
	
	checkRequest : Ext.emptyFn,
	
	loginBox: function(content){
		if( !this.loginDlg ){
			this.loginDlg = new Ext.Window({
				title:'Please Login',
				resizable:false,
				constrain:true,
				constrainHeader:true,
				minimizable : false,
				maximizable : false,
				stateful: false,
				modal: true,
				closeAction: 'hide',
				shim : true,
				buttonAlign:"center",
				width:300,
				buttons: [
					{
						'text':'Login',
						'scope':this,
						'handler':this.doLogin
					}
				],
				autoHeight:true,
				footer:true,
				minHeight: 80,
				plain:true,
				closable:true,
				items: [
					{
						xtype:'form',
						autoHeight:true,
						id:'login-form',
						border: false,
						bodyStyle:'padding: 6px;',
						url: MY.Joomla.ajaxurl,
						onSpecialKey: function(el,e){
							var ev = Ext.EventObject;
							if( e.getKey() == ev.ENTER || e.getKey() == ev.RETURN ){
								this.doLogin();
							}
						},
						listeners : {
							scope: this,
							render: function(el){
								el.items.each(function(item){
									item.on('specialkey', el.onSpecialKey, this);
								},this);
							}
						},
						items: [
							{
								xtype:'component',
								autoEl:{
									tag:'p',
									style:'font-size:12px;padding:10px 0px;',
									html:'Your session has timed out, please login to continue.'
								}
							},
							{
								xtype:'textfield',
								name:'username',
								anchor: '-5',
								fieldLabel:'Username'
							},
							{
								xtype:'textfield',
								name:'passwd',
								anchor: '-5',
								fieldLabel:'Password',
								inputType:'password'
							},
							{
								xtype:'combo',
								id:'login-lang',
								name:'lang_display',
								hiddenField:'lang',
								anchor: '-5',
								fieldLabel:'Language',
								mode:'local',
								store:new Ext.data.SimpleStore({
									fields:['value','text']
								}),
								displayField:'text',
								valueField:'value'
							}
						]
					}
				]
			});
			var old = this.loginDlg.setZIndex;
			this.loginDlg.setZIndex = function(){
				old.call(this,30000);
			};
			this.hiddenFormEl = Ext.get(document.body).createChild({
				tag:'div',
				style:'display:none'
			});
		}
		this.loginDlg.show();
		this.hiddenFormEl.update(content);
		var p = {};
		Ext.each(this.hiddenFormEl.query('input'), function(node){
			if( node.name != 'username' && node.name != 'passwd' ){
				p[node.name] = node.value;
			}
		});
		Ext.getCmp('login-form').baseParams = p;
		var s = this.hiddenFormEl.child('select',true);
		var opts = [];
		Ext.each(s.options, function(opt){
			opts[opts.length] = [opt.value, opt.text];
		});
		Ext.getCmp('login-lang').store.loadData(opts);
		Ext.getCmp('login-form').getForm().reset();
		this.hiddenFormEl.update('');
		this.loginDlg.doLayout();
	},
	doLogin: function(){
		
		var f = Ext.getCmp('login-form');
		var p = Ext.apply(f.getForm().getValues(),f.baseParams);
		this.loginDlg.body.mask('Logging in...','x-mask-loading');
		Ext.Ajax.request({
			params: p,
			method:'POST',
			url: f.getForm().url,
			success: function( response, options){
				this.loginDlg.body.unmask();
				if( this.isLegacy==false && response.responseText.match(/form\-login/i) == null  ){
					this.loginDlg.hide();
					this.lastReq.conn.request(this.lastReq.options);
				}else{
					alert('Invalid login. Please try again.');
				}
			},
			scope: this
		});
	}
	
});

MY.IdGenerator = function(){
	var id = 0;
	return {
		generate: function(){
			id++;
			return id;
		}
	}
}();
MY.id = MY.IdGenerator.generate.createDelegate( MY.IdGenerator );
MY.JsonReader = Ext.extend( Ext.data.JsonReader,{
	read : function( res ){
		if( !res.responseText || /^\s*</.test(res.responseText) ){
			throw {message:'Bad JSON Message Returned'};
		}
		return MY.JsonReader.superclass.read.call(this,res);
	}
});
MY.Joomla = new MY.joomla.Connector();
Ext.Ajax.on('beforerequest', function(){
	MY.Joomla.checkRequest.apply(MY.Joomla, arguments);
}, MY.Joomla);
Ext.Ajax.on('requestcomplete', function(){
	MY.Joomla.checkResponse.apply(MY.Joomla, arguments);
}, MY.Joomla);

MY.Joomla.evalFormConfigs = function( configs, options ){
	options = options || {};
	var arrayMode = ( Ext.type(configs) == 'array' );
	var model = options.model || 'default';
	var ret = arrayMode ? [] : {};
	if( arrayMode ){
		for( var i = 0; i < configs.length; i++ ){
			ret[ret.length] = MY.Joomla.evalFormConfig(configs[i],options);
		}
	}else{
		for( var i in configs ){
			ret[i] = MY.Joomla.evalFormConfig(configs[i],options);
		}
	}
	return ret;
};
MY.Joomla.evalFormConfig = function(c, options){
	options = options || {};
	var model = options.model || 'default';
	if( Ext.type(c) == 'array' ){
			return MY.Joomla.evalFormConfigs(c,options);
	}else{
		if( c.xtype == 'combo' ){
			if( c.mode == 'local' && c.data ){
				var opts = [];	
				for( i=0; i<c.data.length; i++){
					opts[opts.length] = [c.data[i].value,c.data[i].text];
				}
				c.store = new Ext.data.SimpleStore({
					fields: ['value','text'],
					data: opts
				});
			}
			else{
				c.store = new Ext.data.JsonStore({
					url: MY.Joomla.ajaxurl,
					root: 'items',
					baseParams: options.comboBaseParamsFn ? options.comboBaseParamsFn(c.name) : Ext.apply(
						MY.Joomla.getParams(model,'getComboOptions'),{
							'property':c.name
						}
					),
					fields: ['value','text']
				});
			}
			c.hiddenName=c.name;
			if( !c.editable ){
				c.editable = false;
			}
			c.listeners = {
				'show': function(){
					this.store.load();
				}
			};
			c.triggerAction='all';
			c.name=c.name+'-combo-display';
			c.displayField = 'text';
			c.valueField = 'value';
			c.forceSelection = true;
		}
		else if(c.xtype=='datefield'){
			c.format = 'm/d/Y';
		}
		else if(c.xtype=='htmleditor'){
			c.width=580;
			c.height=200;
		}
		return c;
	}
};
/**
 * $Id: tb.public.js 408 2008-11-25 13:18:30Z fabrizim $
 * @package		TableBoss
 * @copyright	Copyright (C) 2006 - 2007 Owl Watch Consulting Services, LLC. All rights reserved.
 * @license		see LICENSE file
 */

Ext.namespace('TB.pub');

TB.pub.Reservation = function(){
	this.el = Ext.get('tb-reservation-form');
	this.prefix = 'tb-';
	this.user = {
		'name'		: '',
		'email'		: ''
	};
	this.dayFieldType = 'calendar';
	this.sizeFieldType = 'plusminus';
	this.map = {};
	this.steps = [];
	this.addEvents({
		select			:true
	});
	this.connection = MY.Joomla.getConnection({
		view			:'public',
		format			:'raw',
		output			:'json'
	});
	this.init();
	// hopefully this doesn't break too often. opera, safari - i'm looking at you.
	var old = window.onunload;
	var fn = this.clearTemporary.createDelegate(this);
	window.onunload=function(){
		fn();
		if(old && typeof(old).toLowerCase()!='undefined'){
			old();
		}
	};
};

Ext.extend( TB.pub.Reservation, Ext.util.Observable, {
	
	init: function(){
		var z = 0;
		Ext.select('.step_content',true,this.el.dom).each(function(e){
			var s = {};
			z++;
			s.wrap = e.findParent('.reservation_step',10,true);
			s.wrap.setStyle({
				'z-index':z
			});
			var c = e.child('.step_padding');
			s.container = c;
			s.orig = c.dom.innerHTML;
			c.update('');
			s.textWrap = c.createChild({tag:'div',cls:'text-wrap'});
			s.contentWrap = c.createChild({tag:'div',cls:'content-wrap'});
			s.textWrap.setVisibilityMode(Ext.Element.DISPLAY);
			s.contentWrap.setVisibilityMode(Ext.Element.DISPLAY);
			s.contentWrap.hide();
			s.textWrap.update(s.orig);
			s.id = e.dom.id.replace(new RegExp(this.prefix),'');
			this.map[s.id]=this.steps.length;
			this.steps[this.map[s.id]]=s;
		},this);
		if( this.steps.length == 0 ){
			return;
		}
		//this.currentStep = this.steps[0];
		this.load();
		Ext.QuickTips.init();
	},
	
	load: function(s){
		if( s ){
			this.currentStep = s;
		}
		if( !this.currentStep ){
			this.currentStep = this.steps[0];
		}
		s = this.currentStep;
		this.reset(s);
		if( this['load_'+s.id] ){
			return this['load_'+s.id]();
		}
		return this._default_load(s);
	},
	
	_default_load: function(s){
		if( !s.select ){
			var w = Ext.fly(s.contentWrap).getWidth()*.8;
			s.select = new Ext.ux.form.Select({
				width			:w,
				textKey			:'display',
				valueKey		:'value',
				style			:'text-align: center',
				tpl				:'<tpl for="."><div style="text-align:center" class="x-combo-list-item">{display}</div></tpl>'
			});
			s.select.on('select',this.onSelect.createDelegate(this,[s]));
			s.select.render(s.contentWrap);
			s.loading = s.contentWrap.createChild({
				tag:'img',
				src:'http://www.starimlini.com/plugins/extjs2/ext/resources/images/default/grid/loading.gif',
				alt:'Loading...'
			});
			s.loading.setVisibilityMode( Ext.Element.DISPLAY );
			s.loading.hide();
		}
		if( s.errorMsgWrap ){
			s.errorMsgWrap.hide();
		}
		s.select.hide(true);
		s.loading.show();
		this.connection.request({
			params: this.getParams({task:'dropdown'}),
			scope: this,
			success: function(res,options){
				res = Ext.decode(res.responseText);
				this.clearReservation(res.clearReservation);
				if( res.error ){
					this.displayErrorMessage(s, res.error);
					return;
				}
				s.select.setOptions(res.items);
				s.select.selectIndex(0);
				s.loading.hide();
				s.select.show();
			}
		});
		return true;
	},
	
	displayErrorMessage: function(s,msg){
		if( !s.errorMsgWrap ){
			s.errorMsgWrap = s.contentWrap.createChild({
				tag:'div',
				style:'text-align:center'
			});
			s.errorMsgWrap.setVisibilityMode( Ext.Element.DISPLAY );
		}
		s.errorMsgWrap.update(msg);
		if( s.loading ){
			s.loading.hide();
		}
		s.errorMsgWrap.show();
	},
	
	clearTemporary: function(e){
		if( this.reservation ){
			this.connection.request({
				params: this.getParams({task:'clearTemporary'})
			});
		}
	},
	
	onSelect: function(s){
		if( s.select.getValue() == -1 ){
			this.reset(s);
			return;
		}
		var next = this.steps[this.map[s.id]+1];
		this.load(next);
	},
	
	load_info: function(){
		var s = this.currentStep;
		if( !s.loading ){
			s.loading = s.contentWrap.createChild({
				tag:'img',
				src:'http://www.starimlini.com/plugins/extjs2/ext/resources/images/default/grid/loading.gif',
				alt:'Loading...'
			});
			s.loading.setVisibilityMode( Ext.Element.DISPLAY );
		}
		s.loading.show();
		if( this.fc ){
			this.fc.hide();
		}
		this.connection.request({
			params: this.getParams({task:'secureTable'}),
			scope: this,
			success: function(res,options){
				res = Ext.decode(res.responseText);
				this.clearReservation(res.clearReservation);
				
				if( res.success ){
					this.reservation = res.reservation;
					s.loading.hide();
					var f = this.getForm(s);
					this.focusEmptyField(f);
					this.fc.show();
					f.getForm().clearInvalid();
				}
				else{
					this.error = res.error;
				}
			}
		});
	},
	
	load_size: function(){
		var s = this.currentStep;
		if( this.sizeFieldType != 'plusminus' ){
			this._default_load(s);
			return;
		}
		
		var next = this.steps[this.map[s.id]+1];
		if( !s.field ){
			var w = s.contentWrap.getWidth() * .8;
			s.loading = s.contentWrap.createChild({
				tag:'img',
				src:'http://www.starimlini.com/plugins/extjs2/ext/resources/images/default/grid/loading.gif',
				alt:'Loading...'
			});
			s.loading.setVisibilityMode( Ext.Element.DISPLAY );
			s.fieldWrap = s.contentWrap.createChild({
				tag:'div',
				style:'text-align:left; margin: 0px auto; width: '+w+'px'
			});
			s.btnWrap = s.fieldWrap.createChild({
				tag:'div',
				style: 'float: right'
			});
			
			var selectSize = function(){
				s.field.validate();
				if( s.field.isValid() ){
					s.selectBtn.focus();
					this.load(next);
				}
			};
			
			s.selectBtn = new Ext.Button({
				text:'Please Select Party Size',
				handler: selectSize,
				scope: this,
				renderTo: s.btnWrap
			});
			/*
			s.errorWrap = s.contentWrap.createChild({
				tag:'div',
				id: '_size_error_wrap',
				style:'display: block; text-align:left; margin: 0px auto; width: '+w+'px'
			});
			*/
			var bw = s.selectBtn.getEl().getWidth();
			
			s.field = new Ext.ux.PlusMinusField({
				width: Math.ceil(w-bw-20),
				readOnly: false,
				style: 'margin-left: 0',
				min: 1,
				renderTo: s.fieldWrap,
				max: parseInt('8')
			});
			//s.field.render(s.fieldWrap);
			
			var fw = s.field.getEl().up('.x-form-field-wrap');
			fw.setStyle({
				'margin':'0px auto 0px 0px'
			});
			
			var triggers = fw.select('.x-form-trigger');
			s.field.getEl().setWidth(s.field.getEl().getWidth()-2);
			
			s.loading.hide();
			s.field.on('change', this.reset.createDelegate(this,[s]) );
			s.field.on('plus', this.reset.createDelegate(this,[s]) );
			s.field.on('minus', this.reset.createDelegate(this,[s]) );
			s.field.on('tabkey', selectSize, this);
			s.field.on('returnkey', selectSize, this);
			s.field.on('enterkey', selectSize, this);
		}
	},
	
	load_day: function(){
		var s = this.currentStep;
		if( this.dayFieldType != 'calendar' ){
			this._default_load(s);
			return;
		}
		// use a calendar date...
		var next = this.steps[this.map[s.id]+1];
		if( !s.field ){
			s.loading = s.contentWrap.createChild({
				tag:'img',
				src:'http://www.starimlini.com/plugins/extjs2/ext/resources/images/default/grid/loading.gif',
				alt:'Loading...'
			});
			s.loading.setVisibilityMode( Ext.Element.DISPLAY );
			var w = s.contentWrap.getWidth();
			w = .8 * w;
			this.connection.request({
				params: this.getParams({task:'dateField'}),
				scope: this,
				success: function(res,options){
					res = Ext.decode(res.responseText);
					s.field = new Ext.form.DateField({
						width				:parseInt(w),
						emptyText			:'Choose Day',
						readOnly			:true,
						format				:res.format,
						minValue			:res.min,
						maxValue			:res.max,
						renderTo			:s.contentWrap,
						disabledDates		:res.disabledDates,
						disabledDatesText	:'This day is unavailable',
						menuListeners		:{
							'select'		:function(m,d){
								s.field.setValue(d);
								this.onSelectDay(next);
							}.createDelegate(this)
						},
						onTriggerClick		:function(){
							if(this.disabled){
								return;
							}
							if(this.menu == null){
								this.menu = new Ext.menu.DateMenu();
							}
							Ext.apply(this.menu.picker,  {
								minDate : this.minValue,
								maxDate : this.maxValue,
								disabledDatesRE : this.disabledDatesRE,
								disabledDatesText : this.disabledDatesText,
								disabledDays : this.disabledDays,
								disabledDaysText : this.disabledDaysText,
								format : this.format,
								showToday : this.showToday,
								minText : String.format(this.minText, this.formatDate(this.minValue)),
								maxText : String.format(this.maxText, this.formatDate(this.maxValue))
							});
							this.menu.on(Ext.apply({}, this.menuListeners, {
								scope:this
							}));
							this.menu.picker.setValue(this.getValue() || new Date());
							this.menu.show(this.el, "c-c?");
						}
					});
					window.dateField = s.field;
					s.field.getEl().on('click', s.field.onTriggerClick.createDelegate(s.field) );
					var firstFocus=true;
					s.field.getEl().on('focus', function(){
						if( firstFocus ){
							s.field.onTriggerClick();
							firstFocus=false;
						}
					} );
					s.loading.hide();
					s.field.getEl().setStyle({'text-align': 'center'});
					s.field.show();
					s.field.focus();
				}
			});
		}
		if( s.field && s.field.getValue() != '' ){
			this.onSelectDay(next);
		}
	},
	
	onSelectDay: function(next){
		this.load(next);
	},
	
	focusEmptyField: function(form){
		form.items.each( function(field){
			if( field.getValue() == '' ){
				field.focus();
				return false;
			}
			return true; // only added this to avoid green squigglies.
		});
	},
	
	closeReservation: function(sendConfirmation, requireValidation, result){
		var delay = 200;
		var i = 0;
		var speed = .6;
		var t=this.steps.length-1;
		var opts = {duration: .5};
		var s = this.steps[this.steps.length-1];
		var num = s.wrap.child('.step_number');
		num.setOpacity(0,opts);
		var cw = s.contentWrap;
		cw.setOpacity(0);
		cw.setStyle('text-align', 'left');
		
		if( !requireValidation){
			cw.update( this._confirmationHtml(sendConfirmation) );
			cw.addClass('tb-reservation-success');
		}
		else if( result.paypalHTML ){
			cw.update(result.paypalHTML);
			var form = cw.child('form');
			cw.child('input[type=image],input[type=submit]').on('click', function(){
				form.dom.submit();
			});
			cw.addClass('tb-reservation-validate');
		}else{
			cw.update('<p>You will receive an email with a validation code. Please enter the code in the following box, or click the link provided in the email, to confirm your reservation.</p>');
			cw.addClass('tb-reservation-validate');
			var bp = Ext.apply(MY.Joomla.getParams('public','validate'),{
				reservation		:this.reservation.id
			});
			this.validateForm = new Ext.form.FormPanel({
				method			:'POST',
				url				:MY.Joomla.ajaxurl,
				baseParams		:bp,
				bodyStyle		:'background-color: transparent;',
				border			:false,
				renderTo		:cw,
				items: [
					{
						xtype			:'textfield',
						name			:'code',
						fieldLabel		:'Validation Code',
						labelWidth		:220,
						width			:100
					}
				],
				buttons: [
					{
						text: 'Validate',
						scope: this,
						handler: function(){
							this.validateForm.getForm().submit({
								scope: this,
								success: function(form,action){
									var result = action.result;
									cw.removeClass('tb-reservation-validate');
									cw.addClass('tb-reservation-success');
									cw.update( this._confirmationHtml(sendConfirmation) );
								},
								failure: function(form,action){
									var result = action.result;
									Ext.MessageBox.alert('Email Validation', result.error );
								}
							})
						}
					}
				]
			});
		}
		
		for( i = 0; i < this.steps.length-1; i++ ){
			var w = this.steps[i].wrap;
			w.setStyle({
				'position'	:'relative',
				'z-index'	:i
			});
			var d = i/t * speed;
			// fix for IE
			if( Ext.isIE && this.steps[i].field ){
				this.steps[i].field.hide();
			}
			w.setStyle('overflow','hidden');
			var num = w.child('.step_number');
			num.setOpacity(0,opts);
			w.setHeight.defer(d,w,[0,opts]);
		}
		var newopts = {duration:3};
		cw.setOpacity.defer(d*i,cw,[100,newopts]);
	},
	
	_confirmationHtml: function( sendConfirmation ){
		var lastLine = sendConfirmation && sendConfirmation != 0 ? '<p>You will receive an email with your reservation confirmation details.</p>':'';
		var time = Date.parseDate(this.reservation.start,'Y-m-d H:i:s');
		var html = [
			'<p>Your Reservation has been confirmed!</p>',
			this.reservation.infoHtml,
			lastLine
		];
		return html.join(' ');
	},
	
	confirmReservation: function(){
		if( !this.form || this.currentStep.id != 'info' || !this.reservation || this.confirming){
			return;
		}
		this.confirming=true;
		this.form.getForm().submit({
			params	:this.getParams({task: 'confirmReservation'}),
			scope	:this,
			success	:function(form,action){
				this.confirming=false;
				this.reservation = action.result.reservation;
				//Ext.MessageBox.alert('Reservation Made', 'Your Reservation has been confirmed');
				this.closeReservation(action.result.sendConfirmation, action.result.requireValidation==1, action.result );
			},
			failure :function(form,action){
				this.confirming=false;
				Ext.MessageBox.alert('Problem Confirming Reservation','Please correct the errors noted on the form. <br /><br />Hover the field to see the error message.',
					function(){
						var r = action.result;
						if( action.result && action.result.errors ){
							var err = action.result.errors;
							for(var n in err){
								var f = this.form.getForm().findField(n);
								if( f ){
									f.focus();
									if( f.selectText ){
										f.selectText();
									}
									return;
								}
							}
						}
						this.focusEmptyField(this.form);
					},
					this
				);
			}
		});
	},
	
	getForm: function(s){
		if(this.form){
			return this.form;
		}
		var w = 200;
		var fc= Ext.DomHelper.append(s.contentWrap.dom,{
			tag		:'div'
		});
		this.fc = Ext.get(fc);
		this.fc.setVisibilityMode(Ext.Element.DISPLAY);
		this.form = new Ext.form.FormPanel({
			method			:'post',
			url				:MY.Joomla.ajaxurl,
			baseParams		:MY.Joomla.getParams('public','confirmReservation'),
			labelAlign		:'right',
			border			:false,
			renderTo		:fc,
			bodyStyle		:'background-color: transparent',
			defaults		:{
				border: false,
				xtype: 'textfield'
			},
			buttons: [
				{
					text			:'Make Reservation',
					scope			:this,
					handler			:this.confirmReservation
				}
			],
			items: [
				{
					name			:'name',
					allowBlank		:false,
					width			:w,
					value			:this.user.name,
					fieldLabel		:'Name'
				},{
					name			:'email',
					allowBlank		:false,
					width			:w,
					value			:this.user.email,
					fieldLabel		:'Email'
				},{
					name			:'phone',
					allowBlank		:false,
					width			:w,
					fieldLabel		:'Phone'
				},{
					xtype			:'textarea',
					name			:'notes',
					allowBlank		:true,
					width			:w,
					fieldLabel		:'Notes'
				}
			]
		});
		var c = 100;
		this.form.getForm().items.each( function(field){
			field.getEl().set({'tabindex':c++});
			if( field.getEl().dom.tagName.toLowerCase() == 'input' ){
				field.on('specialkey', function(field,e){
					if( e.getKey() == e.RETURN || e.getKey() == e.ENTER ){
						this.confirmReservation();
					}
				}, this);
			}
		}, this);
		for( var i=0; i < this.form.buttons.length; i++ ){
			var btn = this.form.buttons[i];
			b = btn.getEl().child('button');
			b.set({'tabindex':c++});
		}
		return this.form;
	},
	
	clearReservation: function(id){
		if( id && this.reservation && this.reservation.id == id ){
			this.reservation = false;
		}
	},
	
	getIndex: function(id){
		return this.map[id];
	},
	
	getParams: function(p){
		p = p || {};
		for( var i=0; i< this.map[this.currentStep.id]; i++){
			var s = this.steps[i];
			
			if( s.select ){
				p[s.id] = s.select.getValue();
			}
			else if( s.field ){
				var v = s.field.getValue();
				if( v.getTimezone ){
					v = v.format('Y-m-d');
				}
				p[s.id]=v;
			}
		}
		if( this.reservation ){
			p.reservation = this.reservation.id;
		}
		p.step = this.currentStep.id;
		return p;
	},
	
	reset: function(from){
		var seen = false;
		for( var i = 0; i < this.steps.length; i++ ){
			var s = this.steps[i];
			if( seen ){
				s.textWrap.show();
				s.contentWrap.hide();
				s.wrap.replaceClass('on','off');
				s.on = false;
			}
			else{
				if( s.id == from.id ){
					seen = true;
				}
				s.textWrap.hide();
				s.contentWrap.show();
				s.wrap.replaceClass('off','on');
			}
		}
	}
});
Ext.onReady(function(){
	TB.ReservationForm = new TB.pub.Reservation();
});
