// JavaScript Document
var thousand_sep = " ";
var decimal_point = ",";
var default_precision = 0;

// -------------------------------------------------------------

function deleteCartItem(idKey, currency)
{
	rowCount = $('tr[id*="cartTableRow"]').length;
	
	if(rowCount > 1)
	{
		$('#cartTableRow' + idKey).remove();
		//$.post("action.php", { action: "cartDeleteItem", id: idKey }); // save setting
		$.ajax({
		   type: "GET",
		   url: "action.php?action=cartDeleteItem&id="+idKey,
			success: function(){
				recalcCartTotalPrice(currency);
				document.location.reload();
			}
		});
				
	}
	else
	{
		if(confirm('Odstraňujete z košíku poslední položku. Košík bude vymazán.'))
		{
			$('#cartTableRow' + idKey).remove();

			$.ajax({
			   type: "GET",
			   url: "action.php?action=cartDeleteItem&id="+idKey,
			   success: function(){
					document.location.reload();
				}
			});
 			
		}
	}
}

// -------------------------------------------------------------

function changePieces(idKey, currency)
{
	var price = $('#cartPcsPrice' + idKey).val() * $('#cartPieces' + idKey).val();
	var lastDeliveryId = $('#lastDeliveryId').val();
	
	$('#cartPriceLabel' + idKey).html(formatPrice(price, currency));

	// save setting
	$.post("action.php", { action: "cartChangePieces", id: idKey, pieces: $('#cartPieces' + idKey).val() },  function(data){
		changeDeliveryByCountry(currency);
		recalcCartTotalPrice(currency);
		
		/*$('#cartDeliveryWrapper').load('cart-delivery.php', function() {
			$('#delivery' + lastDeliveryId).click();
			recalcCartTotalPrice(currency);
		});		*/
  	});	
	
}

// -------------------------------------------------------------

function recalcCartTotalPrice(currency)
{
	var rows = $('tr[id*="cartTableRow"]');
	var totalPrice = 0;
	var totalPieces = 0;
	var price = 0;
	
	$.each(rows, function(index, value) { 
		key = value.getAttribute('key');
		price = $('input[id*="cartPcsPrice' + key + '"]').val() * $('input[id*="cartPieces' + key + '"]').val();
		totalPieces = totalPieces + parseFloat($('input[id*="cartPieces' + key + '"]').val());
		totalPrice = totalPrice + parseFloat(price);
	});
	
	
	$('tr[minprice]').each(function(index) {
		
		if($(this).attr('minprice') != '' && $(this).attr('maxprice') != '')
		{
			if(totalPrice > $(this).attr('maxprice') || totalPrice < $(this).attr('minprice')) 
			{
				$(this).hide();
				
				selInput = $(this).find('input[type="radio"]');
				if(selInput.attr("checked"))
				{
					selInput.attr("checked", '');
					
					$('#lastDeliveryId').val(null);
					$('#cartPrice_delivery').val(null);
					$('#deliveryRowName').html('');
				}
			}
		}
		
	});
	
	//$('#indexCartPieces').html(totalPieces);
	$('#indexCartPrice').html(formatPrice(totalPrice, currency, 2));

	if($('#cartPrice_delivery').val())	
		var cartPriceDelivery = parseFloat($('#cartPrice_delivery').val());
	else
		var cartPriceDelivery = 0;

	if($('#cartPrice_payment').val())
		var cartPricePayment = parseFloat($('#cartPrice_payment').val());
	else
		var cartPricePayment = 0;

	if(!postageLimit || (postageLimit && postageLimit >= totalPrice))
	{
		$('#deliveryRowPrice').html(formatPrice(cartPriceDelivery, currency));
		$('#paymentRowPrice').html(formatPrice(cartPricePayment, currency));
		
		$('strong[id^="deliveryPriceLabel"]').each(function(index)
		{
			if($(this).attr('defprice') > 0)
				$(this).html('+' + formatPrice($(this).attr('defprice'), currency));
			else
				$(this).html('<i>zdarma</i>');
		});

		totalPrice = totalPrice + cartPriceDelivery + cartPricePayment;
	}
	else
	{
		$('#deliveryRowPrice').html(formatPrice(0, currency));
		$('#paymentRowPrice').html(formatPrice(0, currency));
		$('strong[id^="deliveryPriceLabel"]').html('<i>zdarma</i>');
	}
		
	
	$('#cartTableTotalPrice').html(formatPrice(totalPrice, currency));
	$('#totalPrice').html(formatPrice(totalPrice, currency));
	
	
	
}

