var cur_scene_id = false;
var cur_tab = false;
var r2d2 = false;
window.addEvent('domready', function() {
	r2d2 = new Lightbox('r2d2', { width: 540, fixed: true });
	
	anchor_open_scene();
	anchor_open_scene.periodical(300);
	
	load_thumbs.periodical(1000);
});

function anchor_open_scene() {
	var anchor = location.hash.substring(1); 
	var scene_id = false;
	var type = false;
	
	if (anchor.indexOf('finished/') >= 0) {
		scene_id = anchor.substr(10);
		type = 'finished';
	}
	else if (anchor.indexOf('scene/') >= 0) {
		scene_id = anchor.substr(7);
	}
	else if (anchor.indexOf('scene') >= 0) {
		scene_id = anchor.substr(5);
		type = 'finished';
	}
	else {
		if ( anchor == '/' )
			close_scene();
		return;
	}
	
	var cur_type = $('tab_finished').hasClass('selected') ? 'finished' : false;
	if ( scene_id != cur_scene_id || type != cur_type ) {
		open_scene(scene_id, type);
		
		try {
			pageTracker._trackEvent('Scenes', 'History', type + '/' + cur_scene_id);
		} catch(e) { }
	}
}

function open_scene(id, mode, event) {
	if (event) {
		var e = new Event(event);
		e.stop();
	}
	if (!mode) mode = 'scene';
	
	cur_tab = mode;
	cur_scene_id = id;
	
	if (rules) rules.hide();
	$('disp_scene_id').innerHTML = id;
	$('total_finished').innerHTML = chunk_list[id - 1].total_videos;
	$('thumbnail_content').setStyle('background', '');
	$('thumbnail_content').setStyle('background', "url('/assets/images/sw_chunks/thumbs/t500_" + id + ".jpg')");

	tab_switch(mode);
	
	update_scene_controls();
	
	r2d2.show();
	stop_deathstar();
	
	try {
		pageTracker._trackEvent('Scenes', 'Open', mode + '/' + cur_scene_id);
	} catch(e) { }
}

function close_scene() {
	start_deathstar();
	r2d2.hide();
	location.href = '#/';
	cur_scene_id = false;
}

function accept_scene() {
	if ( !is_logged_in ) {
		login.show();
		close_scene();
		return false;
	}
	
	new Request({ url: '/accept', onComplete: on_accept_scene_finish }).send('chunk_id=' + cur_scene_id); 
	$('accept_scene_btn').value = 'Loading...';
}

function on_accept_scene_finish(data) {
	if ( data > 0 ) {
		can_take_scenes = false;
		//last_chunk_id = false;
		
		$('chunk_' + cur_scene_id).className = 'droid type_taken yours'; 
		chunk_list[cur_scene_id - 1].status = 'taken';
		chunk_list[cur_scene_id - 1].total_users++;
		user_chunk_list.push(cur_scene_id.toString());
		user_videos.push(false);
		user_videos = user_videos.clean();
		refresh_your_scenes();

		r2d2.hide();
		
		$('i_agree_btn').show();
		rules.show();
	}
	else {
		scene_error(data);	
	}
	
	$('accept_scene_btn').value = 'Take this scene';
	r2d2.redraw();
}

function refresh_your_scenes() {
	new Request({ url: '/ajax/template/your_scenes', onSuccess: 
		function(txt) { 
			$('your_scenes').innerHTML = txt; 
		} 
	}).send('chunk_id=' + cur_scene_id);
}

function display_chunks(type) {
	$('sort_all').removeClass('selected');
	$('sort_finished').removeClass('selected');
	$('sort_free').removeClass('selected');
	$('sort_taken').removeClass('selected');
	
	$('sort_' + type).addClass('selected');
	
	$$('.droid').hide();
	
	setCookie('sort_type', type);
	
	if ( type == 'free' ) {
		if (total_untaken_scenes == 0)
			$$('.type_' + type).show();
		else
			$$('.untaken').show();
	} 
	else if (type == 'all') {
		$$('.droid').show();
	} 
	else {
		$$('.is_' + type).show();
	}
	
	page_touched = true;
}


function tab_switch(tab) {
	if (tab == 'scene' || chunk_list[cur_scene_id - 1].total_users == 0) {
		location.href = '#/scene/' + cur_scene_id;
		
		update_scene_controls();
		
		$('thumbnail_content').show();
		$('finished_content').hide();
		
		$('tab_finished').removeClass('selected');
		$('tab_scene').addClass('selected');
	} else {
		location.href = '#/finished/' + cur_scene_id;
		
		$('thumbnail_content').hide();
		$('finished_content').show();
		
		$('tab_finished').addClass('selected');
		$('tab_scene').removeClass('selected');
		
		$('finished_content').innerHTML = 'Loading ...';
		new Request({ 
			url: '/ajax/home/get_chunk_info',
			onSuccess: function(data) {
				$('finished_content').innerHTML = data;	
			}
		}).send('chunk_id=' + cur_scene_id);
	}
}

