//global vars
lang = $$('html')[0].readAttribute('lang');
if (lang == '') {
	lang = 'en';
}
_calendar_n = 1;
hotelSelection = [];
selectedHotel = -1;

function openFrame(title, page, width, height) {
	var barHeight = 20;
	_modalFrame = new Control.Modal(false,{
		overlayCloseOnClick: true,
		width: width,
		height: height + barHeight
	});

	_modalFrame.mode = 'named';
	_modalFrame.html = '<div id="modalBar" style="height:'+barHeight+'px;">'+
				'<b class="title">'+title+'</b>'+
				'<img width="15" height="15" src="/images/commun/s_close.png" onclick="_modalFrame.close();" />'+
		'</div>'+
		'<iframe id="modalFrame" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" '+
			 'width="'+width+'" height="'+height+'">'+
		'</iframe>'+
		'<script type="text/javascript">'+
			 '$(\'modalFrame\').src = \''+page+'\';'+
		'</script>'
			;
	_modalFrame.open();
}
function openMap(idHotel, title) {
	title = title || 'Google Map';
	var queryStr = '';
	if (idHotel > 0) {
		queryStr = '?idHotel='+idHotel;
	}
	openFrame(title, 'gmap.php'+queryStr, 750, 507);
}
function isEmail(email) {
	var regex = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
    return !(email == '' || !regex.test(email));
}
function testform(mail) {
	if(!isEmail(mail.value)) {
		alert('Error in you email adress.');
		mail.focus();
		return false;
	}
	return true;
}

