﻿/**
* jQuery.ScrollTo - Easy element scrolling using jQuery.
* @version 1.4
*/
(function(h) { var m = h.scrollTo = function(b, c, g) { h(window).scrollTo(b, c, g) }; m.defaults = { axis: 'y', duration: 1 }; m.window = function(b) { return h(window).scrollable() }; h.fn.scrollable = function() { return this.map(function() { var b = this.parentWindow || this.defaultView, c = this.nodeName == '#document' ? b.frameElement || b : this, g = c.contentDocument || (c.contentWindow || c).document, i = c.setInterval; return c.nodeName == 'IFRAME' || i && h.browser.safari ? g.body : i ? g.documentElement : this }) }; h.fn.scrollTo = function(r, j, a) { if (typeof j == 'object') { a = j; j = 0 } if (typeof a == 'function') a = { onAfter: a }; a = h.extend({}, m.defaults, a); j = j || a.speed || a.duration; a.queue = a.queue && a.axis.length > 1; if (a.queue) j /= 2; a.offset = n(a.offset); a.over = n(a.over); return this.scrollable().each(function() { var k = this, o = h(k), d = r, l, e = {}, p = o.is('html,body'); switch (typeof d) { case 'number': case 'string': if (/^([+-]=)?\d+(px)?$/.test(d)) { d = n(d); break } d = h(d, this); case 'object': if (d.is || d.style) l = (d = h(d)).offset() } h.each(a.axis.split(''), function(b, c) { var g = c == 'x' ? 'Left' : 'Top', i = g.toLowerCase(), f = 'scroll' + g, s = k[f], t = c == 'x' ? 'Width' : 'Height', v = t.toLowerCase(); if (l) { e[f] = l[i] + (p ? 0 : s - o.offset()[i]); if (a.margin) { e[f] -= parseInt(d.css('margin' + g)) || 0; e[f] -= parseInt(d.css('border' + g + 'Width')) || 0 } e[f] += a.offset[i] || 0; if (a.over[i]) e[f] += d[v]() * a.over[i] } else e[f] = d[i]; if (/^\d+$/.test(e[f])) e[f] = e[f] <= 0 ? 0 : Math.min(e[f], u(t)); if (!b && a.queue) { if (s != e[f]) q(a.onAfterFirst); delete e[f] } }); q(a.onAfter); function q(b) { o.animate(e, j, a.easing, b && function() { b.call(this, r, a) }) }; function u(b) { var c = 'scroll' + b, g = k.ownerDocument; return p ? Math.max(g.documentElement[c], g.body[c]) : k[c] } }).end() }; function n(b) { return typeof b == 'object' ? b : { top: b, left: b} } })(jQuery);

var epgTransversal = {
    cons: {
        animation_speed: 400
    },
    initFilters: function() {
    }
};

