﻿/*
************************************************************************* 
***
***  File: Scripts.js
***  Created By: Andrew Reid / TJ O'Connor
***  Created On: 04.22.2010                                 
***  Description: JavaScript controller for all Pulse API interaction
***
*************************************************************************
*/ 



// ----------------- init/set variables -----------------
//var baseURL = "http://tpn/";
//var baseURL = "http://areid/Pulse/";
//var baseURL = "http://beta.thepulsenetwork.com/";
var baseURL = "http://tpn.thepulsenetwork.com/";


var screenNumber = "ThePulseNetwork";
var userCookie = getCookie('PulseNetworkCookie');
var urlFeed = "";

var uid = new UserId();
var eid = new EpisodeId();
var sid = new ShowId();
var cid = new CommercialId();
var sslug = new ShowSlug();

$(function () {
    initAjax();
});



function UserId() {
    this.value = '';
}
function EpisodeId() {
    this.value = '';
}
function ShowId() {
    this.value = '';
}
function CommercialId() {
    this.value = '';
}
function ShowSlug() {
    this.value = '';
}
// ----------------- init variables -----------------


// ----------------- general functions -----------------

function loginPage() {
    $('.login-widget').show();
}


function WriteURL(path) {
    document.write(baseURL + path);
}

function showAjax(widgetID) {
    // Strech Panel to match Widget
    // IE bug
    //$(widgetID).find("div.widget-loading-panel").height($(widgetID).find("div.widget-content").outerHeight());
    //$(widgetID).find("div.widget-loading-panel").width($(widgetID).find("div.widget-content").outerWidth());

    // Show Loading Panel
    $(widgetID).find("div.widget-loading-panel").show();
    // Show Loading Header
    $(widgetID).find("div.widget-loading-header").show();
}

function initAjax() {
    $("div.widget-loading-panel").hide();
    // Hide Loading Header
    $("div.widget-loading-header").hide();
}