function replace_scene() 
{
	var vid = user_videos[user_chunk_list.indexOf(cur_scene_id.toString())];
	window.location = 'http://www.vimeo.com/' + vid + '/settings/videofile';
}

function watch_original_scene() 
{
	
	tab_switch('scene');
	play_scene();
}

function update_scene_controls() 
{
	// Reset everything
	hide_controls();
	
	if (chunk_list[cur_scene_id - 1].total_users == 0) {
		$('tab_finished').hide();
	} else {
		$('tab_finished').show();
	}
	
	$('play_scene_btn').show();
	$('play_scene').innerHTML = '';
	$('upload_btn').value = 'Upload';
	$$('.swiff-uploader-box').destroy();
	
	if ( user_chunk_list.contains(cur_scene_id.toString()) ) {
		var vid = user_videos[user_chunk_list.indexOf(cur_scene_id.toString())];
		
		$('download_btn').show();
		$('play_scene_btn').show();
		
		if ( !(vid > 0) ) { // user still working on scene
			set_scene_message('This is your scene! Are you ready to upload your video?');
			$('upload_btn').show();
			$('return_btn').show();
		}
		else { // user finished the scene
			$('replace_btn').show();
			set_scene_message('You have uploaded this scene. Thanks for participating!');
		}
		return false;
	}
	
	if ( user_chunk_list.length >= 3 ) { // already has three scenes
		scene_error(-3);
		return false;
	}
	
	if ( !can_take_scenes ) { // still need to finish first scene
		scene_error(-2);
		return false;
	}
	
	if ( total_rounds == chunk_list[cur_scene_id - 1].total_users ) { // scene maxed out
		set_scene_message('Sorry! This scene is no longer available.');
	}
	
	switch( chunk_list[cur_scene_id - 1].status ) { 
		case 'free':
			if ( total_rounds != chunk_list[cur_scene_id - 1].total_users ) {
				$('accept_scene_btn').show();
				$('random_btn').show();
				set_scene_message("Do you want to reenact this scene? Once you've taken the scene, you'll have the option to download the 15 second clip. Don't worry, you can give back this scene if you're not happy with it.");
			}
			break;
	}
}

function set_scene_message(txt) {
	$('scene_info').innerHTML = txt;
}

function scene_error(error_id) {
	msg = '';
	switch(error_id.toInt()) {
		case -1:
			msg = "Sorry! You can't choose this scene because you already own the next or previous scene. We have this rule so that individual people can't take more than two scenes in a row and to keep the spirit of randomness.";
			break;
		case -2:
			msg = 'In order to take this scene, you must complete the scene you already have.';
			break;
			
		case -3:
			msg = ('You already have a max of three scenes.');
			break;
			
		case -4:
			msg = ('Uh oh, looks like someone got this scene before you did.');
			break;
	
		case -5:
			msg = ('Sorry, but you had this scene before and you let it expire. You\'re not allowed to choose this scene again.');
			break;
			
		case -6:
			msg = 'Sorry! This scene is currently not availble because there is already a finished version of this scene. This is a new rule added in order to speed up the overall progress of the project. <a href="javascript:void(0)" onclick="display_chunks(\'free\'); close_scene();">Click here if you would like to see all available scenes.</a>';
			break;
			
		default:
			msg = 'An uknown error occurred.';
			break;
	}
	
	set_scene_message(msg);
}

function hide_controls() {
	$('accept_scene_btn').hide();
	$('download_btn').hide();
	$('upload_btn').hide();
	$('random_btn').hide();
	$('replace_btn').hide();
	$('return_btn').hide();
}

function play_scene() {
	if ( !is_logged_in ) {
		login.show();
		close_scene();
		return false;
	}
	
	var mp4 = '<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' + cur_scene_id + '.mp4" ><PARAM NAME="autoplay" VALUE="true" ><EMBED SRC="/assets/videos/sw_chunks/orig/chunk' + cur_scene_id + '.mp4" TYPE="image/x-macpaint" PLUGINSPAGE="http://www.apple.com/quicktime/download" WIDTH="500" HEIGHT="211" AUTOPLAY="true"></EMBED></object>';
	$('play_scene').innerHTML = mp4;
	$('play_scene_btn').hide();
}

function give_back_scene() {
	if ( confirm('Once returned, anyone else can take this scene. Are you sure you want to give back this scene?')) {
		chunk_list[cur_scene_id - 1].status = 'free';
		chunk_list[cur_scene_id - 1].total_users--;
		$('chunk_' + cur_scene_id).className = 'droid type_free';	
		user_chunk_list.erase(cur_scene_id.toString());
		user_videos.erase(false);
		user_videos.clean();
		
		new Request({ url: '/reject', onSuccess: refresh_your_scenes }).send('chunk_id=' + cur_scene_id);
		
		can_take_scenes = true;
		close_scene();
	}
}

