/*********************************************************************************
Game Score Manager ( Singletone Class)
  
Descriptiopn: gets game highscores and user highscore from user acount
			  and use a JsReapeater to implant the data on the page
created: 11/4/2007
editor: Eitan Yarimi
/*******************************************************************************/

GameScoreMgr = {};

/********************************************************************
initilize parameters

sTemplate = ID of the elements holds the reapeater template
iSku = Game Sku Number 
iChannel = channel ID number 
maxScores = max scores for the reapeter to render

/********************************************************************/

GameScoreMgr.init = function(iSku, iChannel,iMaxScores ,sTemplate)
{
	//logger
	this.log = new Log4Js.Logger("GameScoreMgr");

	//parameters
	this.MaxScore = iMaxScores;
	this.ChannelID = iChannel;
	this.SkuID = iSku; 
	this.iMode=1;
	this.sTemplate = sTemplate;
	this.sTargetIDGameScore;
	this.sTargetIDUserScore;
	this.blnIsMultiPlayer = false;
	
	//set a Worker class
	this.getUAScores = new UA.Game(this.SkuID,this.ChannelID);
	this.getUAScores.log = this.log;
	
	this.log.info("Mgr initiated");
}
/********************************************************************/

/**********************************************************************
Get Score Data
*********************************************************************/

/*GameScoreMgr.getScoresOf = function( enPeriod, sTargetElementID, sTemplate )
{
	//TODO
}

GameScoreMgr.getWeeklyScores = function( sTargetElementID, sTemplate )
{
	//TODO
}

GameScoreMgr.getHourlyScores = function( sTargetElementID, sTemplate )
{
	//TODO
}*/


/********************************/
//Get GameScore
/********************************/
GameScoreMgr.getEverScores = function( sTargetElementID, sTemplate )
{
	//Set parameters	
	this.sTemplate = sTemplate;
	this.sTargetIDGameScore = sTargetElementID;
	
	if(sTemplate != null)
	{ 
		this.sTemplate = sTemplate;
	}
	
			
	//Get scores from User Acoounts	(callback)
	this.getUAScores.GetGameHighScores(this.iMode,
									   this.MaxScore,
									   UA.Game.Scores.Periods.EVER,
									   this.EverScores_onSuccess,
									   this.onFail,
									   this.OnTimeOut
									   );
	
}
/********************************/
//OnSuccess GameScore
/********************************/
GameScoreMgr.EverScores_onSuccess = function(ScoreData)
{
	this.log.info("Success EverHighScore");
	
	// add formated score
	// add avatar image
	var sAvatarImg;
	for ( var i=0; i < ScoreData.TopScores.length; i++ )
	{
		ScoreData.TopScores[i].formatted_score = Number(ScoreData.TopScores[i].Score).format();
		
		//parse img url
		sAvatarImg = ScoreData.TopScores[i].Avatar;
		sAvatarImg = sAvatarImg.substring(67);
		sAvatarImg = sAvatarImg.substring(0,sAvatarImg.length-3)

        //fallback for no-image slihuete
        var sAvatarImgEnding = sAvatarImg.substr(sAvatarImg.length - 4).toLowerCase();
        if (sAvatarImgEnding != ".jpg" 
            && sAvatarImgEnding != ".gif" 
            && sAvatarImgEnding != ".png"
            )
        {
            sAvatarImg = "/graphics/MySpace/en/userPortlet/no_pic.jpg";
        }
				
		//set avatar
		ScoreData.TopScores[i].avatarImg = sAvatarImg;
					
		//set image for mp rating		
		ScoreData.TopScores[i].userRankingImgUrl = (ScoreData.TopScores[i].Score==null)? "" : TC.MpRanking.getMpRankingByScore(ScoreData.TopScores[i].Score).image;    
		
	}
	
	//obtaining the template
    var strTemplate = $(GameScoreMgr.sTemplate).value;
  
	var iRowNum = 1;
  
    //defining mapping:
    var oMapping =  {NAME: "Nickname",
					 AVATAR:"avatarImg",
                     SCORE : "Score",
                     FORMATTED: "formatted_score",
                     USER_IMG_RANKING_URL:"userRankingImgUrl",
                     ROWNUM : function(item){ return iRowNum++; }                     
                     };
                     
	this.log.debug("Reapeater Target ID :" + GameScoreMgr.sTargetIDGameScore);
	this.log.info("Template of Repeater: <hr> " + strTemplate.replace(/\</g, "&lt;") );
								
	//reapeater
    var repeater = new TC.Controls.Repeater(strTemplate);
    repeater.render($(GameScoreMgr.sTargetIDGameScore),
												  oMapping,
												  ScoreData.TopScores);
}

/********************************/
//Get UserScore
/********************************/
GameScoreMgr.GetUserBestScore = function( sTargetElementID,ismultiplayer ) 
{

	//set parameters
	this.blnIsMultiPlayer = ismultiplayer;
	this.sTargetIDUserScore = sTargetElementID;
	
	//Get scores from User Acoounts	(callback)
	this.getUAScores.GetUserHighScore(this.iMode,
									  this.UserBestScore_onSuccess,
									  this.onFail,
									  this.OnTimeOut);

}
/********************************/
//OnSuccess UserScore
/********************************/
GameScoreMgr.UserBestScore_onSuccess = function(ScoreData)
{	
	//Set Score to Page
	if(GameScoreMgr.blnIsMultiPlayer )
	{
		$(GameScoreMgr.sTargetIDUserScore).innerHTML = GameScoreMgr.addCommas(ScoreData.userHighScore) ;  //+" "+ getUserPositionWithPrefix("("+ScoreData.userPosition+")" ) ;
	}
	else
	{
		$(GameScoreMgr.sTargetIDUserScore).innerHTML = GameScoreMgr.addCommas(ScoreData.userHighScore) + " (Top " + calculateUserRanking(ScoreData.userRanking)  + " %) " ;
	}
			
	
}

/********************************/
//OnFail
/********************************/
GameScoreMgr.onFail = function(ScoreData)
{
	this.log.error("Faild to retrive score");		
}


/********************************/
///OnTimeout 
/********************************/
GameScoreMgr.OnTimeOut = function(request)
{
	this.log.info(request + "Time Out");
}

/************************************************************************/





/**********************************************************************
Add commas to numbers (util method)
*********************************************************************/

GameScoreMgr.addCommas = function(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;

}



