var row_price_contents = '';
var row_price_id = '';
var row_price_all_contents = '';
var row_price_all_id = '';
var row_days_contents = '';
var row_days_id = '';
var date_from = false;
var date_to = false;
var total_price = 0;
var total_price_all = 0;
var count_days = 0;
var currency = 'Rur';
var column_days;
var price_rules = [];
var total_price_unsafe_element = '';

function check_rule(date,rule) {
	switch (rule[0]) {
		case '*':
			return true;
		case 'w':
			var x = date.getDay();
			return (rule[1]<=x)&&(x<=rule[2]);
		case 'd':
			var x = date.getTime();
			return (rule[1].getTime()<=x)&&(x<=rule[2].getTime());
	}
	return false;
}
function recount_price_all() {
	total_price_all = total_price;
	$('.form-price-simple-input:checked').each(function () {
		total_price_all += parseInt($(this).parent().html().replace(/\ .+/,''),10);
	});

	if (total_price_all > 0) {
		$('#'+row_price_all_id).html('<span>'+row_price_all_contents.replace('TOTAL_ALL_PRICE','</span> '+total_price_all+' '+currency)).show();
	} else {
		total_price_all = 0;
		$('#'+row_price_all_id).html('').hide();
	}

	total_price_unsafe_element.val(total_price_all);
}
function recount_price() {
	$('.form table.form-price-table span.price-tag').remove();
	total_price = 0;
	var day = new Date();
	if (count_days>0) {
		column_days = [];
		var cols = $('.form table.form-price-table th').length-2;
		for (i=0;i<cols;i++) {
			column_days[i] = 0;
		}
		for (time=date_from.getTime(); time<date_to.getTime(); time+=24*60*60*1000) {
			day.setTime(time);
			var ok = false;
			for (i in price_rules) {
				for (j in price_rules[i][1]) {
					if (check_rule(day,price_rules[i][1][j])) {
						ok = true;
						break;
					}
				}
				if (ok) {
					column_days[price_rules[i][0]-1]++;
					break;
				}
			}
			if (!ok) {
				alert('Achtung! Ich habe keine Regel für Ihr Datum.');
				return;
			}
		}
		column_days = column_days.reverse();
		$('.form table.form-price-table input:checked').each(function () {
			var price = 0;
			var field = $(this).parent();
			for (i in column_days) {
				field = field.prev();
				price += parseInt(field.text(),10) * column_days[i];
			}
			$(this).after('<span class="price-tag">'+price+' '+currency+'</span>');
			total_price += price;
		});
	}

	if (total_price > 0) {
		$('#'+row_price_id).html('<span>'+row_price_contents.replace('TOTAL_PRICE','</span> '+total_price+' '+currency)).show();
	} else {
		total_price = 0;
		$('#'+row_price_id).html('').hide();
	}
	recount_price_all();
}
function recount_days() {
	date_from = $('#row_field84 input[type=text], #row_field199 input[type=text]').eq(0).datepicker('getDate');
	date_to = $('#row_field85 input[type=text], #row_field200 input[type=text]').eq(0).datepicker('getDate');
	count_days = 0;
	if (date_from && date_to) {
		count_days = Math.round((date_to.getTime()-date_from.getTime())/(24*60*60*1000));
	}
	if (count_days > 0) {
		$('#'+row_days_id).html('<span>'+row_days_contents.replace('COUNT_DAYS','</span> '+count_days)).show();
	} else {
		$('#'+row_days_id).html('').hide();
	}
	recount_price();
}

