﻿
//WHAT: For integrated FBC/MAP login/logout linking/unlinking
//WHEN: 7/14/09
//WHO:  willzhan@microsoft.com

var xd_receiver_path = 'http://' + window.location.host + '/FBC/Connect/xd_receiver.htm';  
var api_key;
var faceboxShown;
var isFBCAuthenticated;    //comment page needs it to be global

//since www.tvguide.com, movie.tvguide.com, etc all lower their domains, we have to lower the domain here and in cross-domain comm channel
lowerDomain();

function lowerDomain()
{
    var domParts = document.domain.split('.');
    if(domParts.length > 1)
    {
        document.domain = domParts[domParts.length-2] + '.' + domParts[domParts.length-1];
        
        if (domParts[domParts.length-2] == "tvguide"){
           api_key = '4631b4ff1e53d450c3f9726dd45be7de';
        } else {
           api_key = 'a4bf35761cb25305ba49caa405b8a7d5';
        }
    }
}

//these two functions are for setting MAPCookie on client side which is required by comment page.
function setLoginCookie(displayName, mapUsername, cookieValue, wucIndex) {
    var daze = 0;   //0= session cookie, 365

    if (cookieValue != null && cookieValue != "") {
        isLoggedInX = true;
        writeLoginCookie("MAPCookie", cookieValue, daze);
        tvgUserName = mapUsername;
        tvgDisplayName = displayName;

        if (wucIndex == 1)  /* FB login button in comment area */
            toggleCommentLoginArea();
    }
}

function writeLoginCookie(strName, strValue, iDays) {
    var strCookie = strName + "=" + strValue + "; ";
    if (iDays != 0) {
        var date = new Date();
        date.setTime(date.getTime() + (iDays * 24 * 60 * 60 * 1000));
        strCookie += "expires=" + date.toGMTString() + "; ";
    }

    //so it works in both tvgol.local and tvguide.com domains
    var domParts = document.domain.split('.');
    strCookie += "domain=." + domParts[domParts.length - 2] + '.' + domParts[domParts.length - 1] + "; ";
    strCookie += "path=/";
    document.cookie = strCookie;
}

