/**
 * Profile
 */
function Profile(){
	
	Box.call(this);
	this.title = "Profile";
	eventhook.addListener(this,"loggedIn");
}

Profile.prototype = new Box;
Profile.prototype.constructor = Profile;
Profile.prototype.returnCounter = 4;
Profile.prototype.template = "#template_profile";
Profile.prototype.userName = "";
Profile.prototype.icon = "boxicons/profile.png";


Profile.prototype.addContent = function(obj){
	
	if (obj == null)
		obj = this;	
	
	//Activate links if required
	if (obj.userId == userId){ //If the user we're getting this for is the logged in user
		
		$(obj.containerId + " .link_profile_playerPic").click(obj.jqueryCallbackPlayerPicClickFunc(obj));
		$(obj.containerId + " .link_profile_edit").click(obj.jqueryCallbackProfileEditClickFunc(obj));		
	} else {
		
		$(obj.containerId + " .link_profile_playerPic").click(function(event){event.preventDefault();});
		$(obj.containerId + " .link_profile_edit").click(function(event){event.preventDefault();});				
	}
	
	$(obj.containerId + " .link_user_stats").click(obj.jqueryCallbackUserStatsClickFunc(obj));	
	$(obj.containerId + " .link_user_seeds").click(obj.jqueryCallbackUserSeedsClickFunc(obj));		
	
	if (this.userId != 0)
	
		this.getProfileData();
	else {
	
		$(this.containerId + " .profile_content").hide();
		$(this.containerId + " .profile_not_logged_in").show();
		this.loaded();
	}
}

Profile.prototype.jqueryCallbackUserStatsClickFunc = function(obj){
	
	return function(event){
	
		event.preventDefault();
			
		var stats = new UserStats;
		stats.setOwner(obj).setUserId(obj.userId);
		obj.addChild(stats);
	}
}

Profile.prototype.jqueryCallbackUserSeedsClickFunc = function(obj){
	
	return function(event){
	
		event.preventDefault();
			
		var seeds = new UserSeeds;
		seeds.setOwner(obj).setUserId(obj.userId);
		obj.addChild(seeds);
	}
}

Profile.prototype.jqueryCallbackPlayerPicClickFunc = function(obj){
	
	return function(event){
		
		event.preventDefault();
			
		var avatars = new ProfileAvatars;
		avatars.setOwner(obj).setTitle("Avatars").setUserId(obj.userId);
		obj.addChild(avatars);
		
	}	
}

Profile.prototype.jqueryCallbackProfileEditClickFunc = function(obj){
	
	return function(event){
		
		event.preventDefault();
		
		var editor = new ProfileEditor;
		editor.setOwner(obj).setTitle("Information").setUserId(obj.userId);
		obj.addChild(editor);
	}
}


Profile.prototype.getProfileData = function(obj){
	
	if (obj == null)
		obj = this;	
	
	if (obj.returnCounter != 4)
		return;
	
	obj.returnCounter = 0;
	
	$.getJSON("interface/json.php",{action: "getUserDetails", userId: obj.userId},obj.jqueryCallbackProfileUserDetailsFunc(obj));
	$.getJSON("interface/json.php",{action: "userGameStats", userId: obj.userId},obj.jqueryCallbackProfileUserGameStatsFunc(obj));
	$.getJSON("interface/json.php",{action: "getUserAchievements", userId: obj.userId, starting: 1, number: 16, orderBy: "date"},
			obj.jqueryCallbackProfileUserAchievementsFunc(obj));
	$.getJSON("interface/json.php",{action: "getUserShouts", userId: obj.userId, starting: 1, number: 5, orderBy: "date"},
			obj.jqueryCallbackProfileUserShoutsFunc(obj));
}

Profile.prototype.jqueryCallbackProfileUserDetailsFunc = function(obj){
	
	return function(data){
		
		var genders = new Array();
		genders["M"] = "Male";
		genders["F"] = "Female";
		genders["U"] = "Unspecified";
		$(obj.showId + " .box_title_text").html("Profile:<br/>" + data.userName);
		obj.userName = data.userName;
		$(obj.containerId + " .profile_userName").html(data.userName);
		$(obj.containerId + " .profile_countryFlag").attr("src", "images/flags/" + data.country + ".gif");
		$(obj.containerId + " .profile_countryName").html(data.countryName);		
		$(obj.containerId + " .profile_gender").html(genders[data.gender]);
		$(obj.containerId + " .profile_motto").html(data.motto);
		$(obj.containerId + " .profile_picture").attr("src","images/avatars/playerpics" + data.picture + ".png");
		$(obj.containerId + " .profile_seeds").html(data.seeds);
		obj.icon = "boxicons/resize/avatars/playerpics" + data.picture + ".png";
		
		obj.jqueryReturned(obj);
	}
}

