﻿function Show(pShowID) {

    // ============= PUBLIC PROPERTIES ========================
    ShowID = pShowID;               // internal reference
    this.ShowID = pShowID;          // external reference
    AudioRtmpPath = '';             // internal reference
    this.AudioRtmpPath = '';        // external reference
    AudioClipPath = '';             // internal reference
    this.AudioClipPath = '';        // external reference
    AudioClipsFolderID = '';        // internal reference
    this.AudioClipsFolderID = '';   // external reference
    AudioClipsPrefixText = '';      // internal reference
    this.AudioClipsPrefixText = ''; // external reference
    LiveStreamRtmpPath = '';        // internal reference
    this.LiveStreamRtmpPath = '';   // external reference
    LiveStreamClipName = '';        // internal reference
    this.LiveStreamClipName = '';   // external reference
    imgPlayerLogo = '';             // internal reference
    this.imgPlayerLogo = '';        // external reference
    pageAudio = 1;                  // internal current page index
    
    // ============= PUBLIC METHODS ===========================
    this.Initialize = function() {
        getShowDetails(pShowID);
        // --- audio ------------------------
        addAudioGetMoreLink();
        initAudioClickHandler();
        initBackToSummariesClickHandler();
        initBlogPostClickHandler();
        initCustomContentRequestHandler();
        initTabClickHandler();
        initVideoClickHandler();
    }

    this.getNextAudioPage = function() {
        var pageNum = pageAudio + 1;
        ShowAjaxIcon();
        $.ajax({
            type: "POST",
            url: "/ajax/showService.asmx/getPagedAudio",
            data: "{FolderID: " + AudioClipsFolderID + ", ClipPath: '" + AudioClipPath + "', PageNum: " + pageNum + ", PageSize: 50, RtmpPath: '" + AudioRtmpPath + "', ClipPrefixText: '" + AudioClipsPrefixText + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleAudioPagedResponse,
            error: AjaxFailed
        });
        pageAudio = pageAudio + 1;
    }   
    
    // ============= PRIVATE METHODS ========================

    //
    function addAudioGetMoreLink() {
        $('#audioArchives_cont').append('<a id="getMoreAudio" href="#" onclick="oShow.getNextAudioPage();return false;"><img src="/styles/images/moreAudio.png" alt="more" border="0" /></a>');
    }

    //
    function removeAudioGetMoreLink() {
        $('#getMoreAudio').remove();
    }

    // alert user if ajax request failed
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
        HideAjaxIcon();
    }

    function getAudio(audioId, clipPath) {
        ShowAjaxIcon();
        $.ajax({
            type: "POST",
            url: "/ajax/showService.asmx/getAudio",
            data: "{AudioId: '" + audioId + "', ClipPath: '" + clipPath + "', RtmpPath: '" + AudioRtmpPath + "', ClipPrefixText: '" + AudioClipsPrefixText + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleAudioResponse,
            error: AjaxFailed
        });
    }

    function getAudioIdFromUrl(audioUrl) {
        var audioParms = audioUrl.substring(audioUrl.search("&audio="));
        return audioParms.substring(audioParms.search("=") + 1);
    }

    function getBlogPost(BlogPostId) {
        ShowAjaxIcon();
        $.ajax({
            type: "POST",
            url: "/ajax/showService.asmx/getBlogPost",
            data: "{BlogPostId: '" + BlogPostId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleBlogPostResponse,
            error: AjaxFailed
        });
    }

    function getBlogPostIdFromUrl(BlogPostUrl) {
        var blogpostParms = BlogPostUrl.substring(BlogPostUrl.search("&blogpost="));
        return blogpostParms.substring(blogpostParms.search("=") + 1);
    }

    function getCustomContent(ContentId) {
        ShowAjaxIcon();
        $.ajax({
            type: "POST",
            url: "/ajax/showService.asmx/getCustomContent",
            data: "{ContentId: '" + ContentId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleCustomContentResponse,
            error: AjaxFailed
        });
    }

    function getCustomContentIdFromUrl(CustomContentUrl) {
        var contentParms = CustomContentUrl.substring(CustomContentUrl.search("&content="));
        return contentParms.substring(contentParms.search("=") + 1);
    }

    function getDayOfWeekName(dayofweek) {
        var DaysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
        return DaysOfWeek[dayofweek];
    }
    
    function getMonthName(month) {
        var MonthNames = ["January", "February", "March", "Arpil", "May", "June",
                          "July", "August", "September", "October", "November", "December"];
        return MonthNames[month];
    }

    function getShowDetails(ID) {
        $.ajax({
            type: "POST",
            url: "/ajax/showService.asmx/getShowDetails",
            data: "{ShowID: " + ID + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleShowDetailsResponse,
            error: AjaxFailed
        });
    }
    
    function getShowIdFromUrl(Url) {
        var idParms = Url.substring(Url.search("&id="));
        var idParmsPlus = idParms.substring(idParms.search("=") + 1);
        return idParmsPlus.replace(idParmsPlus.substring(idParmsPlus.search("&")),"");
    }

    function getVideo(videoId) {
        ShowAjaxIcon();
        $.ajax({
            type: "POST",
            url: "/ajax/showService.asmx/getVideo",
            data: "{VideoId: '" + videoId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleVideoResponse,
            error: AjaxFailed
        });
    }

    function getVideoIdFromUrl(videoUrl) {
        var videoParms = videoUrl.substring(videoUrl.search("&video="));
        return videoParms.substring(videoParms.search("=") + 1);
    }

    function HideAjaxIcon() {
        $("#ajaxIcon").html('');
    }

    function PlayAudio(result) {
        // setup playlist from ajax result and attach to player
        var FilenameWOExt = result.Filename.substr(0, result.Filename.lastIndexOf('.')) || result.Filename;
        var clipname = result.FileFormat + ':' + AudioClipsPrefixText + FilenameWOExt;
        var playlist = [
           { url: imgPlayerLogo, title: result.Title },
           { url: clipname, title: result.Title, img: false, netConnectionUrl: AudioRtmpPath }
        ];
           if ($f('player1').isLoaded()) {
               $f('player1').stop();
           }
        $f('player1').play(playlist);
        // update UI by removing currently playing video
        $('.clipPlaying').removeClass('clipPlaying');
        // find the loading clip and change it to playing clip
        $('.clipLoading').removeClass('clipLoading').addClass('clipPlaying');
        HideAjaxIcon();
    }

    function PlayLiveStream() {
        // setup playlist from ajax result and attach to player
        var playlist = [
        //{ url: 'afa', title: 'Testing' },
           {url: LiveStreamClipName, title: 'LIVE STREAM', netConnectionUrl: LiveStreamRtmpPath }
        ];
        $f('player1').play(playlist);
        // update UI by removing currently playing video
        $('.clipPlaying').removeClass('clipPlaying');
        // find the live clip and change it to playing clip
        $('.live_clip_container').addClass('clipPlaying');
        HideAjaxIcon();
    }

    function PlayVideo(result) {
        // setup playlist from ajax result and attach to player
        var playlist = '';
        if (result.VideoMimeType == 'video/mp4') {
            playlist = [
               { url: 'mp4:'+result.VideoFilename, 
                 title: result.VideoTitle, 
                 netConnectionUrl: 'rtmp://mediaserver3.afa.net/VideoBlog' }
            ];
        } else {
            playlist = [
               { url: result.VideoFilename,
                   title: result.VideoTitle,
                   netConnectionUrl: 'rtmp://mediaserver3.afa.net/VideoBlog'
               }
            ];
    }
        $f('player1').play(playlist);
        // update UI by removing currently playing video
        $('.clipPlaying').removeClass('clipPlaying');
        // find the loading clip and change it to playing clip
        $('.clipLoading').removeClass('clipLoading').addClass('clipPlaying');
        HideAjaxIcon();
    }

    function ShowAjaxIcon() {
        $("#ajaxIcon").html('<img src="/images/icons/showAjaxIcon.gif" alt="" />');
    }
    
    function ShowBlogPost(result) {
        var baseTabUrl = '/Radio/show.aspx?id=' + this.ShowID + '&tab=blog';
        var bpDate = new Date(result.BlogPostDate);

        $("#BlogPostSummaries").hide();

        var detailHtml = '<div class="BackToSummariesNav"><a href="' + baseTabUrl + '">BACK TO BLOG</a></div>';
        detailHtml += '<h2 class="section_h2">' + result.BlogPostTitle + '</h2>';
        detailHtml += '<div class="BlogPostDate">';
        detailHtml += getDayOfWeekName(bpDate.getDay()) + ', ';
        detailHtml += getMonthName(bpDate.getMonth()) + ' ' + bpDate.getDate() + ', ' + bpDate.getFullYear();
        detailHtml += '</div>';
        detailHtml += result.BlogPostHtml;
        $("#BlogPostDetail").html(detailHtml);

        $("#BlogPostDetail").show(300);

        initBackToSummariesClickHandler();
        HideAjaxIcon();
    }

    function ShowBlogPostList() {
        $("#BlogPostDetail").hide(100);
        $("#BlogPostSummaries").show(300);
    }

    function ShowContentDetail(result) {
        var baseTabUrl = '/Radio/show.aspx?id=' + this.ShowID + '&tab=custom';

        $("#CustomSummaries").hide();

        var detailHtml = '<div class="BackToSummariesNav"><a href="' + baseTabUrl + '">BACK TO LIST</a></div>';
        detailHtml += '<h2 class="section_h2">' + result.ContentTitle + '</h2>';
        detailHtml += result.ContentHtml;
        $("#CustomDetail").html(detailHtml);

        $("#CustomDetail").show(300);

        initBackToSummariesClickHandler();
        HideAjaxIcon();
    }

    function ShowContentList() {
        $("#CustomDetail").hide(100);
        $("#CustomSummaries").show(300);
    }

    // ------------- PRIVATE METHODS ( CLICK HANDLERS ) ---------------------
    function initAudioClickHandler() {
        $(".audioFile a").click(function(e) {
            e.preventDefault();
        });

        $(".audioFile").click(function(e) {
            e.preventDefault();
            var audioId = getAudioIdFromUrl($("a", this).attr("href"));
            $(this).addClass("clipLoading");
            getAudio(audioId, AudioClipPath);
        });
    }

    function initBackToSummariesClickHandler() {
        $(".BackToSummariesNav a").click(function(e) {
            e.preventDefault();
            var link = $(this).attr("href")
            var tabParms = link.substring(link.search("&tab="));
            var section = tabParms.substring(tabParms.search("=") + 1);
            var ShowId = getShowIdFromUrl(link);
            var FolderId = 2;
            switch (section) {
                case 'blog':
                    ShowBlogPostList();
                    break;
                case 'custom':
                    ShowContentList();
                    break;
            }
        });
    }
    
    function initBlogPostClickHandler() {
        $(".BlogPostList li a").click(function(e) {
            e.preventDefault();
            var BlogPostId = getBlogPostIdFromUrl($(this).attr("href"));
            getBlogPost(BlogPostId);
        });
    }
    
    function initCustomContentRequestHandler() {
        $(".CustomContentList li a").click(function(e) {
            e.preventDefault();
            var contentId = getCustomContentIdFromUrl($(this).attr("href"));
            getCustomContent(contentId);
        });
    }
    
    function initTabClickHandler() {
        $("#sectionTabs li a").click(function(e) {
            // override click handler
            e.preventDefault();
        });
            
        $("#sectionTabs li").click(function(e) {
            e.preventDefault();
            // get id of li and concat to string to get container name
            var contentContainerName = "#tabcontent-" + this.id;
            // deselect ALL tabs
            $("#sectionTabs li").each(function(i, listitem) {
                $(listitem).removeClass("selected");
            });
            // hide currently displayed container
            $(".selectedContainer").removeClass("selectedContainer").addClass("Container");
            // select clicked tab and show matching container
            $(this).addClass("selected");
            $(contentContainerName).removeClass("Container").addClass("selectedContainer");
        });
    }

    function initVideoClickHandler() {
        $(".clip_container a").click(function(e) {
            e.preventDefault();
        });

        $(".clip_container").click(function(e) {
            var videoId = getVideoIdFromUrl($("a", this).attr("href"));
            $(this).addClass("clipLoading");
            getVideo(videoId);
        });

        // handle live stream click
        $(".live_clip_container a").click(function(e) {
            e.preventDefault();
        });

        $(".live_clip_container").click(function(e) {
            PlayLiveStream();
        });
    }

    // ------------- PRIVATE METHODS ( AJAX HANDLERS ) ---------------------

    // handle ajax response to getAudio
    function handleAudioResponse(result) {
        if (result.d) {
            handleAudioResponse(result.d);
        } else {
            PlayAudio(result);
        }
    }

    // handle ajax response to getAudio
    function handleAudioPagedResponse(result) {
        if (result.d) {
            handleAudioPagedResponse(result.d);
        } else {
            $.each(result.Results, function(i, clip) {
                $('#audioFileList').append('<li class="audioFile"><a href="/Radio/show.aspx?id=' + ShowID + '&tab=audio&audio=' + clip.AudioID + '">' + clip.Title + ' - ' + clip.SubTitle + '</a></li>');
            });
            // attach click handlers for new audio items
            initAudioClickHandler();
            if (result.PageNum == result.TotalPages) {
                // last page, remove get more link
                removeAudioGetMoreLink();
            }
            HideAjaxIcon();
        }
    }

    // handle ajax response to getBlogPost
    function handleBlogPostResponse(result) {
        if (result.d) {
            handleBlogPostResponse(result.d);
        } else {
            ShowBlogPost(result);
        }
    }

    // handle ajax response to getCustomContent
    function handleCustomContentResponse(result) {
        if (result.d) {
            handleCustomContentResponse(result.d);
        } else {
            ShowContentDetail(result);
        }
    }

    // handle ajax response to getShowDetails
    function handleShowDetailsResponse(result) {
        if (result.d) {
            handleShowDetailsResponse(result.d);
        } else {
            AudioRtmpPath = result.AudioClipsRtmpPath;               // internal reference
            this.AudioRtmpPath = result.AudioClipsRtmpPath;          // external reference
            AudioClipPath = result.AudioClipsFilePath;               // internal reference
            this.AudioClipPath = result.AudioClipsFilePath;          // external reference
            AudioClipsFolderID = result.AudioClipsFolderID;          // internal reference
            this.AudioClipsFolderID = result.AudioClipsFolderID;     // external reference
            AudioClipsPrefixText = result.AudioClipsPrefixText;      // internal reference
            this.AudioClipsPrefixText = result.AudioClipsPrefixText; // external reference
            LiveStreamRtmpPath = result.LiveStreamRtmpPath;          // internal reference
            this.LiveStreamRtmpPath = result.LiveStreamRtmpPath;     // external reference
            LiveStreamClipName = result.LiveStreamClipName;          // internal reference
            this.LiveStreamClipName = result.LiveStreamClipName;     // external reference

            imgPlayerLogo = result.imgPlayerLogo;                    // internal reference
            this.imgPlayerLogo = result.imgPlayerLogo;               // external reference
        }
        

    }

    // handle ajax response to getVideo
    function handleVideoResponse(result) {
        if (result.d) {
            handleVideoResponse(result.d);
        } else {
            PlayVideo(result);
        }
    }

}

Show.prototype.ShowID = 0;

