/*
 * Shopping cart widget
 */
 
(function () {
	//constructor
	LAMP.Cart = function() {
	
		var self;
		var hidden = true;
		var cartTableShown = false;
		
		// public fields
		
		var items = new Array();
		
		var redraw = function(items, cost) {

			$('#cartdiv').slideUp('normal', function() {
				$('#cartitems').html(items);				
				$('#cartcost').html(formatPrice(cost));
				
				var cartend = 'товаров';
				if((items > 4) && (items < 21)) {
					cartend = 'товаров';
				} else if((items % 10) == 1) {
					cartend = 'товар';
				} else if(((items % 10) >= 2) && ((items % 10) <= 4)) {
					cartend = 'товара';
				}
				
				$('#cartend').html(cartend);				
				$('#cartdiv').slideDown();
			});				
			hidden = false;			
			
		};
		
		var drawTable = function(cartItems, order) {
											
			if(cartTableShown) {
				$('#cartholder').slideUp();
			}
		
			cartTableShown = true;
		
			//alert('drawTable!');
			
			if(!cartItems || cartItems.length < 1) {
				$('#cartholder').html('Корзина пуста.<br /> Вы можете добавить товары в корзину, найдя их через форму поиска, либо <a href="/products">в каталоге</a>.');
				$('#cartholder').show();
				return;
			}
			
			hbegin = '<table id="carttable" cellspacing="0"><tr><th>Кол-во</th><th>Наименование</th><th>Стоимость, р.</th></tr>';
			
			hc = '';
			
			//alert(items);
			
			var totalPrice = 0;
			
			for (type in cartItems) {				
				items = cartItems[type];				
				for(i=0; i < items.length; i++) {

					var count, price, pnum = '';
					if (type == 'lamp') {
						var count = items[i][0];
						var price = items[i][6];
						var pnum = items[i][7];						
					} else if (type == 'accessory') {						
						var count = items[i][0];
						var price = items[i][2];						
					}
					totalPrice += price * count;
					//alert('!');
					//hc += '<tr><td>asdf</td></tr>';
					if(order) {
						hc += '<tr><td class="ccol1">'+count+'</td>';
					} else {
						hc += '<tr><td class="ccol1"><input type="text" value="'+count+'" class="input-text quantity" id="'+items[i][1]+'" itemType="'+type+'"/></td>';
					}
					if (type == 'lamp') {
						hc += '<td class="ccol2">Лампа для '+items[i][3]+' '+items[i][2];
						if(pnum != '') hc += ' ('+pnum+')';
					} else if (type == 'accessory') {
						hc += '<td class="ccol2">' +items[i][4];	
					}
					hc += '</td><td class="ccol3">'+formatPrice(price * count)+'</td></tr>';
				};				
			}
			
			hc += '<tr><td colspan="3" class="ctotal">Всего: &nbsp; '+formatPrice(totalPrice)+'</td></tr>';
			
			if(order) {
				hend = '</table>';
			} else {
				hend = '<tr><td colspan="3" class="cbut">'+
				'<a id="msglink" class="butlink" style="float: left; margin: 0" href="#" onclick="cart.update(); return false">Обновить</a>'+
				'<a id="msglink" class="butlink" style="float: right; margin: 0;" href="/checkout/request">Оформить &raquo;</a>'+				
				'</td></tr></table>';
			}										
			
			$('#cartholder').html(hbegin+hc+hend);
			
			
			$('#cartholder').slideDown();
			
		};
	
	
		// public methods
		
		//this.addItem = function(alias, bAlias) {
		this.addItem = function(type, id) {
			//alert('ie: '+id);
			
			var url = '/plugins/projectorlamps/controller.php?cmd=addtocart&type='+type+'&id='+id;
			url += '&rnd=' + ('' + Math.random()).substring(10);
			
			progressShow();
			
			$.getJSON(url, function(o) {
				progressHide();
				
				if(o.res == 'error' || !o.cart) {
					alert('Error: ' + o.reason);				
				} else {	
					//alert('fine!' + o.cart.items);
					redraw(o.cart.items, o.cart.cost);
				}
			});
			
			if(typeof pageTracker != 'undefined') {pageTracker._trackPageview('/ajax/addtocart')};
			
		};
		
		this.addItemByAlias = function(lamp, brand) {
		
			var url = '/plugins/projectorlamps/controller.php?cmd=addtocart&type=lamp&lamp='+lamp+'&brand='+brand;
			url += '&rnd=' + ('' + Math.random()).substring(10);
			
			progressShow();
			
			$.getJSON(url, function(o) {
				progressHide();
				if(o.res == 'error' || !o.cart) {
					alert('Error: ' + o.reason);				
				} else {	
					//alert('fine!' + o.cart.items);
					redraw(o.cart.items, o.cart.cost);
				}
			});
			
			if(cartTableShown) {
				//alert('lets play!');
				$('#cartholder').slideUp();
				this.showTable();								
			}
			
			if(typeof pageTracker != 'undefined') {pageTracker._trackPageview('/ajax/addtocart')};			
		};
		
		this.showTable = function(order) {
			//alert('showTable!');
			
			var url = '/plugins/projectorlamps/controller.php?cmd=getcart&order='+order;
			url += '&rnd=' + ('' + Math.random()).substring(10);
			
			progressShow();
			
			$.getJSON(url, function(o) {
				progressHide();
				if(o.res == 'error' || !o.cart) {
					alert('Error: ' + o.reason);				
				} else {	
					//alert('fine!' + o.cart.items);
					//redraw(o.cart.items, o.cart.cost);
					//alert('ok!');
					drawTable(o.cart, order);
				}
			});
		};
		
		this.yo = function() {
			alert('yo!');
		};
		
		this.update = function() {
			//alert('update!');
			
			var data = new Object();
			data.id = new Array();
			data.value = new Array();
			
			var types = new Array();
			var ids = new Array();
			var values = new Array();
			
			$('.quantity').each(function(i) {
				//alert(this.id);
				//var a = new Array();
				//a[this.id+''] = 23;//this.value;
				//map.push(a);
				//map[this.id] = this.value;
				//json += '"'+this.id+'": "'+this.value+'", '				
				//eval('data.id'+(this.id)+' = this.value');
				//data.map[this.id] = this.value;
				//data.id.push(this.id);
				//data.value.push(this.value);
				types.push($(this).attr('itemType'));
				ids.push(this.id);
				values.push(this.value);
			});
			
			data.types = types.join(',');
			data.ids = ids.join(',');
			data.values = values.join(',');
			
			//json = json.substring(0, json.length-2) + '}';
			//alert(json);
			
			//alert(map[7177]);
			//alert(map[7190]);
			//alert(map[7191]);
			
			//alert(Object.toJSON(map));
			//alert(JSON.stringify(map));
			//json = new Object();
			//json.data1 = 'value1';
			//alert(data);
			//alert(data.map);
			
			progressShow();
			
			$.post("/plugins/projectorlamps/controller.php?cmd=cartupdate", data, function(o) {
				progressHide();
				//alert(o);
				if(o.res != 'ok') {
					alert('Error: '+o.reason);
				} else {
					//alert('ok');
					redraw(o.cartsum.items, o.cartsum.cost);
					drawTable(o.cartitems);
				}
				
			}, 'json');
			
			return false;
		};
	
	};
	
	//self = this;

})();
