﻿/*
    Video Categories: 
        HD=Handheld Demo,
        KD=Kiosk Demo, 
        RS=Real Stories, 
        HTS=How To Series, 
        HMS=Health Masters Series
*/
var categoryIds = new Array("HD", "KD", "RS", "HTS", "HMS", "VR");
var categoryTitles = new Array("CarMD's Handheld Demo", "CarMD's Kiosk Demo", "CarMD's Real Stories", "CarMD's Easy \"How To...\" Series", "CarMD's Vehicle Health Matters Series", "CarMD's Vehicle Reviews");
var categoryRates = new Array("Poor", "Nothing special", "Worth watching", "Pretty cool", "Awesome!");
var currentVideoList = null;
var currentVideoId = null;
var currentRating = 0;
var ratedVideos = "";
var currentCategory = null;
var currentVideoObject = null;
var index = -2;
var timeoutObj = null;
var timeoutRating = null;
var isPlaying = false;
/**/

function Replay() {
    ShowHideReplayVideo(false, false);
    index = -2;
    $f().play(videoMoviesUrl + "/" + currentVideoObject.VideoFile);
    isPlaying = true;
    SetHiddenInfo();
    document.title = "CarMD Video";
}

/*On category change*/
function SelectedCategoryChange(index) {
    $("#no-video").hide();
    //Check if user is on selected tab at this time?
    if (categoryIds[index - 1] == currentCategory) return false;
    //Reset current Video list
    currentVideoList = null;

    for (var k = 1; k <= 5; k++) {
        var i = (k == 1) ? 1 : k + 1;

        if (index == i) {
            document.getElementById("tab" + i).src = "images/tab" + i + "_on.gif";
        } else {
            document.getElementById("tab" + i).src = "images/tab" + i + "_off.gif";
        }
    }
    currentCategory = categoryIds[index - 1];
    $("#spSelectedCategory").html(categoryTitles[index-1]);
    LoadVideosByCategory(index);
    currentShowIndex = -1;
}
/*Load list of Video by category*/
function LoadVideosByCategory(category) {
    $("#VideoList").html("");
    $.ajax({
        type: "GET",
        url: "/Video/GetVideosByCategory?ran=" + Math.random(),
        data: "category=" + categoryIds[category - 1],
        dataType: "json",
        error: function(xhr, des, error) { /*could not load ajax*/
            alert(xhr.resposeText);
            window.location.reload();
        },
        success: function(jsonData) {
            currentVideoList = jsonData;
            BindVideosToList(jsonData);
        }
    });
    document.title = "CarMD Video";
}

/*Bind Videos to list*/
function BindVideosToList(jsonResult) {
    var videos = "<ul id='video_list'>\n";
    if (jsonResult.length > 0) {
        var thumb = "";
        for (var i = 0; i < jsonResult.length; i++) {
            if (jsonResult[i].ThumbImage != '') {
                thumb = jsonResult[i].ThumbImage;
            } else {
                thumb = "no-image.gif";
            }
            videos += " <li>\n";
            videos += "     <a onclick=\"SetupVideoInfo('" + jsonResult[i].Id + "')\" href='#' style='width:80px;height:80px;background: url(" + videoThumbsUrl + "/" + thumb + ") 0 0 no-repeat;'>\n";
            videos += "         <div class='content'>\n";
            videos += "         <div class='title'>" + jsonResult[i].Title + "</div>\n";
            videos += "              <span style='font-size:11px'>";
            videos +=               jsonResult[i].Quot + "<br />\n";
            videos += "             <i>Length: " + jsonResult[i].Length + "</i><br />\n";
            videos += "             <i>Views: <span id='" + jsonResult[i].Id + "'>" + jsonResult[i].NumOfViewing + "</span></i>\n";
            videos += "              </span>"
            videos += "         </div>";
            videos += "     </a>\n";
            videos += " </li>\n"
        }
        if (currentVideoId != null) {
            SetupVideoInfo(currentVideoId); // Play video from querystring
        } else {
            //Reset old data
            ClearCurentData();
            //Display play button
            $("#btn_video").css("visibility", "visible");
        }

    } else {
        //Reset old data
        ClearCurentData();
        videos += "<li><h4>No video found.</h4></li>";
    }
    videos += "</ul>\n";
    $("#VideoList").html(videos);
    ApplyStyle();
}

