Object.extend(AC.OverlayPanel.prototype, {
	movie: null,
	prevMovie: null,
	initialize: function(contents, view, triggerClassName, options) {
		this.titlePanel = $('titlePanel');
		this.moviePanel = $('moviePanel');
		this.controllerPanel = $('controllerPanel');
		this.overlayId = "OverlayPanel";
		this.overlayShadowId = "OverlayPanelShadow";
		this.createOverlay();
		//this.setDefaults();

		AC.ViewMaster.Viewer.prototype.initialize.call(this,null,this.swapViewElement,"OverlayPanel",options);
		this.options.shouldAnimateContentChange = false;
	},
	triggerClicked: function(evt,element) {
 		// stop the default event
 		Event.stop(evt);
					
        if(this._isDisplaying) return;

		//Reset shadow image
		this.setOverlayShadowImageSrc(null);

		this._popPosition = null;
		this.currentSectionEvent = evt;
		this.superTriggerClicked(evt,element);
	},
	
	afterPop: function(item, i) {
		this.closeBtnContainer.style.display = "block";
		this.currentSection.content.style.visibility = "visible";
		this.setPoppedClass();
		//this.resetOverlay();
		if(this.currentSectionEvent.element().up('.video')) {
			this.setMovieNav();
			this.playMovie(this.currentSectionEvent.element().up('.video').movieUrl, this.currentSectionEvent.element().up('.video').movieId);
		}
 	},

	setMovieNav: function() {
		this.overlay.select('#gallerynav a').each(function(video) {
			var params = video.href.split('?');
			var movieUrl = params[0];
			var movieId = params[1];
			video.observe('click', function(evt) {
				Event.stop(evt);
				this.playMovie(movieUrl, movieId);
			}.bind(this))
		}.bind(this));
	},

	playMovie: function(url, id) {
		var target = $('overlay-'+id);
		var movieTitle = target.down('span').innerHTML;
		if(this.prevMovie) this.prevMovie.removeClassName('active');
		
		target.addClassName('active');
		this.prevMovie = target;
		if(this.movie) this.closeMovie();
		this.movieController = new AC.QuicktimeController();
		this.controllerPanel.innerHTML = '';
		this.controllerPanel.appendChild(this.movieController.render());
		
		this.movie = AC.Quicktime.packageMovie('movie', url, {
			width: 640,
			height: 400,
			autoplay: true,
			controller: false,
			cache: true,
			bgcolor: '#FFFFFF'
		});
		this.titlePanel.update(movieTitle);
		this.moviePanel.appendChild(this.movie);
		this.movieController.attachToMovie(this.movie, {
			onMoviePlayable: function() {
				this.movieController.monitorMovie(this.movie);
				this.track(url, movieTitle, 'V@S');
			}.bind(this),
			onMovieFinished: function() {
				this.track(url, movieTitle, 'V@E');
			}.bind(this)
		})
	},
	
	closeMovie: function() {
		if(this.movie) {
			this.movieController.Stop();
			this.movieController.detachFromMovie();
			this.controllerPanel.innerHTML = '';
			this.moviePanel.removeChild(this.movie);
			this.movie = null;
			this.moviePanel.innerHTML = ''
			this.titlePanel.innerHTML = ''
		}
	},
	
	close: function(evt) {
 		if (evt) Event.stop(evt);
		if(this.movie) this.closeMovie();
		var width = this.defaultWidth;
		var left = this.overlay.offsetLeft;
		var height = this.defaultHeight;
		var top = this.overlay.offsetTop;

		if (left>=0 && top>=0) { // if we are actually showing at the point of closure

			this.willClose(this);

			if (!AC.Detector.isiPhone()) {
				var percent = (100*this._width) / width;

				// do the craziness
				new Effect.Parallel([
					new Effect.MoveBy(this.overlay, this.top-this.padtop-top, this.left-this.padleft-left, { sync:true }), 
					new Effect.Scale(this.overlay, percent, { sync:true, scaleContent:false}),
					new Effect.Fade(this.overlay, { sync:true })
				],
				{ duration:0.3, afterFinish:this.afterClose.bind(this) });
			} else {
				this.afterClose();
			}

		}
	},
	
	track: function(url, title, state) {
		var movieName = 'Apple - Back to School - '+title;
		if (state == 'V@E') {
			AC.Tracking.trackClick({
				prop13: movieName +' - '+ state
			}, this, 'o', movieName +' - '+ state);
		} else {
			AC.Tracking.trackPage({
				pageName:movieName,
				prop4: url,
				prop6: movieName,
				prop13: movieName +' - '+ state
			});
		} 
	}
});



