﻿var CommunityLogin = 
{
    CenterScreenTimeout: null,

    CenterScreen: function(elementId)
    {
        var $centerDiv = $(elementId);
        var windowsHeight = $(window).height();
        var windowsWidth = $(window).width();
        
        $centerDiv.css({
            'position': 'absolute',
            'top': ((windowsHeight / 2 - $centerDiv.height() / 2) + $(window).scrollTop()) + 'px',
            'left': (windowsWidth / 2 - $centerDiv.width() / 2) + 'px',
            'z-index': '25'
        });
        
        if ($centerDiv.css('display') == 'none')
        {
            $centerDiv.slideDown(500, function()
            {
                if (elementId == '#OpenIdPopUp')
                    $('#' + GetClientId('openid_identifier')).focus();
            });
        }

        CommunityLogin.CenterScreenTimeout = setTimeout(function() { CommunityLogin.CenterScreen(elementId); }, 50);
    },
    
    DisplayLoginButton: function(controlId)
    {
        $('#' + controlId).css('display', '');
    },
    
    DisplayLogInThrobber: function(display)
    {
        if (display)
        {
            $('#login_tdn').css('display', 'none');
            $('#login_intersoft').css('display', 'none');
        }
        
        $('#login_throbber').css('display', display == true ? '' : 'none');
    },        
    
    ShowErrorLogin: function(controlId)
    {
        var element = document.getElementById(GetClientId(controlId));
        CreateForumCallOut("ErrorLogin", element );
        element.focus();
    },
    
    Refresh: function()
    {
        if (window.location.href.indexOf("#") == -1)
        {
            var date = new Date();
            
            var href = window.location.href;
            if (href.indexOf("?") != -1)
            {
                var query = "?";
                var hrefParts = href.split("?");
                var parts = hrefParts[1].split("&");
                
                for (var i = 0; i < parts.length; i++)
                {
                    if (parts[i].indexOf("=") != -1)
                    {
                        query += parts[i] + "&";
                    }
                }
                
                window.location.href = hrefParts[0] + query + date.getTime();
            }
            else
            {
                href = (href.substr(href.length - 1, 1) == "/") ? href : href + "/";
                window.location.href = href + "?" + date.getTime();
            }
        }
        else
            window.location.reload(true);
    },
    
    ResetPassword: function()
    {
        $('#' + GetClientId('login_password')).val('');    
    }
};

