///*************************************************************/
// Namespace for MySpace specific project code: Project
///*************************************************************/
Project = {};
	 
///*************************************************************/
// Project Global Variables Start 
// Most of them should be loaded via HeadUC
///*************************************************************/
Project.PartnerCookieName="OBERONSESSION"; // use oberon cookie 
Project.AuthCheckCookieName="ocua";
Project.authenticationAdapterURL = null;
Project.channelCode = null;
Project.userStatus = "guest" ;
Project.MyspaceUserCookieName = "USER";
Project.UserIdCookieName = "CachedUserID";
Project.waitForUserIdCookie = true;
Project.maximumPlayersinRoom = 150 // default value can be configured by chanel property "ADDITIONAL_DATA_6" on init; 
if(window.UA) Project.currentUser = new UA.User();

Project.log = new Log4Js.Logger("Project");

///*************************************************************/


///*************************************************************/
//  Project  -  read Cookie
//  if no name is provided - use the Partner-cookie name.
///*************************************************************/
Project.readCookie =  function(strCookieName) 
{
	if(!strCookieName) strCookieName = this.PartnerCookieName;
	
	var cookieString=document.cookie;
	var index1=cookieString.indexOf(strCookieName);
		
	if (index1==-1) return ""; 
		
	var index2=cookieString.indexOf(';',index1);
		
	if (index2==-1) index2=cookieString.length; 
		
	return unescape(cookieString.substring(index1+strCookieName.length+1,index2));
}


///*************************************************************/
//	Returns true if the current user is logged on as a member,  
///*************************************************************/
Project.isMember = function()
{
	var userState = this.getSessionState()
	return (userState != "guest") && (userState != "") ;
}


Project.getSessionState = function()
{
	if	(	Url.here.domain.toLowerCase().contains("oberon-media.com") 
		&&	(	Url.here.path.toLowerCase().contains("/gameshell.aspx")
			||	Url.here.path.toLowerCase() == "/land/toolr.aspx"
			)
		)
	{
		//gameshell at oberon domain
		return Url.here.params.memsess;
	}	
	else
	{
		//myspace domain
		return Project.readCookie();
	}
}

///*************************************************************/
// returns true if 
//    - the user is guest 
//    - the user is not logged in
///*************************************************************/
Project.isGuest = function()
{
	return !this.isMember();
}

///*************************************************************/
// check if user has an authentication cookie
///*************************************************************/
Project.isLoggedIn = function()
{
	return !!this.getSessionState();
}

///*************************************************************/
// check if user logged in myspace
///*************************************************************/
Project.isMySpaceLoggedIn = function()
{
	return !!Project.readCookie(this.MyspaceUserCookieName);
}



///*************************************************************/
// Project.GetAvailableRoom 
//  select availbale room from the presence
// Notice* :this code is possible by an enhancment made only in myspace gamecenter
///*************************************************************/
Project.GetAvailableRoom  = function()
{

	var ageGroup = (Project.userType == 'minor')?'minors':'adults';
	var isCurrentUserAMember = this.isMember();
	
	this.log.debug("Project.GetAvailableRoom - ageGroup: [" + ageGroup + "], isCurrentUserAMember : [" + isCurrentUserAMember + "]");
	
	//select all the rooms that fits the age-group AND the user login-type
	arr = PresenceCatalog.Rooms.All.select( 
			function(room){
				return (   room.ageGroup == ageGroup 
						&& (!Project.onlineSku || Project.onlineSku == room.sku)
						&& (isCurrentUserAMember || room.isMembersOnly == false)
						) 
						  }
			);
	
	this.log.debug("Project.GetAvailableRoom - total rooms found fit for user age-group,login and online sku: " + arr.length);
			
	//select the first available room 
	var availableRoom = arr[0];
			
	for( var i = 0 ; i < arr.length ; i++ )
	{
		if(availableRoom.NumberOfPlayers > arr[i].NumberOfPlayers)
		{
			availableRoom = arr[i];
		}
	}

	//selected room :
	this.log.debug("Selected room: " + Object.serialize(availableRoom) );

	return availableRoom.roomUrl
	
}
///*************************************************************/
// create auto play link  for the play button
// used in lobby promo  only
///*************************************************************/
Project.createAutoPlayLink =  function (skuCode,gameCode)
{	
	var rurl = "";	
		
	var oLobby = PresenceCatalog.Lobbies.All.BySku[skuCode];
	var oSku = TC.SKUs[skuCode];

	//if no info in presence, 
	// or presence reports lobby full for the current user login type 
	//   - return empty string;
	if( !oLobby )
	{
		this.log.error("Project.createAutoPlayLink - no lobby found in presence for SKU: " + skuCode );
		return "";
	}
	if(	!oSku  )
	{
		this.log.error("Project.createAutoPlayLink - no sku object found for SKU: " + skuCode );
		return "";
	}
	
	var isRequireLogin = false ;// eval(oSku.isMultiPlayer) || oSku.isSupportsHighScore;


	// CREATE THE RETURN URL FOR THE ADAPTER
	//---------------------------------------		
	//in multiplayer games, guest must loggin, and comes back to lobby,
	// REGARDLESS TO AVAILABLE ROOMS
	//redirect guest in multiplayer game to lobby
	if(isRequireLogin && !Project.isMember() )
	{
		rurl = "/Lobby.aspx?lobby=" + oLobby.LobbyID ;

	}
	else 
	{
		this.log.debug("Project.createAutoPlayLink - user is authenticated, or game is not MP");

		rurl = Project.GetAvailableRoom() ;
	}

	// CREATE THE FULL INVOCATION FUNCTION
	//---------------------------------------		
	//if no room found
	if  ( !rurl )
	{
		this.log.warn("Project.createAutoPlayLink - no rurl found. Empty string returned");
		// no rooms available
		return "";
	}

	var str = "Javascript:Project.openRoom('"  
			+ rurl
			+ "',"
			+ isRequireLogin
			+ ");" ;
	
	this.log.info("Project.createAutoPlayLink - returned : " + str);
	return str;
}

