/**
* @author gabriel
*/

var MYID = null;
var MYIDNUM = null;
var MYDBID = null;
var ALLAVS = new Array();
var MYAV = null;
var USERPREFS = {};	
var FBCONNECTION;

var OTHERID = null;


var avleft = false;
var avright = false;
var avkeyup = false;
var avcanup = true;


var lJWSID = "jWebSocket Client Gaming",
lWSC = null,
eLog = null,
eUsername = null,
ePool = null,
eMessage = null,
eDebug = null,
eKeepAlive = null;

var IN = 0;
var OUT = 1;
var EVT = 2;
var SYS = "SYS";
var USR = null;

/*********   log   ********/

function log( aUsername, aEvent, aString ) {
	var lFlag;
	switch( aEvent ) {
		case IN: lFlag = "<"; break;
		case OUT: lFlag = ">"; break;
		case EVT: lFlag = "*"; break;
		default: lFlag = "?";
	}
	if( !aUsername ) {
		aUsername = lWSC.getUsername();
	}
	if( !aUsername ) {
		aUsername = "USR";
	}
	eLog.innerHTML +=
		aUsername + " " +
		lFlag + " " +
		aString + "<br>";
	if( eLog.scrollHeight > eLog.clientHeight ) {
		eLog.scrollTop = eLog.scrollHeight - eLog.clientHeight;
	}
}

function clearLog() {
	eLog.innerHTML = "";
	eLog.scrollTop = 0;
}

function doFocus( aElement ) {
	aElement.focus();
	aElement.select();
}

function connect() {

	function login() {
		var lUsername = eUsername.value;
		var lRes = lWSC.login( lUsername, "", "" );
	}

	// if already connected  --> re-login...
	if( lWSC.isConnected() ) {
		login();
		return;
	}

	var lURL = jws.JWS_SERVER_URL + "/;prot=json,timeout=300000"; //120000
	
	lWSC.open( lURL, {
		OnOpen: function( aEvent ) {
			login();
			checkKeepAlive({ immediate: false });
		},

		OnMessage: function( aEvent, aToken ) {
			if( aToken ) {
				if( aToken.type == "response" ) {
					if( aToken.reqType == "login" ) {
						if( aToken.code == 0 ) {
							lWSC.getAuthClients({
								pool: null
							});
						} else {
							doFocus( eUsername );
						}
					} else if( aToken.reqType == "getClients" ) {
					}
				} else if( aToken.type == "event" ) {
				} else if( aToken.type == "goodBye" ) {
					doFocus( eUsername );
					
				} else if( aToken.type == "broadcast" ) {
				}
			}
		},

		OnClose: function( aEvent ) {
			lWSC.stopKeepAlive();
			doFocus( eUsername );
		}

	});
}

function disconnect() {
	lWSC.stopKeepAlive();
	var lRes = lWSC.close({
		timeout: 3000
	});
	log( SYS, OUT, "logout: " + lRes.msg );
}

function checkKeepAlive( aOptions ) {
	if( !aOptions ) {
		aOptions = {};
	}
	aOptions.interval = 30000;
	if(eKeepAlive != null)
	{
		if( eKeepAlive.checked ) {
			lWSC.startKeepAlive( aOptions );
		} else {
			lWSC.stopKeepAlive();
		}
	}
}

function usrKeyDnLsnr( aEvent ) {
	if( aEvent.keyCode == 13 ) {
		connect();
	}
}

var player = {
	loc_x: 750,
	loc_y: 40,
	speed: 10
};

function initPage() {
	
	eLog = jws.$( "sdivChat" );
	eUsername = jws.$( "stxfUsername" );
	eDebug = jws.$( "schkDebug" );
	eKeepAlive = jws.$( "schkKeepAlive" );

	if( jws.browserSupportsWebSockets() ) {

		lWSC = new jws.jWebSocketJSONClient();

		initAvatarEvents();
		
		connect();
	} else {
		jws.$( "sbtnLogin" ).setAttribute( "disabled", "disabled" );
		jws.$( "sbtnLogout" ).setAttribute( "disabled", "disabled" );
		jws.$( "sbtnClearLog" ).setAttribute( "disabled", "disabled" );

		eDebug.setAttribute( "disabled", "disabled" );
		eKeepAlive.setAttribute( "disabled", "disabled" );
		eUsername.setAttribute( "disabled", "disabled" );

		var lMsg = jws.MSG_WS_NOT_SUPPORTED;
		alert( lMsg );
		log( SYS, IN, lMsg );
	}
	
}