var CommunityLoginAJAX =
{
    AJAXLogin: null,

    AJAXTimeout: function(functionName, timeout)
    {
        var ajaxManager = CommunityLoginAJAX.GetAJAXManager();
        if (ajaxManager == null)
        {
            window.setTimeout(function() { CommunityLoginAJAX.AJAXTimeout(functionName); }, timeout);
        }
        else
        {
            switch (functionName)
            {
                case "CheckSessionTimeout":
                    ajaxManager.Invoke(functionName);
                    break;
                case "DoLoginIntersoft":
                case "DoLoginTDN":
                    var username = $('#' + GetClientId('login_username')).val();
                    var password = $('#' + GetClientId('login_password')).val();
                    var rememberMe = $('#' + GetClientId('checkRememberMe'))[0].checked + "";

                    if (functionName == "DoLoginIntersoft")
                        password = $.md5(username.toLowerCase() + password);

                    ajaxManager.Invoke(functionName, username, password, rememberMe);
                    break;
                case "DoLogout":
                    ajaxManager.Invoke(functionName);
                    break;
            }
        }
    },

    GetAJAXManager: function()
    {
        if (CommunityLoginAJAX.AJAXLogin == null)
        {
            CommunityLoginAJAX.AJAXLogin = new WebFlyPostBackManager("loginFPB");
            CommunityLoginAJAX.AJAXLogin.OnInitialize();

            with (CommunityLoginAJAX.AJAXLogin)
            {
                _Asynchronous = true;
                Asynchronous = true;
                ServiceUrl = document.getElementById("fpbmLoginConn").value;
                PostViewState = false;
                PostInputControls = false;
                PostHiddenFields = false;
                PostControlState = false;
                ClientSideEvents.OnResponseSuccess = "CommunityLoginAJAX.OnResponse";
                ClientSideEvents.OnError = "CommunityLoginAJAX.OnError";
            }
        }

        return CommunityLoginAJAX.AJAXLogin;
    },

    OnError: function(controlId, functionName, error)
    {
    },

    OnResponse: function(controlId, functionName, returnValue)
    {
        switch (functionName)
        {
            case "CheckSessionTimeout":
                if (returnValue)
                {
                    setTimeout(function() { CommunityLoginAJAX.CheckSessionTimeout(); }, 3600000); // 1 hour
                }
                else
                {
                    DisplayBlocker(true);
                    CommunityLogin.CenterScreen('#SessionInformation');
                }
                break;
            case "DoLoginIntersoft":
            case "DoLoginTDN":
                var result = unescape(returnValue).split(";");

                switch (result[0])
                {
                    case "success":
                        CommunityLogin.Refresh();
                        break;
                    case "fail":
                        CommunityLogin.ResetPassword();
                        CommunityLogin.ShowErrorLogin("login_password");
                        break;
                    case "register":
                        if (functionName == "DoLoginIntersoft")
                            window.location = "/Community/Registration.aspx";
                        else
                            window.location = "/Community/Registration.aspx?referral=" + location.href;
                        break;
                }

                CommunityLogin.DisplayLogInThrobber(false);

                if (functionName == "DoLoginIntersoft")
                    CommunityLogin.DisplayLoginButton("login_intersoft");
                else
                    CommunityLogin.DisplayLoginButton("login_tdn");

                break;
            case "DoLogout":
                CommunityLogin.Refresh();
                break;
        }
    },

    CheckSessionTimeout: function()
    {
        if (document.getElementById("hasLogin") != null)
            CommunityLoginAJAX.AJAXTimeout("CheckSessionTimeout", 2000);
    },

    DoLogin: function(type)
    {
        CommunityLogin.DisplayLogInThrobber(true);

        switch (type)
        {
            case "Intersoft":
                CommunityLoginAJAX.AJAXTimeout("DoLoginIntersoft", 100);
                break;
            case "TDN":
                CommunityLoginAJAX.AJAXTimeout("DoLoginTDN", 100);
                break;
        }

        event.cancelBubble = true;
        event.returnValue = false;
        return false;
    },

    DoLogout: function()
    {
        CommunityLoginAJAX.AJAXTimeout("DoLogout", 100);

        event.cancelBubble = true;
        event.returnValue = false;
        return false;
    }
};

