function showTV () {
	var tableHTML = '<tr>';
	var i;
	var j;
	var quantity = $("#quantitySelection").selectedValues();
	var pack = $("#packSelection").selectedValues();
	var rows = Math.ceil(quantity/2);
	
	$.getJSON("/handlers/get_receivers.php?pack="+pack, function(data){
		
		$("#packDescription").html(data.description);
		
		var receivers_options = data.options;
		for (i = 1; i <= rows; i++) {
			tableHTML += '<tr><td><div class="telek">' + i + '</div><div class="dir1">';
			tableHTML += '<div class="dir"><strong>Ресивер:</strong></div>';
			tableHTML += '<div><select name="receiver' + i + '" class="first">' + receivers_options + '</select></div>';
			tableHTML += '</div></td>';
			if (i < rows || quantity == rows*2) {
				j = i + rows;
				tableHTML += '<td><div class="telek">' + j + '</div><div class="dir1">';
				tableHTML += '<div class="dir"><strong>Ресивер:</strong></div>';
				tableHTML += '<div><select name="receiver' + j + '" class="first">' + receivers_options + '</select></div>';
				tableHTML += '</div></td>';
			}
			tableHTML += '</tr>';
		}
		$("#mainTable").html(tableHTML);
	});
}

function getPacks () {
	var typeSelection = document.getElementById('typeSelection');
	var packSelection = $("#selectionDiv select[name=pack]"); 
	packSelection.removeOption(/./);
	packSelection.ajaxAddOption("/handlers/get_packs.php", {type: typeSelection.options[typeSelection.selectedIndex].value}, "pack", function(data) { 
		packSelection.attr("selectedIndex", 0);
		showTV();
	});
}

function resetTV () {
	$("#selectionDiv select[name=quantity]").attr('selectedIndex', 0);
	$("#selectionDiv select[name=type]").attr('selectedIndex', 0);
	$("#TVprice1").html('');
	$("#TVprice2").html('');
	getPacks();
}

function calculateTV (rate) {
	var quantity = $("#quantitySelection").selectedValues();
	var type = $("#typeSelection").selectedValues();
	var pack = $("#packSelection").selectedValues();
	var receivers = $("#mainTable select[name^=receiver]");
	var requestUrl = '/handlers/calculate_price.php?quantity=' + quantity + '&type=' + type + '&pack=' + pack;
	for (i = 0; i < receivers.length; i++) {
		requestUrl += '&receiver[' + receivers[i].name.substring(8,9) + ']=' + receivers[i].options[receivers[i].selectedIndex].value;
	}
	$.getJSON(requestUrl, function(data){
		var receivers_options = data.options;
		var price1 = data.price1;
		var price2 = data.price2;
		if (price2 > 0) {
			$("#TVprice1").html('<span>Сумма:</span> ' + Math.round((price1 + price2)*rate) + ' $.');
			$("#TVprice2").html('<span>Абонплата:</span> есть');
		} else {
			$("#TVprice1").html('<span>Сумма:</span> ' + Math.round(price1*rate) + ' $.');
			$("#TVprice2").html('<span>Абонплата:</span> нет');
		}
	});
}