var epgList = {
    // #### Attributes ####
    cons: { channel_height: 40,
        minut_pixels: 3
    },
    _currentServiceID: 'Meo',
    _currentPackID: '',
    _currentDate: '',
    _currentLeft: 0,
    _currentChannIdx: 0,
    _currentState: 0,
    _currentRequest: null,
    _currentAccount: '',
    _currentDetail: '',
    _remotePvrEnabled: 'False',
    _urlDetalheGravacao: '/ver/tv/guiatv/Pages/EpgDetail.aspx',
    _currentUrl: window.location,
    urlLogin: '/ver/Pages/login.aspx',
    // #### Private Methods ####
    _epgLoaded: function(msg) {
        jquery('#program_list_container').html(msg);
        jquery(".epg_sp").click(epgList._detailClick);
    },
    _animationStopped: function() {
        epgList._currentState = 0;
    },
    _detailClick: function() {
        epgList.beginShowDetail(this);
    },
    _loadEpg: function(endCallback) {
        // LOAD EPG DATA
        if (epgList._currentRequest)
            epgList._currentRequest.abort();

        epgList._currentRequest = jquery.ajax({
            type: "GET",
            url: "/_layouts/meosite/HttpHandlers/EpgList.ashx?Service=" + epgList._currentServiceID + "&Pack=" + epgList._currentPackID + "&BeginDate=" + epgList._currentDate + "&BeginChannel=" + epgList._currentChannIdx + "&Account=" + epgList._currentAccount,
            dataType: 'html',
            success: function(msg) {
                epgList._epgLoaded(msg);
                BindModal();
                if (endCallback != undefined)
                    endCallback();
            }
        });
    },
    // #### Public Methods ####
    hideDetail: function() {
        // var popupObj = jquery(".epg_popup");
        //if (popupObj.length > 0) {
        //jquery(".epg_channel").height(epgList.cons.channel_height);
        //jquery(".epg_programs").height(epgList.cons.channel_height);
        //jquery("#epg_channel_list").height(328);

        jquery(".epg_prog_sel").removeClass("epg_prog_sel");
        //jquery(".meo_success_epg").removeClass("meo_success_epg");
        //jquery(".meo_error_epg").removeClass("meo_error_epg");

        //   jquery(".epg_popup").remove();
        //}
    },
    endShowDetail: function(obj_id) {

        ClearModalBox();

        var jquery_obj = jquery(obj_id);

        // LOAD EPG Detail
        jquery("#loadingDetail").html("<div class='rec_loading' id='loading'><span class='epg_loading_txt'><i>A processar...</i></span></div>");
        jquery.ajax({
            type: "GET",
            url: "/_layouts/meosite/HttpHandlers/EpgDetail.ashx?Service=" + epgList._currentServiceID + "&ProgramID=" + jquery_obj.attr("id") + '&Account=' + epgList._currentAccount,
            dataType: 'html',
            success: function(msg) {
                jquery("#loadingDetail").html('');
                jquery("#boxes_lb").append(msg);
                jquery("#progtitledtl").text(jquery("#progtitle").text());
                jquery("#channelnamedtl").text(jquery("#progchannel").text());
                jquery("#synprgdtl").text(jquery("#progdesc").text());
                jquery("#progbegdtl").text(jquery_obj.attr("beg"));
                jquery("#progsurdtl").text(jquery_obj.attr("dur"));
                jquery("#cinza_box").show();
                jquery("#hideDetail").show();
                jquery(".boxs_1_lb").css("height", "");
                jquery(".boxs_1_mcinza").css("height", "");
                jquery("#progremdtl").html('&nbsp;<a href="/_layouts/meosite/HttpHandlers/IcsGenerator.ashx?ProgramID=' + jquery_obj.attr("id") + '&Date=' + epgList._currentDate + '&Time=' + jquery_obj.attr("beg") + '&dur=' + jquery_obj.attr("dur") + '" target="_blank"><img src="/Style%20Library/MeoImages/ic_sino.gif" alt="Agendar no seu calend&#225;rio" style="vertical-align:-12px;" /></a>&nbsp;');
                epgList.loadBts(jquery_obj);
            }
        });


        jquery_obj.parent().addClass("epg_prog_sel");

        OpenModalWindow();

        epgList._animationStopped();
    },
    recordingProgram: function() {
        var jquery_obj = jquery(this);
        var progName = jquery(".desc").children(0).html();
        var scheduleID = jquery_obj.attr("ScheduleID");
        var prgID = jquery_obj.attr("prgID");
        var acct = jquery_obj.attr("acctID");
        var listing = jquery_obj.attr("listing");
        var programID = scheduleID + "_" + prgID;

        jquery("#btngravar").hide();
        jquery("#btngravarseries").hide();
        jquery(".bot_gravar_opcoes").hide();

        jquery(".ad_bot_gravacao").append("<div class='rec_loading' id='loading'><span class='epg_loading_txt'><i>A processar...</i></span></div>");

        //if (confirm("Tem a certeza que deseja gravar o programa '" + progName + "'?")) {
        jquery.ajax({
            type: "POST",
            url: "/_layouts/meosite/HttpHandlers/RecordingMng.asmx/RecordingProgram",
            dataType: 'json',
            data: '{accountNumber:"' + acct + '", programID:"' + prgID + '", scheduleID:"' + scheduleID + '"}',
            contentType: 'application/json',
            success: function(responseData) {
                jquery("#loading").remove();
                jquery(".ad_bot_gravacao").click(epgList.hideMsg);
                if (responseData.d.Code == "OK") {
                    jquery_obj.remove();
                    jquery(".ad_bot_gravacao").html('<div class=\"meo_success_epg\">' + responseData.d.Message + '</div>');
                    jquery("#" + programID).prepend('<div class=\"bts bt_programa_epg\" style=\"cursor:pointer\"/>');
                    jquery("#" + programID).attr("recid", responseData.d.RecordingID);
                    jquery("#" + programID).attr("seriesid", responseData.d.SeriesID);
                }
                else if (responseData.d.Code == "ERR-01") {
                    window.location = epgList.urlLogin + '?returnurl=' + epgList.returnUrl();
                }
                else if (responseData.d.Code == "ERR-04") {
                    jquery(".ad_bot_gravacao").unbind('click');
                    jquery(".ad_bot_gravacao").html('<div class=\"meo_error_epg\">O programa n&#227;o ir&#225; gravar porque existem demasiadas grava&#231;&#245;es agendadas ao mesmo tempo. Clique <a href="#dialogConf" name="modalconf">aqui</a> para resolver os conflitos.</div>');
                    jquery("#" + programID).prepend('<div class=\"bts bt_programa_epg_err\" style=\"cursor:pointer\"/>');
                    jquery("body").append(responseData.d.Message);
                    //BindModal();
                    OpenConflictModalWindow();
                    BindResolvebtn();
                    jquery("#" + programID).attr("recid", responseData.d.RecordingID);
                }
                else {
                    jquery(".ad_bot_gravacao").html('<div class=\"meo_error_epg\">' + responseData.d.Message + '</div>');
                }
            },
            error: function(responseData) {
                jquery(".ad_bot_gravacao").click(epgList.hideMsg);
                jquery("#loading").remove();
                jquery(".ad_bot_gravacao").html('<div class=\"meo_error_epg\">Ocorreu um erro inesperado. Tente mais tarde.</div>');
            }
        });
    },
    recordingSeries: function() {
        var jquery_obj = jquery(this);
        var progName = jquery(".desc").children(0).html();
        var prgID = jquery_obj.attr("prgID");
        var scheduleID = jquery_obj.attr("ScheduleID");
        var acct = jquery_obj.attr("acctID");
        var listing = jquery_obj.attr("listing");
        var programID = scheduleID + "_" + prgID;

        jquery("#btngravar").hide();
        jquery("#btngravarseries").hide();
        jquery(".bot_gravar_opcoes").hide();

        jquery(".ad_bot_gravacao").append("<div class='rec_loading' id='loading'><span class='epg_loading_txt'><i>A processar...</i></span></div>");

        //if (confirm("Tem a certeza que deseja gravar a série '" + progName + "'?")) {
        jquery.ajax({
            type: "POST",
            url: "/_layouts/meosite/HttpHandlers/RecordingMng.asmx/RecordingSeries",
            dataType: 'json',
            data: '{accountNumber:"' + acct + '", programID:"' + prgID + '", scheduleID:"' + scheduleID + '"}',
            contentType: 'application/json',
            success: function(responseData) {
                jquery("#loading").remove();
                jquery(".ad_bot_gravacao").click(epgList.hideMsg);
                if (responseData.d.Code == "OK") {
                    jquery_obj.remove();
                    jquery(".ad_bot_gravacao").html('<div class=\"meo_success_epg\">' + responseData.d.Message + '</div>');
                    jquery("#" + programID).prepend('<div class=\"bts bt_serie_epg\" style=\"cursor:pointer\"/>');
                    jquery("#" + programID).attr("recid", responseData.d.RecordingID);
                    jquery("#" + programID).attr("seriesid", responseData.d.SeriesID);
                }
                else if (responseData.d.Code == "ERR-01") {
                    window.location = epgList.urlLogin + '?returnurl=' + epgList.returnUrl();
                }
                else if (responseData.d.Code == "ERR-04") {
                    jquery(".ad_bot_gravacao").unbind('click');
                    jquery(".ad_bot_gravacao").html('<div class=\"meo_error_epg\">O programa n&#227;o ir&#225; gravar porque existem demasiadas grava&#231;&#245;es agendadas ao mesmo tempo. Clique <a href="#dialogConf" name="modalconf">aqui</a> para resolver os conflitos.</div>');
                    if (responseData.d.SeriesID != "")
                        jquery("#" + programID).prepend('<div class=\"bts bt_serie_epg_err\" style=\"cursor:pointer\"/>');
                    else
                        jquery("#" + programID).prepend('<div class=\"bts bt_programa_epg_err\" style=\"cursor:pointer\"/>');
                    jquery("body").append(responseData.d.Message);
                    //BindModal();
                    OpenConflictModalWindow();
                    BindResolvebtn();
                    jquery("#" + programID).attr("recid", responseData.d.RecordingID);
                    jquery("#" + programID).attr("seriesid", responseData.d.SeriesID);
                }
                else
                    jquery(".ad_bot_gravacao").html('<div class=\"meo_error_epg\">' + responseData.d.Message + '</div>');
            },
            error: function(responseData) {
                jquery(".ad_bot_gravacao").html('<div class=\"meo_error_epg\">Ocorreu um erro inesperado. Tente mais tarde.</div>');
            }
        });
    },
    beginShowDetail: function(obj_id) {
        if (epgList._currentState == 1)
            return;

        var jquery_obj = jquery(obj_id);
        if (jquery_obj.length == 0)
            return;


        epgList._currentDetail = jquery_obj[0].id.toString();

        epgList.hideDetail();

        var leftElement = (Math.floor((jquery_obj.parent().position().left) / (epgList.cons.minut_pixels * 60))) * (epgList.cons.minut_pixels * 60);
        if (leftElement < epgList._currentLeft) {
            epgList._currentLeft = leftElement;
            jquery(".epgtimewrapper").scrollTo(epgList._currentLeft, epgTransversal.cons.animation_speed);
            jquery("#epg_program_list").scrollTo(epgList._currentLeft, epgTransversal.cons.animation_speed, function() { epgList.endShowDetail(obj_id); });

        }
        else
            epgList.endShowDetail(obj_id);
    },
    scrollLeft: function() {
        if (epgList._currentState == 1)
            return;
        epgList.hideDetail();
        var left_move = jquery(".epgtimewrapper").scrollLeft() - (epgList.cons.minut_pixels * 60 * 2);
        if (left_move < 0)
            left_move = 0;
        epgList._currentLeft = left_move;
        epgList._currentState = 1;
        jquery(".epgtimewrapper").scrollTo(left_move, epgTransversal.cons.animation_speed);
        jquery("#epg_program_list").scrollTo(left_move, epgTransversal.cons.animation_speed, epgList._animationStopped);

        return false;
    },
    scrollRight: function() {
        if (epgList._currentState == 1)
            return;
        epgList.hideDetail();
        var right_move = jquery(".epgtimewrapper").scrollLeft() + (epgList.cons.minut_pixels * 60 * 2);
        if (right_move < (1620 * epgList.cons.minut_pixels)) {
            epgList._currentLeft = right_move;
            epgList._currentState = 1;
            jquery(".epgtimewrapper").scrollTo(right_move, epgTransversal.cons.animation_speed);
            jquery("#epg_program_list").scrollTo(right_move, epgTransversal.cons.animation_speed, epgList._animationStopped);
        }
    },
    endScrollUpDown: function() {
        epgList._loadEpg();
        epgList._animationStopped();
    },
    beginScrollUp: function() {
        if (epgList._currentState == 1)
            return;
        epgList.hideDetail();
        var prev = epgList._currentChannIdx;
        epgList._currentChannIdx -= 10;
        if (epgList._currentChannIdx < 0) epgList._currentChannIdx = 0;
        if (prev != epgList._currentChannIdx) {
            jquery('#program_list_container').html('<div class="epg_loading" style="left:' + epgList._currentLeft + 'px;"></div>');
            epgList._currentState = 1;
            jquery("#epg_channel_list").scrollTo('-=410px', epgTransversal.cons.animation_speed, epgList.endScrollUpDown);
        }
    },
    beginScrollDown: function() {
        if (epgList._currentState == 1)
            return;
        epgList.hideDetail();
        var prev = epgList._currentChannIdx;
        epgList._currentChannIdx += 10;
        var numChannels = jquery(".epg_channel").length;
        if (epgList._currentChannIdx >= (numChannels - 10)) epgList._currentChannIdx = numChannels - 10;
        if (epgList._currentChannIdx < 0) epgList._currentChannIdx = 0;

        if (prev != epgList._currentChannIdx) {
            jquery('#program_list_container').html('<div class="epg_loading" style="left:' + epgList._currentLeft + 'px;"></div>');
            epgList._currentState = 1;
            jquery("#epg_channel_list").scrollTo('+=410px', epgTransversal.cons.animation_speed, epgList.endScrollUpDown);
        }
    },
    //CONTEXT
    scrollToContext: function() {
        if (epgList._currentState == 1)
            return;

        var prev = epgList._currentChannIdx;

        var contextChannIdx = jquery.query.get('channIdx');
        if (contextChannIdx != null || contextChannIdx.toString().length > 0) {
            epgList._currentChannIdx = jquery.query.get('channIdx');
        }
        else
            return;
        //Calculate how many pixels should we go down	
        var pixelsDown = (contextChannIdx / 8) * 328;

        epgList.hideDetail();
        var numChannels = jquery(".epg_channel").length;
        if (epgList._currentChannIdx >= (numChannels - 8)) epgList._currentChannIdx = numChannels - 8;
        if (epgList._currentChannIdx < 0) epgList._currentChannIdx = 0;

        epgList._currentState = 1;
        if (prev != epgList._currentChannIdx)
            jquery("#epg_channel_list").scrollTo(pixelsDown + 'px', epgTransversal.cons.animation_speed * 2, epgList.scrollToContextHour);
        else
            epgList.scrollToContextHour();
    },
    hasReturnContext: function() {
        var contextChannIdx = jquery.query.get('channIdx');
        if (contextChannIdx != null && contextChannIdx.toString().length > 0)
            return true;

        return false;
    },
    scrollToContextHour: function() {
        //animation has stopped
        epgList._currentState = 0;
        jquery('#program_list_container').html('');

        var contextHour = jquery.query.get('hour');
        if (contextHour != null && contextHour.toString().length > 0) {
            jquery('#program_list_container').html('<div class="epg_loading" style="left:' + epgList._currentLeft + 'px;"></div>');
            epgList.scrollToHour(contextHour);
            epgList._loadEpg(epgList.openContextDetail);
        }
        else {
            jquery('#program_list_container').html('<div class="epg_loading" style="left:' + epgList._currentLeft + 'px;"></div>');
            epgList.scrollToNow();
            epgList._loadEpg();
        }
    },
    openContextDetail: function() {
        //animation has stopped
        epgList._currentState = 0;

        var contextDetailIdx = jquery.query.get('detailIdx');

        if (contextDetailIdx != null && contextDetailIdx.toString().length > 0) {
            epgList.beginShowDetail(jquery('#' + contextDetailIdx.toString()));
        }
        else
            return;
    },
    returnUrl: function() {
        if (window.location.toString().indexOf('?') > 0)
            return window.location.toString().split('?')[0] + escape(jquery.query.SET("channIdx", epgList._currentChannIdx).SET("hour", (epgList._currentLeft / epgList.cons.minut_pixels / 60)).SET("detailIdx", epgList._currentDetail).toString());
        else
            return window.location.toString() + escape(jquery.query.SET("channIdx", epgList._currentChannIdx).SET("hour", (epgList._currentLeft / epgList.cons.minut_pixels / 60)).SET("detailIdx", epgList._currentDetail).toString()); ;
    },
    scrollToHour: function(hour) {
        if (epgList._currentState == 1)
            return;

        var pos_now = (hour * epgList.cons.minut_pixels * 60);
        epgList._currentState = 1;
        jquery(".epgtimewrapper").scrollTo(pos_now, epgTransversal.cons.animation_speed);
        jquery("#epg_program_list").scrollTo(pos_now, epgTransversal.cons.animation_speed);
        epgList._currentLeft = pos_now;
    },
    //END CONTEXT
    scrollToPrimeTime: function(hour) {
        if (epgList._currentState == 1)
            return;
        epgList.hideDetail();

        var pos_now = (hour * epgList.cons.minut_pixels * 60);
        epgList._currentState = 1;
        jquery(".epgtimewrapper").scrollTo(pos_now, epgTransversal.cons.animation_speed);
        jquery("#epg_program_list").scrollTo(pos_now, epgTransversal.cons.animation_speed, epgList._animationStopped);
        epgList._currentLeft = pos_now;
    },
    scrollToNow: function() {
        if (epgList._currentState == 1)
            return;
        epgList.hideDetail();

        var thisdate = new Date();
        var pos_now = (thisdate.getHours() * epgList.cons.minut_pixels * 60);
        epgList._currentState = 1;
        jquery(".epgtimewrapper").scrollTo(pos_now, epgTransversal.cons.animation_speed);
        jquery("#epg_program_list").scrollTo(pos_now, epgTransversal.cons.animation_speed, epgList._animationStopped);
        epgList._currentLeft = pos_now;
    },
    callInit: function() {
        epgList._urlDetalheGravacao = jquery('#sel_UrlDetail').val();
        epgList._currentServiceID = jquery('#sel_service').val();
        epgList._currentPackID = jquery('#sel_pack').val();
        epgList._currentDate = jquery('#sel_date').val();
        epgList._currentAccount = jquery('#sel_svcAccount').val();
        epgList._currentUrl = jquery('#sel_Url').val();
        epgList._remotePvrEnabled = jquery('#RemotePVRFeaturesEnabled').val();


        jquery.scrollTo.defaults.axis = 'xy';
        jquery.scrollTo(0, 0); //reset the screen to (0,0)
        jquery("#epg_channel_list").scrollTo(0, 0);

        // CLICK LEFT, RIGHT, UP and DOWN
        jquery('#epg_moveleft').click(epgList.scrollLeft);
        jquery('#epg_moveright').click(epgList.scrollRight);
        jquery('#epg_moveup').click(epgList.beginScrollUp);
        jquery('#epg_movedown').click(epgList.beginScrollDown);

        // CLICK 'NOW'
        jquery("#currentHour").click(epgList.scrollToNow);

        epgTransversal.initFilters();
        // INIT TODAY DATE
        // scroll to current hour
        if (epgList.hasReturnContext())
            epgList.scrollToContext();
        else {
            epgList.scrollToNow();
            jquery('#program_list_container').html('<div class="epg_loading" style="left:' + epgList._currentLeft + 'px;"></div>');
            epgList._loadEpg();
        }
    },

    hideMsg: function() {
        //jquery(".syn").children(".pos_bots_prog").remove();
        jquery_obj = jquery(".epg_prog_sel").children(".epg_sp");
        epgList.loadBts(jquery_obj);

        //return false;
    },

    loadBts: function(jquery_obj) {
        jquery(".ad_bot_gravacao").text('');
        var url;
        var hostname = window.location.hostname;
        if (jquery(".bts", jquery_obj).length > 0)
            jquery(".ad_bot_gravacao").append('<a class="bot_gravar_opcoes" href="' + epgList._urlDetalheGravacao + '?Acct=' + epgList._currentAccount + '&RecordID=' + jquery_obj.attr("recid") + '&Source=' + epgList.returnUrl() + '">CONFIGURAR</a>');
        else if (epgList._remotePvrEnabled == 'True') {
            var now = new Date();
            var progDate = new Date(epgList._currentDate);
            var begin = (jquery_obj.parent().position().left / epgList.cons.minut_pixels) * 60;
            var duration = parseInt(jquery_obj.attr("dur")) * 60;
            progDate.setTime(progDate.getTime() + ((begin + duration) * 1000));
            if (progDate > now) {
                //DIV para 3 botoes de gravação
                if (jquery_obj.attr("serieid") != "") {
                    jquery(".ad_bot_gravacao").append('<div id="btngravar" listing="true" ScheduleID="' + jquery_obj.attr("id").split('_')[0] + '" acctID="' + epgList._currentAccount + '" prgID="' + jquery_obj.attr("id").split('_')[1] + '"><a class="bot_gravar">GRAVAR</a></div><div id="btngravarseries" listing="true" ScheduleID="' + jquery_obj.attr("id").split('_')[0] + '" acctID="' + epgList._currentAccount + '" prgID="' + jquery_obj.attr("id").split('_')[1] + '"><a class="bot_gravar_series">GRAVAR A S&Eacute;RIE</a></div><a class="bot_gravar_opcoes" href="' + epgList._urlDetalheGravacao + '?ScheduleID=' + jquery_obj.attr("id").split('_')[0] + '&ProgramID=' + jquery_obj.attr("id").split('_')[1] + '&Acct=' + epgList._currentAccount + '&Source=' + epgList.returnUrl() + '">GRAVAR COM OP&Ccedil;&Otilde;ES</a>');
                    jquery('#btngravar').click(epgList.recordingProgram);
                    jquery('#btngravarseries').click(epgList.recordingSeries);
                }
                else {
                    jquery(".ad_bot_gravacao").append('<div id="btngravar" listing="true" ScheduleID="' + jquery_obj.attr("id").split('_')[0] + '" acctID="' + epgList._currentAccount + '" prgID="' + jquery_obj.attr("id").split('_')[1] + '"><a class="bot_gravar">GRAVAR</a></div><a class="bot_gravar_opcoes" href="' + epgList._urlDetalheGravacao + '?ScheduleID=' + jquery_obj.attr("id").split('_')[0] + '&ProgramID=' + jquery_obj.attr("id").split('_')[1] + '&Acct=' + epgList._currentAccount + '&Source=' + epgList.returnUrl() + '">GRAVAR COM OP&Ccedil;&Otilde;ES</a>');
                    jquery('#btngravar').click(epgList.recordingProgram);
                }
            }
            url = "http://" + hostname + epgList._urlDetalheGravacao + '?ScheduleID=' + jquery_obj.attr("id").split('_')[0] + '&ProgramID=' + jquery_obj.attr("id").split('_')[1];
        }

        //url = url.substring(0, url.indexOf("&Acct="));
        var urltmp = toAbs(url, window.location.toString().toLowerCase());
        getRedesSociais(jquery("#progtitle").text(), "/", "MeoSocialNetworksList", urltmp, false, 0);
    }
};