var CommunityFeedsAJAX =
{
    AJAXFeeds: null,

    AJAXTimeout: function(functionName, timeout)
    {
        var ajaxManager = CommunityFeedsAJAX.GetAJAXManager();
        if (ajaxManager == null)
        {
            window.setTimeout(function() { CommunityFeedsAJAX.AJAXTimeout(functionName); }, timeout);
        }
        else
        {
            switch (functionName)
            {
                case "GetSplashNewsFromBlog":

                    ajaxManager.Invoke(functionName);
                    break;
            }
        }
    },

    GetAJAXManager: function()
    {
        if (CommunityFeedsAJAX.AJAXFeeds == null)
        {
            CommunityFeedsAJAX.AJAXFeeds = new WebFlyPostBackManager("feedsFPB");
            CommunityFeedsAJAX.AJAXFeeds.OnInitialize();

            with (CommunityFeedsAJAX.AJAXFeeds)
            {
                _Asynchronous = true;
                Asynchronous = true;
                WebServiceResponseFormat = "Json";
                ServiceUrl = document.getElementById("fpbmFeedsConn").value;
                PostViewState = false;
                PostInputControls = false;
                PostHiddenFields = false;
                PostControlState = false;
                ClientSideEvents.OnResponseSuccess = "CommunityFeedsAJAX.OnResponse";
                ClientSideEvents.OnError = "CommunityFeedsAJAX.OnError";
            }
        }

        return CommunityFeedsAJAX.AJAXFeeds;
    },

    OnError: function(controlId, functionName, error)
    {
    },

    OnResponse: function(controlId, functionName, returnValue)
    {
        switch (functionName)
        {
            case "GetSplashNewsFromBlog":
                if (returnValue != null)
                {
                    var newsFeedContainer = document.getElementById("newsFeedContainer");
                    var newsFeed = "";

                    var caption;
                    
                    for (var i = 0; i < returnValue.length; i++)
                    {
                        caption = "Posted : " + returnValue[i].PublishDate;
                        newsFeed += "<p><a class=\"actionlink\" href=\"" + returnValue[i].Url + "\" target=\"_blank\" alt=\"" + caption + "\" title=\"" + caption + "\">" + returnValue[i].Title + "</a></p>";
                    }

                    newsFeedContainer.innerHTML = newsFeed;

                    if (!IS.ie)
                        Animation.Do(newsFeedContainer, "FadeIn", 3, null);
                }
                break;
        }
    },

    InitializeFeeds: function()
    {
        CommunityFeedsAJAX.AJAXTimeout("GetSplashNewsFromBlog", 100);
    }
}
        

$(function() { $("div.openid:eq(0)").openid(); });

$(document).ready(function() 
{
    if ($('.loginbox').length > 0)
    {
        $('#' + GetClientId('login_username')).focus(function() { OnFocusLoginInput(this); });
        $('#' + GetClientId('login_username')).blur(function() { OnBlurLoginInput(this); });

        $('#' + GetClientId('login_password')).focus(function() { OnFocusLoginInput(this); });
        $('#' + GetClientId('login_password')).blur(function() { OnBlurLoginInput(this); });

        $('.loginwatermark').click(function() { FocusLoginInput(this); });

        $('ul#LoginType div').mouseover(function() { $(this).css('background-image', 'url(/WebResources/Images/Community/login/LoginStatusActiveBackground.png)'); });
        $('ul#LoginType div').mouseout(function() 
        {
            if ($(this).hasClass('highlight'))
                $(this).css('background-image', 'url(/WebResources/Images/Community/login/LoginStatusActiveBackground.png)');
            else
                $(this).css('background-image', '');
        });

        $('ul#LoginType div').click(function() 
        {
            $('ul#LoginType div').css('background-image', '');
            $('ul#LoginType div').removeClass('highlight');
            $(this).css('background-image', 'url(/WebResources/Images/Community/login/LoginStatusActiveBackground.png)');
            $(this).addClass('highlight');
        });

        $('ul#LoginType div:eq(2)').click(function() {
            ShowConfirmationPopUp('google');
        });

        $('li[name=yahoo]').click(function() {
            ShowConfirmationPopUp('yahoo');
        });

        $('ul#LoginType div:eq(3)').click(function() {
            DisplayBlocker(true);
            $('#LeaveConfirmationOpenId').hide();
            CommunityLogin.CenterScreen('#OpenIdPopUp');
        });

        $('ul#LoginType div:eq(0)').click(function() {
            $('#login_tdn').css('display', 'none');
            $('#login_intersoft').css('display', '');
            $('#userwatermark').html('<em>Intersoft Social ID</em>');
        });

        $('ul#LoginType div:eq(1)').click(function() {
            $('#login_tdn').css('display', '');
            $('#login_intersoft').css('display', 'none');
            $('#userwatermark').html('<em>Intersoft ID</em>');
        });

        $('#closePopUp').click(function() { ClosePopUp('OpenIdPopUp'); });

        if ($('input[id$=OpenIdError]').val() != "") {
            DisplayBlocker(true);
            $('#LeaveConfirmationOpenId').hide();
            CommunityLogin.CenterScreen('#OpenIdPopUp');
            ResizeOpenIdPopUpBox('large');
            switch ($('.openIdProvider').val()) {
                case 'google':
                    break;
                case 'yahoo':
                    break;
                default:
                    $('input[id$=openid_identifier]').val($('input[id$=providerRequest]').val());
                    $('#openid_error_label').text($('input[id$=OpenIdError]').val());
                    $('#openid_error_label').css({ 'display': '', 'color': 'red', 'margin-top': '15px' });
                    $('input[id$=OpenIdError]').val('');
                    break;
            }
        }
    }

    if ($('input[type=text]').length > 0) {
        $('input[type=text]').keydown(function() {
            if (event.keyCode == 13) {
                event.cancelBubble = true;
                event.returnValue = false;
                return false;
            }
        });
    }

    if ($('input[type=password]').length > 0) {
        $('input[type=password]').keydown(function() {
            if (event.keyCode == 13) {
                event.cancelBubble = true;
                event.returnValue = false;
                return false;
            }
        });
    }
});