function displayCityList(code, disabled) {
	disabled = (disabled === true) ? '1' : '0';
	var url = 'ajax/citylist.php';
	var params = {
		countryCode: code,
		disable: disabled
	};
	new Ajax.Updater(
						{success:'cityList'},
						url,
						{method:'get', parameters:params}
					);
}
function showDatesModal(link){
	Modal = new Control.Modal(false,{
		overlayCloseOnClick: true,
		width: 360,
		height: 180
	});

	Modal.mode = 'named';
	Modal.html = '<div id="modalCalendar"><i>'+calendarModal.title+'</i>'+
		'<div id="resaLink" style="display:none">&nbsp;</div>'+
		'<form action="" method="post" onsubmit="return setDates()">'+
		'<table><tr><td width="20%">&nbsp;</td><td style="text-align:left">'+
		'<div id="pick">'+
		'<p>'+
		'<input type="text" maxlength="10" value="'+$F('arrivee1')+'" id="arrivee2" name="arrivee" onclick="selectarrivee(2);"/>'+
		'<a href="#" name="arr2" id="arr2" onclick="return selectarrivee(2);">'+
		'<img src="images/commun/cal.png" alt="" class="calimg" /></a>'+
		'</p>'+
		'<p>'+
		'<input type="text" maxlength="10" value="'+$F('depart1')+'" id="depart2" name="depart" onclick="selectdepart(2);"/>'+
		'<a href="#" name="dep2" id="dep2" onclick="return selectdepart(2);">'+
		'<img src="images/commun/cal.png" alt="" class="calimg" /></a>'+
		'</p>'+
		'</div></td>'+
		'<td align="left"><p>'+
		'<input type="image" src="images/'+lang+'/reservez.png" alt="" class="submit"/>'+
		'</p>'+
		'</td><td width="20%">&nbsp;</td></tr></table></form></div>';
	Modal.open();

	$('modal_container').style.padding = '0';
	$('resaLink').update(link.href);
	return false;
}
function setDates() {
	var link = $('resaLink').innerHTML;
	link = link.unescapeHTML();
	new Ajax.Request('/ajax/postDates.php',
	  {
	    method:'get',
	    parameters:{
    				arrivee : $F('arrivee2'),
    				depart : $F('depart2')
	    			},
	    onSuccess: function(transport){
	      if (transport.responseText == 'ok') {
	      	document.location = link;
	      }
	    }
	  });
	return false;
}
function cancelDates(){
    $('nbnight').update();
    $('arrivee1', 'depart1').invoke('setValue', '');
	new Ajax.Request('/ajax/cancelDates.php',
			  {
			    method:'get',
			    onSuccess: function(transport){
			      if (transport.responseText == 'ok') {
					var sForm = $('searchForm');
					var action = location.href;
						action = action.replace(/(&arrivee=|&depart=)([0-9]{4}|[0-9]{2})[\/-][0-9]{2}[\/-]([0-9]{4}|[0-9]{2})/g, '');
						action = action.replace(/(arrivee=|depart=)([0-9]{4}|[0-9]{2})[\/-][0-9]{2}[\/-]([0-9]{4}|[0-9]{2})&?/g, '');
						action = action.replace('#', '');
					if (sForm.readAttribute('class') == 'to_submit') {
						sForm.action = action;
						sForm.submit();
			      	} else {
			      		document.location = action;
			      	}
			      }
			    }
			  });
}
function postDates() {
	new Ajax.Request('/ajax/postDates.php',
		  {
		    method:'get',
		    parameters:{
	    				arrivee : $F('arrivee1'),
	    				depart : $F('depart1')
		    			},
		    onSuccess: function(transport){
		      if (transport.responseText == 'ok') {
	      		var path = location.href;
					path = path.replace(/(&arrivee=|&depart=)([0-9]{4}|[0-9]{2})[\/-][0-9]{2}[\/-]([0-9]{4}|[0-9]{2})/g, '');
					path = path.replace(/(arrivee=|depart=)([0-9]{4}|[0-9]{2})[\/-][0-9]{2}[\/-]([0-9]{4}|[0-9]{2})&?/g, '');
					path = path.replace('#', '');

	      		if (/\?/.test(path)) {
	      			path += '&';
	      		} else {
	      			path += '?';
	      		}

	      		path += 'arrivee='+$F('arrivee1')+'&depart='+$F('depart1');
	      		document.location = path;
		      }
		    }
		  });
	return false;
}
function validateSearch() {
	var form = $('cityField');
	if (form.selectedIndex == 0) {
		form.focus();
		return false;
	}
	return true;
}
//getHotelSelection
function getHotelSelection(dir) {
	if (!$('hotelSelection')) {
		return false;
	}
	hotelSelectionSize = hotelSelection.size();

	if (hotelSelectionSize == 0) {
		new Ajax.Request('ajax/hotelSelection.php',
		  {
		  	parameters:'country='+$('hotelSelection').lang,
		    method:'post',
		    onSuccess: function(transport){
		      hotelSelection = transport.responseText.evalJSON();
			  selectedHotel = 0;
		    }
		  });
	}
	if (selectedHotel >= 0 && typeof(dir) == 'string') {
		if (selectedHotel == 0) {
			$$('#prev', '#next').invoke('absolutize');
		}
		switch(dir) {
			case 'prev':
				if (selectedHotel != 0) {
					selectedHotel--;
				}else if(selectedHotel == 0) {
					selectedHotel = (hotelSelectionSize - 1);
				}
			break;
			case 'next':
				if (selectedHotel != (hotelSelectionSize -1)) {
					selectedHotel++;
				} else {
					selectedHotel = 0;
				}
			break;
		}

		var hotelData = {};
		hotelData.ville = hotelSelection[selectedHotel][0];
		hotelData.name = hotelSelection[selectedHotel][1];
		hotelData.photo = hotelSelection[selectedHotel][2];
		hotelData.link = hotelSelection[selectedHotel][3];
		hotelData.hotelId = hotelSelection[selectedHotel][4];
		//update image
		var hotelImage = $$('#hotelSelection .inside img').first();
		hotelImage.src = 'http://static'+Math.floor(Math.random()*5)+'.prestigia.com/static_prestigia_photos/'+hotelData.hotelId+'/medium/'+hotelData.photo;
		hotelImage.alt = hotelData.name;
		hotelImage.up().href = hotelData.link;
		//update ville
		$('hotelSelectionVille').update(hotelData.ville);
		//update links
		var hotelLink = $$('#hotelSelection .inside .bold').first();
		hotelLink.href = hotelData.link;
		hotelLink.title = hotelData.name+' - '+hotelData.ville;
		hotelLink.update(hotelData.name);
	}
	return false;
}
//Initialise le filtre
function initializeFilter(){
	$('selectStars').selectedIndex = 0;
}
//hotel results filter
function filterResults() {
	var selectZone = $('selectCityZone'), selectStars = $('selectStars'),
		selectedStarValue = 0, selectedZoneValue = '', hotelsToHide = [], hotelsToShow = [];

	if (selectZone.selectedIndex != 0) {
		selectedZoneValue = selectZone.options[selectZone.selectedIndex].text;
	}

	if (selectStars.selectedIndex != 0) {
		selectedStarValue = selectStars.options[selectStars.selectedIndex].value;
		selectedStarValue = parseInt(selectedStarValue, 10);
	}

	filterHotels.each(function(hotel){
		if ((hotel.stars == selectedStarValue || selectedStarValue == 0) &&
			(hotel.zone == selectedZoneValue || selectedZoneValue == '') &&
			(hotel.price >= sliderMinValue && hotel.price <= sliderMaxValue))
		{
			hotelsToShow.push($('offer'+hotel.id));
		} else {
			hotelsToHide.push($('offer'+hotel.id));
		}
	});

	hotelsToShow.invoke('show');
	hotelsToHide.invoke('hide');

	//hide/show demandeDispoTitle
	var needToHide = true;
	$('notDispoHotels').childElements().each(function(hotel){
		if (hotel.visible()) needToHide = false;
	});
	var elementToHide = $$('div.lighter')[1];
	elementToHide.show();
	if (needToHide) elementToHide.hide();

	//ie6 dom refresh
	if (Prototype.Browser.IE) {
		var content = $('content');
		content.innerHTML = content.innerHTML;
	}
}

