$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

$.fn.setButtonIcon = function(icon) {
	if ( $(this).hasAttr("data-icon") == false){
		$(this).addClass('ui-btn-icon-left');
		$(this).attr('data-icon', icon);
		$(this).children('span:first').append($('<span>').attr('class', 'ui-icon ui-icon-check ui-icon-shadow'));
	}
};


function save_object(name, obj){
	localStorage.setItem(name, JSON.stringify(obj));
}

function load_object(name){
	return JSON.parse(localStorage.getItem(name));
}

function remove_object(name){
	localStorage.removeItem(name);
}


function get_current_team(){
	return load_object('teams')[load_object('current_team_id')];
}

var colors = ['green', 'red', 'blue', 'black', 'brown', 'magenta', 'orange', 'yellow'];


function Team(){
	this.id = null;
	this.name = null;
	this.color = null;
	this.score = 0;
}
Team.prototype.toString = function(){
	return this.name == null ? 'Team ' + this.id : this.name;
}
Team.prototype.toHtml = function(){
	return $('<div>').append($('<span>').html(this.toString())
		.css({'color': colors[this.id], 'font-weight':'bold'})).html();
}

function WordPack(){
	this.id = null;
	this.verbose = null;
}

function Game(){
	this.teams = [];
	this.wordpacks = [];
	this.words = [];
	this.moves_count = 40;
	this.secs_per_move = 60;
	this.current_team = null;
}

function GameTurn(){
	this.team = null;
	this.skipped_words = [];
	this.guessed_words = [];
}

var game = new Game();
var gameTurn = new GameTurn();

var gameSetupView = (function(){
	function init(){
		$.each(game.teams, function(i, team){
			team.score = 0;
		});
	}
	return {
		init: init
	};
	
})();

var teamsView = (function(){
	function init(){
		$('#list-teams').html($('#list-teams-last'));
	    if (game.teams.length == 0){
	    	this.add_team();
	    	this.add_team();
	    }
	    else{
	    	$.each(game.teams, function(i, team){
	    		$('#list-teams-last').before(
	    			$('<li>')
	    				.attr({id: 'team-entry-' + i, 'class': 'team-entry'})
						.append($('<div>')
							.attr({'data-role': 'fieldcontain'})
							.append($('<span>')
	    						.css('background-color', team.color)
	    						.html(team.id))
	    					.append($('<input>')
	    						.attr({value: team.name, type: 'text', name: 'name'}))
						)
				);
	    		$('#team-entry-' + i).page();
	        });
	    	//$('#list-teams').listview("refresh");
	    }
	}
	function add_team(){
		var teams_num = $('#list-teams').children().size() - 1;
		$('#list-teams-last').before($('<li>')
			.attr({'class': 'team-entry textBoxLI'})
			.append(
		        $('<input>')
		    	.css({'color': colors[teams_num], 'font-weight': 'bold'})
	          	.attr({id: 'team-entry-' + teams_num, placeholder: 'Team ' + (teams_num + 1), type: 'text'}).textinput()
			));
		$('#list-teams').listview("refresh");
		$('#list-teams').find('input[type=text]').blur();
		$('#team-entry-' + teams_num).focus();
	}
	function reset(){
		$('#list-teams').html($('#list-teams-last')).listview('refresh');
		this.add_team();
		this.add_team();
		$('#team-entry-0').focus();
	}
	function save_teams(){
		game.teams = [];
		$.each($('#list-teams').children('.team-entry'), function(i, team_node){
			var team = new Team();
			team.id = i;
			team.name = $('#team-entry-' + i).val() || 'Team ' + (i + 1);
			team.color = colors[i];
			team.score = 0;
			game.teams.push(team);
		});
		
		$('#button-show-teams').setButtonIcon('check');
		$.mobile.changePage('#page-game-setup');
	}
	return {
		init: init,
		save_teams: save_teams,
		reset: reset,
		add_team: add_team};
})();


var wordpackView = (function(){
	function done(){
		$.mobile.changePage('#page-game-setup');
		var wordPack = new WordPack();
	    wordPack.id = 'RU_GENERAL';
	    wordPack.verbose = 'Russian demo wordpack';
	    game.wordpacks.push(wordPack);
	    $('#button-show-wordpack').setButtonIcon('check');
	    $.mobile.changePage('#page-game-setup');
	}
	return {
		done: done
	}
})();