function ShowConfirmationPopUp(provider) 
{
    event.cancelBubble = true;
    event.returnValue = false;

    var $elemObj = null;
    
    switch (provider) {
        case "yahoo":
            break;
        case "google":
            break;
        case "openid":
            $elemObj = $('input[id$=openid_identifier]');
            if ($elemObj.val() == "") {
                $elemObj.focus();
                return false;
            }
            else {
                ResizeOpenIdPopUpBox('small');
                $('#openid_error_label').css('display', 'none');
            }
            break;
        default:
            $elemObj = $('input[id$=openid_username]');
            if ($elemObj.val() == "") {
                $elemObj.focus();
                return false;
            }
            break;
    }
    
    if ($('#' + GetClientId('IgnoreLeaveWarning')).val() == '0') {
        ShowConfirmationWindow(provider);
        return false;
    }
    else {
        SetProviderString(provider);
        $('form').submit();
    }
}

function ClosePopUp(popUpId, abortBlocker) 
{
    $('#' + popUpId).css('display', 'none');
    if (abortBlocker == null)
        DisplayBlocker(false);
    ResizeOpenIdPopUpBox('small');
    clearTimeout(CommunityLogin.CenterScreenTimeout);
    CommunityLogin.CenterScreenTimeout = null;

    event.cancelBubble = true;
    event.returnValue = false;

    return false;
}

function ConfirmSubmitForm(provider) {
    SetProviderString(provider);
    
    if(provider == 'google')
        $('#' + GetClientId('IgnoreLeaveWarning')).val($('#CheckboxConfirmLeave')[0].checked ? '1' : '0');
    else
        $('#' + GetClientId('IgnoreLeaveWarning')).val($('#CheckboxConfirmLeaveOpenId')[0].checked ? '1' : '0');

    $('form').submit();
}

function ResizeOpenIdPopUpBox(size) {
    switch (size) {
        case 'small':
            $('.leftBoxId').css({
                'background-image': 'url(/WebResources/images/community/login/BoxLeft.png)',
                'height': '152px'
            });
            $('.midBoxId').css({
                'background-image': 'url(/WebResources/images/community/login/BoxMid.png)',
                'height': '152px'
            });
            $('.rightBoxId').css({
                'background-image': 'url(/WebResources/images/community/login/BoxRight.png)',
                'height': '152px'
            });
            break;
        case 'large':
            $('.leftBoxId').css({
                'background-image': 'url(/WebResources/images/community/login/BoxLeftTall.png)',
                'height': '252px'
            });
            $('.midBoxId').css({
                'background-image': 'url(/WebResources/images/community/login/BoxMidTall.png)',
                'height': '252px'
            });
            $('.rightBoxId').css({
                'background-image': 'url(/WebResources/images/community/login/BoxRightTall.png)',
                'height': '252px'
            });
            break;
    }
}

