var order_error = false;

$(document).ready( function() {
  calculatePrice();
  
  /*
	rows = parseInt($("#rows").attr('value'));
	
	$('#order_form #lampion_' + rows).bind('change', addRow);
  */
	
	if (order_error)
		alert('Vyplňte, prosím, pole označená červeně.');
    
  $("select.type").change(function(){
    calculatePrice();
  })  
  
  $("input.count, select.type").keyup(function(){
    calculatePrice();
  })
});

function calculatePrice() {
  var count = 0;
  var totalPrice = 0;
  
  $("input.count").each(function(){
    if (parseInt($(this).attr('value')))
      count += parseInt($(this).attr('value'));
  });
  
  $("tr.lampion").each(function(){
    if ($(this).find('td select:first').attr('value') && $(this).find('td input:first').attr('value'))
    {
      if (parseInt($(this).find('td input:first').attr('value')))
      {
        index = (count < 10) ? 'price_1' : (count < 30) ? 'price_2' : 'price_3';
        totalPrice += prices[$(this).find('td select:first').attr('value')][index] * parseInt($(this).find('td input:first').attr('value'));
      }
    }
  })
  
  if (totalPrice > 0)
    totalPrice += postagePrice;
  
  $("#totalPrice").text(num2money(totalPrice));  
}

function addRow()
{
	row_number = parseInt($("#rows").attr('value')) + 1;

	var newRow = $.ajax({
									url: "add_row/" + row_number,
									async: false
								}).responseText;
	
	$(this).parent().parent().after(newRow);
	$(this).unbind('change', addRow);
	$("#lampion_" + row_number).bind('change', addRow);
  
  $("#lampion_" + row_number).change(function(){
    calculatePrice();
  });
  
  $("#lampion_" + row_number).keyup(function(){
    calculatePrice();
  })
  
  $("#count_" + row_number).keyup(function(){
    calculatePrice();
  })
	
	$("#rows").attr('value', row_number);
}

// formatovani cen
function num2money(n_value) {
  // validate input
  if (isNaN(Number(n_value)))
    return 'ERROR';
  
  minus = (n_value < 0) ? true : false;
  
  // save the sign
  var b_negative = Boolean(n_value < 0);
  n_value = Math.abs(n_value);
  
  var s_result = '';
  
  // separate all orders
  var b_first = true;
  var s_subresult;
  while (n_value >= 1) 
  {
    s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);
    s_result = s_subresult.slice(-3) + ((b_first) ? '' : '.') + s_result;
    b_first = false;
    n_value = n_value / 1e3;
  }
  
  if (s_result == '')
    s_result = 0;
  else if (minus)
    s_result = '-' + s_result;
  
  // apply formatting and return
  return s_result;
}
