jQuery(document).ready(function($) {
	$('<div>').attr('id','popup').appendTo('body');
	$('#cart-in-line').css('z-index','30');
	// Počet položek v košíku
	counter = 0;
	totalPrice = 0;
	if($.cookie('cart')!=null&&$.cookie('cart')!="") {
		data = $.parseJSON($.cookie('cart'));
		$.each(data,function(key,value) {
			counter++;
			totalPrice += parseInt(value.attr.cena);
		});
	}

	$('#cart-in-line').html('<a href="javascript:void()" class="cart-view"><span class="counter">'+counter+'</span>ks - <span class="total-price">'+totalPrice+'</span> Kč</a> <a href="#" class="send-cart">Odeslat</a>');
	$('.remove-item').css('cursor','pointer');

	// Klik na vložit do košíku
	$('.add_item').click(function() {
		button = $(this);
		$('#popup').dialog({
			modal: true,
			buttons: {
				'Odeslat': function() {
					odeslane = {};
					
					$('#formular .atribut').each(function() {
						if($(this).children('.title').text()=="Počet") key = "item_count";
						else key = $(this).children('.title').text();
						odeslane[key] = $(this).find('select option:selected').val();
					});
					ids = button.attr('href').match(/#(\w+):(\d+)/);
					
					if (ids[1] == 'idv'){
						var parent = button.parent().parent();
					} else {
						var parent = button.parent();
					};

					odeslane[ids[1]] = ids[2];

					nazev = button.attr('rel');
					odeslane['nazev'] = nazev;


					cena = parseInt(parent.find('.discount strong:last').attr('price'));
					if (isNaN(cena)){cena = parent.find('.cena strong')[0].innerHTML.replace(/\D/, '')}
					cena *= parseInt(odeslane.item_count);
					odeslane['cena'] = cena;

			                if($.cookie('cart')==null||$.cookie('cart')=="") {
						data = [];
						outputData = {
							'id':0,
							'attr':odeslane
						};
                        			data.unshift(outputData);
						if(outputData.attr.nazev!=undefined) $.cookie('cart',JSON.encode(data),{expires: 7, path: '/'});
					}

					else {
						data = $.parseJSON($.cookie('cart'));
        			                maxNumero = 0;
                       				$.each(data,function(key,value) {
                                			maxNumero = (maxNumero<parseInt(value.id))?parseInt(value.id):maxNumero;
	                        		});

						outputData = {
			                                'id':(maxNumero+1),
                                			'attr': odeslane
                        			};

                        			if(outputData.attr.nazev!=undefined) data.unshift(outputData);
                        			$.cookie('cart',JSON.encode(data),{expires: 7, path: '/'});
					}

			                $('.counter').text(parseInt($('.counter').text())+1);
			                $('.total-price').text(parseInt($('.total-price').text())+cena);
					$('#formular').html('');
					
					$(this).dialog('close');
				},
				'Zrušit': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#popup').html('<div id="formular"></div>');

		$(this).parent().find('li.attr').each(function() {
			data = $(this).text().match(/(\w+):(.+)/);
			nazev = data[1];
			hodnoty = $.trim(data[2]).split(",");
		
			select = $('<select>');
			$.each(hodnoty,function(key,val) {
				$('<option>').text(val).val(val).appendTo(select);
			});

			$('<div class="atribut">').append($('<span>').attr('class','title').text(nazev)).append(select).appendTo('#formular');
		});


		select = $('<select class="numerofitem">');
		for(i=1;i<21;i++) $('<option>').text(i).val(i).appendTo(select);
		$('<div class="atribut">').append($('<span>').attr('class','title').text("Počet")).append(select).appendTo('#formular');

		return false;
	});

	// Klik na počet položek v košíku
	$('#cart-in-line a.cart-view').click(function() {
		if($('#cart-list').length!=0) $('#cart-list').remove();
		else {
			$('<div>')
				.attr('id','cart-list')
				.css({
					'position':'absolute',
					'z-index':'20',
					'width':'400px',
					'background-color':'#000',
					'color':'#fff',
					'-moz-border-radius':'5px',
					'border-radius':'5px',
					'padding':'10px',
					'text-align':'left'
					})
				.html('<strong>Váš košík</strong>')
				.appendTo('body')
				.hide().fadeIn();
			
			if($.cookie('cart')==null||$.cookie('cart')==""){ 
				return false;
				data = "Žádné zboží";
			}

			else {
				data = $.parseJSON($.cookie('cart'));
				myCart = "";
				$.each(data,function(key,value) {
					myCart += '<tr><td>'+value.attr.nazev+'</td><td>'+value.attr.cena+'Kč</strong></td><td style="text-align: center;"><img src="http://static.bn1.cz/alanky/images/remove.png" class="remove-item" id="'+value.id+'" /></td></tr>';
				});
			}

			$('<table>')
				.html('<tr><td><strong>Název</strong></td><td><strong>Cena</strong></td><td width="50px"><strong>Odstranit</strong></td></tr>'+myCart)
				.css('width','100%')
				.appendTo('#cart-list');
		}

		return false;
	});

	$('.send-cart').click(function() {
		$('<form>').attr({'action':'/zahradni-nabytek/objednavka/','method':'POST','id':'submit-formular'}).appendTo('body');
		$('<input>').attr({'type':'hidden','name':'data','value':$.cookie('cart')}).appendTo('#submit-formular');
		$('#submit-formular').submit();
	});

	$('.remove-item').live('click',function() {
		itemId = $(this);

		newCart = [];
		data = $.parseJSON($.cookie('cart'));
		$.each(data,function(key,value) {
			if(value.id!=itemId.attr('id')) newCart.unshift(value);
			else newPrice = parseInt($('.total-price').text())-parseInt(value.attr.cena);
		});
		$.cookie('cart',JSON.encode(newCart),{expires: 7, path: '/'});
		$(this).parent().parent().fadeOut('slow',function() {
			$(this).remove();
			$('.counter').text(parseInt($('.counter').text())-1);
			$('.total-price').text(newPrice);
		});
		$(this).parent().parent().remove();
	});
});