function DisplayBlocker(display)
{

    if (display)
    {
        var $divBlocker = $('<div id="uiblocker"></div>');
        $divBlocker.css({ 'width': '100%', 'height': $('form').height(), 'z-index': '10', 'position': 'absolute',
            'top': '0px', 'left': '0px', 'background-color': 'black', 'opacity': '0.7', 'filter': 'alpha(opacity=70)'
        });
        $divBlocker.appendTo("form");
    }
    else
    {
        $('#uiblocker').remove();
    }
}


function DisplayLogin()
{
    $('.profilebox').css('display', 'none');
    $('.loginbox').css('display', '');

    $('ul#LoginType div').removeClass('highlight');
    $('ul#LoginType div:eq(0)').addClass('highlight');

    $('#login_intersoft').css('display', '');
    $('#login_tdn').css('display', 'none');
    $('#login_throbber').css('display', 'none');

    $('#userwatermark').html('<em>Intersoft Social ID</em>');
}

function DisplayWelcomeMessage(username)
{
    var el = document.getElementById("quickAccessAction");
    
    if (el != null)
    {
        Listener.Add(el, "onmouseover", QuickAccessMouseOver);
        Listener.Add(el, "onmouseout", QuickAccessMouseOut);
    }
    
    Listener.Add(window, "onunload", OnUnload);

    var d = new Date();
    var curr_hour = d.getHours();
    var note = "Good ";
    
    if (curr_hour <= 10)
    {
        note += "Morning";
    }
    else if (curr_hour <= 13)
    {
        note += "Day";
    }
    else if (curr_hour <= 17)
    {
        note += "Afternoon";
    }
    else
    {
        note += "Evening";
    }

    note += ", " + username;

    $('#WelcomeNotes').text(note);
}

function FocusLoginInput(element)
{
    var parentElement = element.parentElement;
    $('input', parentElement).focus();
}

function OnFocusLoginInput(element)
{    
    var watermarkElement = document.getElementById(element.attributes["watermark"].value);

    if (watermarkElement.style.display != "none")
        watermarkElement.style.display = "none";
}

function OnBlurLoginInput(element)
{    
    var watermarkElement = document.getElementById(element.attributes["watermark"].value);
    
    if (element.value == "")
    {
        watermarkElement.style.display = "";
    }
    else
    {
        watermarkElement.style.display = "none";
    }
}

function ShowConfirmationWindow(provider)
{

    if ($('#' + GetClientId('IgnoreLeaveWarning')).val() != 1)
    {
        var providerString = "";
        switch (provider)
        {
            case "google":
                DisplayBlocker(true);
                CommunityLogin.CenterScreen('#LeaveConfirmation');
                break;   
            case "yahoo":
                $('#LeaveConfirmationOpenId').show();
                break;
            default:
                ResizeOpenIdPopUpBox('large');
                $('#LeaveConfirmationOpenId').show();
        }

        return false;
    }

    return true;
}

function SetProviderString(provider)
{

    switch (provider)
    {
        case "google":
            $('#' + GetClientId('providerRequest')).val("https://www.google.com/accounts/o8/id");
            $('#' + GetClientId('openIdProvider')).val('google');
            break;
        case "yahoo":
            $('#' + GetClientId('providerRequest')).val("http://yahoo.com/");
            $('#' + GetClientId('openIdProvider')).val('yahoo');
            break;
        case "openid":
            providerString = $('#' + GetClientId('openid_identifier')).val();
            $('#' + GetClientId('providerRequest')).val(providerString);
            break;
        default:
            var pattern = $('#' + GetClientId('openid_providerpattern')).val();
            var username = $('#' + GetClientId('openid_username')).val();
            providerString = pattern.replace(new RegExp("[\{]0[\}]", "g"), username);
            $('#' + GetClientId('providerRequest')).val(providerString);
            break;
    }
}

function PerformLogin()
{
    if (event.keyCode == 13)
    {        
        var type = "";
        if ($('#login_tdn').css('display') != "none")
            type = "TDN";
        if ($('#login_intersoft').css('display') != "none")
            type = "Intersoft";

        return CommunityLoginAJAX.DoLogin(type);
    }
}

