MagnifyEmbeddablePlayer = Class.create({
	initialize: function( config ) {		
		this.config = config.config ? config.config : {};
		
		this.type = config.type;
		this.toolRoot = config.toolRoot;
		this.componentRoot = config.componentRoot;
		this.panelContainer = config.panelContainer;
		this.registrationRequired = config.registrationRequired;
		this.isSSO = config.isSSO;
		this.reloadRequired = false;
		
		this.hidePlaylist = this.config.hide_playlist == 1 ? true : false;
		this.readMore = this.config.read_more == 1 ? true : false;
		this.leaveBehind = this.config.leave_behind == 1 ? true : false;
		this.widgetCID = this.config.cid;
		this.leaveBehindCounter = this.config.lb_counter ? this.config.lb_counter : 10;
		if ( this.leaveBehindCounter == 0 ) 
			this.leaveBehind = false;
			
		if ( this.type == 'ivp' ) 
			this.leaveBehindCounter = -1;
			
		this.continuousPlay = this.type == 'mvp' ? true : false;
		this.autoplay = this.config.init_autoplay == 1 ? true : false;
		this.syncAd = this.config.sync_ad == 1 ? true : false;
			
		this.defaultContentItem = config.contentItem;	
		this.currentContentItem = config.contentItem;	
		if ( this.currentContentItem )
			this.currentContentItem.autoplay = this.autoplay;
		this.defaultPlaylist = config.playlist;
		
		this.adSlots = config.adSlots;
		this.videoAds = config.videoAds;
		this.playlists = config.playlists;
		this.embedURL = config.embedURL;
		this.queryString = this.createQueryString();
		
		this.panels = new Hash();
		this.ads = new Hash();
		this.registeredPlaylists = new Hash();
		this.registeredContent = new Hash();		
		
		this.loggedIn = false;
		this.lastPanel = "";
		this.currentPanel = "";
		this.lastScrollDistance = 0;
		this.hostname = "http://" + location.hostname;
		
		if ( this.adSlots )
			this.registerAdSlots();
			
		if ( this.playlists )
			this.registerPlaylists();
			
		window.continuousPlay = this.continuousPlay;
			
		this.auth = new MagnifyEmbeddablePlayer.Auth( this, {} );
		
		this.registerListeners();
	},
	
	registerListeners: function() {
		var player = this;
		if ( window.addEventListener ) 
			window.addEventListener("load", function() { player.completeSetup(); }, false);
		else if ( window.attachEvent ) 
			window.attachEvent("onload", function() { player.completeSetup(); });
	},
	
	completeSetup: function() {
		if ( $('mvp_embed_code') ) {
			$('mvp_embed_code').value = '<iframe src="' + this.embedURL + '" width="' + this.config.width + '" height="' + this.config.height + '" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" allowtransparency="true"></iframe>';
		}
		
		if ( this.registrationRequired ) {
			this.requireLogin();
		}
	},
	
	createQueryString: function() {
		return $H( this.config ).toQueryString();
	},

/*---- Content Management ----*/	

	registerContent: function( config, callback ) {
		if ( !this.registeredContent.get(config.cid) )
			this.registeredContent.set( config.cid, new MagnifyEmbeddablePlayer.Content( this, config ) );
	},

/*---- Content Management ----*/	

	registerLeaveBehind: function(config) {
		if ( !this.leaveBehindPanel )
			this.leaveBehindPanel = new MagnifyEmbeddablePlayer.LeaveBehind( this, config );
	},
	
	showLeaveBehind: function() {
		try {
			this.leaveBehindPanel.show();
		} catch(e) {  console.log("error in showLeaveBehind: " + e.message); }
	},


/*---- Panel Management ----*/		
	
	showPanel: function( tab, panelKey, effect ) {
		if ( this.companionAd && this.companionAd.showing ) {
			this.companionAd.hideAd();
		}
		
		if ( panelKey == 'playlists' ) {
			this.showPlaylists();
			tab.removeClassName("magnify-widget-playlist-tab");
			tab.addClassName("magnify-widget-playlist-tab-on");
			
		} else {				
			var panel = this.panels.get(panelKey);
			if ( !panel ) {
				panel = new MagnifyEmbeddablePlayer.Panel( this, { tab: tab, container: this.panelContainer, id: panelKey, effect: effect } );
				this.panels.set(panelKey, panel);
			}
			panel.tab = tab;
			
			if ( this.currentPanel && panel.id == this.currentPanel.id ) {
				panel.hidePanel();
				return;
			}
		
			if ( this.currentPanel && this.currentPanel.id != 'playlists' ) {
				this.currentPanel.hidePanel();
			}
			
			panel.showPanel();
		}
	},
	
	showSubnav: function(id) {
		this.currentPanel.showSubnav(id);
	},
		
	destroyPanels: function() {
		var player = this;
		this.panels.values().each( function(panel, i) {
			Element.remove( panel.parentId );
			player.panels.unset(panel.id);
		});
		this.currentPanel = undefined
	},

	
/*---- Playlist Management ----*/

	registerPlaylists: function() {
		var player = this;
		this.playlists.each( function( playlist, i ) {
			player.registerPlaylist( playlist );
		});
	},
	
	registerPlaylist: function( playlist ) {
		if ( !this.registeredPlaylists.get(playlist.cid) ) {
			this.registeredPlaylists.set( playlist.cid, new MagnifyEmbeddablePlayer.Playlist( this, playlist ) );
		}
	},
		
	showPlaylists: function() {
		if ( !$('magnify_widget_playlist_container') ) {
			var navContainer = $('magnify_widget_playlist_nav_container');
			var container = document.createElement('div');
			container.id = 'magnify_widget_playlist_container';
			navContainer.insert(container);
 		}
 		
 		if ( this.currentPanel ) {
 			this.currentPanel.hidePanel();
 		}
 	},

	
/*---- Playlist Item Management ----*/

	registerPlaylistItem: function(playlistCID, playlistItem) {
		var playlist = this.registeredPlaylists.get( playlistCID );
		playlist.registerItem( playlistItem );
	},


/*---- Ad Management ----*/
	
	registerAdSlots: function() {
		var player = this;
		this.adSlots.each( function( adSlot, i ) {
			player.registerAdSlot(adSlot);
		});
	},
	
	registerAdSlot: function(adSlot) {
		this.ads.set( adSlot.id, new MagnifyEmbeddablePlayer.Ad( this, adSlot ) );
	},

	refreshAds: function() {
		var player = this;
		var adArray = ['magnify_widget_rect_frame', 'magnify_widget_bottom_leader_frame', 'magnify_widget_bottom_banner_frame', 'cb_medrect1_frame'];
		
		// if our frame has been destroyed by tremor
		if ( !$('magnify_widget_rect_frame') && $('adCompanionBanner') ) {
			$('adCompanionBanner').innerHTML = '<iframe id="magnify_widget_rect_frame" src="" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0" allowtransparency="true" width="300" height="250"></iframe>';
		}
		
		adArray.each( function(el) {
			if ( $(el) ) {
				$(el).src = player.toolRoot + 'ad.mason?loc=' + el + '&amp;content_item_cid=' + player.currentContentItem.cid + '&amp;autoplay=' + player.currentContentItem.autoplay + (player.queryString ? '&amp;' + player.queryString : '');
			}
		});
	},
	
	
/*---- Authentication Management ----*/

	checkAuth: function(callback) {
		var player = this;
		
		new Ajax.Request( this.toolRoot + 'get_login.minc', {
			method: 'get',
			onSuccess: function(transport) { 
				player.loggedIn = transport.responseText > 0;
				if ( player.loggedIn ) {
					player.registrationRequired = false;
				}
				if ( callback ) {
					callback();
				}
			}
		});	
	},

	requireLogin: function() {
		var player = this;
		this.checkAuth(function() {
			if ( !player.loggedIn ) {
				player.reloadRequired = true;
				if ( $('magnify_player_require_login') ) {
					$('magnify_player_require_login').show();
				}
				if ( $('magnify_player_container') ) {
					$('magnify_player_container').update();
				}
				player.auth.showLogin();
			}
		});
	},
	
	
/*---- Thumbnail Scroller ----*/

	registerScroller: function(config) {
		this.thumbnailScroller = new MagnifyEmbeddablePlayer.ThumbnailScroller( this, config );
	},
	

/*---- Embed Code ----*/	

	showEmbedCode: function(link, el) {
		if ( el.style.display == 'none' ) {
			Effect.Appear(el, {queue: { scope: 'embed_link'}} );
			link.innerHTML = "hide embed code";
		} else {	
			Effect.Fade(el, {queue: { scope: 'embed_link'}} );
			link.innerHTML = "embed this player";
		}
		return false;
	},


/*---- Email ----*/	
	
	sendEmail: function(url, form, target) {
		var player = this;
		new Ajax.Updater(target, this.toolRoot + url + (this.queryString ? '?' + this.queryString : ''), {
			method: 'post', 
			parameters: Form.serialize( form ), 
			evalScripts: true,
			onComplete: function() {
				player.currentPanel.insertCloseLink();
			}
		});
	},
	
	
/*---- Rating ----*/	
	
	swapRate: function(level, img_on, img_off) {
		for ( var i=1; i <= 5; i++ ) {
			$('mvp_rating_' + i).src = ( i <= level ? img_on : img_off );
		}
	},
	
	
/*---- Tagging ----*/
	
	addUserTag: function(tag) {
		var player = this;
		new Ajax.Updater('magnify_widget_playlist_item_tag_content', this.toolRoot + 'tag.minc?content_item_cid=' + this.currentContentItem.cid + '&amp;width=' + this.width + '&amp;add_tags=' + escape( tag ), {
			method: 'get',
			onComplete: function( transport ) {
				player.currentPanel.insertCloseLink();
			}
		}); 
	},
	
	dropUserTag: function(tag_nid) {
		var player = this;
		new Ajax.Updater('magnify_widget_playlist_item_tag_content', this.toolRoot + 'tag.minc?content_item_cid=' + this.currentContentItem.cid +'&amp;width=' + this.width + '&amp;drop_tag=' + tag_nid, {
			method: 'get',
			onComplete: function( transport ) {
				player.currentPanel.insertCloseLink();
			}
		}); 
	},
	

/*---- Object Submission ----*/	

	saveObject: function(url, form, target) {
		var player = this;
		new Ajax.Request(this.toolRoot + 'get_login.minc', {	
			onSuccess: function(transport) { 
				player.loggedIn = transport.responseText; 
				player.finishSave(url, form, target); 
			}
		});
	},
	
	finishSave: function(url, form, target) {
		var player = this;
		
		if ( !url || !form || !target ) {
			return;
		}
		if ( this.loggedIn > 0 ) {
			var params = "";
			if ( typeof(form) == 'object' ) { 
				params = Form.serialize( form );
			} else {
				params = form;
			}
			new Ajax.Updater(target, this.toolRoot + url, {
				method: 'post', 
				parameters: params, 
				evalScripts: true,
				onComplete: function( transport ) {
					player.currentPanel.insertCloseLink();
				}
			});	
		} else {
			this.delayedObject = new Array(url, Form.serialize( form ), target);
			if ( this.isSSO ) {
				window.open('/embed/player/modules/sso_login', 'sso_login', '');			
				new Ajax.Updater(target, this.toolRoot + 'sso_login_msg.minc?content_item_cid=' + this.currentContentItem.cid + '&amp;width=' + this.width, {
					method: 'get', 
					evalScripts: true
				});
			} else {
				this.auth.showLogin();	
			}
		}
	},
	


/*---- Player Play Behaviors ----*/

	stopContinuousPlay: function() {
		this.continuousPlay = false;
	},
	
	loadNext: function() {
		if ( this.companionAd && this.companionAd.showing ) {
			this.companionAd.hideAd();
		}
		
		if ( this.currentPlaylist )
			this.nextItem = this.currentPlaylist.getNextItem();
			
		if ( this.readMore || this.leaveBehind ) {
			this.showLeaveBehind();
		} else if ( this.nextItem ) {
			this.nextItem.makeSelected();
			this.nextItem.loadContent();
		}
	},
	
	getCurrentContent: function() {
		return this.registeredContent.get(this.currentContentItem.cid);
	},
	
	
	registerController: function(controller) {
		var content = this.getCurrentContent();
		if ( content )
			content.registerController(controller);
	},
	
	replay: function() {
		var content = this.getCurrentContent();
		content.config.container = 'magnify_video_player';
		content.width = this.config.player_width;
		content.height = this.config.player_height;
		content.autoplay = true;
		content.load();
	},
	
	pause: function() {
		var content = this.getCurrentContent();
		if ( content )
			content.pause();
	},
	
	play: function() {
		var content = this.getCurrentContent();
		if ( content )
			content.play();
	},


/*---- Misc Convenience Methods ----*/	

	getAddThis: function(url, title, container, preferredCount) {
		var content_url = encodeURIComponent(url);
		var content_title = encodeURIComponent(title);
		var container = $(container);
		if ( !preferredCount ) {
			preferredCount = 2;
		}
		
		['twitter', 'facebook'].each( function(name, i) {
			var link = new Element('a');
			link.addClassName('addthis_button_' + name);
			container.appendChild(link);		
		});
		addthis.toolbox(container, {}, {url: url, title: title});
	},
	
	injectCSS: function() {
		var ss = document.createElement('style');
		var def = css_string;
		ss.setAttribute("type", "text/css");
		if (ss.styleSheet) {   // IE
			ss.styleSheet.cssText = def;
		} else {                // the world
			var tn = document.createTextNode(def);
			ss.appendChild(tn);
		}
		var head = document.getElementsByTagName('head')[0];
		head.appendChild(ss);
	},

	injectScript: function(url) {
		var oScript = document.createElement("script"); 
		var dtRf = new Date(); 
		oScript.setAttribute("src", url + "?rf=" + dtRf.getTime()); 
		var head = document.getElementsByTagName('head')[0];
		document.body.appendChild(oScript);
	},
	
	createMessage: function(el, message) {
		el.innerHTML = '<div style="text-align: center; margin-top: ' + parseInt(el.offsetHeight/2 - 20) + 'px;" class="mvp-loading-message">' + message + '</div>';
	}
});

