//Browser-based view script
var uniqueID;
var playerAudioImage = "images/playerAudioImage.jpg";
var playerNotAvailableImage = "images/playerNotAvailableImage.jpg";

function initView() {
    //add setData calls for major UI elements
    $.extend($("#featured")[0], {
        setData: function(data) {
            $("#featured").data('sermons', data);
            setFeaturedSermon(data[0]);
            setSermonTiles("#featuredVideos", data, $("#featured").data('format'), $("#featured").data('index'), $("#featured").data('limit'), $("#featured").data('sectionsize'));
        }
    });

    $.extend($("#searchResult")[0], {
        setData: function(data, pageFunc) {
            setPages('searchResultPages', data[0].PageCount, data[0].CurrentPage, pageFunc);
            setSearchResults(data[0].Results, data[0].Total);
            showSearchResult(true);
        }
    });

    $.extend($("#ministry")[0], {
        setData: function(data, pageFunc) {
            setPages('ministryListPages', data[0].PageCount, data[0].CurrentPage, pageFunc, 1);
            setMinistryList(data[0].Results, data[0].Letter);
        }
    });

    $.extend($("#viewed")[0], {
        setData: function(data, pageFunc) {
            setPages('mostviewedPages', data[0].PageCount, data[0].CurrentPage, pageFunc, $("#mostviewedPages").hasClass('paginationSmall') ? 0 : 1);
            setSermonTiles('#viewed .videos', data[0].Results, $("#viewed").data('format'), $("#viewed").data('index'), $("#viewed").data('limit'), $("#viewed").data('sectionsize'));
        }
    });

    $.extend($("#recent")[0], {
        setData: function(data, pageFunc) {
            setPages('mostrecentPages', data[0].PageCount, data[0].CurrentPage, pageFunc, 1);
            setSermonTiles('#recent .videos', data[0].Results, 0, 0);
        }
    });

    $.extend($("#ministryrecent")[0], {
        setData: function(data, pageFunc) {
            setPages('mostrecentPages', data[0].PageCount, data[0].CurrentPage, pageFunc);
            setSermonTiles('#ministryrecent .videos', data[0].Results, 1, 0, undefined, 1);
            $("#playerVideoCount").html(data[0].Total);
        }
    });
    
    $.extend($("#main")[0], {
        setData: function(data) {
            $("#main").data('sermon', data[0]);
            setSermonPlayer(data[0]);
            model.GetData(["TruthcastingSermonNoteSelect", data[0].SermonID], function(data) { $("#attachments")[0].setData(data); });
        }
    });
    
    $.extend($("#attachments")[0], {
        setData: function(data) {
            $("#attachments").data('list', data);
            setSermonAttachments(data);
        }
    });

    $.extend($("#channels")[0], {
        setData: function(data, pageFunc) {
            setPages('channelPages', data[0].PageCount, data[0].CurrentPage, pageFunc);
            setSubChannelTiles('#channels .subchannels', data[0].Results);
            $("#playerChannelCount").html(data[0].Total);
        }
    });

    $.extend($("#channelvideos")[0], {
        setData: function(data, pageFunc) {
            setPages('channelvideosPages', data[0].PageCount, data[0].CurrentPage, pageFunc, 1);
            setSermonTiles('#channelvideos .videos', data[0].Results, 1, 0);
            model.setMinistryID(data[0].ChannelID);
            $("#ChannelName").html(data[0].ClientName);
            $("#SubChannelName").html(data[0].ChannelName);
        }
    });
}

function isIPad() {
    return (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null);
}

function isPlayer()
{return (location.href.indexOf('/player.aspx') > 0);}

function mostviewed(p) {
    location.hash = "#mostviewed_page=" + ((p!=undefined) ? p : lastmostviewed_page);
}

function mostrecent(p) {
    location.hash = "#mostrecent_page=" + ((p != undefined) ? p : lastmostrecent_page);
}

