/**
 * Namespace for I-Play specific project code: Project
 */
Project = {};


/**
 * Project Global Variables Start 
 * Most of them should be loaded via HeadUC
 */
Project.hssWindowHight = 0;
Project.hssWindowWidth = 0;
Project.authenticationAdapterURL = "";
Project.channelCode = 0;
Project.channelDomain = "";
Project.mainDomain = ""; // for comcast (comcast.net domain will contain comcast + chill domains)
Project.allChannels = ""; /*all channels all comcast channels (comcast, comcast beta and chill)*/
Project.loginUrl = '/Profile/SignIn.aspx'; // The absolute login page URL
Project.createThankYouUrl = '/Profile/CreateProfileThankYou.aspx';
/**
 * Project Global Variables End 
 */

/*
* Returns the full create thank you URL
*/
Project.getFullCreateThankYouUrl = function()
{
    var fullUrl = 'http://' + Project.channelDomain + Project.createThankYouUrl;
    return fullUrl;
}

/*
* Project Sign Out
*/
Project.signOut = function()
{
	Clearance.forget( Url.relativeUrl( { withClearanceParams: false, withHereParams: true } ) );
}	

/**
 *	Returns true if the current user is logged on as a member,  
 *  encluding the 3rd-party single-sign-on of the partner
 */
Project.isMember = function()
{
	var bIsMember = ( ProfileMgr.user.IsLoggedOn() && !(ProfileMgr.user.isGuest()) );
	return bIsMember
}

/**
 *	This function will open Popup for Online Shell
 */
Project.openRoom =  function (sUrl, iWidth, iHight, isMembersOnly)
{
	Claim.isNumber(this.channelCode, "Project.openRoom is called without initiating Project.channelCode");
	// initialize width & height in-case they are not provided
	if (! iWidth) iWidth = this.hssWindowWidth;
	if (! iHight) iHight = this.hssWindowHight;
	
	// send to login if member room only and user is guest or not logged in
	if ( isMembersOnly && !Project.isMember() )
	{
		Project.sendToLogin();
		return void(0);
	}
    
	// roadblocking: check if we have "adid" variable (in window's scope)
	// if exists - add it to the query string
	// otherwise - do nothing
	var myAdid;
	try 
	{
		myAdid = parent.adid;
	} 
	catch (e){}
	if( myAdid )	
		sUrl = Url.appendParams( sUrl, { adid: myAdid } );
    
	// Update the target url to the membership guest login url
	{
		if (sUrl.indexOf("http://") == -1)
			sUrl = location.protocol + "//" + Project.channelOberonDomain + sUrl;
			
		var roomUrl = Url.parse(sUrl);
		var sAuthCookieName = Clearance.cookieName(Clearance.UNCLASSIFIED, false);
		var sAuthCookieValue = getCookie(sAuthCookieName);

		if(sAuthCookieValue == null)
			sAuthCookieValue = "";

		if ( roomUrl.domain )
		{
			var refUrl = Url.parse(location.href);
			// Pass the RefID to the game shell
			var refID = (typeof(refUrl.params.RefID) != 'undefined' ? refUrl.params.RefID : "");
			sUrl = Url.appendParams( sUrl, "refID="+refID );
		}

		if ( !ProfileMgr.user.IsLoggedOn() )
		{
			if (roomUrl.domain)
				sUrl = Project.getGuestLoginUrl(sUrl);
			else
				sUrl = Project.getGuestLoginUrl( location.protocol + "//" + location.host + sUrl );
		}
		
		if (/*roomUrl.domain && */ProfileMgr.user.IsLoggedOn())
		{
			var start = sUrl.indexOf("/gameshell/app");
			sUrl = sUrl.substring(start);
			sUrl = Url.relativeUrl( { protocol: roomUrl.protocol, domain: roomUrl.domain, path: sUrl, withClearanceParams: true, withHereParams: false } ); 
		}
	}
    
	// Open the popup with the final url
	try
	{
		window.top.open(sUrl, "online", "width=" + iWidth + ", height=" + iHight).focus();
	}
	catch(ex)
	{
		if(!window["log"])
		window.log = new Log4Js.Logger("[window] - app/lobby.aspx");
		log.error("couldn't open popup. Exception: " + Serialize(ex) );
	}
	return void(0);
}

