﻿var currOid = "";
var currPid = "";

String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str);
};
// Function to display the checkin counts for each button and also determine if its in checkin state or checked out state.
function updateCheckinButtons(results) {
    if (results !== "") {
        var obj = eval('(' + results + ')');
        if (obj.EpisodeUserCheckInInfoList.length === 0)
        { return; }
        for (i = 0; i < obj.EpisodeUserCheckInInfoList.length; i++) {
            var checkinInfo = obj.EpisodeUserCheckInInfoList[i];
            var spanText = $("div.ch-b-w.tvo-" + checkinInfo.TVObjectId.toString() + ".epprog-" + checkinInfo.EpisodeProgramId.toString() + " span.ch-b-t:first").outerHTML();
            $("div.ch-b-w.tvo-" + checkinInfo.TVObjectId + ".epprog-" + checkinInfo.EpisodeProgramId + " span.ch-b-t").remove();
            var html = spanText + getDisplayText(checkinInfo.TVObjectId, checkinInfo.EpisodeProgramId, checkinInfo.TotalUsersCheckedIn, checkinInfo.HasUserCheckedIn, checkinInfo.AllowReCheckin);
            $("div.ch-b-w.tvo-" + checkinInfo.TVObjectId + ".epprog-" + checkinInfo.EpisodeProgramId).html(html);
        }
    }
}

// Checkin from the Igoogle page. Google page will pass in the Pid with a anchor. 
// We parse it and determine if the checkin needs to be done.

function googleCheckin() {
    if (typeof (isGooglecheckin) != 'undefined' && isGooglecheckin == true) {
        //get the full url 
        var full_url = document.location.href;
        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        if (parts != null && parts.length > 0) {
            var trgt = parts[1];
            var inputElem = $("a[name=" + trgt + "]").next().find("input[type='image']");
            if (inputElem == 'undefined' || inputElem == null) return;
            if (inputElem.attr("onclick") == 'undefined' || inputElem.attr("onclick") == null) return;
            var fnText = inputElem.attr("onclick").toString();
            if (fnText != 'undefined' && fnText != "") {
                //Now parse and get the checkin function details
                var st = fnText.indexOf("{", 0);
                var end = fnText.indexOf("}", 0);

                if (st > 0 && end > 0) {
                    var fn = fnText.substring(st + 1, end);
                    if (fn.indexOf("true,", 0) > 0) {
                        //Actual checkin
                        eval(fn.replace(";", ""));
                    }
                }
            }
        }
    }
}

// Function to draw the checkin buttons and get their counts from the service.
// This will be the initial function that gets called on the page.

function getCheckIns() {
    var batchInput = "";
    currOid = "";
    currPid = "";
    $("div[class^='ch-b-w ']").each(function() {
        var arrCls = $(this).attr("class").split(' ');

        var chkInType = $(this).attr("data-checkintype");
        if (chkInType == "4" && arrCls[1].replace("tvo-", "") != "0" && arrCls[2].replace("epprog-", "") != "0") //SPORTS
        {
            var pid = arrCls[2].replace("epprog-", "");
            var newCls = $(this).attr("class").replace("epprog-" + pid, "epprog-0"); //SET PROGID  =0
            $(this).attr("class", newCls);
            arrCls = $(this).attr("class").split(' ');
        }

        if (arrCls.length == 3) {
            batchInput += arrCls[1].replace("tvo-", "") + "," + arrCls[2].replace("epprog-", "") + "," + chkInType + "|";
        }
    });

    if (batchInput !== "") {
        batchInput = batchInput.slice(0, -1);
        $.ajax({
            url: "/Handler/CheckIns.ashx",
            type: "POST",
            data: { method: "getbatchcheckin", pids: batchInput },
            cache: false,
            error: function() { },
            success: function(results) {
                updateCheckinButtons(results);
                googleCheckin();
            }
        });
    }
}

// Draws the user specific hot list/episode containers in the home page, depending on the
// favorite shows the user has.