Profile.prototype.jqueryCallbackProfileUserGameStatsFunc = function(obj){
	
	return function(data){
	
		   $(obj.containerId + " .profile_highestScore").html(data.highestScore);
		   $(obj.containerId + " .profile_highestScoreGameName").html(data.highestScoreGameName);
		   $(obj.containerId + " .profile_highestRank").html(data.highestRank);
		   $(obj.containerId + " .profile_highestRankGameName").html(data.highestRankGameName);
		   $(obj.containerId + " .profile_games").html("");
		   
		   for (var i = 0; i < data.game.length; i++){
			   
			   if (data.game[i].gameTotalScore){
				   var game = $("#template_profile_game").clone().css("display","").appendTo(obj.containerId + " .profile_games");
				   game.find(".profile_game_image").attr("src","images/games/game" + data.game[i].gameId + ".png");
				   game.find(".profile_game_name").html(data.game[i].gameName);			   
				   game.find(".profile_game_rank").html(data.game[i].gameHighestRank);			   
				   game.find(".profile_game_score").html(data.game[i].gameTotalScore);
			   }
		   }
		   
		   if (data.game.length == 0) {
		   	
				if (obj.userId == userId)
		   			$(obj.containerId + " .profile_games").html("Play some Barking Seed games and they will appear here.");									
				else
					$(obj.containerId + " .profile_games").html("No games played yet.");				
		   }
		   
		   obj.jqueryReturned(obj);
	}
}

Profile.prototype.jqueryCallbackProfileUserAchievementsFunc = function(obj){
	
	return function(data){
	
		   $(obj.containerId + " .profile_achievements").html("");
		   for (i = 0; i < data.achievement.length; i++){
			   
			   //Clone the image template once for each achievement image we're going to display
			   $("#template_profile_achievementImage").clone().attr("alt",data.achievement[i].achievementDescription).attr("title",data.achievement[i].achievementName).attr("src","images/achievements/achievement" + data.achievement[i].achievementId + ".png").css("display","inline").appendTo(obj.containerId + " .profile_achievements");
		   }
		   
		   obj.jqueryReturned(obj);
	}
}

Profile.prototype.jqueryCallbackProfileUserShoutsFunc = function(obj){
	
	return function(data){
		
		   $(obj.containerId + " .profile_shouts").html("");
		   for (i = 0; i < data.shout.length; i++){
			   
			   var shout = $("#template_profile_shout").clone().css("display","").appendTo(obj.containerId + " .profile_shouts");
			   shout.find(".profile_shout_image").attr("src","images/games/game" + data.shout[i].gameId + ".png");
			   shout.find(".profile_shout_text").html(data.shout[i].msg);
			   shout.find(".profile_shout_gameName").html(data.shout[i].gameName);			   
			   var msgDate = data.shout[i].dateTime.split(" ");
			   var msgTime = msgDate[1];
			   msgDate = msgDate[0].split("-");
			   var d = new Date(msgDate[0],msgDate[1]-1,msgDate[2]);
			   shout.find(".profile_shout_time").html(msgTime + " " + d.toDateString());
		   }
		   		
		   if (data.shout.length == 0) {
		   		if (obj.userId == userId)
			   		$(obj.containerId + " .profile_shouts").html("Say something! Your latest shouts will appear here.");				
				else
		   			$(obj.containerId + " .profile_shouts").html("No shouts yet.");									
		   }
		
		   obj.jqueryReturned(obj);
	}
}

Profile.prototype.jqueryReturned = function(obj){
	
	if (++obj.returnCounter == 4){
		
		$(this.containerId + " .profile_content").show();
		$(this.containerId + " .profile_not_logged_in").hide();		
		obj.loaded();
	}
}

Profile.prototype.childRemoved = function(child){

	this.getProfileData(this);
	Box.prototype.childRemoved.call(this,child);
}

Profile.prototype.eventCallback = function(eventType){
	
	if (eventType == "loggedIn") {
		if (this.userId == 0)
		this.userId = userId;
		this.getProfileData(this);
	}
}

/**
 * Profile avatar selector
 */
function ProfileAvatars(){
	
	Box.call(this);
}

ProfileAvatars.prototype = new Box;
ProfileAvatars.prototype.constructor = ProfileAvatars;
ProfileAvatars.prototype.template = "#template_profile_avatars";

ProfileAvatars.prototype.addContent = function(){

	this.getProfileAvatarData();
}

ProfileAvatars.prototype.getProfileAvatarData = function(obj){
	
	if (obj == null)
		obj = this;	
	
	$.getJSON("interface/json.php",{action: "getUserAvatars"},obj.jqueryCallbackProfileAvatarsFunc(obj));
}

