var UMenu = UMenu || {};
//данные для комбобоксов
UMenu.data ={"countryList":[
	    {
		    "name": "Австрия",
		    "id": "0",
		    "cityList": [
			    {
				    "city": "Вена",
				    "countryId": "0",
				    "link": "http://www.vienna-austria.ru",
				    "hotelLink" : "http://www.vienna-austria.ru/hotel_vienna.php"
			    },
			    {
				    "city": "Зальцбург",
				    "countryId": "0",
				    "link": "http://www.salzburg-austria.ru",
				    "hotelLink" : "http://www.salzburg-austria.ru/salzburg_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Англия",
		    "id": "1",
		    "cityList": [
			    {
				    "city": "Лондон",
				    "countryId": "1",
				    "link": "http://www.london-england.ru",
				    "hotelLink" : "http://www.london-england.ru/london_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Венгрия",
		    "id":"2",
		    "cityList": [
			    {
				    "city": "Будапешт",
				    "countryId": "2",
				    "link": "http://www.budapest-hungary.ru",
				    "hotelLink" : "http://www.budapest-hungary.ru/budapest_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Германия",
		    "id":"3",
		    "cityList": [
			    {
				    "city": "Берлин",
				    "countryId": "3",
				    "link": "http://www.berlin-germany.ru",
				    "hotelLink" : "http://www.berlin-germany.ru/berlin_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Греция",
		    "id":"4",
		    "cityList": [
			    {
				    "city": "о.Крит",
				    "countryId": "4",
				    "link": "http://www.crete-greece.ru",
				    "hotelLink" : "http://www.crete-greece.ru/crete_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Египет",
		    "id":"5",
		    "cityList": [
			    {
				    "city": "Шарм эль Шейх",
				    "countryId": "5",
				    "link": "http://www.sharm-el-sheikh.ru",
				    "hotelLink" : "http://www.sharm-el-sheikh.ru/hotels_sharm.php"
			    },
			    {
				    "city": "Хургада",
				    "countryId": "5",
				    "link": "http://www.hurgada-egypt.ru",
				    "hotelLink" : "http://www.hurgada-egypt.ru/hotels_hurghada.php"
			    }
		    ]
	    },
	    {
		    "name": "Индонезия",
		    "id":"6",
		    "cityList": [
			    {
				    "city": "о.Бали",
				    "countryId": "6",
				    "link": "http://www.e-bali.ru",
				    "hotelLink" : "http://www.e-bali.ru/bali_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Иордания",
		    "id":"7",
		    "cityList": [
			    {
				    "city": "Петра",
				    "countryId": "7",
				    "link": "http://www.jordan-petra.ru",
				    "hotelLink" : "http://www.jordan-petra.ru/petra_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Испания",
		    "id":"8",
		    "cityList": [
			    {
				    "city": "Барселона",
				    "countryId": "8",
				    "link": "http://www.barcelona-spain.ru",
				    "hotelLink" : "http://www.barcelona-spain.ru/oteli.php"
			    }
		    ]
	    },
	    {
		    "name": "Италия",
		    "id":"9",
		    "cityList": [
			    {
				    "city": "Рим",
				    "countryId": "9",
				    "link": "http://www.rome-italy.ru",
				    "hotelLink" : "http://www.rome-italy.ru/oteli.php"
			    }
		    ]
	    },
	    {
		    "name": "Китай",
		    "id":"10",
		    "cityList": [
			    {
				    "city": "Пекин",
				    "countryId": "10",
				    "link": "http://www.peking-china.ru",
				    "hotelLink" : "http://www.peking-china.ru/pekin_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Малайзия",
		    "id":"11",
		    "cityList": [
			    {
				    "city": "Куала Лумпур",
				    "countryId": "11",
				    "link": "http://www.kuala-lumpur-malaysia.ru",
				    "hotelLink" : "http://www.kuala-lumpur-malaysia.ru/lumpur_hotel.php"
			    },
			    {
				    "city": "о.Лангкави",
				    "countryId": "11",
				    "link": "http://www.langkawi-malaysia.ru",
				    "hotelLink" : "http://www.langkawi-malaysia.ru/langkawi_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Мальдивы",
		    "id":"12",
		    "cityList": [
			    {
				    "city": "Мальдивы",
				    "countryId": "12",
				    "link": "http://www.republic-of-maldives.ru",
				    "hotelLink" : "http://www.republic-of-maldives.ru/maldives_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Нидерланды",
		    "id":"13",
		    "cityList": [
			    {
				    "city": "Амстердам",
				    "countryId": "13",
				    "link": "http://www.amsterdam-netherlands.ru",
				    "hotelLink" : "http://www.amsterdam-netherlands.ru/amsterdam_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "ОАЭ",
		    "id":"14",
		    "cityList": [
			    {
				    "city": "Дубай",
				    "countryId": "14",
				    "link": "http://www.dubai-uae.ru",
				    "hotelLink" : "http://www.dubai-uae.ru/dubai_hotels.php"
			    }
		    ]
	    },
	    {
		    "name": "Россия",
		    "id":"15",
		    "cityList": [
			    {
				    "city": "Москва",
				    "countryId": "15",
				    "link": "http://www.russia-moscow.net",
				    "hotelLink" : "http://www.russia-moscow.net/rus/moscow_hotel.php"
			    },
			    {
				    "city": "Санкт-Петербург",
				    "countryId": "15",
				    "link": "http://www.saint-petersburg-russia.ru",
				    "hotelLink" : "http://www.saint-petersburg-russia.ru/spb_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Сингапур",
		    "id":"16",
		    "cityList": [
			    {
				    "city": "Сингапур",
				    "countryId": "16",
				    "link": "http://www.singapore-singapore.ru",
				    "hotelLink" : "http://www.singapore-singapore.ru/singapore_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "США",
		    "id":"17",
		    "cityList": [
			    {
				    "city": "Лас-Вегас",
				    "countryId": "17",
				    "link": "http://www.las-vegas-usa.ru",
				    "hotelLink" : "http://www.las-vegas-usa.ru/lasvegas_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Турция",
		    "id":"18",
		    "cityList": [
			    {
				    "city": "Анталия",
				    "countryId": "18",
				    "link": "http://www.antalia-turkey.com",
				    "hotelLink" : "http://www.antalia-turkey.com/antalya_hotel.php"
			    },
			    {
				    "city": "Стамбул",
				    "countryId": "18",
				    "link": "http://www.istanbul-turkey.ru",
				    "hotelLink" : "http://www.istanbul-turkey.ru/oteli.php"
			    },
			    {
				    "city": "Улудаг",
				    "countryId": "18",
				    "link": "http://www.uludag.ru",
				    "hotelLink" : "http://www.uludag.ru/uludag_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Финляндия",
		    "id":"19",
		    "cityList": [
			    {
				    "city": "Хельсинки",
				    "countryId": "19",
				    "link": "http://www.finland-helsinki.ru",
				    "hotelLink" : "http://www.finland-helsinki.ru/hels_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Франция",
		    "id":"20",
		    "cityList": [
			    {
				    "city": "Париж",
				    "countryId": "20",
				    "link": "http://www.france-paris.ru",
				    "hotelLink" : "http://www.france-paris.ru/oteli.php"
			    }
		    ]
	    },
	    {
		    "name": "Чехия",
		    "id":"21",
		    "cityList": [
			    {
				    "city": "Прага",
				    "countryId": "21",
				    "link": "http://www.zlatapraha.ru",
				    "hotelLink" : "http://www.zlatapraha.ru/oteli.php"
			    },
			    {
				    "city": "Карловы Вары",
				    "countryId": "21",
				    "link": "http://www.karlovy-vary.org",
				    "hotelLink" : "http://www.karlovy-vary.org/oteli.php"
			    },
			    {
				    "city": "Марианские Лазне",
				    "countryId": "21",
				    "link": "http://www.marianske-lazne.ru",
				    "hotelLink" : "http://www.marianske-lazne.ru/marlazne_hotel.php"
			    }
		    ]
	    },
	    {
		    "name": "Швейцария",
		    "id":"22",
		    "cityList": [
			    {
				    "city": "Цюрих",
				    "countryId": "22",
				    "link": "http://www.zurich-switzerland.ru",
				    "hotelLink" : "http://www.zurich-switzerland.ru/zurich_hotel.php"
			    }
		    ]
	    },
	    {
		"name": "Швеция",
		"id":"23",
		"cityList": [
			{
			    "city": "Стокгольм",
			    "countryId": "23",
			    "link": "http://www.stockholm-sweden.ru",
			    "hotelLink" : "http://www.stockholm-sweden.ru/stockholm_hotel.php"
			}
		]
	    }
	]
  };

(function($){
    $(document).ready(function () {
       $.extend(UMenu, {
           /**
            * Объект меню
            * @private
            */
           _$menu: {},
           /**
            * Объект области контента
            * @private
            */
           _$content: {},
           /**
            * Объект области навигации
            * @private
            */
           _$navigation: {},
           tmpls: {
               select: new EJS({url:'/tmpls/select_options.ejs'})
           },
           /**
            * Инициализация меню
            * @private
            */
           init: function () {
               this._initObjects();
               this._setListeners();
               $('li:first',this._$navigation).trigger('click');
			 // $('li#reserving',this._$navigation).trigger('click');
           },
           /**
            * Инициализирует основные объекты меню
            * @private
            */
           _initObjects: function () {
               this._$menu = $('#_uk_menu');
               this._$navigation = $('#_uk_menu #navigation_list');
               this._$content = $('#_uk_menu #menu_content');
           },
           /**
            * Установка обработчиков
            * @private
            */
           _setListeners: function () {
               //переключение меню
               this._$menu.delegate('#navigation_list li', 'click', function (){
                    var $this = $(this),
                        menuType;
                    if (!$this.hasClass('active')){
                        menuType = $this.attr('id');
                        UMenu.switchMenu(menuType);
                        UMenu._$navigation.find('.active').removeClass('active');
                        $this.addClass('active');
                    } else {
                       return;
                    }
               });
               //выбор страны
               this._$menu.delegate('.countries', 'change', function (){
                   var  selected = $(this).find(':selected'),
                        sIndex = (parseInt(selected.index())-1); //индекс выбранного эл-та
                   UMenu._filterCitiesByCountry(sIndex);
                   UMenu._setCityLink();
               });
               //выбор города
               this._$menu.delegate('.cities', 'change', function () {
                   var  selected = $(this).find(':selected'),
                        caption = selected.text(), //название города
                        city = UMenu._findCityByCaption(caption);  //объект города
                        UMenu._setCityLink(city);
               });
               //бронирование
               this._$menu.delegate('.radioContainer', 'click', function () {
                   var value;
                   UMenu._$menu.find('.radioChecked').removeClass('radioChecked');
                   $(this).addClass('radioChecked');
                   value = $(this).find('input').attr('value');
                   UMenu._$content.find('.okLink').attr('href', value);
               })
           },
           /**
            * Переключает пункты меню
            * @param {String} menuType тип меню который надо отобразить
            */
           switchMenu: function (menuType){
                var template = UMenu._getContent(menuType);
                UMenu._$content.fadeOut(200, function(){
                    UMenu._$content.attr('class', menuType);
                    UMenu._$content.html(template);
                    UMenu._$content.fadeIn(200);
                    if (UMenu._$content.find('.placeSelector').length){ //заполнить боксы если они есть
                        UMenu.fillSelects();
                    }
                });
           },
           /**
            * Заполняет комбобоксы
            */
           fillSelects: function () {
                this._fillCountries();
                this._fillCities();
           },
           /**
            * Заполняет поле стран
            * @private
            */
           _fillCountries: function () {
                var data = this.data;
                    template = this.tmpls.select;
                this._$content.find('.countries').append(template.render({id:'',value:'-',caption:''})) //первый
                for (var i = 0; i < data.countryList.length; i++) {
                    this._$content.find('.countries').append(template.render({id:'',value:i,caption:data.countryList[i].name}));
                }
           },
           /**
            * Заполняет поле городов
            * @private
            */
           _fillCities: function () {
                var data = this.data;
                    template = this.tmpls.select;
                this._$content.find('.cities').append(template.render({id:'',value:'-',caption:''})) //первый
                for (var i = 0; i < data.countryList.length; i++) {
                    for (var k = 0; k < data.countryList[i].cityList.length; k++) {
                        this._$content.find('.cities').append(template.render({id:'',value:k, caption:data.countryList[i].cityList[k].city}));
                    }
                }
           },
           /**
            * При выборе стран заполняет города только для выбранной страны
            * @param {Number} id идентификатор выбранной страны (он же порядковый номер в массиве)
            * @private
            */
           _filterCitiesByCountry: function (id) {
               var  cityBox = this._$content.find('.cities'),
                    template =  this.tmpls.select;
               cityBox.empty();
               cityBox.append(template.render({id:'',value:'-',caption:''})) //первый
               if (id >= 0){
                    UMenu.data.countryList[id]
                    for (var i = 0; i < UMenu.data.countryList[id].cityList.length; i++) {
                        cityBox.append(template.render({id:'',value:i, caption:this.data.countryList[id].cityList[i].city}));
                    }
               } else {
                    this._fillCities();
               }
           },
           /**
            * Ищет объект для выбранного города в данных по названию
            * @param {String} caption название города
            * @returns {Object | boolean} city Объект выбранного города или false если город не найден
            * @private
            */
           _findCityByCaption: function (caption) {
               var city;
               if (caption) {
                   for (var i=0; i<this.data.countryList.length;i++){
                       for (var k=0;k<this.data.countryList[i].cityList.length;k++){
                           if (this.data.countryList[i].cityList[k].city == caption) {
                               city = this.data.countryList[i].cityList[k];
                               return city;
                           }
                       }
                   }
               }
               return false;
           },
           /**
            * Устанавливает ссылку для выбранного город
            * @param {Object} city объект выбранного города
            * @private
            */
           _setCityLink: function (city) {
               var okBtn = this._$content.find('.okLink');
                if (city){
                    if (this._$navigation.find('.active').attr('id') == 'guide'){
                        okBtn.attr('href', city.link)
                    } else if (this._$navigation.find('.active').attr('id') == 'hotels') {
                        okBtn.attr('href', city.hotelLink)
                    }
                } else {
                    okBtn.attr('href', '#');
                }
           },
           /**
            * Возвращает скомпилированный шаблон указанного типа
            * @param {String} type тип шаблона
            * @private
            */
           _getContent: function (type) {
               var template,
                   tmpl_url;
               if (type){
                   tmpl_url = '/tmpls/' + type + '.ejs';
                   switch(type){
                       case 'guide': template = new EJS({url:tmpl_url}).render(); break;
                       case 'hotels': template = new EJS({url:tmpl_url}).render(); break;
                       case 'gallery': template = new EJS({url:tmpl_url}).render(); break;
                       case 'reserving': template = new EJS({url:tmpl_url}).render(); break;
                       case 'social': template = new EJS({url:tmpl_url}).render(); break;
                       case 'forum': template = new EJS({url:tmpl_url}).render(); break;
                       default: throw Error('Шаблон не найден');
                   }
                return template;
               } else {
                   throw Error('Необходимо указать тип содержимого для выбора шаблона');
               }
           }
       });

       UMenu.init();
    });
})(jQuery)