function setFeaturedSermon(sermon) {
    $("#featureMovie").click(function(){showSermon(sermon.SermonID);});
    $("#featureMovieThumb").attr('src', sermon.VideoImage);
    $("#featuredChurchName").html(sermon.ClientName);
    $("#featuredSermonTitle").html(sermon.SermonTitle);
    $("#featuredSermonSpeaker").html(sermon.SpeakerName);
    $("#featuredSermonDate").html(dateFormat(sermon.GivenDate, "mm/dd/yyyy"));
    $("#featuredSermonViews").html(sermon.TotalViews + " Views");
}

function setSermonPlayer(sermon) {
    if (sermon != undefined) {
        model.setMinistryID( sermon.ChannelID );
        model.setSermonID( sermon.SermonID );
        //model.setSubchannelID( sermon.SubChannelID );
        if (isIPad()) {
            setSermonHTML5(sermon);
        } else {
            setSermonFlash(sermon);
        }
        $("#churchLogo img").attr('src', sermon.ChannelImage);
        $("#churchLogo a").attr('href', sermon.HomeLink);
        $("#playerClientName").html(sermon.ClientName);
        $("#main h1").html(sermon.SermonTitle);
        $("#main h3").html(sermon.SpeakerName);
        $("#playerTitle").html(sermon.SermonTitle);
        $("#playerSpeaker").html(sermon.SpeakerName);
        $("#playerDescription").html(sermon.SermonDescription);
        $("#playerTags").html(sermon.SearchKeywords);
        $("#playerDate").html(dateFormat(sermon.GivenDate, "mm/dd/yyyy"));
        $("#playerTopic").html(sermon.SermonTopic);
        $("#playerViews").html(sermon.TotalViews);
        document.title = "TruthCasting - " + sermon.ClientName + " - " + sermon.SermonTitle;
        if (sermon.CanBeDownloaded && sermon.AudioURL) {
            $("#playerAudioDownload").attr('href', sermon.AudioURL.replace("http://media.truthcasting.com/", "http://media.truthcasting.com/download.aspx?f="));
            $("#playerAudioDownload").parent().show();
        } else {
            $("#playerAudioDownload").attr('href', '');
            $("#playerAudioDownload").parent().hide();
        }
        if (sermon.CanBeSold) {
            $("#purchaselink").attr('href', "https://www.truthcasting.com/shopping/default.asp?ID=" + sermon.SermonID);
            $("#purchaselink").parent().show();
        } else {
            $("#purchaselink").attr('href', '');
            $("#purchaselink").parent().hide();
        }
        $("#embedlink").attr('href', "javascript:embed(this," + sermon.SermonID + ")");
        $("#fb_like_iframe").attr('src', "http://www.facebook.com/plugins/like.php?layout=button_count&locale=en_US&node_type=link&show_faces=false&width=75&href=" + escape(sermon.PermaLink));
    } else {
        //bad sermon id or something
        location.replace('default.aspx');
    }
}

function setSermonFlash(sermon) {
    var pvp = $("#PVP").get(0);
    if (!playerReady || pvp==null || pvp.setProperties===undefined) {
        return setTimeout(function() { setSermonFlash(sermon) }, 100);
    }
    uniqueID = "w"+Math.random()*100000;
    var props;
    var ad_url = (sermon.CanUsePlayer==1) ? null : "http://ads.pursuantgroup.com/OpenX/www/delivery/avw.php?zoneid=2&n=a3acdf89&cb=" + uniqueID;
    if (sermon.IsVideo) {
        props =
        {
            thumbFrame: { source: sermon.VideoImage },
            mediaIsAudio: false,
            videoSource: sermon.VideoURL,
            audioSource: null,
            preloaderVideo: { autoPlay: false, source: ad_url },
            startPlayback: { visible: true },
            allcontrols: { visible: true }
        };
    } else if (sermon.AudioURL!=null){
        props =
        {
            thumbFrame: { source: playerAudioImage },
            mediaIsAudio: true,
            videoSource: null,
            audioSource: sermon.AudioURL,
            preloaderVideo: { autoPlay: false, source: ad_url },
            startPlayback: { visible: true },
            allcontrols: { visible: true }
        };
    } else {
        props =
        {
            thumbFrame: { source: playerNotAvailableImage },
            mediaIsAudio: true,
            videoSource: null,
            audioSource: null,
            preloaderVideo: { autoPlay: false },
            startPlayback: { visible: false },
            allcontrols: { visible: false }
        };
    }
    playerStop();
    pvp.setProperties(props);
}

