﻿/* v 2.1 rev. a

- re-engineered fetch/publish process
- now you may specify the ajax request url and whether to invoke at that url the proxy service or not
- improved jquery element selection
- fixed parseInt base 10 bug
- -0:00 song duration (SAM) causes to publish -:-

*/

/* v 1.0.1

- added support for "__" songs
- fixed bug: when splits[1] was undefined then fillPlaylist was getting called each second

*/

/* v 1.0
*/
////--------------------------------------------- regia update

//// main options

var jPLogic =
{
    // for a single channel, denote the file regia<channelName>.txt (or regia.txt if <channelName>="")
    // to fetch through a direct ajax request or by invoking the proxy service (RegiaService.aspx?ch=<channelName>);
    // for multiple channels, you must invoke the proxy service to ask for the combined result of all channels,
    // i.e. RegiaService.aspx?ch=<channelName1>,<channelName2>&domain=proxyDomainURL
    channelNames: [ "" ],

    // URL to ask for regia contents.
    // A that url, you may ask for regia<channelName>.txt (or regia.txt if <channelName>="")
    // or you may invoke the proxy service to ask for the combined result of multiple channels.
    // e.g. http://www.radiomusic.net or 'localhost'
    ajaxRequestURL: "localhost",

    // Specify whether to fetch regia contents through the proxy service (RegiaService.apx).
    // Notice that through the proxy service you may ask for a single channel regia contents or the combined result of multiple channels.
    // Whereas through a direct ajax request you may ask for a single channel regia contents.
    useProxy: false,

    // Specify the url the proxy service will ask for regia files.
    // eg. http://www.radiomusic.net or 'localhost'
    proxyDomainURL: 'localhost',

    // SAM picture upload Host;
    // e.g. http://www.radiomusic.net or 'localhost'
    pictureHOST: 'localhost',        

    // SAM picture upload web directory;
    // if null, then it defaults to Images/AlbumPictures/<channelName>
    // or Images/AlbumPictures if <channelName>=""
    pictureDirectory: null,        

    // if null, it defaults to Logo<channelName>.jpg
    pictureDefault: null,        

    // specify maximum number of songs to be published in the coming up: 0 (no coming up), 1, 2, 3, ecc.
    maxQueue: 4,

    // source delay in seconds;
    // the following values might help:
    // 32 kbps -> 64 secs (32*64 = 2048), 96 kbps -> 18 secs, 128 kbps -> 16 secs (128*16 = 2048)
    sourceDelay: 16
}

//// private variables

var jPLogicPrivate =
{
    // regiaFetch() interval time (sec)
    regiaFetchIntervalTime: 16,

    // regiaFetch() interval ID
    regiaFetchIntervalID: null,
    
    // settings for the ajax request
    regiaAjaxSettings: null,
    
    // ajax request result
    fetchedData: null    
}

//// start update process

function StartRegiaUpdate()
{
    //-- stop currently running (if any) update process --//
    
    if (jPLogicPrivate.regiaFetchIntervalID != null)
        clearInterval(jPLogicPrivate.regiaFetchIntervalID);

    jPLogicPrivate.fetchedData = null;
    jPLogicPrivate.regiaFetchIntervalID = null;

    //-- prepare ajax request --//

    var requestURL = "";
    
    if (jPLogic.ajaxRequestURL != "localhost")
        requestURL = jPLogic.ajaxRequestURL + "/";

    // proxy service -> single or multi channel request
    if (jPLogic.useProxy)
    {
        requestURL += "RegiaService.aspx?ch=";
        
        for(var i=0; i<jPLogic.channelNames.length; i++)
            requestURL += jPLogic.channelNames[i] + (i < jPLogic.channelNames.length-1 ? "," : "");
            
        requestURL += "&domain=" + jPLogic.proxyDomainURL;
        
        if (jPLogic.channelNames.length > 1)
            requestURL += "&pcn=yes";
    }
    // direct ajax request for regia<channelName> file -> single channel request
    else
        requestURL += "regia" + jPLogic.channelNames[0] + ".txt";

    //alert(requestURL);
    
    jPLogicPrivate.regiaAjaxOptions =
    {
       type: "GET",
       url: requestURL,
       dataType : "text",
       cache: false,
       success: function (data) { regiaFetchSuccess(data) }//,
       //error: function (xmlHttpRequest, textStatus, errorThrown) { alert(errorThrown + ", " + xmlHttpRequest.status + ", " + xmlHttpRequest.statusText) }    
    };

    //-- update regia immediately, then start update routine --//

    regiaFetch();
    
    // start update routine
    
    setTimeout(
        function() { regiaFetchIntervalID = setInterval(regiaFetch, jPLogicPrivate.regiaFetchIntervalTime*1000); },
        5000);
}

function regiaFetch()
{
    $.ajax(jPLogicPrivate.regiaAjaxOptions);
}