var epgDtl = {
    // #### Attributes ####
    _selectedChannel: '',
    _currentDetail: '',
    // #### Private Methods ####
    // #### Public Methods ####
    hideProgram: function() {
        jquery(".dtl_prog_sel").removeClass("dtl_prog_sel");
    },
    expandProgram: function() {
        var jquery_obj = jquery(this);
        epgDtl.hideProgram();
        jquery_obj.parent().addClass("dtl_prog_sel");
    },
    _scrollToDate: function(referenceDate) {
        var selProgram = null;
        var selDate = null;

        var progs = jquery(".dtl_prog");
        for (i = 0; i < progs.length; i++) {
            var progDate = new Date();
            var progTime = jquery(".dtl_time", progs[i]).attr("time").split(":");
            if (progTime && progTime.length == 2) {

                progDate.setHours(parseInt(progTime[0]));
                progDate.setMinutes(parseInt(progTime[1]));
                progDate.setSeconds(0);

                if (progDate <= referenceDate &&
		    		(selDate == null || selDate < progDate)) {
                    selDate = progDate;
                    selProgram = progs[i];
                }
            }
        }

        if (selProgram != null) {
            epgDtl.hideProgram();
            jquery(selProgram).addClass("dtl_prog_sel");
            jquery("#dtl_body").scrollTo(selProgram, epgTransversal.cons.animation_speed);
        }
    },
    scrollToNow: function() {
        epgDtl._scrollToDate(new Date());
    },
    scrollToPrimeTime: function(hour) {
        var date = new Date();
        date.setHours(hour);
        date.setMinutes(0);
        date.setSeconds(0);

        epgDtl._scrollToDate(date);
    },
    callInit: function() {
        epgDtl._selectedChannel = jquery('#sel_channel').val();
        jquery(".dtl_title").click(epgDtl.expandProgram);
        jquery(".dtl_title_channel").click(epgDtl.expandProgram); /**/


        jquery("#currentHour").click(epgDtl.scrollToNow);

        epgTransversal.initFilters();

        jquery("#dtl_body").scrollTo(jquery(".dtl_prog_sel"), epgTransversal.cons.animation_speed);
    }
};