function loadHPHotListContainers() {
    //if (isFBCAuthenticated === true || isLoggedInX === true) {
    //alert(TVGOL.User.isLoggedIn);
    if (TVGOL.User.isLoggedIn) {
        if ($('div.h-rb-w.h-hotlist')) {
            $('div.h-rb-w.h-hotlist div.h-b-c div.h-hotlist-leadin').hide();
            faveTVObjectIDs = TVGOL.User.favorites.list;

            if (faveTVObjectIDs != "") {
                // $('div.h-rb-w.h-hotlist div.h-b-c div.h-b-s.clear.h-more-c div.h-more-l').show();
                $('div.h-rb-w.h-hotlist div.h-b-c h3 a').show();
                $.ajax({
                    url: "/Handler/HotList.ashx", cache: false, timeout: 10000, type: "GET",
                    data: { method: "watchlist", oids: faveTVObjectIDs },
                    beforeSend: function() { hlAjaxCalls++; },
                    error: function(results) {
                        cancallCheckIns();
                    },
                    success: function(results) {
                        $('div.h-rb-w.h-hotlist div.hotlist-favorites').append(results);
                        var favCount = $('div.h-rb-w.h-hotlist div.hotlist-favorites div.h-b-s.clear').size();
                        var isSponsered = $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-b-s.clear.hotlist-sponsored').size();

                        if (favCount === 0) {
                            $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-hotlist-leadin').html('<div class="h-more">None of your favorites are on today; <a href="' + WWWBaseUrl + '/Watchlist">add more</a></div>');
                        }
                        else if (favCount > 0) {
                            if (isSponsered > 0 && favCount == 3) {
                                favCount = favCount - isSponsered;
                            }
                            var strIsAre = (favCount > 1) ? "are" : "is";
                            $('div.h-rb-w.h-hotlist div.hotlist-favorites div.h-hotlist-leadin').text(favCount + " of your favorites " + strIsAre + " on tonight:");
                            $('div.h-rb-w.h-hotlist div.hotlist-favorites div.h-hotlist-leadin').show();
                            $('div.h-rb-w.h-hotlist div.hotlist-favorites').show();

                            if (favCount == 1 || (favCount == 2 && isSponsered < 1)) {
                                $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-hotlist-leadin').text("You might also like:");
                                $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-hotlist-leadin').show();
                            }
                            else {
                                $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-hotlist-leadin').hide();
                            }

                            for (i = 0; i < favCount; i++) {
                                $('div.h-rb-w.h-hotlist div.hotlist-favorites div.h-b-s.clear').eq(i).show();
                                $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-b-s.clear').eq(i).hide();
                            }

                            for (i = 0; i < 5; i++) { // DE-DUP EDITORIAL & FAVROITE
                                for (x = 0; x < $('div.h-rb-w.h-hotlist div.hotlist-favorites div.h-b-s.clear:visible').size(); x++) {
                                    favClass = $('div.h-rb-w.h-hotlist div.hotlist-favorites div.h-b-s.clear:visible').eq(x).find('.hotlist-button div').attr("class");
                                    for (y = 0; y < $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-b-s.clear:visible').size(); y++) {
                                        edtClass = $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-b-s.clear:visible').eq(y).find('.hotlist-button div').attr("class");
                                        if (edtClass == favClass) {
                                            $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-b-s.clear:visible').eq(y).remove();
                                            $('div.h-rb-w.h-hotlist div.hotlist-editorial div.h-b-s.clear:hidden').eq(0).show();
                                        }
                                    }
                                }
                            }
                        }
                        cancallCheckIns();
                    }
                });
            }
            else {
                $('div.hotlist-editorial div.h-hotlist-leadin').html('<div class="h-more"><a href="' + WWWBaseUrl + '/watchlist">Add your favorite shows now</a></div>');
                getCheckIns();
            }
        }

        if ($('div.h-rb-w.h-fullepisodes')) {
            if (faveTVObjectIDs !== "") {
                $.ajax({
                    url: "/Handler/HotList.ashx", type: "GET", cache: false, timeout: 10000,
                    data: { method: "videos", oids: faveTVObjectIDs },
                    beforeSend: function() { },
                    error: function(results) {
                    },
                    success: function(results) {
                        if (results === "") {
                            $('div.h-rb-w.h-fullepisodes div.h-b-c div.h-watchlist-leadin').show();
                        }
                        else {
                            $('div.h-rb-w.h-fullepisodes div.h-b-c').prepend(results);
                            var itemCount = $('div.h-rb-w.h-fullepisodes div.h-b-c div.h-b-s.clear').size();
                            for (i = 0; i < itemCount; i++) {
                                if (i < 2) {
                                    $('div.h-rb-w.h-fullepisodes div.h-b-c div.h-b-s.clear').eq(i).show();
                                }
                                else {
                                    $('div.h-rb-w.h-fullepisodes div.h-b-c div.h-b-s.clear').eq(i).hide();
                                }
                            }
                        }
                    }
                });
            }
            else {
                $('div.h-rb-w.h-fullepisodes div.h-b-c div.h-watchlist-leadin').html('<div class="h-more"><a href="' + WWWBaseUrl + '/Watchlist">Add your favorite shows now</a></div>');
                $('div.h-rb-w.h-fullepisodes div.h-b-c div.h-watchlist-leadin').show();
            }
        }
//        if (tvgDisplayName === '') {
//            $('div#multi_login_username_0').ajaxStop(function() { // MAKE SURE THAT THE USER VARIABLE IS SET
//                if (tvgDisplayName !== '') {
//                    setHotListHeading();
//                }
//            });
//        }
//        else {
            setHotListHeading();
//        }
    }
    else {
        getCheckIns();
    }
}