/*Setup Video info*/
function SetupVideoInfo(videoId) {
    $("#no-video").hide();
    index = -2;
    ClearCurentData();
    $.ajax({
        type: "GET",
        url: "/Video/GetVideoDetails?ran=" + Math.random(),
        data: "videoId=" + videoId,
        dataType: "json",
        error: function(xhr, des, error) { /*could not load ajax*/
            alert(xhr.resposeText);
            window.location.reload();
        },
        success: function(jsonData) {
            BindNewData(jsonData);
            UpdateViewNumber(videoId);
            $("#" + videoId).html(parseInt($("#" + videoId).html()) + 1);
        }
    });
}

/*Show modal panel*/
function ShowModalPanel(videoId) {
}

/*Call Flash to play a Video*/
function PlayVideo(videoFile) {
    $("#no-video").hide();
    $("#btn_video").css("visibility", "hidden");
    ShowHideReplayVideo(false, false);
    $f().play(videoMoviesUrl + "/" + videoFile);
    isPlaying = true;
    document.title = "CarMD Video";
}

/*Stop and reset player*/
function StopAndResetPlayer() {
    $f().stop();
    $f().unload();
}

/*Reset current data*/
function ClearCurentData() {
    $("#no-video").hide();
    StopAndResetPlayer(); /*Stop and reset player*/
    $("#spSelectedVideo").html("");
    $("#spNumOfRating").html("");
    $("#bNumOfViewing").html("");
    $("#diggLink").removeAttr("href");
    $("#myspaceLink").removeAttr("href");
    $("#facebookLink").removeAttr("href");
    $("#txtURL").val("");
    $("#txtEmbed").val("");
    currentVideoId = null;
    currentVideoObject = null;
    CloseInfo();
    ShowHideReplayVideo(false, false);
    ReDrawRatingPanel();
    LockRatingPanel();
}

/*Re-bind new data*/
function BindNewData(videoObj) {

    currentVideoObject = videoObj; //Set current video
    ReDrawRatingPanel();
    PlayVideo(videoObj.VideoFile); /*Start play video*/
    
    $("#spSelectedVideo").html(videoObj.Title);
    $("#txtURL").val(HTTPFullPathAndAppName + "/Video/Watch/?v=" + videoObj.Id + "&n=" + videoObj.VideoName);
    $("#txtEmbed").val(GetEmbedString());

    $("#diggLink").attr("href", "http://digg.com/submit?phase=2&url=" + $("#txtURL").val());
    $("#diggLink").attr("target", "_blank");

    $("#myspaceLink").attr("href", "http://www.myspace.com/Modules/PostTo/Pages/?t=" + videoObj.Title + "&u=" + $("#txtURL").val() + "&c=" + $("#txtEmbed").val());
    $("#myspaceLink").attr("target", "_blank");
        
    $("#facebookLink").attr("href", "http://www.facebook.com/sharer.php?u=" + $("#txtURL").val() + "&t=" + videoObj.Title);
    $("#facebookLink").attr("target", "_blank");

    var averageRating = Math.round(videoObj.SumOfRating / videoObj.CountOfRating);
    currentRating = averageRating;
    ChangeRating(averageRating);   
    $("#spNumOfRating").html(videoObj.CountOfRating + " ratings.");
    $("#bNumOfViewing").html(videoObj.NumOfViewing + " views");
    
    if(IsVideoRated(videoObj.Id))
    {
        LockRatingPanel();
        $("#spNumOfRating").html($("#spNumOfRating").html()+ " You have already rated");
    }
}

/*Build embed string for current Video*/
function GetEmbedString() {
    var ebstring = "";
    ebstring += "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"267\" height=\"150\">";
    ebstring += "<param name=\"movie\" value=\"" + HTTPFullPathAndAppName + "/Video/flowplayer-3.0.7.swf\"></param>";
    ebstring += "<param name=\"flashvars\" value='config={\"clip\":{\"url\":\"" + videoMoviesUrl + "/" + currentVideoObject.VideoFile + "\",\"autoPlay\":false}}'></param> ";
    ebstring += "<param name='wmode' value='transparent'></param>";
    ebstring += "<embed type=\"application/x-shockwave-flash\" width=\"267\" height=\"150\"";
    ebstring += " src=\"" + HTTPFullPathAndAppName + "/Video/flowplayer-3.0.7.swf\"";
    ebstring += " flashvars='config={\"clip\":{\"url\":\"" + videoMoviesUrl + "/" + currentVideoObject.VideoFile + "\",\"autoPlay\":false}}'></embed>";
    ebstring += "</object>";
    return ebstring;
}

/*On Video play completed*/
function OnVideoCompleted() {
    alert("Called by Flash on end of movie stream");
}