function download_scene() {
	if ( !is_logged_in ) {
		login.show();
		close_scene();
		return false;
	}
	window.location = '/assets/videos/sw_chunks/orig/chunk' + cur_scene_id + '.mp4';
}

function random_scene() {
	while(1) {
		var r = Math.round(Math.random() * (chunk_list.length-1));
		if ( chunk_list[r].status == 'free' ) {
			open_scene(r + 1);
			break;
		}
	}
}

function show_random_finished_scene() 
{
	random_scene();
	next_finished_scene();
}

function next_finished_scene() {
	var id = cur_scene_id;
	while(1) {
		id++;
		if ( id >= chunk_list.length ) id = 1;
		
		if ( chunk_list[id - 1].total_videos > 0 ) {
			open_scene(id, 'finished');
			break;
		}
	}
}

function prev_finished_scene() {
	var id = cur_scene_id;
	while(1) {
		id--;
		if ( id <= 0 ) id = chunk_list.length;
		
		if ( chunk_list[id - 1].total_videos > 0 ) {
			open_scene(id, 'finished');
			break;
		}
	}
}

///////////////////////////////////////////////
// Uploading stuff

function upload_scene() {
	$('play_scene_btn').hide();
	$('play_scene').innerHTML = '';
	$('upload_btn').value = 'Hold on...';
	$('tab_finished').hide();
	new Request({ url: '/upload/ticket', onSuccess: on_get_ticket }).send();
}

function on_get_video(video_id) {
	can_take_scenes = true;
	
	chunk_list[cur_scene_id].status = 'finished';
	user_videos.erase(false);
	user_videos.push(video_id.toString);
	set_scene_message("Congratulations! You have finished uploading your scene. We must validate your scene before we post it to StarWarsUncut.com. You can watch the progess <a href=\"http://www.vimeo.com/" + video_id.trim() + "\">here</a>");
}

function upload_finish(ticket_id) {
	set_scene_message("Almost done...");
	$('close_btn').show();
	new Request({ url: '/upload/finish', onSuccess: on_get_video }).send('ticket_id=' + ticket_id + '&chunk_id=' + cur_scene_id);
	swf_uploader = false;
}

function upload_cancel() {
	swf_uploader = false;
	close_scene();
}

var swf_uploader = false;
function on_get_ticket(data) {
	hide_controls();
	
	$('upload_btn').show();
	$('upload_btn').value = 'Choose your video to upload ...';
	set_scene_message("Great! You're all set to upload. Uploaded videos may be subject to removal if they do not abide by the <a href='javascript:show_rules();'>rules</a>.");
	
	data = JSON.decode(data);
	
	var url = data[1];
	var ticket_id = data[0]; 
	console.log(url);
	// Uploader instance
	swf_uploader = new Swiff.Uploader({
		path: 'assets/javascript/Swiff.Uploader.swf',
		url: url,
		verbose: false,
		queued: false,
		multiple: false,
		width: 200,
		target: $('upload_btn'),
		instantStart: false,
		//typeFilter: {
		//	'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
		//},
		//fileSizeMax: 2 * 1024 * 1024,
		onSelectSuccess: function(files) {
			$('close_btn').hide();
			if (Browser.Platform.linux) 
				window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
			this.setEnabled(false);
			this.start();
		},
		onFileProgress: function(files) {
			console.log('test1');
			$('upload_btn').value = 'Uploading ' + files.progress.percentLoaded + '%';
		},
		onSelectFail: function(files) {
			console.log('test2');
		},
		appendCookieData: true,
		onQueue: false,
		onFileComplete: function(file) {
			console.log('test3');
			if (file.response.error) {
				set_scene_message('Uploading <em>' + this.fileList[0].name + '</em> failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
			} else {
				set_scene_message('Finished uploading!');
			}
			
			upload_finish(ticket_id);
 
			file.remove();
		},
		onComplete: function() {
		}
	});
	r2d2.redraw();
}

function load_thumbs() {
	if( page_touched ) {
		page_touched = false;
		for(var i = 1; i <= thumb_list.length; i++) {
			if(thumb_list[i - 1]) {
				var c = $('chunk_' + i);
				
				if( c.getPosition().y > window.getScrollTop() && c.getPosition().y < window.getScrollTop() + window.getHeight()) {
					if (c.getStyle('background') == '')
						c.setStyle('background', "url('" + thumb_list[i - 1] + "')");
					thumb_list[i - 1] = false;
				}
			}
		}
	}
}