var baseUrl = 'http://projektai.partner1.lt/liudoirankiai/';
var old_curr_am = 0;
var action=false;
var object;
var go = true;
$(document).ready( function() {
	$('.cart_link').live('click', function(e){ e.preventDefault(); updateBasket(e, this);});
	
	$('.curr_am').keyup(
			function(e){
				if(e.keyCode >= 48 && e.keyCode <=57 || e.keyCode == 8) {
					action = e;
					object = this;
					if(go) {
						go = false;
						setTimeout('updateBasket()',500);
						//updateBasket(e, this);
						//this.blur();
					}
				}
			}
	);
	
	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 = '';
		} else {
			old_curr_am = 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();
	});
});

/**
 * 
 * @param e
 * @return
 * 
 * @todo to fix price calculation when quantity is wroted by hand.
 * @todo add que manager
 */
var run = 0;
var e;
function updateBasket(e, link) {
	
	
	if(e==undefined) {
		e = action;
	}
	
	
	
	if(this != window) {
		link = this;
	} 
	
	if(link == undefined) {
		link = object;
	}
	
	var currentAm		= $(link).parents('tr').find('.curr_am').val();

	if (currentAm == "") {
		currentAm = 0;
	}
	
	currentAm = parseInt(currentAm);
	
	var unitPrice		= parseFloat($(link).parents('tr').find('.unit_price').html().replace(/\./,'').replace(/,/, '.'));
	var productsCnt		= parseInt($('#b_total_items').html());
	var totalPrice		= parseFloat($('#b_total_price').html().replace(',', '.'));
	var pastAm;
	
	if(old_curr_am == 0) {
		old_curr_am = currentAm;
	}
	
	
	switch ($(link).attr('rel')) {
		case 'up':
			currentAm++;
			break;
		case 'down':
			currentAm--;
			break;
		case 'del':
			currentAm = 0;
			break;
	}
	
	var change;
	
	if(old_curr_am == currentAm) {
		change = parseInt(currentAm);
	} else {
		change = currentAm - parseInt(old_curr_am);
	}
	
	$(link).parents('form').find('.am').val(currentAm);
	
	var currentPrice	= currentAm * unitPrice;
	currentPrice		= currentPrice.toFixed(2) + '';
	currentPrice		= currentPrice.replace(/\./, ',');
	
	//console.log('old '+old_curr_am);
	//console.log('change '+change);
	
	// update product quantities
	$(link).parents('tr').find('.curr_am').val(currentAm);
	$(link).parents('tr').find('.total_price').html(currentPrice);
	var tp = unitPrice;
	
	var fp = totalPrice + (tp*change);
	fp = new String(fp.toFixed(2)).replace(/\./,',');

	$('#b_total_items').html(productsCnt+(change));
	$('#b_total_price').html(fp);
	
	$('#cart').blink(1, 3);
	
	// show cross sell items
	$('#cross_selling_items').html('');
	$('#cross_selling').hide();
	object = link;
	
	if(action != false) {
	
		sendBasket();

	} else {
		if(run < 1) {
			run = run +1;
			setTimeout('sendBasket()',1000);
		}
	}
	
	old_curr_am = 0;
	go = true;
	action = false;
}

function sendBasket() {
	link = object;
	run = 0;
	$.ajax( {
		type	: "POST",
		url		: "index.php",
		data	: $(link).parents('form').serialize(),
		dataType	: "json",

		success	: function(msg) {
		
			// show cross sell items
			$('#cross_selling_items').html('');
			$('#cross_selling').hide();
			
			if (countProperties(msg.crossSelling) > 0) {
				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;
}