Ext.override(Ext.form.DateField, {
    initDisabledDays : function(){
        if(this.disabledDates){
            var dd = this.disabledDates;
            var re = "(?:";
            for(var i = 0; i < dd.length; i++){
                re += this.formatDate(dd[i]);
                if(i != dd.length-1) re += "|";
            }
            this.ddMatch = new RegExp(re + ")");
        }
    }
    ,setDisabledDates : function(dd){
        this.disabledDates = dd;
        this.initDisabledDays();
        if(this.menu)
        {
            this.menu.picker.setDisabledDates(this.ddMatch);
        }
    }
});

var timeStore = new Ext.data.SimpleStore({
    fields: ['time'],
    data: [
    	['10:00 AM'], ['10:15 AM'], ['10:30 AM'], ['10:45 AM'],
    	['11:00 AM'], ['11:15 AM'], ['11:30 AM'], ['11:45 AM'],
    	['12:00 PM'], ['12:15 PM'], ['12:30 PM'], ['12:45 PM'],
    	['1:00 PM'], ['1:15 PM'], ['1:30 PM'], ['1:45 PM'],
    	['2:00 PM'], ['2:15 PM'], ['2:30 PM'], ['2:45 PM'],
    	['3:00 PM'], ['3:15 PM'], ['3:30 PM'], ['3:45 PM'],
    	['4:00 PM'], ['4:15 PM'], ['4:30 PM'], ['4:45 PM'],
    	['5:00 PM'], ['5:15 PM'], ['5:30 PM'], ['5:45 PM'],
    	['6:00 PM'], ['6:15 PM'], ['6:30 PM'], ['6:45 PM'],
    	['7:00 PM'], ['7:15 PM'], ['7:30 PM'], ['7:45 PM'],
    	['8:00 PM'], ['8:15 PM'], ['8:30 PM'], ['8:45 PM'],
    	['9:00 PM'], ['9:15 PM'], ['9:30 PM'], ['9:45 PM'],
    	['10:00 PM'], ['10:15 PM'], ['10:30 PM'], ['10:45 PM'],
    	['11:00 PM'], ['11:15 PM'], ['11:30 PM'], ['11:45 PM']
    ]
});

var noOfMonthsAhead = 1;
var isPHStoreLoaded = false;
var phStore = new Ext.data.JsonStore({
	url: '/RestaurantBookingServlet?action=getPublicHolidays&no_of_months='+noOfMonthsAhead
   ,root: 'results'
   ,fields: ['date']
   ,autoLoad:true
});
phStore.on('load', function(store, records){
	isPHStoreLoaded = true;
});

