var baseUrl = 'http://projektai.partner1.lt/liudoirankiai/';

$(document).ready( function() {
	$('.cart_link').live('click', updateBasket);
	
	$('.curr_am').keyup(updateBasket);
	
	var doBlink = function(obj,start,finish) { jQuery(obj).fadeOut(300).fadeIn(300); if(start!=finish) { start=start+1; doBlink(obj,start,finish); } }
	jQuery.fn.blink = function(start,finish) { return this.each(function() { doBlink(this,start,finish) }); }
	
	$('.b_update_link, form .default_nextlinecontainer a').live('click', function (e) {
		e.preventDefault();
		$(this).parents('form').submit();
	});
	
	$('#search input').focus(function () {
		if (this.value  == 'Paieška') {
			this.value = '';
		}
	});
	
	$('#search input').blur(function () {
		if (this.value  == '') {
			this.value = 'Paieška';
		}
	});
	
	$('.curr_am').focus(function () {
		if (this.value  == '0') {
			this.value = '';
		}
	});
	
	$('.curr_am').blur(function () {
		if (this.value  == '') {
			this.value = '0';
		}
	});
	
	$('.print_ico').click (function (e) {
		e.preventDefault();
		
		window.print();
	});
	
	$('#desc_table form').submit(function(e) {
		e.preventDefault();
	});
	
	$('#shipping_next').click(function (e) {
		e.preventDefault();
		$('#payment').submit();
	});
});

function updateBasket(e) {
	e.preventDefault();
	
	var currentAm		= parseInt($(this).parents('tr').find('.curr_am').val());
	var unitPrice		= parseFloat($(this).parents('tr').find('.unit_price').html().replace(/,/, '.'));
	var link			= this;
	
	switch ($(this).attr('rel')) {
		case 'up':
			currentAm++;
			break;
		case 'down':
			currentAm--;
			break;
		case 'del':
			currentAm = 0;
			break;
	}
	
	$(link).parents('form').find('.am').val(currentAm);
	
	var currentPrice	= currentAm * unitPrice;
	currentPrice		= currentPrice.toFixed(2) + '';
	currentPrice		= currentPrice.replace(/\./, ',');
	
	//console.log(link);
	
	$.ajax( {
		type	: "POST",
		url		: "index.php",
		data	: $(link).parents('form').serialize(),
		dataType	: "json",
		success	: function(msg) {
			// update product quantities
			$(link).parents('tr').find('.curr_am').val(currentAm);
			$(link).parents('tr').find('.total_price').html(currentPrice);
			
			$('#b_total_items').html(msg.cnt);
			$('#b_total_price').html(msg.price);
		
			$('#cart').blink(1, 3);
			
			// show cross sell items
			$('#cross_selling_items').html('');
			$('#cross_selling').hide();
			
			if (countProperties(msg.crossSelling) > 0) { console.log('yra');
				for(var i in msg.crossSelling) {
					var product = msg.crossSelling[i];
					$('#cross_selling_items').append('<div class="item"><img src="'+product.imageDir+'/'+product.icon+'" /><a href="'+product.link+'">'+product.title+'</a><hr /></div>');
				}
				$('#cross_selling').show();
			}
		}
	});
}

function countProperties ( obj ) {
	var count = 0;
	for (var i in obj) {
		count++
	}
	return count;
}
