﻿/****************** Latest 6/30/2008 ****************************/
/* This function updates channel names which appear 
under Video Tabs above the player and copies over 
above the playlist spot (simple control no server side involved)*/

var AmazonDisplay = false;
var AmazonState = 0;
var g_desc;
function CopyDIV(IDS) {
    document.getElementById('CopiedDIV').innerHTML = document.getElementById(IDS).innerHTML;
}
/***********************************************/
/* This is the main Ooyala Player script that generates Playlist, 
loops through getItem key provideo by Ooyala API
and returns Title, Thumb, EmbedCode, Duration time */

function SetVideoCount(videoCount, mesg) {
    var theDiv = document.getElementById("VideoCount");
    if (mesg == null) mesg = ""; else mesg = " " + mesg;
    if (theDiv != null) theDiv.innerHTML = videoCount.toString() + " clips" + mesg; ;
}

function setVideoMessage(playerId, mesg) {
    var player = document.getElementById(playerId);
    var lineup = player.getLineup();
    SetVideoCount(lineup.length, mesg);
}

function getAmazon(desc) {
    AmazonDisplay = false;
    var theDiv = document.getElementById("shopButton");
    theDiv.className = "shopButtonDisabled";

    //check to see if there are keywords - check for pipe symbol
    var pipe_loc = desc.indexOf("|");
    if (pipe_loc == -1) {
        desc = '';
        g_desc = desc;
    }
    else {
        //strip off up until the first pipe
        desc = desc.substring(pipe_loc);
        g_desc = desc;
    }
    //get top sellers if noamazon key is passed
    var noshop = desc.indexOf("noamazon");
    if (noshop == -1) 
        getAmazonAJAX(desc);
    else
        getAmazonAJAX('');
}

var oldEmbedCode = -1;

function onPlaying(playerId) {
    //to display player's status uncomment setVideoMessage to show Playing status 
    //setVideoMessage(playerId, "(Playing)"); 
    var player = document.getElementById(playerId);
    var current = player.getCurrentItem();

    /* truncate my title */
    var shortTitle = current.title;
    if (shortTitle == null) shortTitle = "";
    shortTitle = shortTitle.substring(0, 100);
    /* end truncate my title */
    document.title = "TV Guide Video | " + player.getTitle() + " " + current.title;
    document.getElementById("videoTitle").innerHTML = shortTitle;
    var tminutes = parseInt(current.time / 60);
    var tseconds = tSecondsFormat(parseInt(current.time % 60));
    document.getElementById("videoDuration").innerHTML = "" + tminutes + ":" + tseconds + "";
    var embedCode = player.getCurrentItemEmbedCode();
    oldEmbedCode = embedCode;

    var lineup = player.getLineup();
    for (var i = 0; i < lineup.length; i++) {
        if (lineup[i].embedCode == embedCode) {
            var divName = "lineup_" + i.toString();
            var myDiv = document.getElementById(divName);
            if (!myDiv) return;
            myDiv = myDiv.nextSibling;
            if (!myDiv) return;
            highlightLink(myDiv);
            break;
        }
    }
}

/* onStateChanged will disply status of the player, either playing, buffering, paused, finished or error */
function onStateChanged(playerId, e) {
    var playerState = e.state;
    var player = document.getElementById('ooyalaPlayer');
    var current = player.getCurrentItem();

    if (playerState == 'playing') {
        s.prop3 = s.eVar3 = current.title;
        s.linktrackVars = "prop3,eVar3,events";
        s.linktrackEvents = "event9";
        s.events = "event9";
        s.tl("http://nyc1onldev1:2008/video/onevideo.aspx?v=", 'o', current.title);
        s.Media.trackVars = "prop3,eVar3,events";
        s.Media.trackEvents = "event9";
        s.Media.open(current.title, current.time, playerId);
        s.Media.play(current.title, 0);
    }
    else if (playerState == 'paused') {
        s.prop3 = s.eVar3 = current.title;
        s.Media.trackVars = "prop3,eVar3,events";
        s.Media.trackEvents = "event9";
        s.Media.stop(current.title, current.time);
        s.Media.close(current.title);
    }
    if (e.state == 'playing') {
        onPlaying(playerId);
    }
    if (e.state == 'buffering') {
        onBuffering(playerId);
    }
    if (e.state == 'paused') {
    }
    if (e.state == 'finished') {
        setVideoMessage(playerId, "(Done)");
    }
    if (e.state == 'error') {
        setVideoMessage(playerId, "(Error)");
    }
}
/* hide leave behind ad */
var leaveHide = "";

function onBuffering(playerId) {
    //setVideoMessage(playerId,"(Loading)");
}

