<%
"use strict";

import "/js/utility.js"
import "/tv/js/constants.js"
import "/tv/js/tvutil.qjs"

    var pageLoadStartTime = new Date();

    var myth  = new Myth();
    var guide = new Guide();
    var dvr   = new Dvr();
    var channel = new Channel();

    var StartIndex = 0;
    if (getIntegerArg("Start"))
        StartIndex = getIntegerArg("Start");

    var StartTime;
    if (getArg("StartTime"))
        StartTime = myth.ParseISODateString(getArg("StartTime"));

    if (!isValidObject(StartTime))
        StartTime = new Date();

    var EndTime = null; // Javascript sucks
    if (getArg("EndTime"))
        EndTime = myth.ParseISODateString(getArg("EndTime"));

    if (!isValidObject(EndTime))
    {
        EndTime = new Date();
        EndTime.setMonth(StartTime.getMonth() + 1); // Javascript sucks
    }

    var ChanId = 0;
    if (getIntegerArg("ChanId"))
        ChanId = getIntegerArg("ChanId");

    var Filter = "";
    if (getArg("Filter"))
        Filter = getArg("Filter");

    var TitleFilter = "";
    if (getArg("TitleFilter"))
        TitleFilter = getArg("TitleFilter");

    var CategoryFilter = "";
    if (getArg("CategoryFilter"))
        CategoryFilter = getArg("CategoryFilter");

    var PersonFilter = "";
    if (getArg("PersonFilter"))
        PersonFilter = getArg("PersonFilter");

    var KeywordFilter = "";
    if (getArg("KeywordFilter"))
        KeywordFilter = getArg("KeywordFilter");

    var OnlyNew = 0;
    if (getBoolArg("OnlyNew"))
        OnlyNew = getBoolArg("OnlyNew");

    var Sort = "";
    if (getArg("Sort"))
        Sort = getArg("Sort");

    var Descending = 0;
    if (getBoolArg("Descending"))
        Descending = getBoolArg("Descending");

    var listOnly = 0;
    if (getBoolArg("ListOnly"))
        listOnly = 1;

    var Count = 30;
    var Details = 1;
    var progLoadTimeStart = new Date();
    var Channels = channel.GetChannelInfoList(0,0,0,1).ChannelInfos;
    var programList = Array();
    var programs = Array();

    // If no arguments were supplied then show the 'no matches' message
    if (getArgCount() > 0)
    {
        programList = guide.GetProgramList(StartIndex, Count,
                                           StartTime, EndTime, ChanId,
                                           TitleFilter, CategoryFilter,
                                           PersonFilter, KeywordFilter,
                                           OnlyNew, Details,
                                           Sort, Descending);
        programs = programList.Programs;
    }
    var progLoadTimeEnd = new Date();
    var nextStartIndex = (StartIndex + Count);
    if (nextStartIndex >= programList.TotalAvailable)
        nextStartIndex = 0;

    var matchString = qsTr("No Matches");
    if (programList.TotalAvailable)
    {
        var matchStart = StartIndex+1;
        var matchTotal = programList.TotalAvailable;
        var matchCount = ((StartIndex + Count) <= matchTotal) ? (StartIndex + Count) : matchTotal;
        matchString = formatStr(qsTr("%1-%2 of %3 Matches"), matchStart, matchCount, matchTotal);
    }
%>

