var Modal = new Class({
	Implements: [Events, Options],
	options: {
		overlayId: 'modal-overlay',
		modalId: 'modal-window',
		hasClose: true,
		closeClass: 'close',
		closeHtml: '',
		clickToClose: true,
		transitionDuration: 250,
		onShowComplete: Class.empty,
		onHideComplete: Class.empty,
		onUpdateComplate: Class.empty
	},
	initialize: function(options){
		this.setOptions(options);
		
		// create overlay element
		this.overlay = new Element('div').setProperty('id', this.options.overlayId).inject(document.body);
		if(this.options.clickToClose){
			// add a pointer on the overlay if click to close is set
			this.overlay.setStyle('cursor', 'pointer');
		}
		
		// create modal window
		this.modal = new Element('div').setProperty('id', this.options.modalId).injectAfter(this.overlay);
		if(this.options.hasClose){
			// create close button if option set
			this.modalClose = new Element('div').addClass(this.options.closeClass).set('html', this.options.closeHtml).inject(this.modal);
		}
		this.modalContent = new Element('div').addClass('content').inject(this.modal);
		
		// create effects objects
		this.modal.fx = new Fx.Tween(this.modal, {
			property: 'opacity',
			duration: this.options.transitionDuration
		});
		this.overlay.fx = new Fx.Tween(this.overlay, {
			property: 'opacity',
			duration: this.options.transitionDuration
		});
		this.overlay.fx.set(0);
		
		this.isOpen = false;
		
		this.attach();
	},
	attach: function(){
		var self = this;
		
		if(this.options.clickToClose){
			this.overlay.addEvent('click', function(){
				self.hide();
			});
		}
		
		window.addEvent('resize', function(){
			if(self.isOpen){
				self.positionOverlay();
				self.positionModal();
			}
		});
		
		// attach event if option set for close
		if(this.options.hasClose){
			this.modalClose.addEvent('click', function(){
				self.hide();
			});
		}
	},
	show: function(content){
		// modal is not open yet
		if(!this.isOpen){
			this.isOpen = true;
			
			this.modal.fx.set(0);
			this.modal.setStyle('display', 'block');
			// inject content in to modal window
			content.inject(this.modalContent);
			
			// fix for ie6 select boxes showing through and safari 2 flash showing through
			if(window.ie6)
				$$('select').setStyle('visibility', 'hidden');
			else if(window.webkit419)
				$$('embed').setStyle('visibility', 'hidden');
			
			// show/position and fade in overlay
			this.overlay.setStyle('display', 'block');
			this.positionOverlay();
			this.overlay.fx.start(0.6).chain(function(){
				this.positionModal();
				this.modal.fx.start(1).chain(function(){
					this.fireEvent('onShowComplete');
				}.bind(this));
			}.bind(this));
		}
		// modal is already open so we just need to update and reposition
		else{
			this.modal.fx.start(0).chain(function(){
				this.modalContent.empty();
				content.inject(this.modalContent);
				this.positionModal();
				this.modal.fx.start(1).chain(function(){
					this.fireEvent('onShowComplete');
					this.fireEvent('onUpdateComplete');
				}.bind(this));
			}.bind(this));
		}
	},
	hide: function(){
		if(this.isOpen){
			this.isOpen = false;
			this.modal.fx.start(0).chain(function(){
				this.modal.setStyles('display', 'none');
				this.overlay.fx.start(0).chain(function(){
					// fix for ie6 select boxes showing through and safari 2 flash showing through
					if(window.ie6)
						$$('select').setStyle('visibility', 'visible');
					else if(window.webkit419)
						$$('embed').setStyle('visibility', 'visible');
					this.overlay.setStyle('display', 'none');
					this.modalContent.empty();
					this.fireEvent('onHideComplete');
				}.bind(this));
			}.bind(this));
		}
	},
	positionOverlay: function(){
		this.overlay.setStyles({
			'height': window.getScrollHeight(),
			'width': window.getWidth()
		});
	},
	positionModal: function(){
		var modalSize = this.modal.getSize();
		var left = (window.getScrollLeft() + (window.getWidth() - modalSize.x)/2);
		var top = (window.getScrollTop() + (window.getHeight() - modalSize.y)/2);
		if(top < 0)
			top = 0;
		this.modal.setStyles({
			'top': top,
			'left': left
		});
	}
});

