Ext.onReady(function(){
	var domNodeID = 'hotel-search-form';
	var domNode = Ext.get(domNodeID);
	if (domNode) {
		//config*************************************************************************
		var validationDelayInMillis = 500;
		
		function getNodeValue(nodeName, defaultValue) {
			var domNode = Ext.get(nodeName);
			var value = defaultValue;
			if (domNode) {
				value = domNode.dom.innerHTML;
			}
			return value;
		}
		var checkin = getNodeValue('req-param-checkin', '');
		var checkout = getNodeValue('req-param-checkout', '');
		var req_fr = getNodeValue('req-param-req_fr', '');
		if (req_fr=='true') {
			req_fr = true;
		} else {
			req_fr = false;
		}
		var default_area_size_in_sqm = getNodeValue('req-param-fr_area_sqm', '0');
		var default_area_size_in_sqf = getNodeValue('req-param-fr_area_sqf', '0');
		var default_area_size_unit = getNodeValue('req-param-fr_area_unit', 'sqm');
		var show_sqm = true;
		if (default_area_size_unit!='sqm') {
			show_sqm = false;
		}
		var default_capacity = getNodeValue('req-param-fr_capacity', '0');
		
		var hotel_name = getNodeValue('req-param-hotel_name_keyword', '');
		hotel_name = Url.replaceEscape(hotel_name);
		var district = getNodeValue('req-param-district', 'hotel.district.00');
		var star_rate = getNodeValue('req-param-star_rate', '-1');
		var locale = getNodeValue('req-param-locale', 'en_US');
		
		//Create error window*****************************************************************************
	    var errWindow = new Ext.Window({
	        title: 'Invalid input!',
	        width: 350,
	        height:'auto',
	        layout: 'fit',
	        plain:true,
	        bodyStyle:'padding:5px;',
	        buttonAlign:'center',
	        closeAction: 'hide',
	        html: '',
	
	        buttons: [{
	            text: 'Close',
	            handler: function(){errWindow.hide()},
	            scope: this
	        }]
	    });
		
		var errMsg = '';
		errWindow.on('show', function(){
			this.body.dom.innerHTML = "<div style='padding:10px;color:red;font: 12px;'>"+errMsg+"</div>";
		});

		var city_store = new Ext.data.SimpleStore({
		    fields: ['city'],
		    data: [['Singapore']]
		});
		
		var room_no_store = new Ext.data.SimpleStore({
		    fields: ['no'],
		    data: [['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['9+']]
		});
		
		var adult_no_store = new Ext.data.SimpleStore({
		    fields: ['no'],
		    data: [['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'], ['11'], ['12'], ['13'], ['14'], ['15'], ['16'], ['17'], ['18'], ['19'], ['20'], ['20+']]
		});
		
		var child_no_store = new Ext.data.SimpleStore({
		    fields: ['no'],
		    data: [['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['9+']]
		});
		
		var area_size_in_sqm_store = new Ext.data.SimpleStore({
		    fields: ['value', 'text'],
		    data: [['0', 'Any size'], ['100', '>= 100'], ['300', '>= 300'], ['500', '>= 500'], ['1000', '>= 1000'], ['2000', '>= 2000']]
		});
		
		var area_size_in_sqf_store = new Ext.data.SimpleStore({
		    fields: ['value', 'text'],
		    data: [['0', 'Any size'], ['1000', '>= 1,000'], ['3000', '>= 3,000'], ['5000', '>= 5,000'], ['10000', '>= 10,000'], ['20000', '>= 20,000']]
		});
		
		var area_size_unit_store = new Ext.data.SimpleStore({
		    fields: ['value', 'text'],
		    data: [['sqm', 'square metres'], ['sqf', 'square feet']]
		});
		
		var capacity_store = new Ext.data.SimpleStore({
		    fields: ['value', 'text'],
		    data: [['0', 'Any number'], ['20', '> 20'], ['40', '> 40'], ['60', '> 60'], ['100', '> 100'], ['300', '> 300'], ['500', '> 500'], ['1000', '> 1000']]
		});
		
		var hotelSearchStore = new Ext.data.JsonStore({
	    	url: '/HotelServlet?action=getHotelSummary'
	       	,root: 'results'
       		,totalProperty: 'totalCount'
	       	,fields: ['id','name','address','star_rate','district_id']
	    });
	    
		var districtStore = new Ext.data.JsonStore({
	    	url: '/HotelServlet?action=getHotelDistrictList&locale='+locale+'&with_all=y'
	       ,root: 'results'
	       ,fields: ['value', 'text']
	    });
	    districtStore.on('load', function(st, recs){
	    	if (district=='') {
	    		Ext.getCmp('hotel-search-district').setValue(recs[0].get('id'));
	    	} else {
	    		Ext.getCmp('hotel-search-district').setValue(district);
	    	}
	    });
	    
	    var resultTpl = new Ext.XTemplate(
	        '<tpl for="."><div class="search-item">',
	        	'<h3>{name}</h3>',
	        	'<table width="100%">',
	        		'<tr valign="center">',
	        			'<td width="30%" class="sub-info">Rating:</td>',
	        			'<td width="70%" class="sub-info"><img src="/shared/sir/images/{star_rate}-star.gif"/></td>',
	        		'</tr>',
	        		'<tr valign="top">',
	        			'<td class="sub-info">District:</td>',
	        			'<td class="sub-info">{district_id}</td>',
	        		'</tr>',
	        		'<tr valign="top">',
	        			'<td class="sub-info">Address:</td>',
	        			'<td class="sub-info">{address}</td>',
	        		'</tr>',
	        	'</table>',
	        '</div></tpl>'
	    );
		
		var today = new Date().clearTime();
		var default_check_in;
		if (checkin!=0) {
			default_check_in = checkin;
		} else {
			default_check_in = new Date(today.setDate(today.getDate()+3)).clearTime();
		}
		
		var default_check_out;
		if (checkout!=0) {
			default_check_out = checkout;
		} else {
			default_check_out = new Date(today.setDate(today.getDate()+3)).clearTime();
		}

		var noOfMonthsAhead = 6;
		var currentDate = new Date();
		var date = new Date();
		var maxDate = new Date(date.setMonth(date.getMonth()+noOfMonthsAhead)).clearTime();
		//Create panel*****************************************************************************
	    var searchForm = new Ext.FormPanel({
	    	//autoHeight:true,
	        labelWidth: 60, // label settings here cascade unless overridden
	        height:513,
	        labelAlign: 'top',
	        bodyStyle:'padding:5px 5px 0;',
	        title: '<span class="home-centerpanel-header">Search Hotels</span>',
	        iconCls: 'icon-zoom',
	        frame: true,
	        layout: 'column',
	        items: [
				{
            		columnWidth:1,
            		border:false,
            		layout:'form',
					labelAlign: 'left',
            		items: [
	        			{
	        				xtype:'combo',
		                    width: 140,
		                    fieldLabel: 'City',
		                    editable: false,
						    mode: 'local',
		                    store: city_store,
						    displayField: 'city',
		                    valueField: 'city',
						    triggerAction: 'all',
		                    id: 'hotel-search-city',
		                    value:'Singapore'
	        			}
            		]
				}
	        	,{
            		columnWidth:1,
            		border:false,
            		style:'line-height:9px',
            		html:'&nbsp;'
	        	}
	        	//first line: check-in date, check-out date
				,{
            		columnWidth:1,
            		border:false,
            		layout:'form',
			        labelAlign: 'left',
            		items: [
	        			{
							xtype: 'datefield',
	        				id:'hotel-search-check-in-date',
	        				format:'m/d/Y',
	        				width: 140,
		                    fieldLabel: 'Check in',
		                    minValue:currentDate.clearTime(),
		                    maxValue:maxDate,
		                    maxText: "You can only book a hotel within "+noOfMonthsAhead+" months. If you need further assistance, please contact us via e-mail:booking@ninelogic.com or phone:(+65)66997071.",
		                    value:default_check_in,
		                    listeners:{
		                    	'select':function(df, checkin_date){
							      	var checkout_date = Ext.getCmp('hotel-search-check-out-date').getValue();
							      	if (checkin_date >= checkout_date) {
							      		//check_in date is equal or latter than check_out date, adjust check_out date
							      		checkout_date = new Date(checkin_date.getFullYear(), checkin_date.getMonth(), checkin_date.getDate()+3);
							      		if (checkout_date >= df.maxValue) {
							      			checkout_date = df.maxValue;
							      		}
								      	Ext.getCmp('hotel-search-check-out-date').setValue(checkout_date);
								      	if (checkout_date <= checkin_date) {
								      		Ext.getCmp('hotel-search-check-out-date').markInvalid('Check out date must be greater than check in date.');
								      	}
								    }
		                    	}
		                    }
	        			}
            		]
				}
	        	,{
            		columnWidth:1,
            		border:false,
            		style:'line-height:2px',
            		html:'&nbsp;'
	        	}
				,{
            		columnWidth:1,
            		border:false,
            		layout:'form',
			        labelAlign: 'left',
            		items: [
	        			{
	        				xtype: 'datefield',
							id:'hotel-search-check-out-date',
	        				format:'m/d/Y',
	        				width: 140,
		                    fieldLabel: 'Check out',
		                    minValue:currentDate.clearTime(),
		                    maxValue:maxDate,
		                    maxText: "You can only book a hotel within "+noOfMonthsAhead+" months. If you need further assistance, please contact us via e-mail:booking@ninelogic.com or phone:(+65)66997071.",
		                    value:default_check_out,
		                    listeners:{
		                    	'select':function(df, checkout_date){
							      	var checkin_date = Ext.getCmp('hotel-search-check-in-date').getValue();
							      	if (checkin_date >= checkout_date) {
							      		//check_in date is equal or latter than check_out date, adjust check_in date
							      		checkin_date = new Date(checkout_date.getFullYear(), checkout_date.getMonth(), checkout_date.getDate()-3).clearTime();
							      		if (checkin_date <= df.minValue) {
							      			checkin_date = df.minValue;
							      		}
								      	Ext.getCmp('hotel-search-check-in-date').setValue(checkin_date);
								      	if (checkout_date <= checkin_date) {
								      		df.markInvalid('Check out date must be greater than check in date.');
								      	}
								    }
		                    	}
		                    }
	        			}
            		]
				}
	        	,{
            		columnWidth:1,
            		border:false,
            		style:'line-height:9px',
            		html:'&nbsp;'
	        	}
	        	,{
	        		columnWidth:1,
	        		bodyStyle:'font-size:12px;color:#888;padding-top:15px;',
	        		html:'------------------- Optional -------------------'
	        	}
	            ,{
	        		columnWidth:1,
			        border: false,
			        id:'more-options-1',
	        		layout:'form',
	        		items:[
		                {
		                	xtype: 'combo',
		                	id:'hotel-search-hotel-name',
					        store: hotelSearchStore,
					        fieldLabel: 'Hotel name',
					        emptyText: '',
					        displayField:'name',
					        typeAhead: false,
					        loadingText: 'Searching...',
					        width: 204,
					        bodyStyle:'padding-top:40px;',
					        pageSize:10,
					        minChars: 1,
					        queryDelay: 500,
					        hideTrigger:true,
					        emptyText: "Enter part of hotel name",
					        tpl: resultTpl,
					        itemSelector: 'div.search-item',
					        value:hotel_name
					        ,onSelect: function(record){ // override default onSelect to do redirect
					            this.setValue(Url.replaceEscape(record.get("name")));
					            this.collapse();
					        }
							,listeners: {
								expand: function(combo) {
							     	if (combo.assetHeight == 0 && combo.pageSize > 0 && Ext.isIE7)
							       		combo.assetHeight = 28;
							  	}
							}
					    }
	        		]
	            }
	            ,{
	        		columnWidth:1,
			        border: false,
			        id:'more-options-2',
			        labelAlign: 'top',
	        		layout:'form',
	        		items:[
	        			new Ext.ux.form.CheckboxCombo({
			                fieldLabel: "District",
							width: 204,
							listWidth: 204,
							maxHeight:200,
							firstEntryExclusive:true,
							mode: 'local',
							store: new Ext.data.ArrayStore({
								fields: ['value', 'text'],
								data: [['hotel.district.00','All districts'],['hotel.district.01','Balestier'],['hotel.district.02','Bugis'],['hotel.district.03','Bukit Timah'],['hotel.district.04','Changi Airport'],['hotel.district.05','Chinatown'],['hotel.district.06','Clarke Quay'],['hotel.district.07','East Coast'],['hotel.district.08','Shenton Way'],['hotel.district.09','Geylang'],['hotel.district.10','Kallang '],['hotel.district.11','Little India '],['hotel.district.12','Marina Bay'],['hotel.district.13','Orchard'],['hotel.district.15','Sentosa Island '],['hotel.district.16','West Coast '],['hotel.district.17','Yishun']]
							}),
							valueField: 'value',
							displayField: 'text',
				            value:district,
			                id: 'hotel-search-district'
						})
	        		]
	            }
	            ,{
	        		columnWidth:1,
			        border: false,
			        id:'more-options-3',
			        labelAlign: 'top',
			        style:'',
	        		layout:'form',
	        		items:[
	        			new Ext.ux.form.CheckboxCombo({
			                fieldLabel: "Star rating",
							width: 204,
							listWidth: 204,
							firstEntryExclusive:true,
							mode: 'local',
							store: new Ext.data.ArrayStore({
								fields: ['value', 'text'],
								data: [['-1', 'All stars'], ['1', '1 star'], ['2', '2 star'], ['3', '3 star'], ['4', '4 star'], ['5', '5 star']]
							}),
							valueField: 'value',
							displayField: 'text',
				            value:star_rate,
			                id: 'hotel-search-star-rate'
						})
	        		]
	            }
	        	,{
            		columnWidth:1,
            		border:false,
            		layout:'form',
            		id:'more-options-4',
            		items: [
            			{
            				xtype: 'checkbox',
            				id:'hotel-search-require-function-rooms',
		                	checked:req_fr,
		                	boxLabel: 'require function rooms',
					        fieldLabel:'', 
					        labelStyle:'display:none;',
					        labelSeparator:'',
		                	inputValue: 1,
		                	listeners:{
		                		'check': function(cb, checked) {
		                			if (checked) {
		                				Ext.getCmp('hotel-search-area-size-in-sqm').enable();
		                				Ext.getCmp('hotel-search-area-size-in-sqf').enable();
		                				Ext.getCmp('hotel-search-area-size-unit').enable();
		                				Ext.getCmp('hotel-search-capacity').enable();
		                			} else {
		                				Ext.getCmp('hotel-search-area-size-in-sqm').disable();
		                				Ext.getCmp('hotel-search-area-size-in-sqf').disable();
		                				Ext.getCmp('hotel-search-area-size-unit').disable();
		                				Ext.getCmp('hotel-search-capacity').disable();
		                			}
		                		}
		                	}
            			}
		        	]
	        	}
	            ,{
	        		columnWidth:.75,
			        border: false,
			        hidden:!show_sqm,
	        		layout:'form',
	        		style:'padding-bottom:3px;',
	        		labelWidth:57,
	        		labelAlign:'left',
	        		id:'more-options-5',
	        		items:[
	        			{
	        				xtype:'combo',
	        				disabled:!req_fr,
			                fieldLabel: 'Area',
	        				width: 82,
						    mode: 'local',
	        				store:area_size_in_sqm_store,
						    displayField: 'text',
		                    valueField: 'value',
						    editable: false,
						    triggerAction: 'all',
						    value:default_area_size_in_sqm,
			                id: 'hotel-search-area-size-in-sqm'
	        			}
	        		]
	            }
	            ,{
	        		columnWidth:.75,
			        border: false,
	        		layout:'form',
	        		style:'padding-bottom:3px;',
	        		hidden:show_sqm,
	        		labelWidth:57,
	        		labelAlign:'left',
	        		id:'more-options-6',
	        		items:[
	        			{
	        				xtype:'combo',
	        				disabled:!req_fr,
			                fieldLabel: 'Area',
	        				width: 82,
						    mode: 'local',
	        				store:area_size_in_sqf_store,
						    displayField: 'text',
		                    valueField: 'value',
						    editable: false,
						    triggerAction: 'all',
						    value:default_area_size_in_sqf,
			                id: 'hotel-search-area-size-in-sqf'
	        			}
	        		]
	            }
	            ,{
	        		columnWidth:.25,
			        border: false,
	        		layout:'form',
	        		labelAlign:'left',
	        		id:'more-options-7',
	        		items:[
	        			{
	        				xtype:'combo',
	        				disabled:!req_fr,
					        hideLabel: true,
	        				width: 50,
	        				listWidth: 50,
						    mode: 'local',
	        				store:area_size_unit_store,
						    displayField: 'value',
		                    valueField: 'value',
		                    tpl: '<tpl for="."><div class="x-combo-list-item combo-list-item-lvl1" ext:qtip="{text}">{value}</div></tpl>',
						    editable: false,
						    triggerAction: 'all',
						    value:default_area_size_unit,
			                id: 'hotel-search-area-size-unit',
			                listeners:{
		                    	'select': function(combo, rec, index){
		                    		var value = combo.getValue();
		                    		if (value == 'sqm') {
		                    			Ext.getCmp('more-options-5').show();
		                    			Ext.getCmp('more-options-6').hide();
		                    		} else if (value == 'sqf') {
		                    			Ext.getCmp('more-options-5').hide();
		                    			Ext.getCmp('more-options-6').show();
		                    		}
		                    	}
			                }
	        			}
	        		]
	            }
	            ,{
	        		columnWidth:1,
			        border: false,
	        		layout:'form',
	        		labelWidth:57,
	        		labelAlign:'left',
	        		id:'more-options-8',
	        		items:[
	        			{
	        				xtype:'combo',
	        				disabled:!req_fr,
			                fieldLabel: 'Capacity',
	        				width: 142,
						    mode: 'local',
	        				store:capacity_store,
						    displayField: 'text',
		                    valueField: 'value',
						    editable: false,
						    triggerAction: 'all',
						    value:default_capacity,
			                id: 'hotel-search-capacity'
	        			}
	        		]
	            }
	            ,{
	            	columnWidth:1,
	            	style:'line-height:21px;',
	            	html:'&nbsp;'
	            }
			],
			buttonAlign:'center',
		    buttons: [
		    	{
		    		text: '<b>Search</b>',
		    		style: '',
		    		minWidth: 100,
		    		handler: function() {
                    	var isCheckInDateValid = Ext.getCmp('hotel-search-check-in-date').isValid();
                    	var isCheckOutDateValid = Ext.getCmp('hotel-search-check-out-date').isValid();
                    	if (!isCheckInDateValid || !isCheckOutDateValid) {
				    		errMsg = 'Some fields contain errors. Please correct them first.';
				    		errWindow.show();
				    		return;
                    	}
                    	var check_in_date = Ext.getCmp('hotel-search-check-in-date').getValue();
                    	var check_out_date = Ext.getCmp('hotel-search-check-out-date').getValue();
                    	if (check_in_date>=check_out_date) {
						    Ext.getCmp('hotel-search-check-out-date').markInvalid('Check out date must be greater than check in date.');
				    		errMsg = 'Some fields contain errors. Please correct them first.';
				    		errWindow.show();
				    		return;
                    	}
                    	if (!check_out_date.between(check_in_date, new Date(check_in_date.getFullYear(), check_in_date.getMonth()+1, check_in_date.getDate()))) {
                    		Ext.getCmp('hotel-search-check-out-date').markInvalid('For making room bookings more than 1 month, please contact our sales directly at (65)6699-7071.');
				    		errMsg = 'Some fields contain errors. Please correct them first.';
				    		errWindow.show();
				    		return;
                    	}
		    			
		    			var checkin = Ext.getCmp('hotel-search-check-in-date').getValue().format('m/d/Y');
		    			var checkout = Ext.getCmp('hotel-search-check-out-date').getValue().format('m/d/Y');
		    			var hotel_name = Url.encode(Ext.getCmp('hotel-search-hotel-name').getValue());
		    			var district = Ext.getCmp('hotel-search-district').getValue();
		    			var star_rate = Ext.getCmp('hotel-search-star-rate').getValue();
		    			var req_fr = Ext.getCmp('hotel-search-require-function-rooms').getValue();
		    			var fr_area_sqm = Ext.getCmp('hotel-search-area-size-in-sqm').getValue();
		    			var fr_area_sqf = Ext.getCmp('hotel-search-area-size-in-sqf').getValue();
		    			var fr_area_unit = Ext.getCmp('hotel-search-area-size-unit').getValue();
		    			var fr_capacity = Ext.getCmp('hotel-search-capacity').getValue();
		    			window.location='/hotels/showSummary.jsp?check-in='+checkin+'&check-out='+checkout
		    							+'&hotel_name_keyword='+hotel_name+'&district='+district
		    							+'&star_rate='+star_rate+'&req_fr='+req_fr+'&fr_area_sqm='+fr_area_sqm
		    							+'&fr_area_sqf='+fr_area_sqf+'&fr_area_unit='+fr_area_unit+'&fr_capacity='+fr_capacity;
		    		}
		    	}
		    ]
	    });
		
		searchForm.on('render', function(){
			//districtStore.load();
		});
	    searchForm.render(domNodeID);
	    
	}
});