<% if (!listOnly) {%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/3rdParty/jquery/jqueryUI/css/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/css/site.css">
<link rel="stylesheet" type="text/css" href="/tv/css/programsearch.css">
<link rel="stylesheet" type="text/css" href="/tv/css/common.css">
<link rel="stylesheet" type="text/css" href="/tv/css/category_colors.css">
<script type="text/javascript" src="/3rdParty/jquery/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="/3rdParty/jquery/jqueryUI/js/jquery-ui-1.10.3.js"></script>
<script src="/3rdParty/jquery/jqueryJScroll/jquery.jscroll.js"></script>
<script src="/js/utility.js"></script> <!-- ECMA not JS -->
<script src="/js/util.qjs"></script>
<script src="/tv/js/common.js"></script>
<script src="/tv/js/programsearch.js"></script>
</head>
<body>

<div style="border:1px #CC0000 solid;background-color: rgba(102, 0, 0, 0.7);padding:7px;margin:5px;text-align:center;">
    This feature is in beta and is missing some functionality. Please report any bugs you encounter ...
</div>

<!-- Popup Option Menu -->
<!-- To avoid the need to define multiple overlapping menus, we use JS+CSS as
     an indirect if/else. It might seem convoluted but the alternatives are
     generating this bit of HTML client side with JS (bad), generating it server
     side (harder to maintain/template) or keeping in together inline with the
     other related html, with as little non-html markup as possible -->
<div id="optMenu" class="contextMenu" style="display:none;">
    <div class="button scheduleMenu" onClick="MythCommon.RecordProgram(gChanID, gStartTime, 'Single Record')">
        <%=qsTr("Record this showing")%>
    </div>
    <div class="button scheduleMenu" onClick="MythCommon.RecordProgram(gChanID, gStartTime, 'Record All')">
        <%=qsTr("Record all showings")%>
    </div>
    <div class="button scheduleMenu" onClick="MythCommon.RecordProgram(gChanID, gStartTime, 'Record One')">
        <%=qsTr("Record one showing")%>
    </div>
    <div class="button scheduleMenu" onClick="MythCommon.RecordProgram(gChanID, gStartTime, 'Record All (Channel)')">
        <%=qsTr("Record all showings (this channel)")%>
    </div>
    <div class="button delSchedMenu" onClick="dontRecord(gChanID, gStartTime)">
        <%=qsTr("Don't Record")%>
    </div>
    <div class="button delSchedMenu" onClick="neverRecord(gChanID, gStartTime)">
        <%=qsTr("Never Record")%>
    </div>
    <div class="button delSchedMenu" onClick="deleteRecRule(gChanID, gStartTime)">
        <%=qsTr("Delete Recording Rule")%>
    </div>
    <div class="button normalMenu" onClick="loadScheduler('upcoming', gChanID, gStartTime)">
        <%=qsTr("Edit recording rule")%>
    </div>
</div>

<!-- Popup Program Details Box -->
<div id="programDetails" class="programExDetail" style="display:none;">
</div>

<!-- Filter Options -->
<div id="filterType">
    <ul>
        <li><a href="#titleFilterGroup"><%=qsTr("Title")%></a></li>
        <li><a href="#channelFilterGroup"><%=qsTr("Channel")%></a></li>
        <li><a href="#personFilterGroup"><%=qsTr("People")%></a></li>
        <li><a href="#categoryFilterGroup"><%=qsTr("Category")%></a></li>
        <li><a href="#keywordFilterGroup"><%=qsTr("Keyword")%></a></li>
    </ul>
    <form>
    <fieldset id="titleFilterGroup" disabled>
        <label for="TitleFilter"><%=qsTr("Title")%>:
            <input type="text" list="titleList" id="TitleFilter" name="TitleFilter" onChange="MythProgramSearch.SubmitFilterForm(this.form);">
            <datalist id="titleList">
            <%
                StoredSearches = guide.GetStoredSearches("title");
                for (var listIdx = 0; listIdx < StoredSearches.length; listIdx++)
                {
            %>
                <option <% if (TitleFilter == StoredSearches[listIdx]) {%>selected<%}%>><%=StoredSearches[listIdx]%></option>
            <%
                }
            %>
            </datalist>
        </label>
        <input type="button" id="TitleSearch" name="TitleSearch" value="<%=qsTr("Search")%>" onClick="MythProgramSearch.SubmitFilterForm(this.form);" />
    </fieldset>
    <fieldset id="channelFilterGroup" disabled>
        <label for="ChanId"><%=qsTr("Channel")%>:
            <select id="ChanId" name="ChanId" onChange="MythProgramSearch.SubmitFilterForm(this.form);">
                <!-- <option value="0"><%=qsTr("All")%></option> -->
            <%
                for (var listIdx = 0; listIdx < Channels.length; listIdx++)
                {
            %>
                <option value="<%=Channels[listIdx].ChanId%>" <% if (ChanId == Channels[listIdx].ChanId) {%>selected<%}%>><%=Channels[listIdx].ChannelName%></option>
            <%
                }
            %>
            </select>
        </label>
        <input type="button" id="ChannelSearch" name="ChannelSearch" value="<%=qsTr("Search")%>" onClick="MythProgramSearch.SubmitFilterForm(this.form);" />
    </fieldset>
    <fieldset id="personFilterGroup" disabled>
        <label for="PersonFilter"><%=qsTr("Person")%>:
            <input type="text" list="peopleList" id="PersonFilter" name="PersonFilter" onChange="MythProgramSearch.SubmitFilterForm(this.form);">
            <datalist id="peopleList">
            <%
                var StoredSearches = guide.GetStoredSearches("people");
                for (var listIdx = 0; listIdx < StoredSearches.length; listIdx++)
                {
            %>
                <option <% if (PersonFilter == StoredSearches[listIdx]) {%>selected<%}%>><%=StoredSearches[listIdx]%></option>
            <%
                }
            %>
            </datalist>
        </label>
        <input type="button" id="PersonSearch" name="PersonSearch" value="<%=qsTr("Search")%>" onClick="MythProgramSearch.SubmitFilterForm(this.form);" />
    </fieldset>
    <fieldset id="categoryFilterGroup" disabled>
        <label for="CategoryFilter"><%=qsTr("Category")%>:
            <select id="CategoryFilter" name="CategoryFilter" onChange="MythProgramSearch.SubmitFilterForm(this.form);">
            <%
                var Categories = guide.GetCategoryList();
                for (var listIdx = 0; listIdx < Categories.length; listIdx++)
                {
            %>
                <option <% if (CategoryFilter == Categories[listIdx]) {%>selected<%}%>><%=Categories[listIdx]%></option>
            <%
                }
            %>
            </select>
            <input type="button" id="CategorySearch" name="CategorySearch" value="<%=qsTr("Search")%>" onClick="MythProgramSearch.SubmitFilterForm(this.form);" />
        </label>
    </fieldset>
    <fieldset id="keywordFilterGroup" disabled>
        <label for="KeywordFilter"><%=qsTr("Keyword")%>:
            <input type="text" list="keywordList"  id="KeywordFilter" name="KeywordFilter" onChange="MythProgramSearch.SubmitFilterForm(this.form);">
            <datalist id="keywordList">
            <%
                StoredSearches = guide.GetStoredSearches("keyword");
                for (var listIdx = 0; listIdx < StoredSearches.length; listIdx++)
                {
            %>
                <option <% if (KeywordFilter == StoredSearches[listIdx]) {%>selected<%}%>><%=StoredSearches[listIdx]%></option>
            <%
                }
            %>
            </datalist>
        </label>
        <input type="button" id="KeywordSearch" name="KeywordSearch" value="<%=qsTr("Search")%>" onClick="MythProgramSearch.SubmitFilterForm(this.form);" />
    </fieldset>
    <fieldset id="optionGroup">
        <label for="Sort"><%=qsTr("Sort")%>:
            <select id="Sort" name="Sort" onChange="MythProgramSearch.SubmitFilterForm(this.form);">
                <option value="starttime" <% if (Sort == "starttime") {%>selected<%}%>><%=qsTr("Start Time")%></option>
                <option value="channel" <% if (Sort == "channel") {%>selected<%}%>><%=qsTr("Channel")%></option>
                <option value="title" <% if (Sort == "title") {%>selected<%}%>><%=qsTr("Title")%></option>
                <option value="duration" <% if (Sort == "duration") {%>selected<%}%>><%=qsTr("Duration")%></option>
            </select>
        </label>
        <input type="hidden" name="ListOnly" value="1" />
    </fieldset>
    </form>
</div>

<div id="programList-container" style="overflow:hidden;clear:both;width:100%;">
<div id="programList" class="programList jscroll">

<%} // End of the header %>
 
