/**
 * Бронирование отелей
 *
 * @author Kulikov D. A.
 * @version 0.1 beta
 */
var Hotel = {

	_system: function()
	{
		return $F('SystemType');
	},

	php_backend: function()
	{
		switch (this._system()) {
			case "kuoni": return "/ajax/hotel/kuoni";
			case "gta":   return "/ajax/hotel/gta";
			case "miki":  return "/ajax/hotel/miki";
		}
	},

	hash: '',                    // хеш результата поиска отелей. Используется при перемещении по страницам.
	GoogleMarkers: '',           // массив маркеров отелей для отображения их на Google Map
	SortHotelBy: '',             // параметр сортировки отелей (name, category, price)
	SearchByError: '',           // содержит функцию которая отправляет повторный запрос в случае задержки результатов более чем на 30 секунд
	SearchParams:                // параметры поиска отелей — кол-во и тип комнат, информация о детя (если есть)
	{
		Rooms: [],      // комнаты array( name — название типа комнаты, id, numBeds — кол-во кроватомест, count — кол-во комнат этого типа )
		StartDate: '',  // дата начала бронирования
		Duration: '',   // продолжительность
		Country: '',    // страна
		City: ''        // город
	},

	/**
	 * Функции, вызывающиеся при window.onload
	 */
	OnLoad_Action: function()
	{
		/* Открываем форму с параметрами поиска */
		$('Search_Parametrs').opened = true;

		/* Если указан отель который нужно найти — стартуем поиск сразу. («Найти подобные отели») */
		if ($F('SearchLikeThisHotelID')) {
			Effect.toggleOrderBlock($('Search_Parametrs'), function(){
				$('Hotels_List').show();
				Hotel.Search({ 'action': 'SearchHotelsBySavedPost', 'BookingID': $F('SearchLikeThisHotelID')});
			});
		}
        
		/*  */
		if ($('autoStartBooking')) {
			Hotel.StartSearching();
		}

		/* при нажатии «Найти отели» */
		$('Search_Hotels').onclick = Hotel.StartSearching;

		/* добавление комнаты при поиске отелей */
		$('Add_Hotel_Room').onclick = Hotel.addRoom;

		/* подгружаем города для выбранной страны */
		if ($F('Hotel_Country') && !$F('Hotel_City')) Hotel.getCity($F('Hotel_Country'), $('Hotel_City'), 0);
		$('Hotel_Country').onchange = function() { Hotel.getCity($F('Hotel_Country'), $('Hotel_City'), 0); }
		
		if ($('SystemType')) {
			$('SystemType').onchange = function() 
			{
				Hotel.newSystem();
			}
			
//	        Hotel.getCity($F('Hotel_Country'), $('Hotel_City'), 0); 
//	        Hotel.getCategories($('hotelCategories'));
//	        Hotel.getRoomTypes('Hotel_Rooms');
//	        Hotel.getHotelLocations($('hotelLocation'));
//	        Hotel.getHotelFacilities($('hotelFacilities'));
//	        Hotel.getRoomFacilities($('roomFacilities'));       
//	        Hotel.isShowElement($('budget'));
		}	
	},
	
	/**
	 *Измение всяких данных в зависимости от туроператора
	 */
	newSystem: function()
	{
		Hotel.getCity($F('Hotel_Country'), $('Hotel_City'), 0); 
		Hotel.getCategories($('hotelCategories'));
		Hotel.getRoomTypes('Hotel_Rooms');
		Hotel.getBestCities('bestCities');
		Hotel.getHotelLocations($('hotelLocation'));
		Hotel.getHotelFacilities($('hotelFacilities'));
		Hotel.getRoomFacilities($('roomFacilities'));		
		Hotel.isShowElement($('budget'));
	},

	/**
	 * Отправляем запрос на поиск, скрываем и открываем нужные блоки
	 */
	StartSearching: function()
	{
		if (!Validate($$('#Search_Parametrs select'), true)) return false;
		Effect.toggleOrderBlock($('Search_Parametrs'), function(){
			$('Hotels_List', $('Search_Parametrs').down("div.status")).invoke('show');
			Hotel.SortHotelBy = $F('SortBy');
			Hotel.SaveSearchParams();
			$('Hotels_List').opened = false;
			Hotel.Search({ 'action': 'SearchHotels', q: $('Hotel_Form')});
		});
	},

	/**
	 * Перехватываем нажатие на номера страниц и отправляем запрос
	 * на подгрузку следующей страницы
	 */
	ObservPageClick: function()
	{
		$$("#Page_Navigation a").each(function(element){
			element.onclick = function(){
				if (!element.getAttribute("page")) return false;
				fx.open('Hotels_List', false, 50, function(){
					Hotel.Search({ 'action': 'SearchHotelsFromCache', 'page': element.getAttribute("page"), 'hash': Hotel.hash});
				});
				$('Hotels_List').opened = false;
				return false;
			}
		});
	},

	/* сортировка списка найденных отелей */
	SortBy: function(element)
	{
		if (element.className == 'active') return false;
		Hotel.SortHotelBy = element.getAttribute("sort");
		fx.open('Hotels_List', false, 50, function(){
			Hotel.Search({ 'action': 'SearchHotelsFromCache', 'page': '1', 'SortBy': element.getAttribute("sort"), 'hash': Hotel.hash});
		});
		$('Hotels_List').opened = false;
	},

	/* изменение типа сортировки — отмечаем текущий тип в шаблоне */
	ChangeSortType: function()
	{
		$$('#SortType a').each(function(element){
			element.className = 'inside';
			if (element.getAttribute("sort") == Hotel.SortHotelBy) {
				element.className = 'active';
			}
		});
	},

	/**
	 * Переводим фокус на карту, при необходимости открываем ее
	 */
	ShowMap: function()
	{
		$('Google_Map').style.marginTop = '10px';
		if (!$('Google_Map').opened) {
			fx.open($('Google_Map'), 1, false);
			$('Google_Map').opened = true;
		}
		fx.scrollTo($('Google_Map'));
	},
	
	
    /**
     * Вывод лучших городов
     */	
	getBestCities: function(div)
	{
        JsHttpRequest.query(
            this.php_backend(),
            {'action': 'getBestCities'},
            function(result, text){
                $(div).innerHTML = text;
            },
            true
        );
	},


	/**
	 * Выбор, куда ехать курьеру - в офис или квартиру
	 */
	chooseDeliveryPlace: function(element)
	{
		if ($(element).value == 'office') {
			$('deliveryOffice').show();
			$('deliveryFlat').hide();
		} else {
			$('deliveryOffice').hide();
			$('deliveryFlat').show();
		}
 	},

	/**
	 * Поиск отелей
	 * На вход передаем хеш парметров ajax запроса
	 * post_array = {'action': 'SearchHotels', q: $('Hotel_Form')} — запрос на поиск отелей
	 * post_array = {'action': 'SearchHotelsFromCache', 'page': 2, 'hash': Hotel.hash} — запрос на отображение второй страныцы
	 */
	Search: function(post_array)
	{
		if (post_array.action == "SearchHotels") {
			Hotel.SearchByError = setTimeout(function(){
				Hotel.Search({'action': 'SearchHotelsByError', q: $('Hotel_Form')});
			}, 60000);
		}
		if (!$('Hotels_List').opened) {
			fx.open('Hotels_List', 50, 90);
			$('Hotels_List_Content').innerHTML = '<div><img src="/_public/images/ajax-loader.gif" align="absmiddle"> Подождите, идет поиск отелей…</div>';
		}
		
		if (post_array.system) {
			$('SystemType').value = post_array.system;
		}
		
		JsHttpRequest.query(
			this.php_backend(),
			post_array,
			function(result, text){
			    $('HotelNameID').value = ''; // обнуляем значение предвыбранного отеля
				if (text && post_array.action == "SearchHotels") { clearTimeout(Hotel.SearchByError); }

				if (result.hash) Hotel.hash = result.hash;
				Hotel.GoogleMarkers = result.GoogleMarkers;
				$('Hotels_List_Content').innerHTML = text;
				Hotel.ChangeSortType();
				fx.open($('Hotels_List'), $('Hotels_List').offsetHeight, false, function(){
					$('Hotels_List').style.height = '100%';
					Effect.animateButton();
					Effect.toggleWhiteBlock();
					Hotel.ObservPageClick();
					loadGoogleMap();         // подгрузка GoogleMaps
                    
                    if ($('autoStartBooking')) {
                        var button = $$('#hipnt'+ $F('autoStartBooking') +' td.hotel_photo > input:button');
                        if (button.length) {
                            button[0].onclick();
                        }
                    }
				});
				$('Hotels_List').opened = true;
			},
			true
		);

		fx.scrollTo($('Hotels_List'));
		$('Google_Map').style.marginTop = '0px';
		$('Google_Map').style.height = '0px';
		$('Google_Map').opened = false;
	},

	/**
	 * Запоминаем параметры поиска отелей для последующей
	 * раскладки формы бронирования
	 */
	SaveSearchParams: function()
	{
		Hotel.SearchParams = {
			FormData:  $('Hotel_Form').serialize(),
			Country:   $F('Hotel_Country') == '' ? $F('definedCountry') : $F('Hotel_Country'),
			City:      $F('Hotel_City') == '' ? $F('definedCity') : $F('Hotel_City'),
			StartDate: $('Start_Date').next('select', 2).value +'-'+$('Start_Date').next('select', 1).value +'-'+$('Start_Date').next('select', 0).value,
			Duration:  $F('Duration'),
			Rooms: []
		}
		$$('select.RoomType').each(function(element, i){
			var room = element.options[element.selectedIndex];
			Hotel.SearchParams.Rooms[i] = {
					name: room.text,                     // название
					id: room.value,                      // id комнаты
					numBeds: room.getAttribute('cnt'),   // кол-во кровато-мест
					count: element.next().down('select').value, // кол-во таких комнат
					numChild: (room.value == '4' || room.value == '7') ? element.next('.countChild').down('select').value : false  // кол-во детей, если есть
			}
		});
	},
	
	/**
	 * Выбор одного из популярных направлений
	 * 
	 */
	chooseBestCity: function(cityId, countryId, element)
	{
		/*
		$('definedCountry').value = countryId;
		$('definedCity').value = cityId;
		$('Hotel_Country').disable();
		$('Hotel_City').disable();
		*/
		
		
		$(element).up('div', 2).descendants('a').each(function(some)
		{
			$(some).removeClassName('chosen');
		});
		$(element).addClassName('chosen');
		
		$('Hotel_City').disable();
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action': 'getCity', 'Country': countryId },
			function(result, errors) {
				$('Hotel_City').length = 0;
				result.each(function(element, index){
					$('Hotel_City').options[index] = new Option(element.name, element.id);
					if (element.selected == 1) {
						$('Hotel_City').options[index].style.color = 'blue';
					}
					if (element.id == cityId) {
						$('Hotel_City').options[index].selected = true;
					}
				});
				$('Hotel_City').enable();
				$('Hotel_Country').value = countryId;
				$('Hotel_City').value = cityId;
						 
			}
		);
		
		/*
		$('otherDirection').hide();
		$('otherDirectionTitle').show();
		*/
	},
	
	/**
	 * Выбор других, не таких популярных, городов
	 */
	showOtherDirection: function(element)
	{
		$('definedCountry').value = 0;
		$('definedCity').value = 0;
		$('Hotel_Country').enable();
		$('Hotel_Country').value="";
        $('bestCities').descendants('a').each(function(some)
        {
            $(some).removeClassName('chosen');
        });
		
		$('otherDirection').show();
		$('otherDirectionTitle').hide();
	},

	/**
	 * Отображение формы бронирования отелей
	 * Создание необходимого кол-ва полей для туристов
	 * Данные беруться из формы поиска
	 */
	showBookingForm: function(button, FormDiv)
	{
		button.disable(); FormDiv.show();
		fx.open(FormDiv, 24, false, function() {
			FormDiv.style.height = '100%';
			var RoomBox   = FormDiv.down('span.Room_Box');
			var RoomIndex = 0;

			// установка параметров бронирования
			
			if (Hotel._system() != 'miki') {
				RoomBox.previous('input.HotelCountry').value = Hotel.SearchParams.Country;
				RoomBox.previous('input.HotelCity').value    = Hotel.SearchParams.City;
				RoomBox.previous('input.StartDate').value    = Hotel.SearchParams.StartDate;
				RoomBox.previous('input.Duration').value     = Hotel.SearchParams.Duration;
			}
							
			RoomBox.previous('input.FormData').value     = Hotel.SearchParams.FormData;


			// создание полей для ввода данных туристов
			Hotel.SearchParams.Rooms.each(function(element, index){
			    // создаем необходимое кол-во номеров
				for (var i = 0; i < element.count; i++) {
				    // берем первую комнату в первом номере для клонирования
					var newRoom = RoomBox.down('div.column').cloneNode(true);
					newRoom.getElementsByTagName('h3')[0].innerHTML = (RoomIndex+1) +'-й номер: '+ element.name;
					newRoom.getElementsByClassName('TouristRoomType')[0].value = element.id;

					// обнуляем кол-во спальных мест в ней
					newRoom.getElementsByTagName('span')[0].innerHTML = '';

					// создаем необходимое кол-во спальных мест в номере
					for (var j = 0; j < element.numBeds; j++) {
						var newTourist = RoomBox.down('fieldset').cloneNode(true);
						newTourist.getElementsByClassName('TouristRoomType')[0].value = element.id;
						newRoom.getElementsByTagName('span')[0].appendChild(newTourist);
					}

					// если есть места для детей, то добавляем и их тоже
					for (var k = 0; k < element.numChild; k++) {
                        var newChild = RoomBox.down('fieldset').cloneNode(true);
                        newChild.addClassName('Child');
                        newChild.getElementsByClassName('TouristRoomType')[0].value = element.id;
                        newChild.getElementsByClassName('isChild')[0].value = '1';
                        newRoom.getElementsByTagName('span')[0].appendChild(newChild);
                    }

                    // изменяем имена полей для правильного построения массива данных в бекенде
					[newRoom.getElementsByTagName('input'), newRoom.getElementsByTagName('select')].each(function(inputCollection){
						$A(inputCollection).each(function(input){
							input.name = input.name.replace(/\d+/, RoomIndex);
						});
					});

					// добавляем комнаны и идем дальше
					if (RoomIndex == 0) RoomBox.innerHTML = '';
					RoomBox.appendChild(newRoom);
					RoomIndex++;
				}
			});
		});
		FormDiv.opened = true;
	},
	
	calculateVisaPrice: function(elem){
        var invitationBlock = $(elem).up('.Room_Box').next('div.column').down('span.invitation');
        if(invitationBlock) invitationBlock.show();
        var visaprice = parseInt( $(elem).up(2).next('div').getAttribute('price') );
        var users = 0;
        $(elem).up(2).getElementsBySelector('input.radio').each( function(dd){ if(dd.checked) users++; } );
        var conp = users == 1 ? 20 : 35;
        var str = ( users > 0 ? visaprice * users + conp : '0' ) + ' EUR' ;
        if( users ) str += '<br /><span style="color: #7C6F44; font-weight: normal; font-size: 12px;">( ' + users + 'чел х ' + visaprice + ' EUR (консульский сбор) + ' + conp + ' EUR (занос документов в посольство) )</span> ';
        $(elem).up(2).next('div').down().innerHTML = str;
        
        if(users > 0 && invitationBlock){
            invitationBlock.hide();
        }
	},

	/**
	 * Отправка данных формы бронирования отеля
	 */
	Booking: function(form)
	{
	    var resultMessage = '';
		if (!Validate(form.getElements(), true)) return false;
		form.down('.Booking_Button').innerHTML = '<img src="/_public/images/ajax-loader.gif" width="230" height="25" align="absmiddle">';
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action': 'BookingHotel', q: form },
			function(result, errors){
				fx.scrollTo(form.up('.hotel_descriptions'));
				if (!errors || errors.strip() == '') {
					form.up('tr').down('.button').disable();
					resultMessage =
						'<h2 style="color: green">Ваша заявка успешно принята</h2>' +
						'<del>&nbsp;</del>' +
						'Все данные отправлены вам на электронную почту.  <br/>' +
						'В ближайшее время менеджер свяжется с вами для уточнения параметров бронирования.<br/>';
					if(result.bookingId && !$(form).hasClassName('near-cancellation-deadline')){
					    resultMessage += '<del>&nbsp;</del><a href="#" onclick="Hotel.GotoPay(this,\''+ result.bookingId +'\', \''+ result.publicKey +'\'); return false;">Перейти к оплате брони</a>';
					}
					form.up('.content').innerHTML = resultMessage;	
				} else {
					form.up('.content').innerHTML =
						'<div class="error">' + errors +
						'<del>&nbsp;</del>' +
				   		'<a href="#" class="inside" onclick="Effect.toggleOrderBlock($(\'Search_Parametrs\')); return false;">Искать другой отель</a></div>';
				}
			}
		);
	},
	
	GotoPay: function(obj, bookingId, publicKey)
	{
	    form = $(obj).up('.content');
	    form.innerHTML = '<img src="/_public/images/ajax-loader.gif" width="230" height="25" align="absmiddle">';
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action': 'GotoOnlinePay', 'BookingID': bookingId, 'publicKey': publicKey },
			function(result, errors){
				if (!errors || errors.strip() == '') {
					window.location.href = 'https://pay.dsbw.ru/index/index/code/' + result.mtCode + '/sum/' + result.sum + '/currency/euro';
				} else {
					form.innerHTML = errors;
				}
			}
		);	
	},


	_mainTouristLoaded: false,

	/**
	 * Обновление списка «Турист, на которого оформляется бронь»
	 */
	addMainTourist: function(MainTourist)
	{
		if (!this._mainTouristLoaded){
			this._mainTouristLoaded = true;
			MainTourist.length = 0;
			$A(MainTourist.up('.column').previous('.Room_Box').getElementsByClassName('TouristSurname')).each(function(element, index){
				if (element.value != "") {
					MainTourist.options[MainTourist.length] = new Option(element.value, index);
				}
			});
		}
	},

	/**
	 * Получение списка городов для выбранной страны
	 * int CountryID — id'р страны
	 * obj CitySelect — select со списком городов
	 */
	getCity: function(CountryID, CitySelect, cityId)
	{
		if (!CountryID) return;
		CitySelect.disable(); fx.hidden(CitySelect, 0.2);
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action': 'getCity', 'Country': CountryID },
			function(result, errors) {
				CitySelect.length = 0;
				result.each(function(element, index){
					CitySelect.options[index] = new Option(element.name, element.id);
					if (element.selected == 1) {
						CitySelect.options[index].style.color = 'blue';
					}
					if (element.id == cityId) {
						CitySelect.options[index].selected = true;
					}
					
				});
				CitySelect.enable(); fx.hidden(CitySelect, 1);
			}
		);
	},
	
	/*
	 * Получение категорий отелей согласно оператору
	 */
	getCategories: function(categories)
	{
		categories.disable(); fx.hidden(categories, 0.2);
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action' : 'getCategories'},
			function(result, errors) {
				categories.length = 0;
				result.each(function(element, index){
					categories.options[index] = new Option(element.name, element.id);
					if (element.selected == 1) categories.options[index].style.color = 'blue';
				});
				categories.enable(); fx.hidden(categories, 1);
			}
		);
	},
	
	/*
	 * Получение типов номеров согласно оператору
	 */
	getRoomTypes: function(roomTypesDiv)
	{
		$$('#' + roomTypesDiv + ' select.RoomType').each(function(selectNode) {
			selectNode.disable();
			fx.hidden(selectNode, 0.2);
		});
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action' : 'getRoomTypes'},
			function(result, errors) {
				$$('#' + roomTypesDiv + ' select.RoomType').each(function(selectNode) {
					selectNode.length = 0;
					
					result.each(function(element, index){
						var option = new Option(element.name, element.id);
						option.setAttribute('cnt', element.cnt);
						selectNode.options[index] = option;
						
					});
					selectNode.enable(); fx.hidden(selectNode, 1);
				});
			}
		);
		
	},
		
	
	/*
	 * Получение расположения номеров согласно оператору
	 */
	getHotelLocations: function(location)
	{
		location.disable(); fx.hidden(location, 0.2);
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action' : 'getHotelLocations'},
			function(result, errors) {
				location.length = 0;
				result.each(function(element, index){
					location.options[index] = new Option(element.name, element.id);
					if (element.selected == 1) location.options[index].style.color = 'blue';
				});
				location.enable(); fx.hidden(location, 1);
			}
		);
	},
	
	
	/*
	 * Получение перечня услуг в отеле согласно оператору
	 */
	getHotelFacilities: function(hotelFacilities)
	{
		var prototypeChild = hotelFacilities.down('label').cloneNode(true);

		JsHttpRequest.query(
			this.php_backend(),
			{ 'action' : 'getHotelFacilities'},
			function(result, errors) {
				hotelFacilities.innerHTML = '';
				result.each(function(element, index){
					var facility = prototypeChild.cloneNode(true); 
					facility.getElementsByTagName('input')[0].value = element.id;
					facility.getElementsByTagName('span')[0].innerHTML = element.name;
					hotelFacilities.appendChild(facility);
				});
			}
		);
		
	},	
	
	
	/*
	 * Получение перечня услуг в номерах согласно оператору
	 */
	getRoomFacilities: function(roomFacilities)
	{
		var prototypeChild = roomFacilities.down('label').cloneNode(true);

		JsHttpRequest.query(
			this.php_backend(),
			{ 'action' : 'getRoomFacilities'},
			function(result, errors) {
				roomFacilities.innerHTML = '';
				result.each(function(element, index){
					var facility = prototypeChild.cloneNode(true); 
					facility.getElementsByTagName('input')[0].value = element.id;
					facility.getElementsByTagName('span')[0].innerHTML = element.name;
					roomFacilities.appendChild(facility);
				});
			}
		);
		
	},	
	
	/*
	 * Отображать или нет параметры ввода цены
	 */
	isShowElement: function(element)
	{
		if (!$(element)) return;
		switch (this._system()) {
			case "miki":  
				$(element).show();
				break;
				
			case "kuoni":
			default:			
				$(element).hide(); 
				break;
		}						
	},		
		
	/**
	 * Добавляем номера в отеле
	 */
	addRoom: function ()
	{
		var newChild = $('Hotel_Rooms').down('div').cloneNode(true);
		newChild.getElementsByTagName('span')[0].show();
		newChild.getElementsByTagName('label')[0].innerHTML = '&nbsp;';
		newChild.getElementsByTagName('span')[1].hide();
		newChild.getElementsByClassName('ctrl_delete')[0].show();
		newChild.getElementsByTagName('div')[1].hide();
		newChild.getElementsByTagName('div')[2].hide();
		$('Hotel_Rooms').appendChild(newChild);
		return false;
	},


	/* отображение поля «кол-во детей» при выборе типа комнаты */
	showChildCount: function(element){
	    var block = element.up();

		if (element.value == '4' || element.value == '7') {
			block.down('span', 1).show().down('select').setAttribute('vartype', 'select');
		    block.down('span').hide().down('select').selectedIndex = 0;
		} else {
		    block.down('span').show().down('select').show();
			block.down('span', 1).hide().down('select').selectedIndex = 0;
			block.down('div').down('div', 0).hide();
			block.down('div').down('div', 1).hide();
		}
	},

	/* отображение полей с возрастом детей */
	showChildAge: function(element)
	{
		if (element.value == 1) {
			element.up().next('div').down('div', 0).show();
			element.up().next('div').down('div', 1).hide();
		} else if (element.value == 2) {
			element.up().next('div').down('div', 0).show();
			element.up().next('div').down('div', 1).show();
		} else {
			element.up().next('div').down('div', 0).hide();
			element.up().next('div').down('div', 1).hide();
		}
	},


	toggleAllPhoto: function(HotelID, link)
	{
	    var block = link.up('.img').down('.AllHotelPhoto');
	    if (block.offsetHeight) {
	        link.innerHTML = 'показать все фотографии';
	        block.hide(); return;
	    }
	    link.hide();
		JsHttpRequest.query(
			this.php_backend(),
			{ 'action': 'LoadImage', 'HotelID': HotelID },
			function(result, text) {
				block.innerHTML = text;
				block.show();
				if (text) {
					link.innerHTML = 'скрыть фотографии';
					link.show();
				}					
			}
		);
	},

	toggleSpa: function(action)
    {
        Utility.toggleSpo(action);
    }
}


