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));
		}
		if (Browser.Engine.webkit) document.body.setStyle("overflow-x","hidden")
	},
	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');
					if (Browser.Engine.webkit) document.body.setStyle("overflow-x","auto")
					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();
		
		this.returnToState();
	},
	returnToState:function() {
		if (document.location.hash!="" && document.location.hash.indexOf("companyId")>-1) {
			this.showSpecialOffers("/vegas/play/sports/fantasy-football/details.jsp?"+document.location.hash.substring(1));
			document.location.hash="so-details-wrap"
		}
	},
	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();
				}
				
				//show Special Offers overlay
				else if(target.hasClass('view-details')){
					if (target.hasClass("no-overlay")) return;
					e.preventDefault();
					this.showSpecialOffers(target.get('href'));
					this.specialOffersUrl=target.get("href").split("?").pop()
				}
				
				//add hash tag so we can save state
				else if (target.get("id")=="so-details-overview") {
					document.location.hash=this.specialOffersUrl
				}
			}
			
			// Fantasy Football's special offers thumbnails
			if(target.get('tag') == 'img'){
				if(target.hasClass('view-details')){
					e.preventDefault();
					this.showSpecialOffers(target.getParent('a').get('href'));
					this.specialOffersUrl=target.getParent('a').get("href").split("?").pop()
				}
			}
		}.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);
	},
	showSpecialOffers: function(href) {
		var request = new Request.HTML({
			onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
				// show in modal window
				this.modal.show(responseElements['0']);
				
				// customized select box
				var customSelect = new SkinnedSelectBox($$('.skinnable'), $('dropdown-instruct'));
				customSelect.addEvent("switch",function(item) {
					
					//set vars for ellipsis setting
					var y=$("dropdown-instruct").getElement(".custom-select-current-value")
					
					//reduce length until width no longer needs to scroll
					while(y.getSize().x<y.getScrollSize().x) {
						y.set("html",y.get("html").substring(0,y.get("html").length-5)+"...")
					}					
					
					//add custom scroll bars for overflow
					if (item.getSize().y<item.getScrollSize().y) {//minus 26 from ScrollSize to get the height w/o white space or 42 in IE
					
					$("detailsscroll_holder").setStyles({visibility:"visible"})//make scrollbars visible if they're needed
					//$("detailsscroll").getElement("div.knob").setStyles({height:Math.round((item.getSize().y/item.getScrollSize().y)*300)})//make knob size relative to scrolling size of content
					var scrolls = new Slider($("detailsscroll"), $("detailsscroll").getElement("div.knob"),{
						mode:"vertical",
						steps:Math.max(item.getScrollSize().y-item.getSize().y,0),
						wheel:true,
						onChange:function(index) {
							item.scrollTo(0,index)
						},
						 onStart:function() {
							item.scrollTo(0,0)
						 }
					}).set(0);
					
					$("so-details-right").addEvents({mousewheel:function(event) {
						event.stop().preventDefault();
						if(event.wheel > 0) var stp=scrolls.step-5
						if(event.wheel < 0) var stp=scrolls.step+5
						scrolls.set(stp)
					}})
					}else $("detailsscroll_holder").setStyles({visibility:"hidden"})//hide scroller if we don't need it
				})

				// add sIFR 
				sIFR.replace({src:'/swf/play/sports/AstuteBlackSSI.swf'}, {
					selector: 'h1#so-details-propname', 
					wmode: 'transparent',
					css: [
					  '.sIFR-root { font-size: 20px; color: #000000; font-weight: normal; text-transform: uppercase; }'
					],					
					fitExactly: true,
					tuneHeight: -12,
					offsetTop: -6
				});
			
			//if (Browser.Engine.trident4) setTimeout(function() {$$("select").setStyle("visibility","hidden")},451)
			}.bind(this)
		});
		request.get(href);
	}
});