function init(data){
	$('#data_table').databind(data);
}
//selectedItemsIds
var siis = {};

function calcAll(){
	var sumWithoutTax = 0;
	for(var i in siis){
		sumWithoutTax += parseInt(siis[i]['sumTd'].html());
	}	
	$('#sum_without_tax').html(sumWithoutTax);
	
	var discount = parseInt($('#discount').val());
	var sumWithoutTaxWithDiscount = Math.round(sumWithoutTax*(100-discount)/100);
	$('#sum_without_tax_with_discount').html(sumWithoutTaxWithDiscount);
	
	var nds = Math.round(sumWithoutTaxWithDiscount * 0.2);
	$('#nds').html(nds);
	
	var nr = Math.round(sumWithoutTaxWithDiscount * 0.005);
	$('#nr').html(nr);
	
	var toPay = sumWithoutTaxWithDiscount + nds + nr;
	$('#to_pay').html(toPay);
}

function calcTotalRow(obj){
	var time = 5;
	$(obj).parent().parent().find("td select.time option:selected").each(function () {
        time = parseInt($(this).val());
	});
	var days = parseInt($(obj).parent().parent().find('td input.day_count').val());
	var rate = 1;
	$(obj).parent().parent().find("td select.rate option:selected").each(function () {
        rate = parseInt($(this).val());
	});
	
	var showDay = 288*rate;
	$(obj).parent().parent().find('td.show_day').html(showDay);
	
	var showPeriod = showDay * days;
	$(obj).parent().parent().find('td.show_period').html(showPeriod);
	
	var showAll = (showPeriod * time)/60;	
	$(obj).parent().parent().find('td.show_all').html(Math.round(showAll));
	
	
	
	var showAllTime = showAll;//parseInt($(obj).parent().parent().find('td.show_all').html());
	var price = parseInt($(obj).parent().parent().find('td.field\\[price\\]').html());
	$(obj).parent().parent().find('td.sum').html(Math.round(price*showAllTime));
	
	calcAll();
}

function paintRows(){
	var i = 0;
	$('#data_table tbody tr').each(function(){
		$(this).addClass('row' + (i%2));
		i++;
	});
}

function dateStartChanged(obj){
	if($(obj).parent().parent().find('td input.day_count_e').val() == '')
		return;
	var days = calcDate($(obj).val(), $(obj).parent().parent().find('td input.day_count_e').val());
	if (days<1)
		alert("В указаном периоде меньше одного дня.")
	$(obj).parent().parent().find('td input.day_count').val(days);
	$(obj).parent().parent().find('td input.day_count').change();
}

function dateEndChanged(obj){
	if($(obj).parent().parent().find('td input.day_count_s').val() == '')
		return;
	var days = parseInt(calcDate($(obj).parent().parent().find('td input.day_count_s').val(), $(obj).val()));
	if (days<1)
		alert("В указаном периоде меньше одного дня.")
	$(obj).parent().parent().find('td input.day_count').val(days);
	$(obj).parent().parent().find('td input.day_count').change();
}


function calcDate(start, end){
	var startArr = start.split("/");
	var endArr = end.split("/");
	var startDate = new Date(startArr[2],startArr[1],startArr[0]);
	var endDate = new Date(endArr[2],endArr[1],endArr[0]);
	var days = (endDate.getTime() - startDate.getTime())/86400000;
	return days;
}

function showMore(){
	if($('.more').css('display') == "none"){
		$('.more').show();
		$('#more_href').html('убрать информацию');
	}else{
		$('.more').hide(); 
		$('#more_href').html('показать информацию');
	}
}

function showError(mess){
	alert(mess);
}