// -------------------------------------------------------------

function changeDelivery(deliveryLabel, priceVal, currency, obj)
{

	$('#lastDeliveryId').val(obj.value);
	$('#deliveryRowName').html($('#' + deliveryLabel).html());
	//$('#deliveryRowPrice').html(formatPrice(priceVal, currency));
	$('#cartPrice_delivery').val(priceVal);
	
	recalcCartTotalPrice(currency);
}

// -------------------------------------------------------------

function changePayment(paymentLabel, priceVal, currency, obj)
{
	$('#lastPaymentId').val(obj.value);
	$('#paymentRowName').html($('#' + paymentLabel).html());
	//$('#paymentRowPrice').html(formatPrice(priceVal, currency));
	$('#cartPrice_payment').val(priceVal);
	
	recalcCartTotalPrice(currency);
}

// -------------------------------------------------------------

function showTableDelivery(obj, currency)
{
	if(obj.checked)
		$('#tableCustomerDelivery').show();
	else
		$('#tableCustomerDelivery').hide();
		
	changeDeliveryByCountry(currency)
}

// -------------------------------------------------------------

function changeDeliveryByCountry(currency)
{
	var idCountry;
	var lastDeliveryId = $('#lastDeliveryId').val();

	
	if($('#tableCustomerDelivery').css('display') != 'none')
		idCountry = $('#d_country').val();
	else
		idCountry = $('#country').val();
	
	if($('#country :selected').text() == 'Slovensko') 
	{
		$('#customerTypeFirm').attr('disabled', 'disabled');
		$('#customerTypeFirm').attr('checked', '');
		$('#customerTypeUser').attr('checked', 'checked');
		changeCustomerType('user');
	}
	else
		$('#customerTypeFirm').attr('disabled', '');
		
	
	$('#cartDeliveryWrapper').load('cart-delivery.php?idCountry=' + idCountry + '&checkedId=' + lastDeliveryId, function() {
		
		$('#delivery' + $('input[name="id_delivery_type"]:checked').val()).click();
		$('#payment' + $('input[name="id_delivery_type"]:checked').val()).click();
		
		recalcCartTotalPrice(currency);
		
	});		
}


// -------------------------------------------------------------

