var FoodOrderingWizard = Class.create(Wizard, {
	'initialize': function($super) {
		$super('.FoodOrderingWizard');
	},
	// 'addStage': function(stage) {
		// this._super(stage);
		
		
	// },
	'configure': function($super) {
		var schedulerWizardStage = new SchedulerWizardStage();
		this.addStage(schedulerWizardStage);
		
		var categoriesWizardStage = new CategoriesWizardStage();
		this.addStage(categoriesWizardStage);
		
		var productsWizardStage = new ProductsWizardStage();
		this.addStage(productsWizardStage);
		
		var productDetailWizardStage = new ProductDetailWizardStage();
		this.addStage(productDetailWizardStage);
		
		schedulerWizardStage.bind('add_meal_click', this.callback(function(e, position) {
			this.data['AddPosition'] = position;
			this.goTo(1);
		}));
		
		categoriesWizardStage.bind('category_selected', this.callback(function(e, cat) {
			this.data['CurrentCategoryID'] = cat.CategoryID;
			this.goTo(2);
		}));
		
		productsWizardStage.bind('product_selected', this.callback(function(e, p) {
			this.data['CurrentProductID'] = p.ProductID;
			this.goTo(3);
		}));
		
		var productAddedCallback = this.callback(function(e, product) {
			//alert(JSON.stringify(product));
			var addPosition = this.data['AddPosition'];
			var date = addPosition.Date;
			var mealTypeName = addPosition.MealTypeName;
			
			schedulerWizardStage.scheduler.addProduct(date, mealTypeName, product);			
			this.goTo(0);
		});
		
		productsWizardStage.bind('product_added', productAddedCallback);
		productDetailWizardStage.bind('product_added', productAddedCallback);
	},
	'setAllowedDays': function(days) {
		this.data['AllowedDays'] = days;
	},
	'setFoodType': function(foodType) {
		this.data['FoodType'] = foodType;
	},
	'setEarliestDeliveryDate': function(date) {
		this.data['EarliestDeliveryDate'] = date;
	}
});

var SchedulerWizardStage = Class.create(WizardStage, {
	'initialize': function($super) {
		$super('.SchedulerWizardStage');
		
		this.scheduler = new Scheduler('.Scheduler');			
		this.calendar = new Calendar(new Date());
	},
	'configure': function() {
		this.calendar.setAllowedDays(this.data['AllowedDays']);
		this.calendar.setEarliestDate(this.data['EarliestDeliveryDate']);
		
		//this.scheduler.setFoodType(this.data['FoodType']);
		
		this.calendar.bind('save', this.callback(function(e) {
			this.scheduler.addDates(this.calendar.addedDates);
			this.scheduler.removeDates(this.calendar.removedDates);
			
			jQuery('.CalendarDialog').dialog('close');
		}));		
		
		this.scheduler.bind('add_meal_click', this.callback(function(e, e2) {
			this.trigger('add_meal_click', e2);
		}));
		
		this.container.find('.AddDatesButton').click(this.callback(function(e) {
			this.calendar.setDates(this.scheduler.getDates());
			
			jQuery('.CalendarDialog').dialog('open');
		}));
		
		this.container.find('.NextButton').click(this.callback(function(e) {
			var button = jQuery(e.sender);
			/*
			var form = jQuery('#ViewForm');
			var hidden = jQuery('#ScheduleDataHidden');
			
			hidden.val(JSON.stringify(this.scheduler.schedulerData));
			form.attr('action', '/foodordering/schedule/saveschedule');
			form[0].submit();
			*/
			
			var json = JSON.stringify(this.scheduler.getData());
			
			jQuery.post('/foodordering/schedule/ajaxsaveschedule', { 'ScheduleData': json }, function(responseText) {
				var response = JSON.parse(responseText);
				
				if (response.Notices.length) {
					var notice = response.Notices[0];
					
					if (notice.Type == 'Warning') {
						if (confirm(notice.Message + '\n\nWould you like to continue anyway?')) {
							window.location = button.attr('href');
						}
					}
					else if (notice.Type == 'Error') {
						alert(notice.Message);
					}
				}
				else {
					window.location = button.attr('href');
				}
			});
			
			return false;
		}));
		
		this.scheduler.bind('change', this.callback(function() {
			var json = JSON.stringify(this.scheduler.getData());
			
			jQuery.post('/foodordering/schedule/ajaxsaveschedule', { 'ScheduleData': json }, function(responseText) {
				var response = JSON.parse(responseText);
				
				ScheduleView.UpdateTotalPrice(response.TotalPrice);
				ScheduleView.ShowNotices(response.Notices);
			}, 'text');
		}));
	},
	'show': function($super) {
		$super();
	}
});

