var FBR = {

	is_ie		: /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)
	, is_ie6	: (parseInt(navigator.appVersion.split('MSIE')[1]) == 6)
	
	/*
	, toggleVisibilityItem: function(item, item_class, nav, nav_class) {
		
			$$('.'+nav_class).removeClassName(nav_class);
			$(nav).addClassName(nav_class);

			$$('.'+item_class).removeClassName(item_class);
			$(item).addClassName(item_class);			
	
	}
	*/

	, toggleContactFooter_status : false
	, toggleContactFooter: function(action) {
			
			function stopEffect(eff) { if (eff !== false) Event.stop(eff);	}
				
			var action		= (action != null) ? action : !this.toggleContactFooter_status;
			var menu		= $('footer_contact');
			var menu_effect	= false;
			var menu_event 	= false;
			
			if (action) {
				
				// SHOW MENU
				menu_effect = Effect.Appear(menu, {duration: 0.3
					, afterFinish: function(){
						menu_event = Event.observe(menu, 'mouseleave', function(event) {
							FBR.toggleContactFooter(false);
						});
					}
				});
				
				this.toggleContactFooter_status = true;

			} else {

				// HIDE MENU
				menu_effect = Effect.Fade(menu, {duration: 0.3
					, beforeStart: function(){
						 if (menu_event !== false) Event.stop(menu_event);
					}
				});

				this.toggleContactFooter_status = false;

			}

		
	}

	, toggleReservations_status : false
	, toggleReservations: function(action, toshow) {

			var item		= $('header_reservations');
			var res			= $('res');
			var def			= res.getAttribute('default_main');
			var action		= (action != null) ? action : !this.toggleReservations_status;

			if (action) {
			
				if (def && def.length) {
					item.down('DIV.main_menu').hide();
					item.down('DIV.header').show();
					$$('FORM[name="'+def+'_form"]').invoke('show');
				}
						
				item.show();				
				this.toggleReservations_status = true;
			} else {
				item.hide();
				item.select('FORM').invoke('hide');
				item.down('DIV.header').hide();
				item.down('DIV.main_menu').show();
				this.toggleReservations_status = false;
			}
	
	}
	, toggleReservationsOld: function(action, toshow) {

			var action		= (action != null) ? action : !this.toggleReservations_status;
			var item		= $('header_reservations');

			item.removeClassName('loaded');
			
			if (action) {

				item.update('<div id="header_reservations_embed"> </div>');
				item.show();				
				this.toggleReservations_status = true;
				var flash_config 	= (document.location.href.indexOf('ifb/')>0) ? 'reservations_config_ifb' : 'reservations_config';
				var flash_source 	= (document.location.href.indexOf('ifb/')>0) ? 'ifb' : 'web';				
				var flashvars 		= {conf_uri: '/assets/swf/'+flash_config+'.xml', strtSection: "", source: flash_source};
				var params 			= { wmode:"transparent", bgcolor: "#ff00ff", menu: "true", quality: "high", scale: "noScale", allowScriptAccess: "always", swLiveConnect: "true", allowFullScreen: "false" };
				swfobject.embedSWF("/assets/swf/reservations.swf", "header_reservations_embed", "240", "540", "9","assets/playerProductInstall.swf", flashvars, params);

			} else {

				item.hide();
				this.toggleReservations_status = false;

			}
		
	}
	, reservationsLoaded: function() {
			$('header_reservations').addClassName('loaded');	
	}


	, appendQueryParams: function(iframe_id) {
		
		if ((document.location.href).indexOf('?') < 0) return;

		if ((iframe = $(iframe_id))) {

			// First, get all the params in the current url	
	
			var query_params 	= {};
			var url 			= document.location.search.replace( /^\?|#.*$/g, '' );
			var url_parts 		= url.split('&');
			var nv;
	
			for (i = 0; i < url_parts.length; i++) {
				nv = url_parts[i].split('=');
				query_params[nv[0]] = nv[1];
			}
	
			// Second, loop through all the possible params which can be passed to iframe
	
			var possible 	= ['arrive','depart','adult','child','promo','group'];
			var iframe_src 	= iframe.src;
			var to_append	= (iframe_src.indexOf('?') > 0) ? '&' : '?';
			
			possible.each(function(p) {
				if (query_params[p]) {	
					to_append += p+'='+query_params[p];
				}		
			});
			
			if (to_append.length > 1) {
				iframe.src = iframe_src + to_append;
			}			
			
		}
	
	}

	, _resizeFlash: function(items, height) {
	
			items.each(function(i){		
				i.setStyle({
					height: height+'px'
				});			
			});
	
			return true;
	
	}
	
	, openWindow: function(url, params) {
			if (!url) return;
			
			// <a href="javascript:FBR.openWindow('http://www.google.com', {height: 600, width: 600});">OPEN</a>

			var height 	= params.height || 300;
			var width 	= params.width 	|| 300;
			var scroll 	= params.scroll	|| 'no';
			var name 	= params.name 	|| 'PopWindow';
			var resize 	= params.resize || 0;

			var left	= (screen.width - width) / 2;
			var top 	= (screen.height - height) / 2;

			winprops 	= 'height='+height+',width='+width+',top='+top+',left='+left+',resizable='+resize+',scrollbars='+scroll;
		
			openwindow 	= window.open(url, name, winprops);
			openwindow.focus();
	}

	, showGiftCard : function() {	
		FBR.openWindow('https://www.fontainebleau.com/web/promotions/fontainebleau_gift_cards/gift_cards', {width: 420, height: 500, scroll: 'yes'});
	}

	, contact: function(form) {
		
			var form 	= $(form);
			var error	= form.down('#contact_form_error_msg');
			var has_err	= false;
			
			var req		= ['contact[first_name]', 'contact[last_name]', 'contact[email]']
			
			error.hide();
			
			$$('.field_error').invoke('removeClassName', 'field_error');
			
			req.each(function(elem) {
			
				var field = $(elem);
				
				if (!field.value.length || (field.value == field.getAttribute('default'))) {
					has_err = true;
					field.addClassName('field_error');
				}
			
			});

			var topic = $('contact[topic]');
			if (!topic.value.length || (topic.value == 'Please select')) {
				has_err = true;
				topic.up('.select_group').addClassName('field_error');
			}
			
			if (has_err) {
				console.log(error);
				error.show();
				Effect.Pulsate(error,{ pulses: 2});
				return false;
			} else {
				$('pop_contact_form_loading').show();
				$('pop_contact_form_submit').hide();
				return true;
			}
			
			return false;
			
	}

	, pop : {
	
		width_padding		: 134
		, default_width 	: 750
		, top_offset		: 100
		, is_init			: false	

		, overlay			: null
		, pop_content		: null
		, pop_table			: null
		, pop_image			: null

		, init: function() {

				var content_html = '<div id="pop_wrapper" style="display: none;">'
									+ '<div id="pop_innerwrapper">'
										 + '<div id="pop_close"><a href="#CLOSE" onClick="FBR.pop.hide(); return false;">CLOSE</a></div>'
										 + '<div id="pop_content"></div>'
									+ '</div>'
									+ '</div>';
									
				var overlay_html = '<div id="pop_overlay" style="display: none;"></div>';

				$$('BODY').first().insert({top: content_html + overlay_html});
				
				this.overlay 		= $('pop_overlay');
				this.pop_content 	= $('pop_content');
				this.pop_wrapper 	= $('pop_wrapper');
				this.pop_inner 		= $('pop_innerwrapper');

				this.is_init 		= true;

				// Assign close listener to overlay
				this.overlay.observe('click', function() {
					FBR.pop.hide()
				});		

		}


		, video: function(flv, width, height,share) {
			
				var w = width || '800';
				var h = height || '450';
				var s = share || 'http://www.fontainebleau.com/web/discover/view_video';
		
				this._show('<div style="width: '+w+'px; height: '+h+'px;"><div id="pop_video"> </div></div>', 'video');
	
				var flashvars 	= {
					configUrl: '/assets/swf/media_player_share.xml'
					, assetURL: flv
					, shareUrl: s
					, addThisPath: "/assets/swf/AddThisMenuAPI.swf"
					};	
				var params 		= {wmode:'opaque', bgcolor: "#000000", menu: "true", quality: "high", scale: "noScale", allowScriptAccess: "always", swLiveConnect: "true", allowFullScreen: "true"};		
				swfobject.embedSWF("/assets/swf/media_player_share.swf", "pop_video", w, h, "9.0.28","assets/playerProductInstall.swf", flashvars, params);
			
		}

		
		, show: function(img, width) {
				this._show('<img src="' + img + '"/>');
		}

		, _showLoading: function() {
				this._show('<img src="/assets/img/loading.gif"/>', 'loading');
		}

		, _show: function(content, type) {
		
				if (!this.is_init) this.init();

				this.pop_inner.style.marginTop = (($$('BODY').first().viewportOffset()[1] * -1) + this.top_offset) + 'px';

				this.overlay.show();
				this.pop_inner.className = (type||'');
				this.pop_content.update(content);
				this.pop_wrapper.show();

				// Why is this in here? It's breaking the centering in IE
//				this.pop_wrapper.style.width = (this.pop_inner.getWidth()) + 'px';

				// Assign close listener to overlay
				this.overlay.observe('click', function() {
					FBR.pop.hide()
				});			

		}


		, hide: function() {
				this.overlay.hide();
				this.pop_wrapper.hide();
		}
	
	}

	, initDropdown: function(num, prefix) {
	
			if (prefix == undefined) prefix = 'dropdown_';
	
			$$('#'+prefix+num).each(function(drop) {
			
				var button	= drop.down('a.button');
				var links	= drop.down('.links');
				var status	= 'hide';

				var _toggleDropdown = function() {
					return (status == 'hide') ? _showDropdown() : _hideDropdown();
				};

				var _showDropdown = function() {

					status = 'show';

					button.addClassName('open');
					links.show();

					drop.observe('mouseleave', function(e){
						if (e.relatedTarget && !e.relatedTarget.up('.dropdown')) {
							_hideDropdown();
						}
					});					
				
				};

				var _hideDropdown = function() {

					status = 'hide';

					// Close it
					button.removeClassName('open');
					links.hide();
					
					// Clear listener
					Event.stopObserving(drop, 'mouseout');
				
				};
				
				button.observe('click', _toggleDropdown);

				links.observe('click', _hideDropdown);
			
			});
			
			return;
			
			
			
			
			if (button.hasClassName('open')) {

				// Close it
				button.removeClassName('open');
				links.hide();
				
				// Clear listener
				Event.stopObserving(drop, 'mouseout');
				
			} else {

				// Open it
				button.addClassName('open');
				links.show();

				drop.observe('mouseleave', function(e){
					
					console.log('mouseleave');
				
					if (e.relatedTarget && !e.relatedTarget.up('.dropdown')) {
						FBR.toggleDropdown(e.findElement('DIV.dropdown'));							
						drop.stopObserving('mouseout');
					}
				});

			}	
	
	}

	, selectDropdown: function(num, item) {
			
			drop 	= (parseFloat(num)) ? $('dropdown_'+num) : num;
			button	= drop.down('a.button');
			links	= drop.down('.links');
			
			button.update(item.innerHTML);
			
			console.log(links);
			
			//FBR.toggleDropdown(num);

			// Close it
			button.removeClassName('open');
			links.hide();
			
			// Clear listener
			Event.stopObserving(drop, 'mouseout');
	
	}
	
	, dropdownOption: function(list, num, option) {
		
			if (!list) return;
			if (!num) return;
			
			option = $(option);
			
			if (option) {
				var val = option.innerHTML;
				var dd	= option.up('.dropdown');
				var btn = dd.down('.button');
				btn.innerHTML = val;
			}
			
			var items = $(list).select('div.option');
			
			items.each(function(i){ i.hide(); });
	
			$(list).down('div.option_'+num).show();
	
	}

	, galleryPhoto: function(num, count) {
	
			$$('.photo_full').invoke('hide');
			$('photo_full_'+num).show();

			$$('#ft_wrpper_inner .active').invoke('removeClassName', 'active');
			$('photo_thumb_'+num).addClassName('active');
			
			page = Math.ceil(num/6);

			FBR.footerSlides.go(page);
	
	}


	, showItem: function(show, hide, button) {

			var to_hide = $$('.'+hide);
			if (to_hide.length) to_hide.invoke('hide');

			if ((to_show = $(show))) to_show.show();

			if (button && (button = $(button))) {
				
				$$('.active').invoke('removeClassName', 'active');
				
				button.addClassName('active');			

			}
	
	}
	
	, inputFieldDefault: function(input) {

			input.addClassName('default');
			var default_string 	= input.getAttribute('default');
			if (!input.value.length) input.value = default_string;
		
			input.observe('focus', function(event){
				if ($F(input) != default_string) return;
				input.value = '';
				input.removeClassName('default');
			});
		
			input.observe('blur', function(event){
				if ($F(input) != '') return;
				input.addClassName('default');
				input.value = default_string;
			});

	}
	
	, initNav: function() {
	
			if (!this.is_ie6) return;
			
			$$('#header_menu_list .main').each(function(menu) {				
				Event.observe(menu, 'mouseenter', function(event){
					menu.addClassName('hover');
				});
				Event.observe(menu, 'mouseleave', function(event){
					menu.removeClassName('hover');
				});
			});	

			$$('#header_top .discover').each(function(menu) {				
				Event.observe(menu, 'mouseenter', function(event){
					menu.addClassName('hover');
				});
				Event.observe(menu, 'mouseleave', function(event){
					menu.removeClassName('hover');
				});
			});	
	
	}

	, initTvListings: function(list) {
	
			$$('#'+list+' .listing').each(function(menu) {		
				
				Event.observe(menu, 'mouseover', function(){
					menu.addClassName('listing_open');
				});
				Event.observe(menu, 'mouseout', function(){
					menu.removeClassName('listing_open');
				});
			});	
		
	
	
	}

	, footerSlides : {
		
			list 			: null
			, prefs			: {
				images_per_slide	: 4
				, slide_class		: 'tile'
				, slider_id			: 'ft_wrpper_inner'
				, slide_width		: 246
			}
			, slides		: null
			, slide_cnt		: 0
			, slide_cur		: 1
			, slide_pages	: 1
			, nav_prev		: null
			, nav_next		: null
			, nav_pages		: null
		
			, init : function(car, width, per) {
			
				if (per) this.prefs.images_per_slide = per;
				
				if (width)			this.prefs.slide_width = width;
			
				this.list 			= $(car).down('#'+this.prefs.slider_id);				
				this.slides 		= this.list.select('.'+this.prefs.slide_class);
				this.slide_cnt		= this.slides.length;
				this.slide_pages	= Math.ceil(this.slide_cnt / this.prefs.images_per_slide);
				this.nav_prev		= $(car).down('#ft_nav_prev');
				this.nav_next		= $(car).down('#ft_nav_next');
				this.list.setStyle({width: ((this.slide_cnt+1)*this.prefs.slide_width)+'px'});
				this.showNav();				
				
			}

			, showNav : function() {
				if (this.slide_cur > 1) 				this.nav_prev.addClassName('active');
				if (this.slide_cur < this.slide_pages) 	this.nav_next.addClassName('active');
			}

			, hideNav : function() {
				this.nav_prev.removeClassName('active');
				this.nav_next.removeClassName('active');
			}

			, prev : function() {				
				if (this.slide_cur > 1) {
					this.hideNav();
					this.slide_cur 	= this.slide_cur - 1;
					var move 		= ((this.slide_cur - 1) * this.prefs.images_per_slide * this.prefs.slide_width) * -1;
					this._move(move);
				}			
			}

			, go : function(go_page) {

					if (this.slide_cur == go_page) return;
					

					this.hideNav();

					var move 	= ((go_page-1) * (this.prefs.images_per_slide * this.prefs.slide_width)) * -1;
					
//					console.log('images_per_slide: '+this.prefs.images_per_slide+' / slide_width:'+this.prefs.slide_width);
//					console.log('go_page: '+go_page+' / move: '+move+' / slide_cur: '+this.slide_cur+' / slide_pages:'+this.slide_pages);

					//alert('go_page: '+go_page+' / move: '+move+' / slide_cur: '+this.slide_cur+' / slide_pages:'+this.slide_pages);

					if ((go_page == this.slide_pages) && (this.slide_pages % this.prefs.images_per_slide != 0)) {
						// Going to last page with incomplete set of tiles
						var offset	= (this.slide_cnt % this.prefs.images_per_slide);
						var move 	= move + (offset * this.prefs.slide_width);
					}
					
					this._move(move);
					this.slide_cur = go_page;
			
			}
			
			, next : function() {

				if (this.slide_cur < this.slide_pages) {
					this.go((this.slide_cur + 1));
				}			

			}

			, _move : function(num) {				
				$(this.prefs.slider_id).morph('left: '+num+'px', {
					duration	: 1
					, beforeStart 	: function(e) {
						e.element.addClassName('scrolling');
					}
					, afterFinish 	: function(e) {
						e.element.removeClassName('scrolling');
						this.showNav();
					}.bind(this)
				});
			}
		
		}
		
		
	, initGalleryModals: function(xsl) {
	
			$$('.photobox A').each(function(btn) {
			
				var href = btn.getAttribute('href');

				btn.observe('click', function(e) {

					e.preventDefault();

					FBR.pop._show('<div id="pop_gallery"> </div>', 'gallery');

					new Ajax.Updater('pop_gallery', href, {parameters: { t: xsl }, onComplete: function() {
						FBR.footerSlides.init('thumbs_scroll', 79, 6);
					}});
					
					
					
					
				
				});
				
			
			});
	
	
	}
	
	
	, initNewHome: function(start) {
			
			// This is required to prevent caching page state when using back button
			window.onunload = function(){};
	
	
			var slide_container	= jQuery('#home_fullscreen');
			var slide_images 	= jQuery('IMG', slide_container);
			var loaded_images	= 0;	
			var timer			= false;
			var ratio 			= 1000 / 1500;
	
			slide_images.css({'zIndex':'1'});	

	
			jQuery(window).resize(function() {
	
				if (timer) clearTimeout(timer);
	
				var header_size = 112;
				var footer_size = 10;
				
				var h = jQuery(window).height();
				var w = jQuery(window).width();
				
				jQuery('#home_fullscreen').height(h-header_size-footer_size);
				jQuery('#home_fullscreen').width(w);
				
				// Resize images_per_slide
				var win_h = slide_container.height()
				var win_w = slide_container.width();
				if (win_h/win_w <= ratio) {
					// Go by width
					var h = win_w * ratio;
					var w = win_w;
				} else {
					// Go by height
					var h = win_h;
					var w = win_h / ratio;
				}
				h = Math.ceil(h);
				w = Math.ceil(w);
				var t = ((win_h - h)/2) -1;
				var l = (win_w - w)/2;				
				slide_images.css({'height':h, 'width':w, 'position': 'absolute', 'top': t, 'left': l});	
				
				/*
				timer = setTimeout(function() {
					jQuery(window).trigger('resize');
				}, 500);
				*/
			
			}).trigger('resize');


			jQuery('#home_fullscreen A').hover(function() {	
				jQuery(this).find('.pink_on').stop(true,true).animate({width: 600}, 900);
			}, function() {
				jQuery(this).find('.pink_on').stop(true,true).animate({width: 0}, 900);
			});
			
			
			
			slide_images.one('load', function() {
				loaded_images++
				if (loaded_images == slide_images.length) {
					setTimeout(start_the_show, 1100);
				}
			}).each(function() {
				if (this.complete) { jQuery(this).trigger('load'); }
			});
			
			
			
			function start_the_show() {
				
				jQuery(window).trigger('resize');				

				slide_container.cycle({
					fx: 'fade',
					timeout: 5000,
					startingSlide: (start-1),
					slideExpr: slide_images,
					before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
					
						var num 	= jQuery(nextSlideElement).data('slide');
						var title 	= jQuery('.slidetitle-'+num);
						
						if ( jQuery.browser.msie ) {
							jQuery('.link_wrapper', slide_container).hide();
							setTimeout(function() {title.show();}, 600);
						} else {
							jQuery('.link_wrapper', slide_container).fadeOut();
							title.delay('500').fadeIn();
						}

						
					}
				});
				
				jQuery('#home_fullscreen_loading').delay(500).fadeOut();
			
			}	


	
	}
		
};