function IEVersion(){
	return parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf('MSIE')+5), 10);
}
function addCurrency(n) {
	return n + hotelCurrency;
}
function sliders() {
	var sliderValues = [], prices = [];
	eMinPrice = $('minPrice');
	eMaxPrice = $('maxPrice');

	filterHotels.each(function(hotel) {
		if (prices.indexOf(hotel.price) == -1) {
			prices.push(hotel.price);
		}
	});

	sliderMinValue = prices.min();
	sliderMaxValue = prices.max();
	sliderValues = prices.sortBy(function(n){return n});

    Slider = new Control.Slider($$('.handle'), 'priceSlider', {
					range : $R(sliderMinValue, sliderMaxValue),
					values : sliderValues,
					sliderValue : [sliderMinValue, sliderMaxValue],
					restricted : true,
					onSlide: function(value) {
						if (value[0] == value[1]) {
							return;
						}
						eMinPrice.update(addCurrency(value[0]));
						eMaxPrice.update(addCurrency(value[1]));
					},
					onChange: function(value) {
						if (value[0] == value[1]) {
							var valueIndex, neareastValue;
							if (sliderMinValue != value[0]) {
								valueIndex = Slider.allowedValues.indexOf(value[0]);
								neareastValue = Slider.allowedValues[valueIndex - 1];
								Slider.setValue(neareastValue, 0);
							}
							if (sliderMaxValue != value[1]) {
								valueIndex = Slider.allowedValues.indexOf(value[1]),
								neareastValue = Slider.allowedValues[valueIndex + 1];
								Slider.setValue(neareastValue, 1);
							}
						}
						eMinPrice.update(addCurrency(value[0]));
						eMaxPrice.update(addCurrency(value[1]));
						sliderMinValue = value[0];
						sliderMaxValue = value[1];
						filterResults();
					}
			    });
	eMinPrice.update(addCurrency(sliderMinValue));
	eMaxPrice.update(addCurrency(sliderMaxValue));
}
var hotelsTri = {
	tri : function(option) {
		if(option.value == ''){
			return;
		}
		this.dispoHotels = $('dispoHotels');
		this.notDispoHotels = $('notDispoHotels');
		this[option.value]();
	},
	pricesDesc : function() {
		this.sortHotels('desc');
	},
	pricesAsc : function() {
		this.sortHotels('asc');
	},
	sortHotels : function(type) {
		filterHotels = filterHotels.sortBy(function(e){
							return e['price'] * 1;
						});
		var tmpElements = [], hotelsData = filterHotels.clone();
		if (type == 'desc') {
			hotelsData = hotelsData.reverse();
		}

		['dispoHotels', 'notDispoHotels'].each(function(elem) {
			tmpElements[elem] = new Element('div', {
												'id': elem+'Copy',
												'style': 'display:none'
											});
			var first = true;
			hotelsData.each(function(hdata){
				if ($('offer' + hdata.id).descendantOf(elem)) {
					var elementClass = '';
					if (first) {
						elementClass = 'offre first';
						first = false;
					} else {
						elementClass = 'offre';
					}
					var hotelCopy = new Element('div', {
						'class': elementClass,
						'id': 'offer' + hdata.id
					}).update($('offer' + hdata.id).innerHTML);
					tmpElements[elem].insert(hotelCopy);
				}
			});
			this[elem].update(tmpElements[elem].innerHTML);
		}, this);
	},
	recommend : function() {
		var notesData, notesValues, tmpElements = [];
		['dispoHotels', 'notDispoHotels'].each(function(elem) {
			if (this[elem]) {
				notesData = {};
				notesValues = [];
				tmpElements[elem] = new Element('div', {
												'id': elem+'Copy',
												'style': 'display:none'
											});
				var notesElements = $$('#'+elem+' .note i');

				if (notesElements.size == 0) {
					return;
				}

				notesElements.each(function(note){
					var hotelId = note.up('.offre').id;
					hotelId = hotelId.gsub('offer', '');
					hotelId = parseInt(hotelId, 10);
					var noteValue = parseInt(note.innerHTML, 10);
					if(isNaN(noteValue)){
						noteValue = 0;
					}
					if (typeof notesData[noteValue] == 'undefined') {
						notesData[noteValue] = [];
					}
					notesData[noteValue].push(hotelId);
					notesValues.push(noteValue);
				});
				notesValues = notesValues.uniq();
				notesValues = notesValues.sortBy(function(e){
					return e * -1;
				});

				var first = true;
				notesValues.each(function(note){
					notesData[note].each(function(hotelId){
						if ($('offer' + hotelId).descendantOf(elem)) {
							var elementClass = '';
							if (first) {
								elementClass = 'offre first';
								first = false;
							} else {
								elementClass = 'offre';
							}
							var hotelCopy = new Element('div', {
								'class': elementClass,
								'id': 'offer' + hotelId
							}).update($('offer' + hotelId).innerHTML);
							tmpElements[elem].insert(hotelCopy);
						}
					});
				});
				this[elem].update(tmpElements[elem].innerHTML);
			}
		}, this);
	}
}
function jsLink(link) {
	window.location = link + '.html';
}

