// light and dark versions of images
var newIconLight = '';
var newIconDark = '';
var hdIconDark = '';
var hdIconLight = '';
var closeHudDark = '';
var closeHudLight = '';

var Overlay = Class.create();
Overlay.prototype = {
	overlayElement: null,
	overlayPopup: null,
	clickX: null,
	clickY: null,
	movieHeight: null,
	movieWidth: null,
	button: null,
	qtPanel: null,
	qtController: null,
	
	initialize: function() {
		this.overlayElement = Builder.node('div', { id:'overlay'});
		this.overlayPopup = Builder.node('div', { id:'popup' }, [
			Builder.node('div', { id:'qt-display'}), 
			Builder.node('img', { id:'qt-spinny', src:'/trailers/images/qt_spinny.gif'}),
			Builder.node('a', { id:'popup-itunes' }, [
				Builder.node('img', { })
			]),
			Builder.node('img', { id:'popup-close', src:'/trailers/images/popup_close_light.gif'})
			
		]);
		$$('body').first().appendChild(this.overlayElement);
		$$('body').first().appendChild(this.overlayPopup);
		Element.hide(this.overlayElement);
		Element.hide(this.overlayPopup);
	},
	
	onClick: function(button) {
		this.button = button;
		this.movieHeight = parseInt(button.href.toQueryParams().height)+16;
		this.movieWidth = parseInt(button.href.toQueryParams().width);
		//this.size = button.className;
		this.clickX = Position.cumulativeOffset(button)[0] + (button.getWidth()/2);
		this.clickY = Position.cumulativeOffset(button)[1] + (button.getHeight()/2);
		button.hasClassName('hd') ? this.showHD() : button.hasClassName('mobile') ? this.downloadMobile() : this.showPopup();
	},
		
	
	showOverlay: function() {
		this.overlayElement.setStyle({ height: getPageDimensions().height +'px' });
		this.overlayElement.show();
	},
	
	downloadMobile: function() {
		alert('User downloads the movie in a .zip file');
	},
	
	itunesLink: function(link) {
		if(link){
			$('popup-itunes').style.display = 'block';
			$('popup-itunes').href=link;
		}
	},
	
	showHD: function() {
		var qt = AC.Quicktime.packageMovie('movie', '/trailers/images/qtbutton.mov', {
			href: this.button.href,
			autohref: true,
			target: "quicktimeplayer",
			width: 1,
			height: 1,
			autoplay: false,
			controller: false,
			cache: true
		});
		this.track(this.button.href, 'HD');
		$('content').appendChild(new Element('div', { 'id':'hd-qt'}))
		$('hd-qt').appendChild(qt);
	},
	
	hideOverlay: function() {
		this.overlayElement.hide();
	},
	
	showPopup: function() {
		var left = (windowSize().width/2) - ((this.movieWidth+36)/2);
		var top = ((windowSize().height/2) + windowSize().y) - ((this.movieHeight+200)/2);
		this.showOverlay();
		this.overlayPopup.setStyle({
			height:'0px',
			width:'0px',
			left: (this.clickX) + 'px',
			top: (this.clickY) + 'px',
			opacity:'0'
		});
		$('qt-display').setStyle({
			height:'0px',
			width:'0px',
			left:'0px',
			top:'0px'
		});	
		$('qt-spinny').setStyle({
			height:'0px',
			width:'0px',
			left:'0px',
			top:'0px'
		});		
		$('popup-close').setStyle({
			height:'0px',
			width:'0px',
			right:'0px',
			bottom:'0'
		});
		$('popup-itunes').down('img').setStyle({
			height:'0px',
			width:'0px'
		});
		this.overlayPopup.show();
		new Effect.Transform([
			{ '#popup' : 
				'height:'+(this.movieHeight+69)+'px;' +
				'width:'+(this.movieWidth+36)+'px;' +
				'left:'+left+'px;' +
				'top:'+top+'px;' + 
				'opacity:1' },
			{ '#qt-display' :
				'height:'+this.movieHeight +'px;' +
				'width:'+this.movieWidth +'px;' +
				'top:18px;' +
				'left:18px' },
			{ '#qt-spinny' :
				'height:30px;' +
				'width:30px;' +
				'top:'+(this.movieHeight/2) +'px;' +
				'left:'+(this.movieWidth/2) +'px;'},
			{ '#popup-close' :
				'height:28px;' +
				'width:60px;' +
				'right:18px;' +
				'bottom:10px' },
			{ '#popup-itunes img' :
				'height:28px;' +
				'width:158px;' }
		], { duration: .6 , afterFinish:this.afterPop.bind(this) }).play();
		
		
	},
	
	afterPop: function() {
		this.qtPanel = $('qt-display');		
		this.addClickEvent();
		
		if(this.qtController) {
			if(this.qtController.Playing) this.qtController.Stop();
			this.qtController.detachFromMovie();
			this.qtController = false;
			this.qtPanel.update('');
		}	
		
		var movie = AC.Quicktime.packageMovie('trailerMovie', this.button.href, {
			width: this.movieWidth,
			height: this.movieHeight,
			controller: true,
			showlogo: false,
			cache: true,
			bgcolor: '#000000',
			autoplay: true
		});
		$('qt-spinny').hide();
		this.qtPanel.appendChild(movie);
		this.qtController = new AC.QuicktimeController();
		this.qtController.attachToMovie(movie, {
			onMoviePlayable: function() {
				
			}.bind(this),
			onMovieFinished: function() {
				
			}.bind(this)
		});
		this.qtController.monitorMovie();
		movie = null;
		
	},
		
	afterClose: function() {
		this.overlayPopup.hide();
		$('qt-spinny').show();
		this.hideOverlay();
	},
	
	addClickEvent: function() {
		[$('overlay'),$('popup-close')].each(function(el) {
			Event.observe(el, 'click', function() {
				this.hidePopup();
			}.bind(this));
			
		}.bind(this))
	},
	
	hidePopup: function() {
		if(this.qtController) {
			if(this.qtController.isPlaying) this.qtController.Stop();			
			this.qtController.detachFromMovie();
			this.qtController = false;
			this.qtPanel.update('');
			window.playmusic();
		}
		new Effect.Transform([
			{ '#popup' : 
				'height:0px;' +
				'width:0px;' +
				'left:'+this.clickX+'px;' +
				'top:'+this.clickY+'px;' + 
				'opacity:0' },
			{ '#qt-display' :
				'height:0px;' +
				'width:0px;' +
				'left:0px;' +
				'top:0px'},
			{ '#qt-spinny' :
				'height:0px;' +
				'width:0px;' +
				'left:0px;' +
				'top:0px'},
			{ '#popup-close' :
				'height:0px;' +
				'width:0px;' +
				'right:0px;' +
				'bottom:0px' },
			{ '#popup-itunes img' :
				'height:0px;' +
				'width:0px;' }
		], { duration: .4 , afterFinish:this.afterClose.bind(this) }).play();
	}
};