/*
* go to page in the gameCenterWindowName window.
*/
Project.sendToPage = function(sUrl, bClosing)
{
	ProfileMgr.submitToPage(	{	action : sUrl
								,	target : ProfileMgr.settings.gameCenterWindowName
								}
							);
	
	if(bClosing)
		window.close();
}

/**
* goto login page in the gameCenterWindowName window.
*
*/
Project.sendToLogin = function( requiresConfirmation, closeSelf, thankUrl )
{	
	// confirm redirect if required
	var confirmed;
	if ( requiresConfirmation )
	    confirmed = confirm('This will end your game session');
	else
	    confirmed = true;
    
    // redirect if confirmed
	if( confirmed )
	{
	    var loginPage = Project.loginUrl;
        if ( thankUrl )
            loginPage += '?thankUrl=' + encodeURIComponent( thankUrl + '?' + window.location.search);
            
        //Next two lines are duplicated just because sometimes RefID can come once with small 'd' in the end and once with capital 'D' at the end.
        if (Url.here.params.RefID)
			loginPage = Url.appendParamValue( loginPage, "RefID", Url.here.params.RefID );
	    if (Url.here.params.RefId)
			loginPage = Url.appendParamValue( loginPage, "RefId", Url.here.params.RefId );
			
	    Project.sendToPage( loginPage, closeSelf );
	}
}

String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
}; 

Project.openPopUpWindow = function(sFullURL,iWidth,iHeight,winName,sParams)
{
	
	if (sParams != null && sParams != "")
	{
		sParams += ",";
	}
	else
	{
		sParams ="";
	}
	sParams += "width=" + iWidth + ",height=" + iHeight;
	window.open(sFullURL,winName,sParams);
	return false
}

/*
 * Delete old Oberon cookies.
 * Temporary solution for users who have a valid Oberon cookie, which leads to an invalid user.
 * This case occurs in case a user was made invalid by changing the channel's authentication namespace.
 * Oberon cookies expire much earlier than a year, so the problem is irrelevant after a year (2009 and forth).
 */
Project.DeleteOldOberonCookies = function()
{
    var date=new Date();
    (date.getFullYear() < 2009)
    {
        var cookieName = 'VisitedChillSiteWithTransferSupport';
        if (readCookie(cookieName) != 1)
        {
            date.setDate(date.getDate()+365);
            setDomainCookie(cookieName, 1, date.toGMTString())
            
            if (Project.isMember())
                Project.signOut();
        }
    }
}
    
/*
 * Removes any unwanted parameters from a given URL (ex: errorCode)
 */
Project.removeUnwantedUrlParameters = function( url )
{
    // TODO: Rethink whether this should be here or in the Membership object or both
    var cleanUrl = Url.parse( url );
    delete cleanUrl.params.errorCode;
    cleanUrl = Url.appendParams( cleanUrl.base, cleanUrl.params );
    return cleanUrl;
}

/*
 * Sends the user to the requested membership page
 */
Project.sendToMembership = function( target, closeSelf, thankUrl, retUrl, failUrl, username, password, remember )
{
    // Default the return URL to the channel home page
    if ( !retUrl )
        retUrl = ProfileMgr.settings.channelHomePage;
    
    // Remove the errorCode parameter from the URLs
    if ( thankUrl )
        thankUrl = Project.removeUnwantedUrlParameters( thankUrl );
    if ( retUrl )
        retUrl = Project.removeUnwantedUrlParameters( retUrl );
    if ( failUrl )
        failUrl = Project.removeUnwantedUrlParameters( failUrl );

	//Next two lines are duplicated just because sometimes RefID can come once with small 'd' in the end and once with capital 'D' at the end.
	if (Url.here.params.RefID)
		target = Url.appendParamValue( target, "RefID", Url.here.params.RefID );
	if (Url.here.params.RefId)
		target = Url.appendParamValue( target, "RefId", Url.here.params.RefId );	
	
    // Send and close by passed parameters
    var finalTarget;
    if ( username )
        finalTarget = Membership.getFinalDirectLoginUrl( target, thankUrl, retUrl, failUrl, username, password, remember );
    else
        finalTarget = Membership.getFinalUrl( target, thankUrl, retUrl, failUrl );
	Project.sendToPage( finalTarget, closeSelf );
}