function cartDisableCustomerContact(val, currency)
{
	if(val)
	{
		$('#tableCustomer').attr('class', 'toGray');
		$('#tableCustomerDelivery').attr('class', 'toGray');
		$('#tableOther strong').attr('class', 'toGray');
		
		//$('#savedDeliveryAddresses').attr('disabled', 'disabled');
		$('#name').attr('disabled', 'disabled');
		$('#surname').attr('disabled', 'disabled');
		$('#firm').attr('disabled', 'disabled');
		$('#street').attr('disabled', 'disabled');
		$('#zipcode').attr('disabled', 'disabled');
		$('#city').attr('disabled', 'disabled');
		$('#country').attr('disabled', 'disabled');
		//$('#delivery_address').attr('disabled', 'disabled');
		$('#d_name').attr('disabled', 'disabled');
		$('#d_surname').attr('disabled', 'disabled');
		$('#d_firm').attr('disabled', 'disabled');
		$('#d_street').attr('disabled', 'disabled');
		$('#d_zipcode').attr('disabled', 'disabled');
		$('#d_city').attr('disabled', 'disabled');
		$('#d_country').attr('disabled', 'disabled');
		$('#phone').attr('disabled', 'disabled');
		$('#email').attr('disabled', 'disabled');
		
		$.post("action.php", { action: "getCustomer" },  function(data){
			if(data)
			{
				var customerObject = $.parseJSON(data);

				$('#name').val(customerObject['name']);
				$('#surname').val(customerObject['surname']);
				$('#firm').val(customerObject['firm']);
				$('#street').val(customerObject['street']);
				$('#zipcode').val(customerObject['zipcode']);
				$('#city').val(customerObject['city']);
				$('#country').val(customerObject['id_country']);
			}
		});	
		
		$.post("action.php", { action: "getCustomerDeliveryAddress", id: $('#savedDeliveryAddresses').val() },  function(data){
			if(data)
			{
				var deliveryObject = $.parseJSON(data);

				$('#d_name').val(deliveryObject['name']);
				$('#d_surname').val(deliveryObject['surname']);
				$('#d_firm').val(deliveryObject['firm']);
				$('#d_street').val(deliveryObject['street']);
				$('#d_zipcode').val(deliveryObject['zipcode']);
				$('#d_city').val(deliveryObject['city']);
				$('#d_country').val(deliveryObject['id_country']);
				
				changeDeliveryByCountry(currency);
			}
		});	
	}
	else
	{
		$('#tableCustomer').attr('class', '');
		$('#tableCustomerDelivery').attr('class', '');
		$('#tableOther strong').attr('class', '');
		
		//$('#savedDeliveryAddresses').attr('disabled', '');
		$('#name').attr('disabled', '');
		$('#surname').attr('disabled', '');
		$('#firm').attr('disabled', '');
		$('#street').attr('disabled', '');
		$('#zipcode').attr('disabled', '');
		$('#city').attr('disabled', '');
		$('#country').attr('disabled', '');
		//$('#delivery_address').attr('disabled', '');
		$('#d_name').attr('disabled', '');
		$('#d_surname').attr('disabled', '');
		$('#d_firm').attr('disabled', '');
		$('#d_street').attr('disabled', '');
		$('#d_zipcode').attr('disabled', '');
		$('#d_city').attr('disabled', '');
		$('#d_country').attr('disabled', '');
		$('#phone').attr('disabled', '');
		$('#email').attr('disabled', '');
	}
}

// -------------------------------------------------------------

function savedDeliveryAddressChange()
{
	if($('#savedDeliveryAddresses').val() == '')
	{
		$('#d_name').val('');
		$('#d_surname').val('');
		$('#d_firm').val('');
		$('#d_street').val('');
		$('#d_zipcode').val('');
		$('#d_city').val('');
	}
	else
	{
		$.post("action.php", { action: "getCustomerDeliveryAddress", id: $('#savedDeliveryAddresses').val() },  function(data){
			if(data)
			{
				var deliveryObject = $.parseJSON(data);

				$('#d_name').val(deliveryObject['name']);
				$('#d_surname').val(deliveryObject['surname']);
				$('#d_firm').val(deliveryObject['firm']);
				$('#d_street').val(deliveryObject['street']);
				$('#d_zipcode').val(deliveryObject['zipcode']);
				$('#d_city').val(deliveryObject['city']);
				$('#d_country').val(deliveryObject['id_country']);
			}
		});	
	}	
}

// -------------------------------------------------------------

function changeCustomerType(val)
{
	if(val == 'firm')
	{
		$('tr[id^="tableRowFirm"]').show();
	}
	else
	{
		$('tr[id^="tableRowFirm"]').hide();
	}
}


// -------------------------------------------------------------