function TrackMacOrder() {
	// random order of macs, then save that so it remains in that order
	macs = [
		'<img src="http://images.apple.com/euro/aoc/images/whichmac_book20090610.jpg" width="129" height="128" alt="MacBook"><h3>MacBook</h3><h4>Con un procesador más veloz y más capacidad, el MacBook es mejor que nunca.</h4><a href="#aoc" class="OverlayPanel"><img class="button" src="http://images.apple.com/es/aoc/images/btn_buynow20080603.gif" width="71" height="15" alt="Comprar ahora" onclick="ftSpotActivityTrack(\ftBuyNowMacBook\)"></a>',
		'<img src="http://images.apple.com/es/aoc/images/whichmac_air20080603.jpg" width="129" height="128" alt="MacBook Air"><h3>MacBook Air</h3><h4>El MacBook Air sigue redefiniendo lo que es posible. Sigue siendo ultrafino y ultraportátil.</h4><a href="#aoc" class="OverlayPanel"><img class="button" src="http://images.apple.com/es/aoc/images/btn_buynow20080603.gif" width="71" height="15" alt="Comprar ahora" onclick="ftSpotActivityTrack(\ftBuyNowAir)"></a>',
		'<img src="http://images.apple.com/es/aoc/images/whichmac_pro20081013.jpg" width="129" height="128" alt="MacBook Pro"><h3>MacBook Pro</h3><h4>El nuevo MacBook Pro lleva la ingeniería de precisión y la tecnología avanzada a todo el mundo.</h4><a href="#aoc" class="OverlayPanel"><img class="button" src="http://images.apple.com/es/aoc/images/btn_buynow20080603.gif" width="71" height="15" alt="Comprar ahora" onclick="ftSpotActivityTrack(\ftBuyNowPro\)"></a>',
		'<img src="http://images.apple.com/es/aoc/images/whichmac_imac20080603.jpg" width="129" height="128" alt="iMac"><h3>iMac</h3><h4>El sobremesa todo en uno tan potente como atractivo, capaz de hacer todo lo que se te ocurra.</h4><a href="#aoc" class="OverlayPanel"><img class="button" src="http://images.apple.com/es/aoc/images/btn_buynow20080603.gif" width="71" height="15" alt="Comprar ahora" onclick="ftSpotActivityTrack(\ftBuyNowiMac\)"></a>'	
	]
	orders = [
		{ id:'MB-MBA-MBP-IMAC', order:[1,0,2,3] },
		{ id:'MBA-MB-MBP-IMAC', order:[0,1,2,3] },
		{ id:'MBP-MBA-MB-IMAC', order:[2,1,0,3] },
		{ id:'IMAC-MBA-MBP-MB', order:[3,1,2,0] }
	]
	cookieOrderSet = document.cookie.match ( '(^|;) ?bts_order=([^;]*)(;|$)' );
	if(cookieOrderSet) {
		orderIndex = $A(cookieOrderSet[2].split(','));
	} else {
		orderIndex = Math.floor(Math.random()*4);
		document.cookie = 'bts_order='+orderIndex+'; expires=12/31/2050; domain=apple.com';
	}
	return orders[orderIndex].id;
}
TrackMacOrder();

Event.onDOMReady(function() {
	// do some CSS magic for no javascript version
	Element.addClassName('main', 'hasjs');

	// display macs
	orders[orderIndex].order.each(function(index) {
		$('randomizeMacs').appendChild(new Element('li').update(macs[index]));
	});
	$('randomizeMacs').select('a').invoke('observe','click', function(evt) {
		var model = this.previous('h3').innerHTML;
		var order = orders[orderIndex].id;
		AC.Tracking.trackClick({
			prop2: model,
			prop3: order,
			prop6: null,
			channel: null
		});
	})
	
	
	$$('.video').each(function(video) {			
		var params = video.href.split('??');
		video.href = params[0];
		video.movieUrl = params[1];
		video.movieId = params[2];
	});
	
	/* swapper
	----------------------------- */
	// some DOM stuff
	var wrapper = $$('.swapcontainer')[0];
	var triggers = $$('#main .swapnav');
	var contents = $$('#main .swapcontent');

	// all the important stuff
	if (triggers.length>0 && contents.length>0) {
		var pagenav = new PageNav($$('#main .pagenav'), $$('#main #subnav li'), 'swapcontent');
		var swapper = new FadeSwap(wrapper, triggers, contents, 'click');
		var anchors = new AnchorFix(triggers, contents, swapper);
		
		// find the default
		var id = 0;
		if (document.location.hash) {
			var initial = document.location.hash;
			initial = initial.match(/#(.*)/)[1];
			var doesContentExist = anchors.doesContentExist(initial)
			if (doesContentExist) {
				id = doesContentExist.index;
			}
		}
		
		// swap to the default
		swapper.swapContent(null, id);
	}
	/* hero fader
	----------------------------- */
	if($$('#hero>img').length > 0) new AC.CrossfadeQueue($$('#hero>img'), 'hero');
	
	/* send to a friend
	----------------------------- */
	if($('sendtofriend')) $('sendtofriend').observe('click', function() {
		AC.Tracking.trackClick({
			pageName: 'Apple - Back to School - Send to a Friend',
			prop3: 'Apple - Back to School - Send to a Friend'
		});
	});
	if($('compare')) $('compare').observe('click', function() {
		AC.Tracking.trackClick({
			pageName: 'Apple - Back to School - Compare Macs',
			prop3: 'Apple - Back to School - Compare Mac'
		});
	});
	$$('#themechooser li.choice').each(function(theme, i) {
		Event.observe(theme, 'click', function(evt, i) {
			Share.theme = i;
			var color = theme.down('img').className;
			$w($('sharepreview').className).each(function(clas) {
				if(clas.indexOf('theme-') != -1) $('sharepreview').removeClassName(clas);
			});
			$('sharepreview').addClassName('theme-'+color);
			$$('#themechooser li').each(function(li) {
				if(li.hasClassName('active')) li.removeClassName('active');
			})
			theme.addClassName('active');
		}.bindAsEventListener(this, i));
	});
	Share.shareId = 106;
	Share.parameters = { 'sharePhpUrl': '/uk/aoc/scripts/share.php', 'theme':0, 'geo':'us' };
	Share.initOptions(arguments);
	Share.buildForm();
	Share.addValidation();
});
function signUpWindow() {
	window.open('/uk/aoc/includes/signup.html','sharer','toolbar=0,status=0,width=345,height=790')
	return false;
}
