var Slider = Class.create(AC.Slider, {
	scrollBy: parseInt(1),
	populate: function(items) {
		items.each(function(item) {
			var sliderItem = new AC.SliderItem(item);
			this.items.push(sliderItem);
		}.bind(this));
		this.render(8);
	},
	
	scrollToItem: function(index) {
		var page = null;

		var itemsPerPage = this.itemsPerPage*this.scrollBy;
		for (var i=1; i<=this.totalPages-this.scrollBy+1; i++) {
			
			// figure out the upper and lower bounds on this page
			var lowerBound = (i*this.itemsPerPage)-this.itemsPerPage;
			var upperBound = lowerBound+itemsPerPage-1;
			// check if it's visible on the current page so we don't scroll if we don't have to
			if (i==this.currentPage && index>=lowerBound && index<=upperBound) page = i;

			// if we don't have a page number, and we're between the bounds, set the page number
			if (!page && index>=lowerBound && index<=upperBound) page = i;
		}

		if (page!=this.currentPage) {
			this.scrolltoPageNumber(page);
		}
	}
});		

var AdsSwap = Class.create({
	defaultSlider: 'latest',
	movieSize: 'medium',
	newMovieSizes: { small:'320x180', medium:'480x272', large:'640x360', hd:'848x480' },
	oldMovieSizes: { small:'320x256', medium:'480x376', large:'640x496', hd:'848x496' },
	ads: { latest:[], y2006:[], y2007:[], y2008:[] },
	adQuery: null,
	nowPlaying: null,
	displayPanel: null,
	controllerPanel: null,
	pageTitle: document.title,
	
	initialize: function() {
		this.triggers = $$('.trigger');
		this.displayPanel = $('display');
		this.controllerPanel = $('controller');

		var adCollection = $$('#ads-nojs div');
		adCollection.each(function(ad, i) { this.sortAds(ad, i) }.bind(this));
		
		var deeplink = false;
		if(document.location.hash) {
			this.loadQuery(document.location.hash.match(/#(.*)/)[1]);
			deeplink = true;
		} 
		
		this.makeSlider(this.ads[this.defaultSlider], deeplink);
		this.setBrowserNavEvents();
		this.setSizeNavEvents();
		this.setupAd(this.adQuery ? this.adQuery : this.ads[this.defaultSlider][0]);
	},
		
	sortAds: function(ad, i) {
		ad.postDate = ($w(ad.className)[0])
		ad.url = ad.down('a').href;
		ad.title = ad.down('h3').innerHTML;
		ad.subtitle = ad.down('h4') ? ad.down('h4').innerHTML : null;
		// create urls to all movie sizes
		if(ad.url.substring(ad.url.length-11, ad.url.length-4) == '480x272') {
			ad.small = ad.url.replace('480x272',this.newMovieSizes.small);
			ad.medium = ad.url.replace('480x272',this.newMovieSizes.medium);
			ad.large = ad.url.replace('480x272',this.newMovieSizes.large);
			ad.hd = ad.url.replace('480x272',this.newMovieSizes.hd);
		} else {
			ad.small = ad.url.replace(ad.url.substring(ad.url.length-11, ad.url.length-4),this.oldMovieSizes.small);
			ad.medium = ad.url.replace(ad.url.substring(ad.url.length-11, ad.url.length-4),this.oldMovieSizes.medium);
			ad.large = ad.url.replace(ad.url.substring(ad.url.length-11, ad.url.length-4),this.oldMovieSizes.large);
			ad.hd = ad.url.replace(ad.url.substring(ad.url.length-11, ad.url.length-4),this.oldMovieSizes.hd);
		} 
			
		// sort all ads into appropriate array	
		var postyear = ad.postDate.substring(0,4);
		if(i < 8) this.ads.latest.push(ad);
		if(postyear == '2008') this.ads.y2008.push(ad);
		if(postyear == '2007') this.ads.y2007.push(ad);
		if(postyear == '2006') this.ads.y2006.push(ad);
	},

	makeSlider: function(active, deeplink) {
		var slider = new Slider('slider', active);
		this.setBrowserItemEvents(active);
		if(deeplink) {
			slider.scrollToItem(this.adQuery.position);
		} 
	},
	
	loadQuery: function(hash) {
		// search arrays for ad query
		var found = false;
		$H(this.ads).each(function(ad) {
			if(!found) {
				ad[1].each(function(elem, i) {
					if(elem.id == 'ad-'+hash) {
						found=true;
						this.defaultSlider = ad[0];
						this.adQuery = this.ads[this.defaultSlider][i];
						// array index for auto-sliding
						this.adQuery.position  = i;
					}
				}.bind(this))						
			}
		}.bind(this));
	},
	
	setBrowserNavEvents: function() {
		$(this.defaultSlider).addClassName('active');
		this.triggers.each(function(trigger, i) {
			trigger.observe('click', function() {
				trigger.addClassName('active');
				this.triggers.each(function(others, j) {
					if(i != j) this.triggers[j].removeClassName('active');
				}.bind(this))
				this.makeSlider(this.ads[trigger.id]);
				if($(this.nowPlaying.id)) $(this.nowPlaying.id).addClassName('active');
			}.bind(this))
		}.bind(this))
		
	},
	
	setSizeNavEvents: function() {
		$$('.movieoption').each(function(option) {
			option.observe('click', function(e) {
				Event.stop(e);
				var size = option.id.substring(7, option.id.length);
				this.movieSize = size;
				this.packageAd(option.href);
			}.bind(this));
		}.bind(this));
		
	},
	
	setBrowserItemEvents: function(active) {
		$$('#slider div').each(function(ad) {
			var adId = ad.id;
			ad.down('a').observe('click', function(e) {
				Event.stop(e);
				active.each(function(item) {
					if($(item.id).hasClassName('active')) $(item.id).removeClassName('active');
					if(item.id == adId) this.setupAd(item);
				}.bind(this));
			}.bind(this))
		}.bind(this));
	},
	
	setupAd: function(item) {
		document.title = this.pageTitle + ' - ' + item.title;
		// set size urls and events
		$('ad-title').update(item.title);
		$('option-small').href=item.small;
		$('option-medium').href=item.medium;
		$('option-large').href=item.large;
		$('option-hd').href=item.hd;
		
		// currently playing movie to keep active across sliders
		this.nowPlaying = item;
		if($(item.id)) $(item.id).addClassName('active');
		this.packageAd(item[this.movieSize]);
	},
	
	packageAd: function(url) {

		// set size as content class to change layout
		var contentClasses = $w($('content').className);
		if(contentClasses.length > 0) {
			contentClasses.each(function(className) {
				if(className == 'small' || className == 'medium' || className == 'large' || className == 'hd') $('content').removeClassName(className);
			});
		}
		$('content').addClassName(this.movieSize);

		//extract width x height form url (123)x(456).mov
		var dimensionMatch = url.match(/(\d{1,3})x(\d{1,3})\.mov/i);

		var movieWidth = parseInt(dimensionMatch[1], 10)
		var movieHeight = parseInt(dimensionMatch[2], 10)

		// subtract 16 from the height in old movie urls where the 
        // default controller was included in the dimensions
		if((movieHeight + "").match(/6$/)) {
		    movieHeight -= 16;
	    }

		if(this.movieController) {
			this.movieController.Stop();
			this.movieController.detachFromMovie();
		}
		var movie = AC.Quicktime.packageMovie('admovie', url, {
			width: movieWidth,
			height: movieHeight,
			controller: false,
			showlogo: true,
			autostart: true,
			cache: true
		});

		this.displayPanel.innerHTML = '';
		this.displayPanel.removeClassName('loading');
		this.controllerPanel.innerHTML = '';
		// set movie container dimensions
		this.displayPanel.setStyle({ height:movieHeight+'px' });
		this.displayPanel.setStyle({ width:movieWidth+'px' });
		this.displayPanel.appendChild(movie);
		if(AC.Detector.isQTInstalled()) {
			this.movieController = new AC.QuicktimeController();
			this.movieController.render(this.controllerPanel);
			this.movieController.attachToMovie(movie, {
				onMoviePlayable: function() {
					this.track('Start')
				}.bind(this),
				onMovieFinished: function() {
					this.track('End')
				}.bind(this)
			});
			this.movieController.monitorMovie();
        }
	},
	
	track: function(state) {
		if (state == 'Start') {
			this.order++;
		}

		if (state == 'Start') {
			AC.Tracking.trackPage({
				pageName: 'V@S: ' + AC.Tracking.pageName() + ' - '+this.nowPlaying.title + ' - '+this.movieSize,
				prop4: this.nowPlaying.url,
				prop6: this.nowPlaying.title,
				prop13: 'V@S: ' + AC.Tracking.pageName() + ' - '+this.nowPlaying.title + ' - '+this.movieSize
			});
		} else if (state == 'End') {
			AC.Tracking.trackClick({
				prop13: 'V@E: ' + AC.Tracking.pageName() + ' - '+this.nowPlaying.title + ' - '+this.movieSize
			}, this, 'o', 'V@E: ' + AC.Tracking.pageName() + ' - '+this.nowPlaying.title + ' - '+this.movieSize);
		}

	}
});
Event.observe(window, 'load', function() {
	if(AC.Detector.isiPhone()) {
		$('main').addClassName('iphone');
		$('ads-nojs').select('a').each(function(ad) {
			ad.href = ad.href.replace(ad.href.substr(ad.href.length-11, 7), 'r320-9cie')
		})
	} else {
		new AdsSwap();
	}	
});