function validateOrder(formId)
{
	var validateItems = new Array();
	
	if($('#lastDeliveryId').val() == '')
	{
		alert('Nemáte vybraný typ doručení zásilky. Vyberte jej prosím.');
		return false;
	}
	
	if($('#delivery_address').attr("checked"))
		validateItems = Array('name', 'surname', 'street', 'zipcode', 'city', 'phone', 'email', 'd_name', 'd_surname', 'd_street', 'd_city', 'd_zipcode');
	else
		validateItems = Array('name', 'surname', 'street', 'zipcode', 'city', 'phone', 'email');
	
	if(CheckForm(formId, validateItems))
	{
		return true;
	}
	else
	{
		return false;
	}
	
	return false;
}


// -------------------------------------------------------------


function validateRegistration(formId)
{
	var validateItems = new Array();
	
	if($('#delivery_address').attr("checked"))
		validateItems = Array('code', 'username', 'password1', 'password2', 'name', 'surname', 'street', 'zipcode', 'city', 'phone', 'email', 'd_name', 'd_surname', 'd_street', 'd_city', 'd_zipcode');
	else
		validateItems = Array('code', 'username', 'password1', 'password2', 'name', 'surname', 'street', 'zipcode', 'city', 'phone', 'email');
	
	if(CheckForm(formId, validateItems, Array('password1', 'password2')))
	{
		return true;
	}
	else
	{
		return false;
	}
	
	return false;
}
	
// -------------------------------------------------------------

function checkUsernameExist(myUsername)
{
	$.post("action.php", { action: "checkUsernameExist", username: myUsername },  function(data){
		if(data)
		{
			$('#existUsername').html('<i><b>' + myUsername + '</b></i>')
			$('#rowUsernameExist').show();
			$('#username').val('');
			$('#username').focus();
		}
		else
		{
			$('#rowUsernameExist').hide();
		}
	});	
	
	return false;
}

// -------------------------------------------------------------

function showProducerFilter()
{
	
	$('#producerFilter').toggle();
	
}

// -------------------------------------------------------------

function showCartLogin()
{
	$('#cartLoginForm').toggle();
	$('#username').focus();
}

// -------------------------------------------------------------
// -------------------------------------------------------------


//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
function showCartInfo(){
	document.getElementById('cartInfo').style.display = 'block';	
}


//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
function hideCartInfo(){
	document.getElementById('cartInfo').style.display = 'none';
}


//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
function gotoCart(lang){
	window.location.href = document.getElementsByTagName('base')[0].href + lang + '/kosik/';
}


// -------------------------------------------------------------

function formatPrice(priceValue, currency, decimalsCount)
{
	if(decimalsCount == null) var decimalsCount = 2;

	return formatFloat(parseFloat(priceValue), decimalsCount, 1) + ' ' + currency;
}

// -------------------------------------------------------------

function formatFloat(aFloat, aPrecision, aRound)
{
	try {
		precision = default_precision;
		if(!isNaN(aPrecision))
		if(Math.abs(aPrecision)<=10)
		precision = aPrecision;
	} catch(e) {
		precision = default_precision;
	}
	
	try {
		number = parseFloat(aFloat+'');
		if(isNaN(number))
			return "NaN";
	} catch(e) {
		return "NaN";
	}


	number = Math.round(number * Math.pow(10, aRound)) / Math.pow(10, aRound);
	integerpart = '' + ((number<0) ? Math.ceil(number) :
	Math.floor(number));
	decimalpart = Math.abs(Math.round((number - integerpart)*(Math.pow(10, precision))));
	
	if(decimalpart<10)
		decimalpart="0"+decimalpart;
	if(decimalpart==0)
		decimalpart="00";
	
	var buff = "";
	for(j=-1, i=integerpart.length; i>=0; i--, j++){
		if((j%3) == 0 && j>1)
			buff = thousand_sep + buff;
		buff = integerpart.charAt(i) + buff;
	}
	
	if(precision>0)
		return buff+decimal_point+decimalpart;
	return buff;
}