/*Chang rating when mouse moves on rating images*/
function ChangeRating(index) {
    /*Check if current video object is null - player is stopped*/
    if (currentVideoObject == null) return false;
    
    if ((isUserLogin == "false" && index == currentRating) || isUserLogin == "true") {
        for (var i = 1; i <= 5; i++) {
            if (i <= index) {
                document.getElementById("start" + i).src = "images/rate_1.gif";
            } else {
                document.getElementById("start" + i).src = "images/rate_0.gif";
            }
        }
    }
        
    if (isUserLogin == "false") {
        $("#spNumOfRating").html("<a style='color:#fff; text-decoration:none; font-weight:bold' href='/Member/Login'>Sign in</a> to rate");
    } else {
        $("#spNumOfRating").html(categoryRates[index - 1]);
    }
    clearTimeout(timeoutRating);
}

function ResetRating() {
    if(currentVideoObject!=null) timeoutRating = window.setTimeout('ResetRatingDelay()', 800);
}

/*Delay 1s after mouse out of start*/
function ResetRatingDelay() {
    ChangeRating(currentRating);
    $("#spNumOfRating").html(currentVideoObject.CountOfRating + " ratings.");
    if (IsVideoRated(currentVideoObject.Id)) {
        LockRatingPanel();
        $("#spNumOfRating").html($("#spNumOfRating").html() + " You have already rated");
    }   
}

/*Lock Rating panel after rated*/
function LockRatingPanel() {
    var img = null;
    for (var i = 1; i <= 5; i++) {
        img = document.getElementById("start" + i);
        img.onclick = null;
        img.onmouseover = null;
    }
}

/*Reset rating panel on playing new video*/
function ReDrawRatingPanel() {
    var strRating = "";
    strRating+="<img align=\"left\" id=\"start1\" alt=\"\" src=\"images/rate_0.gif\" style=\"cursor:pointer\" onmouseover=\"ChangeRating(1)\" onclick=\"Rate(1)\" class=\"rating\" />\n";
    strRating += "<img align=\"left\" id=\"start2\" alt=\"\" src=\"images/rate_0.gif\" style=\"cursor:pointer\" onmouseover=\"ChangeRating(2)\" onclick=\"Rate(2)\" class=\"rating\" />\n";
    strRating += "<img align=\"left\" id=\"start3\" alt=\"\" src=\"images/rate_0.gif\" style=\"cursor:pointer\" onmouseover=\"ChangeRating(3)\" onclick=\"Rate(3)\" class=\"rating\" />\n";
    strRating += "<img align=\"left\" id=\"start4\" alt=\"\" src=\"images/rate_0.gif\" style=\"cursor:pointer\" onmouseover=\"ChangeRating(4)\" onclick=\"Rate(4)\" class=\"rating\" />\n";
    strRating += "<img align=\"left\" id=\"start5\" alt=\"\" src=\"images/rate_0.gif\" style=\"cursor:pointer\" onmouseover=\"ChangeRating(5)\" onclick=\"Rate(5)\" class=\"rating\" />\n";
    $("#ratingPanel").html(strRating);
}

/*Rate a video*/
function Rate(level) {
    if (currentVideoObject == null) {
        alert("Please select to play a video first.");
        return false;
    }
    if (isUserLogin == "true") {
        /*Send rate to server, then update video's rating*/
        LockRatingPanel();
        SendRating(currentVideoObject.Id, level);
        //$("#spNumOfRating").html("Thanks for your rating.");
    }
}

/*Check if the user has already rated for a video yet*/
function IsVideoRated(videoId) {
    return ratedVideos.indexOf("{" + videoId + "}") > -1;
}

/*Send a rating to server*/
function SendRating(videoId, level) {
    /*Call Ajax to send*/
    $.ajax({
        type: "GET",
        url: "/Video/Rate?ran=" + Math.random(),
        data: "videoId=" + videoId + "&level=" + level,
        dataType: "json",
        error: function(xhr, des, error) { /*could not load ajax*/
            alert("Your session has been time out. Please re-login to rate this video.");
            window.location.reload();
        },
        success: function(jsonData) {
            currentVideoObject.CountOfRating += 1;
            var averageRating = Math.round(jsonData.SumOfRating / jsonData.CountOfRating);
            ChangeRating(averageRating);
            currentRating = averageRating;
            $("#spNumOfRating").html(jsonData.CountOfRating + " ratings. Thanks for your rating.");
        }
    });
    /*Update rated videos*/
    ratedVideos += ",{" + videoId + "}";
}