var ModalHandler = new Class({
	Implements: [Events, Options],
	options: {
		loginUrl: '/vegas/play/sports/modal/login.jsp',
		sendToAFriendUrl: '/vegas/play/sports/modal/send.jsp',
		newsListUrl: '/vegas/play/sports/modal/news.jsp'
	},
	initialize: function(options){
		this.setOptions(options);
		
		this.modal = new Modal();
		
		this.attach();
	},
	attach: function(){
		// event delegation for opener links
		$(document.body).addEvent('click', function(e){
			var target = $(e.target);
			if(target.get('tag') == 'a'){
				// send to a friend links
				if(target.hasClass('send-to-a-friend')){
					e.preventDefault();
					// use ajax to get the form
					var request = new Request.HTML({
						onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
							// show the form
							this.showSendToAFriend(responseHTML);
						}.bind(this)
					});
					request.get(target.get('href'));
				}
				
				// show all news articles link
				else if(target.get('id') == 'show-news-list'){
					e.preventDefault();
					this.showNewsList();
				}
			}
		}.bind(this));
	},
	getLogin: function(){
		// check to see if the user is already logged in before doing anything
		if(!isLoggedIn){
			var request = new Request.HTML({
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					// show the form
					this.showLogin(responseHTML);
				}.bind(this)
			});
			request.get(this.options.loginUrl);
			return true;
		}
		else
			return false;
	},
	showLogin: function(html){
		// strip the required html and make an element from it
		var responseText = html.split('<body>')[1].split('</body>')[0];
		var responseElement = new Element('div').set('html', responseText);
		
		// atach a on submit event to the form that
		var self = this;
		responseElement.getElement('form').addEvent('submit', function(e){
			e.stop();
			// submit the form with ajax
			var url = this.action + "?" + this.toQueryString();
			new Request({
				url: url,
				method: 'post',
				onComplete: function(response){
					if(response.contains('modal-login'))
						self.showLogin(response); // User not logged in yet show the form again
					else
						window.location.reload(); // refresh the page
					/*// Use the response length to determine if the user has logged in or not
					if(response.contains('modal-login')){
						// User not logged in yet show the form again
						self.showLogin(response);
					}
					else{
						// refresh the page
						window.location.reload();
						// The user has succesfully logged in. Set the global login flag to true and hide the popup
						isLoggedIn = true;
						self.modal.hide();
					}*/
				}
			}).send();
		});
		
		// show in modal window
		this.modal.show(responseElement.getFirst());
	},
	showSendToAFriend: function(html){
		// strip the required html and make an element from it
		var responseText = html.split('<body>')[1].split('</body>')[0];
		var responseElement = new Element('div').set('html', responseText);
		
		// atach a on submit event to the form that
		var self = this;
		responseElement.getElement('form').addEvent('submit', function(e){
			e.stop();
			// submit the form with ajax
			var url = this.action + "?" + this.toQueryString();
			new Request({
				url: url,
				method: 'post',
				onComplete: function(response){
					// take the response and put back in the page
					self.showSendToAFriend(response);
				}
			}).send();
		});
		
		// show in modal window
		this.modal.show(responseElement.getFirst());
	},
	showNewsList: function(){
		// pull in the news list
		var request = new Request.HTML({
			onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
				// show in modal window
				this.modal.show(responseElements[0]);
				// apply scroll bar
				new ScrollBar('news-scroll',{
					trackDimension: 17
				});
			}.bind(this)
		});
		request.get(this.options.newsListUrl);
	}
});


/*
 * This is a patch for Mootools Request.HTML
 *
 * If you use Request.HTML to load some data containing any HTML special chars
 * like &nbsp; or &laquo; it won't work with Webkit based browsers.
 */