MagnifyEmbeddablePlayer.LeaveBehind = Class.create({
	initialize: function(player, config) {
		this.config = config;
		this.scrollCount = 0;
		this.player = function() {
			return player;
		}
		if ( config.playlist ) {
			this.player().registerPlaylist( config.playlist );
			this.registeredPlaylist = this.player().registeredPlaylists.get(config.playlist.cid);
			this.registeredPlaylist.loadItems();
		}
	},
	
	buildPlaylist: function() {			
		var leaveBehind = this;	
		
		if ( !this.registeredPlaylist ) {
			this.registeredPlaylist = this.player().currentPlaylist;
		}
		
		if ( !this.registeredPlaylist )
			return;
			
		this.player().nextItem = this.registeredPlaylist.getNextItem();
			
		this.container = $('mvp_read_more');
		
		this.watchAgainContainer = $('mvp_item_watch_again');
			
		this.readMoreContainer = $('mvp_read_more_container');
		this.itemContainer = new Element('div', { 'id': 'mvp_leave_behind_container', 'class': 'clearfix' } );
		this.readMoreContainer.insert( { 'after': this.itemContainer } );
			
		this.playlistContainer = new Element('div');
		this.playlistContainer.id = "mvp_leave_behind_related_container";
		
		this.playlistHeader = new Element('div');
		this.playlistHeader.id = "mvp_leave_behind_related_header";
		this.playlistHeader.className = "clearfix";
		
		this.playlistTitle = new Element('div');
		this.playlistTitle.id = "mvp_leave_behind_related_title";
		this.playlistTitle.update(this.registeredPlaylist.title || "More Videos");
		
		this.playlistLink = new Element('a');
		this.playlistLink.id = "mvp_leave_behind_related_link";
		this.playlistLink.href = this.player().hostname + this.registeredPlaylist.url;
		this.playlistLink.target = "_top";
		this.playlistLink.update("See more &raquo;");
		
		
		this.prevControl = new Element('div');
		this.prevControl.className = "magnify-widget-controls-left";
		this.prevControl.observe("click", function() { this.scrollPrev(); }.bind(this));
		
		this.nextControl = new Element('div');
		this.nextControl.className = "magnify-widget-controls-right";
		this.nextControl.observe("click", function() {this.scrollNext(); }.bind(this));
		
		this.playlistWindow = new Element('div');
		this.playlistWindow.id = "mvp_leave_behind_related_window";
		
		this.playlist = new Element('div');
		this.playlist.id = "mvp_leave_behind_related";
		
		var relatedItems = this.registeredPlaylist.sortedItems();		
		if ( this.registeredPlaylist.items.keys().indexOf(this.player().defaultContentItem.cid) < 0 ) {
			var unrelatedItem = this.player().registeredContent.get(this.player().defaultContentItem.cid);
			relatedItems.unshift( unrelatedItem );
		}
		
		// should we include the current item in the list?
		relatedItems.each( function( item, i ) {
			//if ( item.cid != leaveBehind.player().currentContentItem.cid ) {
				item.relatedOrder = i;
				itemDiv = leaveBehind.buildPlaylistItem( item );
				leaveBehind.playlist.appendChild( itemDiv );
			//}
		});
		
		this.playlistHeader.appendChild(this.playlistTitle);
		this.playlistHeader.appendChild(this.playlistLink);
		this.playlistContainer.appendChild( this.playlistHeader );
		this.playlistWindow.appendChild( this.playlist );
		
		this.playlistContainer.appendChild( this.prevControl );
		this.playlistContainer.appendChild( this.playlistWindow );
		this.playlistContainer.appendChild( this.nextControl );
		this.itemContainer.appendChild( this.playlistContainer );
	},
	
	buildPlaylistItem: function(item) {		
		var leaveBehind = this;	
		
		var containerDiv = new Element('span');
		containerDiv.className = "mvp-related-item-container";
		containerDiv.id = "mvp_related_item_container_" + item.cid;
		
		var itemDiv = new Element('div');
		if ( this.player().nextItem && item.cid == this.player().nextItem.cid ) {
			itemDiv.className = "mvp-related-item-selected";
		} else {
			itemDiv.className = "mvp-related-item";
		}
		itemDiv.observe("click", function() { item.loadContent(); leaveBehind.clearCountdown(); });		
		
		var itemImg = new Element('img');
		itemImg.className = "mvp-related-item-thumbnail";
		itemImg.src = item.thumbnailURL;
		
		itemDetails = new Element('div');
		itemDetails.className = "mvp-related-item-description";
		itemDetails.update( item.title );
		
		itemDiv.appendChild(itemImg );
		itemDiv.appendChild( itemDetails );
		containerDiv.appendChild( itemDiv );
		
		return containerDiv;
	},
	
	scrollPrev: function() {
		this.clearCountdown();
		if ( this.scrollCount == 0 ) {
			return;
		}
		var dist = $$('.mvp-related-item-container').first().getWidth();
		new Effect.Move(this.playlist, { x: 1*dist, y: 0, duration: 0.75, queue: { position: 'front', scope: 'related_items' } } );
		this.scrollCount--;
	},
	
	scrollNext: function() {
		this.clearCountdown();
		this.scrollCount++;
		if ( this.scrollCount == this.registeredPlaylist.items.values().length ) {
			return
		}
		var dist = $$('.mvp-related-item-container').first().getWidth();
		new Effect.Move(this.playlist, { x: -1*dist, y: 0, duration: 0.75, queue: { position: 'front', scope: 'related_items' } } );
	},
	
	scrollToItem: function() {
		var item = this.player().nextItem ? this.player().nextItem : this.player().currentContentItem;
		var itemContainer = $('mvp_related_item_container_' + item.cid);
		if ( !item || !itemContainer ) 
			return;
		var containerLoc = parseInt(this.playlist.style.left || 0);
		var itemLoc = itemContainer.positionedOffset()[0];
		var dist = containerLoc-itemLoc;
		new Effect.Move(this.playlist, { x: dist, y: 0, duration: 0.75, queue: { position: 'front', scope: 'related_items' } } );
		this.scrollCount = item.relatedOrder;
	},
	
	show: function() {
		try {
			this.container = $('mvp_read_more');
			if ( this.player().leaveBehind )
				this.buildPlaylist();	
			
			$('magnify_player_container').insert({'top':  new Element('img', { src: this.player().currentContentItem.largeThumbnailURL, width: this.player().currentContentItem.width, height: Math.floor( this.player().currentContentItem.width * .75 ) } ) });
			this.container.show();	
			
			if ( this.player().leaveBehind )
				this.scrollToItem();
			
			if ( this.player().nextItem != 'undefined' )
				this.startCountdown();
		} catch(e) { "error showing leave behind in show(): " + console.log( e.message ); }
	},
	
	clearCountdown: function() {
		if ( this.countDownInterval )
			clearInterval(this.countDownInterval);
		if ( this.player().leaveBehindTimeout )
			clearTimeout( this.player().leaveBehindTimeout );
		if ( this.countDown )	
			this.countDown.update('');
	},
	
	updateCountdown: function() {
		if ( this.timer == 0 ) {
			this.clearCountdown();
		}
		if ( !this.countDown ) { 
			this.countDown = new Element('div');
			this.countDown.id = "mvp_leave_behind_countdown_container";
			this.watchAgainContainer.insert( { 'after': this.countDown } );
		}
		this.countDown.update( '<span id="mvp_leave_behind_countdown_text">Next video in</span> <span id="mvp_leave_behind_countdown">' +this.timer + " second" + (this.timer == 1 ? "" : "s") + "</span>" );		
		this.timer--;			
	},
	
	startCountdown: function() {
		if ( this.player().leaveBehindCounter < 0 )
			return;
		
		this.timer = this.player().leaveBehindCounter;
		this.countDown = undefined;
		var leaveBehind = this;
		this.countDownInterval = setInterval( function() { leaveBehind.updateCountdown() }, 1000);
		
		this.player().leaveBehindTimeout = setTimeout(function() {	
			leaveBehind.player().nextItem.makeSelected();
			leaveBehind.player().nextItem.loadContent();
		}, this.player().leaveBehindCounter*1000);
	}
}),


