window.addEvent('domready', function() {

	var StoreDetails = new Class({
		'options':{
		},
		'initialize': function(options)
		{
			this.storeId = $("store");
			this.storeName = $("storeName");
			this.storeAddress = $('storeAddress');
			this.storeType = $('storeType');
			this.partyRoom = $('partyRoom');
			this.mcCafe = $('mcCafe');
			this.carSpaces = $('carSpaces');			
			this.wheelchairAccess = $('wheelchairAccess');
			this.babyChangeFacility = $('babyChangeFacility');
			this.highChairsAvailable = $('highChairsAvailable');
			this.playLand = $('playLand');
			this.specialoffers = $('specialoffers');
			this.specialoffersBox = $('specialOffersBox');

			this.empty = {
				'storeId':' ',
				'name':' ',
				'address':' ',
				'StoreType':' ',				
				'HavePartyRoom':' ',
				'HaveMcCafe':' ',
				'TotalCarSpace':' ',
				'HaveWheelChairAccess': ' ',				
				'HaveBabyRoom':' ',
				'TotalHighChairs':' ',
				'HavePlayLand':' ',				
				'SpecailOfferName':' '
			};
		},
		'update': function(item) {
			var specialoffer = item.SpecailOfferName;
					
			if(this.storeId != null){this.storeId.set('value', item.storeId);}
			if(this.storeName != null){this.storeName.set('text', item.name);}
			if(this.storeAddress != null){this.storeAddress.set('text', item.address);}
			if(this.storeType != null){this.storeType.set('text', item.StoreType);}	
			if(this.partyRoom != null){this.partyRoom.set('text', item.HavePartyRoom);}
			selectYesNo(item.HaveMcCafe, this.mcCafe);
			if(this.carSpaces != null){this.carSpaces.set('text', item.TotalCarSpace);}
			selectYesNo(item.HaveWheelChairAccess, this.wheelchairAccess);
			selectYesNo(item.HaveBabyRoom, this.babyChangeFacility);
			if(this.highChairsAvailable != null){this.highChairsAvailable.set('text', item.TotalHighChairs);}				
			selectYesNo(item.HavePlayLand, this.playLand);
			if(this.specialoffers != null){this.specialoffers.set('text', item.SpecailOfferName);}
			
			if(specialoffer != '') {
				this.specialoffersBox.addClass('specialoffers-box');
			} else {
				this.specialoffersBox.removeClass('specialoffers-box');
			}
		},
		'clear': function() {
			this.update(this.empty);
		},
		'getStore' : function() {
			return this.storeId.get('value');
		}
	});
	
	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 = $('storeNameItems-PostCode');
		},
		
		'processStoreListBySuburb': function(items) {
			if(items.length == 0 ) {
				alert('No store found.');
			} else {
				items.each(function(item){
					if ($('storeItems').get('value') == item.storeId){
						this.store.update(item);
						return;
					}
				}.bind(this));
				
			}
		},
		
		'processStoreListByPostCode': function(items, storeId) {
			var found = false;
			this.clear();
			var postcodePanel = $('storeNameItems-PostCode');
			if(items.length>0) {	
				new Element('label', {'class':'store-list-left', 'text':'Here are the closest party restaurants near you:'}).inject(new Element('h3').inject(postcodePanel), 'top');
				items.each(function(item) {
					var aItem = new Element('a', {
						
						'href':'#',
						'id':'storeNameItems' + item.storeId.toString(),
						'text':item.name,
						'class': 'store-list-left',
						'name':'store',
						'value':item.storeId,
						'events': {
							'click': function(event) {
								event.stop();
								store.update(this);
							}.bind(item)
						}
					}).inject(postcodePanel);
					new Element('br').inject(postcodePanel);
					if(storeId && storeId == item.storeId)
					{
						this.store.update(item);
						found = true;
					}
				}.bind(this));//end each
				if(!found)
				{
					this.store.update(items[0]);
				}
			} else {
				alert('Sorry, no stores found');
			}
		},
		'clear': function() {
			//this.postcodePanel = $('storeNameItems-PostCode');
			$('storeNameItems-PostCode').empty();
		}		
	});
	
	var info = new StoreInformation();
	var store = new StoreDetails();
	var processor = new StoreProcess(store);
	var search = new Search(store, info, processor);

//-------------------------------------------------------
//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});
				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
//-------------------------------------------------------