Request.HTML.implement({
	processHTML: function(text){
		var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
		text = (match) ? match[1] : text;
		
		var container = new Element('div');
		
		return $try(function(){
			var root = '<root>' + text + '</root>', doc;
			if(Browser.Engine.trident){
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = false;
				doc.loadXML(root);
			}else{
				doc = new DOMParser().parseFromString(root, 'text/html');
			}
			root = doc.getElementsByTagName('root')[0];
			for(var i = 0, k = root.childNodes.length; i < k; i++){
				var child = Element.clone(root.childNodes[i], true, true);
				if(child) container.grab(child);
			}
			return container;
		}) || container.set('html', text);
	}
});




//summer events page

var addthis_pub="vegassummer";
var addthis_offset_top = (Browser.Engine.trident?-13:182);
var summer={
	init:function() {
		//hide cats
		this.origCats=$("events-cat").clone().getElements("option")
		this.trimCats()
		
		//attach events
		this.attach()
		
		//check for #hash
		if (document.location.hash!="") this.handleHash();
	},
	attach:function() {
		this.attachShare()
		$$("a.events-tab").addEvent('click',this.events.tabs.bind(this))
		$("btn-next-events").addEvent("click",this.events.init.bind(this))
		$("events-cat").addEvent("change",this.events.init.bind(this))
	},
	handleHash:function() {
		
		var url=new Hash(), lru=document.location.hash.replace("&eventStart=0","")+"&eventStart=0"
		lru.split(/[#|&]/).each(function(item,index) {
			if (item.contains("=")) {//should beef up this check
				url.set(item.split("=").shift(),item.split("=").pop())
			}
		})
		$$("a.events-tab.on").removeClass("on")
		$$("a.events-tab")[url.get('tab')-1].addClass("on")
		$("btn-next-events").set("href","?"+url.toQueryString())
			.fireEvent("click",[{stop:function(){},target:$("btn-next-events")},true])
		//if (!url.get("eventStart")) 
	},
	origCats:[],
	changing:false,
	trimCats:function(list){
		this.changing=true;
		list=list||$("smr-events-list")
		var si=$("events-cat").get('value')||"all"
		$("events-cat").empty()
		list.get("class").split(",").each(function(item,index) {
			$("events-cat").grab(this.origCats[item].clone())
		},this)
		
		$$("#events-cat>option[value='"+si+"']").set("selected","selected")
		this.changing=false
	},
	events:{
		request:null,
		tabs:function(event) {
			event.stop()
			$$("a.on.events-tab").removeClass("on")
			$("btn-next-events").set("href",$(event.target).addClass("on").get("href")).fireEvent("click",[event,true])
		},
		coolRotator:function(event) {
			$("rotator").setStyles({top:event.page.y,left:event.page.x,display:"block"})
		},
		init:function(event,fresh) {
			if (this.changing) return
			event.stop()
			var elm=$(event.target.form)||$(event.target)
			
			//if its the form, then add an href...small hack :(
			if (elm==$("events-cat-form") && !elm.getProperty("href")) fresh=true,elm.set("href",elm.get("action"))
			else if (elm==$("events-cat-form")) fresh=true
			
			//get params from href
			var url=new Hash()
			elm.getProperty("href").split(/[?|&]/).each(function(item,index) {
				if (item.contains("=")) {//should beef up this check
					url.set(item.split("=").shift(),item.split("=").pop())
				}
			})	
			url.extend({"category":$("events-cat").get('value')})//whoo, 2 sources of data :(	
			document.addEvent("mousemove",this.events.coolRotator)
			
			this.events.request=new Request.HTML({
				url:"/vegas/features/summer/events-inc.jsp",
				method:"get",
				onComplete:function(rt) {
					rt=rt[1]||rt[0]//sometimes a <style> gets sent making the ul rt[1], else it's rt[0]
					//filter out categories)
					this.trimCats(rt)
					//hide share links, if they're still open
					$$(".smr-events-share").fireEvent("mouseout")
					
					//remove cool rotator
					document.removeEvent("mousemove",this.events.coolRotator)
					$("rotator").setStyles({display:"none"})
				
					//if fresh=true, replace ul#smr-events-list if not, append LI's-->also, set opacity to 0 so we can make them fade in
					if (fresh)
						rt.replaces($("smr-events-list")).getElements("li").addClass("opacity-stuff").setStyle("opacity",0)
					else
						rt.getElements("li").addClass("opacity-stuff").setStyle("opacity",0).inject($("smr-events-list"))
						
					//fade in
					$$("li.opacity-stuff").each(function(item) {
						new Fx.Morph(item,{duration:750}).start({
							"opacity":[0,1]
						}).chain(function() {
							this.element.removeClass("opacity-stuff")
						})
					})
					
					//update url
					window.location.replace("#"+url.toQueryString());
					url.erase("eventStart");
					$("btn-next-events").setProperty("href","?"+url.set("index",parseInt(url.get("index"))+1).toQueryString());
					$("events-cat-form").setProperty("href","?"+url.set("index",1).toQueryString());
					
					//reattach new share links
					this.attachShare(true)
					
					//check if this is the last set of results
					if (this.events.request && this.events.request.getHeader("X-events-full")=="true") {
						//hide button
						new Fx.Morph($("btn-next-events")).start({
							"opacity":[0]
						}).chain(function() {
							this.element.setStyles({display:"none",opacity:1})
						})
					}else {
						//make sure button is visible
						$("btn-next-events").setStyles({display:"block"})
						new Fx.Morph($("btn-next-events")).start({
							"opacity":[1]
						})
					}
				}.bind(this)
			}).get(url)
		}
	},
	attachShare:function(removeEvents) {
		$$(".smr-events-share").each(function(item) {
			SHARETHIS.addEntry({
					title:item.getProperty("title"),
					url:item.getProperty("href")
				},{
					button:false
			}).attachButton(item)
			item.removeEvents().addEvent("click",function(event) {event.stop()})
		})
		
		/***old functions for addthis-->leaving in case we switch back***
		if (removeEvents) $$(".smr-events-share").removeEvents()
		$$(".smr-events-share").addEvents({
		"mouseover":function() {
			return addthis_open(this, '',this.get("href"), this.get("title"))
		},
		"click":function(event) {
			if (Browser.Engine.trident4) var scrll=document.documentElement.scrollTop
			var rtn=addthis_sendto()
			if (Browser.Engine.trident4) {
				window.scrollTo(0,scrll)
				$("at16pcc").setStyles({"top":scrll})
			}
			return rtn
		},
		"mouseout":addthis_close
		})
		*/
	}
}


