var modify = {
	init:function(){
		jQuery('.tSearchRoomNumber').change(function(){
			//call function selectRooms
			modify.selectRooms(jQuery(this).val());
		});
		jQuery("#configForm fieldset.roomWrapper select[name$='adultNumber']").change(function(){
			modify.onChangeAdultNumber(jQuery(this));
		});
	},
	
	//open number of rooms selected
	selectRooms:function(val){		
		jQuery('form.config div.line').addClass('off').find("select").prop("disabled", true);
		for (i=0; i<val; i++) {
			jQuery('form.config div.line:eq('+i+')').removeClass('off').find("select").prop("disabled", false);
		}
	},
	
	//check children's combo when updating adult's combo
	onChangeAdultNumber:function(comboAdultNumber){	
		var hotelMaxRoomOccupancy = this.templateDatas.hotelDatas.hotel.hotelMaxRoomOccupancy;		
		if (hotelMaxRoomOccupancy.childrenNumber == 0) {
			return;
		}		
		var comboChildrenNumber = comboAdultNumber.parent('.line').children("select[name$='childrenNumber']");
		
		var paxNumberRemaining = hotelMaxRoomOccupancy.paxNumber - comboAdultNumber.val();
		if (paxNumberRemaining < hotelMaxRoomOccupancy.childrenNumber) {
			var childrenMaxNumber = paxNumberRemaining;
		} else {
			var childrenMaxNumber = hotelMaxRoomOccupancy.childrenNumber;
		}
		
		if (comboChildrenNumber.children("option:last").val() != childrenMaxNumber) {
			if (comboChildrenNumber.children("option:last").val() > childrenMaxNumber) {
				for (i = comboChildrenNumber.children("option:last").val(); i > childrenMaxNumber; i--) {
					comboChildrenNumber.children("option[value="+ i +"]").remove();
				}
			} else {
				for (i = parseInt((comboChildrenNumber.children("option:last").val()),10) + 1; i <= childrenMaxNumber; i++) {
					var option = document.createElement('option');
					option.value = i;
					option.innerHTML = i;
					comboChildrenNumber.append(option);
				}
			}
		}
		
		if (childrenMaxNumber == 0) {
			comboChildrenNumber.hide();
			comboChildrenNumber.prev('label').hide();		
		} else {
			comboChildrenNumber.show();
			comboChildrenNumber.prev('label').show();
		}
	},
	
	//variable
	lang : null,
	main:null,
	$selectCurrency : null,
	mainUrl :null,
	templateDatas : {
		hotelDatas : null,
		Express : null
	},
	siteCode : "ALL",
	maporamaDirectory : "accor",
	maporamaSiteOrigin : "ALL",
	maporamaXml : "common",
	
	//initialisation
	initModify : function(){
		//language
		this.lang = jQuery("html").attr("lang");
		if(this.lang == "en") this.lang = "gb";
		//others
		this.main = jQuery("#room-dates .middleContent");
		this.$selectCurrency = jQuery("#selectCurrency");
		//package
		this.mainUrl = document.location.href.split("#")[0];
		//execute room template
		ajaxRequest._executeByUrl(
			"/bean/getViewBeans.action?beans=HotelRoomOccupancyViewBean|CurrenciesViewBean|BookingConfigurationViewBean|OriginViewBean|InterHotelsViewBean",
			"validatorInvalidState", 
			"modify.success(errors, response)"
		);
	},
	//onsuccess
	success : function(errors, json){
			if(errors && errors.length > 0){
				ajaxRequest.showErrors(errors, "errorMessage");
				// supprime le loader puis affiche le contenu
				jQuery("#addrooms .contentContainer").css("background", "none");
				jQuery("#addrooms .middleContent").css("visibility", "visible");//loading state
			}
			else if (json.viewBeans && json.viewBeans.HotelRoomOccupancyViewBean && json.viewBeans.OriginViewBean){
				if(json.viewBeans.InterHotelsViewBean && json.viewBeans.InterHotelsViewBean != null) Interhotels._init(json.viewBeans.InterHotelsViewBean);
				utils.manageCallcenterDatas(json.viewBeans.OriginViewBean.accorhotels);
				
				//load addrooms template
				jQuery("#engineTemplate").setTemplateURL("/"+this.lang+"/templates-v66/booking/sum-booking-engine.tpl");
				jQuery("#titleTemplate").setTemplateURL("/"+this.lang+"/templates-v66/booking/room-dates-titles.tpl");
				jQuery("#hotelTemplate").setTemplateURL("/"+this.lang+"/templates-v66/booking/specific-hotel-descriptive.tpl");
				jQuery("#modifyTemplate").setTemplateURL("/"+this.lang+"/templates-v66/booking/modify.tpl");
				modify.templateDatas.hotelDatas = json.viewBeans.HotelRoomOccupancyViewBean;
				this.templateDatas.Express = json.viewBeans.BookingConfigurationViewBean;
				this.siteCode = json.viewBeans.OriginViewBean.siteCode;
				this.maporamaDirectory = json.viewBeans.OriginViewBean.maporamaDirectory;
				this.maporamaSiteOrigin = json.viewBeans.OriginViewBean.maporamaSiteOrigin;
				this.maporamaXml = (this.maporamaSiteOrigin=="BUS" || this.maporamaSiteOrigin=="TRV")?"resa2010pro":"common";
		
				//execute template
				if(json.viewBeans.HotelRoomOccupancyViewBean.basketFull != true){
					jQuery("#hotelTemplate").setParam('siteCode', this.siteCode);
					jQuery("#hotelTemplate").setParam('maporamaDirectory', this.maporamaDirectory);
					jQuery("#hotelTemplate").setParam('maporamaSiteOrigin', this.maporamaSiteOrigin);
					jQuery("#hotelTemplate").setParam('maporamaXml', this.maporamaXml);
					jQuery("#hotelTemplate").setParam('centerType', json.viewBeans.HotelRoomOccupancyViewBean.centerType);
					jQuery("#hotelTemplate").setParam("amenitiesLabel", json.viewBeans.HotelRoomOccupancyViewBean.amenitiesLabel);
					jQuery("#hotelTemplate").setParam("hotelslist", json.viewBeans.HotelRoomOccupancyViewBean.displayHotelsList);
					jQuery("#hotelTemplate").setParam("doHotelLink", true);
					jQuery("#hotelTemplate").setParam("hotelListUrl", json.viewBeans.BookingConfigurationViewBean.hotelListUrl);
					jQuery("#titleTemplate").processTemplate(modify.templateDatas.hotelDatas);
					jQuery("#hotelTemplate").processTemplate(modify.templateDatas.hotelDatas.hotel);
				}
				jQuery("#modifyTemplate").setParam("securedDomain", json.viewBeans.OriginViewBean.securedDomain);
				jQuery("#modifyTemplate").processTemplate(modify.templateDatas.hotelDatas);
				jQuery("#engineTemplate").processTemplate(this.templateDatas.Express);
				this.init();				
				utils.tooltips.init(jQuery(".leftContent .tooltip, .middleContent .tooltip"));
				popins.init(jQuery(".middleContent .popin"));
				
				if(json.viewBeans.BookingConfigurationViewBean != null && json.viewBeans.BookingConfigurationViewBean.idBox != null){
					utils.writeIdBox(json.viewBeans.BookingConfigurationViewBean.idBox, this.lang);

				}else jQuery("#identificationProTemplate").css("display", "none");
				
				//fill config rooms
				if (this.templateDatas.hotelDatas.missingInfo == true && this.templateDatas.hotelDatas.displayConf == true && this.templateDatas.hotelDatas.roomAvails.length > 0) {					
					jQuery(".tSearchRoomNumber option[value='"+ this.templateDatas.hotelDatas.roomNumber +"']").attr('selected', 'selected');
					this.selectRooms(this.templateDatas.hotelDatas.roomAvails.length);
				}
				
				//init calendar
				var maxDateResa = modify.templateDatas.Express.bookingEngineRules.maxDateResa;
				var maxPeriodResa = modify.templateDatas.Express.bookingEngineRules.maxPeriodResa;
				var dayIn = monthIn = yearIn = nbNight = dayOut = monthOut = yearOut = 0;
				
				if(this.templateDatas.Express.period != null && this.templateDatas.hotelDatas.compliantPeriod == null){
					var dayIn  = this.templateDatas.Express.period.dayIn;
					var monthIn = this.templateDatas.Express.period.monthIn;
					var yearIn = this.templateDatas.Express.period.yearIn;
					var dayOut  = this.templateDatas.Express.period.dayOut;
					var monthOut = this.templateDatas.Express.period.monthOut;
					var yearOut = this.templateDatas.Express.period.yearOut;
					var nbNight = this.templateDatas.Express.period.nbDay;
				}
				else if(this.templateDatas.hotelDatas.compliantPeriod != null){
					var dayIn  = this.templateDatas.hotelDatas.compliantPeriod.dayIn;
					var monthIn = this.templateDatas.hotelDatas.compliantPeriod.monthIn;
					var yearIn = this.templateDatas.hotelDatas.compliantPeriod.yearIn;
					var dayOut  = this.templateDatas.hotelDatas.compliantPeriod.dayOut;
					var monthOut = this.templateDatas.hotelDatas.compliantPeriod.monthOut;
					var yearOut = this.templateDatas.hotelDatas.compliantPeriod.yearOut;
					var nbNight = this.templateDatas.hotelDatas.compliantPeriod.nbDays;
				}
				
				if(dayIn != 0 && monthIn != 0 && yearIn != 0 && dayOut != 0 && monthOut != 0 && yearOut != 0 && nbNight != 0){
					var dateIn = new Date(yearIn, monthIn-1, dayIn, 12, 0, 0);
					var dateOut = new Date(yearOut, monthOut-1, dayOut, 12, 0, 0);
					
					jQuery(".tArrivalDate").val(utils.printDate(dateIn, i18n.calendar.displayDateFormat));
					jQuery("input[name='search.dayIn']").val(dayIn);
					jQuery("input[name='search.monthIn']").val(monthIn);
					jQuery("input[name='search.yearIn']").val(yearIn);
					jQuery(".tDepartureDate").val(utils.printDate(dateIn, i18n.calendar.displayDateFormat));
					jQuery("input[name='search.dayOut']").val(dayOut);
					jQuery("input[name='search.monthOut']").val(monthOut);
					jQuery("input[name='search.yearOut']").val(yearOut);
					jQuery("input[name='search.nightNb']").val(nbNight);
				}
				if(jQuery("#sumbookingEngine .calendarDates").size() > 0) new Calendar('sumbookingEngine',maxDateResa,maxPeriodResa);
				if(jQuery("#configForm fieldset.datesWrapper").size()) {
					// fill calendar only when adding a new room
					if(this.templateDatas.hotelDatas.add == true && this.templateDatas.hotelDatas.displayDates == true && this.templateDatas.hotelDatas.period != null){						
						var dateIn = new Date(this.templateDatas.hotelDatas.period.yearIn, this.templateDatas.hotelDatas.period.monthIn-1, this.templateDatas.hotelDatas.period.dayIn);
						jQuery("#configForm fieldset.datesWrapper .tArrivalDate").val(utils.printDate(dateIn, i18n.calendar.displayDateFormat));
						jQuery("#configForm fieldset.datesWrapper .tArrivalDateStr").val(utils.printDate(dateIn, i18n.calendar.displayDateFormat));
						var dateOut = new Date(this.templateDatas.hotelDatas.period.yearOut, this.templateDatas.hotelDatas.period.monthOut-1, this.templateDatas.hotelDatas.period.dayOut);
						jQuery("#configForm fieldset.datesWrapper .tDepartureDate").val(utils.printDate(dateOut, i18n.calendar.displayDateFormat));
						jQuery("#configForm fieldset.datesWrapper .tDepartureDateStr").val(utils.printDate(dateOut, i18n.calendar.displayDateFormat));
						var nbNight = this.templateDatas.hotelDatas.period.nbDays;
						jQuery("#configForm fieldset.datesWrapper .tNights").removeClass('off').find(".tDuree").text(nbNight);
					}
					new Calendar('configForm',maxDateResa,maxPeriodResa);
				}
				/*//if(jQuery.browser.msie){
					
					jQuery("#search-dateIn").next().click(function(){
							alert('ok');
							//var p = jQuery(".ui-datepicker-trigger");
							//var position = p.position();
							//alert("top: " + position.top);
							//alert(document.getElementById('search-dateIn').offsetTop);
							//jQuery("#ui-datepicker-div").attr('style','')
							//jQuery("#ui-datepicker-div").css("left",position.left);
							var posTop = document.getElementById('dates').offsetTop;
							jQuery("#ui-datepicker-div").css("top",posTop+150);
					});	
					jQuery('#ui-datepicker-div').click(function(){
							var posTopOut = document.getElementById('dates').offsetTop;
							jQuery("#search-dateOut img").next().click(function(){
								alert('toto');
								alert(posTopOut);
								jQuery("#ui-datepicker-div").css("top",posTopOut+150);									   
							});											
																		
						});
					

				//}*/
				//
				
				jQuery("fieldset.roomWrapper div.off select").prop("disabled", true);
				
				jQuery(".submiter").click(function(){
					jQuery("#configForm").submit();
					return false;
				});
				//link
				modify.initDetailsLinks();
				//booking engine
				modify.subBooking();
				
				// supprime le loader puis affiche le contenu
				jQuery("#room-dates .contentContainer").css("background", "none");
				modify.main.css("visibility", "visible");//loading state
				
				jQuery("#configForm fieldset.roomWrapper select[name$='adultNumber']").change();
		}
    },
	// Init display description details
	initDetailsLinks : function(){
		var $detailsLinks = jQuery("div.blocHotel .tDetailsLink");
		$detailsLinks.click(function(){
		jQuery(this).parent().addClass('off').removeClass('on');
		jQuery(".description + .fullDescription").addClass('on').removeClass('off');
			return false;
		});
	},
	//Submit Booking
	subBooking : function() {
		jQuery(".tSubmit").click(function(){
			// disabled input 
			if(jQuery("input[class$=tDisabled]")) {jQuery("input[class$=tDisabled]").prop("disabled",true);}
			jQuery("#sumbookingEngine").submit();
			return false;
		});
	},
	
	answerBooking :  function(errors, json){
		if(errors && errors.length > 0){
			ajaxRequest.showErrors(errors, "errorMessage","sumbookingEngine");
		}
	}
};

jQuery(document).ready(function(){

	utils.rewriteTitle();
	jQuery.noConflict();
	utils.tooltips.init();
	modify.initModify();			
});
