﻿/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js" /> 
//------------------------------------------------------------------------
// MASTER PAGE
//------------------------------------------------------------------------
//Light up the appropriate tab
var filter = null;
var isClinicMode = false;
$(document).ready(function() {

    var on = $("#VideoTabs").children('li.on');
    if (on != null)
        on.removeClass("on");
    var v = location.pathname.toLowerCase();
    if (v.indexOf("video/play", 0) > -1) {
        $("#VideoTabs").children('li:eq(1)').addClass("on");
    }
    else if (v.indexOf("video/dashboard", 0) > -1) {
        $("#VideoTabs").children('li:eq(2)').addClass("on");
    }
    else if (v.indexOf("video/edit", 0) > -1) {
        $("#VideoTabs").children('li:eq(3)').addClass("on");
    }
    else {
        $("#VideoTabs").children('li:eq(0)').addClass("on");
    }

    if (!Silverlight.isInstalled("2.0"))
        $("#hd_nosilverlight").css("display", "block");

    //$("#isPublic").change(onSelectChange);

    //SetClinicMode(isClinicMode);
    
    $(".required").tooltip()
    $(".new").tooltip()
    $(".restricted").tooltip()
    $(".published").tooltip()
});

function onSelectChange(groupId) {
    var dropdown = document.getElementById("isPublic");
    var index = dropdown.selectedIndex;
    var ddVal = dropdown.options[index].value;
    var ddText = dropdown.options[index].text;
    //alert("You Selected " + ddText);
    filter = ddVal;
    
    url = "/Front/Video/Filter/" + ddVal;
    document.location = url;
}
function getVideoTab(index) {
    switch (index) {
        case 4:
            location.href = "/Front/Video/Edit";
            break;
        case 3:
            location.href = "/Front/Video/Dashboard";
            break;
        case 2:
            location.href = "/Front/Video/Player";
            break;
        default:
            location.href = "/Front/Video/";
            break;
    }
}


function SLDebug(message) {
    alert(message);
}


function getSearchResults(txtSearch, searchByPhrase) {

    if (txtSearch != "") {
        var url = "/Front/Video/Search";
        var targetDiv = "#leftSection";
        var ajaxLoading = "<img id='ajax-loader' src='/Front/Styles/Images/loading-spinner-big.gif' align='center' width='100px' height='100px' alt='loading...' />";

        $.fn.colorbox.close()

        $(targetDiv).html("<div style='text-align:center'>" + ajaxLoading + "</div>");
        $('#searchValue').attr('value', txtSearch);
        $.post(url, { searchValue: txtSearch, SearchByPhrase: searchByPhrase, PageNum: 0 }, function(result) {
            $(targetDiv).html(result);
            $('#ChapPanel').hide();
        });
    }
}


//------------------------------------------------------------------------
// Video Edit
//------------------------------------------------------------------------

function confirmSubmit(confirmText) {
    var agree = confirm(confirmText);
    if (agree)
        return true;
    else
        return false;
}


//function UpdateVideoToEdit(videoId) {
function GetVideoEditData(videoId) {

    $('#cboxClose').addClass('cboxCloseHidden');
    $('#name').val('');
    $('#isPublished').attr('checked', false);
    //$('#isPublic').attr('checked', false);
    $('#showChapters').attr('checked', false);
    $('#isRequired').attr('checked', false);
    $('#allowDownload').attr('checked', false);
    $('#clinicStartDate').val('');
    $('#clinicEndDate').val('');
    $('#videoEditTags').val('');
    $('#instructions').val('');
    $('#cutupId').val('');
    $('#sortOrder').val('');

    $.fn.colorbox({ width: '655px', height: '385px', inline: true, href: '#colorboxContainer', open: true });
    $('#cboxClose').hide();
    $.ajaxSetup({ cache: false });
    $.getJSON("/Front/Video/GetVideoJSON/" + videoId, null, function(data) {
        //alert(data.Name);
        $('#name').val(data.Name);
        $('#isPublished').val(data.IsPublishCutup);
        $('#isPublic').attr('selectedIndex', data.ViewableBy);
        $('#priorIsPublic').val(data.ViewableBy);
        $('#showChapters').attr('checked', data.SearchOnly);
        $('#isRequired').attr('checked', data.IsRequired);
        $('#allowDownload').attr('checked', data.AllowDownload);
        $('#clinicStartDate').val(data.ClinicStartDateString);
        $('#clinicEndDate').val(data.ClinicEndDateString);
        $('#videoEditTags').val(data.VideoEditTags);
        var instructions = '';
        if (data.Instructions != null && data.Instructions != 'null') {
            instructions = data.Instructions;
        }

        $('#instructions').val(instructions);
        $('#cutupId').val(data.CutupId);
        $('#groupId').val(data.GroupId);
        $('#sortOrder').val(data.SortOrder);

        $('#spinner').hide();
        $('#video_form').show();
        $("#video_form").animate({ scrollTop: $("#video_form").attr("scrollHeight") }, 3000);
    });
}