function EPGChangePack(drpDwnID, pageUrl) {
    var jquery_obj = jquery('#' + drpDwnID);

    window.location = pageUrl + '?Pack=' + jquery_obj.val() + '&date=' + jquery('#sel_date').val().substring(0, 10);
}

function EPGChangeServiceAccount(drpDwnID, pageUrl) {
    var jquery_obj = jquery('#' + drpDwnID);

    window.location = pageUrl + '?Account=' + jquery_obj.val() + '&date=' + jquery('#sel_date').val().substring(0, 10);
}


function EPGShowChannel(drpDwnChannelID, drpDwnDateID, drpDwnTimeID, pageUrl) {
    var drpDwnChannel = jquery('#' + drpDwnChannelID);
    var drpDwnDate = jquery('#' + drpDwnDateID);
    var drpDwnTime = jquery('#' + drpDwnTimeID);

    if (drpDwnChannel.val() == '') {
        alert('Por favor, seleccione um canal.');
        return;
    }

    window.location = pageUrl + '?Channel=' + drpDwnChannel.val() + '&date=' + drpDwnDate.val().substring(0, 10) + '&time=' + drpDwnTime.val();
}

function EPGRedirect(pageUrl) {
    window.location = pageUrl;
}

function toAbs(link, host) {

    if (link.indexOf("http://") != -1) {
        return link;

    }
    else {
        var url = host.substring(0, host.indexOf("/pages/"));
        return url + link;
    }
    return "";
}