MagnifyEmbeddablePlayer.Content = Class.create(MagnifyEmbeddablePlayer, {
	initialize: function( player, config ) {
		this.config = config;
		
		this.player = function() {
			return player;
		}	
		
		this.container = $(config.container);
		this.cid = config.cid;
		this.media_item_cid = config.media_item_cid;
		this.width = config.width;
		this.height = config.height;
		this.title = config.title;
		this.thumbnailURL = this.config.thumbnail_url;
		this.largeThumbnailURL = this.config.large_thumbnail_url;
		this.service = this.config.magnify_hosted ? 'magnify' : this.config.media_pipeline_cid;
		this.callback = this.config.callback;
		this.autoplay = this.config.autoplay;
		this.hasPreroll = this.player().videoAds && ( this.config.magnify_hosted == 1 );
		this.manuallyPaused = false;
		this.registerListeners();
	},
	
	registerListeners: function() {
		var content = this;
		if ( !this.autoplay )
			this.container.observe('click', function() { content.load(); });
	},
	
	registerController: function(controller) {
		this.controller = controller;
	},
	
	load: function() {
		var content = this;
		this.player().currentContentItem = this;
		
		if ( this.player().registrationRequired ) {
			this.player().requireLogin();
			return;
		}
		
		this.container = $(this.config.container);
		
		if ( !this.container )
			this.container = $('magnify_video_player');
		
		if ( typeof(StatsObject) != "undefined" ) {
			StatsObject.ajaxy = true;
			StatsObject.packLog();
		}
		
		if ( this.callback ) {
			callback();
			return;
		}
		
		if ( this.player().type == 'ivp' ) {
			var playerURL = this.player().hostname + '/item/' + this.cid;
			window.location.href = playerURL;	
		} else {
			new Ajax.Updater(this.container, this.getContentURL(), {
				method: 'get',
				evalScripts: true,
				asynchronous: true,
				onSuccess: function() {
					try {
						content.container.stopObserving("click");
						if ( content.player().leaveBehindPanel )
							content.player().leaveBehindPanel.clearCountdown();
						try {
							pSUPERFLY.virtualPage("/video/player/", playerURL);
						} catch(e) { }
						content.player().destroyPanels();
						if ( !content.hasPreroll ) {
							content.player().refreshAds();
						}
						
						content.autoplay = true;
						if ( content.player().companionAd != undefined && content.player().type != 'svp' && !content.player().hidePlaylist )
							content.player().companionAd.showAd(content.hasPreroll);
					} catch(e) { console.log("error retrieving content: " + e.message) }
				}
			});
		}
	},
	
	pause: function() {
		if ( this.controller != undefined ) {
			this.controller.pause();
			this.manuallyPaused = true;
		}
	},
	
	play: function() {
		if ( this.controller != undefined && this.manuallyPaused ) {
			this.controller.play();
			this.manuallyPaused = false;
		}
	},
	
	getContentURL: function() {
		var contentConfig = new Hash();
		// this should really be player().config.player_width / player_height
		contentConfig = $H(this.player().config);
		contentConfig.set('width', this.width);
		contentConfig.set('height', this.height);
		contentConfig.set('autoplay', 1);
		contentConfig.set('callback', this.callback);
		contentConfig.set('content_item_cid', this.cid);	
		contentConfig.set('media_cid', this.media_item_cid);
		contentConfig.set('preserve_aspect_ratio', 0);	
		contentConfig.set('mute', this.player().config.mute);
		contentConfig.set('continuous_play', this.player().continuousPlay ? 1 : 0);	
		contentConfig.set('read_more', this.player().readMore || this.player().leaveBehind ? 1 : 0);	
		contentConfig.set('player_cid', this.player().widgetCID);
		contentConfig.set('widget_type_cid', this.player().type);
		return this.player().hostname + ( this.autoplay ? this.player().componentRoot : '/item/' ) + 'player_content?' +  contentConfig.toQueryString();
	}
});