function regiaFetchSuccess(data)
{
    // check contents
    
    if (data.indexOf("##########") == -1)
        return;

    // publish regia contents immediately
    if (jPLogicPrivate.fetchedData == null)
    {
        jPLogicPrivate.fetchedData = data;
        regiaPublish();
    }
    // publish delay
    else if (jPLogicPrivate.fetchedData != data)
    {
        jPLogicPrivate.fetchedData = data;
        var delay = jPLogic.sourceDelay*1000 - jPLogicPrivate.regiaFetchIntervalTime*1000;   
        if (delay <= 0)          
            regiaPublish();
        else
            setTimeout(regiaPublish, delay);
    }
}

function regiaPublish()
{   
    var fetchedData = jPLogicPrivate.fetchedData;

    if ((fetchedData == null) || (fetchedData == ""))
        return;    

    //-- Split regia contents into lines --//
    
    var linesAux = fetchedData.split(new RegExp("\n|\r"));
    var lines = new Array();

    var i=0;
    var j=0;
    
    // remove empty lines (for simplicity, we discard lines with less than 3 characters)
    for (; i<linesAux.length; i++)
        if(linesAux[i].length >= 3)
            lines[j++] = linesAux[i];

    // just in case
    if (lines.length == 0)
        return;

    //-- Parse lines --//

    // Remember that fetchedData may be the contents of a single regia<channelName>.txt file
    // or the combined result of multiple channels as obtained through the proxy service.
    // Moreover, regia contents may be introduced by <channelName>.
    // Look at RegiaService.aspx.cs to see the format of fetched data.
    
    i=0;
    j=0;
    
    for (; i < lines.length; j++)
    {
        var channelName = "";
        var pictureURL = "";
        var pictureDefault = "";
        
        // set channelName

        if (j < jPLogic.channelNames.length)
            channelName = jPLogic.channelNames[j];        
            
        // override channelName: regia may be introduced by its channelName

        if (lines[i].indexOf("##########") == -1)
            channelName = lines[i++];
        
        // set host picture url and default picture url
        
        if (jPLogic.pictureHOST != 'localhost')
            pictureURL = jPLogic.pictureHOST + "/";            
            
        if (jPLogic.pictureDirectory != null)
            pictureURL += jPLogic.pictureDirectory;
        else
        {
            if (channelName == "")
                pictureURL += "Images/AlbumPictures";
            else
                pictureURL += "Images/AlbumPictures/" + channelName;
        }
        
        if (jPLogic.pictureDefault != null)
            pictureDefault = jPLogic.pictureDefault;
        else
            pictureDefault = "Logo" + channelName + ".jpg";
    
        //-- Parse regia contents --//
    
        var regiaContents = lines[i++];
        
        var history = null;
        var queue = null;
        
        var splits = regiaContents.split("##########");

        // check contents
        if (splits[1] == undefined)
            continue;

        history = splits[0].split("a@@@@@@@@z");
        queue = splits[1].split("a@@@@@@@@z");

        var songTitle;              // titolo della canzone
        var songArtist;             // artista
        var songPicture;            // copertina
        var songDuration = Number.NaN;      // durata della canzone
        var songNext = Number.NaN;          // ora inizio della prossima canzone
            
        //-- ON AIR --//

        // Find html elements to update
        
        var j_onair_title;
        var j_onair_artist;
        var j_onair_picture;
        
        var jselector_suffix = "";

        // multiple channels request: each channel must have own html elements
        if (jPLogic.channelNames.length != 1)
            jselector_suffix = "_" + channelName;
        // single channel request: html elements might have or not channelName as suffix
        else if ($('#onair_title' + "_" + channelName).length != 0)
                jselector_suffix = "_" + channelName;

        j_onair_title = $('#onair_title' + jselector_suffix);
        j_onair_artist = $('#onair_artist' + jselector_suffix);
        j_onair_picture = $('#onair_picture' + jselector_suffix);
                
        // Update OnAir data
              
        if ((j_onair_title.length != 0) && (history.length == 5))
        {    
            songTitle = history[0];
            songArtist = history[1];
            songDuration = history[3];
            songPicture = history[4];                

            var blankSong = (songTitle == "__") && (songArtist == "__");

            // scheduled time
            
            try
            {   
                var played = str2sec(history[2].substring(11));  // skip date, eg. '23/09/2009 9.34.10'
                var duration = str2sec(songDuration);                
                
                if (duration == 0)
                    duration = Number.NaN;
                
                songNext = played + duration;
            }
            catch(e)
            {
                songNext = Number.NaN;
                songDuration = Number.NaN;
            }

            // special case: leave the row blank
            
            if (blankSong)
            { 
                songTitle = "";
                songArtist = "";
                songPicture = "";
            }

            // publish song information               
            
            j_onair_title.text(songTitle);
            j_onair_artist.text(songArtist);
            
            if (j_onair_picture.length != 0)
            {
                var fullPictureURL;
                if (songPicture != "")
                    fullPictureURL = pictureURL + "/" + songPicture;
                else
                    fullPictureURL = pictureURL + "/" + pictureDefault;

                j_onair_picture.attr("src", fullPictureURL);
            }
        }
        
        //-- COMING UP --//

        if ((jPLogic.maxQueue != 0) && (queue.length > 0) && ((queue.length-1)%4 == 0) )   // groups of 4 items
        {
                // Find html elements to update
        
                var jcuwrapper;
        
                // multiple channels request: each channel must have own html elements
                if (jPLogic.channelNames.length != 1)
                    jcuwrapper = $(".ComingUpWrapper." + channelName);
                // single channel request: just look for .ComingUpWrapper
                else 
                    jcuwrapper = $(".ComingUpWrapper");
                
                // Update data
            
                var iq = 0;     // index songs in queue
                var ip = 0;     // index published songs
                                
                for(; (iq*4 < queue.length-1) && (ip < jPLogic.maxQueue); iq++)
                {
                    // prepare data                
                
                    songTitle = queue[iq*4];
                    songArtist = queue[iq*4 + 1];
                    songPicture = queue[iq*4 + 3];
                    var songScheduleStr = "-:-";

                    blankSong = (songTitle == "__") && (songArtist == "__");

                    // special case: leave the row blank
                    
                    if (blankSong)
                    { 
                        songTitle = "";
                        songArtist = "";
                        songPicture = "";
                        songScheduleStr = "";
                    }
                    
                    // scheduled time
                    
                    if (!blankSong && !isNaN(songNext))                    
                    {
                        try
                        {   
                            songDuration = str2sec(queue[iq*4 + 2]);

                            if (songDuration == 0)
                                songDuration = Number.NaN;

                            songScheduleStr = sec2str(songNext);                    
                            songNext += songDuration;
                        }
                        catch(e)
                        {
                            songScheduleStr = "-:-";
                            songNext = Number.NaN;
                            songDuration = Number.NaN;
                        }
                    }       

                    // publish song information
                    if (songDuration > 45 || isNaN(songNext) || blankSong)
                    {                               
                        jcuwrapper.find(".title_" + ip).text(songTitle);
                        jcuwrapper.find(".artist_" + ip).text(songArtist);
                        jcuwrapper.find(".schedule_" + ip).text(songScheduleStr); 
                        jcuwrapper.find(".row_" + ip).show();
                        ip++;
                    }
                }
                            
                for(; ip < jPLogic.maxQueue; ip++)
                    jcuwrapper.find(".row_" + ip).hide();
        }
    }
}