var rest_rec;
var disable_instant_confirm_sat_lunch = false;
var disable_instant_confirm_sat_dinner = false;
var disable_instant_confirm_sat_eve = false;
var disable_instant_confirm_sun_lunch = false;
var disable_instant_confirm_sun_dinner = false;
var disable_instant_confirm_ph_lunch = false;
var disable_instant_confirm_ph_dinner = false;
var disable_instant_confirm_ph_eve = false;
var disable_instant_confirm_has_other = false;
var lunch_time = [];
var dinner_time = [];
var timeError = false;
function showRestaurantBookingForm(restId, bookingId) {
	var maxLengthOtherRequirements = 500;
	var validationDelayInMillis = 2000;
	var otherRequirementsEmptyText = 'We will do our best to help you.';
	
	//define stores*******************************************************************************************
    var restStore = new Ext.data.JsonStore({
    	url: '/RestaurantBookingServlet?action=getRestaurantSummaryForBooking&rest-id='+restId
       ,root: 'results'
       ,totalProperty: 'totalCount'
       ,id: 'id'
       ,fields: ['id', 'name', 'photo', 'district', 'cuisine', 'discount', 'occasion', 'viproom', 'expense', 'address', 'points_rate', 'other_benefits', 'name_identifier',
       			'instant_confirmable', 'instant_confirm_no_of_pax', 'instant_confirm_lunch_lb', 'instant_confirm_lunch_ub',
       			'instant_confirm_dinner_lb', 'instant_confirm_dinner_ub', 'instant_confirm_disabled_dates'
       ]
    });

	//define stores*******************************************************************************************
    var bookingStore = new Ext.data.JsonStore({
    	url: '/RestaurantBookingServlet?action=getUserRestaurantBookingRecords&bookingid='+bookingId
    	,root: 'results'
       	,totalProperty: 'totalCount'
       	,id: 'id'
       	,fields: ['id', 'booking_date2', 'booking_time2', 'dining_date2', 'dining_time2',
       			'rest_id', 'rest_name', 'rest_address', 'no_of_persons', 'viproom', 'title', 'name', 
       			'mobile', 'mobile_ctry_code', 'email', 'contact_via', 'points', 'status', 'book_via', 
       			'diner_preferred_language', 'other_requirements', 'total_bill']
    });
	
	//define stores*******************************************************************************************
    var userStore = new Ext.data.JsonStore({
    	url: '/RestaurantBookingServlet?action=getUserInfoForRestaurantBooking'
       ,root: 'results'
       ,fields: ['user_id', 'title', 'real_name', 'mobile_ctry_code', 'mobile', 'email', 'prev_notify_via', 'prev_preferred_lang']
    });
	
	var titleStore = new Ext.data.SimpleStore({
	    fields: ['title'],
	    data: [['Mr.'], ['Ms.']]
	});
	
	var viproomStore = new Ext.data.SimpleStore({
	    fields: ['viproom'],
	    data: [["I don't mind"], ['Preferred'], ['Required']]
	});
	
	var contactviaStore = new Ext.data.SimpleStore({
	    fields: ['contactvia'],
	    data: [["SMS"], ['E-mail'], ['Phone']]
	});
	
	var preferredLanguageStore = new Ext.data.SimpleStore({
	    fields: ['language'],
	    data: [["English"], ['Chinese']]
	});
	
	//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:#15428b;font: 12px;'>"+errMsg+"</div>";
	});
	
	//handle submit*****************************************************************************************
	 var doSubmit = function(){
		var contactvia = Ext.getCmp('booking-form-contactvia').getValue();
		if (contactvia == 'E-mail') {
			contactvia = 'Email';
		}
    	var isDateValid = Ext.getCmp('booking-form-date').isValid();
    	var isTimeValid = Ext.getCmp('booking-form-time').isValid();
    	var isNoOfPersonValid = Ext.getCmp('booking-form-noofperson').isValid();
    	var isNameValid = Ext.getCmp('booking-form-name').isValid();
    	var isMobileValid = Ext.getCmp('booking-form-mobile').isValid();
    	var isEmailValid = Ext.getCmp('booking-form-email').isValid();
    	var isOtherRequirementsValid = Ext.getCmp('booking-form-other-requirements').isValid();
    	if (timeError || !isDateValid || !isNoOfPersonValid || !isNameValid || ((contactvia=='SMS' || contactvia=='Phone') && !isMobileValid) || (contactvia=='Email' && !isEmailValid) || !isOtherRequirementsValid) {
    		errMsg = 'Some fields contain errors. Please correct them first.';
    		errWindow.show();
    		return;
    	}
    	
    	var record = restStore.getAt(0);
    	var hasVipRoom = record.get('viproom');
    	var optVipRoom = Ext.getCmp('booking-form-viproom').getValue();
    	if (optVipRoom == 'Required' && (hasVipRoom == 'No' || hasVipRoom == '')) {
    		Ext.getCmp('booking-form-viproom').markInvalid("This restaurant doesn't have VIP room.");
    		errMsg = 'Some fields contain errors. Please correct them first.';
    		errWindow.show();
    		return;
    	}
		
		var mobile = Ext.getCmp('booking-form-mobile').getValue();
		var email = Ext.getCmp('booking-form-email').getValue();
		if (contactvia == 'SMS') {
			if (mobile.length == 0) {
				Ext.getCmp('booking-form-mobile').markInvalid("Mobile number is required if you want to be contacted by sms.");
	    		errMsg = 'Some fields contain errors. Please correct them first.';
	    		errWindow.show();
	    		return;
			}

		} else if (contactvia == 'Phone') {
			if (mobile.length == 0) {
				Ext.getCmp('booking-form-mobile').markInvalid("Phone number is required if you want to be contacted by phone.");
	    		errMsg = 'Some fields contain errors. Please correct them first.';
	    		errWindow.show();
	    		return;
			}

		} else if (contactvia == 'Email') {
			if (email.length == 0) {
				Ext.getCmp('booking-form-email').markInvalid("E-mail is required if you want to be contacted by e-mail.");
	    		errMsg = 'Some fields contain errors. Please correct them first.';
	    		errWindow.show();
	    		return;
			}
		}
		
		//vcode can't be empty for instant confirm
		var isVcodeValid = Ext.getCmp('booking-form-vcode').isValid();
		if (Ext.get('instant_confirm_cb').dom.checked) {
			var vcode = Ext.getCmp('booking-form-vcode').getValue();
			if (!isVcodeValid) {
	    		errMsg = 'Some fields contain errors. Please correct them first.';
	    		errWindow.show();
	    		return;
			}
			if (!vcode || vcode.length==0) {
				Ext.getCmp('booking-form-vcode').markInvalid("This field is required.");
	    		errMsg = 'Some fields contain errors. Please correct them first.';
	    		errWindow.show();
	    		return;
			}
		}

		var otherRequirementsCmp = Ext.getCmp('booking-form-other-requirements');
		if(otherRequirementsCmp.getRawValue() == ''){
			Ext.getCmp('booking-form-other-requirements').setRawValue('');
		}
		
		Ext.getCmp('submit-btn').disable();
		panel.form.submit({
			waitMsg:'Saving...', 
			reset: false, 
			failure: function(form, action) { 
				Ext.getCmp('submit-btn').enable();
				var msg = action.result.msg;
				Ext.Msg.show({
					title: 'Failure', 
					msg: '<span style="color:red">'+msg+'</span>',
					buttons: Ext.Msg.OK,
					minWidth: 400
				});
			}, 
			success: function(windowForm, action) { 
				var msg = action.result.msg;
				Ext.getCmp('restaurant-booking-form').destroy();
				Ext.Msg.show({
					title: 'Success', 
					msg: '<span style="color:green">'+msg+'</span>',
					buttons: Ext.Msg.OK,
					minWidth: 400
				});
			} 
		});
	 }
	
	var restTpl = new Ext.XTemplate(
	    '<tpl for="."><div class="search-item" style="">',
	    	'<div style="margin-bottom:5px;">',
	    	'<div style="margin-bottom:0px;">',
		    	'<table width="100%" cellspacing="0" cellpadding="0">',
		    		'<tr>',
		    			'<td width="77%"><h3><span style="{points_rate:this.getPointsRateDisplayCss}"><img src="/shared/sir/images/goldaward.gif" width="16" height="16" ext:qtip="Business Partner"/>&nbsp;&nbsp;</span><a class="link" href="/singapore/restaurant/{name_identifier}*{id}/" target="_blank" ext:qtip="Click to view details of this restaurant.">{name}</a></h3></td>',
		    			'<td width="23%" style="{instant_confirmable:this.getInstantConfirmDisplayCss}"><input type="checkbox" name="instant_confirm_cb" id="instant_confirm_cb" onclick="clickInstantConfirmCB()"/> Instant confirmation</td>',
		    		'</tr>',
		    	'</table>',
		    '</div>',
	    	'<div style="line-height:16px;">',
		    	'<table width="100%" cellspacing="3">',
		    		'<tr valign="top">',
		    			'<td align="right" width="16%" style="font-size:11px;padding-right:3px;">Discount &#25240;&#25187;:</td>',
		    			'<td width="84%" style="font-size:11px;">{discount:this.getDiscountStr}</td>',
		    		'</tr>',
	        		'<tr valign="top" style="{other_benefits:this.getDisplayCss}">',
	        			'<td align="right" style="font-size:11px;padding-right:3px;">Other benefits:</td>',
	        			'<td style="font-size:11px;">{other_benefits:this.getOtherBenefitsStr}</td>',
	        		'</tr>',
		    		'<tr valign="top">',
		    			'<td align="right" style="font-size:11px;padding-right:3px;">Address &#22320;&#22336;:</td>',
		    			'<td style="font-size:11px;">{address}</td>',
		    		'</tr>',
		    		'<tr valign="top">',
		    			'<td align="right" style="font-size:11px;padding-right:3px;">Reservation &#39044;&#30041;:</td>',
		    			'<td style="font-size:11px;color:#F758C2;">Restaurant generally reserves your seat(s) for only 30 minutes, so pls be punctual.</td>',
		    		'</tr>',
		    	'</table>',
	    	'</div>',
	    '</div></tpl>',
        {
        	getDiscountStr: function(discount) {
        		if (discount && discount.length != 0) {
        			return '<font style="color:#FF7700;">'+discount+'</font>';
        		}
        		return 'No';
        	}
        },
        {
        	getOtherBenefitsStr: function(other_benefits) {
        		if (other_benefits && other_benefits.length != 0) {
        			return '<font style="color:#FF7700;">'+other_benefits+'</font>';
        		}
        		return 'No';
        	}
        },
        {
        	getPointsRateStr: function(points_rate) {
        		if (points_rate == 0) {
        			return points_rate;
        		}
        		return '<font style="color:#FF7700;">'+points_rate+'</font>';
        	}
        },
        {
        	getPointsRateDisplayCss: function(rate) {
        		if (rate!=0) {
        			return "";
        		}
        		return 'display:none;';
        	}
        },
		{
    		getDisplayCss: function(str){
    			if (str && str.length != 0) {
    				return '';
    			}
    			return 'display:none;';
    		}
    	},
    	{
    		getInstantConfirmDisplayCss: function(str) {
    			if (str && str.toLowerCase()=="y") {
    				return "";
    			}
    			return 'display:none;';
    		}
    	}
	);
	
	RestSummaryPanel = Ext.extend(Ext.DataView, {
		frame: true
		,loadingText: 'loading...'
		,itemSelector: 'table'
		,style:'padding-top:5px'
		,tpl: restTpl
	});
	
	var doLoadContact = function() {
    	var isUsernameValid = Ext.getCmp('login-form-username').isValid();
    	var isPasswordValid = Ext.getCmp('login-form-password').isValid();

    	var username = Ext.getCmp('login-form-username').getValue();
    	var password = Ext.getCmp('login-form-password').getValue();
    	if (username.length == 0) {
    		Ext.getCmp('login-form-username').markInvalid("User name cannot be empty.");
    		isUsernameValid = false;
    	}
    	
    	if (password.length == 0) {
    		Ext.getCmp('login-form-password').markInvalid("Password cannot be empty.");
    		isPasswordValid = false;
    	}
    	
    	if (err_username || !isUsernameValid || !isPasswordValid) {
    		errMsg = 'Some fields contain errors. Please correct them first.';
    		errWindow.show();
    		return;
    	}
		
		//backend check user credentials
		var err_username = false;
	    var loginStore = new Ext.data.JsonStore({
	    	url: '/RestaurantBookingServlet?action=doUserLogin'
	       ,root: 'results'
	       ,fields: ['status', 'msg']
	    });
	    
		loginStore.load({
			params: {
		        id: username,
		        pwd: password
		    },
		    
		    callback: function(records){
		    	for (var x = 0; x < records.length; x++){
		            var status = records[x].get('status');
		            if (status == 'failed') {
		            	errMsg = records[x].get('msg');
						errMsg = errMsg;
						errWindow.show();
						return;
		            }
		        }  
		                  
				//define user store
			    var userStore = new Ext.data.JsonStore({
			    	url: '/RestaurantBookingServlet?action=getUserInfoForRestaurantBooking'
			       ,root: 'results'
			       ,fields: ['user_id', 'title', 'real_name', 'mobile_ctry_code', 'mobile', 'email', 'prev_notify_via', 'prev_preferred_lang']
			    });

		    	userStore.load({
					params: {
				    },
				    callback: function(records){
				    	if (records && records.length != 0) {
				    		//hide sign in components
				    		Ext.getCmp('signin-checkbox').hide();
			    			for (var i=1; i<=4; i++) {
                				Ext.getCmp('existing-user-'+i).hide();
            				}
				    		
				            var title = records[0].get('title');
				            if (title && title.length != 0) {
					            Ext.getCmp('booking-form-title').setValue(title);
				            } else {
				            	Ext.getCmp('booking-form-title').setValue('Mr.');
				            }
				            
				            var real_name = Url.replaceEscape(records[0].get('real_name'));
				            if (real_name && real_name.length != 0) {
					            Ext.getCmp('booking-form-name').setValue(real_name);
				            } else {
				            	Ext.getCmp('booking-form-name').setValue('');
				            }
				            
				            var mobile_ctry_code = records[0].get('mobile_ctry_code');
				            Ext.getCmp('booking-form-mobile-ctrycode').setValue(mobile_ctry_code);
				            
				            var mobile = records[0].get('mobile');
				            Ext.getCmp('booking-form-mobile').setValue(mobile);
				            
				            var email = Url.replaceEscape(records[0].get('email'));
				            Ext.getCmp('booking-form-email').setValue(email);
				            
				            var prev_notify_via = Url.replaceEscape(records[0].get('prev_notify_via'));
				            if (prev_notify_via == 'Email') {
				            	prev_notify_via = 'E-mail';
				            }
				            if (prev_notify_via && prev_notify_via.length != 0 && prev_notify_via== 'E-mail') {
					            Ext.getCmp('booking-form-contactvia').setValue(prev_notify_via);
	                			Ext.getCmp('contact-phone-no').hide();
	                			Ext.getCmp('contact-phone-no-dash').hide();
	                			Ext.getCmp('contact-phone-no-ctrycode').hide();
	                			
	                			Ext.getCmp('contact-email').show();
				            } else {
				            	Ext.getCmp('booking-form-contactvia').setValue('SMS');
				            }
				            
				            var prev_preferred_lang = Url.replaceEscape(records[0].get('prev_preferred_lang'));
				            if (prev_preferred_lang && prev_preferred_lang.length != 0) {
					            Ext.getCmp('booking-form-preferred-language').setValue(prev_preferred_lang);
				            } else {
				            	Ext.getCmp('booking-form-preferred-language').setValue('English');
				            }
				    	}
				    }
		    		
		    	});
		    }
		});

	}
	
	var currentDate = new Date();
	var date = new Date();
	//define main view****************************************************************************************
    var panel = new Ext.FormPanel({
    	url:'/RestaurantBookingServlet',
    	id:'booking-form-panel',
        autoHeight: true,
        autoScroll: false,
        frame: true,
        layout: 'column',
        labelAlign:'top',

        items: [
        	{
	        	columnWidth:1,
	        	items:[
			        new RestSummaryPanel({
			            store: restStore
			        })
	        	]
        	},
        	{
            	columnWidth:.45,
            	layout:'column',
            	style:'padding-top:10px;',
            	items:[
		            {
		            	columnWidth:.5,
		            	layout:'form',
						bodyStyle:'padding:0 0 0 10px;',
		                items: [{
		                    xtype:'datefield',
		                    fieldLabel: 'Dining date &#29992;&#39184;&#26085;&#26399;',
		                    allowBlank: false,
		                    width: 100,
		                    value:currentDate.clearTime(),
		                    minValue:currentDate.clearTime(),
		                    maxValue:new Date(date.setMonth(date.getMonth()+noOfMonthsAhead)).clearTime(),
		                    maxText:'It is too far from current date. Call our hotline 6699-7071 if you have special requests.',
		                    disabledDatesText: 'This date is not allowed for instant confirmation.',
		                    disabledDaysText: 'This date is not allowed for instant confirmation.',
		                    //disabledDates:['10/15/2009','10/31/2009','11/01/2009','11/04/2009','12/01/2009'],
		                    //disabledDates:undefined,
		                    //disabledDays:[0,6],
		                    id: 'booking-form-date',
		                    name: 'booking-form-date',
		                    listeners:{
		                    	'blur':function(df) {
		                    		if (Ext.get('instant_confirm_cb').dom.checked) {
			                    		var disableLunch = false;
			                    		var disableDinner = false;
			                    		
			                    		var date = df.getValue();
			                    		var date2 = df.getValue();
										var tmr = new Date(date2.setDate(date2.getDate()+1)).clearTime();
			                    		//if date falls in weekend or friday
			                    		var day = date.getDay();
			                    		if (day == 6) {	//sat
		                    				if (disable_instant_confirm_sat_lunch) {
		                    					disableLunch = true;
		                    				}
		                    				if (disable_instant_confirm_sat_dinner) {
		                    					disableDinner = true;
		                    				}
			                    		} else if (day == 5) {	//fri
			                    			if (disable_instant_confirm_sat_eve) {
			                    				disableDinner = true;
			                    			}
			                    		} else if (day == 0) {	//sun
		                    				if (disable_instant_confirm_sun_lunch) {
		                    					disableLunch = true;
		                    				}
		                    				if (disable_instant_confirm_sun_dinner) {
		                    					disableDinner = true;
		                    				}
			                    		}
			                    		
			                    		//if day is in ph or ph eve
										if (!(disableLunch&&disableDinner)) {
			                    			if (disable_instant_confirm_ph_lunch || disable_instant_confirm_ph_dinner) {	//ph
			                    				//get all dates in ph store and compare
			                    				phStore.each(function(rec){
			                    					var datestring = rec.get('date');
													var d=Date.parse("datestring");	//d is time long
													var ph_date = new Date();
													ph_date.setTime(d);
													if (ph_date.getTime()==date.getTime()) {
					                    				if (disable_instant_confirm_ph_lunch) {
					                    					disableLunch = true;
					                    				}
					                    				if (disable_instant_confirm_ph_dinner) {
					                    					disableDinner = true;
					                    				}
													}
			                    				});
			                    			}
			                    			if (disable_instant_confirm_ph_eve) {	//ph eve
			                    				//get all dates in ph store and compare
			                    				phStore.each(function(rec){
			                    					var datestring = rec.get('date');
													var d=Date.parse(datestring);	//d is time long
													var ph_date = new Date();
													ph_date.setTime(d);
													
													//get selected_date+1 and compare
													if (ph_date.getTime()==tmr.getTime()) {
					                    				if (disable_instant_confirm_ph_eve) {
					                    					disableDinner = true;
					                    				}
													}
			                    				});
			                    			}
			                    		}
	
			                    		//if day is special
			                    		if (!(disableLunch&&disableDinner)&&disable_instant_confirm_has_other) {
											var instant_confirm_disabled_dates = rest_rec.get('instant_confirm_disabled_dates');
											if (instant_confirm_disabled_dates && instant_confirm_disabled_dates.length!=0) {
												for (var i=0; i<instant_confirm_disabled_dates.length; i++) {
													var instant_confirm_disabled_date = instant_confirm_disabled_dates[i];
													if (instant_confirm_disabled_date.date.toLowerCase()!='sat'
														&&instant_confirm_disabled_date.date.toLowerCase()!='sun'
														&&instant_confirm_disabled_date.date.toLowerCase()!='ph'
													) {
														var datestring = instant_confirm_disabled_date.date;
														var d=Date.parse(datestring);	//d is time long
														var special_date = new Date();
														special_date.setTime(d);
														
														if (special_date.getTime()==date.getTime()) {
						                    				if (instant_confirm_disabled_date.lunch.toLowerCase()=='y') {
						                    					disableLunch = true;
						                    				}
						                    				if (instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						                    					disableDinner = true;
						                    				}
														} else if (special_date.getTime()==tmr.getTime()) {
						                    				if (instant_confirm_disabled_date.eve.toLowerCase()=='y') {
						                    					disableDinner = true;
						                    				}
														}
													}
												}
											}
			                    		}
			                    		
			                    		var newTime = [];
			                    		if (!disableLunch) {
											for (var i=0; i<lunch_time.length; i++) {
												var array = [];
												array.push(lunch_time[i]);
												newTime.push(array);
											}
			                    		}
			                    		if (!disableDinner) {
											for (var i=0; i<dinner_time.length; i++) {
												var array = [];
												array.push(dinner_time[i]);
												newTime.push(array);
											}
			                    		}
	                    				var newTimeStore = new Ext.data.SimpleStore({
										    fields: ['time'],
										    data: newTime
										});
	                    				Ext.getCmp('booking-form-time').bindStore(newTimeStore);
	                    				
	                    				//trigger validation
	                    				triggerTimeValidation(newTimeStore);
		                    		}
		                    	}
		                    }
		                }]
		            }
		            ,{
		            	columnWidth:.5,
		            	layout:'form',
		                items: [{
		                    xtype:'combo',
		                    width: 100,
		                    fieldLabel: 'Dining time &#29992;&#39184;&#26102;&#38388;',
		                    editable: false,
						    mode: 'local',
		                    store: timeStore,
						    displayField: 'time',
		                    valueField: 'time',
						    triggerAction: 'all',
						    allowBlank: false,
		                    tpl: '<tpl for="."><div class="x-combo-list-item combo-list-item-lvl1">{time}</div></tpl>',
		                    id: 'booking-form-time',
		                    name: 'booking-form-time', 
		                    value:'7:00 PM',
		                    listeners:{
		                    	'blur':function(combo){
		                    		triggerTimeValidation(combo.store);
		                    	}
		                    }
		                }]
		            }
		            ,{
		            	columnWidth:.5,
		            	layout:'form',
						bodyStyle:'padding:0 0 0 10px;',
		                items: [{
		                    xtype:'numberfield',
		                    width: 100,
		                    fieldLabel: 'No of person &#20154;&#25968;',
			                allowBlank: false,
			                allowDecimals: false,
			                allowNegative: false,
		                    id: 'booking-form-noofperson',
		                    name: 'booking-form-noofperson'
		                }]
		            }
		            ,{
		            	columnWidth:.5,
		            	layout:'form',
		                items: [{
		                    xtype:'combo',
		                    width: 100,
		                    fieldLabel: 'VIP room &#21253;&#21410;',
		                    store: viproomStore,
						    displayField: 'viproom',
		                    valueField: 'viproom',
						    mode: 'local',
						    editable: false,
						    triggerAction: 'all',
						    tpl: '<tpl for="."><div class="x-combo-list-item combo-list-item-lvl1">{viproom}</div></tpl>',
		                    id: 'booking-form-viproom',
		                    name: 'booking-form-viproom',
			                value: "I don't mind"
		                }]
		            }
            	]
        	}
            ,{
            	columnWidth:.55,
            	layout:'form',
            	style:'padding-top:10px;',
                items: [{
                    xtype:'textarea',
                    border:false,
                    width: 330,
                    height: 70,
                    maxLength: maxLengthOtherRequirements,
                    fieldLabel: 'Other requirements &#20854;&#20182;&#35201;&#27714; (<span id="charcount">'+maxLengthOtherRequirements+'</span> chars left)',
                    emptyText: otherRequirementsEmptyText,
                    id: 'booking-form-other-requirements',
                    name: 'booking-form-other-requirements',
                    enableKeyEvents:true,
                    value:'',
                    listeners: {
                    	'keyup': function(cmp, e) {
                    		var textLength = cmp.getValue().length;
                    		var left = maxLengthOtherRequirements-textLength;
                    		if (left < 0) {
                    			left = '<span style="color:red">'+left+'</span>';
                    		}
                    		Ext.get('charcount').dom.innerHTML = left;
                    	}
                    }
	                
                }]
            }
            ,{
            	columnWidth:1,
            	height:5,
            	style:'line-height:5px;border-bottom:1px solid #eeeeee;',
            	html:'&nbsp;'
            }
        	,{
        		columnWidth:1,
        		id:'signin-checkbox',
            	layout:'form',
		        labelWidth:1,
			    border:false,
            	bodyStyle:'padding:0 10px;',
                items: [{
            		xtype: 'checkbox',
                	id:'signin-existing-user', 
                	checked:false,
                	boxLabel: 'Sign in to load your contact details. &#36890;&#36807;&#29992;&#25143;&#21517;&#39044;&#35746;&#12290;',
			        fieldLable:'', 
			        labelStyle:'display:none;',
			        labelSeparator:'',
                	inputValue: 1,
                	listeners:{
                		'check': function(cb, checked) {
                			if (checked) {
                				for (var i=1; i<=4; i++) {
	                				Ext.getCmp('existing-user-'+i).show();
                				}
                			} else {
                				for (var i=1; i<=4; i++) {
	                				Ext.getCmp('existing-user-'+i).hide();
                				}
                			}
                		}
                	}
                }]
        	}
            ,{
            	columnWidth:.06,
            	id:'existing-user-1',
            	hidden:true,
            	html:'&nbsp'
            }
            ,{
            	columnWidth:.38,
            	layout:'form',
            	id:'existing-user-2',
            	hidden:true,
                labelWidth: 100,
                labelAlign:'left',
                items: [{
                    xtype:'textfield',
                    id:'login-form-username',
			        height:20,
                    width: 100,
                    maxLength: 16,
                    fieldLabel: '<span style="font-size:11px;">User name &#29992;&#25143;&#21517;</span>',
    				validationDelay: validationDelayInMillis,
					validator: function(value){
						return validateUsername(value);
					}
                }]
            }
            ,{
            	columnWidth:.365,
            	layout:'form',
            	id:'existing-user-3',
            	hidden:true,
		        labelWidth:90,
                labelAlign:'left',
	            keys: [{
		            key: Ext.EventObject.ENTER,
		            fn: doLoadContact
		        }],
                items: [{
                    xtype:'textfield',
                    id:'login-form-password',
			        height:20,
				    width:100,
			        fieldLabel:'<span style="font-size:11px;">Password &#23494;&#30721;</span>',
	                inputType: 'password',
                    maxLength: 20,
    				validationDelay: validationDelayInMillis,
    				validator: function(value){
						return validatePassword(value);
					}
                }]
            }
            ,{
            	columnWidth:.196,
            	id:'existing-user-4',
            	hidden:true,
            	items:[{
            		xtype:'button',
            		text:'<span style="font-size:11px;">Load</span>',
            		handler:doLoadContact
            	}]
            }
            ,{
            	columnWidth:1,
            	height:5,
            	style:'line-height:5px;'
            }
            ,{
            	columnWidth:.09,
            	bodyStyle:'padding:0 0 0 10px;',
            	layout:'form',
                items: [{
                    xtype:'combo',
                	width:44,
                	listWidth: 44,
                    fieldLabel: 'Contact',
                    labelSeparator: '',
                    store: titleStore,
				    displayField: 'title',
                    valueField: 'title',
				    mode: 'local',
				    editable: false,
				    triggerAction: 'all',
				    tpl: '<tpl for="."><div class="x-combo-list-item combo-list-item-lvl1">{title}</div></tpl>',
                    id: 'booking-form-title',
                    name: 'booking-form-title',
                    value: 'Mr.'
                }]
            }
            ,{
            	columnWidth:.21,
            	layout: 'form',
                items: [{
                    xtype:'textfield',
                    width: 100,
                    fieldLabel: 'name &#32852;&#31995;&#20154;',
                    allowBlank: false,
                    id: 'booking-form-name',
                    name: 'booking-form-name'
                }]
            }
            ,{
            	columnWidth:.22,
            	layout:'form',
                items: [{
                    xtype:'combo',
                    width: 110,
                    fieldLabel: 'Confirm via &#30830;&#35748;',
                    store: contactviaStore,
				    displayField: 'contactvia',
                    valueField: 'contactvia',
				    mode: 'local',
				    editable: false,
				    triggerAction: 'all',
				    tpl: '<tpl for="."><div class="x-combo-list-item combo-list-item-lvl1">{contactvia}</div></tpl>',
                    id: 'booking-form-contactvia',
                    name: 'booking-form-contactvia',
	                value: "SMS",
	                listeners:{
	                	'select': function(combo, record, index) {
	                		var value = combo.getValue();
	                		if (value == 'E-mail') {
	                			Ext.getCmp('contact-phone-no').hide();
	                			Ext.getCmp('contact-phone-no-dash').hide();
	                			Ext.getCmp('contact-phone-no-ctrycode').hide();
	                			
	                			Ext.getCmp('contact-email').show();
	                		} else {
	                			Ext.getCmp('contact-phone-no').show();
	                			Ext.getCmp('contact-phone-no-dash').show();
	                			Ext.getCmp('contact-phone-no-ctrycode').show();

	                			Ext.getCmp('contact-email').hide();
	                		}
	                	}
	                }
                }]
            }
            ,{
            	columnWidth:.063,
            	id:'contact-phone-no-ctrycode',
            	layout:'form',
            	labelWidth:50,
                items: [{
                    xtype:'numberfield',
                    width: 35,
                    fieldLabel: 'Phone',
                    labelSeparator: '',
                    autoScroll:false,
	                allowBlank: false,
	                allowDecimals: false,
	                allowNegative: false,
                    maxLength: 3,
                    value:'65',
                    id: 'booking-form-mobile-ctrycode',
                    name: 'booking-form-mobile-ctrycode'
                }]
            }
            ,{
            	columnWidth:.01,
            	id:'contact-phone-no-dash',
            	style:'padding-top:23px',
            	html:'-'
            }
            ,{
            	columnWidth:.21,
            	id:'contact-phone-no',
            	layout: 'form',
                items: [{
                    xtype:'numberfield',
                    width: 100,
                    fieldLabel: 'number &#30005;&#35805;',
	                allowDecimals: false,
	                allowNegative: false,
                    maxLength: 16,
                    id: 'booking-form-mobile',
                    name: 'booking-form-mobile'
                }]
            }
            ,{
            	columnWidth:.283,
            	id:'contact-email',
            	layout:'form',
            	hidden:true,
                items: [{
                    xtype:'textfield',
                    width: 145,
                    fieldLabel: 'E-mail &#30005;&#23376;&#37038;&#20214;',
    				maxLength: 128,
    				validationDelay: validationDelayInMillis,
                    validator: function(value){
						return validateEmail(value);
					},
                    id: 'booking-form-email',
                    name: 'booking-form-email'
                }]
            }
            ,{
            	columnWidth:.18,
            	layout:'form',
                items: [{
                    xtype:'combo',
                    width: 110,
                    fieldLabel: 'Preferred &#35821;&#35328;',
                    store: preferredLanguageStore,
				    displayField: 'language',
                    valueField: 'language',
				    mode: 'local',
				    editable: false,
				    triggerAction: 'all',
				    tpl: '<tpl for="."><div class="x-combo-list-item combo-list-item-lvl1">{language}</div></tpl>',
                    id: 'booking-form-preferred-language',
                    name: 'booking-form-preferred-language',
	                value: "English"
                }]
            }
            ,{
            	columnWidth:1,
            	items:[
	            	{
		            	xtype:'hidden',
		            	value: 'saveRestaurantBooking',
		            	name: 'action'
	            	}
	            	,{
		            	xtype:'hidden',
		            	value: restId,
		            	name: 'rest-id'
	            	}
	            	,{
		            	xtype:'hidden',
		            	value: bookingId,
		            	name: 'booking-id'
	            	}
            	]
            }
            ,{
            	columnWidth:1,
            	bodyStyle:'padding:0 0 0 10px;',
            	html:'P.S. Use international format for phone number, e.g. 65-91234567 where 65 is the country code for Singapore.'
            }
            ,{
            	columnWidth:1,
            	height:10,
            	style:'line-height:10px;'
            }
            ,{//******************************verification code********************************************
        		columnWidth:.32,
        		id:'vcode-1',
		        hidden:true,
		        bodyStyle:'padding:0 0 0 10px;',
        		layout:'form',
        		labelAlign:'left',
        		items:[
        			{
        				xtype:'textfield',
		                fieldLabel: 'Verification code',
		                validationDelay: validationDelayInMillis,
        				width: 60,
        				minLength: 4,
        				minLengthText: 'Length must be 4.',
        				maxLength: 4,
        				maxLengthText: 'Length must be 4.',
        				name: 'booking-form-vcode',
		                id: 'booking-form-vcode'
        			}
        		]
            }
            ,{
        		columnWidth:.26,
        		id:'vcode-2',
		        hidden:true,
        		items:[
        			{
	                	xtype:'panel',
				        border: false,
	                	style:'font-size:12px;',
	                    html: '<img src="ValidationJPGServlet?action=rest_booking_instant_confirm_vcode&t='+(new Date()).getTime()+'" width="150" height="23" align="top" border="0" />'
        			}
        		]
            }
            ,{
        		columnWidth:.42,
        		id:'vcode-3',
		        hidden:true,
        		items:[
        			{
	                	xtype:'panel',
				        border: false,
	                	style:'font-size:11px;',
	                    html: 'Letters are not case-sensitive'
        			}
        		]
            }//end verification code
            ,{
            	columnWidth:1,
            	height: 20
            }
	    ]
	    ,buttons: [
	    	{
	    		id: 'submit-btn',
	    		minWdith:100,
	    		text: '<b>Book</b>',
	    		handler: doSubmit
	    	},
	        {
	        	text: '<b>Close</b>',
	    		minWdith:100,
	            handler: function(){Ext.getCmp('restaurant-booking-form').destroy()}
	        }
	    ]
    });
    
    panel.on('render', function(){
    	if (bookingId && bookingId.length!=0) {
    		//hide sign in components
    		Ext.getCmp('signin-checkbox').hide();
			for (var i=1; i<=4; i++) {
				Ext.getCmp('existing-user-'+i).hide();
			}

			bookingStore.load({
				params: {
			    },
			    callback: function(records){
			    	diningDate = records[0].get('dining_date2');
					diningTime = records[0].get('dining_time2');
					if (diningTime.charAt(0) == '0') {
						diningTime = diningTime.substring(1, diningTime.length);
					}
			    	Ext.getCmp('booking-form-date').setValue(diningDate);
					Ext.getCmp('booking-form-time').setValue(diningTime);
			    	
			    	noOfPerson = records[0].get('no_of_persons');
			    	Ext.getCmp('booking-form-noofperson').setValue(noOfPerson);
			    	
			    	vipRoom = Url.replaceEscape(records[0].get('viproom'));
			    	Ext.getCmp('booking-form-viproom').setValue(vipRoom);
			    	
			    	otherRequirements = Url.replaceEscape(records[0].get('other_requirements'));
			    	Ext.getCmp('booking-form-other-requirements').setValue(otherRequirements);
			    	
		            contactTitle = Url.replaceEscape(records[0].get('title'));
		            Ext.getCmp('booking-form-title').setValue(contactTitle);
		            
		            contactName = Url.replaceEscape(records[0].get('name'));
		            if (contactName && contactName.length != 0) {
			            Ext.getCmp('booking-form-name').setValue(contactName);
		            }
		            
		            contactMobileCtryCode = records[0].get('mobile_ctry_code');
		            Ext.getCmp('booking-form-mobile-ctrycode').setValue(contactMobileCtryCode);
		            
		            contactMobile = records[0].get('mobile');
		            Ext.getCmp('booking-form-mobile').setValue(contactMobile);
		            
		            contactEmail = Url.replaceEscape(records[0].get('email'));
		            Ext.getCmp('booking-form-email').setValue(contactEmail);
		            
		            contactVia = records[0].get('contact_via');
		            if (contactVia && contactVia.length != 0) {
			            if (contactVia == 'Email') {
			            	contactVia = 'E-mail';
                			Ext.getCmp('contact-phone-no').hide();
                			Ext.getCmp('contact-phone-no-dash').hide();
                			Ext.getCmp('contact-phone-no-ctrycode').hide();
                			
                			Ext.getCmp('contact-email').show();
			            }
			            Ext.getCmp('booking-form-contactvia').setValue(contactVia);
		            }
		            
		            contactPreferredLanguage = records[0].get('diner_preferred_language');
		            Ext.getCmp('booking-form-preferred-language').setValue(contactPreferredLanguage);
			    }
			})
		
    	} else {
	    	userStore.load({
				params: {
			    },
			    callback: function(records){
			    	if (records && records.length != 0) {
			    		//hide sign in components
			    		Ext.getCmp('signin-checkbox').hide();
		    			for (var i=1; i<=4; i++) {
	        				Ext.getCmp('existing-user-'+i).hide();
	    				}
			    		
			            var title = records[0].get('title');
			            if (title && title.length != 0) {
				            Ext.getCmp('booking-form-title').setValue(title);
			            }
			            
			            var real_name = Url.replaceEscape(records[0].get('real_name'));
			            if (real_name && real_name.length != 0) {
				            Ext.getCmp('booking-form-name').setValue(real_name);
			            }
			            
			            var mobile_ctry_code = records[0].get('mobile_ctry_code');
			            Ext.getCmp('booking-form-mobile-ctrycode').setValue(mobile_ctry_code);
			            
			            var mobile = records[0].get('mobile');
			            Ext.getCmp('booking-form-mobile').setValue(mobile);
			            
			            var email = Url.replaceEscape(records[0].get('email'));
			            Ext.getCmp('booking-form-email').setValue(email);
			            
			            var prev_notify_via = Url.replaceEscape(records[0].get('prev_notify_via'));
			            if (prev_notify_via && prev_notify_via.length != 0) {
				            if (prev_notify_via == 'Email') {
				            	prev_notify_via = 'E-mail';
	                			Ext.getCmp('contact-phone-no').hide();
	                			Ext.getCmp('contact-phone-no-dash').hide();
	                			Ext.getCmp('contact-phone-no-ctrycode').hide();
	                			
	                			Ext.getCmp('contact-email').show();
				            }
				            Ext.getCmp('booking-form-contactvia').setValue(prev_notify_via);
			            }
			            
			            var prev_preferred_lang = Url.replaceEscape(records[0].get('prev_preferred_lang'));
			            if (prev_preferred_lang && prev_preferred_lang.length != 0) {
				            Ext.getCmp('booking-form-preferred-language').setValue(prev_preferred_lang);
			            }
			    	}
			    }
	    		
	    	});
    	}
    });
    
	var win = Ext.getCmp('restaurant-booking-form');
	if (win) {
		win.show();
		return;
	}
	
	//Create window*****************************************************************************
    var booking_form = new Ext.Window({
    	id: 'restaurant-booking-form',
        title: '<span style="font-size:12px;">Restaurant Booking Form</span>',
        width: 650,
        height:'auto',
        draggable:false,
        autoScroll:true,
        border:false,
        buttonAlign:'center',
		items:[
			panel
		]

    });
    restStore.on('load', function(store, records){
    	if (records && records.length != 0) {
	    	rest_rec = records[0];
	    	Ext.getCmp('restaurant-booking-form').setTitle('<span style="font-size:12px;">Restaurant Booking Form' + ' - ' + rest_rec.get('name') + '</span>');
    	}
    });
    booking_form.on('show', function(){
    	restStore.load();
    });
	booking_form.show();
	
	
	//validate username***************************************************
	function validateUsername(username) {
		if (username=="") {
			return "";
		}
		var msg = checkUsername2(username);
		if (msg.length != 0) {
			return msg;
		}
		
		//Create store to check user login*********************************************************
	    var store = new Ext.data.JsonStore({
	    	url: '/RestaurantBookingServlet?action=checkUsernameAvailability'
	       ,root: 'results'
	       ,fields: ['status', 'exist', 'msg']
	    });

		//backend check user availability
		store.load({
			params: {
		        username: username
		    },
		    
		    callback: function(records){
		    	for (var x = 0; x < records.length; x++){
		            var status = records[x].get('status');
		            var exist = records[x].get('exist');
		            if (status == 'success' && exist == 'no') {
		            	Ext.getCmp('login-form-username').markInvalid("This username doesn't exist.");
						err_username = true;
						return;
		            }
		            if (status == 'success' && exist == 'yes') {
						err_username = false;
						return;
		            }
		        }  
		    }
		});
		return true;
	}
	
	//validate password***************************************************
	function validatePassword() {
		var cmp = Ext.getCmp('login-form-password');
		var password = cmp.getValue();
		var msg = checkPassword2(password);
		if (msg.length != 0) {
			return msg;
		}
		return true;
	}

	//validate email*******************************************************
	function validateEmail() {
		var cmp = Ext.getCmp('booking-form-email');
		var email = cmp.getValue();
		if (email.length == 0) {
			return true;
		}
		var msg = checkEmail(email);
		if (msg.length != 0) {
			return msg;
		}
		return true;
	}

}