///*************************************************************/
// create a gamshell link
///*************************************************************/

Project.gameShellLink = function (skuCode)
{	
	var rurl = "";	
		
	var oLobby = PresenceCatalog.Lobbies.All.BySku[skuCode];
	var oSku = TC.SKUs[skuCode];

	//if no info in presence, 
	// or presence reports lobby full for the current user login type 
	//   - return empty string;
	if( !oLobby )
	{
		this.log.error("Project.createAutoPlayLink - no lobby found in presence for SKU: " + skuCode );
		return "";
	}
	if(	!oSku  )
	{
		this.log.error("Project.createAutoPlayLink - no sku object found for SKU: " + skuCode );
		return "";
	}
	
	var isRequireLogin = false;//eval(oSku.isMultiPlayer) || oSku.isSupportsHighScore;


	// CREATE THE RETURN URL FOR THE ADAPTER
	//---------------------------------------		
	//in multiplayer games, guest must loggin, and comes back to lobby,
	// REGARDLESS TO AVAILABLE ROOMS
	//redirect guest in multiplayer game to lobby
	if(isRequireLogin && !Project.isMember() )
	{
		rurl =  escape(Url.here.path + '?' + Url.here.query) ;
	}
	else 
	{
		this.log.debug("Project.gameShellLink - user is authenticated, or game is not MP");
				
		rurl = escape( Project.GetAvailableRoom());
	}

	// CREATE THE FULL INVOCATION FUNCTION
	//---------------------------------------		
	//if no room found
	if  ( !rurl )
	{
		this.log.warn("Project.gameShellLink - no rurl found. Empty string returned");
		// no rooms available
		return "";
	}
		
	this.log.info("Project.gameShellLink - returned : " + rurl);
	return  rurl;
}

///*************************************************************/
//This function will open Online game Shell
///*************************************************************/

Project.openRoom =  function(sUrl,isRequireLogin) 
{

	Claim.isString(this.authenticationAdapterURL, "Project.openRoom is called without initiating Project.authenticationAdapterURL");
	Claim.isNumber(this.channelCode, "Project.openRoom is called without initiating Project.channelCode");
	Claim.isString(this.PartnerCookieName, "Project.PartnerCookieName is empty");
	 
    try
    {
    
       //get adapter command
	    var cmd = this.getAdapterCommand(false); //isRequireLogin);
	  	
	  	//Remove oberon-media (OLR) prefix - it is not needed for myspace.
	  	sUrl = sUrl.replace("http://myspace.oberon-media.com","");
	  	sUrl = sUrl.replace("http://myspace-uk.oberon-media.com",""); 
		//authenticate adapter url
		top.location.href = this.authenticationAdapterURL + "?cmd=" + cmd + "&channel=" + this.channelCode +  "&rurl=" + escape(sUrl.replace("/gameshell/app","")  ); 
		
    }
    catch(ex)
    {
        if(!window["log"])
            window.log = new Log4Js.Logger("[window] - app/gameshell.aspx");
        log.error("couldn't open gameshell room. Exception: " + Object.serialize(ex) );
    }
    return void(0);
      
}

