window.addEvent('domready', function() {

	var StoreInformation = new Class({
		'initialize':function() {
			this.stateId = $('state_id');
			this.suburbId = $('suburb_id');
			this.postcode = $('postcode_id');
			this.buttonGo = $('button_go');
		},
		'update':function(buttonGo) {	
			
			if(this.stateId != null){this.stateId.set('value', $('stateItems').get('value'));}
			if(this.suburbId != null){this.suburbId.set('value', $('suburbItems').get('value'));}
			if(this.postcode != null){this.postcode.set('value', $('postCode').get('value'));}
			if(this.buttonGo != null){this.buttonGo.set('value', buttonGo);}
		},
		'getStateId':function() {
			return this.stateId.get('value');
		},
		'getSuburbId':function() {
			return this.suburbId.get('value');
		},
		'getPostcode':function() {
			return this.postcode.get('value');
		},
		'getButtonGo':function() {
			return this.buttonGo.get('value');
		}		
	});
	
	var Search = new Class({
		'initialize': function(store, info, processor) {
			this.store = store;		
			this.postcode = $('postCode');
			this.suburbitems = $('suburbItems');
			this.info = info;
			this.processor = processor;
		},
		
		'onPostCodeSearchGo': function() {
			var postcode = this.postcode.get('value');
			this.store.clear();
			if(this.validatePostcode(postcode)) {
				this.searchByPostCode(postcode);
			} else {
				alert('Please enter a valid postcode');
			}
		},
		
		'validatePostcode' : function(postcode)	{
			return (postcode.length> 0 && postcode.length<5) && !isNaN(postcode);
		},
		
		'searchByPostCode': function(postcode) {
			this.info.update(1);
			
			// TODO Search by postcode
			var request = new Request.JSON({
				url: 'GetStoreList.do?postcode=' + postcode,
				onComplete: function(getJsonData) {
					if(getJsonData !=null) {
						this.processor.processStoreListByPostCode(getJsonData.StoreList, this.store.storeId.get('value'));					
					} else {
						alert('Sorry, no stores found');
					}
				}.bind(this),
				onFailure:function() {
				}
			}).send();

		},
		
		'onSearchBySuburb': function() {
			var suburb = this.suburbitems.get('value');
			this.store.clear();
			if(this.validateSuburb(suburb)) {
				this.searchBySuburb(suburb);
			} else {
				alert('Please select a suburb');
			}
		},
		

		'validateSuburb' : function(suburb)	{
			return suburb.length> 0 && !isNaN(suburb);
		},
		
		'searchBySuburb': function(suburbId) {
			// TODO Search by Suburb
			var request = new Request.JSON({
				url: 'GetStoreList.do?suburbId='+ suburbId,
				onComplete: function(getJsonData) {
					if(getJsonData != null) {
						//this.processStoreListBySuburb(getJsonData.StoreList);
						this.processor.processStoreListBySuburb(getJsonData.StoreList);
					} else {
						//this.onErrorNotFoundJSON();
					}
				}.bind(this),
				onFailure:function() {
					
				}
			}).send();
			
			this.info.update(0);
		}
	});

	var StoreProcess = new Class({
		'initialize':function(store) {
			this.store = store;
			this.postcodePanel = $('storeNameItemsPostCode');
		},
		
		'processStoreListBySuburb': function(items, storeId) {
			this.clear();
			
			if (items.length == 0) {
				alert('No store found.');
			} else if(items.length>1) {
				this.displayStoreList(items, 0);
			} else {
				this.store.update(items[0]);
			}
		},
		
		'processStoreListByPostCode': function(items, storeId) {
			this.displayStoreList(items, storeId);
		},
		'displayStoreList': function(items, storeId) {
			var found = false;
			this.clear();

			if(items.length>0) {
				// create title
				new Element('label', {'class':'red-text', 'text':'Here are the closest party restaurants near you:'}).inject(new Element('h3').inject(this.postcodePanel), 'top');
				// create table temporary for displaying
				var tableTemp = new Element('table', {'class': 'party-room-store-list'}).inject(this.postcodePanel);
				// create tbody of the table
				var tbodyTemp = new Element('tbody').inject(tableTemp);
				//items.each(function(item) {
				for(var i=0; i<items.length; i++) {
					// create container
					var trTemp = new Element('tr').inject(tbodyTemp);									// tr has two columns
					var tdTemp1 = new Element('td', {'class': 'party-room-stor-name'}).inject(trTemp);	// td column1
					var tdTemp2 = new Element('td', {'class': 'party-room-number-pan'}).inject(trTemp);	// td column2
					// create ahref
					new Element('a', {
						'href':'#',
						'id': 'storeNameItems' + items[i].storeId.toString(),
						'text':items[i].name,
						'class': 'store-list-left',
						'value':items[i].storeId,
						'events': {
							'click': function(event) {
								event.stop();
								store.update(this);
							}.bindWithEvent(items[i])
						}
					
					}).inject(tdTemp1);
					// display party room
					new Element('span', {'html':'Party Rooms(' + items[i].HavePartyRoom + ')&nbsp;', 'class': 'party-room-number'}).inject(tdTemp2);
					// display balloons
					for(var j = 0; j<items[i].HavePartyRoom; j++){
						// create div for display the balloons
						new Element('div', {'class': 'party-room-balloon'}).inject(tdTemp2);
					}
					// check the old storeid that get from session	
					if(storeId && storeId == items[i].storeId) {
						this.store.update(items[i]);
						found = true;
					}	
				}
				// update store if it was found
				if(!found) {
					this.store.update(items[0]);
				}
			} else {
				alert('Sorry, no stores found');
			}
		},
		'clear': function() {
			//this.postcodePanel = $('storeNameItemsPostCode');
			$('storeNameItemsPostCode').empty();
		}		
	});
	
	var info = new StoreInformation();
	var store = new StoreDetails();
	var processor = new StoreProcess(store);
	var search = new Search(store, info, processor);


//-------------------------------------------------------
var bookingThisRestaurant = $('bookingThisRestaurant');
if($chk(bookingThisRestaurant)){
	bookingThisRestaurant.addEvent('click', function() {
		if(store.getStore()==''){
			alert('Please select one suburb, or type post code to get the store. ');
		}else{
			document.frm_store.submit();
		}
	});
}
//-------------------------------------------------------
//add item into suburb
	var addItemsSuburb = function(items) {
		var suburbs = $('suburbItems');
		suburbs.empty();

		if(items && items.length >0) {
			suburbs.adopt(new Element('option', {'value' : '0', 'html' : 'Please select'}));
			
			items.each(function(item){
				var e = new Element('option', {'value' : item.suburbId, 'html' : item.suburbName});
				//create option element
				if((suburbs != 0) && (suburbs == item.suburbId)) {
					e.setProperty('selected','selected');	
				}
				//create value into option
				suburbs.adopt(e);
			});//end each function
		} else {
			suburbs.adopt(new Element('option', {'value' : '0', 'html' : 'Please select'}));
		}
	};	//end addItemsSuburb
//-------------------------------------------------------
//load data inot suburb on page load
//load 
if($('stateItems')!=null) {
	var requestSuburb = new Request.JSON({
		url: 'GetAvailableSuburbs.do?stateId=' + ($('state_id') != null && $('state_id').get('value') != 0 ? $('state_id').get('value'):$('stateItems').get('value')) ,
		onComplete: function(getJsonData)
		{
			if(getJsonData != null)
			addItemsSuburb(getJsonData.AvailableSuburbs);
		}
	}).send();
}
//-------------------------------------------------------		

//load data into suburb
if($('stateItems')!=null) {
	$('stateItems').addEvent('change', function(e) {
		var request = new Request.JSON({		
				url: 'GetAvailableSuburbs.do?stateId=' + $('stateItems').get('value'),				
				onComplete: function(getJsonData)
				{
					if(getJsonData != null)
    					addItemsSuburb(getJsonData.AvailableSuburbs);
				}
		}).send();
		
	//end event
	});
}
//-------------------------------------------------------
//clear information from store detail
function clearInformationStoreDetail() {	
	store.clear()
	
	$('storeNameItemsPostCode').empty();
	$('storeNameRadioItemsSuburb').empty();
	//$('postCode').set('value', '');
}
//--------------------------------------------------------	
if($('buttonGO')!=null){	
	$('buttonGO').addEvent('click', function(e){
		if($('suburbItems').get('value') != 0) {
			store.clear();
			search.searchBySuburb($('suburbItems').get('value'));
		} else {
			if($('stateItems').get('value') == 0) {
				alert('Please select a state and suburb.');
			} else {
				alert('Please select a suburb.');
			}				
		}
	});	
}	

//------------------------------------------------------
//POST CODE
var PostCodeSearch = function() {
		store.clear();
		search.onPostCodeSearchGo();
		info.update(1);
}
//---------------------------------------------------
//text box
if($('postCode')!=null){
	$('postCode').addEvents({
		'keydown': function(e)	{
			e = new Event(e);
			if (e.key == 'enter') 
			{
				e.stop();
				PostCodeSearch();
			}
		}
	});
}
//---------------------------------------------------	
//button GO POST CODE	
if($('buttonGoPostCode')!=null){
	$('buttonGoPostCode').addEvent('click', function(e){
		PostCodeSearch();
		//end request
	});
}	
//-------------------------------------------------------
if($('searchagainBCS')!=null){
	var searchagainBCS = $('searchagainBCS');
	 searchagainBCS.addEvent('click', function(event){
	 	event.stop();
		clearInformationStoreDetail();
	 });
}
//load function
//doScrollBarSize();
//-------------------------------------------------------

function doScrollBarSize() {

	var heightScrollBar = parseInt($('scrollbar1').getStyle('height').replace('px',''));
	var heightContainer = parseInt($('ulStoreInfo').getStyle('height').replace('px',''));
	if(heightScrollBar< heightContainer)
	{
		$('scrollbar1').setStyle('display','block');
	}else{
		$('scrollbar1').setStyle('display','none');	
	}
	
}

});