MagnifyEmbeddablePlayer.Ad = Class.create(MagnifyEmbeddablePlayer, {
	initialize: function( player, config ) {		
		if ( config.type == 'companion' ) {
			return new MagnifyEmbeddablePlayer.Ad.Companion(player, config);
		}
		
		this.type = config.type;
		
		this.player = function() {
			return player;
		}
	}
});

MagnifyEmbeddablePlayer.Ad.Companion = Class.create(MagnifyEmbeddablePlayer.Ad, {	
	initialize: function( player, config ) {
		this.type = config.type;
		this.showing = false;
		this.adDelay = 5000;
		this.adDistance = 0;
		
		this.player = function() {
			return player;
		}
		this.handle = $('magnify_widget_rect_handle');
	
		this.player().companionAd = this;						
		if ( this.player().type == 'svp' || this.player().hidePlaylist ) {
			this.adDistance = $('magnify_player_content').offsetHeight;		
		} else {
			this.adDistance = $('magnify_widget_playlist_container').offsetHeight;
		}
		
		this.registerListeners();
		this.toggleHandle();
		
		if ( !this.player().currentContentItem.autoplay && !this.player().syncAd ) {
			this.showAd(false);
		}
	},
	
	registerListeners: function() {
		var ad = this;
		this.handle.observe('click', function() { ad.toggleAd(true); });	
	},

	toggleAd: function() {
		if ( this.showing ) {
			this.hideAd();
		} else {		
			this.showAd();
		}
	},
	
	updateHandle: function(text) {
		this.handle.innerHTML = text;		
	},
	
	toggleHandle: function() {
		if ( !this.player().currentContentItem.autoplay && this.player().syncAd && this.player().type == 'mvp' ) {
			this.handle.hide();
		} else {
			this.handle.show();
		}
	},
	
	showAd: function(manual) {
		var ad = this;
		var maintainAd = false;
		
		if ( this.showing ) {
			clearTimeout( this.hideInterval );
			manual = true;
			maintainAd = true;
		}
		
		this.toggleHandle();
		
		if ( $('magnify_widget_playlist_item_companion') ) {			
			if ( !maintainAd ) {
				new Effect.Move($('magnify_widget_playlist_item_companion'), { x: 0, y: -1*this.adDistance, duration: 0.75, queue: { position: 'front', scope: 'ad' } });
			}
			if ( !manual ) {
				this.hideInterval = setTimeout(function() { ad.hideAd() }, this.adDelay);
			}
			
			if ( $("magnify_widget_rect_frame") ) {
				Effect.Appear( $('magnify_widget_rect_frame'), { duration: .1, queue: { position: 'end', scope: 'ad'} } );
			}
			this.updateHandle('hide ad');
			this.showing = true;
		}	
	},
	
	hideAd: function() {
		if ( this.showing ) {
			if ( $("magnify_widget_rect_frame") ) {
				Effect.Fade( $('magnify_widget_rect_frame'), { duration: .1, queue: { position: 'front', scope: 'ad'} } );
			}
			
			clearTimeout( this.hideInterval );
			this.showing = false;
			new Effect.Move($('magnify_widget_playlist_item_companion'), {x: 0, y: this.adDistance, duration: 0.75, queue: { position: 'end', scope: 'ad' }});
			this.updateHandle('reveal ad');
		}
	}
});