/*
 * Sends the user to the membership user password page
 */
Project.sendToUserPass = function()
{
	Project.sendToMembership( Membership.userInfo.userPassUrl );
}

/*
 * Sends the user to the membership forgot password page
 */
Project.sendToForgotPassword = function()
{
    Project.sendToMembership( Membership.forgotPasswordUrl );
}

/*
 * Sends the user to the membership recent games page
 */
Project.sendToRecentGames = function()
{
    Project.sendToMembership( Membership.userInfo.recentGamesUrl );
}

/*
 * Sends the user to the membership profile summary page
 */
Project.sendToProfileSummary = function()
{
    Project.sendToMembership( Membership.userInfo.profileSummaryUrl );
}

/*
 * Sends the user to the membership personal info page
 */
Project.sendToPersonalInfo = function()
{
    Project.sendToMembership( Membership.userInfo.personalInfoUrl );
}

/*
 * Sends the user to the membership FAS page
 */
Project.sendToFAS = function()
{
    Project.sendToMembership( Membership.userInfo.fasUrl );
}

/*
 * Sends the user to the membership create account page
 *
 * @param {Boolean} closeSelf
 * Whether current window will be closed once the target window is moved to the create account URL or not
 */
Project.sendToCreate = function( closeSelf )
{
    Project.sendToMembership( Membership.createAccountUrl, closeSelf, Project.getFullCreateThankYouUrl() );
}

/*
 * Sends the user to the membership miles page
 */
Project.sendToMiles = function()
{
    Project.sendToMembership( Membership.userInfo.tokensUrl );
}

/*
 * Sends the user to the membership highscores page
 */
Project.sendToHighscores = function()
{
    Project.sendToMembership( Membership.userInfo.highscoresUrl );
}

/*
 * Returns the URL for the membership guest login page
 *
 * @param {String} thankUrl
 * The thank you URL to pass to the target
 * This parameter is optional and if nothing is passed the current URL will be passed
 */
Project.getGuestLoginUrl = function( thankUrl )
{
    var finalTarget = Membership.getFinalUrl( Membership.guestLoginUrl, false, thankUrl );
	return finalTarget;
}


/*
 * The sign in extension for the Project object
 */
Project.SignIn = {};

Project.SignIn.Ids = {};
Project.SignIn.Ids.Username = 'email';
Project.SignIn.Ids.Password = 'password';
Project.SignIn.Ids.RememberMe = 'rememberMe';

Project.SignIn.Ids.Errors = {};
Project.SignIn.Ids.Errors.MissingEmailPassword = 'errorMessage_missingEmailPassword';
Project.SignIn.Ids.Errors.MissingEmail = 'errorMessage_missingEmail';
Project.SignIn.Ids.Errors.MissingPassword = 'errorMessage_missingPassword';
Project.SignIn.Ids.Errors.EmailMismatch = 'errorMessage_emailMismatch';
Project.SignIn.Ids.Errors.PasswordMismatch = 'errorMessage_passwordMismatch';

Project.SignIn.CssClasses = {};
Project.SignIn.CssClasses.HiddenError = 'gzmDisplayNone';
Project.SignIn.CssClasses.VisibleError = 'gzmDisplayBlock';

/*
 * Clear errors
 */
Project.SignIn.ClearErrorMessages = function()
{
    $(Project.SignIn.Ids.Errors.MissingEmail).className = Project.SignIn.CssClasses.HiddenError;
    $(Project.SignIn.Ids.Errors.MissingPassword).className = Project.SignIn.CssClasses.HiddenError;
    $(Project.SignIn.Ids.Errors.MissingEmailPassword).className = Project.SignIn.CssClasses.HiddenError;
    $(Project.SignIn.Ids.Errors.EmailMismatch).className = Project.SignIn.CssClasses.HiddenError;
    $(Project.SignIn.Ids.Errors.PasswordMismatch).className = Project.SignIn.CssClasses.HiddenError;
}

/*
 * Sets the error visibility by parameters in the query string
 */
Project.SignIn.SetErrorsOnLoad = function()
{
    if ( Url.here.params.errorCode == Membership.AccountReturnedStatus.ACCOUNT_NOT_CREATED )
        $(Project.SignIn.Ids.Errors.EmailMismatch).className = Project.SignIn.CssClasses.VisibleError;
    
    if ( Url.here.params.errorCode == Membership.AccountReturnedStatus.USERNAME_PASSWORD_MISMATCH )
        $(Project.SignIn.Ids.Errors.PasswordMismatch).className = Project.SignIn.CssClasses.VisibleError;
}