function setSermonHTML5(sermon) {
    var pvp = $("#html5placeholder");
    uniqueID = "w" + Math.random() * 100000;
    var props;
    var format;
    var ad_url = "http://ads.pursuantgroup.com/OpenX/www/delivery/avw.php?zoneid=2&n=a3acdf89&cb=" + uniqueID;
    if (sermon.IsVideo) {
        format = '<video id="html5player" height="360" width="640" poster="{thumbFramesource}" controls="controls" src="{preloaderVideosource}"></video>'; //type="video/mp4"
        props =
        {
            thumbFramesource: sermon.VideoImage,
            mediaIsAudio: false,
            source: sermon.IPodVideoURL,
            preloaderVideosource: ((sermon.CanUsePlayer==1) ? sermon.IPodVideoURL : ad_url)
        };
    } else if (sermon.AudioURL != null) {
        format = '<audio id="html5player" height="360" width="640" controls="controls" poster="{thumbFramesource}" src="{source}"></audio>';
        props =
        {
            thumbFramesource: playerAudioImage,
            mediaIsAudio: true,
            source: sermon.AudioURL,
            preloaderVideosource: ((sermon.CanUsePlayer==1) ? sermon.AudioURL : ad_url)
        };
    } else {
        format = '<img id="html5player" height="360" width="640" src="{thumbFramesource}"></img>';
        props =
        {
            thumbFramesource: playerNotAvailableImage
        };
    }
    playerStop();
    pvp.html(model.tokenize(format, props));
    if (props.source){
        model.viewedSource = "iPad";
        var video = $("#html5player").get(0);
        //for displaying ads...
        if ((sermon.CanUsePlayer!=1) && sermon.IsVideo) {
            video.addEventListener('ended', function() { video.src = props.source; video.controls = true; video.load(); video.play(); }, false);
        }
        video.addEventListener('progress',function(){ pvpPlayback(video.buffered.end(0) / video.duration); }, false);
    }
}

function playerStop() {
    try{
    var pvp = $("#PVP").get(0);
    pvp.reset();
    }catch(e){}
    try{
    var video = $("#html5player").get(0);
    video.pause();
    }catch(e){}
}

function setSermonAttachments(attachments) {
    $("#attachments").html("Attachments (" + ((attachments===undefined) ? 0 : attachments.length) + ")");
    var list = [];
    var layout = '<li class="truncatetext"><a class="truncatetext" href="{FileURL}" target="_blank">{DisplayName}</a></li>';
    list.push('<ul>');
    if (attachments != undefined) {
        for (i = 0; i < attachments.length; i++) {
            list.push(model.tokenize(layout, attachments[i]));
        }
    }
    list.push('</ul>');
    $("#attachmentlist").html(list.join(""));
}

function setSermonTiles(selector, sermons, format, i, limit, sectionsize) {
    if (limit === undefined) { limit = sermons.length; }
    if (sectionsize === undefined) { sectionsize = 2; }
    var tiles = [];
    var sections = [];
    while (i < sermons.length && i < limit) {
        tiles.push(renderSermonTile(sermons[i], format));
        if (tiles.length == sectionsize) {
            sections.push(renderSermonSection(tiles.join("")));
            tiles = [];
        }
        i++;
    }
    if (tiles.length > 0) { sections.push(renderSermonSection(tiles.join(""))); }
    $(selector).html(sections.join(""));
}