//wucIndex: 0 - header, 1 - comment page, 2 - myTVG pages
function getAuthentication(type, isFBCAuthenticated, wucIndex) {
    //var status = FB.Connect.get_status().result;

    $.ajax({
        url: "/FBC/HTTPHandler/HNDMultiLogin.ashx?type=" + type + "&fbc=" + isFBCAuthenticated,
        type: "GET",
        cache: false,
        success: function(results) {
            var parts = results.split("|");
            var host = window.location.host;
            var fbc_button           = document.getElementById("fbclogin_multi_login_" + wucIndex);
            var multi_login_username = document.getElementById("multi_login_username_" + wucIndex);
            var multi_login_status   = document.getElementById("multi_login_status_" + wucIndex);
            var multi_login_info     = document.getElementById("multi_login_info_" + wucIndex); ;
            var LOGIN_HTML           = "<a href='javascript:loginOut(0);'>Login</a> <a href='javascript:register();'>New User Signup</a>";
            var LOGOUT_HTML          = "<a href='javascript:loginOut(1);'>Logout</a> <a href='javascript:update();'>My Settings</a>";      //<a href='javascript:manageFavorites();'>My Favorites</a>
            var FBC_BUTTON_HEADING   = "<div>Facebook Users</div><div>Connect with Facebook and leave a comment</div><div>Connecting with Facebook allows you to bring your Facebook friends and favorites to TVGuide.com and easily share your TVGuide activity on Facebook! You can also link your Facebook and TVGuide.com accounts.</div>";

            switch (parts[0]) {
                case "0":    //anonymous
                    switch (wucIndex) {
                        case "0":
                            multi_login_status.innerHTML     = LOGIN_HTML;
                            multi_login_info.style.display   = "none";
                            break;
                        case "1":
                            multi_login_status.style.display = "none";
                            multi_login_info.innerHTML       = FBC_BUTTON_HEADING;
                            break;
                        case "2":
                            multi_login_status.style.display = "none";
                            multi_login_info.style.display   = "none";
                            break;
                        default:
                    }
                    multi_login_username.style.display = "none";
                    fbc_button.style.display           = "block";
                    break;
                case "1":    //FBC authenticated but it is first time and linked to implicitly created MAP account: show facebook blue background color
                    switch (wucIndex) {
                        case "0":
                            multi_login_status.innerHTML       = LOGOUT_HTML;
                            multi_login_username.innerHTML     = "Welcome, " + parts[1];          // (Please <a href=\"http://" + host + "/FBC/LinkAccount.aspx\">link</a>)
                            multi_login_username.className     = "ghead-userlinks-welcome-facebook";
                            multi_login_username.style.display = "block";
                            break;
                        case "1":
                        case "2":
                            multi_login_status.style.display   = "none";
                            multi_login_username.style.display = "none";
                            break;
                        default:
                    }
                    fbc_button.style.display       = "none";
                    multi_login_info.style.display = "none";

                    // get and set the login cookie
                    if (parts.length > 3 && parts[3] != null && parts[3] != "")
                        setLoginCookie(parts[1], parts[2], parts[3], wucIndex);

                    //suggest linking, but only once if multiple instances exist
                    if (faceboxShown != 1) {
                        faceboxShown = 1;
                        showFacebox("http://" + host + "/FBC/LinkAccountDialog.aspx");
                    }
                    break;
                case "2":    //FBC authenticated and MAP-linked: show facebook blue background color
                    switch (wucIndex) {
                        case "0":
                            multi_login_status.innerHTML       = LOGOUT_HTML;
                            multi_login_username.innerHTML     = "Welcome, " + parts[1];
                            multi_login_username.className     = "ghead-userlinks-welcome-facebook";
                            multi_login_username.style.display = "block";
                            break;
                        case "1":
                        case "2":
                            multi_login_status.style.display   = "none";
                            multi_login_username.style.display = "none";
                            break;
                        default:
                    }
                    fbc_button.style.display       = "none";
                    multi_login_info.style.display = "none";

                    // get and set the login cookie
                    if (parts.length > 3 && parts[3] != null && parts[3] != "")
                        setLoginCookie(parts[1], parts[2], parts[3], wucIndex);

                    break;
                case "3":    //Only MAP authenticated and linked: show TVG red background color
                    switch (wucIndex) {
                        case "0":
                            multi_login_status.innerHTML       = LOGOUT_HTML;
                            multi_login_username.innerHTML     = "Welcome, " + parts[1];
                            multi_login_username.className     = "ghead-userlinks-welcome-map";
                            multi_login_username.style.display = "block";
                            fbc_button.style.display = "none";
                            break;
                        case "1":
                        case "2":
                            multi_login_status.style.display   = "none";
                            multi_login_username.style.display = "none";
                            fbc_button.style.display           = "block";
                            break;
                        default:
                    }
                    multi_login_info.style.display = "none";
                    break;
                case "4":     //Only MAP authenticated but NOT linked: show TVG red background color
                    switch (wucIndex) {
                        case "0":
                            multi_login_status.innerHTML       = LOGOUT_HTML;
                            multi_login_username.innerHTML     = "Welcome, " + parts[1];
                            multi_login_username.className     = "ghead-userlinks-welcome-map";
                            multi_login_username.style.display = "block";
                            multi_login_info.style.display     = "none";
                            fbc_button.style.display           = "none";
                            break;
                        case "1":
                            multi_login_info.innerHTML         = FBC_BUTTON_HEADING; ;
                            multi_login_username.style.display = "none";
                            fbc_button.style.display           = "block";
                            break;
                        case "2":
                            multi_login_status.style.display   = "none";
                            multi_login_username.style.display = "none";
                            multi_login_info.style.display     = "none";
                            fbc_button.style.display           = "block";
                            break;
                        default:
                    }
                    break;
                default:
            }
        }
    });
}

//MAP login and FBC/MAP logout
function loginOut(inOut) {
    switch (inOut) {
        case 0:  //log into MAP only, FBC login is via FBC button
            document.location = WWWBaseUrl + "/FAP/Login.aspx?ReturnUrl=" + escape(document.location.href);
            break;
        case 1:  //logout facebook, then MAP
            FB.Connect.logout(
                function() {
            document.location = WWWBaseUrl + '/FAP/MAPAction.aspx?returnUrl=' + document.location.href;
                });
            break;
    }
}

//new user MAP registration link
function register() {
    document.location = WWWBaseUrl + "/FAP/Registration.aspx";
}

//update MAP profile link
function update() {
    document.location = WWWBaseUrl + "/FAP/ProfileUpdate.aspx";
}

//manage favorite page link
function manageFavorites() {
    document.location = WWWBaseUrl + "/FBC/MyFavorite.aspx";
}

