/*!
 * Name: cart.js
 **/
(function($){
	$.fn.isCart = function() {
		var _self = this;
		var _class = {
			refreshCountOnDishes: function() {
				var cartDishList = _self.find('.dish');
				cartDishList.each(function(i,element){
					element = $(element);
					var dishObject = element.data('dishObject');
					var dishId = dishObject.id;
					$.cartChanged(dishId, _getCount(dishObject));
				});
			},
			add: function(dishObject, save) {
				if (typeof(dishObject) == 'undefined'
						|| typeof(dishObject['name']) == 'undefined') {
					return;
				}
				save = (typeof(save)=='undefined') ? true : save;
				var dishId = dishObject['id'];
				var cartRestaurant = $('#cart_restaurant' + dishObject['restaurantId']);
				var cartItem = $('#cart_item' + dishId);
				var denyClass = (dishObject['denyOrder']) ? 'deny_order' : '';
				var noTakeoutClass = (dishObject['restaurantTakeout']) ? '' : 'no_takeout';
				if (cartRestaurant.size() == 0) {
					cartRestaurant = $(
						'<li class="restaurant '
						+ denyClass
						+ '" id="cart_restaurant'
						+ dishObject['restaurantId']
						+'"><div class="meta vcard"><span class="name">'
						+ (dishObject['restaurantName'] || '')
						+ '</span><span class="tel">'
						+ (dishObject['restaurantTel'] ? '( ' + dishObject['restaurantTel'] + ' )': '')
						+ '</span></div><ul class="dishes"></ul></li>'
					);
					_self.append(cartRestaurant);
					if(!dishObject['restaurantTakeout']) {
						$('#cart_outer').addClass('notakeout');
					}
				}
				if (cartItem.size() == 0) {
					cartItem = $(
						'<li id="cart_item' + dishId
						+ '" class="dish rev' + dishObject['revision']
						+ '"><span class="name">'
						+ dishObject['name']
						+ '</span><span class="price">'
						+ dishObject['price']
						+ '</span><span class="cart_count" id="cart_count'
						+ dishId
						+ '">0</span><a class="delete" href="javascript:void(0)"></a></li>'
					);
					cartRestaurant.find('.dishes').append(cartItem);
					_bindCartItem(dishObject);
				}
				var count = _countAdd(dishObject)
				cartItem.data('dishObject', dishObject);
				$.cartChanged(dishId, count);
				$('#cart_outer').removeClass('empty');
				var needDeny = _self.find('li.restaurant').size() ==  _self.find('li.deny_order').size();
				if (!needDeny){
					$('#cart_outer').removeClass('denied');
				}
				if (save) { _saveCart() }
				$(window).trigger('cart_change');
				return count;
			},
			removeCount: function(dishObject) {
				var count = 0;
				var dishId = dishObject['id'];
				var cartRestaurant = $('#cart_restaurant' + dishObject['restaurantId']);
				var cartItem = $('#cart_item' + dishId);
				if(cartItem.size()!=0){
					count = _countRemove(dishObject);
					if (count<1) { cartItem.remove() }
					if(cartRestaurant.find('li').size()==0){
						cartRestaurant.remove();
					}
				}
				cartItem.data('dishObject', dishObject);
				$.cartChanged(dishId, count);
				var needDeny = _self.find('li.restaurant').size() ==  _self.find('li.deny').size();
				if (_self.find('li').size()==0) {
					$('#cart_outer').addClass('empty');
				}
				if (needDeny) {
					$('#cart_outer').addClass('denied');
				}
				var noTakeout = 0 < _self.find('li.no_takeout').size();
				if (!noTakeout){
					$('#cart_outer').removeClass('notakeout');
				}
				_saveCart();
				$(window).trigger('cart_change');
				return count;
			},
			removeDish: function(dishObject) {
				var dishId = dishObject['id'];
				var cartRestaurant = $('#cart_restaurant' + dishObject['restaurantId']);
				var cartItem = $('#cart_item' + dishId);
				cartItem.remove();
				$.cartChanged(dishId, 0);
				if (cartRestaurant.find('li').size() == 0) {
					cartRestaurant.remove();
				}
				var needDeny = _self.find('li.restaurant').size() ==  _self.find('li.deny').size();
				if (_self.find('li').size()==0) {
					$('#cart_outer').addClass('empty');
				}
				if (needDeny) {
					$('#cart_outer').addClass('denied');
				}
				var noTakeout = 0 < _self.find('li.no_takeout').size();
				if (!noTakeout){
					$('#cart_outer').removeClass('notakeout');
				}
				_saveCart();
			},
			clear: function() {
				if ($('#cart_outer').hasClass('empty')) {
					return false;
				}
				_self.html('');
				$.cartChanged(null, 0);
				$('#cart_outer').addClass('empty');
				$('#cart_outer').addClass('denied');
				$('#cart_outer').removeClass('notakeout');
				_saveCart();
				$(window).trigger('cart_change');
			},
			getTotalCount: function() {
				var totalCount = 0;
				_self.find(".dish .cart_count").each(function(){
					totalCount += parseInt($(this).html());
				});
				return totalCount;
			}
		};
		function _getCount(dishObject) {
			var counter = $('#cart_count' + dishObject['id']);
			var count = parseInt(counter.html()); 
			return count;
		}
		function _countAdd(dishObject) {
			var counter = $('#cart_count' + dishObject['id']);
			var incremental = dishObject['count'] || 1;
			var count = parseInt(counter.html()) + incremental; 
			counter.html(count);
			return count;
		}
		function _countRemove(dishObject) {
			var counter = $('#cart_count' + dishObject['id']);
			var count = parseInt(counter.html()) - 1; 
			counter.html(count);
			return count;
		}
		function _bindCartItem(dishObject) {
			function toRemoveCount(dishObject) {
				return function() {
					_class.removeCount(dishObject);
				}
			}
			var deleteIcon = _self.find('#cart_item' + dishObject['id'] + ' .delete');
			deleteIcon.click(toRemoveCount(dishObject));
		}
		function _bindClearButton(){
			$('#cart_clear').click(_class.clear);
		}
		function _bindSubmitButton() {
			$('#cart_submit').click(function() {
				if ($('#cart_outer').hasClass('empty') || $('#cart_outer').hasClass('denied') || $('#cart_outer').hasClass('notakeout')) {
					return false;
				}
			});
			$('#in_submit').click(function() {
				if ($('#cart_outer').hasClass('empty') || $('#cart_outer').hasClass('denied')) {
					return false;
				}
			});
		}
		function _bindViewOrderButton() {
			$('a#cart_view').click(function() {
				if ($('#cart_outer').hasClass('noorder')) {
					return false;
				}
			});
		}
		function _saveCart() {
			var dishList = _self.find('li.dish');
			var cartData = {};
			var cartSort = {'sort':[]};
			dishList.each(function(i){
				var data = $(this).data('dishObject');
				data['count'] = parseInt($('#cart_count'+data['id']).html());
				if (!cartData[data['restaurantId']]) {
					cartData[data['restaurantId']] = [];
				}
				cartData[data['restaurantId']].push(data);
				if ($.inArray(data['restaurantId'], cartSort['sort'])==-1) {
					cartSort['sort'].push(data['restaurantId']);
				}
			});
			cartData['sort'] = cartSort;
			var cartDataJson = JSON.stringify2(cartData);
			$.post('cart_update.php',{'name':'cart','value':cartDataJson});
			//set_ie_class();
		}
		function _restoreCart() {
			function callback(response) {
				var cartData = $.parseJSON(response['value']);
				if(cartData!=null){
					if (cartData['sort']) {
						var sort = cartData['sort']['sort'];
						for (var k = 0; k < sort.length; k++) {
							var restaurantId = sort[k];
							if(cartData[restaurantId]!=null && cartData[restaurantId].length!=null){
								for (var j = 0; j<cartData[restaurantId].length;j++){
									_class.add(cartData[restaurantId][j],false)
								}
							}
						}
					} else {
						$.each(cartData,function(i){
							if(cartData[i] != null&&cartData[i].length!=null){
								for (var j = 0; j<cartData[i].length;j++){
									_class.add(cartData[i][j],false)
								}
							}
						});
					}
				}
				//set_ie_class();
			}
			if ($('#cart_json').size() > 0) {
				var response = {
					'ret': 1,
					'value': $('#cart_json').html()
				};
				callback(response);
			} else {
				$.get('cart_get.php',{'name':'cart'}, callback);
			}
		}
		function _bindScrollFix() {
			if (!$('body').hasClass('ie6') && !navigator.userAgent.match(/mobile/i)) {
				var cart = $('#cart_outer');
				var search = $('#sidebar_search #profile_section');
				var searchTop = (search.size() > 0) ? search.offset().top : null;
				var top = cart.offset().top;
				cart.css({'width': cart.width()});
				search.css({'width': search.width()});
				$('#cart_fix_hint').css('width', cart.width());
				var windowHeight = $(window).height();
				$(window).bind('scroll cart_change', function (event) {
					var scrollTop = $(window).scrollTop();
					var height = cart.outerHeight();
					if ($('body').hasClass('ievil')) {
						top = top - 1;
					}
					if (search.size() > 0) {
						var searchHeight = search.outerHeight();
						if (search.size() > 0 && scrollTop >= searchTop) {
							$('#sidebar_search').css('height', searchHeight);
							search.addClass('fixed');
						} else {
							$('#sidebar_search').css('height', 'auto');
							search.removeClass('fixed');
						}
					}
					if ($('#cart_unique .restaurant').size() < 1) {
						cart.removeClass('fixed');
						search.addClass('shadowed');
						$('#cart_inflater').css('height', 'auto');
						return;
					}
					if (scrollTop >= top && height + 150 < windowHeight) {
						$('#cart_inflater').css('height', height);
						$('#cart_fix_hint').hide();
						cart.addClass('fixed');
						search.removeClass('shadowed');
					} else {
						cart.removeClass('fixed');
						$('#cart_inflater').css('height', 'auto');
						top = cart.offset().top;
						if (scrollTop > height + top) {
							$('#cart_fix_hint').show();
							search.removeClass('shadowed');
						} else {
							$('#cart_fix_hint').hide();
							search.addClass('shadowed');
						}
					}
				});
			}  
		}
		function _init() {
			_restoreCart();
			_self.data('class', _class);
			_bindClearButton();
			_bindSubmitButton();
			_bindViewOrderButton();
			_bindScrollFix();
		}
		_init();
		return _class;
	};
	$.cartChanged = function(dishId, count) {
		function change(element, count) {
			if (count==0) {
				if (element.hasClass('hero_dish')) {
					element.find('.cart_count').html('+')
				} else {
					element.find('.cart_count').html('');
				}
				element.removeClass('in_cart');
				element.removeClass('in_cart_ie_hover');
			} else {
				element.find('.cart_count').html(count);
				element.addClass('in_cart');
			}
		}
		if (!dishId) {
			change($('.dish'), count);
		} else {
			if ($('body').hasClass('ie6') || $('body').hasClass('ie7')) {
				change($('#dish' + dishId), count);
				change($('#regular_dish' + dishId), count);
				change($('#hero_dish' + dishId), count);
			} else {
				change($('.dish' + dishId),count);
			}
		}
	};
	$.getDishObject = function(dishElement) { ///重要：here
		var restaurant = dishElement.firstParent('.restaurant');
		return {
			'restaurantId' : restaurant.data('id'),
			'restaurantName' : restaurant.data('name'),
			'restaurantTel' : restaurant.data('tel'),
			'restaurantTakeout' : restaurant.data('takeout'),
			'denyOrder' : restaurant.data('deny_order'),
			'revision' : restaurant.data('rev'),
			'id' : dishElement.data('id'),
			'dishRevision' : dishElement.data('rev'),
			'name' : dishElement.data('name'),
			'price' : dishElement.data('price')
		};
	};
	$.dishCartCountClick = function(event) {
		var _self = $(this).firstParent('.dish');
		var cart = $('#cart_unique');
		var count = cart.data('class').removeCount($.getDishObject(_self));
	};
	$.fn.isDishForCart = function(cart) {
		function dishClick(event) {
			var _self = $(this);
			if ($(event.target).hasClass('cart_count')) { return; }
			if (_self.hasClass('is-section')) { return; }
			if (_self.firstParent('.restaurant').hasClass('no_service')) { return; }
			if (_self.hasClass('disabled')) { return; }
			if ($('body').hasClass('ievil')) {
				_self.addClass('in_cart_ie_hover'); //after click the dish left not dark green right not light green, so this line added
			}
			var count = cart.data('class').add($.getDishObject(_self));
		}
		this.click(dishClick);
		/*
		function dishCountClick() {
			var _self = $(this).firstParent('.dish');
			var count = cart.data('class').removeCount($.getDishObject(_self));
		}
		this.find('.cart_count').click(dishCountClick);
		*/
	};
	$(function(){
		$('#cart_unique').html('').isCart();
		$('.dish').isDishForCart($('#cart_unique'));
		$('a.cart_count').click($.dishCartCountClick);
	});
})(jQuery);