function renderSermonTile(sermon, format) {
    var layout;
    if (format == 0) {
        layout = '<div class="movietile" onclick="location.hash=\'#showSermon={SermonID}\'"><div class="screenshot"><img src="{VideoImage}" title="{SermonTitle}" onerror="missingImage(this)" class="smallThumb" /></div><div class="movieInfo"><h2>{ClientName}</h2><p>{SermonTitle}</p><dl class="additionalInfo"><div class="date">{GivenDate}</div><div class="divider">|</div><div class="views">{TotalViews} Views</div></dl></div></div>';
    } else {
        layout = '<div class="movietile" onclick="location.hash=\'#showSermon={SermonID}\'"><div class="screenshot"><img src="{VideoImage}" title="{SermonTitle}" onerror="missingImage(this)" class="smallThumb" /></div><div class="movieInfo"><h2>{SermonTitle}</h2><p>{SpeakerName}</p><dl class="additionalInfo"><div class="date">{GivenDate}</div><div class="divider">|</div><div class="views">{TotalViews} Views</div></dl></div></div>';
    }
    return model.tokenize(layout, sermon);
}

function renderSermonSection(tiles) {
    return '<div class="section">' + tiles + '</div>';
}

function setSubChannelTiles(selector, channels, limit) {
    if (limit === undefined) { limit = channels.length; }
    var tiles = [];
    var i = 0;
    while (i < channels.length && i < limit) {
        tiles.push(renderChannelTile(channels[i]));
        i++;
    }
    $(selector).html(tiles.join(""));
}

function renderChannelTile(channel) {
    var layout = '<div class="channeltile" onclick="location.hash=\'#showSubChannel={ID}\'"><div class="channelicon"><img src="{ChannelIconURL}" title="{Name}" onerror="missingImage(this)" class="channelimage" /></div><div class="movieInfo"><h1 class="title">{Name}</h1><p>{Description}</p></div></div>';
    return model.tokenize(layout, channel);
}

function setPages(control, nPages, CurrentPage, pageFunc, prevnextstyle) {
    var next_on, next_off, prev_on, prev_off;
    if (prevnextstyle == 1) {
        next_on = '<img src="images/arrow-right.png" title="Next" />';
        next_off= '<img src="images/arrow-right.png" />';
        prev_on = '<img src="images/arrow-left.png" title="Previous" />';
        prev_off= '<img src="images/arrow-left.png" />';
    } else {
        next_on = 'Next';
        next_off= 'Next';
        prev_on = 'Prev';
        prev_off= 'Prev';
    }
    var list = [];
    var start = 1;
    var end = nPages;
    start = Math.floor(CurrentPage / 10) * ((nPages > 11) ? 10 : 0);
    start = (start > 0) ? start : 1;
    start = (start > CurrentPage) ? CurrentPage : start;
    end = start + 9;
    end = (end > nPages) ? nPages : end;
    var ellipsis = (nPages > 11) && (nPages > end);

    list.push('<ul>');
    if (nPages > 1) {
        list.push('<li class="link">' + ((CurrentPage > 1) ? '<a href="javascript:' + pageFunc + '(' + (CurrentPage - 1) + ')">'+prev_on+'</a>' : prev_off) + '</li>');
        if (!ellipsis && (nPages > 11)) {
            list.push('<li><a href="javascript:' + pageFunc + '(' + (start - 1) + ')" style="text-decoration:none;">...</a></li>');
        }
        for (i = start; i <= end; i++) {
            if (i > start) { list.push('<li>&nbsp;</li>'); }
            var inner = (i == CurrentPage) ? '{p}' : '<a href="javascript:' + pageFunc + '({p})">{p}</a>';
            list.push(model.tokenize('<li' + (i == CurrentPage ? ' class="selected"' : '') + '>' + inner + '</li>', { p: i }));
        }
        if (ellipsis) {
            list.push('<li>&nbsp;</li>');
            list.push('<li><a href="javascript:' + pageFunc + '(' + i + ')" style="text-decoration:none;">...</a></li>');
        }
        //list.push('<li>&nbsp;</li>');
        list.push('<li class="link">' + ((CurrentPage < nPages) ? '<a href="javascript:' + pageFunc + '(' + (CurrentPage + 1) + ')">'+next_on+'</a>' : next_off) + '</li>');
    }
    list.push('</ul>');
    $("#" + control).html(list.join(""));
}