var addStoreItems = function(stores) {
	var storeSelectBox = $('storeItems');
	storeSelectBox.empty();
	
	if(stores && stores.length > 0) {
		storeSelectBox.adopt(new Element('option', {'value' : '0', 'html' : 'Please select'}));
		
		stores.each(function(store) {
			var element = new Element('option', {'value' : store.storeId, 'html' : store.name});
			if((stores != 0) && (stores == store.storeId)) {
				element.setProperty('selected', 'selected');
			}
			storeSelectBox.adopt(element);
		});		
	}else {
		storeSelectBox.adopt(new Element('option', {'value' : '0', 'html' : 'Please select'}));
	}
}

//-------------------------------------------------------
//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
	});
}
//-----------------------------------------------------------------
//load data into suburb
if($('suburbItems')!=null)
{/*
	$('suburbItems').addEvent('change', function(e) {
		var request = new Request.JSON({		
				url: 'GetStoreList.do?suburbId=' + $('suburbItems').get('value'),				
				onComplete: function(getJsonData)
				{
					if(getJsonData != null)
    					addItemsStoreInfo(getJsonData.StoreList);    					
				}
		}).send();
	//end event
	});
*/
}
//-------------------------------------------------------
//clear information from store detail
function clearInformationStoreDetail()
{	
	store.clear()
	
	$('storeNameItems-PostCode').empty();
	$('storeNameRadioItems-Suburb').empty();
	//$('postCode').set('value', '');
}
//--------------------------------------------------------
//load data on change store sub item
var storeNameSubItemsOnChange = function(){
		if($('label-items-available-time_message') !=null){$('label-items-available-time_message').set('html','');}
		if($('items-available-time')!=null){$('items-available-time').empty();}
		
		var request = new Request.JSON({
			//file
			url:'GetStoreInfo.do?storeId=' + $('storeNameSubItemsValue').get('value'),
			//do event
			onComplete: function(getJsonData) 
			{	//add into Select
				if(getJsonData != null)
				{
					//addItemsStoreInfo_ByStoreName(getJsonData.StoreInfo);
					if($('dateAvailable')!=null && $('dateAvailable').get('value') != '')
   					{
    					storeNameDate_Change();
    					//addItemsAvailableTime();
   					}
				}else{
					$('btnSubmitBCS').set('disabled', 'disabled');
			   		$('label-items-available-time_message').set({
			   													'html':'There is not available time, please change other date of the calendar.',
			   													'style':'color:#FFFF00;'
			   												   });
				}
			}
		}).send();
}
//-----------------------------------------------------------						
//load data into Store Information
	var addItemsStoreInfo = function(listItems){
	/*	if(listItems.length <=0)
		{
			alert('No store found.');
		}
		//clear stor name item
		if($('storeNameItems-PostCode')!=null)
		{
			$('storeNameItems-PostCode').empty();
		}
		//clear block
		if($('storeNameRadioItems-Suburb')!=null)
		{
		$('storeNameRadioItems-Suburb').empty();
		}
		var firstIndex =0;
		//input data into store information panel
		if(listItems.length>0)
		{
			new Element('label', {'class':'store-list-left', 'text':'Here are the closest party restaurants near you:'}).inject(new Element('h3').inject($('storeNameRadioItems-Suburb')), 'top');
		}
		
		listItems.each(function(listItem)
		{
			if(firstIndex == 0)
			{
				store.update(listItem);
			}
					
			var radioListItem = new Element('input',
			{
				
				'type':'radio',
				'name':'store',
				'value':listItem.storeId,
				'events':
				{
					'click': function(event)
					{
						store.update(this);
						storeNameSubItemsOnChange();
						
					}.bind(listItem)
				}
			}).inject($('storeNameRadioItems-Suburb'));
			 if(firstIndex == 0)
			 {
			 	radioListItem.setProperty('checked', 'checked');
			 }
			 new Element('span',{'html':listItem.name}).inject($('storeNameRadioItems-Suburb'));
			 new Element('br').inject($('storeNameRadioItems-Suburb'));
		//increase firstIndex avoid set selection again
		firstIndex++;
		
		});//end each
	*/
	};//end function
//---------------------------------------------------	
if($('suburbItems') != null) {
	var suburbSelectBox = $('suburbItems');
	suburbSelectBox.addEvent('change', function(event) {
		if(suburbSelectBox.get('value') != 0) {
			$('suburb_id').setProperty('value', suburbSelectBox.get('value'));
			//store.clear();
			//search.searchBySuburb($('suburbItems').get('value'));
			var request = new Request.JSON({
				url: 'GetStoreList.do?suburbId='+ $('suburb_id').get('value'),
				onComplete: function(jsonData) {
					if(jsonData != null) {						
						addStoreItems(jsonData.StoreList);						
					} else {
						
					}
				}.bind(this),
				onFailure:function() {
					
				}
			}).send();
			
		}else {
			$('storeItems').empty();
		}
	});
}