TrailerSwap = Class.create();
Object.extend(Object.extend(TrailerSwap.prototype, AC.ContentSwap.prototype), {
	cs1IsAnimating: false,
	cs2IsAnimating: false,
	lastSelectorIndex: false,
		
	initialize: function(hud) {
		this.pageTitle = document.title;
		this.eventStr = 'click';
		this.wrapper = hud.select('.trailer-content')[0];
		this.lastContent = null;
		// get lists of selectors and content in order
		this.selectorList = hud.select('.trailer-nav .navitem');
		this.contentList = hud.select('.section');
		
		for (var i=0; i<this.contentList.length; i++) {
			this.contentList[i].style.display = 'none';
		}
		
		this.setMouseover();
	},

	swapContent: function(selectorIndex) {
		var selector = this.selectorList[selectorIndex];
		var content = this.contentList[selectorIndex];
		
		// if we aren't already animating
		if (this.cs1IsAnimating == false && this.cs2IsAnimating == false) {

			// set the first anim flag
			this.cs1IsAnimating = true;
			this.cs2IsAnimating = true;
			
			// set the 'on' class
			if(selector) { 
				document.title = this.pageTitle + ' - ' + selector.down('.text').innerHTML;
				if(!selector.hasClassName('active')) selector.addClassName('active');
				if(selector.hasClassName('hd')) selector.down('.text').setStyle({ backgroundImage:'url('+(hudArrowContrast == "dark" ? hdIconLight : hdIconDark) +')'}) 
				
				if(selector.down('.new')) selector.down('.new').src = hudArrowContrast == 'dark' ? newIconLight : newIconDark;
				if(selector.previous()) selector.previous().addClassName('norule');
			}
			

			// if this is the first one
			if (!this.lastSelectorIndex && typeof(this.lastSelectorIndex) == 'boolean') {
				//this.wrapper.setStyle({ minHeight:'135px'});
				if(!AC.Detector.isiPhone()) {					
					this.firstFade(content);
				} else {
					content.style.display = 'block';
					
					this.resetFlag('cs1IsAnimating');
					this.resetFlag('cs2IsAnimating');
				}

			} else if (selectorIndex != this.lastSelectorIndex) {
				// set some more temporary vars
				var lastSelector = this.selectorList[this.lastSelectorIndex];
				this.lastContent = this.contentList[this.lastSelectorIndex];

				// remove the 'on' class
				if (lastSelector.hasClassName('active')) lastSelector.removeClassName('active');
				if(lastSelector.hasClassName('hd')) lastSelector.down('.text').setStyle({ backgroundImage:'url('+(hudContrast == "dark" ? hdIconLight : hdIconDark) +')'}) 
				if(lastSelector.down('.new')) lastSelector.down('.new').src = hudContrast == 'dark' ? newIconLight : newIconDark;
				if (Element.hasClassName(lastSelector.previous(), 'norule')) Element.removeClassName(lastSelector.previous(), 'norule');
				
				// swap
				if(!AC.Detector.isiPhone()) {
					new Effect.Fade(this.lastContent, { duration:.2, queue:{position:'end', scope:'cs1'},
						beforeStart:function() {
							
						},
						afterFinish:this.afterFade.bind(this, content)
					});
				} else {
					this.lastContent.style.display = 'none';
					content.style.display = 'block';
					
					this.resetFlag('cs1IsAnimating');
					this.resetFlag('cs2IsAnimating');
				}
			} else {
				this.resetFlag('cs1IsAnimating');
				this.resetFlag('cs2IsAnimating');
			}

			// set the last content index now that we're done doing everything
			this.lastSelectorIndex = selectorIndex;
		}
	},
	
	firstFade: function(content) {
		this.resetFlag('cs1IsAnimating');
		new Effect.Appear(content, { duration:.3, queue:{position:'end', scope:'cs2'},
			afterFinish:this.afterAppear.bind(this, content)
		});
	},
	
	afterFade: function(content) {
		this.resetFlag('cs1IsAnimating');
		new Effect.Appear(content, { duration:.2, queue:{position:'end', scope:'cs2'},
			//beforeStart:this.fixHeight.bind(this, content),
			afterFinish:this.afterAppear.bind(this, content)
		});
	},
	
	fixHeight: function(content) {
		if(this.lastContent) {
			var difference = this.lastContent.getHeight() - content.getHeight();
			this.wrapper.morph({
				minHeight:this.lastContent.getHeight() - difference + 'px'
			}, { duration:.2, queue:{position:'front', scope:'cs2'} });
		} else {
			this.wrapper.morph({ 
				minHeight:content.getHeight() + 'px'
			}, { duration:.2, queue:{position:'front', scope:'cs2'} });
		}
		
	},
	
	afterAppear: function(content) {
		content.style.position = 'relative';
		content.style.opacity = '';
		this.resetFlag('cs2IsAnimating');
	},

	resetFlag: function(flagName) {
		if(flagName == 'cs1IsAnimating') this.cs1IsAnimating = false;
		if(flagName == 'cs2IsAnimating') this.cs2IsAnimating = false;
	},
	
	selectedTrailer: function() {
		return this.selectedTrailer;
	}
});