var settingsView = (function(){
	function done(){
		game.moves_count = $('#id_moves').val();
	    game.secs_per_move = $('#id_secs_per_move').val();
	    $('#button-show-settings').setButtonIcon('check');
	    $.mobile.changePage('#page-game-setup');
	}
	return {
		done: done
	}
})();

function check_settings(){
    // check if all settings are ok
    if (game.teams.length == 0){
    	// TODO: alert
    	alert("Select teams!");
    	return false;
    }
    if (game.wordpacks.length == 0){
    	alert("Select wordpack!");
    	return false;
    }
    
    $.mobile.changePage('#page-confirm', { transition: "pop" });
}

var confirmSettingsView = (function(){
    function init(){
    	clear();
		$.each(game.teams, function(i, team){
	        $('#confirm-dialog-list-teams').append(team.toHtml());
	        if (i < game.teams.length - 1 ){
	        	$('#confirm-dialog-list-teams').append(', ');
	        }
	    });
		
	    $('#confirm-dialog-wordpack').html(game.wordpacks[0].verbose);
	    $('#confirm-dialog-moves').html(game.moves_count);
	    $('#confirm-dialog-secs-per-move').html(game.secs_per_move);
    }
    function clear(){
    	$('#confirm-dialog-list-teams').html('');
    }
    return {init: init};
    
})();

function load_words(wordpack, word_num, callback){
	var url = '/get_demo_words/' + wordpack + "/" + word_num
	$.get(url , {}, callback);
	return false;
}

function start_game(){
	var word_num = game.moves_count * game.teams.length;
	var wordpack = game.wordpacks[0].id;
	load_words(wordpack, word_num, function(response) {
        if (response.isOk){
          game.words = response.words;
          $.mobile.changePage($('#page-team-ready'));
        }
        else{
          alert('Failed to load words. Please try again later.');
        }
      }
    );
    return false;
}

var teamReadyView = (function(){
	function init(){
		// load more words if needed
		if (game.words.length < game.secs_per_move / 5){
			var word_num = game.moves_count * game.teams.length;
			load_words("RU_GENERAL", word_num, function(response){
				if (response.isOk){
			        game.words.push.apply(game.words, response.words);
			    }
			    else{
			    	alert('Failed to load words. Please try again later.');
			    }
			});
		}
		
		if (game.current_team != null){
	        game.current_team = game.teams[(game.current_team.id + 1) % game.teams.length];
	    }
	    else {
	    	game.current_team = game.teams[0];
	    }
		gameTurn = new GameTurn();
		gameTurn.team = game.current_team;
	    /*$('#team-ready-button-ok').html($('<span class="ui-btn-inner ui-btn-corner-all">')
	    	.append($('<span class="ui-btn-text">').html(game.current_team.toHtml() + ' ready!')).html());*/
			
		$('#team-ready-button-ok').html('<span class="ui-btn-inner ui-btn-corner-all"><span class="ui-btn-text">'+ game.current_team.toHtml() + ' go!</span></span>');
	    
	    // show teams' scores	    
	    $('#teams-scores').html("");
		$.each(game.teams, function(i, team){
			$('#teams-scores').append($('<div class="listItem-c ui-btn-corner-all">').append($('<span>')
				.css("color", team.color)
				.html(team.name))
				.append($('<span>')
					.attr({"style":"float:right"})
					.html(team.score + " / " + game.moves_count)));
		});
		//$('#teams-scores').listview("refresh");
	}
	return {
		init: init,
	}
})();