//function UpdateData() {
function UpdateVideoData(groupId) {

    //var date = $.datepicker.parseDate('MM/DD/YYYY', Date().getDate());

    var url = '/Front/' + groupId + '/Video/VideoEdit/';
    var priorIsPublic = $('#priorIsPublic').val();
    var filter;

    // some code to parse the filter from the URL 
    var pathAry = window.location.pathname.split("/");
    var i = 0;
    var j = null;
    for (i=0;i<pathAry.length;i++)
    {
        if (pathAry[i].toLowerCase() == 'filter')
        {
            j = i+1;
            break;
        }
    }
    if (j != null)
        filter = pathAry[j];

    //alert($('#video').serialize());
    $.post(url, $('#video').serialize(), function (json) {
        //        $.getJSON("/Front/Video/GetVideoJSON/" + $('#cutupId').val(), null, function(data) {
        var videoName = '#videoName_' + $('#cutupId').val();
        var restrictedElement = '#restricted_' + $('#cutupId').val();
        var restrictedValue = (json.ViewableBy == 0).toString();
        var searchOnlyElement = '#searchOnly_' + $('#cutupId').val();
        var searchOnlyValue = json.SearchOnly.toString();
        var newElement = '#new_' + $('#cutupId').val();
        var newValue = (json.ClipCountUserViews == 0).toString();
        var requiredElement = '#required_' + $('#cutupId').val();
        var requiredValue = json.IsRequired.toString()

        var tags = '#tags_' + $('#cutupId').val();
        $(videoName).html(json.Name);
        $(tags).text('');
        $(tags).html(json.ShortTagLinkList);
        //MoveIndicator(restrictedElement, restrictedValue, searchOnlyElement, searchOnlyValue, requiredElement, requiredValue, newElement, newValue, 0, 0);
        ShowHideIndicator(restrictedElement, restrictedValue);
        ShowHideIndicator(searchOnlyElement, searchOnlyValue);
        ShowHideIndicator(requiredElement, requiredValue);
        ShowHideIndicator(newElement, newValue);
        filter = json.ViewableBy;
        //        });
        if ($.fn != null && $.fn.colorbox != null) {
            $.fn.colorbox.close();
        }
        var redirectUrl = "/Front/" + groupId + "/Video/Filter/" + filter;
        if (priorIsPublic != filter) {
            document.location = redirectUrl;
        }
    }, "json");
}

function VideoSortUp(videoId){
    $.post('/Front/Video/VideoSortUp/' + videoId, null, function() {
    });
    return true;
}

function VideoSortDown(videoId){
    $.post('/Front/Video/VideoSortDown/' + videoId, null, function() {
});
    return true;
}

function ShowFullLinkList(id) {
    $('#cboxClose').addClass('cboxCloseHidden');
    $('#fullTags').html("");
    $('#cboxClose').hide();
    $.ajaxSetup({ cache: false });
    $.getJSON("/Front/Video/GetVideoTagsJSON/" + id, null, function(data) {
        //alert(data.Name);
        //var elementName2 = "#fullTags_" + id;
        var l_return = data.valueOf().toString();
        $('#fullTags').html(l_return);
        $.fn.colorbox({ width: '550px', inline: true, href: '#tagsContainer', open: true });
        $('#closeButton').show();
        $('#spinner').hide();
        
        
        //$(elementName).show();
    });
}