if($('buttonGoStore') != null) {
	$('buttonGoStore').addEvent('click', function(e) {		
		if($('storeItems').get('value') != 0) {
			store.clear();
			search.searchBySuburb($('suburbItems').get('value'));
		}else {
			if($('suburbItems').get('value') == 0) {
				alert('Please select a city and then restaurant.');
			}else {
				alert('Please a select restaurant');
			}
		}
	});
}

//----------------------------------------------------
var addItemsStoreInfo_2 = function(listItems){
	//clear storeNameRadioItems-Suburb block
	if($('storeNameRadioItems-Suburb')!=null)
	{
		$('storeNameRadioItems-Suburb').empty();
	}
	//check invalid data
	if($('storeNameItems-PostCode')!=null)
	{
		$('storeNameItems-PostCode').empty();
	}
	new Element('label', {'class':'store-list-left', 'text':'Here are the closest party restaurants near you:'}).inject(new Element('h3').inject($('storeNameItems-PostCode')), 'top');
	//
	var firstIndex =0;	
	listItems.each(function(listItem){
		if(firstIndex == 0)
		{
			store.update(listItem);
		}
		//store value into storenamesubitemvalue
		$('storeNameSubItemsValue').set('value',listItem.storeId);
		var aListItem = new Element('a',
		{
			'href':'#',
			'id':'storeNameItems' + listItem.storeId.toString(),
			'text':listItem.name,
			'class': 'store-list-left',
			'name':'store',
			'value':listItem.storeId,
			'events':
			{
				'click': function(event)
				{
					event.stop();
					store.update(this);
					//store value into storenamesubitemvalue
					$('storeNameSubItemsValue').set('value',listItem.storeId);
				}.bind(listItem)
			}
		}).inject($('storeNameItems-PostCode'));
		new Element('br').inject($('storeNameItems-PostCode'));
		//increase it to avoid check condition again
		firstIndex++;
	  });//end each
	  
	};//end function

//------------------------------------------------------
//POST CODE
var PostCodeSearch = function() {
		store.clear();
		search.onPostCodeSearchGo();
		info.update(1);
}
//---------------------------------------------------
//text box
if($('postCode')!=null)
{
	$('postCode').addEvents({
		'keypress': 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
	});
}	
//----------------------------------------------------
var addItemsStoreInfo_ByStoreName = function(listItems){
	if(listItem.length>0)
	{
		store.update(listItem[listItem.length-1]);
	}
};

//---------------------------------------------------------
//storeName change with calendar
function storeNameDate_Change()
{	
	if($('dateAvailable')!=null)
	{
		var request = new Request.JSON({
			//file
			url: 'GetAvailableTime.do?storeId=' + $('storeNameSubItemsValue').get('value') + '&partyDate=' + $('dateAvailable').get('value'),								
			//do event
			onComplete: function(getJsonData2) 
			{	//add into Select
			   	if(getJsonData2 != null)
			   	{
					addItemsAvailableTime_onChange(getJsonData2.AvailableTime);
					if($('btnSubmitBCS') != null)$('btnSubmitBCS').set('disabled', '');
				}	
			   	else
			   	{
			   		if($("items-available-time")!=null)
			   		{
			   			$('items-available-time').empty();//.set('html', '');
			   		}
			   		//if($('btnSubmitBCS') != null)
			   		if($('btnSubmitBCS') != null)$('btnSubmitBCS').set('disabled', 'disabled');
		   			if($('label-items-available-time_message')!= null)
		   			{
		   			   $('label-items-available-time_message').set({
		   													'html':'There is not available time, please change other date of the calendar.',
		   													'style':'color:#FFFF00;'
		   												   });
		   			}
			   	}
			}
		}).send();
	}
}
//-------------------------------------------------------
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');	
	}
	
}
//-------------------------------------------------------

//add class 'sl_yes' or 'sl_no' based on the value (if any). Otherwise, remove both classes
function selectYesNo(val, element){
	if (element != null){

		if (val != null && val.trim() != ''){
			if (val.toLowerCase() == 'yes') element.addClass('sl_yes');
			else element.addClass('sl_no');
		}
		else{
			element.removeClass('sl_yes').removeClass('sl_no');
		}
		
	}
}

//end domready
});