MagnifyEmbeddablePlayer.Panel = Class.create(MagnifyEmbeddablePlayer, {
	initialize: function( player, config ) {
		this.container = $(config.container);
		this.tab = $(config.tab);
		this.id = config.id;
		this.effect = config.effect;
		this.parentId = 'magnify_widget_playlist_item_' + this.id + "_container";
		this.contentId = 'magnify_widget_playlist_item_' + this.id + '_content';
		this.selectedSubnav = "";
		this.player = function() {
			return player;
		}
		this.buildPanel();
		this.loadPanel();
	},
	
	buildPanel: function() {			
		this.panelContainer = document.createElement('div');
		this.panelContainer.className = 'magnify-widget-playlist-item-content-container-created';
		this.panelContainer.id = this.parentId;
		this.panelContainer.style.zIndex = 499;
		this.panelContainer.style.position = "absolute";
		this.panelContainer.style.left = "0px";
		
		this.panel = document.createElement('div');
		this.panel.className = 'magnify-widget-playlist-item-content';
		this.panel.id = this.contentId;
		
		this.panelContainer.appendChild(this.panel);
		this.container.appendChild(this.panelContainer);	
	},
	
	loadPanel: function() {
		var panel = this;
		new Ajax.Updater(this.panel, this.getPanelURL( this.id ) , {
			evalScripts: true,
			method: 'get',
			asynchronous: true,
			onComplete: function() {				
				panel.insertCloseLink();
			}
		});		
	},
		
	showPanel: function() {
		if ( this.player().type != 'ivp' )
			this.player().pause();
			
		if ( this.player().leaveBehindPanel )
			this.player().leaveBehindPanel.clearCountdown();
		if ( this.effect == 'slide' ) {
			new Effect.BlindDown( this.panelContainer, {duration: 0.5, queue: { position: 'end', scope: 'panel' }});
		} else {
			new Effect.Appear( this.panelContainer, { duration: .1, queue: { position: 'end', scope: 'panel' } });
		}
		this.player().lastPanel = this.player().currentPanel;
		this.player().currentPanel = this;
		this.makeSelected();
	},
	
	hidePanel: function() {
		if ( this.effect == 'slide' ) {
			new Effect.BlindUp( this.panelContainer, { duration: 0.5, queue: { position: 'front', scope: 'panel' } });
		} else {
			new Effect.Fade( this.panelContainer, { duration: .1, queue: { position: 'front', scope: 'panel' } } );	
		}
		this.player().lastPanel = this.player().currentPanel;
		this.player().currentPanel = "";
		this.deselectAll();
		this.player().play();
	},
	
	makeSelected: function() {
		this.tab.removeClassName("magnify-widget-playlist-tab");
		this.tab.addClassName("magnify-widget-playlist-tab-on");
	},
	
	deselectAll: function() {
		$$('.magnify-widget-playlist-tab-on').each( function(el) {
			el.removeClassName("magnify-widget-playlist-tab-on");
			el.addClassName("magnify-widget-playlist-tab");
		});
	},
	
	showSubnav: function(id) {
		if ( id != this.selectedSubnav ) {
			Element.show(id);
			Element.hide(this.selectedSubnav);
			this.selectedSubnav = id;
		}
	},
	
	insertCloseLink: function() {
		if ( this.player().type != 'ivp' ) {
			this.closeContainer = new Element('div');
			this.closeContainer.className = "magnify-player-overlay-close";
			this.closeLink = new Element('a');
			this.closeLink.className = "magnify-player-overlay-close-link";
			this.closeLink.observe('click', function() { this.hidePanel(); }.bind(this));
			this.closeLink.update('close');
			this.closeContainer.appendChild(this.closeLink);
			this.panel.insert( { 'top': this.closeContainer } );
		}
	},
	
	getPanelURL: function( panel ) {
		return this.player().toolRoot +  panel + '.minc?content_item_cid=' + this.player().currentContentItem.cid + ( this.player().queryString ? '&' + this.player().queryString : '' );
	}	
});