<div class="topBar">
    <%=matchString%>
</div>

<%
// The nothing to display message
if (!isValidObject(programs) || programs.length === 0)
{
%>
    <div id="noProgramsRow" class="noProgramsRow">
        <%=qsTr("There are no matching programs.")%>
    </div>
<%
}

var listIdx = 0;
while (listIdx < programs.length)
{
    program = programs[listIdx];
    channel = program.Channel;

    // Deal with any duplicates
    listIdx++;
    var alternateShowings = Array();
    while (listIdx < programs.length)
    {
        nextProgram = programs[listIdx];

        // The next program in the list is a match for the current program
        if ((nextProgram.ProgramId.length > 0 &&
             nextProgram.ProgramId == program.ProgramId) ||
            (nextProgram.Title == program.Title &&
             nextProgram.SubTitle == program.SubTitle))
        {
            // Same program, channel and starttime, duplicate, completely ignore
            if (nextProgram.CallSign == channel.CallSign &&
                nextProgram.StartTime == program.StartTime)
            {
                listIdx++;
                continue;
            }

            // Same program, same channel, different starttime. Make a note,
            // and continue looking
            alternateShowings.push(nextProgram);
            listIdx++;
        }
        else
            break;
    }

    var menu = "normalMenu scheduleMenu";
    if (program.Recording.Status != 0)
        menu = "normalMenu delSchedMenu";

    // RecStatusToClass() - /tv/js/tvutil.qjs
    var statusClass = RecStatusToClass(program.Recording.Status);

    var recStatusDesc = dvr.RecStatusToDescription(program.Recording.Status,
                                                   program.Recording.RecType,
                                                   program.Recording.StartTs);
    var recTypeStr = dvr.RecTypeToString(program.Recording.RecType);

    // Used as a unique identifier and also to access the chanid
    // and starttime for the AJAX scheduling stuff
    var programIdentifier = channel.ChanId + "_" + program.StartTime.toISOString();

    var date = myth.GetFormatDate(program.StartTime);
%>
    <div class="programRow" id="<%=programIdentifier%>_row">
        <div class="channelBox">
            <img class="channelIcon" height="57" alt="<%=escapeHTML(channel.ChannelName)%> Icon" src="/Guide/GetChannelIcon?ChanId=<%=channel.ChanId%>&amp;Height=57" />
            <div class="channelText"><%=escapeHTML(channel.CallSign)%></div>
        </div>
        <div class="programBox">
            <div class="programInnerBox <%=statusClass%>" id="<%=programIdentifier%>" data-recordid="<%=program.Recording.RecordId%>" data-chanid="<%=channel.ChanId%>" data-starttime="<%=program.StartTime.toISOString()%>" onMouseOver="startDetailTimer(this, 'program');" onMouseOut="hideDetail(this);" onClick="showMenu(this, '<%=menu%>');">
                <div class="programHeader">
                    <span class="programTitle"><% if (program.CatType == CategoryType.MOVIE) {%><img src="/tv/images/cat_movie.svg" width="18" height="13" alt="<%=qsTr("Movie")%>" title="<%=qsTr("Movie")%>" /><%}%>
                                               <%=escapeHTML(program.Title)%> <% if (isValidObject(program.Airdate) && program.Airdate.getFullYear() && program.CatType == "movie") {%>(<%=program.Airdate.getFullYear()%>)<%}%></span>
                    <span class="programStartTime"><%=myth.GetFormatDate(program.StartTime)%>, <%=myth.GetFormatTime(program.StartTime)%></span>
                </div>
                <div class="programBody">
                    <span class="programSubtitle"><%=escapeHTML(program.SubTitle)%></span>
                    <% if (program.Season > 0 || program.Episode > 0) { %>
                        <span class="programSeasonEpisode">
                            <% if (program.Season > 0) { %>(<%=qsTr("S %1", "Season x").arg(program.Season)%>
                            <%} else {%>(<% } if (program.TotalEpisodes > 0) { %><%=qsTr("Ep %1/%2", "Episode x of y").arg(program.Episode).arg(program.TotalEpisodes)%>)
                            <%} else if (program.Episode > 0) {%><%=qsTr("Ep %1", "Episode x").arg(program.Episode)%>)<%}%>
                        </span>
                    <%}%>
                    <span class="programDescription"><%=escapeHTML(program.Description)%></span>
                </div>
                <div class="programSchedPopup" id="<%=programIdentifier%>_schedpopup">
                    <%=qsTr("Scheduling")%> ...
                </div>
                <input type="hidden" name="chanid" value="<%=channel.ChanId%>" />
                <input type="hidden" name="starttime" value="<%=program.StartTime.toISOString()%>" />
                <input type="hidden" name="recordid" value="<%=program.Recording.RecordId%>" />
            </div>
        </div>
<%
    // Yes, I know this code formatting is getting really ugly
    if (alternateShowings.length > 0)
    {
%>
        <div class="programAltShowings">
<%
        while (alternateShowings.length > 0)
        {
            var altProgram = alternateShowings.shift();
%>
            <%=altProgram.ProgramId%>,
<%
        }
%>
        </div>
<%
    }
    alternateShowings = [];
%>
    </div>
<%

}
%>