////--------------------------------------------- utilities functions

function sec2str(sec)
{
    var hh = Math.floor(sec/3600) % 24;
    sec = sec % 3600;

    var mm = Math.floor(sec/60)
    sec = sec % 60;
    
    /* print hour and minutes */
    return hh + ":" + (mm <= 9 ? "0" + mm : mm);

    /* print hh:mm:ss
    return hh + ":" + (mm <= 9 ? "0" + mm : mm) + ":" + (sec <= 9 ? "0" + sec : sec);
    */

    /* print hh:mm:ss, omit hh if sec < 3600
    return (hh != 0 ? hh + ":" : "") + (mm <= 9 && hh != 0 ? "0" + mm : mm) + ":" + (sec <= 9 ? "0" + sec : sec);
    */
}

function str2sec(str)
{
    if (str.indexOf(".") != -1)
        splits = str.split(".");
    else
        splits = str.split(":");

    // hh:mm:ss
    if (splits.length == 3)
    {
        hh = parseInt(splits[0],10);
        mm = parseInt(splits[1],10);
        ss = parseInt(splits[2],10);
    }
    // mm:ss
    else if (splits.length == 2)
    {
        hh = 0;
        mm = parseInt(splits[0],10);
        ss = parseInt(splits[1],10);
    }
    else
        return Number.NaN;
    
    return hh*3600 + mm*60 + ss;
}

////------------------------------------------------------ WaveStreaming flash player

/*
    var rate = getQueryParameter("rate");
    var source = getQueryParameter("server");

    // WaveStreaming
    if (source == "WS")
    {
        host = "67.18.168.226";
        port = "6623";
        flashPlayerID = "12410889378";
    }
    // FreeStreamHosting
    else
    {
        host = "87.98.170.118";
        if (rate == "32")
        {
            port = "9028";
            playerID = "";
        }
        else
        {
            port = "8968";
            playerID = "12412121366"
        }
    }

    var params={};
    params.allowfullscreen="false";
    params.autostart="true";
    params.allowscriptaccess="always";

    var flashvars={};
    flashvars.usefullscreen="false";
    flashvars.skin="silverywhite.swf"; // "http://player.wavestreamer.com/cgi-bin/silverywhite/silverywhite.swf";
    flashvars.autostart="true";
    flashvars.file="http://"+host+":"+port+"/"+";stream.mp3&"+ playerID;
    
    var attributes={};
    attributes.id="player" + playerID;
    attributes.name="player" + playerID;

    swfobject.embedSWF("player.swf","playerPlaceHolder","340","54","9.0.0","expressInstall.swf", flashvars, params, attributes);
    // swfobject.embedSWF("http://player.wavestreamer.com/cgi-bin/player.swf","playerPlaceHolder","340","54","9.0.0","expressInstall.swf", flashvars, params, attributes);
*/