function changeCurrency() {
	new Ajax.Request('ajax/changeCurrency.php', {
		method:'post',
		parameters : {dev:$F('dev')},
		onSuccess: function(transport){
		  if (transport.responseText == 'ok') {
		  	document.location = location.href;
		  }
		}
	});
}
function addBookMark(bTitle, bUrl) {
	var title = bTitle ? bTitle : document.title,
		url = bUrl ? bUrl : location.href,
		PB = Prototype.Browser;

	if (PB.Gecko) {//ff
		window.sidebar.addPanel(title, url, '');
	} else if (PB.IE) {//ie
		window.external.AddFavorite(url, title);
	} else {
		var msg = 'Bookmark us with CTRL + D';
		switch(lang) {
			case 'fr':
				msg = 'Ajoutez nous avec CTRL + D';
			break;
			case 'es':
				msg = 'marcador con CTRL + D';
			break;
			case 'de':
				msg = 'Bookmarken Sie uns mit CTRL + D';
			break;
		}
		alert(msg);
	}
}
function largeImg(href, galleryVersion) {
	var width = 350,
		height = 240;
	if (galleryVersion == '1') {
		width = 450;
		height = 270;
	}
	
	var img = $(href).down('img').src;

	_modal = new Control.Modal(false,{
		containerClassName : 'roomPic',
		overlayCloseOnClick: true,
		width: width,
		height: height + 30
	});

	_modal.mode = 'named';
	_modal.html = '<a href="javascript:_modal.close();" style="float:right">'+
						'<img src="/images/commun/s_close.png" width="15" height="15" />'+
					'</a><img src="'+img.replace('/medium/', '/large/')+'" width="'+width+'" height="'+height+'" />';
	_modal.open();

	$('modal_container').style.padding = '0';
	return false;
}
function popup(page,w,h) {
	var w=window.open(page,'nomfen','resizable=no,width=350,height=240,location=no,menubar=no,status=no,scrollbars=no,menubar=no');
	w.focus();
}
function bookNow(quantite, link){
	document.location.href = link+'&quantite='+quantite;
}
function addslashes(str) {
	return str.replace(/\'/g,'\\\'').replace(/\"/g,'\\"').replace(/\\/g,'\\\\').replace(/\0/g,'\\0');
}
function displayPics(miniImg) {
	var largeImgSrc = miniImg.src.replace('/mini/', '/large/');
	$('viewer').update('<img width="350" height="240" src="'+largeImgSrc+'" />');
}
function showPromo(link) {
	var promosLinkDD = $(link).up(),
		promos = promosLinkDD.next();
	promosLinkDD.remove();
	promos.show();
	return false;
}
function filterPromotions(option) {
	var cityId = option.value;
	if (cityId == '') {
		return;
	}
	cityId = cityId * 1;
	$$('.offre').each(function(promo){
		var promoCityId = promo.id.gsub('promo', '') * 1;
		if (promoCityId == cityId) {
			promo.show();
		} else {
			promo.hide();
		}
	});
}
function openRoomCond(roomId) {
	openFrame('', 'room_conditions.php?roomId='+roomId+'&lang='+lang, 455, 239);
}
function showHotelComments(hotelId) {
	openFrame('', 'hotel_comments.php?hotelId='+hotelId, 505, 497);
}
function fbBecomeFan() {
    var pageId = '81626600160',
		cssLink = 'http://static'+Math.floor(Math.random()*5)+'.prestigia.com/static_prestigia_css/fb.css';
    openFrame('', 'http://www.facebook.com/connect/connect.php?id='+pageId+'&connections=10&stream=1&css='+cssLink, 300, 550);
}
function attachTipCal() {
	$$('.reserve a').each(function(elem){
		_calendar_n++;
		var upDiv = elem.up('.room'),
			roomId = upDiv.id.replace('room', '') * 1,
			tipCal = new Element('div', {id: 'pick', className: 'tipCalendar'});
		tipCal.update('<p><input type="text" maxlength="10" value="'+$F('arrivee1')+'" id="arrivee'+_calendar_n+'" '+
		'onclick="selectarrivee('+_calendar_n+');"/>'+
		'<a href="#" name="arr'+_calendar_n+'" id="arr'+_calendar_n+
		'" onclick="return selectarrivee('+_calendar_n+');">'+
		'<img src="/images/commun/cal.png" class="calimg" /></a>'+
		'</p><p>'+
		'<input type="text" maxlength="10" value="'+$F('depart1')+'" id="depart'+_calendar_n+
		'" onclick="selectdepart('+_calendar_n+');"/>' +
		'<a href="#" name="dep'+_calendar_n+'" id="dep'+_calendar_n+'" onclick="return selectdepart('+_calendar_n+');">' +
		'<img src="/images/commun/cal.png" class="calimg" /></a>' +
		'</p><p>'+
		 '<a class="roll" href="javascript:setRoomDates('+_calendar_n+','+roomId+')">'+$$('.searchaction .submit')[0].value+'</a>'+
		'</p><br />');

		new Tip(elem, tipCal, {
			width: 200,
			title: translation['dates_tooltip_title'],
			style: 'prestigia',
			stem: 'rightTop',
			viewport: true,
			hook: {
				target: 'topLeft',
				tip: 'topRight'
			},
			closeButton: true,
			fixed: false,
			hideOthers: true,
			hideAfter: false,
			hideOn: 'click',
			showOn: 'click'
		});

		elem.observe('click', function(e){
			e.stop();
		});
	});
}
function setRoomDates(calendarId, roomId) {
	var params = {
			arrivalDate: $F('arrivee'+calendarId),
			departureDate: $F('depart'+calendarId),
			roomId: roomId
		};
	new Ajax.Request('/ajax/roomDates.php',
			  {
			  	parameters: params,
			    method: 'post',
			    onSuccess: function(tr){
					if (tr.responseText == 'ok') {
						document.location = location.href;
					}
			    }
			  });
}
function initCalendar() {
	var calendar = new Element('div', {id : 'calendar'}).setStyle({
						position : 'absolute',
						left : '305px',
						top : '36',
						width : '14px',
						height : '15px',
						zIndex : '1500'
					});
	$$('body')[0].insert(calendar);
	loadScript('/js/lang/'+lang+'.js', 'utf-8');
	loadScript('/js/calendar.js');
}
function loadScript(file, charset) {
	var attributes = {
			src : file,
			type : 'text/javascript'
		};
	if (charset != null) {
		attributes.charset = charset;
	}
	$$('head')[0].insert(new Element('script', attributes));
}
function applyDinFont() {
	sIFR.replaceElement('.din', named({sFlashSrc: '/flash/din.swf', sBgColor: '#45537A', sColor: '#FFFFFF',
											sCase: 'upper', sFlashVars: 'textalign=right',
											nPaddingTop: '8', nPaddingRight: '10', nPaddingBottom: '4', nPaddingLeft: '10',
											sWmode: 'opaque'}));
}
function verticalCenterElem(e) {
	var dim = e.getDimensions();
	Position.prepare();
	var o = Position.deltaY + ((Control.Modal.getWindowHeight() > dim.height) ?
								Math.floor((Control.Modal.getWindowHeight() - dim.height) / 2) :
								0);
	e.style.top = (dim.height <= Control.Modal.getDocumentHeight()) ? ((o != null && o > 0) ? o : '0') + 'px' : 0;
}

function vignette() {
	var elemCsHelp = $('cshelp');
	if (elemCsHelp) {
		var cookieJar = new CookieJar({expires: 60/*sec*/ * 15}),
			closed = cookieJar.get('closed');

		if (!closed) {
			($$('body')[0]).insert(elemCsHelp.show());
			verticalCenterElem(elemCsHelp);

			if (Prototype.Browser.IE && IEVersion() < 7) {
				Event.observe(window,'resize',(function(){
					verticalCenterElem(elemCsHelp);
				}),false);
				Event.observe(window,'scroll',(function(){
					verticalCenterElem(elemCsHelp);
				}),false);
			} else {
				elemCsHelp.style.position = 'fixed';
			}

			$$('.csclose')[0].observe('click', function(){
				elemCsHelp.hide();
				cookieJar.put('closed', 1);
			});
		}
	}
}

function packSelect(){
	if ($('packs')) {
		var packSelects = $$('.packSelect');
		//remove checked option when pack radio selected
		packSelects.each(function(packSelect) {
			packSelect.observe('click', function(radioEvent) {
				var radioElem = Event.element(radioEvent);
				$$('.packOption').each(function(packOption) {
					if (!packOption.descendantOf(radioElem.up('.packList'))) {
						packOption.checked = false;
					}
				})
			});
		});

		$$('.packOption').each(function(packOption) {
			packOption.observe('click', function(optionEvent) {
				var optionElem = Event.element(optionEvent),
					parentDiv = optionElem.up('.packList'),
					radioElem = parentDiv.select('.packSelect')[0];

				if (!radioElem.checked) {
					radioElem.checked = true;
					$$('.packOption').each(function(packOption) {
						if (!packOption.descendantOf(parentDiv)) {
							packOption.checked = false;
						}
					});
				}
			});
		});
	}
}

Event.observe(document, 'dom:loaded', function() {
	initCalendar();
	getHotelSelection();
	vignette();
	packSelect();
});