//------------------------------------------------------------------------
// Clip Edit
//------------------------------------------------------------------------
function GetClipEditData(clipId) {
    $('#cboxClose').addClass('cboxCloseHidden'); 
    
    $('#title').val('');
    $('#isPublic').attr('checked', false);
    $('#isCutupChapter').attr('checked', false);
    $('#clipEditTags').val('');
    $('#clipId').val('');
    $('#sortOrder').val('');

    $.fn.colorbox({ width: '655px', height: '265px', inline: true, href: '#colorboxContainer', open: true });
    $('#cboxClose').hide();
    $.ajaxSetup({ cache: false });
    $.getJSON("/Front/Video/GetClipJSON/" + clipId, null, function(data) {
        //alert(data.Name);
        $('#title').val(data.Title);
        $('#isPublic').attr('checked', data.IsPublic);
        $('#isCutupChapter').val(data.IsCutupChapter);
        $('#clipEditTags').val(data.ClipEditTags);
        $('#clipId').val(data.ClipId);
        $('#sortOrder').val(data.SortOrder);

        $('#spinner').hide();
        $('#clip_form').show();
        //$("#clip_form").animate({ scrollTop: $("#clip_form").attr("scrollHeight") }, 3000);
    });
}

function UpdateClipData() {

    $.post('/Front/Video/ClipEdit/', $('#clip').serialize(), function(json) {
        $.getJSON("/Front/Video/GetClipJSON/" + $('#clipId').val(), null, function(data) {
            var clipTitle = '#clipTitle_' + $('#clipId').val();
            $(clipTitle).text(data.Title);
            //$('#player_VideoTags').html(data.TagLinkList);
            $('#fullTagsContent_' + $('#clipId').val()).html(data.TagLinkList);
            var title = data.VideoName;
            if (title != data.Title)
                title += " - " + data.Title;
            $('#MainPanelHeader').text(title);
        });
    }, "json");

    $.fn.colorbox.close()
}

function ShowClipLinkList(id) {
    $('#cboxClose').addClass('cboxCloseHidden');
    $('#cboxClose').hide();

    var elementName = "#fullTags_" + id;
    $.fn.colorbox({ width: '400px', inline: true, href: elementName, open: true });
}

//------------------------------------------------------------------------
// Common Edit
//------------------------------------------------------------------------
function CancelUpdateData() {
    $.fn.colorbox.close()
}

$().bind('cbox_closed', function() {
    $('#spinner').show();
    $('#clip_form').hide();
});

$(function() {
    $('.error').hide();
    $('input.text-input').css({ backgroundColor: "#FFFFFF" });
    $('input.text-input').focus(function() {
        $(this).css({ backgroundColor: "#FFDDAA" });
    });
    $('input.text-input').blur(function() {
        $(this).css({ backgroundColor: "#FFFFFF" });
    });
});


//------------------------------------------------------------------------
// Video Player
//------------------------------------------------------------------------
var playingRow = null;
var playingClipId = null;
var priorClipId = null;
var videoClipViewerData = null;

function playClip(videoid) {
    playVideoFile(videoid, true);
}

function playVideo(videoId) {
    playVideoFile(videoId, false);
}

function playVideoFile(videoid, IsClip) {
    if (IsClip)
        location.pathname = location.pathname + "/playclip/" + videoid;
    else {
        var strPath = location.pathname.toString();
        if (strPath.indexOf("/Filter") > -1) {
            strPath = strPath.slice(0, strPath.indexOf("/Filter"));
        }
        location.pathname = strPath + "/player/" + videoid;
    }
}

function GetVideoPlayer() {
    if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content') != null) {
        if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer != null) {
            return $('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer
        }
    }
    return null;
}

// play the selected clip
function PlayClip(clipId) {
    var videoPlayer = GetVideoPlayer();
    if (videoPlayer != null) {
        videoPlayer.HideDownloadButton();
        videoPlayer.SetClip(-1, clipId, true);
        playingClipId = clipId;
    }
}

// called from the scriptable object when a new media source is loaded into the player
function MediaChanged(videoUri)
{
    var dvembed = $("#dvEmbed"); // tag won't exist unless video admin role
    if (dvembed != null) {
        // show the embed tag
        $(dvembed).show();
    }
}

