var Mission = ( function ( $ ) {

	var tasks = {};
	var orderedTasks = [];
	var meta = {};
	var currentTask;
	var taskBoundaryCallback;

	$( function ( ) {
		var initialising = true;
		var last = window.location.hash.substr(1);
		$.history.init ( function ( hash ) {
			if ( initialising ) {
				initialising = false;
				return;
			}

			if ( hash == "start" ) {
				// this function is called before Safari updates, so do it manually...
				if ( $.browser.safari )
					document.location.hash = "start";
				window.location.reload(true);
				return false;
			}

			if ( currentTask && currentTask.get('label') == hash )
				return;

			var task = Mission.tasks(hash);
			if ( task ) {
				var previous = Mission.tasks(task.get('index')-1);
				if ( !previous || previous.completed() )
					task.setup(true);
				else if ( currentTask )
					$.history.load ( currentTask.get('label') );
				else
					window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search;
			} else {
				// TODO: do something on empty!
				window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search + "#start";
			}
		} );
	} );

	function play ( task ) {
		$.history.load ( task.get('label') );
		Events.subscribeOnce ( task, "end", function ( ) {
			var next = Mission.tasks(task.get('index')+1);
			if ( next ) {
				play ( next );
			} else {
				$("#tb_progress").addClass("finished").find("span span").css("width","100%");
				setTimeout ( function ( ) {
					Events.fire ( Mission, "end" );
					API.smokescreen.mission.end ( meta.index, function ( ) {
						var m = Portal.showMessage ( '<div id="portal_end_card"></div>', null, true );
						m.container.parent().parent().css ( "display", "none" );
						Portal.loadPage ( null, './endcard/', null, function ( ) {
							m.container.parent().parent().css ( "display", "" );
							$('#portal_end_card a.ss_replay').click ( function ( ) {
								$.history.load ( "start" );
								return false;
							} );
						}, 'portal_end_card', true );
					} );
				}, 2500 );
			}
		} );
	}

	API.smokescreen.task.start.listen ( function ( rsp, data ) {
		currentTask = Mission.tasks(data.task_index);
	} );

	return {
		init : function ( md ) {
			delete Mission.init;
			meta = md;
		},
		extend : function ( model ) {
			for ( var item in model ) {
				if ( typeof model[item] == "function" ) {
					( function ( fn ) {
						Events.subscribe ( this, item, function ( ) {
							var args = Array.prototype.slice.call ( arguments, 0 );
							var cb = args.pop();
							fn ( cb );
							return true;
						} );
					} ).call ( this, model[item] );
				}
			}
		},
		setTasks : function ( t ) {
			delete Mission.setTasks;
			for ( var task in t ) {
				if ( t.hasOwnProperty ( task ) ) {
					orderedTasks[t[task].index] = task;
					tasks[task] = new Task ( t[task] );
				}
			}
		},
		get : function ( key ) {
			return meta[key];
		},

		start : function ( ep ) {
			Events.fire( this, "setup" );
			var task;
			if ( !(task = Mission.tasks(ep)) ) {
				// no entry point - need to show the start card, and get going 
				task = Mission.tasks(0);

				// showing start card
				var m = Portal.showMessage ( '<div id="portal_start_card"></div>', null, true );
				if ( $.browser.msie )
					m.container.parent().parent().css ( "visibility", "hidden" );
				else
					m.container.parent().parent().css ( "display", "none" );

				var sc_loaded = false;
				var sc_finish = function ( ) { };
				Portal.loadPage ( null, './startcard/', null, function ( ) {
					if ( $.browser.msie )
						m.container.parent().parent().css ( "visibility", "" );
					else
						m.container.parent().parent().css ( "display", "" );
					sc_loaded = true;
					sc_finish();
				}, 'portal_start_card', true );
				Events.subscribeOnce ( task, "loaded", function ( ) {
					setTimeout ( function ( ) {
						var btn = document.createElement("div");
						btn.appendChild ( document.createTextNode ( "Start Mission" ) );
						$(btn).click ( function ( ) {
							API.smokescreen.mission.start ( meta.index, function ( ) {
								m.close();
								play ( task );
							} );
						} );
						sc_finish = function ( ) {
							$("#portal_start_card .ss_loading").append ( btn );
						}
						if ( sc_loaded ) sc_finish();
					}, 1500 );
				} );
				task.setup(false);
			} else {
				API.smokescreen.mission.start ( meta.index, function ( ) {
					play ( task );
				} );
			}
		},
		fail : function ( message ) {
			Events.fire ( this, "fail" );

			$(document.body).removeClass("taskbar");
			$("#subtitles").hide();
			if ( window.SoundStage ) SoundStage.stop();
			if ( window.Chat ) Chat.stop();

			// give them a modal with the option to restart at any task
			var list = [];
			for ( var i = 0; i < Mission.length(); i ++ ) {
				var task = Mission.tasks(i);
				list.push ( task );
				if ( !task.completed() ) break;
			}
			if ( list.length <= 1 ) {
				//Mission.start ( null );
				$.history.load ( "start" );
			} else {
				var content = document.createElement('div');
				content.innerHTML = '<div><strong>You failed the task' + ( message ? ':<br>' + message : '' ) + '</strong><br>&mdash; do you want to pick a task to restart from?</div><hr>';
				var items = document.createElement('ul');
				items.className = "hud-options";
				content.appendChild ( items );
				
				for ( var i = 0; i < list.length; i ++ ) {
					var item = document.createElement('li');
					$(item).html("&bull; ").css({paddingLeft:'1em',textIndent:'-1em',lineHeight:'1.5em'});
					var link = document.createElement('a');
					link.href = "#" + list[i].get('label');
					link.className = "item";
					link.innerHTML = list[i].get('name');
					item.appendChild ( link );
					item.innerHTML += " - " + list[i].get('description');
					items.appendChild ( item );
				}
				
				content.innerHTML += "<hr>";
				var buttons = document.createElement('div');
				buttons.className = "hud-buttons";
				content.appendChild ( buttons );
				var btn = document.createElement('button');
				btn.className = "hud-button";
				$(btn).css({display:'block',width:'100%',position:'relative',left:'-10px'});
				btn.innerHTML = "<span><span>No, I'll just redo this task</span></span>";
				buttons.appendChild ( btn );
				var msg = Portal.showMessage ( content );
				$('a.item',msg.container)
					.css ( 'color', "#fff" )
					.click ( function ( e ) {
						var ep = this.getAttribute('href').substr(1);
						msg.close();
						$.cookie( 'skip_confirm_task', '1' );
						setTimeout ( function ( ) {
							window.location.reload();
						}, 10 );
						//return false;
					} );
				$(btn).click ( function ( ) {
					msg.close();
					$.cookie( 'skip_confirm_task', '1' );
					window.location.reload();
				} );
			}
		},

		tasks : function ( id ) {
			if ( id !== ""+id ) {
				// id is not a string
				if ( isNaN ( parseInt ( id ) ) ) return null;
				id = orderedTasks[id];
			}
			return tasks[id];
		},

		length : function ( ) {
			return orderedTasks.length;
		}
	}

} ) ( jQuery );

$(window).load ( function ( ) {
	Portal.findEntryPoint ( function ( ep ) {
		Mission.start ( ep );
	} );
} );
