// light and dark versions of images

var newIconDark = 'http://johndoe.on-web.fr/lecteur-video/thud_icon_new_dark.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:'http://johndoe.on-web.fr/lecteur-video/tourbi.gif'}),
			Builder.node('a', { id:'popup-itunes' }, [
				Builder.node('img', { src:'http://johndoe.on-web.fr/lecteur-video/fond1.png'})
			]),
			Builder.node('img', { id:'popup-close', src:'http://johndoe.on-web.fr/lecteur-video/fermer.png'})			
		]);
		document.body.appendChild(this.overlayElement);
		document.body.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();
		if($('close_hud')) $('close_hud').addClassName('grayed');
		if($('staf_close')) $('staf_close').addClassName('grayed');
	},
		
	
	showOverlay: function() {
		this.overlayElement.setStyle({ height: getPageDimensions().height +'px' });
		this.overlayElement.show();

	},
	
	itunesLink: function(link) {
		if(link){
			$('popup-itunes').style.display = 'block';
			$('popup-itunes').href=link;
		}
	},
	

	
	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-itunes').down('img').setStyle({
			height:'0px',
			width:'0px'
		});
		this.overlayPopup.show();
		new Effect.Transform([
			{ '#popup' : 
				'height:'+(this.movieHeight+($('popup-itunes').href ? 69 : 60))+'px;' +
				'width:'+(this.movieWidth+100)+'px;' +
				'left:'+left+'px;' +
				'top:'+top+'px;' + 
				'opacity:1' },
			{ '#qt-display' :
				'height:'+this.movieHeight +'px;' +
				'width:'+this.movieWidth +'px;' +
				'top:30px;' +
				'left:50px' },
			{ '#qt-spinny' :
				'height:30px;' +
				'width:60px;' +
				'top:'+(this.movieHeight/2) +'px;' +
				'left:'+(this.movieWidth/2) +'px;'},
			{ '#popup-itunes img' :
				'height:0px;' +
				'width:0px;' }
		], { duration: .6 , afterFinish:this.afterPop.bind(this) }).play();			
	},
	
	afterPop: function() {
		$('popup-close').addClassName('active');
		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() {
				this.track(this.button.href, 'V@S');
				this.qtController.monitorMovie();
			}.bind(this),
			onMovieFinished: function() {
				this.track(this.button.href, 'V@E');
			}.bind(this)
		});		
		movie = null;
		
	},
		
	afterClose: function() {
		this.overlayPopup.hide();
		if($('close_hud')) $('close_hud').removeClassName('grayed');
		if($('staf_close')) $('staf_close').removeClassName('grayed');
		$('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() {
		$('popup-close').removeClassName('active');
		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-itunes img' :
				'height:0px;' +
				'width:0px;' }
		], { duration: .4 , afterFinish:this.afterClose.bind(this) }).play();
	},
	
	track: function(url, state) {
		movieName = AC.Tracking.pageName() + ' - ' + this.button.down('img').alt;
		if (state == 'V@E') {
			AC.Tracking.trackClick({
				prop13: state + ': ' + movieName
			}, this, 'o', state + ': ' + movieName);
		} else {
			if (state == 'HD') {
				state='V@S';
			}
		} 
	}
};

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];


			}

			// 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);

	
	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({ backgroundImage:'url(/trailers/images/hud_button_over_square.png)'}) : button.setStyle({ background:'url(/trailers/images/hud_button_over.png)'});
		});
		Event.observe(button, 'mouseout', function() {
			AC.Detector.isIE() || safari2 ? button.setStyle({ backgroundImage:'url(/trailers/images/hud_button_square.png)'}) : button.setStyle({ background:'url(/trailers/images/hud_button.png)'});
		});
		Event.observe(button, 'click', function(e) {
			Event.stop(e);
			AC.Detector.isIE() || safari2 ? button.setStyle({ backgroundImage:'url(/trailers/images/hud_button_square.png)'}) : button.setStyle({ background:'url(/trailers/images/hud_button.png)'});
			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;
			}
		});
	}
	
	
})
