var Vader = new Class({
	bg: false,
	content: false,
	is_visible: false,
	data: false,
	autoplay: false,
	
	cur_chunk: false,
	cur_user_scene: false,
	cur_scene_index: false,
	
	bg_el: false,
	portrait_el: false,
	name_el: false,
	
	timeline_el: false,
	timeline_pos_el: false,
	timeline_width: false,
	
	scrubber_el: false,
	scrubber_ref_el: false,
	scrubber_pos_el: false,
	scrubber_width: 0,
	
	close_btn: false,
	
	initialize: function(setup) 
	{
		//console.log(options);
		this.bg_el = new Element('div', { 
			'style': 'position: absolute; top: 0px; left: 0px; background: #000; opacity: .85; filter: alpha(opacity=85); z-index: 70; display: none; '
		});
		
		this.close_btn = new Element('div', {
			'id': 'close_btn',
			'class': 'close_btn',
			'html': '<span>&times;</span> Close',
			'events': {
				'click': this.hide.bind(this)
			}
		});
		
		$(document.body).adopt(this.bg_el);
		$(document.body).adopt(this.close_btn);
		
		this.close_btn.hide();
		
		this.data = setup;
		
		this.scrubber_el = $('scrubber');
		this.scrubber_ref_el = this.scrubber_el.getFirst();
		this.scrubber_pos_el = this.scrubber_ref_el.getFirst();
		
		this.timeline_el = $('timeline');
		this.timeline_pos_el = this.timeline_el.getFirst();
		this.timeline_pos_el.setWidth(160 * this.data.length);
		this.timeline_width = 160 * this.data.length;
		
		this.timeline_pos_el.set('tween', { duration: 300, transition: Fx.Transitions.Cubic.easeOut });
		
		this.redraw();

		window.addEvent('resize', this.redraw.bind(this));
		
		this.bg_el.addEvent('click', this.hide.bind(this));
		//this.timeline_el.addEvent('mouseenter', this.timelineOn.bind(this));
		//this.timeline_el.addEvent('mouseleave', this.timelineOff.bind(this));
		
		this.scrubber_pos_el.addEvent('mousedown', this.scrubberDown.bind(this));
		$(document.body).addEvent('mouseup', this.scrubberUp.bind(this));
		
		window.addEvent('mousemove', this.mouseMove.bind(this));
		
		setInterval(this.loadThumbs.bind(this), 500);
		
		this.thumbs_list = $$('img.lazyload');
	},
	
	thumbs_list: false,
	loadThumbs: function()
	{
		for (var i = 0; i < this.thumbs_list.length; i++) {
			var xpos = this.thumbs_list[i].getPosition().x;
			if (this.thumbs_list[i].alt != 'loaded' && xpos > -200 && xpos < window.getWidth()) {
				this.thumbs_list[i].src = this.thumbs_list[i].alt;
				this.thumbs_list[i].alt = 'loaded';
			}	
		}
	},
	
	likeToggle: function(update)
	{
		if (!cur_user) {
			login_popup.show();
			return;
		}
		
		var img = $('like_btn').getFirst();
		var user_likes = this.data[this.cur_chunk - 1].user_scenes[this.cur_scene_index].cur_user_likes;
		
		if (user_likes)
			img.src = '/assets/images/like_btn_off.jpg';
		else
			img.src = '/assets/images/like_btn_on.jpg';
		
		this.data[this.cur_chunk - 1].user_scenes[this.cur_scene_index].cur_user_likes = !user_likes;
		
		new Request({ 
			url: '/ajax/scenes/like?id=' + this.cur_user_scene, 
			onSuccess: function(json) {
				json = JSON.decode(json);
				
				if (json.liked) {
					img.src = '/assets/images/like_btn_on.jpg';
				}
				else {
					img.src = '/assets/images/like_btn_off.jpg';
				}
	        }.bind(this)
	    }).send();
	},
	
	toggleAutoplay: function()
	{
		if (this.autoplay)
		{
			this.autoplay = false;
			$('btn_autoplay').innerHTML = 'Autoplay <span>Off</span>';
		}
		else 
		{
			this.autoplay = true;
			$('btn_autoplay').innerHTML = 'Autoplay <span class="on">On</span>';
		}
	},
	
	selectScene: function(i)
	{
		location.href = '#/scene/' + i;
		this.loadUserScene(i, false);
	},
	
	refreshTitle: function()
	{
		$('vader_title').innerHTML = 'Scene ' + this.cur_chunk + '<span>' + this.data[this.cur_chunk - 1].title + '</span>';
		
		if (cur_user && (is_admin || this.data[this.cur_chunk - 1].title == 'Untitled' || this.data[this.cur_chunk - 1].title == 'null'))
			$('edit_title').show();
		else
			$('edit_title').hide();
	},
	
	loadUserScene: function(chunk_id, user_scene_id)
	{
		this.timelineOff();
		
		if (this.cur_chunk) {
			$('vader_chunk_' + this.cur_chunk).removeClass('selected');
		}
		var chnkplay = $('chunk_play');
		if (chnkplay)
			chnkplay.destroy();
			
		$('vader_chunk_' + chunk_id).addClass('selected');
		$('vader_chunk_' + chunk_id).adopt(
			new Element('div', { 'id': 'chunk_play', 'html': 'Original' })
		);
	
		$$('#vader_user_scenes .thumb').removeClass('selected');
		
		var preloaded = true;
		
		this.show();
		
		if (chunk_id != this.cur_chunk)
		{
			this.cur_chunk = chunk_id;
			preloaded = false;
			
			this.timelineSelectScene(chunk_id);
			this.redrawScrubber();	
		
			this.loadSceneInfo(chunk_id);
		}
		
		this.refreshTitle();
		
		if (user_scene_id > 0) 
		{
			var scenes = this.data[chunk_id - 1].user_scenes;
			
			for (var i = 0; i < scenes.length; i++)
			{
				if (scenes[i].id == user_scene_id) 
				{
					this.cur_user_scene = user_scene_id;
					this.cur_scene_index = i;
					this.userSceneSelect(user_scene_id);
					
					if (cur_user == scenes[i].user_id)
						$('like_btn').hide();
					else 
						$('like_btn').show();
					
					if (this.autoplay)
						this.loadPlayer(scenes[i].video_id);
						
					return;
				}
			}
		}
		else { // Show original
			$('like_btn').hide();
			this.cur_user_scene = false;
			this.showOriginal();
		}
	},
	
	loadPlayer: function(video_id)
	{
		var player = new Swiff('http://vimeo.com/moogaloop.swf', {
			id: 'movieswf',
			container: 'video_container',	
		    width: 500,
		    height: 375,
		    vars: {
				fp_version: 9,
		        clip_id: video_id,
		        show_portrait: 0,
		        show_byline: 0,
		        show_title: 0,
				js_api: 1,
				autoplay: 1,
				color: 'ffffff',
				js_onLoad: 'vader.onPlayerLoaded',
				js_swf_id: 'movieswf'
		    },
			params: {
				allowscriptaccess: 'always',
				allowfullscreen: 'true'
			}
		});
	},
	
	onPlayerLoaded: function()
	{
		document.getElementById('movieswf').api_addEventListener('onFinish', 'vader.onPlayerProgress');
	},
	
	onPlayerProgress: function()
	{
		if (this.autoplay)
		{
		/*	var dur = document.getElementById('movieswf').api_getDuration();
			var sec = document.getElementById('movieswf').api_getCurrentTime();

			if (sec >= Math.floor(dur) - .5) {*/
			
				//	console.log(this.cur_chunk + 1, this.data[this.cur_chunk + 1].user_scenes[0].id)
				$('video_container').innerHTML = '';
			//	console.log(this.data[this.cur_chunk + 1]);
				var scene_index = Math.round(Math.random() * (vader.data[this.cur_chunk].user_scenes.length - 1));
					
				this.loadUserScene(this.cur_chunk.toInt() + 1, this.data[this.cur_chunk].user_scenes[scene_index].id);
				this.loadPlayer(this.data[this.cur_chunk.toInt() - 1].user_scenes[scene_index].video_id);
		//	}
		}
	},
	
	ajax: false,
	loadSceneInfo: function(i)
	{
		this.loading();
		
		if (this.ajax)
			this.ajax.cancel();
		
		this.ajax = new Request({ 
			url: '/ajax/home/player_scene_info?scene_id=' + i, 
			onSuccess: function(json) 
			{
				data = JSON.decode(json);
				$('vader_info').innerHTML 		 = data['info'];
				$('vader_user_scenes').innerHTML = data['user_scenes'];

				if (this.cur_user_scene) {
					this.userSceneSelect(this.cur_user_scene);
				}
				else {
					$('vader_scene_orig').show();
				}
	        }.bind(this)
	    }).send();
	},
	
	loading: function()
	{
		$$('#vader_user_scenes img').destroy(); // turn images black
		
		$('vader_info').innerHTML = '';
		$('vader_info').adopt(
			new Element('div', { 
				'class': 'loading'
			}).adopt(
				new Element('div', {
					'class': 'text',
					'html': 'Loading'
				})
			)
		);
	},
	
	userSceneSelect: function(id)
	{
		$$('.vader_scene_info').hide();
		
		if ($('vader_scene_info_' + id)) {
			$('vader_scene_info_' + id).show();
			$('vader_scene_' + id).addClass('selected');
			$('vader_scene_orig').hide();		
		}
	
		$('like_btn').getFirst().src = '/assets/images/like_btn_' + (this.data[this.cur_chunk - 1].user_scenes[this.cur_scene_index].cur_user_likes ? 'on' : 'off') + '.jpg';
		
		location.href = '#/scene/' + this.cur_chunk + '/' + this.data[this.cur_chunk - 1].user_scenes[this.cur_scene_index].id;
				
		$('vader_chunk_' + this.cur_chunk).removeClass('selected');

		if (!this.autoplay)
		{
			var vid = $('video_container');
			vid.innerHTML = '';
			vid.adopt(
				new Element('div', { 
					'class': 'scene_wrap'
				}).adopt(
					new Element('img', {
						'src': this.data[this.cur_chunk - 1].user_scenes[this.cur_scene_index].thumbnail
					})
				).adopt(
					new Element('img', { 
						'src':  '/assets/images/play_red_btn.png',
						'class': 'play_btn',
						'onclick': 'vader.loadPlayer(' + this.data[this.cur_chunk - 1].user_scenes[this.cur_scene_index].video_id + ')'
					})
				)
			);
		}
	},
	
	playOriginal: function()
	{
		if (!cur_user) {
			login_popup.show();
			return false;
		}
		
		// @TODO add movie path
		var mp4 = '<div class="wrap"><object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab" WIDTH="500" HEIGHT="211" ><PARAM NAME="src" VALUE="/assets/videos/sw_chunks/orig/chunk' + this.cur_chunk + '.mp4" ><PARAM NAME="autoplay" VALUE="true" ><EMBED SRC="/assets/videos/sw_chunks/orig/chunk' + this.cur_chunk + '.mp4" TYPE="image/x-macpaint" PLUGINSPAGE="http://www.apple.com/quicktime/download" WIDTH="500" HEIGHT="211" AUTOPLAY="true"></EMBED></object></div>';
		$('video_container').innerHTML = mp4;
	},
		
	showOriginal: function()
	{
		var vid = $('video_container');
		var el = $('vader_scene_orig');
		
		if (el) {
			el.show();
			$$('.vader_scene_info').hide();
		}
		
		vid.innerHTML = '';
		vid.adopt(
			new Element('div', { 
				'class': 'wrap'
			}).adopt(
				new Element('img', {
					'src': this.data[this.cur_chunk - 1].thumbnail_large
				})
			).adopt(
				new Element('img', { 
					'src':  '/assets/images/play_btn.png',
					'class': 'play_btn',
					'onclick': 'vader.playOriginal()'
				})
			)
		)
	},
	
	timelineSelectScene: function(id)
	{
		var x = ((id - 1) * 160) - (this.window_width / 2) + 80;
		this.timelineMove(x + 50, true);
	},
	
	show: function()
	{
		if (this.is_visible) 
			return false;
			
		this.is_visible = true;
		
		this.bg_el.set('tween', { duration: 300, transition: Fx.Transitions.Cubic.easeOut });
		this.bg_el.setStyle('opacity', 0);
		this.bg_el.show();
		this.bg_el.tween('opacity', .9);
		
		$('vader').setStyle('visibility', 'hidden');
		$('vader').show();
		
		this.delayShow.delay(300, this);

		try {
		$$('.hideflash').hide();
		} catch(e) { }
	},
	
	delayShow: function()
	{
		$('vader').setStyle('visibility', 'visible');
		
		var pos = window.getScrollTop() + 50;
		if (pos + $('vader').getHeight() > window.getScrollHeight())
			pos = window.getScrollHeight() - $('vader').getHeight() - 50;
		$('vader').setY(pos);
		
		this.close_btn.show();
	},
	
	hide: function()
	{
		$('vader').hide();
		this.bg_el.hide();
		this.close_btn.hide();
		this.is_visible = false;
		
		location.href = '#/';
		
		try {
		$$('.hideflash').show();
		} catch(e) { }
	},
	
	timeline_trigger: false,
	timeline_mouse_pos: false,
	timeline_int: false,
	timeline_cur_pos: 0,
	timeline_speed: 0,
	
	timelineOn: function()
	{
		//window.addEvent('mousemove', this.timelineMove.bind(this));
		this.timeline_trigger = true;
		clearInterval(this.timeline_int);
		this.timeline_int = this.timelineAnimate.periodical(30, this);
	},
	
	timelineOff: function()
	{
		//window.removeEvent('mousemove', this.timelineMove.bind(this));
		this.timeline_trigger = false;
		$clear(this.timeline_int);
	},
	
	mouseMove: function(e)
	{
		if (this.timeline_trigger)
		{		
			this.timeline_mouse_pos = e.client;
		}
		
		if (this.scrubber_trigger)
			this.scrubberMove(e);
	},
	
	timelineAnimate: function()
	{
		if (this.timeline_mouse_pos)
		{
			var w 		= this.window_width;
			var diff 	= this.timeline_mouse_pos.x - w / 2;
			var dir 	= diff >= 0 ? 1 : -1;
			diff 		= Math.abs(diff);
			
			// increase distance to animate
			diff -= 400;
			if (diff < 0) diff = 0;
			
			var speed = (diff / (w / 2) * 100) * dir;

			this.timelineMove(this.timeline_cur_pos + speed);
			this.redrawScrubber();
		}
	},
	
	timelineMove: function(x, tween)
	{	
		var timeline_width = this.timeline_pos_el.getWidth();
		
		if (x > timeline_width - this.window_width) {
			this.timeline_cur_pos = timeline_width - this.window_width;
			return;
		}
		else if (x < 0) {
			this.timeline_cur_pos = 0;
			return;
		}
		else 
			this.timeline_cur_pos = x;
		
		//console.log(x);
		if (!tween)
			this.timeline_pos_el.style.left = (-x) + 'px';
		else
			this.timeline_pos_el.tween('left', -x);
	},
	
	window_width: 0,
	
	redraw: function()
	{
		this.window_width = window.getWidth();
		var h = window.getHeight();
		
		this.scrubber_width = 100;//Math.round(this.window_width * (this.window_width / this.timeline_width));
		//this.scrubber_pos_el.setWidth(this.scrubber_width);
		
		this.timeline_el.setWidth(this.window_width);
		
		this.bg_el.setWidth(this.window_width);
		this.bg_el.setHeight(window.getScrollHeight());
		
		this.scrubber_el.setWidth(this.window_width);
	},
	
	/** Scrubber Rub Dub **/
	redrawScrubber: function()
	{
		var scrubw = this.scrubber_width; 
		var pos = (this.timeline_cur_pos / (this.timeline_width - this.window_width - scrubw)) * (this.window_width - scrubw);
		
		if (pos < 0)
			this.scrubber_pos_el.style.marginLeft = '0px';
		else
			this.scrubber_pos_el.style.marginLeft = pos + 'px';
	
	},
	
	scrubber_trigger: false,
	scrubber_offset: 0,
	scrubberDown: function(e)
	{
		this.scrubber_offset =  e.client.x - this.scrubber_pos_el.style.marginLeft.toInt();
		this.scrubber_trigger = true;
	},
	
	scrubberUp: function()
	{
		this.scrubber_trigger = false;
		this.scrubber_offset = 0;
	},
	
	scrubberMove: function(e)
	{
		var x 		= e.client.x;
		var scrubw 	= this.scrubber_width;
		var w 		= this.window_width;
		
		var scrub_pos = x - this.scrubber_offset;
		
		if (scrub_pos < 0) {
			scrub_pos = 0;
		}
		
		if (scrub_pos > w - scrubw) {
			scrub_pos = w - scrubw;
		}

		this.scrubber_pos_el.style.marginLeft = scrub_pos + 'px';
	
		var pos = scrub_pos / (w - scrubw);
		this.timelineMove(pos * (this.timeline_width - this.window_width));
	},
	
	editTitle: function()
	{
		var str = prompt('Enter a new title for this scene');

		if (str != '')
		{
			new Request({ 
				url: '/ajax/scenes/set_scene_title?id=' + this.cur_chunk + '&title=' + encodeURIComponent(str), 
				onSuccess: function(title) {
		        	this.data[this.cur_chunk - 1].title = title;
					this.refreshTitle();
				}.bind(this)
		    }).send();
		}
	},
	
	updateCast: function(el, chunk_id, cast_id)
	{
		if (!is_admin)
			return false;
			
		var img = el.getFirst();
		var remove = 0;
		
		if (img.src.indexOf('_bw_') >= 0) {
			img.src = '/assets/images/badges/badge_' + cast_id + '_50.png';
		}
		else {
			remove = 1;
			img.src = '/assets/images/badges/badge_bw_' + cast_id + '_50.png';
		}
		
		new Request({ 
			url: '/ajax/scenes/chunk_update_cast?remove=' + remove + '&chunk_id=' + chunk_id + '&cast_id=' + cast_id,
			onSuccess: function(rsp) {
				//console.log(rsp);
			}.bind(this)
	    }).send();
	}
});
Vader.implement(new Options);
