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);
        }
    }
});

//define stores*******************************************************************************************
var userStore = new Ext.data.JsonStore({
	url: '/RestaurantServlet?action=getUserInfoForRestaurantBooking'
   ,root: 'results'
   ,fields: ['user_id', 'title', 'real_name', 'mobile_ctry_code', 'mobile', 'email', 'prev_notify_via', 'prev_preferred_lang', 'is_agent']
});

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: '/RestaurantServlet?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;
var has_user_signin = false;
function showRestaurantBookingForm(restId, bookingId) {
	var maxLengthOtherRequirements = 500;
	var validationDelayInMillis = 1000;
	var req_reg = true;
	var otherRequirementsEmptyText = 'We will do our best to help you.';
	var is_agent = '';
	
	//define stores*******************************************************************************************
    var restStore = new Ext.data.JsonStore({
    	url: '/RestaurantServlet?action=getRestaurantSummaryForBooking'
       ,root: 'results'
       ,totalProperty: 'totalCount'
       ,id: 'id'
       ,fields: ['id', 'name', 'phone', 'photo', 'district', 'cuisine', 'discount', 'occasion', 'viproom', 'expense', 'address', 'points_rate', 'other_benefits', 'name_identifier', 'other_notes',
       			'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', 'instant_confirm_disabled_dates'
       ]
    });

	//define stores*******************************************************************************************
    var bookingStore = new Ext.data.JsonStore({
    	url: '/RestaurantServlet?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']
    });
	
	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"], ['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:red;font: 12px;'>"+errMsg+"</div>";
	});
	
	//handle submit*****************************************************************************************
	var errEmailID = false;
	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();
    	var isEmailIDVisible = Ext.getCmp('emailid-2').isVisible();
    	var isEmailIDValid = true;
    	if (isEmailIDVisible) {
    		isEmailIDValid = Ext.getCmp('booking-form-email_id').isValid();
    		if (errEmailID) {
    			isEmailIDValid = false;
    		}
    	}
    	if (timeError || !isDateValid || !isNoOfPersonValid || !isNameValid || ((contactvia=='SMS' || contactvia=='Phone') && !isMobileValid) || (contactvia=='Email' && !isEmailValid) || !isOtherRequirementsValid || !isEmailIDValid) {
    		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;
			}
		}
		
		var mobile_ctry_code = Ext.getCmp('booking-form-mobile-ctrycode').getValue();
		if ((contactvia == 'SMS' || contactvia == 'Phone') && mobile_ctry_code == '65') {
			var str_mobile = new String(mobile);
			if (str_mobile.length != 8 || (str_mobile.charAt(0)!='8'&&str_mobile.charAt(0)!='9')) {
				Ext.getCmp('booking-form-mobile').markInvalid("Mobile number is invalid");
	    		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();
		Ext.getCmp('login-form-username').disable();
		Ext.getCmp('login-form-password').disable();
    	if (!isEmailIDVisible) {
    		Ext.getCmp('booking-form-email_id').disable();
    	}
    	
		panel.form.submit({
			waitMsg:'Saving...', 
			reset: false, 
			failure: function(form, action) { 
				Ext.getCmp('submit-btn').enable();
				Ext.getCmp('login-form-username').enable();
				Ext.getCmp('login-form-password').enable();
				Ext.getCmp('booking-form-email_id').enable();
				var msg = action.result.msg;
				var type = action.result.type;
				Ext.Msg.show({
					title: 'Failure', 
					msg: '<span style="color:red;">'+msg+'</span>',
					buttons: Ext.Msg.OK,
					minWidth: 400
				});
				if (type=='sign_in_required') {
					Ext.getCmp('signin-existing-user').setValue(true);
				}
			}, 
			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 grid = Ext.getCmp('rest-bookings-grid');
				if (grid) {
					grid.store.reload();
				}
			} 
		});

	 }
	
	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}/" 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" style="{phone:this.getDisplayCss}">',
		    			'<td align="right" width="16%" style="font-size:11px;padding-right:3px;">Phone &#30005;&#35805;:</td>',
		    			'<td width="84%" style="font-size:11px;">{phone}</td>',
		    		'</tr>',
		    		'<tr valign="top" style="{discount:this.getDisplayCss}">',
		    			'<td align="right" width="16%" style="font-size:11px;padding-right:3px;"><b>Discount &#25240;&#25187;</b>:</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" width="16%" style="font-size:11px;padding-right:3px;">Address &#22320;&#22336;:</td>',
		    			'<td width="84%" style="font-size:11px;">{address}</td>',
		    		'</tr>',
		    		'<tr valign="top" style="{other_notes:this.getDisplayCss}">',
		    			'<td align="right" style="font-size:11px;padding-right:3px;padding-top:2px;"><b>Note &#27880;&#24847;:</b></td>',
		    			'<td style="font-size:11px;padding-left:3px;" class="red_ul">{other_notes:this.replaceEscape}</td>',
		    		'</tr>',
		    	'</table>',
	    	'</div>',
	    '</div></tpl>',
        {
        	getDisplayCss: function(str) {
        		if (str && str.length!=0) {
        			return "";
        		}
        		return 'display:none;';
        	}
        	,getDiscountStr: function(discount) {
        		if (discount && discount.length != 0) {
        			return '<font style="color:#000000;">'+discount+'</font>';
        		}
        		return 'No';
        	}
        	,getOtherBenefitsStr: function(other_benefits) {
        		if (other_benefits && other_benefits.length != 0) {
        			return '<font style="color:#000000;">'+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;';
    		}
     		,replaceEscape: function(str){
    			return Url.replaceEscape(str);
    		}
    	}
	);
	
	RestSummaryPanel = Ext.extend(Ext.DataView, {
		frame: true
		,loadingText: 'loading...'
		,itemSelector: 'table'
		,style:''
		,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: '/CommonServlet?action=doUserLogin'
	       ,root: 'results'
	       ,fields: ['success', 'msg']
	    });
	    
		loginStore.load({
			params: {
		        id: username,
		        pwd: password
		    },
		    
		    callback: function(records){
		    	for (var x = 0; x < records.length; x++){
		            var status = records[x].get('success');
		            if (status == 'false') {
		            	errMsg = records[x].get('msg');
						errWindow.show();
						return;
		            }
		        }  
		                  
				loadUserContacts();
		    }
		});

	}
	
    var ds = new Ext.data.JsonStore({
    	url: '/RestaurantServlet?action=getRestaurantSummary'
       ,root: 'results'
       ,totalProperty: 'totalCount'
       ,id: 'id'
       ,fields: ['id', 'name', 'phone', 'photo', 'district', 'cuisine', 'discount', 'occasion', 'viproom', 'expense', 'address', 'points_rate', 'other_benefits', 'buffet']
    });

    // Custom rendering Template
    var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item" style="line-height:18px;">',
        	'<h3>',
        		'<table width="96%">',
        			'<tr valign="middle">',
        				'<td width="98%">{name}</td>',
        				'<td width="2%" align="right"><span style="{points_rate:this.getPointsRateDisplayCss}"><img src="/shared/sir/images/goldaward.gif" width="16" height="16" ext:qtip="Business Partner"/></td>',
        			'</tr>',
        		'</table>',
        	'</h3>',
        	'<table width="96%">',
        		'<tr valign="top" style="{phone:this.getDisplayCss}">',
        			'<td width="15%" class="sub-info">Phone:</td>',
        			'<td width="85%" class="sub-info">{phone}</td>',
        		'</tr>',
        		'<tr valign="top">',
        			'<td width="15%" class="sub-info">Discount:</td>',
        			'<td width="85%" class="sub-info">{discount:this.getBenefitStr}</td>',
        		'</tr>',
        		'<tr valign="top" style="{other_benefits:this.getDisplayCss}">',
        			'<td class="sub-info">Other benefits:</td>',
        			'<td class="sub-info">{other_benefits:this.getBenefitStr}</td>',
        		'</tr>',
        		'<tr valign="top">',
        			'<td class="sub-info">Points rate:</td>',
        			'<td class="sub-info">{points_rate:this.getPointsRateStr}</td>',
        		'</tr>',
        		'<tr valign="top">',
        			'<td class="sub-info">Cuisine:</td>',
        			'<td class="sub-info">{cuisine}</td>',
        		'</tr>',
	    		'<tr valign="top">',
	    			'<td class="sub-info">VIP room:</td>',
	    			'<td class="sub-info">{viproom}</td>',
	    		'</tr>',
	    		'<tr valign="top" style="{buffet:this.getDisplayCss}">',
	    			'<td class="sub-info">Buffet:</td>',
	    			'<td class="sub-info">{buffet}</td>',
	    		'</tr>',
	    		'<tr valign="top">',
	    			'<td class="sub-info">Address:</td>',
	    			'<td class="sub-info">{address}</td>',
	    		'</tr>',
        	'</table>',
        '</div></tpl>',
        {
        	getBenefitStr: function(benefit) {
        		if (benefit && benefit.length != 0) {
        			return '<div style="color:#FF7700;">'+benefit+'</div>';
        		}
        		return 'No';
        	}
        },
        {
        	getPointsRateStr: function(points_rate) {
        		if (points_rate == 0) {
        			return points_rate;
        		}
        		return '<div style="color:#FF7700;">'+points_rate+'</div>';
        	}
        },
        {
        	getPointsRateDisplayCss: function(rate) {
        		if (rate!=0) {
        			return "";
        		}
        		return 'display:none;';
        	}
        },
		{
    		getDisplayCss: function(str){
    			if (str && str.length != 0) {
    				return '';
    			}
    			return 'display:none;';
    		}
    	}
    );

	var currentDate = new Date();
	var date = new Date();
	//define main view****************************************************************************************
    var panel = new Ext.FormPanel({
    	url:'/RestaurantServlet',
    	id:'booking-form-panel',
        autoHeight: true,
        autoScroll: false,
        frame: true,
        layout: 'column',
        labelAlign:'top',

        items: [
        	{
	        	columnWidth:1,
	        	items:[
		    		new Ext.ux.BubblePanel({
		    			style:'padding:0 10px 15px;font-size;11px;',
		    			bodyStyle:'padding:0 10px;line-height:16px;',
		    			html:'<span style="font-size:12px;color:#333333;"><b>Note: </b>Reservation Operating Hours: 9:30am - 6:30pm, daily<br/>' +
		    				'SMS confirmation will be sent within 15 minutes for bookings, subjected to availability and operating hours of the establishment. Bookings made outside operating hours will be processed ASAP once operations resume.'
		    		})
	        	]
        	},
        	{
	        	columnWidth:1,
	        	layout:'form',
            	style:'padding-top:10px;padding-left:12px;',
	        	labelAlign:'left',
	        	labelWidth:120,
	        	items:[
	        		{
	                	xtype: 'combo',
				        store: ds,
				        fieldLabel: 'Restaurant search',
				        emptyText: '',
				        displayField:'name',
				        typeAhead: false,
				        loadingText: 'Searching...',
				        width: 475,
						bodyStyle:'',
				        pageSize:10,
				        minChars: 1,
				        queryDelay: 1000,
				        hideTrigger:true,
				        emptyText: "Enter part of the restaurant name to start search",
				        tpl: resultTpl,
				        itemSelector: 'div.search-item'
				        ,onSelect: function(record){ // override default onSelect to do redirect
				            this.setValue('');
				            this.collapse();
					    	restStore.load({
								params: {
							        'rest-id': record.get("id")
							    }
					    	});
				        }
/*				        //workaround for extjs bug
						,listeners: {
							expand: function(combo) {
						     	if (combo.assetHeight == 0 && combo.pageSize > 0 && Ext.isIE7)
						       		combo.assetHeight = 28;
						  	}
						}
*/	        		}
	        	]
        	},
        	{
	        	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;',
			        fieldLabel:'', 
			        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: 128,
                    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',
            	cls:'short_btn',
            	hidden:true,
            	items:[{
            		xtype:'button',
            		minWidth:50,
            		text:'<span style="font-size:10px;">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();
								for (var i=1; i<=3; i++) {
									Ext.getCmp('emailid-'+i).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();
	                			if (!has_user_signin && req_reg) {
									for (var i=1; i<=3; i++) {
										Ext.getCmp('emailid-'+i).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',
					validator: function(value){
						if (!has_user_signin) {
							checkUserRegistration();
						}
						return true;
					},
                    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,
    				validationDelay: validationDelayInMillis,
					validator: function(value){
						if (!has_user_signin) {
							checkUserRegistration();
						}
						return true;
					},
                    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,
		            	id:'rest-id',
		            	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
            //******************E-mail ID****************************
            ,{
            	columnWidth:1,
            	height:5,
            	id:'emailid-1',
            	hidden:true,
            	style:'line-height:5px;border-bottom:1px solid #eeeeee;',
            	html:'&nbsp;'
            }
            ,{
            	columnWidth:.3,
            	layout: 'form',
            	id:'emailid-2',
            	hidden:true,
            	style:'padding-top:10px;padding-left:10px;',
                items: [{
                    xtype:'textfield',
                    width: 145,
                    fieldLabel: 'E-mail &#30005;&#23376;&#37038;&#20214;',
    				maxLength: 128,
    				validationDelay: validationDelayInMillis,
    				allowBlank:false,
                    validator: function(value){
//                    	return validateEmail(value);
						var email_valid_msg = validateEmail(value);
						if (email_valid_msg+'' != 'true') {
							return email_valid_msg;
						}
						var username_valid_msg = checkUsernameAvailability(value);
						if (username_valid_msg+'' != 'true') {
							return username_valid_msg;
						}
						return true;
					},
                    id: 'booking-form-email_id',
                    name: 'booking-form-email_id'
                }]
            }
            ,{
            	columnWidth:.7,
            	id:'emailid-3',
            	hidden:true,
            	style:'padding-top:10px;line-height:14px;',
            	html:"<div><img style='padding-top:5px;' src='/shared/sir/images/red-li2.gif' height='7' width='4'/>&nbsp;This e-mail will be used as your user ID. Please check e-mail for more info after booking.</div>" +
            		"<div><img style='padding-top:5px;' src='/shared/sir/images/red-li2.gif' height='7' width='4'/>&nbsp;You can keep track of your booking records and manage rewards points after sign in.</div>" +
            		"<div><img style='padding-top:5px;' src='/shared/sir/images/red-li2.gif' height='7' width='4'/>&nbsp;The latest &amp; greatest discounts, promotions, news etc. will be sent to this email.</div>"
            }
            ,{
            	columnWidth:1,
            	height: 20
            }
	    ]
        ,buttonAlign:'center'
	    ,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()}
	        }
	    ]
    });
    
    Ext.getCmp('submit-btn').on('render', function(){
    	if (bookingId && bookingId.length!=0) {
    		//modifying booking record, hide sign in components
    		has_user_signin = true;
    		Ext.getCmp('signin-checkbox').hide();
			for (var i=1; i<=4; i++) {
				Ext.getCmp('existing-user-'+i).hide();
			}
			for (var i=1; i<=3; i++) {
				Ext.getCmp('emailid-'+i).hide();
			}

			bookingStore.load({
				params: {
			    },
			    callback: function(records){
			    	var restId = records[0].get('rest_id');
			    	Ext.getCmp('rest-id').setValue(restId);
			    	
			    	var diningDate = records[0].get('dining_date2');
					var 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);
			    	
			    	var noOfPerson = records[0].get('no_of_persons');
			    	Ext.getCmp('booking-form-noofperson').setValue(noOfPerson);
			    	
			    	var vipRoom = Url.replaceEscape(records[0].get('viproom'));
			    	Ext.getCmp('booking-form-viproom').setValue(vipRoom);
			    	
			    	var otherRequirements = Url.replaceEscape(records[0].get('other_requirements'));
			    	Ext.getCmp('booking-form-other-requirements').setValue(otherRequirements);
			    	
		            var contactTitle = Url.replaceEscape(records[0].get('title'));
		            Ext.getCmp('booking-form-title').setValue(contactTitle);
		            
		            var contactName = Url.replaceEscape(records[0].get('name'));
		            if (contactName && contactName.length != 0) {
			            Ext.getCmp('booking-form-name').setValue(contactName);
		            }
		            
		            var contactMobileCtryCode = records[0].get('mobile_ctry_code');
		            Ext.getCmp('booking-form-mobile-ctrycode').setValue(contactMobileCtryCode);
		            
		            var contactMobile = records[0].get('mobile');
		            Ext.getCmp('booking-form-mobile').setValue(contactMobile);
		            
		            var contactEmail = Url.replaceEscape(records[0].get('email'));
		            Ext.getCmp('booking-form-email').setValue(contactEmail);
		            
		            var 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);
		            }
		            
		            var contactPreferredLanguage = records[0].get('diner_preferred_language');
		            Ext.getCmp('booking-form-preferred-language').setValue(contactPreferredLanguage);
			    }
			})
		
    	} else {
			loadUserContacts();
    	}
    });
    
	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];
	    	restId = records[0].get('id');
	    	Ext.getCmp('rest-id').setValue(restId);
	    	var vip_room = rest_rec.get('viproom');
	    	if (vip_room=='' || vip_room.toLowerCase()=='no' || vip_room.toLowerCase()=='n') {
	    	//if (vip_room.toLowerCase()=='no' || vip_room.toLowerCase()=='n') {
	    		Ext.getCmp('booking-form-viproom').disable();
	    	}
	    	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({
			params: {
		        'rest-id': restId
		    }
    	});
    });
	booking_form.show();
	
	
	//validate username***************************************************
	function validateUsername(username) {
		if (username=="") {
			return true;
		}
		var msg = checkUsername2(username);
		if (msg.length != 0) {
			return msg;
		}
		
		//Create store to check user login*********************************************************
	    var store = new Ext.data.JsonStore({
	    	url: '/CommonServlet?action=checkUsernameAvailability'
	       ,root: 'results'
	       ,fields: ['success', '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('success');
		            var exist = records[x].get('exist');
		            if (status == 'true' && exist == 'no') {
		            	Ext.getCmp('login-form-username').markInvalid("This username doesn't exist.");
						err_username = true;
						return;
		            }
		            if (status == 'true' && 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(email) {
		if (email.length == 0) {
			return true;
		}
		var msg = checkEmail(email);
		if (msg.length != 0) {
			return msg;
		}
		return true;
	}

	function checkUserRegistration() {
		var hp_ctry_code = Ext.getCmp('booking-form-mobile-ctrycode').getValue();
		var hp = Ext.getCmp('booking-form-mobile').getValue();
		if (hp=="") {
			return;
		}
		
		//Create store to check user login*********************************************************
	    var store = new Ext.data.JsonStore({
	    	url: '/CommonServlet?action=checkUserRegistrationByHP'
	       ,root: 'results'
	       ,fields: ['req_reg']
	    });

		//backend check user availability
		Ext.getCmp('submit-btn').disable();
		store.load({
			params: {
		        hp: hp,
		        hp_ctry_code: hp_ctry_code
		    },
		    
		    callback: function(records){
		    	if (records && records.length!=0){
		            var s_req_reg = records[0].get('req_reg');
		            if (!has_user_signin && (s_req_reg == 'y' || s_req_reg == 'Y')) {
		            	req_reg = true;
		            	if (Ext.getCmp('booking-form-contactvia').getValue()!='E-mail') {
							for (var i=1; i<=3; i++) {
								Ext.getCmp('emailid-'+i).show();
							}
		            	}
		            } else {
		            	req_reg = false;
						for (var i=1; i<=3; i++) {
							Ext.getCmp('emailid-'+i).hide();
						}
		            }
		        }  
		        Ext.getCmp('submit-btn').enable();
		    }
		});
	}
	
	function checkUsernameAvailability(username) {
		if (username=="") {
			return true;
		}
		var msg = checkUsername2(username);
		if (msg.length != 0) {
			return msg;
		}
		
		//Create store to check user login*********************************************************
	    var signUpStore = new Ext.data.JsonStore({
	    	url: '/CommonServlet?action=checkUsernameAvailability'
	       ,root: 'results'
	       ,fields: ['success', 'exist', 'msg']
	    });

		//backend check user availability
		signUpStore.load({
			params: {
		        username: username
		    },
		    
		    callback: function(records){
		    	for (var x = 0; x < records.length; x++){
		            var status = records[x].get('success');
		            var exist = records[x].get('exist');
		            if (status == 'true' && exist == 'no') {
		            	errEmailID = false;
						//return true;
		            }
		            if (status == 'true' && exist == 'yes') {
						Ext.getCmp('booking-form-email_id').markInvalid('This e-mail has been registered.');
						errEmailID = true;
						//return 'This email has been registered.';
		            }
		        }  
		    }
		});
		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();
	}
}

function loadUserContacts() {
	userStore.load({
		params: {
	    },
	    callback: function(records){
	    	if (records && records.length != 0) {
	    		//hide sign in components
	    		has_user_signin = true;
	    		Ext.getCmp('signin-checkbox').hide();
    			for (var i=1; i<=4; i++) {
    				Ext.getCmp('existing-user-'+i).hide();
				}
    			for (var i=1; i<=3; i++) {
    				Ext.getCmp('emailid-'+i).hide();
				}
	    		
	    		is_agent = records[0].get('is_agent');
	    		if (!is_agent || is_agent.toUpperCase() != 'Y') {	//set booking pref only if the user is not agent
		            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);
		            }
	    		}
	            
	            //dynamically change header sign in part
	            var el_header_sign_in = Ext.get('header-signin');
	            if (el_header_sign_in) {
	            	var signin_win = Ext.getCmp('content-anchor-tip-signin');
	            	if (signin_win) {
		            	Ext.getCmp('content-anchor-tip-signin').destroy();
	            	}
	            	var user_id = records[0].get('user_id');
	            	var current_url = top.location.href;
	            	var dom = el_header_sign_in.dom;
	            	dom.width='320';
	            	el_header_sign_in.dom.innerHTML = '<b>'+user_id+'</b> | <a href="/member/MemberHome.jsp">My Account</a> | <a href="/MemberSignOut.jsp?url='+current_url+'">Sign Out</a>';
	            } else {
	            	is_agent = '';
	            }
	    	} else {
/*    			for (var i=1; i<=3; i++) {
    				Ext.getCmp('emailid-'+i).show();
				}
*/	    	}
	    }
		
	});
}	