function exitPage() {
	if( lWSC ) {
		$.ajax({
			type: "POST",
			url: "assets/avatarUpdateMe.php",
			data: "t=2&id=" + MYDBID,
		});
		
		lWSC.close({ //lWSC.disconnect({
			timeout: 0
		});
	}
}

function initAvatarEvents()
{
	$(document).everyTime(300, function(){
		avMoveHandler();
	})
	
	$(".avinfoopen").live("click", function(){
		avInfoSetPlayerid($(this).attr("playerid"))
	})
	
	$(window).unload(function() {
		exitPage();
	}).bind("beforeunload", function() {
		exitPage();
    });

	
	
	/*$(".av").live("mouseover", function(){
		avMouseOver($(this).attr("id"))
	}).live("mouseout", function(){
		avMouseOut($(this).attr("id"))
	})*/
	$(document).keydown(function(e){
		if (e.keyCode == '37') {
			e.preventDefault();
			if(!avleft) avMoveHandler()
			avleft = true;
		}
		if (e.keyCode == '39') {
			e.preventDefault();
			if(!avright) avMoveHandler()
			avright = true;
		}
		if (e.keyCode == '38') { //hoch
     		e.preventDefault();
			avkeyup = true;
			if(avkeyup && avcanup){
		         avcanup = false;
		         MYAV.animate({
		             bottom: 80
		         }, 80).animate({
		             bottom: 59
		         }, 80, function(){
		             avcanup = true;
		         })
			 }
   		}
		
		if(e.keyCode == '32') //Leertaste
		{
     		//e.preventDefault();
			/*var t = 0;
			//alert( "-> "+ lWSC.players["1234"] )
			for( var lId in lWSC.players) {
					t++
				}
			$("#output").append("<br>+++ " + t)*/
		}
	}).keyup(function(e){
		if (e.keyCode == '37') {
     		e.preventDefault();
			avleft = false;
			avMoveHandler()
   		}
		if (e.keyCode == '39') {
     		e.preventDefault();
			avright = false;
			avMoveHandler()
   		}
		if (e.keyCode == '38') { //hoch
     		e.preventDefault();
			avkeyup = false;
   		}
	})
}

function avMoveHandler()
{	
	var newX = 0;
		if (avright && avcanup) {
			newX = MYAV.position().left + 50;
			if(newX > catPositions[4] + $(window).width()/2) newX = catPositions[4] + $(window).width()/2;
			lWSC.broadcastGamingEvent({
				left: newX
			});
			moveAvatare(MYIDNUM, newX);
		}
		if (avleft && avcanup) 
		{	
			newX = MYAV.position().left - 50;
			if(newX < 100) newX = 100;
			lWSC.broadcastGamingEvent({
				left: newX
			});
			moveAvatare(MYIDNUM, newX);
		}
		/*if (!avright && !avleft) {
			myAv.stop().children(".av_footlst").stop().parent().children(".av_footrst").stop().parent().children(".av_arm").stop().parent().children(".av_head").stop();
			if(ALLAVS[thisId][0] != undefined && ALLAVS[thisId][1] != undefined)
			{
				lWSC.broadcastGamingEvent({
					left: myAv.position().left
				});
			}
		}*/
		
		
		 
}

function moveAvatare(pid, x, speed)
{
	pid = "#player"+pid
	var thisAv = $(pid);
	
	//$("#output").append("|");
	if(thisAv.position() != null)
	{
		if(thisAv.position().left > x && $(pid +" .avbody").css("scaleX") != -1)
		{
			$(pid +" .avbody").css({scaleX: -1,"margin-left":25});
		} 
		else if(thisAv.position().left < x && $(pid +" .avbody").css("scaleX") != 1)
		{
			$(pid +" .avbody").css({scaleX: 1,"margin-left":0});
		}
		
		$(pid +" img:nth-child(5),"+pid +" img:nth-child(1)").css({display:"none"})
		$(pid +" img:nth-child(6),"+pid +" img:nth-child(2)").css({display:"inline"})
		
		
		thisAv.stop().animate({left: x}, speed, "linear", function(){
			$(pid +" img:nth-child(5),"+pid +" img:nth-child(1)").css({display:"inline"})
			$(pid +" img:nth-child(6),"+pid +" img:nth-child(2)").css({display:"none"})
		})
	}
		
}

