// JavaScript Document

Ext.onReady(function(){
    var winBooking;
    var button = Ext.get('show-btn');

	var rooms;
	var days;
	var cost;
	var rate;
	var rateid;
	var df;
	var dt;
//--------------------------		Datasets		  -------------------------------------
//		dsCounter
//		dsHotels
//		dsRooms
//-----------------------------------------------------------------------------------------
//		dsCounter
	var dsCounter = new Ext.data.SimpleStore({
		fields: [ 'count' ],
		data : [['0'],['1'],['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10'],['11'],['12'],['13'],['14'],['15']]
	});
//		dsHotels
	var dsHotels = new Ext.data.JsonStore({
		totalProperty	: 'total',	
		root			: 'results',	
		url				: 'myqueries.php', 	
		baseParams		: { queryid: 101 },
		method			: 'post',
		fields			: [
							{name: 'hotelid', type: 'int'},
							'hotelname', 'hoteladdress', 'hotelcity', 'hoteltel', 'hotelfax', 'hotelemail', 'isheadoffice'
							]
	});							
//		dsRooms
	var dsRooms = new Ext.data.JsonStore({
		totalProperty	: 'total',	
		root			: 'results',	
		url				: 'myqueries.php', 	
		baseParams		: { queryid: 102 },
		method			: 'post',
		fields			: [
							{name: 'rateid', type: 'int'},
							'roomid', 'roomtype', 'rate', 'roomdesc', 'roomphoto'
							]
	});							


//	Form Panel		:	formBasicInfo
	var fieldDestination = new Ext.form.ComboBox({
		fieldLabel		: 'Destination',
		triggerAction	: 'all', 
		name			: 'hotelname',
		mode			: 'local',
		store			: dsHotels,
		hiddenName		: 'hotelid',
		displayField	: 'hotelname',
		valueField		: 'hotelid',
		emptyText		: 'Select Hotel ...',
		width			: 150
	});

	var fieldDateFrom = new Ext.form.DateField({
		name		: 'datefrom',
		fieldLabel	: 'From',
		format		: 'd-m-Y',
		width 		: 150
	});

	var fieldDateTo = new Ext.form.DateField({
		name		: 'dateto',
		fieldLabel	: 'To',
		format		: 'd-m-Y',
		width 		: 150
	});

	var fieldRooms = new Ext.form.ComboBox({
		triggerAction:'all', 
		name		: 'rooms',
		fieldLabel	: 'Rooms',
		mode		: 'local',
		store		: dsCounter,
		displayField: 'count',
		width		: 120
	});

	var fieldAdults = new Ext.form.ComboBox({
		triggerAction:'all', 
		name		: 'adults',
		fieldLabel	: 'Adults',
		mode		: 'local',
		store		: dsCounter,
		displayField: 'count',
		width		: 120
	});

	var fieldChildren = new Ext.form.ComboBox({
		triggerAction:'all', 
		name		: 'children',
		fieldLabel	: 'Children',
		mode		: 'local',
		store		: dsCounter,
		displayField: 'count',
		width		: 120
	});
	
	var fieldNotes = new Ext.form.TextArea({
		name		: 'notes',
		fieldLabel	: 'Notes',
		width 		: 350
	});


	var formBasicInfo = new Ext.FormPanel({
		id			: 'card-0',											
		title		: 'Step 1 of 3: Basic Stay Information',
//		autoHeight	: true,
		labelWidth	: 70, 
		layout		: 'form',
		frame		: true,
		listeners	: { beforeadd: function(){ dsHotels.load({params:{start: 0, limit: 25}}); }},
		items		: [ fieldDestination ,{
					   layout	: 'column',
					   items	: [
							   { 
									columnWidth	: .5,
									layout		: 'form',
									items		: [ fieldDateFrom, fieldAdults ]
							   },{ 
									columnWidth	: .5,
									layout		: 'form',
									items		: [ fieldDateTo, fieldChildren ]
							   }]}, 
					   fieldRooms, fieldNotes ]
	})


//		Grid			:	cmRooms, gridRooms
	var cmRooms = new Ext.grid.ColumnModel([
		{id:'rateid',header: "ID", width: 30, hidden: true, sortable: true, dataIndex: 'rateid'},
		{header: 'Room View', width: 170, renderer: renderEPThumb, sortable: true, dataIndex: 'roomphoto'},
		{header: 'Room', width: 200, renderer: renderEPTopic, sortable: true, dataIndex: 'roomtype'},
		{header: 'Rate (USD)', width: 50, sortable: true, xtype: 'numbercolumn', dataIndex: 'rate'}
	]);
	var gridRooms = new Ext.grid.GridPanel({
		frame		: false,
		region      : 'center',
		store		: dsRooms,
		cm			: cmRooms,
		sm			: new Ext.grid.RowSelectionModel({ 
								singleSelect	: true,
								listeners		: { 
								 	rowselect : function(sm, row, rec) { 
											rate	= rec.get('rate');
											cost	= days * rate * rooms;
											rateid	= rec.get('rateid');
										}
								 }}),
		split       : true,
		loadMask	: true,
		stripeRows	: true,
		viewConfig	: {	forceFit	: true		}
	});
//		Grid Functions	:	renderEPTopic, renderEPThumb
	function renderEPTopic(value, p, record){
		return String.format( '<span align="justify" width="270"><b>{0}</b><br/><p>{1}</p></span>', value, 
							 record.data.roomdesc );
	};
	function renderEPThumb(value, p, record){
		return String.format( '<img src={0} width="150" height="100" />', value );
	};

	var formRoomInfo = new Ext.FormPanel({
		id			: 'card-1',											
		title		: 'Step 2 of 3: Room Selection (Select the Room you wish to book) <a href="http://www.oanda.com/currency/converter/" target="_blank">Currency Converter</a>',
		layout		: 'border',
		frame		: true,
		items		: [ gridRooms ]
	})


	var fieldSummary = new Ext.form.Label({
		name		: 'notes',
		width 		: 350
	});
	var fieldNameF = new Ext.form.TextField({
		name		: 'guestnamef',
		fieldLabel	: 'Name: First',
		tabIndex	: 1,
		width 		: 100
	});
	var fieldNameM = new Ext.form.TextField({
		name		: 'guestnamem',
		fieldLabel	: 'Middle',
		tabIndex	: 2,
		width 		: 100
	});
	var fieldNameL = new Ext.form.TextField({
		name		: 'guestnamel',
		fieldLabel	: 'Family',
		tabIndex	: 3,
		width 		: 100
	});
	var fieldNationality = new Ext.form.TextField({
		name		: 'guestnationality',
		fieldLabel	: 'Nationality',
		tabIndex	: 4,
		width 		: 100
	});
	var fieldTelephone = new Ext.form.TextField({
		name		: 'guesttelephone',
		fieldLabel	: 'Telephone',
		tabIndex	: 5,
		width 		: 100
	});
	var fieldEmail = new Ext.form.TextField({
		name		: 'guestemail',
		fieldLabel	: 'Email',
		tabIndex	: 6,
		width 		: 150
	});
	var fieldSummary = new Ext.form.TextArea({
		name		: 'notes',
		fieldLabel	: 'Summary',
		height		: 100,
		width 		: 330
	});

		
//		Field Set		:	fsPersonalInfo
	var formPersonalInfo = new Ext.FormPanel({
		id			: 'card-2',											
		title		: 'Step 3 of 3: Personal Information',
		layout		: 'form',
		frame		: true,
		items		: [ fieldSummary, {
					   layout		: 'column',
					   labelAlign	: 'top',
					   items		: [
							   { 
									columnWidth	: .3,
									layout		: 'form',
									items		: [ fieldNameF, fieldNationality ]
							   },{ 
									columnWidth	: .3,
									layout		: 'form',
									items		: [ fieldNameM, fieldTelephone ]
							   },{ 
									columnWidth	: .4,
									layout		: 'form',
									items		: [ fieldNameL, fieldEmail ]
							   }] 
				   }, fieldSummary]
	})


	var cardNav = function(incr){
		var l = Ext.getCmp('card-wizard-panel').getLayout();
		var i = l.activeItem.id.split('card-')[1];
		var next = parseInt(i) + incr;
		l.setActiveItem(next);
		Ext.getCmp('card-prev').setDisabled(next==0);
		if(next == 1 || next == 0){Ext.getCmp('card-next').setText('Next &raquo;')}; 
		if(next == 1){
			rooms			= fieldRooms.getValue()
			df				= fieldDateFrom.getValue();
			df 				= df.format ('Y-m-d');
			dt				= fieldDateTo.getValue();
			dt 				= dt.format ('Y-m-d');
			var curDate		= new Date();
			curDate.DateDiff({interval:"d",date1:df,date2:dt});
			days			= curDate.difference;

			df				= fieldDateFrom.getValue();
			df 				= df.format ('d-m-Y');
			dt				= fieldDateTo.getValue();
			dt 				= dt.format ('d-m-Y');

			dsRooms.load({params:{
							start	: 0, 
							limit	: 25, 
							hotelid	: fieldDestination.getValue(), 
							datefrom: df, 
							dateto	: dt}});

			cost = 0;
		}
		if(next == 2){
			Ext.getCmp('card-next').setText('Submit &raquo;');

			var gridHS 		= gridRooms.getSelectionModel();
			var selItems 	= gridHS.getSelections();
			
			fieldSummary.setValue(	'You are about to book ' 
									+ days + ' days at the: ' + '\n' 
									+ fieldDestination.getRawValue() + ' Hotel - '
									+ selItems[0].get('roomtype') + '\n' 
									+ 'at a daily rate of: ' + Ext.util.Format.number(rate, '0,000.00') + ' USD' + '\n' 
									+ 'and total sum of: ' + Ext.util.Format.number(cost, '0,000.00') + ' USD');
		} 
		if(next == 3){
			Ext.Ajax.request({
				url		: 'mysql.php',
				method	: 'POST',
				params	: {
					queryid			: '101',
					guestnamef		: fieldNameF.getValue(), 
					guestnamem		: fieldNameM.getValue(), 
					guestnamel		: fieldNameL.getValue(), 
					guestnationality: fieldNationality.getValue(), 
					guesttelephone	: fieldTelephone.getValue(), 
					guestemail		: fieldEmail.getValue(), 
					rateid			: rateid, 
					datefrom		: df, 
					dateto			: dt, 
					rooms			: fieldRooms.getValue(), 
					adults			: fieldAdults.getValue(), 
					children		: fieldChildren.getValue(), 
					notes			: fieldNotes.getValue() 
				},
				success		: function(){
					Ext.MessageBox.alert('Submit Ok', 'Your request has been submitted successfully<br>You will be contacted by email for confirmation<br>We thank you and hope to see you soon.');
//							this.close();
				},
				failure		: function(){
					Ext.MessageBox.alert('Warning','failure...');
				}
			});
			
		}
	};
	
	
    button.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        if(!winBooking){
            winBooking = new Ext.Window({
			    id			: 'card-wizard-panel',
				title		: 'Regina Hotels Online Booking Form',	
                applyTo		: 'booking-win',
                width		: 500,
                height		: 300,
                closeAction	: 'hide',
				modal		: true,
				layout		: 'card',
				activeItem	: 0, 	// index or id
				bbar: [{
							id: 'card-prev',
							text: '&laquo; Previous',
							handler: cardNav.createDelegate(this, [-1]),
							disabled: true
						}, '->', {
							id: 'card-next',
							text: 'Next &raquo;',
							handler: cardNav.createDelegate(this, [1])
						}],
				items: [	formBasicInfo, formRoomInfo, formPersonalInfo ]
            });
        }
        winBooking.show(this);
    });
});