var animationInProgress = false;
var isMenuDisplayed = false;
var closeTimeOutId = -1;

function AnimateQuickAccess(isDown)
{
    var el = document.getElementById("quickAccess");
    var menu = document.getElementById("quickAccessMenu");
    
    if (isDown)
    {
        var left = ISPosLib.getLeftW3C(el);
        left = left - 5; //since the icon and menu element's size are fixed, the size is hardcoded
        left = (left < 0) ? 0 : left;
        
        menu.style.left = left + "px";
        menu.style.top = (ISPosLib.getTopW3C(el) + 17) + "px";
        menu.style.display = "";
        
        animationInProgress = true;
        Animation.Do(menu, "MenuSlideDown", null, function() {animationInProgress = false;}, {"Speed": IS.ie ? "Fast" : "Slow" });
    }
    else
    {
        animationInProgress = true;
        Animation.Do(menu, "MenuSlideUp", null, function() { isMenuDisplayed = false; animationInProgress = false; }, { "Speed": IS.ie ? "Fast" : "Slow" });
    }
}

function OnUnload()
{
    var el = document.getElementById("quickAccessAction");
    Listener.Unload(el);
}

function QuickAccessMouseOver()
{
    if (closeTimeOutId > -1)
    {
        clearTimeout(closeTimeOutId);
        closeTimeOutId = -1;
    }

    if (!isMenuDisplayed && !animationInProgress)
    {
        if (event.srcElement)
        {            
            var type = GetElementType(event.srcElement);            
            switch (type)
            {
                case "editProfile":
                    SetIconHoverStyle(document.getElementById("ctl00_ctl00_ctl00_ctl00_a_b_UserLogin1_editProfile"), true);
                    break;
                    
                case "viewprofile":
                case "viewprofilemenu":
                    SetIconHoverStyle(document.getElementById("quickAccess"), true);
                    AnimateQuickAccess(true);
                    isMenuDisplayed = true;
                    
                    break;
            }
        }
    }
}

function QuickAccessMouseOut()
{
    var evt = new Object();

    if (closeTimeOutId > -1)
    {
        clearTimeout(closeTimeOutId);
        closeTimeOutId = -1;
    }

    if (event.srcElement)
    {
        var type = GetElementType(event.srcElement);
        if (type == "editProfile")
            SetIconHoverStyle(document.getElementById("ctl00_ctl00_ctl00_ctl00_a_b_UserLogin1_editProfile"), false);
    }
    
    evt.srcElement = event.srcElement;
    evt.toElement = event.toElement;
    
    // reduce sensitivity, don't close too fast
    closeTimeOutId = setTimeout(function() {_QuickAccessMouseOut(evt);}, 500);
}

function _QuickAccessMouseOut(event)
{
    if (isMenuDisplayed && !animationInProgress)
    {
        if (event.toElement)
        {
            var type = GetElementType(event.toElement);
            if (type != "viewprofile" && type != "viewprofilemenu")
            {
                AnimateQuickAccess(false);
                SetIconHoverStyle(document.getElementById("quickAccess"), false);
            }
        }
    }
}

function SetIconHoverStyle(el, isHover)
{
    if (isHover)
        el.style.backgroundImage = "url(/WebResources/Images/Community/icon_user_hover.png)";
    else
        el.style.backgroundImage = "";
}

function GetElementType(el)
{
    var cnt = 0;
    
    while (cnt < 4)
    {
        if (el && el.id)
        {
            switch (el.id)
            {
                case "quickAccess":
                    return "viewprofile";
                    
                case "quickAccessMenu":
                    return "viewprofilemenu";
                    
                case "ctl00_ctl00_ctl00_ctl00_a_b_UserLogin1_editProfile":
                    return "editProfile";
                    
                default:
                    if (el != null)
                        el = el.parentElement;
                        
                    break;
            }
        }
        else
        {
            if (el != null)
                el = el.parentElement;
        }
        
        cnt++;
    }
    
    return "";
}