var CategoriesWizardStage = Class.create(WizardStage, {
	'initialize': function($super) {
		$super('.CategoriesWizardStage');
	},
	'show': function($super) {
		this.container.find('.AjaxCategories').html('<p class="Loading">Loading...</p>');
		this._shown();
		
		var params = { 'MealTypeName': this.data['AddPosition']['MealTypeName'] };
		this.container.find('.AjaxCategories').load('/foodordering/schedule/ajaxcategories', params, this.callback(function() {
			this.bindEvents();
		}));
	},
	'bindEvents': function() {
		this.container.find('.CategoryPodItem').bind('click', this.callback(function(e) {
			//this.trigger('next');
			
			this.trigger('category_selected', {
				'CategoryID': jQuery(e.sender).attr('category-id')
			});
		}));
	}
});

var ProductsWizardStage = Class.create(WizardStage, {
	'initialize': function($super) {
		$super('.ProductsWizardStage');
	},
	'show': function() {
		this.container.find('.AjaxProducts').html('<p class="Loading">Loading...</p>');
		this._shown();
		
		var titleH1 = this.container.find('.page-title h1');
		if (!this.titleFormat) this.titleFormat = titleH1.text();
		titleH1.text('Loading...');
		
		var params = { 'cid': this.data['CurrentCategoryID'] };
		this.container.find('.AjaxProducts').load('/foodordering/schedule/ajaxproducts', params, this.callback(function() {
			this.bindEvents();
			
			var categoryName = this.container.find('.AjaxProducts').find('.Hidden .CategoryName').text();
			var foodType = this.container.find('.AjaxProducts').find('.Hidden .FoodType').text();
						
			var title = this.titleFormat;
			var title = title.replace('[CategoryName]', categoryName);
			var title = title.replace('[FoodType]', foodType.replace('Food', ''));
			
			titleH1.text(title);
		}));
	},
	'bindEvents': function() {
		this.container.find('.ReadMoreButton').bind('click', this.callback(function(e) {
			//this.trigger('next');
			var li = jQuery(e.sender).closest('li');
			
			this.trigger('product_selected', {
				'ProductID': li.attr('product-id')
			});
		}));
	
		this.container.find('.AddMealsButton').bind('click', this.callback(function(e) {
			var liProduct = jQuery(e.sender).closest('.ProductItem');
			
			var id = liProduct.attr('product-id');
			var name = liProduct.find('.ProductName').text();
			var qty = liProduct.find('input.NoOfMeals').val();
			//alert(name);
			
			//alert(id);
			this.trigger('product_added', {
				'ProductID': id,
				'Name': name,
				'Quantity': parseInt(qty),
				'FoodType': this.data['FoodType']
			});
			
			return false;
		}));
	}
});

var ProductDetailWizardStage = Class.create(WizardStage, {
	'initialize': function($super) {
		$super('.ProductDetailWizardStage');
	},
	'show': function() {
		this.container.find('.AjaxProductDetail').html('<p class="Loading">Loading...</p>');
		this._shown();
		
		this.container.find('.AjaxProductDetail').load('/foodordering/schedule/ajaxproductdetail', { 'pid': this.data['CurrentProductID'] }, this.callback(function() {
			this.bindEvents();
		}));
	},
	'bindEvents': function() {
		this.container.find('.AddMealsButton').bind('click', this.callback(function(e) {
			var liProduct = jQuery(e.sender).closest('.ProductDetail');
			
			var id = liProduct.attr('product-id');
			var name = liProduct.find('.ProductName a').text();
			var qty = liProduct.find('input.NoOfMeals').val();
			//alert(name);
			
			this.trigger('product_added', {
				'ProductID': id,
				'Name': name,
				'Quantity': parseInt(qty)
			});
			
			return false;
		}));
	}
});