function SetNewBugs() {
	var today = new Date();
	var img = new Element('img', {
		src:hudContrast == 'dark' ? newIconLight : newIconDark,
		'class':'new',
		width:165,
		height:20,
		border:0
	});
	$$('.trailer-nav li').each(function(li) {
		var classes = li.classNames();
		classes.each(function(c) {
			if(parseInt(c)) {
				var y = c.substring(0,4);
				var m = c.substring(4,6);
			 	var d = c.substring(6,8);
				var postDate = new Date(y,(parseInt(m, 10)-1),d);
				var dif = today - postDate;
				dif = Math.ceil(dif/1000/60/60/24)-1;
				if(dif < 7) li.appendChild(img.cloneNode(true));
			}
		});
	});
};


function getPageDimensions() {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { 
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { 
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	pageDimensions = { height:pageHeight };
	return pageDimensions;	
};

function windowSize() {
	var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
	var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
	var x = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
	var y = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);

	if(AC.Detector.isiPhone()) {
		width = parseInt(980);
		height = parseInt(1212);
	}
	return {'width':width, 'height':height, 'x':x, 'y':y}
};

function preloadCssImages() {
	var styles = '';
	$A(document.styleSheets).each(function(sheet, i) {
		if(i != 0) {
			if(!AC.Detector.isIE()) {
				$A(sheet.cssRules).each(function(rule, i) {
					styles+=rule.cssText
				})			
			} else {
				styles+=sheet.cssText;
			}					
		}
	});
	var section = document.location.toString().match(/http:\/\/[^\/]*\/([^\/]*)/);
	if (section.length>0) section = section[1];
	var search = new RegExp('\/'+section+'\/([^\)]*)', 'g');
	var match = styles.match(search);
	var image = new Image();
	/* match.each(function(match) {
		image.src = match;
	}); */
};

Event.onDOMReady(function() {
	$('main').addClassName('hasjs');
	var safari2 = false;
	if(AC.Detector.isWebKit()) safari2 = AC.Detector.getAgent().match(/safari\/(\d*)\./)[1] < 500;
	
	// if not safari 2, preload all the css images
	if(!safari2 && document.images) setTimeout("preloadCssImages()", 10);
	
	// set HD, NEW and Close images based on light or dark contrasts specified in html 
	$$('.close-hud').each(function(close) {
		close.setStyle({ backgroundImage:'url('+(hudContrast == "dark" ? closeHudLight : closeHudDark) +')'}) 
	});	
	$$('.navitem.hd').each(function(navitem) {
		navitem.down('.text').setStyle({ backgroundImage:'url('+(hudContrast == "dark" ? hdIconLight : hdIconDark) +')'}) 
	})
	SetNewBugs();
	
	if(!$('content').hasClassName('single')) {
		$$('.hud').each(function(hud) {
			var swapper = new TrailerSwap(hud);
			var id = 0;
			swapper.swapContent(id);
		});
	}
	
	TrailerOverlay = new Overlay();
	$$('.trailer-content li a').each(function(button) {
		Event.observe(button, 'mouseover', function() {
			AC.Detector.isIE() || safari2 ? button.setStyle({ }) : button.setStyle({ });
		});
		Event.observe(button, 'mouseout', function() {
			AC.Detector.isIE() || safari2 ? button.setStyle({ }) : button.setStyle({ });
		});
		Event.observe(button, 'click', function(e) {
			Event.stop(e);
			AC.Detector.isIE() || safari2 ? button.setStyle({ }) : button.setStyle({ });
			TrailerOverlay.onClick(button);
		});
	});
	// show message if no quicktime 
	if(!AC.Detector.isQTInstalled()) {
		$('noqt').show();
	}
	
	rentalsTag = 'WWW-NAUS-ITMS-TRAILERS-TOPRENTALS';
	moviesTag = 'WWW-NAUS-ITMS-TRAILERS-TOPMOVIES';
	
	if ($('promorentals') && typeof(rentalsTag) != 'undefined') {
		AC.Tracking.tagLinksWithin('promorentals', 'v0', rentalsTag, function(link) {
			if (link.href) {
				return !!(link.href.match(/itms:\/\/|phobos/));
			} else {
				return false;
			}
		});
	}

	if ($('promomovies') && typeof(moviesTag) != 'undefined') {
		AC.Tracking.tagLinksWithin('promomovies', 'v0', moviesTag, function(link) {
			if (link.href) {
				return !!(link.href.match(/itms:\/\/|phobos/));
			} else {
				return false;
			}
		});
	}
	
	
})