// Returns the button html along with the count text.

function getDisplayText(oid, pid, cnt, hasUserCheckedIn, allowReCheckIn) {
    var txt = "&nbsp;";
    if (cnt == 1) {
        if (hasUserCheckedIn && !allowReCheckIn)
        { txt = "You are watching"; }
        else
        { txt = "1 watching"; }
    }

    if (cnt > 1 && hasUserCheckedIn && !allowReCheckIn) {
        txt = (cnt - 1) + " watching + you";
    }
    else if (cnt > 1 && !hasUserCheckedIn) {
        txt = cnt + " watching";
    }
    var isCheckInButton = true;
    isCheckInButton = (hasUserCheckedIn === false || allowReCheckIn === true);
    var btnText = "";

    if ($("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-image")) {
        btnText = isCheckInButton ? "/images/buttons/watch-sm-off.png" : "/images/buttons/watch-sm-on.png";
    }
    else {
        btnText = isCheckInButton ? "/images/buttons/watch-off.png" : "/images/buttons/watch-on.png";
    }

    var html = "";
//    if ($("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("franchiserow"){
//        html = "<table cellpadding='0' cellspacing='0' border='0'><td style='vertical-align:middle;'><input type='image' value='I\'ll watch' src='" + btnText + "' onclick='checkin(" + isCheckInButton + "," + oid + "," + pid + "," + cnt + ");'/></td>";
//        html += "<td style='padding-left:4px;font-weight:bold; color:" + magicTextClr + "; vertical-align:middle;' nowrap>" + txt + "</td></table>";
//    }
    //else {
        html = "<div><input type='image' value='I\'ll watch' src='" + btnText + "' onclick='checkin(" + isCheckInButton + "," + oid + "," + pid + "," + cnt + ");'/></div><span>" + txt + "</span>";
    //}
    return html;

}

function splitShareMessage(spanText) {
    var arrInfo = spanText.split('~');
    if (arrInfo === null)
    { return null; }
    if (arrInfo.length != 6)
    { return null; }
    if (arrInfo[0] === "") // No tvobject name
    { return null; }

    return arrInfo;
}

// Function to checkin or check out.