// Called from the scriptable object (SL ServerUtility)
function UpdateClipLoaded(clipid) {
    priorClipId = playingClipId;
    playingClipId = clipid;
    priorPercentViewed = 0;
    playingPercentViewed = 0;
    // Highlight playing clip.  TODO: Scroll into view
    if (playingRow != null)
    {
        $(playingRow).removeClass("ui-state-active");
    }
    playingRow = $("#clipRow"+clipid); 
    $(playingRow).addClass("ui-state-active");

    $.ajaxSetup({ cache: false });
    var url = '/Front/Video/GetVideoViewerData/' + playingClipId;
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function (json) {
            var data = json.Data;
            $('#player_VideoPostedBy').text(data.SubDomain);
            $('#player_VideoPublished').text(data.PublishedString);
            $('#player_ClipLength').text(data.Length);
            $('#selectedClipId').val(data.SelectedClipId.toString());
            $('#player_VideoTags').val('');
            $('#player_VideoTags').html(data.TagLinkList);
            if (data.AllowDownload == true) {
                var videoPlayer = GetVideoPlayer();
                if (videoPlayer != null) {
                    videoPlayer.ShowDownloadButton();
                    $('#clipDownload').bind('click', function () {
                        return DownloadVideo(data.VideoUri);
                    });
                }
            }

            var title = data.VideoName;


            //            isClinicVideo = false;
            //            if (data.IsClinicVideo != null)
            //                isClinicVideo = data.IsClinicVideo;
            //            SetClinicMode(isClinicVideo);
            // 
            var myObject = data.ClipViewerData
            $.each(myObject, function (i, val) {
                if (val.ClipId == playingClipId) {
                    //if (title != data.VideoName)
                    title += " - " + val.ClipName;
                    $('#MainPanelHeader').text(title);

                    if (val.PercentComplete == 100) {

                        //                        if (isClinicVideo) {
                        //                            if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content') != null) {
                        //                                if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer != null) {
                        //                                    $('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer.SetClinicMode(false);
                        //                                }
                        //                            }
                        //                        }
                        //$('#watchedIcon_' + playingClipId).show()
                        //ClipComplete(playingClipId, true);
                    }
                    else {
                        //                        if (isClinicVideo) {
                        //                            if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content') != null) {
                        //                                if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer != null) {
                        //                                    $('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer.SetClinicMode(true);
                        //                                }
                        //                            }
                        //                        }
                        //$('#watchedIcon_' + playingClipId).hide()
                        //ClipComplete(playingClipId, false);
                    }
                }

                //                if (val.ClipId == priorClipId) {
                //                    if (val.PercentComplete == 100) {
                //                        $('#watchedIcon_' + priorClipId).show()
                //                    }
                //                    else {
                //                        $('#watchedIcon_' + priorClipId).hide()
                //                    }
                //                }

            });
        },
        data: {},
        async: true

    });

    // query data about the playing clip from the view controller

 }
 

//  Called from the player page from the download button
function DownloadVideo(videoUri) {
    location.href = videoUri;

    

}

  // Called from the scriptable object (SL ServerUtility)
function GetNextClipID(next) {
    // return the next clip in the list
    var isClinicCutup = false;
    var nextClipId = 0;

    var currentRow = $("#clipRow" + next);
    if (currentRow != null) {

        var nextRow = $(currentRow).next()[0];
        if (nextRow != null) {
            var s = $(nextRow).attr('id');
            if (s != null) {
                s = s.split("clipRow")[1];
                nextClipId = s;
            }
        }
    }

    if (nextClipId == 0) {
        nextClipId = next;
    }

    var url = '/Front/Video/GetIsClinicCutup/' + nextClipId;
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function(json) {
            var value = json.Data;
            if (value == true) {
                isClinicCutup = value;
            }
        },
        data: {},
        async: false
    });

    //SetClinicMode(isClinicCutup)
    $.ajaxSetup({ cache: false });
    var url = '/Front/Video/GetVideoViewerData/' + playingClipId;
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function(json) {
            var data = json.Data;
            var myObject = data.ClipViewerData
            //                SetClinicMode(isClinicCutup);
            $.each(myObject, function(i, val) {
                if (val.ClipId == next) {
                    if (val.PercentComplete == 100) {
                        if (nextClipId > 0) {
                            //                                if (isClinicCutup) {
                            //                                    if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content') != null) {
                            //                                        if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer != null) {
                            //                                            $('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer.SetClinicMode(false);
                            //                                        }
                            //                                    }
                            //                                }
                        }
                        //$('#watchedIcon_' + next).show()
                        //ClipComplete(next, true);
                    }
                    else {
                        if (nextClipId > 0) {
                            //                                SetClinicMode(isClinicCutup);
                            //                                if (isClinicCutup) {
                            //                                    if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content') != null) {
                            //                                        if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer != null) {
                            //                                            $('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer.SetClinicMode(true);
                            //                                        }
                            //                                    }
                            //                                }
                        }
                        //$('#watchedIcon_' + next).hide()
                        //ClipComplete(next, false);
                    }
                }
            });
        },
        data: {},
        async: true

    });

    if (isClinicCutup) {
        return null;
    }
    else {
        if (nextClipId != 0 && nextClipId != next) {
            return nextClipId
        }
        else {
            return null;
        }
    }
}