$(function(){
	init(data);
	paintRows();
		
	$('.check_box').change(function () {

		var id = $(this).parent().parent().find('td.field\\[id\\]').html();
		if($(this).attr('checked') == true){
			siis[id] = { 
				'sumTd': $(this).parent().parent().find('td.sum'),
				'city': $(this).parent().parent().find('td.field\\[city\\]').html(),
				'place': $(this).parent().parent().find('td.field\\[location\\]').html(),
				'price': $(this).parent().parent().find('td.field\\[price\\]').html(),
				'fromInput' : $(this).parent().parent().find('td input.day_count_s'),
				'toInput' : $(this).parent().parent().find('td input.day_count_e '),
				'daysInput' : $(this).parent().parent().find('td input.day_count'),
				'timeSelect' :  $(this).parent().parent().find("td select.time"),
				'rateSelect' :  $(this).parent().parent().find("td select.rate"),
			};
			$(this).parent().parent().addClass('selected');
		}else{
			delete siis[id];
			$(this).parent().parent().removeClass('selected');
		}
		calcAll();
	});
	
	$('.date').datepicker({ 
		dateFormat: 'dd/mm/yy',
		dayNames: ['Понедельник', 'Вторник', 'Среда', 'Четвер', 'Пятница', 'Субота', 'Воскресенье'],
		dayNamesMin: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		nextText: 'Следующий',
		prevText: 'Предыдущий'
	});
	
	$('.day_count_s').change(function(){
		dateStartChanged(this);
	});
	
	$('.day_count_e').change(function(){
		dateEndChanged(this);
	});
	
	$('.number').keyup(function(){
		if($(this).val() == ''){
			$(this).val(0);
			return;
		}
		$(this).val(parseInt($(this).val()));
	});
	
	$('#discount').keyup(function(){
		calcAll();
	});
	
	$('.time').change(function(){
		calcTotalRow(this);
	});
	
	$(".day_count").change(function(){
		if($(this).val() == ''){
			$(this).val(0);
		}
		calcTotalRow(this);
	});
	
	$('.rate').change(function(){
		/*var rate = 1;
        $("select option:selected").each(function () {
              rate = parseInt($(this).val());
        });*/
        calcTotalRow(this);
	});
	
	$('#send_request').click(function(){
		if($('#name').val() == ""){
			showError("Введите имя");
			return false;
		}
		if($('#mail').val() == ""){
			showError("Введите email");
			return false;
		}
		if($('#phone').val() == ""){
			showError("Введите номер телефона");
			return false;
		}
		var elements = {};
		var j = 0;
		for(var i in siis){
			var time = 0;
			siis[i]['timeSelect'].find("option:selected").each(function () {
		        time = parseInt($(this).val());
			});
			
			var rate = 0;
			siis[i]['rateSelect'].find("option:selected").each(function () {
		        rate = parseInt($(this).val());
			});
			elements[j] ={
				'sum'  : siis[i]['sumTd'].html(), // $(this).parent().parent().find('td.sum'),
				'city' : siis[i]['city'],
				'place' : siis[i]['place'], 
				'price': siis[i]['price'],
				'from' : siis[i]['fromInput'].val(), //$(this).parent().parent().find('td input.day_count_s'),
				'to'   : siis[i]['toInput'].val(), //$(this).parent().parent().find('td input.day_count_e '),
				'days' : siis[i]['daysInput'].val(), //$(this).parent().parent().find('td input.day_count'),
				'time' : time,
				'rate' : rate
			}
			j++;
		}
		
		dataToSend = {
			'elements' : elements,
			'sum' : $('#sum_without_tax').html(),
			'discount' : $('#discount').val(),
			'sum_d' : $('#sum_without_tax_with_discount').html(),
			'nds' : $('#nds').html(),
			'nr' : $('#nr').html(),
			'to_pay' : $('#to_pay').html(),
			'mail': $('#mail').val(),
			'name': $('#name').val(),
			'phone': $('#phone').val()
		}
		
		$.ajax({
	        type: "POST",
	        url: 'send_request.php',
	        data: dataToSend,
	        dataType: "json",
	        success: function(data) {
				
			},
			error: function(){
				
			}
		});
		alert("Спасибо за внимание, ваш запрос отправлен, и будет обработ в ближайшее время.");
	});
}); 