function ooyalaPlayerCallback(playerId, eventName, data) {

    if (eventName == 'stateChanged') {
        onStateChanged(playerId, data);
        return;
    }
    if (eventName == 'playheadTimeChanged') {
        var player = document.getElementById(playerId);

        if (AmazonDisplay && AmazonState == 0) {
            if (player.getPlayheadTime() >= 20) {
                ShowAmazon();
            }
            if (player.getPlayheadTime() >= 40) {
                HideAmazon();
                AmazonDisplay = false;
            }
        }
        return;
        var player = document.getElementById(playerId);
        if (player.getPlayheadTime() >= 5) {
            //alert("20secs");
        }
    }

    if (eventName == 'loadComplete') {
        startup();
        return;
    }
    if (eventName == "currentItemEmbedCodeChanged") {
        HideAmazon();
        AmazonState = 0;
        var player = document.getElementById(playerId);
        var iDesc = player.getCurrentItemDescription();
        getAmazon(iDesc);
    }
    if (eventName == 'embedCodeChanged') {
        PopulateVideoList();
        HideAmazon();
    }
    if (eventName == 'totalTimeChanged') {
        $(document).ready(function() {
            $("#myAdVideo").fadeOut("slow");
        });
    }
}
function playVideo(embedCode) {
    var player = document.getElementById('ooyalaPlayer');
    player.setCurrentItemEmbedCode(embedCode);
    player.playMovie();
}

function PopulateVideoList() {
    var player = document.getElementById('ooyalaPlayer');
    var lineup = player.getLineup();
    var nav = ''
    for (var i = 0; lineup && i < lineup.length; i++) {
        var divName = "lineup_" + i.toString();
        var shortTitleDiv = truncate(lineup[i].title, 65, '...');
        var minutesZero = formatMinutes(parseInt(lineup[i].time % 60, 10));
        var myThumbImage = player.getPromoFor(lineup[i].embedCode, 80, 60);
        nav += "<li class='resultLink' style='cursor:pointer;' onclick='javascript:playVideo(\"" + lineup[i].embedCode + "\");void(0);'/>";
        nav += "<div id='allChannels'>";
        nav += "<div class='details'>";
        nav += "<div id=\"" + divName + "\" class='Block'></div>";
        nav += "<div ";
        nav += "onmouseup='javascript:highlightLink(this);' class='divlink' >" + shortTitleDiv + "</div>";
        nav += "<div class='pTime'>" + parseInt(lineup[i].time / 60, 10) + ":" + minutesZero + "</div></div>";
        nav += "<div id='" + lineup[i].embedCode + "' class='imageOutline'  ";
        nav += " onclick='javascript:playVideo(\"" + lineup[i].embedCode + "\");void(0);'>";
        nav += "<img src='" + myThumbImage + "' width='80' height='60' alt='" + myThumbImage + "' />";
        nav += "</div></div>";
        nav += "</li>";
    }
    document.getElementById('channelList').innerHTML = nav;
    SetVideoCount(i);
    var $channelScroller = $('#channelList');
    $channelScroller.jScrollPane({ scrollbarWidth: 10, animateTo: false });
}

/* These functions show single video embed tag inside an overlay 
when using embed this video link on Ooyala Page */
$(document).ready(function() {
    //shop button hide/show
    $("#shopButton").click(function() {
        if ($("div.shopButton").hasClass("shopButton")) {
            ShowAmazon();
            AmazonState = 1;
        }
    });

    //Share Single Video
    $("a.singleVideo").click(function() {
        var contents = document.getElementById('singleVideoLink').innerHTML;
        var player = document.getElementById('ooyalaPlayer');
        var current = player.getCurrentItem();
        contents = contents.replace(/%embed%/g, current.embedCode).replace(/&gt;/g, "\>").replace(/&lt;/g, "\<").replace(/&amp;/g, "&");
        document.getElementById('embedcodesinglevideo').value = contents;        
        $("div.overlay").slideDown("slow");
    });
    $("div.closeBtn").click(function() {
        $("div.overlay").slideUp("slow");
        $("div.CopyToClipBoard").fadeOut("slow");
          document.getElementById('d_clip_button').style.disabled = true;
           document.getElementById('d_clip_button').style.display = "none";
           document.getElementById("d_clip_button").style.cursor = "default";
           document.getElementById('copied').style.disabled = true;
           document.getElementById('copied').style.display = "none";        
    });
    $("div.shareVideo:first").click(function() {
        $(this).fadeTo("slow", 0.10);
    });
    $("div.closeBtn:first").click(function() {
        $("a.shareVideo").fadeTo("slow", 0.90);        
    });

    // End of Share Single Video 
    $("a.shareVideo").click(function() {       
        //if (clip!=null)clip.show();
           
        var contents = document.getElementById('myembedcode').innerHTML;
        var player = document.getElementById('ooyalaPlayer');
        var current = player.getCurrentItem();
        contents = contents.replace(/%embed%/g, current.embedCode).replace(/&gt;/g, "\>").replace(/&lt;/g, "\<").replace(/&amp;/g, "&");
        document.getElementById('embedcodesinglevideo').value = contents;
        document.getElementById("d_clip_button").style.visibility = "visible";
        document.getElementById("d_clip_button").style.display = "block";
        document.getElementById("d_clip_button").style.cursor = "hand";
        document.getElementById("copied").style.visibility = "visible";
        document.getElementById("copied").style.display = "block";        
        $("div.overlay").slideDown("slow");
        $("div.CopyToClipBoard").fadeIn(2500);
        turnCursOn();    
        
    });
    $("div.closeBtn").click(function() {
     //   if(clip!=null )clip.hide(); 
        $("div.overlay").slideUp("slow");       
    });
    $("div.shareVideo:first").click(function() {
        $(this).fadeTo("slow", 0.10);
    });
    $("div.closeBtn:first").click(function() {
        $("a.shareVideo").fadeTo("slow", 0.90);
    });
});

