//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// 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";

var LINK_SHOW_LOGIN = "#outerLayout a.showLogInDialog";

// 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 AMS_ONLINE_STORE_URL = ["https://", AMS_DOMAIN_NAME, "/eweb/Shopping/Shopping.aspx"].join('');

var MC_URL = "/handlers/AMSRedirect.ashx"; 
var MF_RETRIEVE_URL = "/handlers/MediaFileContentRetriever.ashx";

var CB_INLINE = "#outerLayout a.colorbox-inline";
var CB_IFRAME = "#outerLayout a.colorbox-if";

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 ORIGINAL_AUX_LINKS_SELECTOR = $('#originalAuxLinks');
var PAGE_AUX_LINKS_SELECTOR = $('#pageAuxLinks');
var AUX_LINKS_SELECTOR = '#hrow1 a.auxLink';
var ACTIVE_AUX_LINK_PARENT_CSS_NAME = 'activeAuxLink';
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// 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:  Tests whether a string value is contained in the current window's querystring.
// Last Revision Date:  03/05/2010.
// Parameters:
//		name:  The text value to test
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
$.queryStringParameter = function(name)
{
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	
	// Return the first match, if matches were found.
	return ((results) && (results.length >= 2)) ? (unescape(results[1])) : '';
}


//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Tests whether a string value is either null or an empty string.
// Last Revision Date:  03/05/2010.
// Parameters:
//		value:  The text value to test
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
String.IsNullOrEmpty = function(value)
{
	return (((value) && (typeof(value) == 'string') && (value.length > 0)) ? false : true);	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// 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
	{
		var _unameCookie = $.cookie(SEPA_UNAME_COOKIE);
		
		return ((_unameCookie == null) ? "" : _unameCookie);
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'GetSSOAuthToken()' function:\n\n" + e);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Triggers the display of the log in form, or, if
// the user is already logged in, redirects to the URL specified
// by the link's href attribute value.
// Parameters:
//		link - The link that was clicked.
// Last Revision Date:  03/18/2010
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function ShowLogInDialogFromLinkOrRedirect(link)
{
	try
	{
		if (link)		
		{	
			var href = $(link).attr('href');
						
			// The user is not currently logged in, so display the log in dialog.
			if (IsUserAuthenticated() == false)
			{
				// Store the currently referenced URL.
				$(PREVIEW_LINK).html(href);
				
				var _html = $("#specialDebug").html();
				$("#specialDebug").html(_html + " | " + href);
										
				// Trigger the display of the log in form.
				if ((window.location.href == 'http://www.solarelectricpower.org/active-dev/log-in-test.aspx') || (window.location.href == 'http://www.solarelectricpower.org/active-dev/usc-home.aspx'))				
				{
					RedirectToLoginForm();
				}	
				else				
				{
					// Scroll to the top of the screen.
					$.scrollTo("0%", 500);
					
					$(A_LOGIN).click();		
				}			
				
			}
			// The user is logged in, so redirect to the URL specified by the link.
			else						
			{
				if (href != null)
				{
					window.location.href = href;
				}				
			}
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'ShowLogInDialogFromLinkOrRedirect()' 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)
			{
				var _link = $(link);
			
				// Retrieve the current href attribute value.
				var href = _link.attr("href");
				var rel = _link.attr("rel");
				
				var encodedAmpersand = escape("&");
							
				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 + encodedAmpersand + 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(encodedAmpersand + 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)
		{
			var _link = $(link);
			
			if (_link.length == 1) 
			{			
				// Store the currently referenced URL.
				$(PREVIEW_LINK).html(_link.attr("href"));
				
				// Redirect to the login form.
				if ((_link.hasClass("loginRequired")) ||  (_link.hasClass("membersOnly")))
				{
					ShowLogInDialogFromLinkOrRedirect(link);
				}
			}
		}
	}
	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 online store anchors.
		var amsOS = $("#outerLayout a[href*='" + AMS_ONLINE_STORE_URL + "'],#outerLayout area[href*='" + AMS_ONLINE_STORE_URL + "']");	
		jQuery.each($(amsOS), function(i, link)		
		{
			var _link = $(link);
			
			if (_link.hasClass('bypassAMS') == false)				
			{
				_link.addClass('bypassAMS');
			}
		});	
		
		// 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)		
		{
			var _link = $(link);
	
			// Retrieve the current href attribute value and escape it.
			var href = escape($(link).attr("href"));
			
			if (href.indexOf("?amsURL=") < 0)			
			{
				if (_link.hasClass('bypassMC') == false) 
				{
					// 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(event)			
			{		
				var _this = $(this);
			
				if ((IsUserAuthenticated() == false) && (_this.attr("class") != "bypassAMS") && (_this.hasClass('bypassMC') == false))	
				{
					ShowLogInDialogFromLinkOrRedirect(_this);

				    // Stop event handling in non-IE browsers:
				    event.preventDefault();
				    event.stopPropagation();

					// Stop event handling in IE
					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.
		$("#outerLayout a[href^='/members/'],#outerLayout a.membersOnly").live("click", function()	
		{	
			if ((IsUserAuthenticated() == false)) 
			{			
				var _link = $(this);
				
				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");	
			
			// Hide any previewBox links.
			$("div.previewBox a.showLogInDialog").hide();	
		}
		else
		{
			loginSrc += ("header_tri_link_button_log_in.jpg");
			
			//$(UNAME_FIELD).val("");
						
			// Hide any previewBox links.
			$("div.previewBox a.showLogInDialog").show();				
		}
		
		// 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 
// sepaconnect.org membership database by submitting the current SSO token
// to the membership verification handler.
// Last Revision Date:  05/31/2011
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SEPAConnectAuthenticate(isLogIn)
{
	var _url = null;
	var _sepaConnectLink = $("#sepaConnectLink");
		
	if (isLogIn == true)	
	{
		_url = "http://www.sepaconnect.org/HigherLogic/Security/NetForumLogin.aspx?ssoToken={token}&amp;ReturnUrl=http://www.sepaconnect.org/sepaconnect/sepaconnect/Home/default.aspx";
		_url = _url.replace("ssoToken={token}", GetSSOAuthToken());
		
		// Does the sepaConnectLink exist?
		if (_sepaConnectLink.length == 1)
		{
			_sepaConnectLink.attr('href', ('/handlers/login-handlers/userloginhandler2.ashx?' + _sepaConnectLink.attr('rel')));	
		}			
	}
	else	
	{
		_url = "http://www.sepaconnect.org/higherlogic/security/logout.aspx?ReturnUrl=http%3A%2F%2Fwww.solarelectricpower.org%2F";
		
		// Does the sepaConnectLink exist?
		if (_sepaConnectLink.length == 1)
		{
			_sepaConnectLink.attr('href', ('/login.aspx?' + _sepaConnectLink.attr('rel')));	
		}			
	}
	
	if (_url != null)	
	{
		// Does the <img> exist?
		if ($("#sepaConnectAuthenticate").length == 1)		
		{
			$("#sepaConnectAuthenticate").attr("src", _url);
		}
		else		
		{
			$("#sepaConnectAuthenticateBox").append('<img id="sepaConnectAuthenticate" alt="SEPA Connect" style="display:none;width:0;height:0;" src="' + _url + '" />');	
		}	
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// 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
	{
		var _loginFailed = $(LOGIN_FAILED);
		var _loginProgress = $(LOGIN_PROGRESS);	
		var _uname = $(UNAME_FIELD);
		var _password = $(PWD_FIELD);
	
		// Confirm the field values.
		var username = $.trim(_uname.val());
		var password = $.trim(_password.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.css("border", "solid 1px red");
		}
		
		if (password.length <= 0)
		{
			errorMessage += "<li>Please enter a non-empty password value.</li>";
			_password.css("border", "solid 1px red");
		}
		
		if (errorMessage.length > 0) 
		{
			_loginFailed.html("Please correct the following errors:<ul>" + errorMessage + "</ul>").show();
		}
		else 
		{		
			_loginFailed.hide().html("Unfortunately, the credentials do not match an existing account.<br />Please check the spelling and case of the credentials and then try again.");
		
			_loginProgress.fadeIn(LUI_DURATION, function(){
				$.ajax({
					type: "POST",
					url:LOGIN_URL,
					data:"username=" + _uname.val() + "&password=" + _password.val(),
					complete: function(XMLHttpRequest, textStatus)
					{
						//alert(XMLHttpRequest.responseText);
					},
					success: function(data, success)
					{
						if (data == "SUCCESS") 
						{
							_loginProgress.fadeOut(LUI_DURATION, function()
							{
								$(LOGIN_FORM).fadeOut(LUI_FORM_DURATION);
								
								SSO_AUTH_TOKEN = GetSSOAuthToken();								
								
								SynchAuthState();
												
								var rurl = $.queryStringParameter('ReturnUrl');
								
								if ((rurl != null) && (rurl.length > 0))
								{								
									window.location.href = unescape(rurl);
								}
								
								SEPAConnectAuthenticate(true);
								
								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
						{
							_loginProgress.hide();
							_loginFailed.show();							
						}
					}
				});				
			});
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'LogIn()' function:\n\n" + e);
	}
}

function RedirectToLoginForm()
{
	window.location.href = ('/log-in.aspx?returnURL=' + escape($(PREVIEW_LINK).html()));
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// 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();
								
								SEPAConnectAuthenticate(false);
								
								try								
								{
									$.get(AMS_LOGOUT_URL);	
								}
								catch(e1){}					
															
																
								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;
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Attempts to retrieve a dimension for a Colorbox dialog
// from a CSS class name.
// Last Revision Date:  05/25/2010
// Parameters:
//		className:  The CSS class name
//		dimension:  A text identifier for the dimension
//		defaultValue:  A default dimension to use if a match isn't found
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetCBDimensionFromClass(className, dimension, defaultValue)
{
	var returnValue = defaultValue;	
	
	if ((className != null) && (className.length > 0))	
	{	
		var re = new RegExp((".*cb" + dimension + "(\\d+(?:%|px)?)*.*"));
		
		var matches = re.exec(className);
		
		if ((matches != null) && (matches.length == 2))					
		{
			returnValue = matches[1];
		}
	}	
	
	return returnValue;
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Creates colorbox links for a specified selector.
// Last Revision Date:  05/25/2010
// Parameters:
//		selector:  The jQuery selector expression
//		isIframe:  Indicates whether the dialog will use iframes
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function CreateColorBoxLinks(selector, isIframe)
{
	if (isIframe == true)
	{	
		$(selector).colorbox({width: function()
			{
				return GetCBDimensionFromClass(this.className, 'w', '50%');
			}
			,height: function()
			{
				return GetCBDimensionFromClass(this.className, 'h', '25%');
			}
			,iframe:true
		});			
	}
	else	
	{
		$(selector).colorbox({width: function()
			{
				return GetCBDimensionFromClass(this.className, 'w', '50%');
			}
			,height: function()
			{
				return GetCBDimensionFromClass(this.className, 'h', '25%');
			}
			,inline:true, href:function(){return this.rel;}
		});
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Synchronizes the CSS styles for page links including
// links to the active page.
// Last Revision Date:  07/21/2010
// Parameters:		None	
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SynchronizePageLinkStyles()
{
	// 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)
	{
		var _link = $(this);		
		
		// 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 ((_link.attr("href").toLowerCase() == pathNameLC) ||  DoesCurrentPathnameContainLinkRel(pathNameLC, _link.attr("rel").toLowerCase()))
		{
			// Alter the link color to white to represent that the page is active for the link.
			_link.css("color", "#fff");				
			
			_link.parent().css("background-color", "#7BA2C6");
		}
	});
	
	// Synchronize aux links.
	$(AUX_LINKS + " a[href='" + pathName + "']").css("color", "white");		
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Initializes the display of the page auxiliary links menus.
// Last Revision Date:  07/21/2010
// Parameters:		None	
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function InitializeAuxiliaryLinkPreviewFunctionality()
{
	// Store the original style for the original aux links.
	if ((PAGE_AUX_LINKS_SELECTOR.length == 1) && (ORIGINAL_AUX_LINKS_SELECTOR.length == 1))	
	{
		var _originalStyle = PAGE_AUX_LINKS_SELECTOR.attr('style');
		
		ORIGINAL_AUX_LINKS_SELECTOR.attr('style', ((_originalStyle != undefined) ? _originalStyle : ''));		
	}
	
	$(AUX_LINKS_SELECTOR).hover(
		function()		
		{
			var _link = $(this);
			
			// Retrieve the current link text, and replace any special text values.
			var _JID = ("#auxLinksFor" + _link.text().toLowerCase().replace(' & ','-and-').replace(' ','-'));//.replace('home','welcome'));
			
			// Search for the matching auxlinks container element by DOM ID.
			var _auxLinksCont = $(_JID);
			
			// Does the target container exist?
			if (_auxLinksCont.length == 1)			
			{
				// Adjust the matching top-level link's class to provide a visual cue of the aux links being displayed.
				_link.parent().toggleClass(ACTIVE_AUX_LINK_PARENT_CSS_NAME);
				
				// Read the override style for the _auxLinksContainer.
				// If the 'style' attribute doesn't exist, attr() returns undefined.
				var _style = _auxLinksCont.attr('style');
				
				// Set the override style for the PAGE_AUX_LINKS_SELECTOR container element.
				PAGE_AUX_LINKS_SELECTOR.html(_auxLinksCont.html()).attr('style', ((_style != undefined) ? (_style) : ''));
			}
		},
		function()		
		{
			// Remove the 'activeAuxLink' class.
			$(this).parent().toggleClass(ACTIVE_AUX_LINK_PARENT_CSS_NAME);
		}
	);
	
	$(PAGE_AUX_LINKS_SELECTOR).mouseleave(function()		
	{
		var _originalStyle = ORIGINAL_AUX_LINKS_SELECTOR.attr('style');
		
		// Replace the active aux links with the original aux links for the current page.
		PAGE_AUX_LINKS_SELECTOR.html(ORIGINAL_AUX_LINKS_SELECTOR.html()).attr('style', ((_originalStyle != undefined) ? _originalStyle : ''));
		
		SynchronizePageLinkStyles();			
	});		
}

$(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");
	
	SynchronizePageLinkStyles();
	
	InitializeAuxiliaryLinkPreviewFunctionality();

	// 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));
		
		return false;
	});	
		
	$(LOGIN_BUTTON).click(function()
	{
		LogIn();
		
		return false;
	});
	
	// 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();
	});	
	
	// Respond to the click event for the show login form links.
	$(LINK_SHOW_LOGIN).live("click", function()	
	{	
		ShowLogInDialogFromLinkOrRedirect($(this));
		
		return false;		
	});	
	
	// 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);
	});
	
	CreateColorBoxLinks(CB_INLINE, false);
	
	CreateColorBoxLinks(CB_IFRAME, true);

	$("a.groupedImageCB").colorbox(); 
		
	var _contentRotatorBoxes = $('#outerLayout div.contentItemRotatorBox');
	
	// Is there at least one content rotator box defined?
	if (_contentRotatorBoxes.length > 0)
	{
		// Dynamically load the jQuery.cycle script.
		jQuery.getScript('http://ajax.aspnetcdn.com/ajax/jquery.cycle/2.99/jquery.cycle.all.min.js', function()
		{		
			_contentRotatorBoxes.each(function(i)
			{
				var _contentRotatorBox = $(this);
				var _classNames = _contentRotatorBox.attr('class');

				// Locate a classname of the form contentDelay<integer-value> and capture the match.
				// If found, the delay value should be a match index 1.
				var slideDelayMatches = new RegExp(/(?:.*contentDelay(\d*))/).exec(_classNames);
				
				//alert(slideDelayMatches[1]);
				
				// Ensure a default slide delay.
				if (slideDelayMatches != null)
				{
					// Ensure that the captured match represents a numeric value.
					if (slideDelayMatches[1].length > 0)
					{										
						slideDelay = slideDelayMatches[1];
					}
					else
					{
						slideDelay = 5000;	
					}									
				}		
				
				_contentRotatorBox.cycle(
				{
					// ms between slide transitions
					timeout:slideDelay,
					// true for random, false for sequence
					random:1, 
					// true to enable "pause on hover" 
					pause:1	
				}).show();				
			});
		});
	}	
});