function BindModal() {

    //select all the a tag with name equal to modal
    jquery('a[name=modal]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();

        // jquery('select').hide();

        //Get the A tag
        var id = jquery("#dialog");

        //Get the screen height and width
        //        var maskHeight = jquery(document).height();
        //        var maskWidth = jquery(window).width();

        //Set heigth and width to mask to fill up the whole screen
        //        jquery('#mask_light').css({ 'width': maskWidth, 'height': maskHeight });

        //transition effect                          
        //        jquery('#mask_light').fadeIn(1000);
        //        jquery('#mask_light').fadeTo("slow", 0.7);

        //Get the window height and width
        var winH = jquery(window).height();
        var winW = jquery(window).width();

        //Set the popup window to center
        id.css('top', winH / 2 - id.height() / 2);
        id.css('left', winW / 2 - id.width() / 2);

        //transition effect
        id.fadeIn(1500); //2000

    });

    //if close button is clicked
    jquery('.window .close').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();

        jquery('#mask_light').hide();
        jquery('.window').hide();
        jquery(".epg_prog_sel").removeClass("epg_prog_sel");

        ClearModalBox();
    });

    //if mask is clicked
    jquery('#mask_light').click(function() {
        jquery(this).hide();
        jquery('.window').hide();
        jquery(".epg_prog_sel").removeClass("epg_prog_sel");

        ClearModalBox();
    });
}