var sermonSearchFormat = '<a href="#showSermon={SermonID}">{SermonTitle} - {SpeakerName}</a>';
var speakerSearchFormat = '<a href="#showChannel={ChannelID}">{SpeakerName} - {ClientName}</a>';
var ministrySearchFormat = '<a href="#showChannel={ID}">{ClientName}</a>';

function all_search(input) {
    searchResultFormat = '?';
    setSearchResults = function(results, total) { setSearchResultsAll(results, total); };
    allSearch.search(input);
}

function ministries_search(input) {
    searchResultFormat = ministrySearchFormat;
    setSearchResults = function(results, total) { setSearchResultsStd(results, total); };
    ministrySearch.search(input);
}

function speaker_search(input) {
    searchResultFormat = speakerSearchFormat;
    setSearchResults = function(results, total) { setSearchResultsStd(results, total); };
    speakerSearch.search(input);
}

function keyword_search(input) {
    searchResultFormat = sermonSearchFormat;
    setSearchResults = function(results, total) { setSearchResultsStd(results, total); };
    keywordSearch.search(input);
}

var searchResultFormat = '';
function setSearchResultsStd(results, total) {
    var list = [];
    if (total > 0 && results != null) {
        var resultStr = (total > 200 ? 'Over 200' : total) + (total == 1 ? ' result found' : ' results found');
        renderSearchResults(resultStr, results, searchResultFormat, 0, 'void(0)', list);
    } else {
        list.push('<h2>No results matched</h2>');
    }
    $("#searchResultsList").html(list.join(""));
}
function setSearchResultsAll(results, total) {
    var list = [];
    if (total > 0 && results != null) {
        renderSearchResults('Ministry', results[0].Value.Results, ministrySearchFormat, results[0].Value.Total, "showAll('#search_ministries')", list);
        renderSearchResults('Speaker', results[1].Value.Results, speakerSearchFormat, results[1].Value.Total, "showAll('#search_speakers')", list);
        renderSearchResults('Sermon', results[2].Value.Results, sermonSearchFormat, results[2].Value.Total, "showAll('#search_keyword')", list);
    } else {
        list.push('<h2>No results matched</h2>');
    }
    $("#searchResultsList").html(list.join(""));
}
function renderSearchResults( title, results, format, total, totalFunc, list) {
    list.push('<h2>'+title+'</h2>');
    list.push('<ul>');
    if (results.length > 0) {
        for (i = 0; i < results.length; i++) {
            list.push(model.tokenize('<li>' + format + '</li>', results[i]));
        }
        var totals = '<a href="javascript:' + totalFunc + '">See all ' + total + ' results</a>';
        list.push('<li class="rightalign">'+((total > 5)?totals:'')+'</li>');
    } else {
        list.push('<li class="rightalign">No results found</li>');
    }
    list.push('</ul>');
}
function showAll(input, tab) {
    $(input).val($('#search_all').val());
    $(input).trigger('keyup');
}

var ministriesLast;
function getMinistriesList(letter, page) {
    if (ministriesLast != letter + page) {
        ministriesLast = letter + page;
        model.GetData(["TruthcastingMinistryList", letter, 50, page ? page : 1], function(channels) { $("#ministry")[0].setData(channels, 'getMinistriesListPage'); })
    }
}

function getMinistriesListPage(page) {
    getMinistriesList($(".alphabet .selected:first").text(), page);
}