function movecatAvatar(pid, moveleft)
{
	pid = "#player"+pid;
	var thisAv = $(pid);
	
	thisAv.stop().animate({
		"margin-bottom": 30 + Math.random() * 70
	}, 200).animate({
		left:  moveleft
	}, 500).animate({
		"margin-bottom": 0
	}, 200);
}


/*************** AV message handling *****************/

function avSendMessage()
{
	var str = noBadWords ( $("#avinputform").attr("value") );
	$("#avinputform").attr("value", "")
	
	
	/** validieren **/
	lWSC.broadcastGamingEvent({
		mes: str
	});
	$("#avinputform").stopTime().oneTime(8000, function() {
		avClearMessage();
	});
}

function avClearMessage()
{
	lWSC.broadcastGamingEvent({
		mes: " "
	});
	if($("#"+MYID +" .av_popup div:nth-child(2) p:nth-child(1)").text() != " ")
	{
		$("#avinputform").stopTime().oneTime(8000, function() {
			avClearMessage();
		});
	} else {
		$("#avinputform").stopTime();
	}
}


function avBroadcastMessage(id,mes)
{
	$("#player"+id +" .av_popup div:nth-child(2) p:nth-child(1)").html(
		$("#player"+id +" .av_popup div:nth-child(2) p:nth-child(2)").text()
	)
	$("#player"+id +" .av_popup div:nth-child(2) p:nth-child(2)").html(
		$("#player"+id +" .av_popup div:nth-child(2) p:nth-child(3)").text()
	)
	$("#player"+id +" .av_popup div:nth-child(2) p:nth-child(3)").html(
		mes
	)
}



/*************** AV MouseOver / Out *****************/


function avMouseOver(id)
{
	$("#"+id+" a img").css({
		opacity: 1
	}).parent().css({
		color: "#ffffff",
		backgroundColor: "#2BB1FF"
	})
}
function avMouseOut(id)
{
	$("#"+id+" a img").css({
		opacity: .5
	}).parent().css({
		color: "#808080",
		backgroundColor: "black"
	})
}








/************************ Update Avatar Prefs ********************/


function updateAvatar(id)
{
	$.ajax({
		type: "POST",
		url: "assets/avatarLoadUserPrefs.php",
		data: "playerid=" + id,
		success: function(data){
			//$("#output").append("<br>!!!!");
			var avprefs = jQuery.parseJSON(data);
			$("#player"+id + " .avnamelabel").html( converUmlaute(avprefs.name) )
			$("#player"+id + " .av_feet").attr("src", "images/avatare/feet/feet_"+avprefs.foot+".png")
			$("#player"+id + " .av_feet_ani").attr("src", "images/avatare/feet/feet_"+avprefs.foot+"_ani.gif")
		
			var avbody = [
						{ "x": "7", "y": "9", "src":"images/avatare/heads/heads_"+avprefs.head+".png" },
						{ "x": "1", "y": "31", "src":"images/avatare/body_"+avprefs.sex+"/body_"+avprefs.sex+"_"+avprefs.body+".png" },
						{ "x": "13", "y": "14", "src":"images/avatare/beards/beards_"+avprefs.beard+".png" },
						{ "x": "19", "y": "18", "src":"images/avatare/glasses/glasses_"+avprefs.glasses+".png" },
						{ "x": "0", "y": "0", "src":"images/avatare/hair/hair_"+avprefs.hair+".png" }
					]
			lWSC.drawPlayerBody("player"+id, avbody)
		}
	});
}

function converUmlaute(str)
{
	var umlaut = new Array("ö", "ä", "ü");
	var umlautersatz = new Array("ö", "ä", "ü");
	var s = " sds";
	for(var i = 0; i < umlaut.length; i++)
	{
		str = str.replace(umlaut[i], umlautersatz[i])
	}
	//var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');
      //  var replacement = '*'.repeat(filter[i].length); 
      //  txt = txt.replace(pattern, replacement);
	return str;
}




















/************ User Info *******************/

function avInfoSetPlayerid(id)
{
	OTHERID = id;
}









