/* variables */
wortopia_timedifference = 0;
wortopia_currentField = '';
wortopia_nextField = '';
/* times */
wortopia_ROUNDTIME = 180;
wortopia_PAUSE = 30;
wortopia_RESULTTIMERANDOM = 3;
wortopia_PRELOADTIME = 10;
wortopia_PRELOADTIMERANDOM = 10;
wortopia_CHATRELOADTIME = 2;
/* status */
wortopia_ISGAME = 1;
wortopia_ISPAUSE = 2; 
wortopia_status = 0;
/* chat */
wortopia_lasttime_chat=false; // far far away future





/* internal clock */ 
function wortopia_getTime() {
	var now = new Date();
	return Math.round((now.getTime() + wortopia_timedifference) / 1000);
}

function wortopia_initTime() {
	wortopia_load('time');
}

function wortopia_callback_time(time) {
	var now = new Date();
	wortopia_timedifference = time - now.getTime();	
	wortopia_init_manager();
}

function wortopia_getGameTime() {
	return wortopia_getTime() % (wortopia_ROUNDTIME + wortopia_PAUSE);
}

function wortopia_getGameId() {
	return Math.floor(wortopia_getTime() / (wortopia_ROUNDTIME + wortopia_PAUSE));
}

/* internal event manager */

function wortopia_init_manager() {
	wortopia_tick();
	window.setInterval("wortopia_tick()", 500);
	if (wortopia_getGameTime() < wortopia_ROUNDTIME) {
		wortopia_getCurrentField();
	}
	else
	{
		if (wortopia_getGameTime() < wortopia_PRELOADTIME + wortopia_ROUNDTIME) {
			window.setTimeout("wortopia_trigger_loadNextField()", (wortopia_PRELOADTIME + wortopia_ROUNDTIME - wortopia_getGameTime()) * 1000);
		}
		else
		{
			wortopia_trigger_loadNextField();
		}
		 
	}	
	wortopia_getResults();
}

function wortopia_tick() {
	if (wortopia_getGameTime() < wortopia_ROUNDTIME) {
		if(typeof wortopia_external_tick_game == 'function') 
			wortopia_external_tick_game(wortopia_ROUNDTIME - wortopia_getGameTime());
			
		if (wortopia_status != wortopia_ISGAME) {
			wortopia_trigger_start()
			wortopia_status = wortopia_ISGAME;
		}		
	}
	else
	{
		if(typeof wortopia_external_tick_pause == 'function') 
			wortopia_external_tick_pause(wortopia_ROUNDTIME + wortopia_PAUSE - wortopia_getGameTime());
		if (wortopia_status != wortopia_ISPAUSE) {
			wortopia_trigger_pause()
			wortopia_status = wortopia_ISPAUSE;
		}	
	}
		
}

function wortopia_trigger_start() {
	if(typeof wortopia_external_start == 'function') 
		wortopia_external_start();
		
	if (wortopia_nextField != '') {
		wortopia_currentField = wortopia_nextField;
		wortopia_nextField = '';
		wortopia_setField(wortopia_currentField);
	} 
	else
	{
		window.setTimeout("wortopia_getCurrentField()", 1000);
		
	} 
}

function wortopia_trigger_pause() {
	if(typeof wortopia_external_pause == 'function') 
		wortopia_external_pause();
	window.setTimeout("wortopia_getResults()", wortopia_getRandom(0, wortopia_RESULTTIMERANDOM*1000));
	window.setTimeout("wortopia_trigger_loadNextField()", wortopia_getRandom(wortopia_PRELOADTIME*1000, (wortopia_PRELOADTIME + wortopia_PRELOADTIMERANDOM)*1000));
}

function wortopia_trigger_loadNextField() {
	wortopia_getNextField();
}

/* username */
function wortopia_setUsername(username) {
	wortopia_load('setUsername', 'username='+username);
}

function wortopia_setTeamname(teamname) {
	wortopia_load('setTeamname', 'teamname='+teamname);
}

function wortopia_getUsername() {
	wortopia_load('getUsername');
}

function wortopia_callback_getUsername(username) {
	alert(username);
}

/* field */

function wortopia_getCurrentField() {
	if (wortopia_currentField == '')
		wortopia_load('getCurrentField','size='+wortopia_size);
}

function wortopia_callback_getCurrentField(field) {
	wortopia_currentField = field;
	wortopia_setField(field);
}

function wortopia_getNextField() {
	wortopia_load('getNextField','size='+wortopia_size);
}

function wortopia_callback_getNextField(field) {
	wortopia_nextField = field;
}

function wortopia_setField(field) {
	/* calling external function */
	if(typeof wortopia_external_setField == 'function')
		wortopia_external_setField(field)
}

/* results */

function wortopia_getResults() {
	wortopia_load('getResults','size='+wortopia_size);
}

function wortopia_callback_getResults(result){
	if(typeof wortopia_external_getResults == 'function')
		wortopia_external_getResults(result);
}

/* chat */
function wortopia_init_chat() {
	wortopia_chat();
	window.setInterval("wortopia_chat()", wortopia_CHATRELOADTIME*1000);
}