function clickInstantConfirmCB() {
	var cb_checked = Ext.get('instant_confirm_cb').dom.checked;
	if (cb_checked) {
		if (!rest_rec) {
			return;
		}
		if (!isPHStoreLoaded) {
			alert('Error loading criteria for instant confirmation. Please reload the page and try again.');
			Ext.get('instant_confirm_cb').dom.checked = false;
			return;
		}
		Ext.getCmp('booking-form-viproom').disable();
		Ext.getCmp('booking-form-other-requirements').disable();
		
		//set max no of pax
		var instant_confirm_no_of_pax = rest_rec.get('instant_confirm_no_of_pax');
		Ext.getCmp('booking-form-noofperson').maxValue = instant_confirm_no_of_pax;
		var value = Ext.getCmp('booking-form-noofperson').getValue();
		if (value) {
			Ext.getCmp('booking-form-noofperson').setValue(value);	//to trigger validation
		}
		
		//set time
		var instant_confirm_lunch_lb = rest_rec.get('instant_confirm_lunch_lb');
		var instant_confirm_lunch_ub = rest_rec.get('instant_confirm_lunch_ub');
		var instant_confirm_dinner_lb = rest_rec.get('instant_confirm_dinner_lb');
		var instant_confirm_dinner_ub = rest_rec.get('instant_confirm_dinner_ub');
		
		var newTimeList = [];
		var index1 = timeStore.find('time', instant_confirm_lunch_lb);
		var index2 = timeStore.find('time', instant_confirm_lunch_ub);
		for (var i=index1; i<index2+1; i++) {
			var rec = timeStore.getAt(i);
			lunch_time.push(rec.get('time'));
		}
		var index3 = timeStore.find('time', instant_confirm_dinner_lb);
		var index4 = timeStore.find('time', instant_confirm_dinner_ub);
		for (var i=index3; i<index4+1; i++) {
			var rec = timeStore.getAt(i);
			dinner_time.push(rec.get('time'));
		}
		
		for (var i=0; i<lunch_time.length; i++) {
			var array = [];
			array.push(lunch_time[i]);
			newTimeList.push(array);
		}
		for (var i=0; i<dinner_time.length; i++) {
			var array = [];
			array.push(dinner_time[i]);
			newTimeList.push(array);
		}
		var newTimeStore = new Ext.data.SimpleStore({
		    fields: ['time'],
		    data: newTimeList
		});
		Ext.getCmp('booking-form-time').bindStore(newTimeStore);

		//set disabled dates
		var disabled_dates = [];
		var disabled_days = [];
		var instant_confirm_disabled_dates = rest_rec.get('instant_confirm_disabled_dates');
		if (instant_confirm_disabled_dates && instant_confirm_disabled_dates.length!=0) {
			for (var i=0; i<instant_confirm_disabled_dates.length; i++) {
				var instant_confirm_disabled_date = instant_confirm_disabled_dates[i];
				if (instant_confirm_disabled_date.date.toLowerCase() == 'sat') {
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y' && instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						disabled_days.push(6);
					}
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y') {
						disable_instant_confirm_sat_lunch = true;
					}
					if (instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						disable_instant_confirm_sat_dinner = true;
					}
					if (instant_confirm_disabled_date.eve.toLowerCase()=='y') {
						disable_instant_confirm_sat_eve = true;
					}
				} else if (instant_confirm_disabled_date.date.toLowerCase() == 'sun') {
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y' && instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						disabled_days.push(0);
					}
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y') {
						disable_instant_confirm_sun_lunch = true;
					}
					if (instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						disable_instant_confirm_sun_dinner = true;
					}
				} else if (instant_confirm_disabled_date.date.toLowerCase() == 'ph') {
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y' && instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						phStore.each(function(rec){
							disabled_dates.push(rec.get('date'));
						});
					}
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y') {
						disable_instant_confirm_ph_lunch = true;
					}
					if (instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						disable_instant_confirm_ph_dinner = true;
					}
					if (instant_confirm_disabled_date.eve.toLowerCase()=='y') {
						disable_instant_confirm_ph_eve = true;
					}
				} else {
					var date = instant_confirm_disabled_date.date;
					if (instant_confirm_disabled_date.lunch.toLowerCase()=='y' && instant_confirm_disabled_date.dinner.toLowerCase()=='y') {
						disabled_dates.push(date);
					}
					disable_instant_confirm_has_other = true;
				}
			}
		}
		if (disabled_dates.length==0) {
			disabled_dates = undefined;
		}
		if (disabled_days.length==0) {
			disabled_days = undefined;
		}
		Ext.getCmp('booking-form-date').setDisabledDates(disabled_dates);
		Ext.getCmp('booking-form-date').setDisabledDays(disabled_days);
		Ext.getCmp('booking-form-date').fireEvent('blur', Ext.getCmp('booking-form-date'));
		Ext.getCmp('booking-form-date').setValue(Ext.getCmp('booking-form-date').getValue());
		//triggerTimeValidation(newTimeStore);	//not needed because date field fire event above will trigger
		
		//show vcode
		for (var i=1; i<4; i++) {
			Ext.getCmp('vcode-'+i).show();
		}
	} else {
		Ext.getCmp('booking-form-viproom').enable();
		Ext.getCmp('booking-form-other-requirements').enable();
		
		//set max no of pax
		Ext.getCmp('booking-form-noofperson').maxValue = Number.MAX_VALUE;
		var value = Ext.getCmp('booking-form-noofperson').getValue();
		if (value) {
			Ext.getCmp('booking-form-noofperson').setValue(value);	//to trigger validation
		}
		
		disable_instant_confirm_sat_lunch = false;
		disable_instant_confirm_sat_dinner = false;
		disable_instant_confirm_sat_eve = false;
		disable_instant_confirm_sun_lunch = false;
		disable_instant_confirm_sun_dinner = false;
		disable_instant_confirm_ph_lunch = false;
		disable_instant_confirm_ph_dinner = false;
		disable_instant_confirm_ph_eve = false;
		disable_instant_confirm_has_other = false;

		//set disabled dates
		Ext.getCmp('booking-form-date').setDisabledDays(undefined);
		Ext.getCmp('booking-form-date').setDisabledDates(['11/05/2000']);	//just some random date passed, this is because setDisabledDays(undefined) doesn't work, should be a bug
		Ext.getCmp('booking-form-date').clearInvalid();
		
		Ext.getCmp('booking-form-time').bindStore(timeStore);
		Ext.getCmp('booking-form-time').clearInvalid()
		timeError = false;
		
		//hide vcode
		for (var i=1; i<4; i++) {
			Ext.getCmp('vcode-'+i).hide();
		}
	}
}

function triggerTimeValidation(timestore) {
	var value = Ext.getCmp('booking-form-time').getValue();
	var index = timestore.find('time', value);
	if (index < 0) {
		Ext.getCmp('booking-form-time').markInvalid('This time is not available.');
		timeError = true;
	} else {
		timeError = false;
		Ext.getCmp('booking-form-time').clearInvalid();
	}
}