Project.openMyGames = function(sUrl)
{	
	var cmd = this.getAdapterCommand(true);
    // authenticate adapter url   
	top.location.href =   this.authenticationAdapterURL + "?cmd=" + cmd + "&channel=" + this.channelCode +  "&rurl=" + escape( sUrl  )   ;
}

///*************************************************************/
 //	This function will open Online game Lobby
///*************************************************************/
Project.openLobby =  function(sUrl,sku) 
{
	
	Claim.isString(this.authenticationAdapterURL, "Project.openRoom is called without initiating Project.authenticationAdapterURL");
	Claim.isNumber(this.channelCode, "Project.openRoom is called without initiating Project.channelCode");
	Claim.isString(this.PartnerCookieName, "Project.PartnerCookieName is empty");
	    
    try
    {
		var isRequireLogin;
		
		//used in .net 1.1 enviroemnt 
		// find out if game is multiplayer using game catalog js
		if(TC.SKUs[sku])
		{
			isRequireLogin = false; // eval(TC.SKUs[sku].isMultiPlayer) || TC.SKUs[sku].isSupportsHighScore;
		}
		else
		{
			this.log.warn("Project.openLobby - no SKU object found for sku. Singleplayer game assumed. SKU: " + sku);
		}
		
		//get adapter command
		var cmd = this.getAdapterCommand(isRequireLogin);
		
		// authenticate adapter url	
		top.location.href =   this.authenticationAdapterURL + "?cmd=" + cmd + "&channel=" + this.channelCode +  "&rurl=" + escape( "/" + sUrl  )   ; 
							  
    }
    catch(ex)
    {
        if(!window["log"])
            window.log = new Log4Js.Logger("[window] - app/lobby.aspx");
        log.error("couldn't open lobby  Exception: " + Object.serialize(ex) );
    }
    
    return void(0);
      
}

///*************************************************************/
// send to profile page 
/*************************************************************/
Project.sentToProfile = function(nickName) 
{

	window.open(this.authenticationAdapterURL + "?cmd=8" +  "&channel=" + this.channelCode + "&nick=" + escape(nickName)); 
}


///*************************************************************/
// send to adapter with Url 
/*************************************************************/
Project.getSendToAdapterWithRetUrl = function(sRetUrl, sCommand)
{
    if (!sCommand) sCommand = "login";
    return  [   this.authenticationAdapterURL 
            ,   "?cmd=", sCommand
            ,   "&channel=", this.channelCode
            ,   "&rurl=",  escape( Url.appendParamValue( sRetUrl, "code", Url.here.params.code ) ) 
            ].join("");
}

// get adapter command parameter by game type ( sp,mp)
/*************************************************************/
Project.getAdapterCommand = function(isRequireLogin)
{
	if (eval(isRequireLogin))
	{
		this.log.info("getAdapterCommand: game requires authentication. cmd=login");
		return "login";	
	}
	this.log.info("getAdapterCommand: game does not require authentication - return guest");

	return "guest";
}

/*************************************************************/
// Writes the Walled-Garden of the OLR games
/*************************************************************/
Project.shellWG = function(sHomeDomain)
{
	var oDesiredUrl = Url.parse(location.href);
	oDesiredUrl.path = "/Land/ToOLR.aspx";
	oDesiredUrl.params.memsess = Project.readCookie();
	oDesiredUrl.domain = sHomeDomain;	
	
	var sShellUrl = Url.relativeUrl(oDesiredUrl);
    var iHeight = 1400;
  
	document.write( ['<IFRAME width="100%" border="0" frameborder="0" height="'+iHeight+'" SCROLLING=NO src="',sShellUrl,'"></IFRAME>'].join("") );
}

///*************************************************************/
// mark text form a text area and copy it 
// used in addtoprifle page
///*************************************************************/
Project.copyFromTextArea = function(theField)
{
	var tempval=$(theField);
	tempval.focus();
	tempval.select();
	
	if(tempval.createTextRange) //IE Only (dont work on firefox)
	{	
		therange= tempval.createTextRange();
		therange.execCommand("Copy");
	}
	
	
}
///*************************************************************/
// returns the URL of the current page, clean from clearance params,
// meant to use as a return url for the adapter
///*************************************************************/
Project.getReturnUrl = function()
{
	var rurl = Url.parse(location.href);
	delete rurl.params.un;
	delete rurl.params.ux;
	delete rurl.params.rn;
	delete rurl.params.rx;
	delete rurl.params.cn;
	delete rurl.params.cx;
	delete rurl.params.an;
	delete rurl.params.ax;
	delete rurl.params.ui;
	rurl = Url.relativeUrl( rurl , {withClearanceParams: false,withHereParams:false} );
	
	if (rurl.contains("?=undefined")) rurl = rurl.substr(0, rurl.indexOf("?=undefined") );

	return rurl;	
}