function BindResolvebtn() {
    recConflict.callInit('/ver/tv/guiatv/Pages/GuiaTV.aspx');
}

function ClearModalBox() {
    jquery("#progtitle").remove();
    jquery("#progchannel").remove();
    jquery("#progdesc").remove();
    jquery("#progtitledtl").text('');
    jquery("#channelnamedtl").text('');
    jquery("#synprgdtl").text('');
    jquery("#progbegdtl").text('');
    jquery("#progsurdtl").text('');
    jquery("#progremdtl").html('');
    jquery(".ad_bot_gravacao").text('');
    jquery("#cinza_box").hide();
    jquery(".boxs_1_mcinza").css("height", "80px");
    jquery("#hideDetail").hide();
    jquery(".boxs_1_lb").css("height", "80px");
}

function OpenModalWindow() {

    var id = jquery("#dialog");

    //Get the screen height and width
    //var maskHeight = jquery(document).height();
    //var maskWidth = jquery(window).width();

    //Set heigth and width to mask to fill up the whole screen
    //jquery('#mask_light').css({ 'width': maskWidth, 'height': maskHeight });

    //transition effect                          
    //jquery('#mask_light').fadeIn(1000);
    //jquery('#mask_light').fadeTo("slow", 0.7);

    //Get the window height and width
    var winH = jquery(window).height();
    var winW = jquery(window).width();

    //Set the popup window to center
    id.css('top', winH / 2 - id.height() / 2);
    id.css('left', winW / 2 - id.width() / 2);

    //transition effect
    id.fadeIn(1500); //2000


}