//end of summer events stuff
window.addEvent("domready",function() {
										
	(function(){
		if ($('tab-instruction')) $('tab-instruction').fade('out');
	}).delay(5000);
		
		$$(".dive-deeper").addEvent("click",function() {
			var item=this.getParent(".item")
			var oldItem=$$(".itemOn").removeClass("itemOn")
			
			item.erase("style").addClass('itemOn')
				.getElement(".dive-deeper-content").clone(true,true)
					.replaces($("smr-dive-deeper").getElement(".dive-deeper-content")).addClass("dive-deeper-content");//specifically add class because IE8 doesn't copy class w/clone method...
			
			addvegasFaves()
			
			
			//set class, so we can calc height with dispaly:block
			$("smr-dive-deeper").addClass("on")
			
			//calculate dive deeper top
			var top=item.getCoordinates().top,obj;
			top-=(Browser.Engine.trident?18:150)
			
			//make sure it doesn't go longer than the page
			if ($("smr-dive-deeper").getSize().y+top>$("smr-content").getSize().y+$("smr-content").getCoordinates().top) obj={"top":$("smr-content").getSize().y-160}
			else obj={"top":top}
			
			new Fx.Morph($("smr-dive-deeper")).start(obj).chain(function () {initSifr()})
			
			//make a "multiplier" so you can start the background closer to 0 if the user didn't jump that far...better visual effect
			new Fx.Morph(item).start({
				"background-position":[[-400,0],[0,0]]
			})
			$$("div.item.itemOn .x").addEvent("click",function(event){document.fireEvent("click",event)})
	
		})
		
		document.addEvent("click",function(event) {
			var element=$(event.target)
			//doesn't work if element IS parent #fixme
			if ((!element.getParent("#smr-dive-deeper") && !element.getParent(".itemOn")) || element.hasClass("x")) {
				$$(".itemOn").removeClass("itemOn")
				if ($("smr-dive-deeper")) $("smr-dive-deeper").removeClass('on')
			}
		})
		
		$$("#smr-pool-strip>img.img").addEvent('click',function() {
			var big=this.getParent("#smr-pool-glry")
			var src=this.get("src").split("pools-thumbs/").join("pools-thumbs/big_")
			$$("#smr-pool-strip>img.selected").removeClass("selected")
			this.addClass('selected')
			new Fx.Morph(big,{duration:0}).start({
				//"background-position":[[-600,0]]
			}).chain(function() {
				big.setStyle("background-image","url("+src+")")
				new Fx.Morph(big,{duration:0}).start({
					"background-position":[[0,0],[0,0]]
				})
			})
		})
		$$("#poolDirectoryId").addEvent("change",function() {
			this.form.submit()
		})		
		
	//stole this code from Music-->login in to my vegas
	var modal = new Modal();
	
	function addvegasFaves() {
	$$("a.vegas-favorites").addEvent("click",function(event) {
		var e=event
		event.stop();
		//console.log("HERE")
		var target = $(event.target);
		if(!isLoggedIn){
			// user is not logged in yet so do it
			new Request({
				url:'/vegas/features/summer/login.jsp',
				method: 'get',
				onComplete: function(text) {
					showLogin(text,target,e)
				}
			}).send();
		}else{
			var form = target.getParent('#login-form-er');
			form.set('send', {
				url: "/vegas/myvegas-user-profile", 
				method: 'post',
				onComplete: function(response){
					var element = new Element('a',{
						"class":"vegas-favorites-saved",
						"href":"/vegas/my-vegas/index.jsp",
						"html":"Saved to My Vegas Favorites"
					})
					var id=target.get("id")
					element.clone().replaces(target)
					if ($(id)) element.clone().replaces($(id))
				}
			});
			form.send();
		}
	});
	}
	addvegasFaves()
	function showLogin(text,target,event){
		// test response for login window
		if(text.contains('login-form-window')){
			// strip the html we need from the response
			var responseText = text.split('<body>')[1].split('</body>')[0];
			var responseElement = new Element('div',{html:responseText});
			var form = responseElement.getElement('form');
			if(form != null){
				form.addEvent('submit', function(e){
					e.stop();
					this.set('send', {
						url: "/vegas/myvegas-user-profile", 
						method: 'post',
						onComplete: function(text) {
							showLogin(text,target,event)
						}
					});
					this.send();					
				});
			}
			modal.show(responseElement);
		}
		// if the response does not contain the login form login must have been sucessfull
		else{
			// refresh the page because if we don't causes weird issues --> (new) try to add favorite first
			if (target) {
				isLoggedIn=true;
				modal.hide()
				new Request({
					url:"/vegas/myvegas-user-profile",
					method:"post",
					onComplete:function() {
						window.location.replace("")
					}
				}).send(target.getParent("form").toQueryString())
			}
		}
		
	}
})

window.addEvent('load', function(){
	// get height of the pool description copy and adjust the height its wrapper accordingly
	if ($('pool-desc')) {
		var desc_height = $('pool-desc').getCoordinates().height;
		$('dive-deeper').setStyle('height', desc_height+60);
	}
});

// SIFR
var FuturaL = {
  src: '/swf/FuturaLight.swf'
};
sIFR.activate(FuturaL);
function initSifr() {
sIFR.replace(FuturaL, {
  selector: 'h2#pool-title',
  wmode: 'transparent',
  css: [
      '.sIFR-root { font-size:35px; color: #676b6c; text-transform: uppercase; }'
  ],
  preventWrap: false,
  fitExactly: true,
  tuneHeight: -10
});

sIFR.replace(FuturaL, {
  selector: '.sifr',
  wmode: 'transparent',
  css: [
      '.sIFR-root { font-size:14px; color: #676b6c; text-transform: uppercase; }'
  ],
  preventWrap: false,
  fitExactly: true,
  tuneHeight: -5
});
}
initSifr()