


jws.ClientGamingPlugIn = {
	NS: jws.NS_BASE + ".plugins.clientGaming",
	
		
	addPlayer: function( left, id, avType ) {
		$("#output").append("+");
		//standard prefs
		var obj = {
				name: "User",
				age: "Noch nicht angeben",
				about: "Noch nicht angeben",
				id: id,
				sex: "m",
				fb: "",
				foot: 1,
				body: 1,
				head: 1,
				beard: 1,
				glasses: 1,
				hair: 1
			};
			
		if (avType == "me") this.userHandlerMe(left, id, avType, obj , true);
		if(avType == "them")
		{
			$.ajax({
				type: "POST",
				url: "assets/avatarLoadUserPrefs.php",
				data: "playerid=" + id,
				success: function(data){
					//$("#output").append(">> "+ id+" >>"+ data)
					if(data != "") obj = jQuery.parseJSON(data);
					lWSC.addPlayerFinish( left, id, avType , obj);
				}
			});
		}
		
	},
	
	userHandlerMe: function(left, id, avType , obj , tryCookie)
	{
		$("#output").append("...... ")
		if(tryCookie) /////// already account
		{
			$.ajax({
				type: "POST",
				url: "assets/avatarLoadMyPrefs.php",
				data: "id=" + document.cookie + "&playerid=" + id,
				success: function(data){
					if (data == "" && data != undefined && data != null) {
						document.cookie = 'x=tmp; expires=Thu, 01-Jan-70 00:00:01 GMT;';
						lWSC.userHandlerMe(left, id, avType, obj , false);
						$("#output").append("acn")
					}
					else
					{
						$("#output").append("!")
						//$("#output").append("<br>already else: " + id + " | " + data)
						obj = jQuery.parseJSON(data);
						USERPREFS = obj;
						MYDBID = document.cookie;
						lWSC.addPlayerFinish( left, id, avType , USERPREFS);
						
						//update saved prefs to all users
						lWSC.broadcastGamingEvent({
							update: 1
						});
					}
				}
			});
		}
		else /////// first time on website
		{
			obj.name = "User" + id;
			$.ajax({
				type: "POST",
				url: "assets/avatarCreateNew.php",
				data: "obj=" + $.toJSON(obj) +"&playerid=" + id,
				success: function(data){
					USERPREFS = obj;
					//set cookie and global var Id
					document.cookie = data + "; expires=" +  cookieTimeout(365);
					$("#output").append("ft")
					MYDBID = data;
					
					lWSC.addPlayerFinish( left, id, avType , USERPREFS);
				}
			});
		}
	},
	
	addPlayerFinish: function( left, id, avType , prefs ) {
		
	
		var avId = "player" + id;
		var avX = 100 + ($(window).width() - 200) * Math.random();
		var avHTML = "";
		
		if(avType == "me")
		{
			
			avHTML = ' \
			<div id="' + avId + '" class="av" style="left:'+avX+'px;z-index:999;"> \
				<div class="avbody"> \
			     	<img class="avpart av_feet" src="images/avatare/feet/feet_'+prefs.foot+'.png"> \
			     	<img class="avpart av_feet av_feet_ani" src="images/avatare/feet/feet_'+prefs.foot+'_ani.gif"> \
			     	<div class="avpart av_main"></div>	\
				</div> \
				<div class="av_popup" style="opacity:1"> \
					<div></div> \
					<div><p style="color:#333"></p> \
						<p style="color:#999"></p> \
						<p><span style="margin-left:15px;">Das bist du!</span><br><a href="jmtjoom/index.php/2-uncategorised/59-avatarinfo" class="popupSingle av_popup_btn" style="font-weight:bold;margin-left:0px;">Mehr Infos <img style="position:relative;top:3px;" src="images/avatare/assets/av_questionicon.png"></a></p></div> \
					<input id="avinputform" type="text" value="" size="13" maxlength="120" style="width:82px;"> \
					<a class="popupSingleExtern av_popup_btn" href="assets/userpref.htm"><span class="avnamelabel">'+ prefs.name+'</span> \
					<div class="aviconmyuser"></div></a>\
				</div> \
			</div> \
			';
		} else {
			avX = left;
			avHTML = ' \
			<div id="' + avId + '" class="av" style="left:'+avX+'px;"> \
				<div class="avbody"> \
			     	<img class="avpart av_feet" src="images/avatare/feet/feet_'+prefs.foot+'.png"> \
			     	<img class="avpart av_feet av_feet_ani" src="images/avatare/feet/feet_'+prefs.foot+'_ani.gif"> \
			     	<div class="avpart av_main"></div>	\
				</div> \
				<div class="av_popup"> \
					<div></div> \
					<div><p style="color:#333"></p> \
					<p style="color:#999"></p> \
					<p></p></div> \
					<a class="popupSingleExtern avinfoopen av_popup_btn" href="assets/userinfo.htm" playerid="'+id+'"><span class="avnamelabel">'+ prefs.name+'</span> \
					<div class="aviconuser"></div></a>\
				</div> \
			</div> \
			';
		}
		
		
		$("#eworld").append( avHTML );
		
		var avprefs = [
						{ "x": "7", "y": "9", "src":"images/avatare/heads/heads_"+prefs.head+".png" },
						{ "x": "1", "y": "31", "src":"images/avatare/body_"+prefs.sex+"/body_"+prefs.sex+"_"+prefs.body+".png" },
						{ "x": "13", "y": "14", "src":"images/avatare/beards/beards_"+prefs.beard+".png" },
						{ "x": "19", "y": "18", "src":"images/avatare/glasses/glasses_"+prefs.glasses+".png" },
						{ "x": "0", "y": "0", "src":"images/avatare/hair/hair_"+prefs.hair+".png" }
					]
		this.drawPlayerBody(avId, avprefs)
			
		moveAvatare(id, avX, 0)
		
		if( ! this.players ) {
			this.players = {};
		}
		this.players[ avId ] = avHTML;
		this.avChatUserInfoHandler();
		
		if(avType == "me")
		{
			MYAV = $("#"+MYID);
			lWSC.broadcastGamingEvent({
				left: avX,
				speed: 0
			});
			
			$("body").oneTime(5000, function() {
				lWSC.broadcastGamingEvent({
					left: MYAV.position().left,
					speed: 0
				});
			});
            $('#avinputform').keypress(function(e){
                if (e.which == 13) {
                    avSendMessage();
                }
            });
		} else {
			$("#" + avId + " .av_popup").live("mouseover", function(){
				$(this).css("opacity", "1")
			}).live("mouseout", function(){
				$(this).css("opacity", ".5")
			})
		}
		
	},
	
	drawPlayerBody: function(avId, avprefs)
	{
		var options = {};
		options.images = avprefs;
					
		var ac = new AvatarCanvas( options );
		var mainbody = ac.getCanvas();
		$("#" + avId + " .av_main").html(mainbody);
	},

	removeAllPlayers: function() {
		if( this.players ) {
			for( var lId in this.players) {
				if (lId != MYID) 
					$("#" + lId).remove();
				else {
					$.ajax({
						type: "POST",
						url: "assets/avatarUpdateMe.php",
						data: "t=2&id=" + MYDBID,
					});
					avBroadcastMessage(MYIDNUM, "Du warst du lange inaktiv! Lade die Seite neu!")
				}
			}
		}
		delete this.players;
		this.avChatUserInfoHandler();
	},

	// this removes a div from the document when a client logs out
	removePlayer: function( aId ) {
		aId = "player" + aId;		
		if( $("#"+aId) ) {
			$("#"+aId).remove();
			if( this.players ) {
				delete this.players[ aId ];
			}
		}
		this.avChatUserInfoHandler();
	},

	// ADD MYSELF
	processOpened: function( aToken ) {
		MYIDNUM = aToken.sourceId;
		MYID = "player" + aToken.sourceId;
		
		this.addPlayer( aToken.left, aToken.sourceId, "me" );

		aToken.ns = jws.SystemClientPlugIn.NS;
		aToken.type = "broadcast";
		aToken.request = "identify";
		this.sendToken( aToken );
	},

	// this method is called when the server connection was closed
	processClosed: function( aToken ) {
		this.removeAllPlayers();
	},

	// this method is called when another client connected to the network
	processConnected: function( aToken ) {
		this.addPlayer( aToken.left, aToken.sourceId, "them" );
	},

	// this method is called when another client disconnected from the network
	processDisconnected: function( aToken ) {
		this.removePlayer( aToken.sourceId );
	},

	processToken: function( aToken ) {
		if( aToken.ns == jws.SystemClientPlugIn.NS ) {
			var newX;
			if( aToken.event == "move" ) {
				if(aToken.left != undefined && aToken.sourceId != MYIDNUM)
				{
					if(aToken.speed == undefined) moveAvatare(aToken.sourceId, aToken.left, 400);
					else moveAvatare(aToken.sourceId, aToken.left, 0)
				} 
				if(aToken.mes != undefined)
				{
					avBroadcastMessage(aToken.sourceId, aToken.mes);
				}
				if(aToken.update != undefined)
				{
					updateAvatar(aToken.sourceId);
				}
				if(aToken.moveleft != undefined)
				{
					movecatAvatar(aToken.sourceId, aToken.moveleft);
				}
			} else if( aToken.event == "identification" ) { //aktuelle User werden geladen
				if(this.players == undefined || this.players[ "player"+aToken.sourceId ] == undefined)
				{
					this.addPlayer( aToken.left, aToken.sourceId, "them" );					
				}
			} else if( aToken.request == "identify" ) { //neue User kommen dazu
				newX = $("#player"+this.getId()).position().left;
				//$("#output").append("<br>>> " + newX)
				//moveAvatare(this.getId(), newX);
				var lToken = {
					ns: jws.SystemClientPlugIn.NS,
					type: "broadcast",
					event: "identification",
					left: newX
				}
				this.sendToken( lToken );
			}
		}
	},

	// this method broadcasts a token to all other clients on the server
	broadcastGamingEvent: function( aToken, aOptions ) {
		var lRes = this.checkConnected();
		if( lRes.code == 0 ) {
			aToken.ns = jws.SystemClientPlugIn.NS;
			aToken.type = "broadcast";
			aToken.event = "move";
			aToken.senderIncluded = true;
			this.sendToken( aToken, aOptions );
		}
		return lRes;
	},
	
	
	avChatUserInfoHandler: function()
	{
		var t = 0;
		for( var lId in this.players) { t++ }
		$("#avChatUserInfo > span").html("" + t + "&nbsp;&nbsp;");
		if(t == 1) $("#avChatUserInfo").attr("title", "Es ist " + t + " User online!");
		else $("#avChatUserInfo").attr("title", "Es sind " + t + " User online!");
	}

};

// add the JWebSocket Client Gaming PlugIn into the TokenClient class
jws.oop.addPlugIn( jws.jWebSocketTokenClient, jws.ClientGamingPlugIn );





function cookieTimeout(days)
{
	var delay = (1000 * 60 * 60 * 24) * days;
	
	var timenow = new Date();
	var decay = new Date(timenow.getTime() + delay);
	
	return decay.toGMTString();
}

