// light and dark versions of images
var newIconLight = '/images/hud_icon_new_light.png';
var newIconDark = '/images/hud_icon_new_dark.png';
var hdIconDark = '/images/hud_icon_hd_dark.png';
var hdIconLight = '/images/hud_icon_hd_light.png';
var closeHudDark = '/images/hud_close_dark.png';
var closeHudLight = '/images/hud_close_light.png';
 
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:'/images/qt_spinny.gif'}),
			Builder.node('a', { id:'popup-itunes' }, [
				Builder.node('img', { src:'/images/popup_itunes_light.png'})
			]),
			Builder.node('img', { id:'popup-close', src:'/images/popup_close_light.png'})
		]);
		$$('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);
		this.movieWidth = parseInt(button.href.toQueryParams().width);
		this.clickX = Position.cumulativeOffset(button)[0] + (button.getWidth()/2);
		this.clickY = Position.cumulativeOffset(button)[1] + (button.getHeight()/2);
		this.showPopup();
	},
		
	showOverlay: function() {
		this.overlayElement.setStyle({ height: getPageDimensions().height +'px' });
		this.overlayElement.show();
	},
	
	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);
    var top = 110;
		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.monitorMovie();
		movie = new SWFObject('/flash/player.swf','ply',this.movieWidth,this.movieHeight,'9','#');
    movie.addParam('allowfullscreen','true');
    movie.addParam('allowscriptaccess','true');
    movie.addParam('wmode','opaque');
    movie.addParam('flashvars','file='+this.button.href.split('?')[0]+'&skin=/flash/overlay.swf&frontcolor=ffffff&lightcolor=6ba9ce&controlbar=over&stretching=uniform&autostart=true&volume=100');
    movie.write(this.qtPanel);
    $('qt-spinny').hide();
    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('');
		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 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 = 'trailers'//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) +')'}) 
	})
	
		$$('.hud').each(function(hud) {
			var swapper = new TrailerSwap(hud);
			var id = 0;
			swapper.swapContent(id);
		});
	
	TrailerOverlay = new Overlay();
	$$('.trailer-content a.trailer').each(function(button) {
		Event.observe(button, 'click', function(e) {
			Event.stop(e);
      // AC.Detector.isIE() || safari2 ? button.setStyle({ backgroundImage:'url(/images/hud_button_square.png)'}) : button.setStyle({ background:'url(/trailers/images/hud_button.png)'});
			TrailerOverlay.onClick(button);
		});
	});
	
	
})