var Order = {
	/**
	 * Авторизовались — отобразить контактные данные
	 */
	change_ClientType: function() {
		$('other_login').hide();
		$('agency_login').show();
	},
	
	changeAdditionalServiceQuantity: function(elem) {
	     var bookingId = $(elem).getAttribute('bookingid');
	     var lid = $(elem).getAttribute('lid');
	     var price = $(elem).up().up().previous().innerHTML;
	     var quantity = $(elem).getValue();
	     
		JsHttpRequest.query(
			'/ajax/hotel/kuoni',
			{ 'action': 'changeQuantity', 'lid': lid, 'quantity': quantity },
			function(result, text) {
			     $(elem).up().previous().show();
			     $(elem).up().previous().innerHTML = quantity;
			     $(elem).up().hide();
			     $(elem).up().up().next().innerHTML = quantity * price;					
			}
		);	     
	},
	
	deleteAdditionalService: function(elem)
	{
	   var lid = $(elem).getAttribute('lid');
		JsHttpRequest.query(
			'/ajax/hotel/kuoni',
			{ 'action': 'deleteAdditionalService', 'lid': lid },
			function(result, text) {
				$(elem).up().up().hide();
			}
		);	   
	},
	
	selectActivated: function(elem)
	{
	     $$('#uniteorder a').each(
	          function(elem){ 
	               $(elem).removeClassName('active'); 
	     });
	     $(elem).addClassName('active');
	},
	
	agregate: function()
	{
		var ids = [];
		var mainId = null;
		$$('#uniteorder a').each(
	          function(elem){ 
	              ids.push($(elem).innerHTML); 
	              if(elem.hasClassName('active')){
	                 mainId = elem.innerHTML;
	              }
	     });
	     console.log(ids, mainId);
	     
	     if(!mainId) {
	     	alert('Необходимо выбрать "главную заявку"');
	     	return;
	     }
		JsHttpRequest.query(
			'/ajax/hotel/kuoni',
			{ 'action': 'agregateOrder', 'ids': ids.uniq(), 'mainId': mainId },
			function(result, text) {
			    console.log(text);
				//$(elem).up().up().hide();
			}
		);		     
	},
	
	addToUnite: function(id)
	{
	   $('unitebar').show();
	   $('uniteorder').innerHTML += '<a href="#"  onclick="Order.selectActivated(this);return false;">'+id+'</a>';
	   $('uniteorder').scrollTo();
	   return false;
	}
}

Login.Result_Action = function(result)
{
	if (result.agent) {
		$('Hotel_Title').innerHTML = 'Бронирование отелей для турагентств<div style="font-size: 16px; padding-top: 10px;">Ваша комиссия составляет 10%</div>';
	} else if (result == 'logout') {
		$('Hotel_Title').innerHTML = 'Бронирование отелей для частных лиц';
	}
}