var cardView = (function(){
	var current_word;
	var secs_passed;
	var timer;
	function init(){
		current_word = game.words.pop(0);
		secs_passed = 0;
		$('#team-name').html(gameTurn.team.name);
		$('#card-word').html(current_word);
		__update_score();
		
		// set timer
	    timer = setInterval(tick, 1000 );
	}
	function tick(){
		secs_passed += 1;
		var secs_left = game.secs_per_move - secs_passed;
		var time_str;
		if (secs_left <= 0){
			time_str = "00:00";
		}
		else {
			var mins = Math.floor(secs_left / 60) + '';
			mins = mins.length == 2 ? mins : "0" + mins;
			
			var secs = (secs_left % 60) + '';
			secs =  secs.length == 2 ? secs : "0" + secs;
			time_str = mins + ":" + secs;
		}
	    $('#card-timer .ui-btn-text').html(time_str);
	}
	function hide(){
		clearInterval(timer);
	}
	function pause(){
		// reset round score
		gameTurn.team.score -= gameTurn.guessed_words.length - gameTurn.skipped_words.length;	
		
		// set previous team
		if (game.current_team.id > 0){
			game.current_team = game.teams[(game.current_team.id - 1)];
		}
		else{
			game.current_team = game.teams[(game.teams.length - 1)];
		}
	}
	function next_word(){
		gameTurn.team.score++;
		gameTurn.guessed_words.push(current_word);
		__next();
	}
	function skip_word(){
		gameTurn.team.score--;
		gameTurn.skipped_words.push(current_word);
		__next();
	}
	function __next(){
		// team wins
		if (gameTurn.team.score >= game.moves_count){
	    	$.mobile.changePage('#page-winner', { transition: "pop" });
	    }
		
		__update_score();
		
		if (secs_passed < game.secs_per_move){
			if (game.words.length == 0){
				// load more words if needed
				load_words();
			}
			current_word = game.words.pop(0);
		    $('#card-word').html(current_word);
		}
		else {
			$.mobile.changePage('#page-turn-summary', { transition: "pop" });
		}
		return false;
    }
	function __update_score(){
		$('#team-score').html(gameTurn.team.score + " / " + game.moves_count);
	}
	return {
		init: init,
		next_word: next_word,
		skip_word: skip_word,
		pause: pause,
		hide: hide
	}
})();

var turnSummaryPage = (function(){
	function show(){
		clear();
		$('#turn-summary-heading').html(gameTurn.team.toString());
		
	    $('#turn-summary-score-1').html('Round Score: ' + (gameTurn.guessed_words.length - gameTurn.skipped_words.length));
	    $('#turn-summary-score-2').html('Total Score: ' + gameTurn.team.score);
	    
	    if (gameTurn.guessed_words.length > 0){
		    $('#turn-summary-guessed-words').html('Guessed words: (' + gameTurn.guessed_words.length + '): ');
		    $.each(gameTurn.guessed_words, function(i, word){
		    	$('#turn-summary-guessed-words').append(word);
		    	if (i < gameTurn.guessed_words.length - 1){
		    		$('#turn-summary-guessed-words').append(', ');
		    	}
		    });
	    }
	    
	    if (gameTurn.skipped_words.length > 0){
			$('#turn-summary-skipped-words').html('Skipped words: (' + gameTurn.skipped_words.length + '): ');
		    $.each(gameTurn.skipped_words, function(i, word){
		    	$('#turn-summary-skipped-words').append(word);
		    	if (i < gameTurn.skipped_words.length - 1){
		    		$('#turn-summary-skipped-words').append(', ');
		    	}
		    });
	    }
	}
	function clear(){
		$('#turn-summary-heading').html('');
		$('#turn-summary-score').html('');
		$('#turn-summary-guessed-words').html('');
		$('#turn-summary-skipped-words').html('');
	}
	return {show: show};
})();

var winnerView = (function(){
	function init(){
		$('#page-winner .winner').html(gameTurn.team.toString());
	}
	return {
		init: init
	};
})();


function max_height(){
    var header = $('div[data-role="header"]:visible');
    var footer = $('div[data-role="footer"]:visible');
    var content = $('div[data-role="content"]:visible');
    var viewport = $(window);
    var content_height = viewport.height() - header.outerHeight() - footer.outerHeight();
    content_height -= (content.outerHeight() - content.height());
    content.height(content_height);
    
	var word = $('#card-word');
	var top = content.height() / 2 - word.outerHeight() / 2;
	$('#card-word').css({ position: "absolute", top: top + "px", left: "0"});
}

var fixgeometry = function() {
    scroll(0, 0);
    var header = $('div[data-role="header"]:visible');
    var footer = $('div[data-role="footer"]:visible');
    var content = $('.fullScreen');
    var viewport = $(window);
    var contentHeight = viewport.height() - header.outerHeight() - footer.outerHeight();
    contentHeight -= (content.outerHeight() - content.height());
    content.height(contentHeight-2);
    content.width(viewport.width()-2);
};