MagnifyEmbeddablePlayer.Playlist = Class.create({
	initialize: function( player, config ) {
		this.config = config;
		this.type = config.list_type_cid;
		this.title = config.title;
		this.description = config.description;
		this.url = config.list_page_href;
		this.cid = config.cid;
		this.container = $(config.container);
		this.items = new Hash();
		this.itemIndex = undefined;
		this.showing = false;
		this.loaded = false;
		this.player = function() {
			return player;
		}
		this.sortedItems = function() {
			return this.items.values().sort( function(a, b) {
				return a.order - b.order;
			});
		}
		
		this.registerListeners();
		
		if ( this.player().defaultPlaylist == this.cid ) {
			this.show();
		}
	},
	
	registerListeners: function() {
		var playlist = this;
		if ( this.container )
			this.container.observe('click', function() { playlist.show(); } );
			
		if ( this.config.onLoad ) {
			this.onLoad = function() {
				this.config.onLoad();
			}
		}
	},
	
	loadItems: function() {
		if ( this.items.values().length > 0 || 
			this.loaded ) {
			this.showPlaylistItems();
			return;	
		}
			
		var playlist = this;
		new Ajax.Request(this.getItemsURL(), {
			method: 'get',
			async: true,
			onSuccess: function( transport ) {
				var items = transport.responseJSON;
				playlist.registerItems( items );
				if ( playlist.onLoad ) {
					playlist.onLoad();
				} else {
					playlist.showPlaylistItems();
				}
			},
			onFailure: function() {
				playlist.player().createMessage('Could not load playlist.');
			}
		});
	},
	
	registerItems: function(items) {
		var playlist = this;
		items.each( function(item, i) {
			item.order = i;
			item.container = playlist.itemContainer;
			playlist.registerItem( item );
		});
		this.player().registeredPlaylists.set( this.cid, this );
	},
	
	registerItem: function(item) {
		if ( !this.items.get(item.content.cid) )
			this.items.set( item.content.cid, new MagnifyEmbeddablePlayer.Playlist.Item( this, item ) );	
	},
	
	// fixme:  something is wrong here in the interchange between multiple playlists in the MVP
	show: function() {
		
		if ( this.player().currentPlaylist && this.player().currentPlaylist.showing && (this.player().currentPlaylist.cid != this.cid) ) {
			this.player().currentPlaylist.hide();
		}
		
		if ( this.showing && (this.player().config.layout != 'compact') ) {
			this.hide();
		} else {
			this.scrollToPlaylist();
			if ( this.container ) {
				this.container.addClassName('magnify-widget-playlist-selected');
				this.container.removeClassName('magnify-widget-playlist');
			}
			this.loadItems();
			this.showing = true;
			this.player().lastPlaylist = this.player().currentPlaylist;
			this.player().currentPlaylist = this;
		}
	},
	
	hide: function() {	
		if ( this.showing ) {
			this.hidePlaylistItems();
			this.restorePlaylists();
			if ( this.container ) {
				this.container.addClassName('magnify-widget-playlist');
				this.container.removeClassName('magnify-widget-playlist-selected');
			}
			this.showing = false;
			this.player().lastPlaylist = this;
			this.player().currentPlaylist = undefined;
		}
	},
	
	showPlaylistItems: function() {
		if ( this.player().hidePlaylist ) {		
			if ( this.player().currentContentItem ) {
				var item = this.items.get(this.player().currentContentItem.cid);
				item.makeSelected();
			}
			return;
		}
		var playlist = this;
		this.itemContainer = $(this.config.itemContainer);	
		
		if ( !this.loaded ) {	
			this.itemContainer.firstDescendant().update();
			
			this.sortedItems().each( function(item, i) {
				// the sliding drawers need a nested div inside them
				playlist.itemContainer.firstDescendant().appendChild(item.html);
				if ( playlist.player().currentContentItem && ( item.cid == playlist.player().currentContentItem.cid ) ) {
					item.makeSelected();
				}
			});
			this.loaded = true;
		}
		
		this.itemContainer.addClassName("magnify-widget-playlist-items-container-selected");
		this.itemContainer.removeClassName("magnify-widget-playlist-items-container");
		if ( !this.player().config.layout == 'compact' )	
			new Effect.BlindDown( this.itemContainer, { duration: 0.3, queue: { position: 'front', scope: 'show_playlist' }} );
		new Effect.Appear( this.itemContainer.firstDescendant(), { duration: 0.3 } );
		this.itemContainer.style.overflow = "auto";		
		
		if ( this.sortedItems().length == 0 ) {
			this.itemContainer.firstDescendant().update('<div class="mvp-no-items-message">No items in this playlist.</div>');
		}
		
		$('magnify_widget_playlist_container').style.overflow = "hidden";
	},
	
	hidePlaylistItems: function() {
		this.itemContainer = $(this.config.itemContainer);
		
		$('magnify_widget_playlist_container').style.overflowY = "auto";
		$('magnify_widget_playlist_container').style.overflowX = "hidden";
		
		this.itemContainer.removeClassName("magnify-widget-playlist-items-container-selected");
		this.itemContainer.addClassName("magnify-widget-playlist-items-container");
		new Effect.Fade( this.itemContainer.firstDescendant(), { duration: 0.3 } );
		if ( !this.player().config.layout == 'compact' )	
			new Effect.BlindUp( this.itemContainer, { duration: 0.3, queue: { position: 'front', scope: 'hide_playlist' }} );
	},
	
	scrollToPlaylist: function() {
		if ( this.player().hidePlaylist )
			return;
			
		if ( this.player().config.layout == 'compact' )	
			return;
			
		try {	
			Position.prepare();	
			var itemLoc = this.container.positionedOffset()[1] - Position.realOffset(this.container)[1];
			var containerLoc = parseInt(this.container.parentNode.style.top);
			this.player().lastScrollDistance = (-1*containerLoc)-itemLoc;
			new Effect.Move(this.container.parentNode, {x: 0, y: this.player().lastScrollDistance, queue: { position: 'end', scope: 'show_playlist' } });
			
		} catch(e) { console.log(e.message); }
	},
	
	restorePlaylists: function() {
		new Effect.Move(this.container.parentNode, {x: 0, y: -1*this.player().lastScrollDistance, queue: { position: 'end', scope: 'hide_playlist' } });
		this.player().lastScrollDistance = 0;
	},
	
	getNextItem: function() {
		var items = this.sortedItems();
		var nextIndex = this.itemIndex != undefined ? Number(this.itemIndex+1) : 0;
		var nextItem = items[nextIndex];
		if ( nextItem ) {
			return nextItem;
		} else {
			if ( this.player().hidePlaylist ) {
				nextItem = items[0];
				return nextItem;
			}
		}
	},
	
	getItemsURL: function() {
		return "/services/json/playlist/" + this.cid;
	}
});


