var ajaxBaseDictsUrl = "index2.php?option=com_csbronni&task=ajax&model=dicts&no_html=1&tmpl=json&method=";

window.addEvent('domready', function() {
	$('search-mod').addEvent('submit', submit_form);
	$('DepartureCityComboBox_combo').addEvent('change', change_departureCity);	
	$('DestinationCountryComboBox_combo').addEvent('change', change_destinationCountry);
	/* города вылета */
	//loadDepartureCities();
	BeginDate = new Date().addDays(15);
	$("DateFromTextBox").value = BeginDate.toFormatString();
	new Calendar({ DateFromTextBox: 'd.m.Y' }, { 
  	classes: ['dashboard'], 
  	direction: 1,  
  	offset: 1,
  	days: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
  	months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']
  });
});

/* Первичная загрузка городов*/
function loadDepartureCities() {
	var url = ajaxBaseDictsUrl + "getDepartureCities";
	new Json.Remote(url, {
		onComplete: function(responce) {
			RenderItemsComboBox(responce['cities'], $('DepartureCityComboBox_combo'), responce['selected'], []);
			$('DepartureCityComboBox_combo').fireEvent('change');
		}
	}).send();
}

/* Обновление стран*/
function change_departureCity(e) {
  if(e) e = new Event(e).stop();
  var url = ajaxBaseDictsUrl + "getDestinationCountriesByDepartureCity&departureCityId=" + $('DepartureCityComboBox_combo').value;
	new Json.Remote(url, {
		onComplete: function(responce) {
			RenderItemsComboBox(responce['countries'], $('DestinationCountryComboBox_combo'), responce['selected'], []);
			$('DestinationCountryComboBox_combo').fireEvent('change');
		}
	}).send();
}
/* Обновление звездочек*/
function change_destinationCountry(e) {
  if(e) e = new Event(e).stop();
  var url = ajaxBaseDictsUrl + "getStars&CountryId=" + $('DestinationCountryComboBox_combo').value;
	new Json.Remote(url, {
		onComplete: function(responce) {
			RenderItemsComboBox(responce['stars'], $('StarsListBox_combo'), 403, []);
		}
	}).send();
}

function submit_form(){
		//переменные для выбора взрослых и детей ad-взрослые chil-дети
		var ad=0,chil=0;
		switch(parseInt($('turists').value)){
			case 1:	ad=1;chil=0;break;
			case 2:	ad=2;chil=0;break;
			case 3:	ad=3;chil=0;break;
			case 4:	ad=1;chil=1;break;
			case 5:	ad=1;chil=2;break;
			case 6:	ad=2;chil=1;break;
			case 7:	ad=2;chil=2;break;
			case 8:	ad=3;chil=1;break;
			case 9:	ad=3;chil=2;break;
		}	
		new Element('input', { type: 'hidden', name: 'adultsCount', value: ad }).injectInside(this);
		new Element('input', { type: 'hidden', name: 'childrenCount', value: chil }).injectInside(this);
		new Element('input', { type: 'hidden', name: 'checkinDateOffset', value: 3 }).injectInside(this);	
		//выбор количества ночей где begin-от и end-до
		var begin=0,end=0;	
		switch(parseInt($('choiceNights').value)){
			case 1 : begin=1;end=5;break;
			case 2 : begin=5;end=6;break;
			case 3 : begin=7;end=8;break;
			case 4 : begin=9;end=10;break;
			case 5 : begin=11;end=12;break;
			case 6 : begin=13;end=14;break;
			case 7 : begin=15;end=29;break;
		}
		new Element('input', { type: 'hidden', name: 'nightsFrom', value: begin }).injectInside(this);
		new Element('input', { type: 'hidden', name: 'nightsTo', value: end }).injectInside(this);
		for(i=5;i>=parseInt($('hotelType').value);i--)
					new Element('input', { type: 'hidden', name: 'stars[]', value: '40'+i }).injectInside(this);

		var popupWidth = parseInt(screen.width * 0.8); 
		if(popupWidth > 980) popupWidth = 980;

		var winprops = 'width='+popupWidth+',scrollbars=1,resizable';
		var winname = ('result' + (Math.random() % 1)).replace(/\./g,"");
		win = window.open('', winname, winprops);
		if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
  
		this.setProperty('target', winname);
		return true;
}

function RenderItemsComboBox(array, control, selected, filter, field)
{
	if ((array == null) || (control == null) || (control.nodeName != "SELECT")) return;
	if (field == null) field = 'russianName';
	
	for(var c=control.children.length; c>0; c--) control.removeChild(control.childNodes[c-1]);
	
	for (var i=0;i<array.length; i++)
	{
		if (filter && IsFilterContains(filter, array[i].id))
		{
			var itemText;
			var itemValue;
			var opt;
			
		  if (array[i][field] != null) itemText = array[i][field];
	    if (array[i].id != null) itemValue = array[i].id;
		  
		  opt = new Element('option', {'value': itemValue});
		  opt.innerHTML = itemText;
		  if(array[i].id == selected) opt.selected = true;
		  
		  opt.injectInside(control);
		}
	}
}

function IsFilterContains(filter, value)
{
	if (filter.length == 0) {return true;}
	for (i=0; i<filter.length; i++){ if (filter[i] == value) {return true};}
	return false;
}


