var loginHtml; 
var loggedIn = false;
var COMM_REG_REDIRECT_URL = '';

if (document.forms != null && document.forms.length > 0 && document.forms[0].SignoutPath != null)
{    
    signoutPath = document.forms[0].SignoutPath.value;
}

// catch clicks only on the login popup layer
$(document).ready(function() {
    $("#login_popup_layer").bind('click', function(ev) {
        if ($(ev.target).is('.rating-app') || $(ev.target).parents('.rating-app').length) {
            
            switch(ev.target.className) {
            case "close":
                CloseLoginPopup();
                break;
            case "continue":
                // Handle the community username link
                if($(ev.target).attr("name") == "NoCommunityUsernameLink")
                {
                	// If the community registration redirect is defined then use it.
                	if (COMM_REG_REDIRECT_URL != null && typeof(COMM_REG_REDIRECT_URL) == "string" && COMM_REG_REDIRECT_URL.length > 0)
                	{
                		$(ev.target).attr({ href: COMM_REG_REDIRECT_URL});
                	}
                	// Otherwise, use the current href and update url to include the return url. slashes are encoded to avoid url rewriting.
                	else
                	{
				$(ev.target).attr({ href: $(ev.target).attr("href") + "?s=" + escape(location.toString()).replace(/\//g, "%2F")});
			}
			//alert('redirecting to ' + $(ev.target).attr('href'));
			return true;
			break;
                }
                //handle the continue button on the forgot password box
                if($(ev.target).attr("name") == "ForgetPasswordSubmitLink")
                {
                    ForgotPasswordSubmit($(ev.target));                 
                }
                else
                {
                    //any other continue just brings back the login gui
                    OpenLoginPopup();                    
                }
                adjustLoginPopup();
                
                ev.preventDefault(); //prevent the page from jumping
                return false;
                break;
            case "signin":
                LoginPopupSubmit(ev.target);
                return false;
                break;
            case "textLink":
                // call a function and do something
                return false;
                break;
            default:
                break;
            }
        }
        else
        {
            // Closes/hides the layer when you click anywhere else.
            CloseLoginPopup();
        }
    });
});

function OpenLoginPopup(sender, popupTitle, popupMessage, commRegRedirectUrl, nameAnchorRedirect)
{
	// Look for the "community registration redirect url".
	COMM_REG_REDIRECT_URL = commRegRedirectUrl;
	// If not found, look for a custom attribute on the sender.	
	if (sender != null && (COMM_REG_REDIRECT_URL == null || COMM_REG_REDIRECT_URL.length <= 0))
	{
		COMM_REG_REDIRECT_URL = $(sender).attr('comm_reg_url');
	}
	
	// Set the "name anchor redirect".
	try
	{
		var nameAnchorElement = document.getElementById('name_anchor_redirect');
		if (nameAnchorElement != null)
		{
			if (nameAnchorRedirect == null)
			{
				nameAnchorRedirect = "";
			}

			nameAnchorElement.value = nameAnchorRedirect;
		}
	}
	catch (e) {}
	
	ShowSignIn("login_popup_container", true, sender, popupTitle, popupMessage);
}

function CloseLoginPopup()
{
	$(".login_popup_container").hide();
	// remove IE6 shim if exists - vc
	if (document.getElementById("login_popup_layer-cover")) {
	    $("#login_popup_layer-cover").remove();
	}
	
}

function LoginPopupSubmit(sender)
{
	if (sender != null)
	{
		disableElements(null, sender.className);
	}
	new AjaxRequest(sender, null, ProcessLoginResults, true).run();
}

//function LoginPopupSignIn(email, password, signoutPath, serverPath, callbackFunction)
//{        
//	serverPath += "&e=" + escape(email);
//	serverPath += "&passwd=" + escape(password);
//	serverPath += "&sop=" + escape(signoutPath);
//	serverPath += "&jsnstsvar=LoginJsonStatus"; 
//
//	new AjaxRequest(serverPath, null, callbackFunction).run();
//}

function ForgotPasswordSubmit(sender)
{
	if (sender != null && $(sender).size() > 0)
	{
		disableElements(null, $(sender).get(0).className);
	}
	$(".login_popup_container").load(
	    $(sender).attr("ajaxhref"),
	    {
		e: escape(document.forms[0].forgotpasswordemail.value)
	    }	    
	);
}

function ShowForgotPassword()
{
	LoginHideAll();

	$("#ForgotPassword").show();
	// Put focus on the field.
	$(".login_popup_forgot_pwd").focus();

	return false;
}

function ShowSignIn(mainPopupContainerName, forceDisplay, sender, popupTitle, popupMessage)
{
    // close any other instances - vc
    CloseLoginPopup();
    
	var mainLayer = $("." + mainPopupContainerName);
	mainLayer = (mainLayer.size() > 0 ? mainLayer.get(0) : null);
        
	//dont do anything if the popup is already visible, unless forced!
	if (forceDisplay || (mainLayer == null || mainLayer.style.display == "none")) //brett
	{                    
		//if they arent yet logged in, reload the original login html so that only signin comes up, and not error messages, or forget password, etc      
		if(!loggedIn && (loginHtml != null && loginHtml != ""))
		{ 
			//rewrite the orginal login html      
			$("." + mainPopupContainerName).html(loginHtml);
		}
		else
		{
			//save the login html
			loginHtml = $("." + mainPopupContainerName).html();
		}  

		LoginHideAll();
		
		// If the sender is defined then attempt to position the popup relative to the sender.
		if (sender != null)
		{
		    positionLoginPopup(sender);
		}	
		
		if (popupTitle != null && typeof(popupTitle) == "string")
		{
			$(".login_popup_title").html(popupTitle);
		}
		
		if (popupMessage != null && typeof(popupMessage) == "string")
		{
			$(".login_popup_message").html(popupMessage);
		}

		$("#LoginBox").show();

		$("." + mainPopupContainerName).show();

		// Put focus on the email field.
		$(".login_popup_email").focus();
	}  
}

function LoginHideAll()
{
	$("#LoginBox").hide();	
	$("#ForgotPassword").hide();
}


//(re)load the logged in menus
/*
function ReloadMainMenu(signoutPath)
{ 
    var menuUpdatePath = document.forms[0].MenuUpdatePath.value;    
    menuUpdatePath += "&sop=" + signoutPath        
    var ajaxRequest = new AjaxRequest(menuUpdatePath, null, UpdateHeader).run();  
}
*/

function UpdateMenu(rawResponse)
{       
	if (rawResponse != null && rawResponse.length > 0)
	{
		//remove any extra form elements
		//var regex = new RegExp("<form(.+)>");
		//rawResponse = rawResponse.replace(regex,"");    
		//rawResponse = rawResponse.replace("</form>","");
		
		$("#HeaderContainer").html(rawResponse);  

		if (navList)
		{
			navList(); //reintialize hover events on the menu (for IE)
		}
	}
}


function GetLoginStatusFromResponse(rawResponse)
{
    var status = false;
    
    if(rawResponse != null && rawResponse.length > 0)
    {
        //parse out the LoginJsonStatus variable from the response
        var searchString = "LoginJsonStatus=";
        var startPos = rawResponse.indexOf(searchString);
        
        if (startPos > -1)        
        {
            startPos += searchString.length; //reset to the begining of the variable
        
            var statusString =  rawResponse.substring(startPos);
            var endPos = statusString.indexOf(";");
            statusString = statusString.substring(0, endPos);    

            var LoginJsonStatus = eval('(' + statusString + ')');
            
            if (LoginJsonStatus != null)        
            {  
                
               if(LoginJsonStatus.JsonStatus != null)
               {
                   if (LoginJsonStatus.JsonStatus.StatusCode == 0)           
                   {               
                        //login sucess                                     
                        status = true;
                   }
               }
               else
               {
                    status = true;
               }
            }   
        }
    }  
    
    return status;
}

function ProcessLoginResults(sender, statusCode, rawResponse)
{
    if (GetLoginStatusFromResponse(rawResponse))
    {
        // Login successful!
        loggedIn = true;
        
        // Load the logged in menus..they will have been included in the response if it was successful
        UpdateMenu(rawResponse);
        
        var loginCallbacks = $(sender).attr("logincb");
        if (loginCallbacks != null && loginCallbacks.length > 0)
        {
		loginCallbacks = eval(loginCallbacks);
		
		for (var i = 0; i < loginCallbacks.length; i ++)
		{
			var aLoginCallback = eval(loginCallbacks[i]);
			if ((aLoginCallback != null) && (typeof(aLoginCallback) == "function"))
			{
				aLoginCallback(sender);
			}
		}
	}
	else
	{
		CloseLoginPopup();
	}
    }
    else
    {
        //login failed...write the rawResponse to the popup...it will include the error message
        $(".login_popup_container").html(rawResponse);          
        adjustLoginPopup();        
    }
}

//
// Returns client position of the given DOM element within the browser window,
// or, within the given "element container" (if elemContainer is non-null).
// The position is returned as a JSON object with properties "left" and "top".
//
function GetClientPosition(elem, elemContainer)
{
	if (typeof(elem.offsetParent) != 'undefined')
	{
		for (var posX = 0, posY = 0; elem != null && elem != elemContainer; elem = elem.offsetParent)
		{
			posX += elem.offsetLeft;
			posY += elem.offsetTop;
		}
		return {'left':posX, 'top':posY};
	}
	else
	{
		return {'left':elem.x, 'top':elem.y};
	}
}

// show please wait and change class
function disableElements(thisEl, buttonClass) {
	if (thisEl == null)
	{
		thisEl = $(".login_popup_layer");
	}
	
	if (thisEl != null)
	{
		$(thisEl).children().find("a."+buttonClass).attr("class","pleasewait");
		$(thisEl).children().find("input").css("background", "#f0f0f0");
	}
}

function positionLoginPopup(sender) {     
    
    if (sender != null)     
    {  
	    // Get the sender's client position within the main container DIV.
	    var position = GetClientPosition(sender, document.getElementById('container'));

    	
	    // determine anchor relative to edge of page container
        var linkDifference = Math.abs($("#container").offset({scroll: false}).left-$(sender).offset({scroll: false}).left);
        
        // determine pop-up layer size
        var boxWidth = $("#login_popup_layer").outerWidth();
    	
	    // determine how the box should be rendered - left or right side
        if (linkDifference < boxWidth) {
            // put on right side
            if (!($("#login_popup_layer div.arrow_left").size() > 0)) {
                $("#login_popup_layer").append("<div class='arrow_left'></div>");        
            }                        
            var leftOffset = $(sender).width() + 48;
           
	        $(".login_popup_container").css("left", position.left + leftOffset).css("top", position.top); // -290                 
        } else {
            // put on the left side
            if (!($("#login_popup_layer div.arrow").size() > 0)) {
                $("#login_popup_layer").append("<div class='arrow'></div>");            
            }        
            $(".login_popup_container").css("left", position.left -226).css("top", position.top); //-265 -290     
        }    
        // add iframe if necessary
    	addIframe();	    
	}	 	
}

function adjustLoginPopup() {   
    // determine existing popup location relative to edge of page container
    var leftEdgeOfContainer = $("#container").offset({scroll: false}).left;
    var leftEdgeOfLP = $("#login_popup_layer").offset({scroll: false}).left;
    
    var linkDifference = Math.abs(leftEdgeOfContainer-leftEdgeOfLP);
    
    // determine pop-up layer size
    var boxWidth = $("#login_popup_layer").outerWidth();
	
    // determine how the box should be rendered - left or right side
    if (linkDifference < boxWidth) {
        // put on right side
        if (!($("#login_popup_layer div.arrow_left").size() > 0)) {
            $("#login_popup_layer").append("<div class='arrow_left'></div>");        
        }                        
    } else {
        // put on the left side
        if (!($("#login_popup_layer div.arrow").size() > 0)) {
            $("#login_popup_layer").append("<div class='arrow'></div>");            
        }                
    }    
    // add iframe if necessary
	addIframe();	    
}

//
// Adds iframe punch through fix if running in IE6 and only if the iframe doesn't already exist.
//
function addIframe() {
    if ($.browser.msie && (typeof XMLHttpRequest == 'function' || !window.XMLHttpRequest)) {     
        if (!(document.getElementById("login_popup_layer-cover"))) {
            // Add iframe cover hack if IE6 -vc
	        if ($.browser.msie && (typeof XMLHttpRequest == 'function' || !window.XMLHttpRequest)) { 
	            var coverFrame = "<IFRAME id='login_popup_layer-cover' src='javascript:void(0);' frameBorder='0' scrolling='no'></IFRAME>";
	            var coverTop = $("#login_popup_layer").css("top");
	            var coverLeft = $("#login_popup_layer").css("left"); 			
	            // append the iframe before to cover IE selectbox
	            $(coverFrame).insertBefore($("#login_popup_layer")).css("left", coverLeft).css("top", coverTop);
	        }
        }    
    }
}