/*
 * Fills the form input from the query string
 */
Project.SignIn.FillFormOnLoad = function()
{
    if ( Url.here.params[Project.SignIn.Ids.Username] )
        $(Project.SignIn.Ids.Username).value = Url.here.params[Project.SignIn.Ids.Username];
    
    if ( Url.here.params[Project.SignIn.Ids.Password] )
        $(Project.SignIn.Ids.Password).value = Url.here.params[Project.SignIn.Ids.Password];
}

/*
 * Sets error message display status and input field values when the page loads
 */
Project.SignIn.OnLoad = function()
{
	Project.SignIn.ClearErrorMessages();
	Project.SignIn.SetErrorsOnLoad();
	Project.SignIn.FillFormOnLoad();
}

/*
 * Validates the various form fields and sets error message display status accordingly
 */
Project.SignIn.ValidateForm = function()
{
	// Clear errors
	Project.SignIn.ClearErrorMessages();
	
	// Validate form
	var isUsernameValid = true;
	
	if($(Project.SignIn.Ids.Username).value == '')
	{
		//$(Project.SignIn.Ids.Errors.MissingEmail).className = Project.SignIn.CssClasses.VisibleError;
		isUsernameValid = false;
	}
	else if( !Membership.isValidUsername( $(Project.SignIn.Ids.Username).value ) )
	{
		$(Project.SignIn.Ids.Errors.EmailMismatch).className = Project.SignIn.CssClasses.VisibleError;
		return false;
	}

	if($(Project.SignIn.Ids.Password).value == '' && !isUsernameValid)
	{
		$(Project.SignIn.Ids.Errors.MissingEmailPassword).className = Project.SignIn.CssClasses.VisibleError;
		return false;
	}
	else if($(Project.SignIn.Ids.Password).value == '')
	{
		$(Project.SignIn.Ids.Errors.MissingPassword).className = Project.SignIn.CssClasses.VisibleError;
		return false;
	}
	else if(!isUsernameValid)
	{
		$(Project.SignIn.Ids.Errors.MissingEmail).className = Project.SignIn.CssClasses.VisibleError;
		return false;
	}
		
//	var username = $(Project.SignIn.Ids.Username).value;
//	var isUsernameValid = Membership.isValidUsername( username );
//	
//	var password = $(Project.SignIn.Ids.Password).value;
//	var isPasswordValid = Membership.isValidLoginPassword( password );
//    
//    if ( !isUsernameValid || !isPasswordValid )
//    {
//        $(Project.SignIn.Ids.Errors.MissingEmail).className = Project.SignIn.CssClasses.VisibleError;
//        return false;
//    }
    
    // Form successfuly validated
    return true;
}

/*
 * Validates, formats, and submits the sign in form
 */
Project.SignIn.SubmitForm = function()
{
	// Validate
	if ( !Project.SignIn.ValidateForm() )
	    return false;
    
    // Format data
    // Default thank URL to requested or homepage if none supplied
    var thankUrl = Url.here.params.thankUrl;
    if ( !thankUrl )
        thankUrl = ProfileMgr.settings.channelHomePage;
    // Add username to fail URL
    var failUrl = Url.appendParamValue( Url.here.full, Project.SignIn.Ids.Username, $(Project.SignIn.Ids.Username).value );
    // Data
    var username = $(Project.SignIn.Ids.Username).value;
    var password = $(Project.SignIn.Ids.Password).value;
    //TODO: When the cookie bug related to ['rememberMe'=false] is solved, 
    //      replace the hard coded ['rememberMe'=true] to reflect the user's actual choice.
    var rememberMe = true; //$(Project.SignIn.Ids.RememberMe).checked;
	
    // Submit
    Project.sendToMembership( Membership.directLoginUrl, false, thankUrl, null, failUrl, username, password, rememberMe );
}


/*
 * Opens the secure explenation popup
 */
Project.SignIn.OpenSecureExp = function()
{
    var url = '/Profile/Security.aspx';
    window.open(url, "security", "width=655, height=185").focus();
}