$(function() {
	var d = new Date();
	var year = d.getFullYear();
	$.datepicker.setDefaults({dateFormat:'dd/mm/yy', firstDay:1});

	if (self_uri.substring(0,9)=='uri:/rus/') {
		$.datepicker.setDefaults({monthNames:['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'], monthNamesShort:['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'], dayNamesMin:['Вс','Пн','Вт','Ср','Чт','Пт','Сб']});
		currency = 'руб.';
	}

	$('.form table tr th:contains(Тип комнаты), .form table tr th:contains(Room type)').parent().parent().parent().addClass('form-price-table');
	$('.form table input').not('.form table.form-price-table input').addClass('form-price-simple-input').parent().addClass('form-price-cell');
	$('.form table.form-price-table td:not(:first-child):not(:last-child)').addClass('form-price-cell');

	$('.form-price-simple-input').change(recount_price_all).click(recount_price_all);
	$('.form table.form-price-table input').change(recount_price).click(recount_price);
	$('.form p.row:contains(Дата въезда) input[type=text], .form p.row:contains(Дата выезда)  input[type=text], .form p.row:contains(Check-in date)  input[type=text], .form p.row:contains(Check-out date) input[type=text]').change(recount_days);
	
	$('.form-price-cell input').before(currency+' ');
	$('.form-price-cell:not(:contains('+currency+'))').append(' '+currency);
	$('.form p.row:contains(Дата) input[type=text], .form p.row:contains(дата) input[type=text], .form p.row:contains(Date) input[type=text], .form p.row:contains(date) input[type=text]').datepicker({changeMonth:true, changeYear:true, yearRange:(year-90)+':'+(year+10)});

	row_days_contents = $('.form p.row:contains(COUNT_DAYS)').text();
	row_days_id = $('.form p.row:contains(COUNT_DAYS)').attr('id');
	row_price_contents = $('.form p.row:contains(TOTAL_PRICE)').text();
	row_price_id = $('.form p.row:contains(TOTAL_PRICE)').attr('id');
	row_price_all_contents = $('.form p.row:contains(TOTAL_ALL_PRICE)').text();
	row_price_all_id = $('.form p.row:contains(TOTAL_ALL_PRICE)').attr('id');
	total_price_unsafe_element = $('.form p.row:contains(PRICE_TOTAL_UNSAFE) input').hide();
	$('.form p.row:contains(PRICE_TOTAL_UNSAFE) *').hide();

	var price_rules_content = $('.form p.row:contains(PRICE_RULES)').text();
	if (!price_rules_content) {
		price_rules_content = $('#price_rules').text();
	}
	$('.form p.row:contains(PRICE_RULES), #price_rules').remove();
	price_rules_content = price_rules_content.replace(' ','').replace('\n','').replace('PRICE_RULES;','').split(';');
	
	for (i in price_rules_content) {
		var a = parseInt(i,10);
		var temp = price_rules_content[i].replace(' ','').replace('\n','').split('=');
		price_rules[a] = [parseInt(temp[0],10),[]];
		if (temp[1]) {
			temp = temp[1].replace(' ','').replace('\n','').split(',');
			for (j in temp) {
				var b = parseInt(j,10);
				price_rules[a][1][b] = [(temp[j][0]=='w')?'w':'d'];
				if (price_rules[a][1][b][0]=='w') {
					temp[j] = temp[j].substr(1);
				}
				temp[j] = temp[j].split('-');
				for (k in temp[j]) {
					var c = parseInt(k,10) + 1;
					price_rules[a][1][b][c] = temp[j][k];
					if (price_rules[a][1][b][0]=='w') {
						price_rules[a][1][b][c] = parseInt(temp[j][k],10);
					} else {
						var temp1 = temp[j][k].split('/');
						price_rules[a][1][b][c] = new Date(parseInt(temp1[2],10),parseInt(temp1[1],10)-1,parseInt(temp1[0],10));
					}
				}
				if (!price_rules[a][1][b][2]) {
					price_rules[a][1][b][2] = price_rules[a][1][b][1];
				}
			}
		} else {
			price_rules[a][1][0] = ['*'];
		}
	}
	$('#'+row_days_id+', #'+row_price_id+', #'+row_price_all_id).css({'color':'#e22','font-weight':'bold'});

	recount_days();
});