//log into Facebook via FBC
function loginFacebook(wucIndex) {
    FB.Facebook.get_sessionState().waitUntilReady(
       function() {
           updateUser();

           switch (wucIndex) {
               case 1:
                   //comment page: reload will lose comment user enters. Use AJAX way.
                   updateMultiLoginState("1");
                   updateMultiLoginState("0");
                   break;
               default:
                   var retUrl = getQueryParameter("ReturnUrl");
                   var tvobjectid = getQueryParameter("tvobjectid");
                   var action = getQueryParameter("action");
                   if (action == "1" && retUrl.length > 0 && tvobjectid.length > 0) {
                       $.ajax({
                           url: "/FBC/HTTPHandler/HNDDVR.ashx?tvobjectid=" + tvobjectid + "&actiontype=1&snapuserid=" + snapUserID + "&snapidentityproviderid=" + snapIdentityProviderID,
                           type: "GET",
                           cache: false,
                           success: function(results) { document.location.href = retUrl }
                       });
                   }
                   else {
                       document.location.href = window.location;
                   }
           }
       }
    );
}

//note: function is used in DVR.aspx as well
function getQueryParameter(strName) {
    var u, i;
    u = document.location.search + "";
    i = u.indexOf(strName + "=", 0);
    if (i >= 0) {
        i += strName.length + 1;
        var n = u.indexOf('&', i);
        if (n > i) {
            return unescape(u.substring(i, n));
        }
        else if (i < u.length) {
            return unescape(u.substring(i));
        }
    }
    return "";
}

//only used by facebook logout button
function logoutFacebook() {
    FB.Connect.logout(
      function() {
          document.location.href = window.location;
      }
   );
}

//This function can update multi-login control UI without a postback, as needed on comment page.
//However, more often we need postback since upon login, content needes to be replaced by personalized content, and upon logout, personalized content needs to be replaced by public content.
function updateMultiLoginState(wucIndex) {
    FB_RequireFeatures(["Api"], function() {                //twice
        FB.init(api_key, xd_receiver_path);
        //needed for using facebook server to get FBC authentication status
        getFBCAuthentication(wucIndex);
        getAuthentication(1, isFBCAuthenticated, wucIndex);
    });
}

//use facebook server to get FBC authentication status from client side
var FACEBOOK_BUG = 0; 

function getFBCAuthentication(wucIndex) {    
    var apiClient = FB.Facebook.apiClient;
    var session = apiClient.get_session();
    var uid = session ? session.uid : null;

    if (uid) {
        if (FACEBOOK_BUG == 1) {
            var sql = "SELECT name, pic_small, pic_small_with_logo FROM user WHERE uid =" + uid;
            FB.Facebook.apiClient.fql_query(sql, function(result, ex) {
                if (result) {
                    isFBCAuthenticated = 1;
                }
                else {  //slower way to detect logout
                    isFBCAuthenticated = 0;
                }
            });
        }
        else {
            isFBCAuthenticated = 1;
        }
    }
    else {
        isFBCAuthenticated = 0;
    } 
}

function updateUser() {
    $.ajax({
        url: "/FBC/HTTPHandler/HNDUserAction.ashx?actiontype=1",
        type: "GET",
        cache: false,
        success: function(results) { }
    });
}

function updateUI(wucIndex) {
    var apiClient = FB.Facebook.apiClient;
    var session = apiClient.get_session();
    var uid = session ? session.uid : null;

    if (uid) {  //facebook bug which did not exist but appeard on 4/22/09: FB.Connect.logout does not really clear session cookie. A valid uid does not mean it is still logged-in.
        var sql = "SELECT name, pic_small, pic_small_with_logo FROM user WHERE uid =" + uid;
        FB.Facebook.apiClient.fql_query(sql, function(result, ex) {
            if (result) {
                document.getElementById("fbclogin_multi_login_" + wucIndex).style.display = "none";
                document.getElementById("fbclogout_multi_login_" + wucIndex).style.display = "block";
                document.getElementById("userphoto_multi_login_" + wucIndex).innerHTML = "<img src='" + result[0]["pic_small"] + "'/>";
                document.getElementById("userinfo_multi_login_" + wucIndex).innerHTML = result[0]['name'];
                document.getElementById("userphoto_multi_login_" + wucIndex).style.display = "block";
                document.getElementById("userinfo_multi_login_" + wucIndex).style.display = "block";
            }
            else {  //this is slower way to detect logout
                showLoggedoutStatus(wucIndex);
            }
        });
    }
    else {
        showLoggedoutStatus(wucIndex);
    }
}