function hideAjax(widgetID) {
    // Hide Loading Panel
    $(widgetID).find("div.widget-loading-panel").fadeOut("slow");
    // Hide Loading Header
    $(widgetID).find("div.widget-loading-header").fadeOut("slow");
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
// ----------------- end general functions -----------------


// ----------------- init player -----------------
var inIntervalShow = 0;

function startTimers() {

    //get the show information
    getShowInfo(eid);

    //start the show ping for show titles
    // for testing intIntervalShow = setInterval(function () { getShowInfo(eid); }, 3000);
    intIntervalShow = setInterval(function () { getShowInfo(eid); }, 6000);

    //check for comercial
    //getCommercialInfo(eid, cid);

    //start commercial info ping
    //intIntervalCommercial = setInterval(function () { getCommercialInfo(eid, cid); }, 2000);

    //check to see if user exists
    //var userCookie = getCookie('PulseNetworkCookie');
    if (userCookie != "") {
        //change url for topic only popup
        $('.AddQueueButton').attr('href', baseURL + 'Popups/Profile.aspx?mode=1');
        //set local var    
        uid.value = userCookie;
        //start queue ping
        //startQueueTimer(uid, eid);
    }
}

function getShowInfo(eid) {
    $.post(baseURL + "_Show.ashx", { "strMode": "showinfo", "strEpisode_Id": eid.value, "strShow_Id": sid.value },
    function (data) {
        if (eid.value != data.Episode_Id) {
            eid.value = data.Episode_Id;
            sid.value = data.Show_Id;
            sslug.value = data.ShowSlug;

            
            if (data.Redirect_Url != "") {
                window.location = data.Redirect_Url;
            }

            if ($('.hiddenLiveChannel').val() != data.Episode_Feed_Url) {
                player.setChannelID(data.Episode_Feed_Url);
                player.setPlay('true');
            }

            //$('.player-banner-panel .show-header-title').html(data.Show_Name);
            $('.player-banner-panel .show-header-title').html("<img src = '" + baseURL + "Images/" + data.Show_Image + "' />");
            //$('.player-banner-panel .episode-header-title').html("Episode: " + data.Episode_Title);

            urlFeed = data.Episode_Feed_Url;
            if (urlFeed == "") {
                window.location = baseURL;
            }

            //update next on
            $.post(baseURL + "_Show.ashx", { "strMode": "nexton", "strEpisode_Id": eid.value },
            function (data) {
                $('.player-banner-panel .next-show-title').html(data.Show_Name);
                //$('.player-banner-panel .next-episode-title').html(data.Episode_Title);
            }, "json");

            //update schedule
            $.post(baseURL + "_Show.ashx", { "strMode": "schedule", "strEpisode_Id": eid.value },
            function (data) {
                $('.player-banner-panel .schedule-inner').html(data.html);
            }, "json");
        }
    }, "json");

}
// ----------------- end init player -----------------


// ----------------- skype functions -----------------
var intInterval = 0;

function startQueueTimer(uid, eid) {
    checkQueue(uid, eid);
    intInterval = setInterval(function () { checkQueue(uid, eid); }, 3000);
}

function checkQueue(uid, eid) {
    $.post(baseURL + "_episodecaller.ashx", { "strMode": "posistion", "strUser_Id": uid.value, "strEpisode_Id": eid.value },
        function (data) {
            //hide button if in queue
            $('.skype-link').hide();
            //unmute player
            //player.sendEvent('MUTE', 'false');
            //no longer in queue
            if (data.count == 0) {
                // hiding for now
                $('.skype-link').show();
                $('#msgHolder').fadeOut();
            }
            //you are live on show
            else if (data.live == "True") {
                $('#msgHolder').html("<h3>You are currently live online.</h3>").fadeIn();
                //player.sendEvent('MUTE', 'true');
            }
            //next in line
            else if (data.count >= 1) {
                $('#msgHolder').html("<h3>You are currently in the queue.  Please Skype us at <a href='callto://" + screenNumber + "/'>" + screenNumber + "</a></h3>");
            }
            //over 2 in the queue
            //else {
            //    $('#msgHolder').html("<h3>You are currently " + data.count + " in the queue.</h3>").fadeIn();
            //}
        }, "json");
}

function registerUser(uid) {
    $.post(baseURL + "_user.ashx", { "strMode": "register", "strUser_Id": uid, "strFirst_Name": $('.txtFirst').val(), "strLast_Name": $('.txtLast').val(), "strTitle": "", "strCompany": $('.txtCompany').val(), "strEmail": $('.txtEmail').val(), "strSkype_Id": $('.txtSkype').val(), "strTwitter_Id": $('.txtTwitter').val(), "strUsername": $('.txtUsername').val() },
    function (data) {
        if (data.transfer == "True") {
            window.location = baseURL;
        }
    }, "json");

    $.facebox.close();
}

function registerSkype(uid, eid) {
    $.post(baseURL + "_user.ashx", { "strMode": "addskype", "strUser_Id": uid.value, "strEpisode_Id": eid.value, "strFirst_Name": $('#txtFirst').val(), "strLast_Name": $('#txtLast').val(), "strEmail": $('#txtEmail').val(), "strSkype_Id": $('.txtSkype').val(), "strTopic": $('#txtTopic').val() },
    function (data) {
        //change url for topic only popup
        $('.AddQueueButton').attr('href', '~/Popups/Profile.aspx?mode=1');
        //set local var 
        uid.value = data.strUser_Id;
        //start queue ping
        startQueueTimer(uid, eid);
    }, "json");

    $.facebox.close();
}
// ----------------- end skype functions -----------------



// ----------------- live player commerical functions -----------------
var intIntervalCommercial = 0;

function getCommercialInfo(eid, cid) {
    $.post(baseURL + "_Commercial.ashx", { "strMode": "get", "strEpisode_Id": eid.value },
    function (data) {
        if (data.Commercial_Id != "") {
            clearInterval(intIntervalCommercial);

            cid.value = data.Commercial_Id;
            //switch streem
            player.sendEvent('LOAD', data.Com_URL);
            player.sendEvent('PLAY');
            //stop looking for ads
        }
    }, "json");
}

function commercialEnd(cid) {
    //first record will delete the commercial
    $.post(baseURL + "_Commercial.ashx", { "strMode": "update", "strCommercial_Id": cid.value }, function (data) { }, "json");
}
// ----------------- end live player commerical functions -----------------



// ----------------- feedback popup script -----------------
function setupFeedback() {
    $('.slide-out-div').tabSlideOut({
        tabHandle: '.handle',                     //class of the element that will become your tab
        pathToTabImage: baseURL + 'Images/feedback-btn-right.png', //path to the image for the tab //Optionally can be set using css
        imageHeight: '160px',                     //height of tab image           //Optionally can be set using css
        imageWidth: '38px',                       //width of tab image            //Optionally can be set using css
        tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
        speed: 300,                               //speed of animation
        action: 'click',                          //options: 'click' or 'hover', action to trigger animation
        topPos: '200px',                          //position from the top/ use if tabLocation is left or right
        leftPos: '20px',                          //position from left/ use if tabLocation is bottom or top
        fixedPosition: false                      //options: true makes it stick(fixed position) on scroll
    });

}
// ----------------- feedback popup script  -----------------


// ----------------- facbox scripts -----------------
function setupFacebox() {
    $('a[rel*=facebox]').facebox({ opacity: 0.7 });
}

// ----------------- end facbox scripts -----------------

// ----------------- mulitlple bit rate functions -----------------
// ----------------- MOVED TO PLAYER PAGE -----------------
//function changeStream(stream, sender) {
//    //alert('test');
//    $('table.bitrate td').removeClass("selected");
//    //alert($(sender).parent());
//    $(sender).parent().addClass("selected");

//    player.sendEvent('LOAD', { 'file': stream, 'type': 'rtmp', 'streamer': 'rtmp://pulsenet.mpl.miisolutions.net/pulsenet-live01' });
//    player.sendEvent('PLAY');
//}
// ----------------- end mulitlple bit rate functions -----------------

// ----------------- live player streaming functions -----------------
// ----------------- MOVED TO PLAYER PAGE -----------------
//function addListeners() {
//    if (player) {
//        player.addModelListener("STATE", "stateListener");
//    } else {
//        setTimeout("addListeners()", 100);
//    }
//}

//function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
//    currentState = obj.newstate;
//    previousState = obj.oldstate;
//    //JW Player 5
//    //if ((currentState == "COMPLETED") && (previousState == "IDLE")) {
//    //JW Player 4
//    if ((currentState == "COMPLETED") && (previousState == "PLAYING")) {
//        commercialEnd(cid);
//        //highwinds
//        //player.sendEvent('LOAD', { 'file': 'http://hwcdn.net/k6m9d6f6/fls/224359-Pulse350.smil', 'provider': 'highwinds' });
//        player.sendEvent('LOAD', { 'file': 'myStream', 'type': 'rtmp', 'streamer': urlFeed });
//        player.sendEvent('PLAY');
//        intIntervalCommercial = setInterval(function () { getCommercialInfo(eid, cid); }, 2000);
//    }
//}
// ----------------- live player streaming functions -----------------


// ----------------- testing functions -----------------
function stopTimer() {
    clearInterval(intInterval);
    clearInterval(intTntervalShow);
    clearInterval(intIntervalCommercial);
}
// ----------------- end testing functions -----------------