<%
if (nextStartIndex > 0)
{
    var obj = this.Parameters;

    obj.Start = nextStartIndex;
    var queryString = toQueryString(obj);
%>
<a class="jscroll-next" href="/tv/programsearch.qsp?<%=queryString%>&amp;ListOnly=1"></a>
<%}%>

<% if (!listOnly) {%>
</div> <!-- End programList -->
</div> <!-- End programList-container -->

<script type="text/javascript" nonce="<%=CSP_NONCE%>">
    function disableFieldset( event, ui )
    {
        if (isValidObject(ui.panel))
        {
            ui.panel.prop("disabled", false);
        }
        else
        {
            ui.oldPanel.prop("disabled", true);
            ui.newPanel.prop("disabled", false);
        }
    }

    $( "#filterType" ).tabs({ active: 0,
                              create: disableFieldset,
                              beforeActivate: disableFieldset});

</script>

<% if (programs.length > 0) {%>
<script type="text/javascript" nonce="<%=CSP_NONCE%>">
    loadJScroll();
</script>
<%}%>

<%
    var pageLoadEndTime = new Date();
%>
<script type="text/javascript" nonce="<%=CSP_NONCE%>">
    console.log("Page Load Time: <%=pageLoadEndTime.getTime() - pageLoadStartTime.getTime()%>ms, Program Load Time: <%=progLoadTimeEnd.getTime() - progLoadTimeStart.getTime()%>ms");
</script>

</body>
</html>
<%}%>
