
 
 basket = {
	get : function(callback) {
		basket.__request("/udata/emarket/basket.json", {}, callback);
	},	
	putElement : function(id, options, callback) {
		basket.__request("/udata/emarket/basket/put/element/" + id + ".json", options, callback);
	},
	modifyItem : function(id, options, callback) {
		if(options.amount == 0) {
			this.removeItem(id, callback);
			return;
		}
		basket.__request("/udata/emarket/basket/put/item/" + id + ".json", options, callback);
	},
	removeElement : function(id, callback) {
		basket.__request("/udata/emarket/basket/remove/element/" + id + ".json", {}, callback);
	},
	removeItem    : function(id, callback) {
		basket.__request("/udata/emarket/basket/remove/item/" + id + ".json", {}, callback);
	},
	removeAll     : function(callback) {
		basket.__request("/udata/emarket/basket/remove_all.json", {}, callback);
	},
	__cleanupHash : function(input) {
		var output = {
			customer : input.customer.object.id,
			items    : input.items,
			summary  : input.summary,
			id	:input.id
		};
		return output;
	},
	__transformOptions : function(options) {
		var o = {};
		for(var i in options) {
			var k;
			if(i.toLowerCase() != "amount") k = "options[" + i + "]";
			else k = i;
			o[k] = options[i];
		}
		return o;
	},
	__request : function(url, options, callback) {
	
		jsonp(url, basket.__transformOptions(options),
			  function(data){
				  if(callback) callback( basket.__cleanupHash(data) );
			  });
	}
};

var shortBasket = {
	recalc: function(result){//для краткой корзины в верху страницы
		var basket = $('short-basket');
		basket.getElement('.total-amount').set('html', result.summary.amount);
		basket.getElement('.total-price').set('html', result.summary.price.actual + ' Р');
		if(basket.getElement('.total-amount').get('text').toInt() > 0){
			basket.getElement('.cart-empty-text').setStyle('display','none');
			basket.getElement('.cart-full-text').setStyle('display','block');
		}
		else {
			basket.getElement('.cart-empty-text').setStyle('display','block');
			basket.getElement('.cart-full-text').setStyle('display','none');
		}
	},
	sinchronize: function(kol, sum){
		var basket = $('short-basket');
		basket.getElement('.total-amount').set('html', kol);
		basket.getElement('.total-price').set('html', sum + ' Р');
		if(kol > 0){
			basket.getElement('.cart-empty-text').setStyle('display','none');
			basket.getElement('.cart-full-text').setStyle('display','block');
		}
		else {
			basket.getElement('.cart-empty-text').setStyle('display','block');
			basket.getElement('.cart-full-text').setStyle('display','none');
		}
	}
};



var frontEndBasket = {
	replaceBasket : function(id) {
		return function(e) {
			var text, rem_item = true, item_total_price;
			if (e.summary.amount > 0) {
				text = e.summary.price.actual + ' ' + e.summary.price.suffix + '.';
				for (var i in e.items.item) {
					var item = e.items.item[i];
					if (item.id == id) {
						rem_item = false;
						item_total_price = item["total-price"].actual;
						item_total_price_original = item["total-price"].original;
					}
				}
				if (rem_item) {
					if ($('cart_item_' + id)) {
						$('cart_item_' + id).destroy();
					}
				}
				else {
					//$('cart_item_price_' + id).set('text', item_total_price);
					item_total_price_original  =  item_total_price_original ? "<s>"+item_total_price_original + ' ' + item["total-price"].suffix+"</s><br>" : '';
					var s = item_total_price_original+item_total_price + ' ' + item["total-price"].suffix;
					$('cart_summary_' + id).set('html', s);
				}
				text = 'Товаров в корзине: ' + e.summary.amount + ' шт на сумму  ' + text;
			}
			else {
				text = 'В корзине нет ни одного товара.';
				if ($('basket')) {
					$('basket').set('html', text);
				}
			}
			$('basket_info_summary').set('html', text);
			shortBasket.sinchronize(e.summary.amount, e.summary.price.actual);
		};
	},

	modify : function(id, amount_new, amount_old) {
		if (amount_new.replace(/[\d]+/) == 'undefined' && amount_new != amount_old) {
			basket.modifyItem(id, {amount:amount_new}, frontEndBasket.replaceBasket(id));
		}
	},
	remove : function(id) {
		basket.removeItem(id, frontEndBasket.replaceBasket(id));
	}
};



var singlton = {
	getInstance: function(className){
		if(typeof singlton.className != 'undefined') return singlton.className;
		else {
			eval('var snew = new '+className+'();');
			singlton.className = snew;
			return snew;
		}
	}
};	

var SimplePopup = new Class({
     Implements: [Events, Options],
     options: {
     },
     initialize: function (){
         var params = Array.link(arguments, {options: Object.type, elements: $defined});
         this.setOptions(params.options || null);
		 this.html();
     },

	html: function(){
		var _self = this;
		this.popup = new Element('div', {'id': 'simple_popup'});
		this.popup.inject(document.body);
		
		this.closeButton = new Element('div', {
			'class': 'close_button',
			'text':'X',
			'events': {
				'click': function(e){
					if(e) e.stop();
					_self.popup.setStyle('z-index', '-1');
				}
			}
		});
		this.closeButton.inject(this.popup);
		this.popup_content = new Element('div', {'class': 'popup_content'});
		this.popup_content.inject(this.popup);
	},
	show: function(e){
		var _self = this;
		this.popup.setStyles({
			'z-index': 100,
			'top': e.page.y - 80,
			'left': e.page.x - 100
		});		
		this.close.delay(1500, _self);
	},	
	close: function(){
		this.closeButton.fireEvent('click');
	},
	content: function(text){
		this.popup_content.set('html',text);
	}

});

function addToBasketEvents(){
	$$('.addToBasket').each(function(item){
		item.removeEvent('click');
		var id = item.getParent('span').getProperty('data:element-id');
		var coords = {};
		var callback = function(result){
			shortBasket.recalc(result);		
			var pops = singlton.getInstance('SimplePopup');
			pops.show(coords);
			pops.content("Товар добавлен в корзину");
		}
		
		var callback2 = function(result){
			/*var request = new umiRequest({
				url: '/udata/emarket/basket.json',
				callback: callback
			});
			request.commit();*/
			basket.get(callback);
		}
		
		item.addEvent('click', function(e){
			e.stop();		
			coords = e;
			//basket.putElement(id,{},callback);
			var url = '/emarket/buy/'+id+'/';
			var request = new umiRequest({
				url: url,
				callback: callback2
			});
			request.setValue('noredirect','1');
			request.commit();
		});
		
	});
}