function truncate(shortTitleDiv, length, ellipsis) {
    if (typeof length == 'undefined') var length = 70;
    if (typeof ellipsis == 'undefined') var ellipsis = '...';
    if (shortTitleDiv.length < length) return shortTitleDiv;
    for (var i = length - 1; shortTitleDiv.charAt(i) != ' ' && i >= 0; i--) length--;
    return shortTitleDiv.substr(0, length) + ellipsis;
}

function formatMinutes(minutesZero) {
    if (minutesZero < 10)
        return "0" + minutesZero;
    return minutesZero;
}

function tSecondsFormat(tseconds) {
    if (tseconds < 10)
        return "0" + tseconds;
    return tseconds;
}

/* Copy function for FF and IE */
/* function CopyClipboard(inElement) {
if (inElement.createTextRange) {
var range = inElement.createTextRange();
//  if (range && BodyLoaded==1)
if (range)    
range.execCommand('Copy');
} else {
var flashcopier = 'flashcopier';
if(!document.getElementById(flashcopier)) {
var divholder = document.createElement('div');
divholder.id = flashcopier;
document.body.appendChild(divholder);
}
document.getElementById(flashcopier).innerHTML = '';
var divinfo = '<embed src="../Video/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashcopier).innerHTML = divinfo;
}
}
*/

/*2nd Part to Copy function to Clipboard embed code */
/*
function ClipBoard(){
var embedcodesinglevideo = document.getElementById('embedcodesinglevideo');
CopyClipboard(embedcodesinglevideo);
}
*/

/****** DoubleClick Ad Call ******/
function syncRoadBlock(adTag) {
    $(document).ready(function() {
        a = adTag.split(';');
        if (a.length > 0) {
            for (x = 0; x <= a.length - 1; x++) {
                if (a[x].indexOf('sz=') == 0) {
                    size = a[x].substring(3);
                    dims = size.split('x');
                    height = dims[1];
                    width = dims[0];
                    var myContainerOff = document.getElementById("myAdBigHolderId").style.display = "none";
                    var myContainerOn = document.getElementById("myAdBigHolderId").style.display = "block";
                    var mylocation2 = window.location.pathname.toLowerCase();
                    if (mylocation2 == "/video/" || mylocation2 == "/video/player.aspx") {
                        if (height == "60") {
                            document.getElementById("myAdBigHolderId").style.display = "none";
                            $("div.myAdBigCl").fadeOut("slow");
                            $("div.myAdBigClose").fadeOut("slow");
                            $("div.myAdVideoCl").fadeIn("slow");
                            $("#myAdVideo").fadeIn("slow");
                            loadRBs('myAdVideo', height, width, adTag);
                        } else if (height == "250") {
                            document.getElementById("myAdBigHolderId").style.display = "block";
                            document.getElementById("myAdBig").style.display = "block";
                            $("div.myAdBigClose").fadeIn("slow");
                            //close button for Ad                                                   
                            $("div.myAdBigClose").click(function() {
                                $("div.myAdBigCl").fadeOut("slow");
                                $(this).fadeOut("slow");
                                $("div.myAdBigHolder").hide("slow");

                                return false;
                            });
                            // end of close button
                            $("div.myAdVideoCl").fadeOut("slow");
                            $("div.myAdBigCl").fadeIn("slow");
                            loadRBs('myAdBig', height, width, adTag);
                        }
                    }
                    else {
                        if (height == "60") {
                            document.getElementById("myAdBigHolderId").style.display = "none";
                            document.getElementById("myAdBig_special").style.display = "none";
                            $("div.myAdBigCl").fadeOut("slow");
                            $("div.myAdVideoCl").fadeIn("slow");
                            $("div.myAdBigClose").fadeOut("slow");
                            loadRBs('myAdVideo_special', height, width, adTag);
                        } else if (height == "250") {
                            document.getElementById("myAdBigHolderId").style.display = "block";
                            document.getElementById("myAdBig_special").style.display = "block";
                            $("div.myAdBigClose").fadeIn("slow");
                            //close button for Ad                                                   
                            $("div.myAdBigClose").click(function() {
                                $("div.myAdBigCl").fadeOut("slow");
                                $(this).fadeOut("slow");
                                $("div.myAdBigHolder").hide("slow");
                                return false;
                            });

                            $("div.myAdVideoCl").fadeOut("slow");
                            $("div.myAdBigCl").fadeIn("slow");
                            loadRBs('myAdBig_special', height, width, adTag);
                        }

                    }
                    /**************End of DoubleClick if statment***********************/
                }
            }
        }
        // closing my jquery here
    });
}