MagnifyEmbeddablePlayer.Playlist.Item = Class.create(MagnifyEmbeddablePlayer.Playlist, {
	initialize: function(playlist, config) {
		try {
			this.playlist = playlist;
			this.container = config.container;
			this.player = function() {
				return this.playlist.player();
			}
			
			this.cid = config.content.cid;
			this.id = "magnify_widget_playlist_item_" + this.cid;
			this.order = config.order;
			this.title = config.content.title;
			this.thumbnailURL = config.content.thumbnail_url;
			this.permaLink = this.player().hostname + "/" + config.media.media_type_cid + "/" + config.content.permalink;
			this.postedDate = config.content.posted;
			this.poster = config.user ? config.user.handle : 'Anonymous';
			this.reviewCount = config.content.review_count;
			this.reviewScore = config.content.review_score;
			
			this.content = config.content;
			this.content.container = 'magnify_video_player';
			this.content.width = this.playlist.player().config.player_width;
			this.content.height = this.playlist.player().config.player_height;
			this.content.autoplay = true;
			
			this.player().registerContent(this.content);
			
			this.buildItem();
		} catch(e) { console.log(e.message); }
	},
	
	buildItem: function() {
		var item = this;
		
		this.html = new Element('div');
		this.html.id = this.id;
		this.html.addClassName("magnify-widget-playlist-item");
		this.html.addClassName("clearfix");
		this.html.observe('click', function() { item.loadContent(); } );
		
		this.thumbnailContainer = new Element('div');
		this.thumbnailContainer.className = "magnify-widget-playlist-item-thumbnail";
		this.thumbnail = new Element('img');
		this.thumbnail.src = this.thumbnailURL;
		//this.thumbnail.style.width = "36px";
		this.thumbnailContainer.appendChild(this.thumbnail);
		
		this.captionContainer = new Element('div');
		this.captionContainer.className = "magnify-widget-playlist-item-caption";
		
		this.captionIndicator = new Element('div');
		this.captionIndicator.className = "magnify-widget-playlist-item-caption-indicator";
		this.captionIndicator.update("Now Playing");
		
		this.captionTitle = new Element('div');
		this.captionTitle.className = "magnify-widget-playlist-item-caption-title";			
		this.captionLink = new Element('a');
		this.captionLink.className = "magnify-widget-playlist-item-caption-title-link";
		this.captionLink.title = this.title;
		this.captionLink.update(this.title);
		//this.captionLink.observe('click', function() { item.loadContent(); } );
		this.captionTitle.appendChild(this.captionLink);
		
		this.captionContent = new Element('div');
		this.captionContent.className = "magnify-widget-playlist-item-caption-content";
		this.captionContent.update("Posted " + this.postedDate + " by " + this.poster);
		
		if ( this.reviewCount ) {
			this.ratingContent = new Element('div');
			this.ratingContent.className = "magnify-widget-playlist-item-rating-content";
			// this.ratingContent.update( this.getRating() + " (" + this.reviewCount + " review" + (this.reviewCount == 1 ? "" : "s" ) + ")" );
			this.ratingContent.appendChild( document.createTextNode( " Rated " ) );
			this.ratingContent.appendChild( this.getRating() );
			this.ratingContent.appendChild( document.createTextNode( " (" + this.reviewCount + " review" + (this.reviewCount == 1 ? "" : "s" ) + ")" ) );
		}
		
		this.captionContainer.appendChild(this.captionIndicator);
		this.captionContainer.appendChild(this.captionTitle);
		if (this.ratingContent) {
			this.captionContent.appendChild(this.ratingContent);
		}
		this.captionContainer.appendChild(this.captionContent);
		
		this.html.appendChild(this.thumbnailContainer);
		this.html.appendChild(this.captionContainer);
	},
	
	loadContent: function() {
		this.makeSelected();
		this.playlist.player().registeredContent.get(this.cid).load();
	},
	
	makeSelected: function() {
		$$('.magnify-widget-playlist-item-selected').each( function(el) {
			el.removeClassName("magnify-widget-playlist-item-selected");
			el.addClassName("magnify-widget-playlist-item");
		});
		this.html.removeClassName("magnify-widget-playlist-item");
		this.html.addClassName("magnify-widget-playlist-item-selected");
		this.scrollIntoView();
		this.playlist.itemIndex = this.order;
	},
	
	scrollIntoView: function() {	
		if ( this.player().hidePlaylist )
			return;
			
		try {
			Position.prepare();
			var listContainer = this.html.parentNode.parentNode;
			var container_y = Position.cumulativeOffset(listContainer)[1];
			var element_y = Position.cumulativeOffset(this.html)[1];
			new Effect.Scroll(listContainer.id, { x: 0, y: ( element_y - container_y ), mode: 'absolute', queue: { position: 'end', scope: 'scroller' } });
		} catch(e) { console.log(e.message); }
	},
	
	getRating: function() {
		var width = this.reviewScore ? ( ( (this.reviewScore-1) / 2.25 ) + 1 ) * 10 : 0;
		var reviewBack = new Element('span');
		reviewBack.className = "mvp_star_rating_back";
		
		var reviewFront = new Element('span');
		reviewFront.className = "mvp_star_rating_front";
		reviewFront.style.width = width + "px";
		
		reviewBack.appendChild(reviewFront);
		
		return reviewBack;
	}
});



MagnifyEmbeddablePlayer.Auth = Class.create(MagnifyEmbeddablePlayer, {
	initialize: function( player, config ) {
		this.player = function() {
			return player;
		}
	},
	
	loadLogin: function() {
		new Ajax.Updater('magnify_widget_playlist_item_login_content', this.getLoginURL(), {				
			evalScripts: true,
			method: "get",
			asynchronous: true
		});
	},
	
	showLogin: function() {
		this.delayedPanel = this.player().currentPanel;
		this.player().showPanel( undefined, 'login' );
	},
	
	cancelLogin: function() {
		$('submit_login_btn').src = '/decor/buttons/signin_small.gif';
		Effect.BlindUp('signup_section');
		$('mvp_login_mode').value = 'signup';
		$('mvp_login_title').innerHTML = "Sign In";
		
		if ( this.player().currentPanel )
			this.player().currentPanel.hidePanel();
		
		if ( this.delayedPanel )	
			this.delayedPanel.showPanel();
	},
	
	logIn: function(url, form, target) {
		new Ajax.Updater(target, this.player().toolRoot + url, {
			method: 'post', 
			parameters: Form.serialize( form ), 
			evalScripts: true
		});		
	},
	
	completeLogin: function() {
		this.player().loggedIn = 1;
		if ( this.player().delayedObject != undefined ) {
			this.player().saveObject(this.player().delayedObject[0], this.player().delayedObject[1], this.player().delayedObject[2]);
		}
		if ( this.player().reloadRequired ) {
			this.player().registrationRequired = false;
			this.player().reloadRequired = false;
			this.player().replay();
		}
		this.player().auth.cancelLogin();
	},
	
	resetPassword: function(url, email, target) {
		new Ajax.Updater(target, this.player().toolRoot + url, {
			method: 'get', 
			parameters: 'reset_password=1&email=' + email, 
			evalScripts: true
		});	
	},
	
	getLoginURL: function() {
		return this.player().toolRoot + "/login.minc?content_item_cid=" + this.player().currentContentItem.cid;
	},
	
	checkEmail: function(email) {
		new Ajax.Request( '/login/email?email=' + escape( email ), { 
			method: 'get',
			onSuccess: function( transport ) { 
				if ( transport.responseText.indexOf('Please') > -1 ) {
					$('submit_login_btn').className = 'mvp-register-button';
					Effect.BlindDown('signup_section');
					$('mvp_login_mode').value = 'signup';
					$('mvp_login_title').innerHTML = "New User Registration";
					Element.hide('submit_button_reset');
				} else {
					$('submit_login_btn').className = 'mvp-signin-button';
					Effect.BlindUp('signup_section');
					$('mvp_login_mode').value = 'signin';
					$('mvp_login_title').innerHTML = "Sign In";	
					Element.show('submit_button_reset');		
				}
			} 
		});
	}
});