function showLoggedoutStatus(wucIndex) {
    document.getElementById("fbclogin_multi_login_" + wucIndex).style.display = "block";
    document.getElementById("fbclogout_multi_login_" + wucIndex).style.display = "none";
    document.getElementById("userphoto_multi_login_" + wucIndex).innerHTML = "";
    document.getElementById("userinfo_multi_login_" + wucIndex).innerHTML = "";
    document.getElementById("userphoto_multi_login_" + wucIndex).style.display = "none";
    document.getElementById("userinfo_multi_login_" + wucIndex).style.display = "none";
}

function showFacebox(url) {
    jQuery(document).ready(function($) {
        jQuery.facebox({ ajax: url })
    })
}

var xmlHttpObjFacebook = null;

function xmlHttpObjLaunch(xmlHttpObj, strUrl) {
    if (xmlHttpObj != null) {
        xmlHttpObj.open("GET", strUrl, true);
        xmlHttpObj.send(null);
    }
}

function getTVOFacebookAJAX(strUrl, ElementID) {
    var callbackfunction = function() { UpdateElementHTML(ElementID) };

    xmlHttpObjFacebook = GetXmlHttpObject(callbackfunction);
    xmlHttpObjLaunch(xmlHttpObjFacebook, strUrl);
}

function UpdateElementHTML(ElementID) {
    if (xmlHttpObjFacebook.readyState == 4 || xmlHttpObjFacebook.readyState == "complete") {
        var elemFbook = document.getElementById(ElementID);
        var strText = xmlHttpObjFacebook.responseText;
        elemFbook.innerHTML = strText;
        elemFbook = document.getElementById(ElementID + "2");
        if (elemFbook) {
            elemFbook.innerHTML = strText.replace(/txtAreaNote/g, "txtAreaNote2").replace(/obj-fbook-friends-like/g, "obj-fbook-friends-like2");
        }
    }
}

function addFavorite(tvobjectid, tvobjectname) {
    if (window.confirm("Would you like to add " + tvobjectname + " to your TV Guide favorites?")) {
        ajaxRequest("/FBC/HTTPHandler/HNDObjectData.ashx?tvobjectid=" + tvobjectid + "&actiontype=2&snapuserid=" + snapUserID + "&snapidentityproviderid=" + snapIdentityProviderID, "ajax-favorite-status");
    }
}

function SendTvoNote(uids, name, ourl, controlid, source) {

    var msg = $("#facebox #" + controlid).val();
    var note;

    if (source == "a")
        note = msg + ". Check out <a href=\"" + ourl + "\">this story</a> about " + name + " on <a href=\"http://www.tvguide.com\">TVGuide.com</a>.";
    else if (source == "p")
        note = msg + ". Check out <a href=\"" + ourl + "\">this photo gallery</a> on <a href=\"http://www.tvguide.com\">TVGuide.com</a>.";
    else
        note = msg + ". Go to the <a href=\"" + ourl + "\">" + name + "</a> page on <a href=\"http://www.tvguide.com\">TVGuide.com</a>.";

    note = EncodeCrossBrowser(note);

    $("#facebox .mytvg-pop").html("<div class='mytvg-pop-header'>Sending <img src='/FBC/images/loading_15x15.gif' alt='loading' border='0' /></div>");
    $.ajax({
        url: "/FBC/HTTPHandler/HNDUserAction.ashx?actiontype=3&uids=" + uids + "&msg=" + note,
        type: "GET",
        cache: false,
        error: function(results) {
            $("#facebox .mytvg-pop").html("<div class='mytvg-pop-header'>Error :(</div><div>" + results + "</div>");
        },
        success: function(results) {
            $("#facebox .mytvg-pop").html("<div class='mytvg-pop-header'>Sent!</div><div>" + results + "</div>");
        }
    });
}

function getFaveStatus(TVObjectID, TVObjectName) {
    var faveText = "";
    if (isLoggedInX) {
        if (faveTVObjectIDs.indexOf(TVObjectID) >= 0) {
            faveText = "<a href=\"/FBC/MyFavorite.aspx\">My favorite show!</a>";
        }
        else {
            faveText = "<a href=\"/FBC/MyFavorite.aspx\" onclick=\"addFavorite('" + TVObjectID + "', '" + TVObjectName.replace(/\'/g, '\\\'') + "'); return false;\">Add to favorites</a>";
        }
    }
    else {
        faveText = "<a href=\"/FBC/MyFavorite.aspx?action=add_fave&tvobjectid=" + TVObjectID + "\">Add to favorites</a>";
    }
    document.getElementById("ajax-favorite-status").innerHTML = faveText;
}