function checkin(ischeckIn, oid, pid, cnt) {
    var spanText = "";
    var html = "";
    var sourceType = 0;
    var checkinType = 0;

    if (ischeckIn) //CheckIn 
    {
        cnt++;
        spanText = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid + " span.ch-b-t:first").outerHTML();
        html = spanText + getDisplayText(oid, pid, cnt, true, false);
        $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).html(html);
        currOid = "";
        currPid = "";

        TVGOL.Events.dispatchEvent("tvgol.checkin.add", { "id": oid, "prog": pid }); //For analytics capture, TAT 08/30/2011

        //Get the SourceType and CheckInType

        if ($("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-sourcetype")) {
            sourceType = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-sourcetype");
        }
        if ($("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-checkintype")) {
            checkinType = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-checkintype");
        }

        //MAKE CALL FOR THE SHARE POPUP
        if (canShowSharePopup()) {
            //html = getPopupHtml(oid, pid);
            //set the display text for the checkin popup
            var gigyaPopup = getDisplayTextForGigyaPopup(oid, pid);
            var socialWall = setDisplayTextForSocialWall(oid, pid);
            var config = {
                "userAction"    : socialWall,
                "popup"         : {
                    "title"     : gigyaPopup.title,
                    "description": "Share <strong>" + gigyaPopup.program + "</strong> on your Social Networks!!"
                }
            };
            TVGOL.services.Gigya.Sharing.init(config);
            
            currOid = oid;
            currPid = pid;

            TVGOL.services.Gigya.Sharing.show(config);
        }

        $.ajax({
            url: "/Handler/CheckIns.ashx",
            type: "POST",
            data: { method: "insertcheckin", pid: pid, oid: oid, sourcetype: sourceType, checkintype: checkinType },
            cache: false,
            error: function() { },
            success: function(results) {
                countTraxCheckIn(oid, pid);
            }
        });
    }
    else {
        cnt--;
        currOid = "";
        currPid = "";
        spanText = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid + " span.ch-b-t:first").outerHTML();
        html = spanText + getDisplayText(oid, pid, cnt, false, false);
        $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).html(html);
        checkinType = 0;
        if ($("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-checkintype")) {
            checkinType = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid).attr("data-checkintype");
        }

        if (checkinType == 4 && oid != "0" && pid != "0") {
            pid = 0;
        }

        $.ajax({
            url: "/Handler/CheckIns.ashx",
            type: "POST",
            data: { method: "deletecheckin", pid: pid, oid: oid },
            cache: false,
            error: function() { },
            success: function(results) {
            }
        });
    }
}

function closeSharePopup() {
    setShareCookies();
    currOid = "";
    currPid = "";
    $(document).trigger('close.facebox');
}

function setShareCookies() {
    if ($('#checkin-share-chkshow').attr('checked')) {
        var cookieOptions = { expires: 365, path: '/', domain: '.tvguide.com' };
        $.subcookie("ch", "lastshared", toMMDDYYYYString(new Date()), cookieOptions);
    }
}

function shareCheckIn(oid, pid) {
    if (pid === null || pid === 0) {
        oid = currOid;
        pid = currPid;
    }
    if (isFBCAuthenticated == 1) {
        var message = $('#checkin-share-txtmessage').val();
        //POST TO FACEBOOK
        if (message == "Tell your friends you’re watching.")
        { message = ""; }
        postToFBWall(oid, pid, escape(message));
    }
    om_FBC_share('Share');
}

function getDisplayTextForGigyaPopup(oid, pid) {
    var spanValue = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid + " span.ch-b-t:first").text();
    var arrMess = splitShareMessage(spanValue);
    var progName = "";
    if (arrMess !== null) {
        progName = arrMess[0];
    }

    var results = {
        title: "Thanks for telling us what you're watching!",
        description: "Share " + progName + " on your Social Networks!!",
        program: progName
    };

    return results;
}

function setDisplayTextForSocialWall(oid, pid) {
    var spanValue = $("div.ch-b-w.tvo-" + oid + ".epprog-" + pid + " span.ch-b-t:first").text();
    var arrInfo = splitShareMessage(spanValue);
    var desc = "";
    var image = "";
    var url = "";
    var title = "Are you watching " + $.trim(arrInfo[0]) + "?";
    var firstdesc = "www.tvguide.com - ";
    var results = {};
    
    if (arrInfo[4] !== "") {
        desc = $.trim(arrInfo[0]) + " is on " + $.trim(arrInfo[4]) + " on " + $.trim(arrInfo[3]) + ".";
    }
    else {
        desc = "Are you watching " + $.trim(arrInfo[0]) + "?";
    }

    if (arrInfo[2] !== "") {
        if ($.trim(arrInfo[2]).startsWith("http://")) {
            url = $.trim(arrInfo[2]);
        }
        else {
            url = "http://www.tvguide.com" + $.trim(arrInfo[2]);
        }
    }
    else {
        url = "http://www.tvguide.com/hot-list#epprog-" + pid;
    }

    results["linkBack"] = url;
    
    if (arrInfo[5] !== "") {
        if ($.trim(arrInfo[5]).startsWith("http://")) {
            image = $.trim(arrInfo[5]);
        }
        else {
            image = "http://static.tvguide.com" + $.trim(arrInfo[5]);
        }
    }

    results["image"] = image;
    results["title"] = title;
    results["description"] = firstdesc + desc;

    return results;
}


