//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// BEGIN:  WEB SERVICE CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var DOMAIN_NAME = window.location.hostname;
var DF_WS_URL = ["http://",DOMAIN_NAME,"/webservices/datafiltering.asmx"].join('');
var _DFServiceProxy = new serviceProxy(DF_WS_URL);
var IS_WEB_METHOD = true;
var MAIL_HANDLER_URL = "/handlers/mailhandler.ashx";
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// END:  WEB SERVICE CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var NB = "&nbsp;"
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// BEGIN:  AUTHENTICATION CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var AUTH_UPDATED_EVENT = "AUTH_UPDATED";
var AUTH_EVENT_TARGETS = ".authEvent";

var LOG_IN_TEXT = "LOG IN";
var LOG_OUT_TEXT = "LOG OUT";

// Cookie Names:
var SEPA_AUTH_COOKIE = "SEPA_AUTH_2";
var SEPA_SSO_COOKIE = "SEPA_SSO";
var SEPA_UNAME_COOKIE = "SEPA_UNAME";

var SSO_ANCHORS = "a.sso,area.sso";

// LOGIN FORM:
var LOGIN_FORM = "#frmLogin";
var LOGIN_BUTTON = "#btnLogin";
var CANCEL_LOGIN_BUTTON = "#btnCancel";
var LOGIN_PROGRESS = "#loginWorking";
var LOGIN_FAILED = "#loginFailed";
var UNAME_FIELD = "#sepaUsername";
var PWD_FIELD = "#sepaPassword";
var A_LOGIN_IMG = "#headerTriLinkImg";
var A_LOGIN = "#mapHeaderTriLink area[href='']";
var ALT_LOGIN = "a.altLogIn";
var PREVIEW_LINK = "#previewLink";

// LOGOUT FORM:
var LOGOUT_FORM = "#frmLogout";
var LOGOUT_BUTTON = "#btnLogout";
var LOGOUT_PROGRESS = "#logoutWorking";

var LUI_FORM_DURATION = 500;
var LUI_DURATION = 1000;
var WEL_UNAME = "#welcomeUname";

var CLASS_AUTH_PROGRESS = ".authProgress";
var SSO_AUTH_TOKEN = "";

var AMS_DOMAIN_NAME = "netforum.avectra.com";
// AMS Links:
var SSO_URL = ["https://", AMS_DOMAIN_NAME, "/eWeb/StartPage.aspx?Site=SEPA"].join('');
var AMS_URL = ["https://", AMS_DOMAIN_NAME].join('');
var AMS_LOGOUT_URL = ["https://", AMS_DOMAIN_NAME, "/eWeb/StartPage.aspx?Logoff=Yes&Site=sepa"].join('');

var MC_URL = "/handlers/AMSRedirect.ashx"; 
var MF_RETRIEVE_URL = "/handlers/MediaFileContentRetriever.ashx";