function AddToDVR(tvobjectid, tvobjectname, div_id) {
    if (window.confirm("Would you like to add " + tvobjectname + " to your TVGuide.com DVR?")) {
        $.ajax({
            url: "/FBC/HTTPHandler/HNDDVR.ashx?tvobjectid=" + tvobjectid + "&actiontype=1&snapuserid=" + snapUserID + "&snapidentityproviderid=" + snapIdentityProviderID,
            type: "GET",
            cache: false,
            success: function(results) { dvrTVObjectIDs += tvobjectid + "|"; document.getElementById(div_id).innerHTML = "<a href='/FBC/DVR.aspx?expand=" + tvobjectid + "#show-" + tvobjectid + "'>This series has been added to your My TVGuide.com DVR</a>"; }
        });
    }
    return false;
}

function AddToDVR2(tvobjectid, tvobjectname, myDiv) {
    if (window.confirm("Would you like to add " + tvobjectname + " to your TVGuide.com DVR?")) {
        $.ajax({
            url: "/FBC/HTTPHandler/HNDDVR.ashx?tvobjectid=" + tvobjectid + "&actiontype=1&snapuserid=" + snapUserID + "&snapidentityproviderid=" + snapIdentityProviderID,
            type: "GET",
            cache: false,
            success: function(results) {
                dvrTVObjectIDs += tvobjectid + "|";
                myDiv.innerHTML = "<a href='/FBC/DVR.aspx?expand=" + tvobjectid + "#show-" + tvobjectid + "'>This series has been added to your My TVGuide.com DVR</a>";
                myDiv.onclick = "";
            }
        });
    }
    return false;
}

function getDVRButton(tvobjectid, tvobjectname, showloginlink) {
    if (typeof (tvobjectid) != undefined && tvobjectid > 0) {
        if (isLoggedInX) {
            if (dvrTVObjectIDs.indexOf(tvobjectid) >= 0)
                document.write("<a href='" + WWWBaseUrl + "/FBC/DVR.aspx?expand=" + tvobjectid + "#show-" + tvobjectid + "'>This series is in your My TVGuide.com DVR</a>");
            else
                document.write("<div id=\"dvr-button-inner-" + tvobjectid + "\"><a onclick=\"return AddToDVR(" + tvobjectid + ", '" + tvobjectname.replace(/\'/g, '\\\'') + "', 'dvr-button-inner-" + tvobjectid + "')\" href='" + WWWBaseUrl + "/FBC/DVR.aspx'>Add this series to your My TVGuide.com DVR</a></div>");
        }
        else {
            if (showloginlink)
                document.write("<a href='" + WWWBaseUrl + "/FBC/login.aspx?action=1&tvobjectid=" + tvobjectid + "&ReturnUrl=" + escape(window.location) + "'>Add this series to your My TVGuide.com DVR</a>");
        }
    }
}


function GetDVRInfo() {
    var dvrText;
    if (isLoggedInX) {
        if (dvrTVObjectIDs.length > 0) {
            $.ajax({
                url: "/FBC/HTTPHandler/HNDDVR.ashx?actiontype=6&faves=" + dvrTVObjectIDs,
                type: "GET",
                cache: false,
                success: function(results) {
                    if (results == "NONE") {
                        dvrText = "<h3>There are no new episodes of your shows at this time.</h3>";
                        dvrText += "<div class='h-video-heart'><a href='/FBC/DVR.aspx#head-moretvshows'>Add shows</a></div>";
                        dvrText += "<div class='h-video-play'><a href='/FBC/DVR.aspx'>Go to My TVGuide.com DVR</a></div>";
                        $("#full-ep-featured").css('display','block');
                    }
                    else {
                        dvrText = results;
                    }
                    $("#div-dvr-content").html(dvrText);
                }
            });
        }
        else {
            $("#full-ep-featured").css('display','block');
            dvrText = "<h3>You are not subscribed to any shows.</h3>";
            dvrText += "<div class='h-video-heart'><a href='/FBC/DVR.aspx#head-moretvshows'>Add shows</a></div>";
            dvrText += "<div class='h-video-play'><a href='/FBC/DVR.aspx'>Go to My TVGuide.com DVR</a></div>";
            $("#div-dvr-content").html(dvrText);
        }
    }
    else {
        $("#full-ep-featured").css('display','block');
        dvrText = "<h3>Get new full episodes of your favorite shows as soon as they're available.</h3>";
        dvrText += "<div class='h-video-createlogin'><a href='/FAP/Registration.aspx'>Create an account</a> or <a href='/FBC/Login.aspx?ReturnUrl=" + escape(window.location) + "'>log in</a></div>";
        $("#div-dvr-content").html(dvrText);
    }
    return false;
}