/**
 * @private
 * used in Project.init sets a cookie
 */
Project.setCookie = function(sName, sValue)
{
	document.cookie= sName + "=" + sValue + ";path=/;domain=" + Url.here.domain;
	Cookies.rawByName[sName] = sValue;

	document.cookie= sName + "=" + sValue + ";path=/;domain=" + Url.here.domain.substr( Url.here.domain.indexOf(".") );
	Cookies.rawByName[sName] = sValue;

}



/**
 * @private, 
 *
 * Authenticates the state of the current browser session, 
 * and correlation between UA cookie, and adapter session
 */
Project.init = function(oSettings)
{
	this.log.info("Initializing Singleton: Project");

	Object.extend( this, oSettings );
	Claim.isString(this.authenticationAdapterURL, "oSettings.authenticationAdapterURL must be provided to .init");
	Claim.isNumber(this.channelCode	, "oSettings.channelCode must be provided to .init");
	

	Project.isInitiated = true;
	
	
}



/*************************************************************/
// Get USer Image  and Location
///add functonality for user image an location
/*************************************************************/
if ( window.ProfileMgr && ProfileMgr.UserDetails ) ProfileMgr.UserDetails.AsPrototype = function(){ return new ProfileMgr.UserDetails({}); }

Project.UserMySpaceInfo = Class.create("ProfileMgr.UserDetails");

Project.UserMySpaceInfo.prototype.initialize = function(oMapping, sNickName)
{

	if(!sNickName)
	{	
		this.USER_HANDLER_URL =  Project.authenticationAdapterURL.replace('ProcessAuthentication.ashx','GetUserSpecificDetail.ashx') + "?cmd=5&source=gc&channel=" + ProfileMgr.settings.channel;
	}else{
		this.USER_HANDLER_URL =  Project.authenticationAdapterURL.replace('ProcessAuthentication.ashx','GetUserSpecificDetail.ashx') + "?channel=" + ProfileMgr.settings.channel + '&cmd=7&source=gc&nick=' + sNickName  ;
	}
		
}

Project.getUserMySpaceInfo = function(oMapping, oEvents)
{
	ui = new Project.UserMySpaceInfo(oMapping);
	Object.extend(ui, oEvents);
	ui.apply();
}

/*************************************************************/

Project.setImgScale = function(oImg, iHeight, iWidth)
{
	if( oImg.height > oImg.width)
	{
		oImg.width = iWidth;
		oImg.style.top = -(oImg.height - iHeight)/2  
	}
	else
	{
		oImg.height = iHeight;
		oImg.style.left = -(oImg.width - iWidth)/2
	}
}

/*************************************************************/
// post to myspace (add widget to profile page)
// T - Tile
// C - Widget Code
// U - (not in use)
// L - ComboBox 1-5
/*************************************************************/
Project.addToProfile = function(T, C, U, L)
{
	var targetUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?' 
					+ 't=' + encodeURIComponent(T)
					+ '&c='+ encodeURIComponent(C) 
					+ '&u='+ encodeURIComponent(U) 
					+ '&l='+ L;
					
	window.open(targetUrl);
}


/***********************************************************/
//Get MySpace User ID (create a cookie named CachedUserID and get a jast response)
/***********************************************************/
Project.createMySpaceUserIDCookie = function()
{	
		
	var _JAST = new Jast.Request(Project.authenticationAdapterURL.replace('ProcessAuthentication.ashx','getuserinfo.ashx') + "?channel=" + ProfileMgr.settings.channel , {	
						onSuccess: function(request) { 
													
							//replace all "{UserID}" with userID
							var header = $('mySpaceHeaderUser');
							var arr = header.getElementsByTagName("A");
							
							for (var  i=0; i < arr.length; i++ )
							{
								arr[i].href = arr[i].href.replace("{UserID}",request.result.Data.userID);
							}
							
														},
						onFailure: function(request) {  },
						onTimeout: function(request) {  }
					})
					
}
/*********************************************************/

setTimeout("Claim.isTrue( Project.isInitiated , 'Placing GlobalFN.js in the page required call to Project.init(oSettings) right after')", 5000);