/*To show or hide the replay list after end of video*/
function ShowHideReplayVideo(flag, isEndOfStream) {
    if (flag==true) {
        //$("#replay").css("visibility", "visible");
        $("#replay").show("slow");
        if (currentVideoList.length > 2) {
            timeoutObj = setTimeout("ShowVideoInfo('next', false)", 5000);
        }
    }
    else {
        //$("#replay").css("visibility", "hidden");
        $("#replay").hide();
        clearTimeout(timeoutObj);
        timeoutObj = null;
    }
}

function ShowVideoInfo(direction, isEndOfStream) {
    if (isPlaying == true && isEndOfStream==false) {
        isPlaying = false;
        return false;
    }
    var total = currentVideoList.length - 1;
    
    /*Process timeout*/
    if (timeoutObj != null && timeoutObj != undefined) {
        if (index + 2 > total) {
            index = -2;
            clearTimeout(timeoutObj);
            timeoutObj = setTimeout("ShowVideoInfo('next', false)", 5000);
            return false;
        }
    }
    /*Show video info*/
    if (currentVideoList!=null && currentVideoList.length > 0) {
        if (direction == "next") {
            if (index + 2 <= total) {
                index += 2;
                DisplayVideoInfo("videoInfoAbove", index);
                DisplayVideoInfo("videoInfoBellow", index + 1);
            } else {
           }
        } else { /*previous*/
            if (index - 2 >= 0) {
                index -= 2;
                DisplayVideoInfo("videoInfoAbove", index);
                DisplayVideoInfo("videoInfoBellow", index + 1);
            } else {
            }
        }
    }
    
    timeoutObj = setTimeout("ShowVideoInfo('next', false)", 5000);
 }

 function DisplayVideoInfo(divId, index) {
     $("#" + divId).html("");
     var video = currentVideoList[index];
     var data = "";
     var averageRating = 0;
     var thumb = "";
     if (video != null) {
         if (video.ThumbImage != '') {
             thumb = video.ThumbImage;
         } else {
             thumb = "no-image.gif";
         }
         averageRating = Math.round(video.SumOfRating / video.CountOfRating);
         if (isNaN(averageRating)) averageRating = 0;
         data += "<img onclick=\"SetupVideoInfo('" + video.Id + "')\" src='" + videoThumbsUrl +"/" + thumb + "' width='70'height='70' style='cursor:pointer' />";
         data += "<div style='position:absolute; top:7px; left:90px;'>";
         data += "<ul>";
         data += "  <li class='title'>" + video.Title + "</li>";
         data += "  <li>" + video.Length + "</li>";
         data += "  <li> From: " + video.PostedBy + " <img src='images/Rate_" + averageRating + ".png' align='absmiddle' style='position:absolute; top:33px; left:180px;'/></li> ";
         data += "  <li> Views: " + video.NumOfViewing + " </li>";
         data += "</ul>";
         data += "</div>";
         $("#" + divId).hide();
         $("#" + divId).html(data);
         $("#" + divId).show("slow");
         $("#" + divId + "_bg").show("slow");         
     } else {
         $("#" + divId).hide("slow");
         $("#" + divId + "_bg").hide("slow");
     }
 }

 function ApplyStyle() {
     // if ($.browser.msie && $.browser.version < 7) return;
     $('#video_list li')
        .find('a')
        .append('<span class="hover" style="background: url(images/play.jpg);" />').each(function() {
            var $span = $('> span.hover', this).css('opacity', 0);
            $(this).hover(function() {
                // on hover
                $span.stop().fadeTo(250, 0.5);
            }, function() {
                // off hover
                $span.stop().fadeTo(250, 0);
            });
        });
    }

function UpdateViewNumber(videoId) {
    for (var i = 0; i < currentVideoList.length - 1;  i++) {
        if (currentVideoList[i].Id == videoId) {
            currentVideoList[i].NumOfViewing += 1;
            break;
        }
    }
}

function SetHiddenInfo() {
    $("#videoInfoAbove").hide("slow");
    $("#videoInfoAbove_bg").hide("slow");

    $("#videoInfoBellow").hide("slow");
    $("#videoInfoBellow_bg").hide("slow");
}

function CloseInfo() {
    $("#videoInfoAbove").hide();
    $("#videoInfoAbove_bg").hide();

    $("#videoInfoBellow").hide();
    $("#videoInfoBellow_bg").hide();
}

/*Play first video in the list*/
function PlayFirstVideo() {
    if (currentVideoList!=null && currentVideoList.length > 0) {
        SetupVideoInfo(currentVideoList[0].Id);
    }
}