function canShowLoginPopup() {
    // MAP COOKIE SHOULD NOT BE SET
    var mapCookie = $.subcookie("MAPCookie");
    if (mapCookie !== null && mapCookie != 'undefined')
    { return false; }
    // Check cookie to see if the user has set to not show
    var show = $.subcookie("ch", "showlogin");
    if (lastShared === null || lastShared == 'undefined') {
        return true;
    }
    else {
        return false;
    }
}

function canShowSharePopup() {
    // 1. IF THE USER HAS SELECTED SHARE TO FACEBOOK
    var shareTo = $.subcookie("ch", "shareto");
    if (shareTo !== null && shareTo != 'undefined' && shareTo == 'fb')
    { return true; }
    // 2 . IF THE lastshared is > 7 then show popup
    var lastShared = $.subcookie("ch", "lastshared");
    if (lastShared === null || lastShared == 'undefined')
    { return true; }
    if (!isValidDate(lastShared))
    { return true; }
    var today = new Date();
    var dt = new Date(lastShared);

    if ((today - dt) / (1000 * 60 * 60 * 24) >= 14) { //14 days
        return true;
    }
    else {
        return false;
    }
}

function isValidDate(dateStr) {
    //var dob  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
    var checkdate = new Date(dateStr);
    if (isNaN(checkdate.getFullYear())) {
        return false;
    }
    else {
        return true;
    }
}

jQuery.fn.outerHTML = function() {
    return $('<div></div>').append(this.clone()).html();
};

function toMMDDYYYYString(date) {
    return isNaN(date) ? 'NaN' : [date.getMonth() > 8 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1), date.getDate() > 9 ? date.getDate() : '0' + date.getDate(), date.getFullYear()].join('/');
}


//function getUserDisplayName() {
//    // CALL ONLY IF LOGGED IN
//    if (tvgDisplayName == '') { // Sometimes the FB ajax for setting this variable is not done yet. so pick up from label
//        if ($('div#multi_login_username_0')) {
//            var nme = $('div#multi_login_username_0').text();
//            tvgDisplayName = nme.replace("Welcome,&nbsp;", "");
//        }
//    }
//    return tvgDisplayName;
//}

function setHotListHeading() {
    if ($('div.h-rb-w.h-hotlist')) {
        $('div.hotlist-heading-text').html("<a href=\"" + WWWBaseUrl + "/watchlist\">" + TVGOL.User.getDisplayName() + "'s Watchlist</a>");
    }
}

function cancallCheckIns() {
    hlAjaxCalls--;
    if (hlAjaxCalls <= 0) {
        getCheckIns();
    }
}

/* Add to Watchlist Hack */
var AddToDVR2 = function() { };

$(document).ready(function() {
    TVGOL.Events.addListener("AddedToFavorites", function(data) {
        faveTVObjectIDs += data.objectID + "|";
        dvrTVObjectIDs += data.objectID + "|";
        if (data.elem) {
            data.elem.html("<a href='" + WWWBaseUrl + "/watchlist'>In your Watchlist</a>").bind("click", function() { void (0); }).addClass("l-addedtodvr").removeClass("l-addtodvr");
        }
    });

    AddToDVR2 = function(tvobjectid, tvobjectname, myDiv) {
        if (window.confirm("Would you like to add " + tvobjectname + " to your Watchlist?")) {
            TVGOL.User.favorites.add({ objectID: tvobjectid, favType: 1, elem: $(myDiv) });
        }
        return false;
    }
});