// Called from the scriptable object (SL ServerUtility)
 function GetPrevClipID(prev) {
     // return the previous clip in the list (if any)
     var previousClipId = null;
     var currentRow = $("#clipRow" + prev);
     if (currentRow != null) {

         var prevRow = $(currentRow).prev()[0];
         if (prevRow != null) {
             var s = $(prevRow).attr('id');
             if (s != null) {
                 s = s.split("clipRow")[1];
                 previousClipId = s;
             }
         }
     }

     if (previousClipId != null) {
         return previousClipId;
     }
     
 }

 function ClipComplete(clipId) {
     ClipCompleted(clipId, true);
 }
 
 function ClipCompleted(clipId, isComplete) {
     if (isComplete) {
         $('#watchedIcon_' + clipId).show();
     }
     else {
         $('#watchedIcon_' + clipId).hide();
     }
 }

 // Called from scriptable object (SL ServerUtility) when user clicks the embed button
 function EmbedSource(strSource) {
     alert(strSource);
 }

 function GetEmbedSource() {
     // get the embed source for the currently playing item
     // toggle visibility
     var videoPlayer = GetVideoPlayer();
     if (videoPlayer != null) {
         s = videoPlayer.GetEmbedSource();
         if (s != null) {
             $("#txtEmbedSource").text(s);
         }
     }
     $("#dvEmbedSource").toggle();
 }

// function SetClinicMode(isClinicMode) {
//     if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content') != null) {
//         if ($('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer != null) {
//             $('#ctl00_a_MainContentPlaceHolder_vp').attr('content').VideoPlayer.SetClinicMode(isClinicMode);
//         }
//     }
// }
 
function ShowHideIndicator(element, value){
    value = value.toString();
    if(value.toUpperCase() == "TRUE"){
        showIndicator(element);
    }
    else {
        hideIndicator(element);
    }
    return false;
}

function showIndicator(element){
    $(element).show();
    //$(element).fadeIn("slow");
    //.animate({opacity : 'show'}, 'fast');
      return false;
}

function hideIndicator(element){
    $(element).hide();
    //$(element).fadeOut('slow'); 
    //.animate({opacity : 'hide'}, 'fast');
      return false;
}

//function MoveIndicator(restrictedElement, restricted, searchOnlyElement, searchOnlyValue, requiredElement, required, newVideoElement, newVideo)
//{
//    MoveIndicator(restrictedElement, restricted, searchOnlyElement, searchOnlyValue, requiredElement, required, newVideoElement, newVideo, 0, 0);
//}

function MoveIndicator(restrictedElement, restricted, searchOnlyElement, searchOnly, requiredElement, required, newVideoElement, newVideo, xOffset, yOffset) {
    restricted = restricted.toString().toUpperCase();
    searchOnly = searchOnly.toString().toUpperCase();
    required = required.toString().toUpperCase();
    newVideo = newVideo.toString().toUpperCase();
    var yposition = yOffset;
    var xposition = xOffset;
    if (required == "FALSE") {
        $(requiredElement).css({ 'z-index': '0' });
    }
    else {
        $(requiredElement).css({ 'z-index': '999' });
    }

    if (newVideo == "TRUE") {
        $(newVideoElement).css({ 'margin-top': (yposition + 'px') });
        yposition -= 10;
    }
    if (required == "TRUE") {
        $(requiredElement).css({ 'margin-top': (yposition + 'px') });
        yposition -= 10;
    }
    if (restricted == "TRUE") {
        $(restrictedElement).css({ 'margin-top': (yposition + 'px') });
        yposition -= 10;
    }
    if (searchOnly == "TRUE") {
        $(searchOnlyElement).css({ 'margin-top': (yposition + 'px') });
    }

    return false;
}