ProfileAvatars.prototype.jqueryCallbackProfileAvatarsFunc = function(obj){
	
	return function(data){
	
		   $(obj.containerId + " .profile_unlocked_avatars").html("");
		   $(obj.containerId + " .profile_locked_avatars").html("");		   
		   
		   for (i = 0; i < data.avatars.length; i++){
			   
			   var image = $("#link_profile_image").clone().attr("id","link_profile_image" + data.avatars[i]).css("display","").appendTo(obj.containerId + " .profile_unlocked_avatars");
			   image.find("img").attr("src","images/avatars/playerpics" + data.avatars[i] + ".png");
		   }
		  
		   for (i = 0; i < data.lockedAvatars.length; i++){
			   
			   $("#locked_image").clone().css("display","").attr("src","images/avatars/playerpics" + data.lockedAvatars[i] + ".png").appendTo(obj.containerId + " .profile_locked_avatars");
		   }		   
		   
		   //Add click events to the new selectable avatars
		   $(obj.containerId + " .link_profile_image").click(function(event){
		  	   
			   event.preventDefault();

			   $(obj.containerId + " a").attr("disabled","true");
			   
			   $.getJSON("interface/json.php",{action: "updateDetails", picture: $(this).attr("id").substring(18)},function(data){
				   
			   });
			   
			   obj.remove();
		   });		   
		
		obj.loaded();
	}
}


/**
 * Profile editor
 */
function ProfileEditor(){
	
	Box.call(this);
}

ProfileEditor.prototype = new Box;
ProfileEditor.prototype.constructor = ProfileEditor;
ProfileEditor.prototype.template = "#template_profile_editor";

ProfileEditor.prototype.addContent = function(){

	this.getProfileEditorData();
}

ProfileEditor.prototype.getProfileEditorData = function(obj){
	
	if (obj == null)
		obj = this;	
	
	$.getJSON("interface/json.php",{action: "getUserDetails", userId: obj.userId},obj.jqueryCallbackProfileEditorFunc(obj));	
}

ProfileEditor.prototype.jqueryCallbackProfileEditorFunc = function(obj){
	
	return function(data){
		
		   $(obj.containerId + " .edit_userName").val(data.userName);		
		   $(obj.containerId + " .edit_firstName").val(data.firstName);
		   $(obj.containerId + " .edit_lastName").val(data.lastName);		   
		   dob = data.dob.split("-");
		   $(obj.containerId + " .dobDay").val(dob[2]);
		   $(obj.containerId + " .dobMonth").val(dob[1]);
		   $(obj.containerId + " .dobYear").val(dob[0]);
		   $(obj.containerId + " .gender").val(data.gender);
		   $(obj.containerId + " .edit_city").val(data.city);
		   $(obj.containerId + " .country").val(data.country);		   
		   $(obj.containerId + " .edit_email").val(data.email);
		   $(obj.containerId + " .edit_mobile").val(data.mobile);
		   $(obj.containerId + " .edit_motto").val(data.motto);
		   
		   //Set button event to update the profile from the editing pane and hide it
		   $(obj.containerId + " .button_update_profile").click(function(event){
			  
			   $(obj.containerId + " .button_update_profile").attr("disabled","true");
			   $(obj.containerId + " .notice_update_error").slideUp();
			   
			   $.getJSON("interface/json.php",{action: "updateDetails", userName: $(obj.containerId + " .edit_userName").val(), firstName: $(obj.containerId + " .edit_firstName").val(), 
				   			lastName: $(obj.containerId + " .edit_lastName").val(), 
				   			dob: $(obj.containerId + " .dobYear").val() + '-' + $(obj.containerId + " .dobMonth").val() + '-' + $(obj.containerId + " .dobDay").val(), 
				   			gender: $(obj.containerId + " .gender").val(), city: $(obj.containerId + " .edit_city").val(),
				   			country: $(obj.containerId + " .country").val(), email: $(obj.containerId + " .edit_email").val(), 
				   			mobile: $(obj.containerId + " .edit_mobile").val(), motto: $(obj.containerId + " .edit_motto").val()},
				        function(data){
				   	
				   	$(obj.containerId + " .button_update_profile").removeAttr("disabled");
				   	
					if (data.success == "0") {
						
						 $(obj.containerId + " .notice_update_error").slideDown();
					}
					else {
					
						obj.remove();
						eventhook.triggerEvent("profileInfoChange");
					}
			   });
		   });
		   
		   $(obj.containerId).find('input').keypress(function(e) {
		       if(e.which == 13) {
		    	   e.preventDefault();
		           $(this).blur();
		           $(obj.containerId + " .button_update_profile").focus().click();
		       }
		   });   
		  
		   obj.loaded();	
	}
}