function setMinistryList(results, letter) {
    var list = [[], []];
    var l = 0;
    for (var i in results) {
        if ((l == 0) && (i >= results.length / 2)) {
            l = 1;
        }
        list[l].push(model.tokenize('<li><a href="player.aspx#showChannel={ID}">{ClientName}</a></li>', results[i]));
    }
    $(".churchList .hint").css('display', 'none');
    $(".List:first").html('<ul>' + list[0].join("") + '</ul>');
    $(".List:last").html('<ul>' + list[1].join("") + '</ul>');
    $(".alphabet .selected").removeClass("selected");
    $(".alphabet li:contains('" + letter.toUpperCase() + "')").addClass("selected");
}

var lastmostviewed_page = 0;
var lastmostviewed_ministry;
function mostviewed_page(p) {
    p = p > 0 ? p : 1;
    if (lastmostviewed_page != p || lastmostviewed_ministry!=model.ministryID) {
        lastmostviewed_page = p;
        lastmostviewed_ministry = model.ministryID;
        model.GetData(["TruthcastingMostViewed", $("#viewed").data('limit'), p, model.ministryID], 
            function(data) { $("#viewed")[0].setData(data, $("#viewed").data('pageFunc')); });
    }
}

var lastmostrecent_page = 0;
function mostrecent_page(p) {
    p = p > 0 ? p : 1;
    if (lastmostrecent_page != p) {
        lastmostrecent_page = p;
        model.GetData(["TruthcastingMostRecent", 10, p], 
            function(data) { $("#recent")[0].setData(data, 'mostrecent'); });
    }
}

var lastmostrecent_ministry = 0;
function ministry_mostrecent_page(p) {
    p = p > 0 ? p : 1;
    if (lastmostrecent_page != p || lastmostrecent_ministry != model.ministryID) {
        lastmostrecent_page = p;
        lastmostrecent_ministry = model.ministryID;
        model.GetData(["TruthcastingMinistryMostRecent", 5, p, model.ministryID], 
            function(data) { $("#ministryrecent")[0].setData(data, 'ministry_mostrecent_page'); });
    }
}

var lastsubchannels_page = 0;
var lastsubchannels_ministry = 0;
function showSubChannels(p) {
    p = p > 0 ? p : 1;
    if (lastsubchannels_page != p || lastsubchannels_ministry != model.ministryID) {
        lastsubchannels_page = p;
        lastsubchannels_ministry = model.ministryID;
        model.GetData(["TruthcastingMinistrySubChannels", 5, p, model.ministryID],
            function(channels) { $("#channels")[0].setData(channels, 'showSubChannels'); });
    }
}

var lastscvideos_page = 0;
var lastscvideos_channel = 0;
function showSubChannelVideos(p) {
    p = p > 0 ? p : 1;
    if (lastscvideos_page != p || lastscvideos_channel != model.subChannelID) {
        lastscvideos_page = p;
        lastscvideos_channel = model.subChannelID;
        model.GetData(["TruthcastingSubChannelPlayer", 10, p, model.subChannelID],
            function(sermons) { $("#channelvideos")[0].setData(sermons, 'showSubChannelVideos'); });
    }
}

function showLogin() {
    if (window.location.toString().indexOf('login.aspx') > 0) {return;}
    var dialog = $('#logindialog');
    var show = dialog.height() < 130;

    dialog.animate({ height: (show ? 130 : 0) }, 'fast',
        function() {
            if (show) { $('#username').focus(); }
            dialog.css("display", show ? "block" : "none");
        });
}

function embed(link, id) {
//    Shadowbox.open({
//        content: 'embed.aspx?ID='+id,
//        player: "iframe",
//        height: 500,
//        width: 670,
//        modal: true,
//        overlayOpacity: 0.3
//    });

    window.open('embed.aspx?ID=' + id, "truthcastingembed", "status=0,toolbar=0,menubar=0,width=670,height=560"); 
}

showError = function(error){
    Shadowbox.open({
        content: '<div class="errorDialog">'+error+'</div>',
        player: "html",
        height: 480,
        width: 640,
        modal: true,
        overlayOpacity: 0.3,
        showClose: true
    });
}