function wortopia_chat(message, team) {
	if (!message) {
		wortopia_load('chat',(wortopia_lasttime_chat?'last='+wortopia_lasttime_chat+'&':'')+'size='+wortopia_size+'');
	}
	else
	{
		wortopia_load('chat',(wortopia_lasttime_chat?'last='+wortopia_lasttime_chat+'&':'')+'size='+wortopia_size+(team?'&team=1':'')+'&message='+message);
	}
}

function wortopia_callback_getChat (chat, last) {
	wortopia_lasttime_chat = last;

	for (var i = 0; i < chat.length; i++) {
		msg = chat[i];
		if (msg.isServer) {
			wortopia_external_addChatMessage(msg.time, true, false, '', '', msg.message);
		}
		else
		{
			wortopia_external_addChatMessage(msg.time, false, msg.isTeam, msg.userId, msg.username, msg.message);
		}
	}
}

function wortopia_write_chat_message(message) {
	wortopia_getChat(message);
}



/*function wortopia_callback_getChat(result){
	
	if (typeof wortopia_external_addChatMessage == 'function') {
		wortopia_external_addChatMessage(false, false, 'wo1', 'Marek Ventur', 'Nachricht');
	}	
}*/

/* guess */

function wortopia_guess(word, wordId) {
	wortopia_load('guess','size='+wortopia_size+'&word='+word+'&wordId='+wordId);
}

function wortopia_callback_guess(wordId, status, points, sumPoints, comment) {
	if(typeof wortopia_external_guess == 'function')
		wortopia_external_guess(wordId, status, points, sumPoints, comment);
}

/* find */

function wortopia_checkWord(word) {
	if (wortopia_getGameTime() > wortopia_ROUNDTIME) 
		return false;
	
	var result; 
	
	word = word.toUpperCase();
	
	Outer: for (y=0; y<wortopia_size; y++) 
		for (x=0; x<wortopia_size; x++) {
			result = new Array();
			result2 = _wortopia_recursive(wortopia_currentField, word, result, x, y);
			if (result2) {
				result = result2;
				break Outer;
			}	
		}
	
	return result;
		
}

function _wortopia_recursive(iNowField, iNowWord, iNowChain, x, y) {
	
	// Work with copies!
	var nowWord = iNowWord+'';
	var nowField = iNowField+'';
	var nowChain = new Array();
	for (i=0;i<iNowChain.length;i++)
		nowChain.push(iNowChain[i]);
	
	if ((x < 0) || (y < 0) || (x >= wortopia_size) || (y >= wortopia_size)) return false;
	//if ($.browser.mozilla) console.log(nowWord+ ' '+ nowField+ ' '+x+' '+y);
	
	if (nowWord == '') {
		return nowChain;
		//if ($.browser.mozilla) console.log('word = "", so ok');
	}
	else
	{
		if (nowField.charAt(y * wortopia_size + x) != nowWord.charAt(0)) {
			//if ($.browser.mozilla) console.log('char '+nowField.charAt(y * wortopia_size + x)+'!='+nowWord.charAt(0));
		
			return false;
		}
		else
		{
			nowChain.push({"x":x, "y":y});
			nowField = wortopia_setCharAt(nowField, y * wortopia_size + x, '#');
			nowWord = nowWord.substr(1);
			//if ($.browser.mozilla) console.log('->'+nowWord+ ' '+ nowField);
			
			result = _wortopia_recursive(nowField, nowWord, nowChain, x+1, y);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x+1, y+1);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x, y+1);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x-1, y+1);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x-1, y);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x-1, y-1);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x, y-1);
			if (result) return result;
			result = _wortopia_recursive(nowField, nowWord, nowChain, x+1, y-1);
			if (result) return result;
			
			return false;
		}
	}
}


// Helpers
function wortopia_load(url,data) {
	if (!data) data = '';
	/*
	if (data != '') data += '&';

	$.ajax({
		url:wortopia_HOST+url,
		dataType:'jsonp',
		data: 'userId='+wortopia_userId+'&'+data+"randId="+randId
	});
	*/
	if (data == '') 
		addScript(url+'?userId='+wortopia_userId);
	else
		addScript(url+'?userId='+wortopia_userId+'&'+data);	
	
}
function deleteScript(id) {
	document.getElementsByTagName('head')[0].removeChild(document.getElementById(id));
}
function addScript(url, data) {
		//alert(wortopia_HOST);
		var randId = wortopia_getRandom(0, 999999);
		//alert(wortopia_HOST+url + "&randId=" + randId);
		if (jQuery) {
			$.ajax({
				'url':wortopia_HOST+url + "&randId=" + randId,
				'data':data,
				'dataType':'script'
			});
		}
		else 
		{
			
			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = wortopia_HOST+url + "&randId=" + randId;
			script.id = 'script_load_' + randId;
			script.onload = function(){
				setTimeout('deleteScript(\'script_load_' + randId + '\')', 2000);
			}
			document.getElementsByTagName('head')[0].appendChild(script);
		}

}


function wortopia_setCharAt(str,index,chr) {
	if(index > str.length-1) return str;
	return str.substr(0,index) + chr + str.substr(index+1);
}

function wortopia_getRandom(min, max) {
	if( min > max ) {
		return( -1 );
	}
	if( min == max ) {
		return( min );
	}
	return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}