var RSS_PROXY = "/handlers/RSSProxy.ashx";
var LOGIN_URL = "/handlers/UserLoginHandler.ashx";
var LOGOUT_URL = "/handlers/UserLogoutHandler.ashx";
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// END:  AUTHENTICATION CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// BEGIN:  CPH CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var AUX_LINKS = "#pageAuxLinks";
var AUX_LINKS_DF= "#auxLinksDefault";
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// END:  CPH CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// BEGIN:  INFOBAR CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var IB_TOGGLE = "#infoBarToggle";
var IB_CONTENT = "#infoBarBody";
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// END:  INFOBAR CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// BEGIN:  EFFECTS CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var CF_ANI_PARAMS_BEFORE = {opacity:1.0};
var CF_ANI_PARAMS_AFTER = {opacity:0.0};
var CF_ANI_DUR_1 = 1000;
var CF_ANI_DUR_2 = 2000;
var FCF_CLOSE = "#TB_closeWindowButton";
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// END:  EFFECTS CONSTANTS
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Provides a generic event handler for the OnComplete
// event for an XMLHTTP request.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function onComplete(XMLHttpRequest, textStatus)
{
    try
    {
        //alert(XMLHttpRequest.responseText);
		//$("#debug").html(XMLHttpRequest.responseText);
    }
    catch (e)
    {
        alert("There was an error during the execution of the 'onComplete()' function:\n\n" + e);
    }
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Provides a generic event handler for the OnError
// event for an XMLHTTP request.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function onError(XMLHttpRequest, textStatus, errorThrown)
{
    try
    {
        alert(XMLHttpRequest.responseText);
    }
    catch (e)
    {
        alert("There was an error during the execution of the 'onError()' function:\n\n" + e);
    }
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Provides a proxy for calling web service methods
// via XMLHTTP requests.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function serviceProxy(serviceURL)
{
    try
    {
        // The internal instance reference:
        var proxyInstance = this;

        // The service URL:
        this.serviceURL = serviceURL;

        // XML Service Call:
        this.invokeXML = function(methodName, methodData, onSuccess, onError, isWebMethod)
        {
			if (isWebMethod === null)
			{
				isWebMethod = true;
			};
		
            var xhr = jQuery.ajax({
                type: "POST",
                // The service endpoint URL:
                url: (proxyInstance.serviceURL + (isWebMethod ? "/" : "?") + methodName),
                processData: true,
                data: methodData,
                //contentType: "application/xml",
                //timeout: 10000,
                dataType: "xml",
                complete: onComplete,
                success: function(data, textStatus)
                {
                    if (onSuccess == null)
                    {
                        return;
                    };

                    // Call the success callback with the full, parsed result.
                    onSuccess(data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                    if (onError == null)
                    {
                        return;
                    };

					/*
                    if (XMLHttpRequest.responseText)
                    {
                        //onError(jsonParsedError);
                    };
                    */                   

                    return;
                }
            });			
        };    

        // Service Call:
        this.invoke = function(methodName, methodData, onSuccess, onError, canUseFullResult)
        {
            jQuery.ajax({
                type: "POST",
                // The service endpoint URL:
                url: (proxyInstance.serviceURL + "/" + methodName),
                data: JSON2.stringify(methodData),
                processData: false,
                contentType: "application/json",
                timeout: 10000,
                dataType: "text",
                complete: onComplete,
                success: function(data, textStatus)
                {
                    if (onSuccess === null)
                    {
                        return;
                    };

                    // Parse with JSON library.
                    var jsonParsedResult = JSON2.parse(data);

                    // Call the success callback with the full, parsed result.
                    if (canUseFullResult === true)
                    {
                        onSuccess(jsonParsedResult);
                        return;
                    };

                    // Call the success callback function with the top-level object removed
                    // from the enclosing wrapper.
                    // This is the default.
                    for (var property in jsonParsedResult)
                    {
                        if (jsonParsedResult.hasOwnProperty(property))
                        {
                            onSuccess(jsonParsedResult[property]);
                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                    if (onError === null)
                    {
                        return;
                    };

                    if (XMLHttpRequest.responseText)
                    {
                        var jsonParsedError = JSON2.parse(XMLHttpRequest.responseText);

                        if (jsonParsedError !== null)
                        {
                            //onError(jsonParsedError);
                            onError(XMLHttpRequest.responseText);
                        }
                        else
                        {
                            jsonParsedError({ Message: "An unknown server error occurred." });
                        }

                    };

                    return;
                }
            });
        };
    }
    catch (e)
    {
        alert("There was an error during the execution of the serviceProxy class:\n\n" + e);
    }
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Determines if the current user is authenticated.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function IsUserAuthenticated()
{
	try
	{
		return ($.cookie(SEPA_AUTH_COOKIE) != null);
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'IsUserAuthenticated()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Retrieves the Single Sign-on Cookie value.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetSSOAuthToken()
{
	try
	{
		return $.cookie(SEPA_SSO_COOKIE);	
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'GetSSOAuthToken()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Retrieves the UNAME Cookie value.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetUserName()
{
	try
	{
		return (($.cookie(SEPA_UNAME_COOKIE) == null) ? "" : $.cookie(SEPA_UNAME_COOKIE));
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'GetSSOAuthToken()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Appends the SSO token value to a specified URL
// and returns the modified URL.
// Parameters:
//		url - The URL text to modify.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function MakeURLSSOCompatible(url)
{
	try
	{
		if ((url != null) && (url.length > 0)) 
		{
			var ac = GetSSOAuthToken(); 
			
			if (ac != null) 
			{
				url += ("&" + ac);
			}
		}
		
		return url;
		
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'MakeURLSSOCompatible()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Appends or removes the SSO token value to a group
// of specified SSO-compatible anchor elements.
// Parameters:
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SynchronizeSSOAnchors()
{
	try
	{
		if ((SSO_AUTH_TOKEN != null) && (SSO_AUTH_TOKEN.length > 0)) 
		{
			// If logged in, make every SSO link SSO compatible.
			jQuery.each($(SSO_ANCHORS), function(i, link)
			{
				// Retrieve the current href attribute value.
				var href = $(link).attr("href");
				var rel = $(link).attr("rel");
								
				if (IsUserAuthenticated() == true) 
				{
					// Add the SSO token value to the href.
					$(link).attr("href", (href + "&" + SSO_AUTH_TOKEN));
					
					// Add the SSO token value to the rel.
					$(link).attr("rel", (rel + "&" + SSO_AUTH_TOKEN));
				}
				else
				{
					// Remove the SSO token value from the href.
					$(link).attr("href", href.replace("&" + SSO_AUTH_TOKEN, ""));
					
					// Remove the SSO token value from the rel.
					$(link).attr("rel", rel.replace("&" + SSO_AUTH_TOKEN, ""));
				}
			});
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'SynchronizeSSOAnchors()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Determines the correct authentication message to display depending
// on the selected link's display class.
// Last Revision Date:  10/09/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SelectAuthenticationMessage(link)
{
	try
	{
		if ((link != null) && ($(link).length == 1))
		{
			// Store the currently referenced URL.
			$(PREVIEW_LINK).html($(link).attr("href"));
		
			// Display the "login required" message.
			if ($(link).hasClass("loginRequired"))
			{
				tb_show("Log In Required", "#TB_inline?height=200&amp;width=650&amp;inlineId=previewDetailsLogIn", "");
			}
			// Display the "members only" message.
			else if ($(link).hasClass("membersOnly"))
			{
				tb_show("Members Only Resource", "#TB_inline?height=200&amp;width=650&amp;inlineId=previewDetailsMembersOnly", "");
			}
			// Display the default message.
			else
			{
				tb_show("Membership Process", "#TB_inline?height=200&amp;width=650&amp;inlineId=previewDetails", "");
			}
		
			//tb_show("Benefits of Registration", "#TB_inline?height=200&amp;width=600&amp;inlineId=previewDetails", "");
		}
	}
	catch (e) 
	{
		alert("There was an error during the execution of the 'SelectAuthenticationMessage()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Syncrhonizes AMS link elements for the current page.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SynchronizeAMSAnchors()
{
	try
	{
		// Retrieve a set of all AMS anchors.
		// ^= Matches elements that have the specified attribute and it starts with a certain value.
		//, #pageAuxLinksBox a[href*='" + MC_URL + "']
		var amsA = $("#outerLayout a[href^='" + AMS_URL + "'],#outerLayout area[href^='" + AMS_URL + "']");			

		jQuery.each($(amsA), function(i, link)
		{
			// Retrieve the current href attribute value and escape it.
			var href = escape($(link).attr("href"));
			
			if (href.indexOf("?amsURL=") < 0)
			{
				// Reset the link to the "Member Center" page.
				$(link).attr("href", (MC_URL + "?amsURL=" + href));
				
				// Reset the "rel" attribute value.
				$(link).attr("rel", href);				
			}
			
			$(link).click(function()
			{			
				if ((IsUserAuthenticated() == false) && ($(link).attr("class") != "bypassAMS")) 
				{
					SelectAuthenticationMessage(link);			

					return false;
				}
			});			
		});
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'SynchronizeAMSAnchors()' function:\n\n" + e);
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Syncrhonizes members-only resource link elements for the current page.
// Last Revision Date:  10/09/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SynchronizeMembersOnlyAnchors()
{
	try
	{
		// Retrieve a set of all AMS anchors.
		// ^= Matches elements that have the specified attribute and it starts with a certain value.
		var links = $("#outerLayout a[href^='/members/'],#outerLayout a.membersOnly");			

		jQuery.each($(links), function(i, link)
		{
			$(link).click(function()
			{			
				if ((IsUserAuthenticated() == false)) 
				{			
					if ($(link).hasClass("membersOnly") == false)
					{
						$(link).addClass("membersOnly");
					}				
					
					SelectAuthenticationMessage(link);
					
					return false;
				}
			});			
		});
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'SynchronizeMembersOnlyAnchors()' function:\n\n" + e);
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Syncrhonizes log-in required resource link elements for the current page.
// Last Revision Date:  10/09/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SynchronizeLogInRequiredAnchors()
{
	try
	{
		// Retrieve a set of all AMS anchors.
		// ^= Matches elements that have the specified attribute and it starts with a certain value.
		var links = $("#outerLayout a.loginRequired");			

		jQuery.each($(links), function(i, link)
		{
			$(link).click(function()
			{			
				if ((IsUserAuthenticated() == false)) 
				{				
					SelectAuthenticationMessage(link);
					
					return false;
				}
			});			
		});
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'SynchronizeLogInRequiredAnchors()' function:\n\n" + e);
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Synchronizes the UI elements that provide cues
// whether the user has authenticated with the system or not.
// Parameters:
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SynchAuthState()
{
	try
	{
		// Ensure that login and logout forms are hidden.
		$(".authForm").hide();
		$(CLASS_AUTH_PROGRESS).hide();
		
		$("input.login").css("border", "solid 1px black");
		
		var unc = $.cookie(SEPA_UNAME_COOKIE);
		var wel = "";
		var loginTitle = "Log in to the SEPA website.";
		var loginAlt = "aLogin";
		var loginSrc = "/common/images/header/";
		
		// Was the cookie value set?
		if (unc)
		{
			wel = ("Welcome,&nbsp;" + unc);	
			loginTitle = "Log out of the SEPA website.";
			loginAlt = "aLogout";	
			loginSrc += ("/header_tri_link_button_log_out.jpg");			
		}
		else
		{
			loginSrc += ("/header_tri_link_button_log_in.jpg");
			$(UNAME_FIELD).val("");	
		}
		
		// Update the welcome message.
		$(WEL_UNAME).html(wel);	
		
		$(A_LOGIN).attr("alt", loginAlt);
		
		$(A_LOGIN).attr("title", loginTitle).attr("alt", loginAlt);
		
		// Update the "src" attribute value for the login image.
		$(A_LOGIN_IMG).attr("src", loginSrc).show();	
		
		// Reset the password field.
		$(PWD_FIELD).val("");	
		
		// Enable or disable the SSO anchor elements for the page.
		SynchronizeSSOAnchors();		
		
		// Rewrite AMS anchor element href attribute values for the page.
		SynchronizeAMSAnchors();
		
		// Ensure that links to member-only resources have the correct display behavior.
		SynchronizeMembersOnlyAnchors();
		
		// Ensure that links to log in required resources have the correct display behavior.
		SynchronizeLogInRequiredAnchors();
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'SynchAuthState()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Attempts to authenticate the user against the 
// membership database by submitting the username and password
// to the membership verification handler.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function LogIn()
{
	try
	{
		// Confirm the field values.
		var username = $.trim($(UNAME_FIELD).val());
		var password = $.trim($(PWD_FIELD).val());
		
		var errorMessage = "";
		
		$("input.login").css("border", "solid 1px black");
		
		if (username.length <= 0)
		{
			errorMessage += "<li>Please enter a non-empty e-mail address value.</li>";
			$(UNAME_FIELD).css("border", "solid 1px red");
		}
		
		if (password.length <= 0)
		{
			errorMessage += "<li>Please enter a non-empty password value.</li>";
			$(PWD_FIELD).css("border", "solid 1px red");
		}
		
		if (errorMessage.length > 0) 
		{
			$(LOGIN_FAILED).html("Please correct the following errors:<ul>" + errorMessage + "</ul>");
			$(LOGIN_FAILED).show();
		}
		else 
		{		
			$(LOGIN_FAILED).hide();
			$(LOGIN_FAILED).html("Unfortunately, the credentials do not match an existing account.<br />Please check the spelling and case of the credentials and then try again.");
		
			$(LOGIN_PROGRESS).fadeIn(LUI_DURATION, function(){
				$.ajax({
					type: "POST",
					url:LOGIN_URL,
					data:"username=" + $(UNAME_FIELD).val() + "&password=" + $(PWD_FIELD).val(),
					complete: function(XMLHttpRequest, textStatus)
					{
						//alert(XMLHttpRequest.responseText);
					},
					success: function(data, success)
					{
						if (data == "SUCCESS") 
						{
							$(LOGIN_PROGRESS).fadeOut(LUI_DURATION, function()
							{
								$(LOGIN_FORM).fadeOut(LUI_FORM_DURATION);
								
								SSO_AUTH_TOKEN = GetSSOAuthToken();								
								
								SynchAuthState();
												
								var rurl = $.query.get("ReturnUrl");
								
								if ((rurl != null) && (rurl.length > 0))
								{								
									window.location.href = unescape(rurl);
								}
								
								var pLink = $(PREVIEW_LINK).html();
								
								if (pLink.length > 0)
								{	
									if ((pLink.indexOf("?amsURL=") > -1) && (unescape(pLink).indexOf("sso=") < 0))
									{
										// Append the SSO token to the end of the pLink URL.
										pLink += escape("&" + GetSSOAuthToken());
									}
												
									window.location.href = pLink;									
								}
								else
								{
									$(AUTH_EVENT_TARGETS).trigger("click");
								}
							});
						}
						else
						{
							$(LOGIN_PROGRESS).hide();
							$(LOGIN_FAILED).show();							
						}
					}
				});				
			});
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'LogIn()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Attempts to log out the user by calling the membership verification handler.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function LogOut()
{
	try
	{
		if (confirm("You are about to log out of the SEPA website.  Do you wish to proceed?") == true)
		{
			$(LOGOUT_FORM).fadeIn(LUI_FORM_DURATION, function()
			{		
				$(LOGOUT_PROGRESS).fadeIn(LUI_DURATION, function()
				{				
					$.ajax(
					{
						type:"POST",
						url:LOGOUT_URL,
						data:"",
						complete:function (XMLHttpRequest, textStatus) 
						{
							//alert(XMLHttpRequest.responseText);
						},
						success: function(data, success)
						{		
							$(A_LOGIN).attr("alt", "aLogin");
						
							$(LOGOUT_PROGRESS).fadeOut(LUI_DURATION, function()
							{
								$(LOGOUT_FORM).fadeOut(LUI_DURATION);
								
								SynchAuthState();
								
								$.get(AMS_LOGOUT_URL);								
																
								if ((window.location.pathname.indexOf("/members/") >= 0) || (window.location.pathname.indexOf("/public/resources/member-center.aspx") >= 0))
								{						
									window.location.href = "/member-center/member-center.aspx"; 
								}
								else
								{
									$(AUTH_EVENT_TARGETS).trigger("click");
								}
							});	
						}			
					});
				});
			});	
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'LogOut()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Attempts to parse a text value to an integer.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetValueAsInt(valueToParse, defaultValue)
{
	try
	{
		return (parseInt(valueToParse));
	}
	catch (e)
	{
		return (defaultValue);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Triggers authentication actions.
// Last Revision Date:  02/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function HandleAuthentication(element)
{
	try
	{
		if ($(element).attr("alt") == "aLogin")
		{
			$(LOGIN_FORM).fadeIn(LUI_FORM_DURATION, function()
			{
				$(UNAME_FIELD).focus();	
			});		
		}
		else
		{
			LogOut();
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'HandleAuthentication' function:\n\n" + e);
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Determines if a link rel value is contained within 
// the current pathname.
// Last Revision Date:  11/04/2009
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function DoesCurrentPathnameContainLinkRel(pathName, linkRel)
{
	// Assume failure.
	var result = false;
	
	// Only proceed if both parameters are non-null, non-empty.
	if ((pathName != null) && (pathName.length > 0) && (linkRel != null) && (linkRel.length > 0))
	{
		// Split the linkRel into a 1-D string array.
		var relParts = linkRel.split(",");
		
		// Cache the array length.
		var length = (relParts != null) ? relParts.length : 0;
		
		// Loop through all of the relParts elements.
		for (var i=0; i < length; i++)
		{
			// Is at least one of the relParts contained within the pathName string?
			if (pathName.indexOf(relParts[i]) > -1)
			{
				result = true;
				
				break;
			}
		}
	}
	
	return result;
}

$(document).ready(function()
{
	// Retrieve any current SSO token.		
	SSO_AUTH_TOKEN = GetSSOAuthToken();
	
	// Add target="_blank" attribute to all <a> elements with rel="external".
    $("a[rel='external']").attr("target", "_blank");
	
	// Retrieve the current page name.
	var pathName = ((location.pathname != null) && (location.pathname != "/")) ? location.pathname : "/sepa.aspx";
	var pathNameLC = pathName.toLowerCase();
	
	// Synchronize footer links.
	$("#frow0 a.fLink[href='" + pathName + "']").css("color", "white");

	// Also, attempt to synchronize the top-level container link background color.
	$("#hrow1 a.hLink").each(function(i)
	{
		// Does the current header link have an href that matches the current pathName?
		// OR
		// Does the current pathName contain the current header link's rel attribute value?
		if (($(this).attr("href").toLowerCase() == pathNameLC) ||  DoesCurrentPathnameContainLinkRel(pathNameLC, $(this).attr("rel").toLowerCase()))
		{
			// Alter the link color to white to represent that the page is active for the link.
			$(this).css("color", "#fff");				
			
			$(this).parent().css("background-color", "#7BA2C6");
		}
	});
	
	// Synchronize aux links.
	$(AUX_LINKS + " a[href='" + pathName + "']").css("color", "white");	

	// If Safari, reduce the header link cell height and line height styles
	if ($.browser.safari)
	{
		$("#r0c1").css("padding-bottom", "10px");
	}
	// Synchronize the authentication state of the current user.
	SynchAuthState();
	
	$(A_LOGIN).click(function()
	{
		HandleAuthentication($(this));
	});	
		
	$(LOGIN_BUTTON).click(function()
	{
		LogIn();
	});
	
	// Trap for Enter key presses on the password field.
	$(PWD_FIELD).keyup(function(e)
	{
		if(e.keyCode == 13) 
		{
			$(LOGIN_BUTTON).click();	
		}
	});	
	
	$(ALT_LOGIN).click(function()
	{
		$(A_LOGIN).click();
		$(UNAME_FIELD).focus();
	});
	
	$(CANCEL_LOGIN_BUTTON).click(function()
	{
		SynchAuthState();
	});	
	
	// Handle the IB toggle button click event.
	$(IB_TOGGLE).click(function()
	{	
		// Toggle the IB content display;
		$(IB_CONTENT).toggle();	
		// Retrieve the current op text char.					
		var op = $(this).attr("rel");
		// Build the revised HTML for the toggle button.
		var h = [NB, ((op == "-") ? "SHOW" : "HIDE"), NB, "EXPLANATION"];
		// Reset the toggle operation.
		op = ((op == "-") ? "+" : "-");
		// Set the new toggle button text and "rel" attribute value.		
		$(this).html(op + h.join('')).attr("rel", op);
	});		
});