function loadRBs(s, h, w, adTag) {
    document.getElementById(s).innerHTML = '<iframe src="' + adTag + '" id="ifr_companion" width="' + w + '" height="' + h + '" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}

var xmlHttpAmazon = null;
var oldQuery = null;
function getAmazonAJAX(query) {
    if (oldQuery == query && AmazonData != null) {
        ProcessReturnFromAmazon(AmazonData);
        return;
    }
    oldQuery = query;
    AmazonData = null;
    xmlHttpAmazon = GetXmlHttpObject(xmlAmazonEvent);

    if (xmlHttpAmazon != null) {
        xmlHttpAmazon.open("GET", "/Script/ajax_callbacks/video_amazon_json.ashx?q=" + escape(query) + "&c=5", true);
        xmlHttpAmazon.send(null);
    }
}

var AmazonData = null;
function xmlAmazonEvent() {
    if (xmlHttpAmazon.readyState == 4 || xmlHttpAmazon.readyState == "complete") {
        AmazonData = xmlHttpAmazon.responseText;
        ProcessReturnFromAmazon(AmazonData);
    }
}

function HideAmazon() {
    $(document).ready(function() {
        $("div.AmazonAd").fadeOut("slow");
    });
}

function ShowAmazon() {

    $(document).ready(function() {
        $("div.AmazonAd").slideDown(1000);
    });
    $("div.close").click(function() {
        $("div.AmazonAd").slideUp("slow");
        $("div.shopButton").fadeIn("slow");
        AmazonState = 2;
    });

}
function ShowLeaveBehind() {
    $(document).ready(function() {
        $("#myAdVideo").fadeIn("slow");
        loadRBs('myAdVideo', height, width, adTag);
    });
}

function ProcessReturnFromAmazon(strText) {
    var d = eval(strText);
    if (d == undefined) return;
    if (d == "") return;

    if (d.Products != null && d.Products.length >= 0) {
        var rVal = new Array();
        var maxLength = 3;
        var l = d.Products.length;
        if (l >= maxLength) {
            l = maxLength;
        }

        for (var i = 0; i < l; i++) {
            var Product = d.Products[i];
            AppendProduct(Product, rVal);

        }
        if (l + 1 != d.Products.length) {
            /* rVal.push("<div class=\"moreProducts\"><img src='/images/ooyala/rightOO.gif'> more " + Product.Title + " products</div>"); */
        }

        var amazonData = rVal.join("");
        var theDiv = document.getElementById("AmazonAdID");
        theDiv.innerHTML = amazonData;
        theDiv = document.getElementById("shopButton");
        theDiv.className = "shopButton";
        AmazonDisplay = true;
        return;
    }
}

function AppendProduct(Product, rVal) {
    if (Product == undefined || Product == null) return;

    rVal.push("<div class='AmazaonWrapper clear'>");
    rVal.push("<div class='AmazonImg' style='background-image: url(" + Product.ImageSrc + ");'>");
    rVal.push("&nbsp;</div>");
    rVal.push("<div class='AmazonDetails'>");
    rVal.push("<a href='");
    rVal.push(Product.DetailPageUrl);
    rVal.push("' target='_blank' class='linkRed' onclick=\"document.getElementById('ooyalaPlayer').pauseMovie();\">");
    rVal.push(Product.Title);
    rVal.push("</a>");
    rVal.push("<br />");
    rVal.push("From: ");
    rVal.push(Product.Publisher);
    rVal.push("<br />");
    /*Check is rating is not empty */
    if (Product.AverageRating != "") {
        rVal.push("Average Customer Review: ");
        rVal.push(Product.AverageRating);
        rVal.push("<br />");
    }
    rVal.push(Product.ShipInfo);
    rVal.push("<br />");
    rVal.push("Buy New: " + Product.Price +
    " (as of " + Product.PriceAsOf + " EST - <a href='" +
    Product.DetailPageUrl + "' class='linkRed' target='_blank' onclick=\"document.getElementById('ooyalaPlayer').pauseMovie();\">more info</a>)");

    rVal.push("</div>");
    rVal.push("</div>");
}