function getRedesSociais(title, targetWeb, listname, requestUrl, invalidateCache, cacheDuration) {
    var i = jquery.ajax({
        type: "POST",
        url: "/_layouts/meosite/HttpHandlers/RedesSociais.asmx/GetRedesSociais",
        dataType: 'json',
        data: '{title:"' + title + '", targetWeb:"' + targetWeb + '", listName:"' + listname + '", requestURL:"' + requestUrl + '", invalidateCache:' + invalidateCache + ', cacheDuration:' + cacheDuration + '}',
        contentType: 'application/json',
        success: function(responseData) {
            if (responseData.d != "") {
                jquery("#redesSociaisSP").html(responseData.d);
            }
        },
        error: function(responseData) {
        }
    });
}

function OpenConflictModalWindow() {

    jquery('a[name=modalconf]').click(function(e) {

        e.preventDefault();

        jquery(".boxs_6").hide();

        var id = jquery("#dialogConf");

        //Get the screen height and width
        var maskHeight = jquery(document).height();
        var maskWidth = jquery(window).width();

        //Set heigth and width to mask to fill up the whole screen
        jquery('#mask').css({ 'width': maskWidth, 'height': maskHeight });

        //transition effect                          
        jquery('#mask').fadeIn(1000);
        jquery('#mask').fadeTo("slow", 0.7);

        //Get the window height and width
        var winH = jquery(window).height();
        var winW = jquery(window).width();

        //Set the popup window to center
        id.css('top', winH / 2 - id.height() / 2);
        id.css('left', winW / 2 - id.width() / 2);

        //transition effect
        id.fadeIn(1500); //2000
    });

}