MagnifyEmbeddablePlayer.ThumbnailScroller = Class.create(MagnifyEmbeddablePlayer, {
	defaultScrollSpeed: 5000,
	
	initialize: function( player, config ) {	
		this.player = function() {
			return player;
		}
		
		this.scroller = config.scroller;
		this.direction = config.direction;
		this.playlist = config.playlist;
		this.linkTarget = config.linkTarget;	
		this.perPage = config.perPage;
		this.autoScroll = config.autoScroll;
		this.debug = config.debug;
		this.currentThumbnailPos = 0;
		this.scrollSpeed = config.scrollSpeed || this.defaultScrollSpeed;
		this.imgHeight = config.height;
		this.imgWidth = config.width;
		this.imgIndex = 0;
		this.scrollInterval;
		this.player().hidePlaylist = true;		
		this.thumbInterval = Math.round( (this.scrollSpeed/4) / this.perPage );
		
		this.registerCallbacks();
		this.getPlaylistItems();
	},
	
	registerCallbacks: function() {			
		var scroller = this;
		this.playlist.onLoad = function() {
			try {			
				scroller.playlistItems = scroller.registeredPlaylist.sortedItems();
				scroller.buildThumbnails(0, scroller.playlistItems.length);
						
				if ( scroller.autoScroll ) {
					scroller.startAutoScroll();
				}
			} catch(e) { console.log("in callback, error: " + e.message); }
		}
	},
	
	getPlaylistItems: function() {
		this.player().registerPlaylist(this.playlist);
		this.registeredPlaylist = this.player().registeredPlaylists.get(this.playlist.cid);
	},
		
	buildThumbnails: function(start, howMany) {
		try {
			if ( this.playlistItems.length == 0 ) { return; }
			var scrollClip = this.scroller;
			this.scrollChild = scrollClip.firstDescendant();
			
			if ( start > this.playlistItems.length-1 ) {
				start = 0;
			}
			if ( this.playlistItems.length < howMany ) {
				howMany = this.playlistItems.length;
			}
			
			this.scrollChild.innerHTML = "";
			var j = start;
			var widget = this;
			
			for ( var i=0; i < howMany; i++ ) {
				if ( j > this.playlistItems.length-1 ) {
					j = 0;	
				}
				widget.createThumbnail( i, j, "bottom" );
				j++;
			}	
			this.currentThumbnailPos = j;
			if ( this.playlistItems.length > this.perPage ) 
				this.placeImgs();
				
			this.scrollChild.show();
		} catch(e) { console.log("in buildThumbnails, error: " + e.message) }
	},
		
	createThumbnail: function( count, index, position ) {
		var thumbnail = this.playlistItems[index];
		thumbnail.count = index;
		var thumbnailDiv = thumbnail.html;
		thumbnailDiv.stopObserving('click');
		var thumbnailLink = new Element('a');
		thumbnailLink.href = thumbnail.permaLink;
		thumbnailLink.target = this.linkTarget;
		thumbnailLink.appendChild(thumbnailDiv);
		if ( position == 'bottom' ) {
			this.scrollChild.insert( { 'bottom': thumbnailLink } );
		} else {
			this.scrollChild.insert( { 'top': thumbnailLink } );		
		}
		
		var interval = this.thumbInterval*count;
		var widget = this;
		setTimeout(function() { widget.showElement(thumbnailLink); }, interval);	
	},
	
	placeImgs: function() {			
		this.images = $$('.magnify-widget-playlist-item');
		
		var thumbnailWidget = this;
		
		this.images.each( function(img, i) {
			var measure = ( thumbnailWidget.direction == 'left' ? thumbnailWidget.imgWidth : thumbnailWidget.imgHeight ) * (i);
			img.style.position = "absolute";
			if ( thumbnailWidget.direction == 'left' ) {			
				img.style.left = measure + 'px';
			} else {
				img.style.top = measure + 'px';
			}
	  	});
	},	
	
	showElement: function(el) {
		Effect.Appear(el);	
	},
	
	startAutoScroll: function() {
		var widget = this;
		this.scrollInterval = setInterval( function() { widget.scrollWidget( this.direction, -1) }, this.scrollSpeed );	
	},
	
	scrollWidget: function(dir) {
		if ( this.direction == 'left' ) {
			if ( dir > 0 ) {
				this.moveBack();	
			} else {
				this.moveForward();
			}
		} else {	
			if ( dir > 0 ) {
				this.moveDown();	
			} else {
				this.moveUp();
			}
		
		}
	},
	
	moveForward: function() {		
		var thumbnailWidget = this;
		var scrollClip = this.scroller;
		var scrollChild = scrollClip.firstDescendant();
		
		var mvAmt = this.perPage*this.imgWidth*-1;
		this.images.each( function(img, i) {
			new Effect.Move( img, { x: mvAmt, y: 0, mode: 'relative', duration: .5, afterFinish: function() {
				if ( parseInt( img.style.left ) < 0 ) {
					var j = ((thumbnailWidget.perPage*thumbnailWidget.imgWidth) + parseInt( img.style.left )) / thumbnailWidget.imgWidth;
					img.style.left = scrollChild.offsetWidth - (thumbnailWidget.perPage*thumbnailWidget.imgWidth) + (thumbnailWidget.imgWidth*j) + "px";
					thumbnailWidget.imgIndex++;
					if ( thumbnailWidget.imgIndex == thumbnailWidget.images.length ) {
						thumbnailWidget.imgIndex = 0;
					}
				}
			}} );
		});	
	},
	
	moveBack: function() {			
		var thumbnailWidget = this;
		var scrollClip = this.scroller;
		var scrollChild = scrollClip.firstDescendant();
		
		var j = this.imgIndex;		
		
		for ( var i = 1; i <= thumbnailWidget.perPage; i++ ) {		
			
			j--;
			if ( j < 0 ) {
				j = thumbnailWidget.images.length-1;
			}
			var currentImg = thumbnailWidget.images[j];
			console.log("j is: " + j);
			currentImg.style.left = ( 0 - thumbnailWidget.imgWidth - ((i-1)*thumbnailWidget.imgWidth) ) + 'px';
		}
	
		this.imgIndex = j;	
		
		var mvAmt = this.perPage*this.imgWidth;
		this.images.each( function(img, i) {
			new Effect.Move( img, { x: mvAmt, y: 0, mode: 'relative', duration: .5 } );
		});	
	},
	
	moveUp: function() {
		var thumbnailWidget = this;
		var scrollClip = this.scroller;
		var scrollChild = scrollClip.firstDescendant();
		
		var mvAmt = this.perPage*this.imgHeight*-1;
		this.images.each( function(img, i) {
			new Effect.Move( img, { x: 0, y: mvAmt, mode: 'relative', duration: .5, afterFinish: function() {
					if ( parseInt( img.style.top ) < 0 ) {
						var j = ((thumbnailWidget.perPage*thumbnailWidget.imgHeight) + parseInt( img.style.top )) / thumbnailWidget.imgWidth;
						img.style.top = scrollChild.offsetHeight - (thumbnailWidget.perPage*thumbnailWidget.imgHeight) + (thumbnailWidget.imgHeight*j) + "px";
						thumbnailWidget.imgIndex++;
						if ( thumbnailWidget.imgIndex == thumbnailWidget.images.length ) {
							thumbnailWidget.imgIndex = 0;
						}
					}			
				}
			});
		});
	},
	
	moveDown: function() {		
		var thumbnailWidget = this;
		var scrollClip = this.scroller;
		var scrollChild = scrollClip.firstDescendant();
		
		var j = this.imgIndex;		
		
		for ( var i = 1; i <= thumbnailWidget.perPage; i++ ) {		
			
			j--;
			if ( j < 0 ) {
				j = thumbnailWidget.images.length-1;
			}
			var currentImg = thumbnailWidget.images[j];	
			currentImg.style.top = ( 0 - thumbnailWidget.imgHeight - ((i-1)*thumbnailWidget.imgHeight) ) + 'px';
		}
	
		this.imgIndex = j;	
		
		var mvAmt = this.perPage*this.imgHeight;
		this.images.each( function(img, i) {
			new Effect.Move( img, { x: 0, y: mvAmt, mode: 'relative', duration: .5 } );
		});	
	
	}
});


MagnifyEmbeddablePlayer.Stats = Class.create(MagnifyEmbeddablePlayer, {
	initialize: function( player, config ) {
		this.player = function() {
			return player;
		}
	}
});

Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }

    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;

    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } else {

    }
  },
  update: function(position) {   
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});












