/* Actions for product-buttons in webshop_standard.php */
$(document).ready( function () {

	$('input.button_buy').focus( function () { $(this).blur(); });

	reload();

	$('.prodSection').change( function () {

		propID = $(this).val();
		price = $('#prod_price').val();
		productID = $('#prodId').val();

		if(propID != 0){
			imageID = $('#prod_'+propID).attr('class');
		}else{
			imageID = 0;
		}

		if(imageID != 0){
			img = $('#thumbnailImage'+imageID).attr('src');

			$('#productImageLargeTD').html('<img src="'+img+'">');
		}

		$.get('xmlhttp/checkPrice.php',{ propID: propID, price: price, productID: productID, imageID: imageID }, function (data) {
			$('.price-body').html(data+':-');
		});
	});

	$('#webshop-cart input.amount').keyup( function(){

		var value = $(this).val();

		if(parseInt(value)){

			var uniqueID = $(this).attr('id');

			$.post('xmlhttp/cartaction.php', { action: 'edit', prodId: 1, uniqueId: uniqueID, amount: value }, function(data){

				data = data.split('|');

				$('.cart').html(data[0]);
				$('#showCart').attr('value', 1);

				$('td.tot_'+uniqueID).html(data[1]);

				$('td.cart_value').html(data[3]);

				$('td.cart_amount span').html(data[4]);

				$('span#tot_price').html(data[2]);

				$('#webshop-cart div.klarna_payment').html(data[5]);
			});
		}
	});
});

function reload(){
	$('input.button_buy').click( buy );
	$('a.button_buy').click( buy );

	fixButtons();
}


function buy(){

	var prodId = $(this).attr('name');
	var prodQt = $('input:text#amount_'+ prodId).val();
	var prodSection = $('#productForm select').serialize();

	$('.cart .basket .items').html('Uppdaterar...');
	
	$('div.confirm-overlay').show();
	$('div.confirm-alert').show();

	$.post('xmlhttp/cartaction.php', { action: 'add', prodId: prodId, prodQty: prodQt, prodSection: prodSection }, function (data) {
		$('.cart').html(data);
		$('#showCart').attr('value', 1);

		fixButtons();
	});

	return false;

}


function removeItem(uniqueId, row, prodId){

	$.post('xmlhttp/cartaction.php', { action: 'del_cart', uniqueId: uniqueId, prodId: prodId }, function (data) {	

		data = data.split('|');

		if (data[0] == 'error') {
			alert("ERROR");
		} else if(data[0] == 'empty'){
			$('#top .cart .cart_items').hide();
			$('.basket .items .amount').html('0');
			$('.basket .items .value').html(data[1]);

			$('#showCart').attr('value', 0);

			$('#top .cart .icon img').attr('src', '/static/images/icon_cart_empty.png');

		} else {
			$('#cart tr#r_'+row).fadeOut();

			$('.basket .items .amount').html(data[0]);
			$('.basket .items .value').html(data[1]);
			$('#cart .totalt').html(data[1]);
			$('#cart .totalt_shipping').html(data[2]);
		}
	});
}

