﻿// THIS FILE IS EXACTLY THE SAME AS OF RADIOMUSIC AND RADIOSALSA4TE

////--------------------------------------------- regia update

function StartRegiaUpdate(_kbps, _channel, _autoResizePopUp)
{
    // stop currently running routine (if any)
    
    if (intervalID != null)
        clearInterval(intervalID);

    // set main parameters
    
    kbps = _kbps;
    regiaUrl = "regia" + _channel + ".txt";
    autoResizePopUp = _autoResizePopUp;
    AlbumPicturesUrl = "Images/AlbumPictures/" + _channel + "/";
    defaultAlbumPicture = "Logo" + _channel + ".jpg";
    
    // set stream delay (it depends on stream speed, the following delay figures have been accurately chosen)
    
    if (kbps == "32")   // 32Kbps branch
    {
        fillDelay = 36;
        fetchInterval = 36;
    }
    else                // 128Kbps branch
    {
        fillDelay = 10;
        fetchInterval = 10;
    }

    // update immediately (the flag will be set to false by fillPlaylist())
    
    updateImmediatelyFlag = true;
    regiaUpdate();
    
    // start update routine
    
    setTimeout(auxStart, 2000);
}

var intervalID = null;

function auxStart()
{
    intervalID = setInterval(regiaUpdate,1000);
}

//// main parameters

var kbps;
var regiaUrl;
var autoResizePopUp;
var AlbumPicturesUrl
var defaultAlbumPicture

//// set the following flag to true to fetch-and-fill immediately

var updateImmediatelyFlag; 

//// regia update delay

var fillDelay;
var fetchInterval;

//// dispatch logic

var secs;   // remaining time to update
var toggle; // 0 -> fetch regia, 1-> fill playlist

function regiaUpdate()
{
    var traceNextAction = document.getElementById("pltraceNextAction");
    var traceRemaining = document.getElementById("pltraceRemaining");
    
    if (updateImmediatelyFlag)
    {
        fetch_regia();

        toggle = 0;
        if (traceNextAction != null)
            traceNextAction.innerHTML = "fetching regia in";
        secs = fetchInterval;
    }
    else
    {
        secs--;    

        if (secs < 0)
        {
            if (toggle == 0)
            {
                fetch_regia();
                toggle = 1;
                if (traceNextAction != null)
                    traceNextAction.innerHTML = "filling playlist in";
                secs = fillDelay;               
            }
            else
            {
                fillPlaylist();
                toggle = 0;
                if (traceNextAction != null)
                    traceNextAction.innerHTML = "fetching regia in";
                secs = fetchInterval;
            }        
        }
    }

    if (traceRemaining != null)
        traceRemaining.innerHTML = secs;    
}

//// fetch regia.xml from server

var req = false;

function fetch_regia()
{
    req = false;
    
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
	        req = new XMLHttpRequest();
        } catch(e) {
	        req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
	        req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
	        try {
  		        req = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch(e) {
  		        req = false;
	        }
        }
    }
    
    // send request
    if(req) {
        req.open("GET", regiaUrl + "?sid=" + Math.random(), true);
        req.onreadystatechange = fetch_callback;
        req.send("");
    }
}

function fetch_callback()
{
    // only if req shows "loaded"
    if (req.readyState == 4)
    {
        var traceStatus = document.getElementById("pltraceStatus");

        if (req.status == 200)
        {   
            if (traceStatus != null)
                traceStatus.innerHTML = "regia fetched";
                
            if (updateImmediatelyFlag)
            {
                updateImmediatelyFlag = false;
                fillPlaylist();
            }
        }    
        else
        {   
            if (traceStatus != null)
                traceStatus.innerHTML = "could not fetch regia";
        }
    }
}

//// fill in the playlist

function fillPlaylist()
{
    var regiaText = req.responseText;
    
    //var regiaXML = req.responseXML;
    
    try
    {
        //-- Get regia root nodes --//
        
        var history = null;
        var queue = null;

        var splits = regiaText.split("##########");

        if (splits[0] != "")
            history = splits[0].split("a@@@@@@@@z");

        if (splits[1] != "")
            queue = splits[1].split("a@@@@@@@@z");

        //var history = regiaXML.getElementsByTagName("history")[0];
        //var queue = regiaXML.getElementsByTagName("queue")[0];

        var title;              // titolo della canzone
        var artist;             // artista
        var picture;            // immagine
        var duration = -1;      // durata
        var songSchedule = -1;  // ora d'inizio della prossima canzone
        
        var pltraceStatusMsg = ""; // debugging message

        //-- NOW PLAYING --//
        
        var nowPlayingWrapperDiv = document.getElementById("nowPlayingWrapper");
        if (nowPlayingWrapperDiv == null)
            pltraceStatusMsg += "nowPlayingWrapper block not found in aspx; ";
        else        
        { 
            if (history==null)
            {
                nowPlayingWrapperDiv.style.display = "none";
                pltraceStatusMsg += "history info not found in regia; ";
            }
            else if (history.length!=5)
            {
                nowPlayingWrapperDiv.style.display = "none";
                pltraceStatusMsg += "unrecognized format of history info in regia; ";
            }
            else            
            {   
                title = history[0];
                artist = history[1];
                duration = history[3];
                picture = history[4];                
                
                try
                {   
                    var played = history[2].substring(history[2].indexOf(" ")+1);
                    songSchedule = str2sec(played) + str2sec(duration);
                }
                catch(e)
                {
                    songSchedule = -1;
                    duration = -1;
                }

                //var played = currentSong.getAttribute("played").substring(played.indexOf(" ")+1);
                //var duration = currentSong.getAttribute("duration");
                //var picture = currentSong.getAttribute("picture");
                //var title = currentSong.getAttribute("title");
                //var artist = currentSong.getAttribute("artist");

                document.getElementById("title_current").innerHTML = title;
                document.getElementById("artist_current").innerHTML = artist;
                var img = document.getElementById("picture_current");
                if (img != null)
                {
                    if (picture != "")
                    {
                        img.src = AlbumPicturesUrl + picture;
                        //img.style.display = "block";
                    }
                    else
                        img.src = AlbumPicturesUrl + defaultAlbumPicture;
                        //img.style.display = "none";
                }

                nowPlayingWrapperDiv.style.display = "block";            
                pltraceStatusMsg += "now playing filled in; ";
            }
        }
        
        // COMING UP
        var comingUpWrapperDiv = document.getElementById("comingUpWrapper");
        if (comingUpWrapperDiv == null)
            pltraceStatusMsg += "comingUpWrapper block not found in aspx page; ";
        else
        {      
            if (queue==null)
            {
                comingUpWrapperDiv.style.display = "none";
                pltraceStatusMsg += "queued song elements not found in regia; ";
            }
            else if ((queue.length-1)%4 != 0)
            {
                comingUpWrapperDiv.style.display = "none";
                pltraceStatusMsg += "unrecognized format of queue info in regia; ";
            }            
            else            
            {                        
                var maxQueueLength = document.getElementById("maxQueueLength").value;

                var i=0;
                var iok = 0;
                                
                while(i*4<queue.length-1 && iok<maxQueueLength)
                {   
                    title = queue[i*4];
                    artist = queue[i*4 + 1];
                    picture = queue[i*4 + 3];
                    
                    if (songSchedule != -1)                    
                    {
                        try
                        {   
                            duration = str2sec(queue[i*4 + 2]);
                        }
                        catch(e)
                        {
                            songSchedule = -1;
                            duration = -1
                        }
                    }       
                                                   
                    if ((duration > 60) || (songSchedule == -1))
                    {
                        divTitle = document.getElementById("title_" + iok);
                        divArtist = document.getElementById("artist_" + iok);
                        divSchedule = document.getElementById("schedule_" + iok);

                        divTitle.innerHTML = title;
                        divArtist.innerHTML = artist;

                        if (songSchedule!=-1)
                        {
                            divSchedule.innerHTML = sec2str(songSchedule);                    
                            songSchedule += duration;                    
                        }
                        else
                            divSchedule.innerHTML = "-:-";                        

                        divRow = document.getElementById("row_" + iok);
                        divRow.style.display = "block";
                        
                        iok++;
                    }

                    i++;
                }

                if (iok!=0)
                    pltraceStatusMsg += "queue filled in; ";
                else
                    pltraceStatusMsg += "no songs to display in queue found in xml file; ";
                
                while(iok<maxQueueLength)
                {
                    divRow = document.getElementById("row_" + iok);
                    divRow.style.display = "none";
                    iok++;
                }

                comingUpWrapperDiv.style.display = "block";
            }
        }

        // trace operation    
        traceStatus = document.getElementById("pltraceStatus");
        if (traceStatus!=null)
            traceStatus.innerHTML = pltraceStatusMsg;
    }
    catch (e)
    {    
        // trace unsuccessful operation    
        traceStatus = document.getElementById("pltraceStatus");
        if (traceStatus!=null)
            traceStatus.innerHTML = pltraceStatusMsg + "Exception: " + e;            
    }

    // Resize popup window
    // resize window if the player is opened in a pop up

    if (autoResizePopUp == true)
    {
        PopUpResize();   
        setTimeout(PopUpResize,500); 
    }
}

function PopUpResize()
{
    // PlayerMini.aspx?resizePopUp=true
    var ok = getQueryParameter("resizePopUp");
    
    if (ok != null)
    {
        dynamicWidth = document.getElementById("PlaylistWrapper").clientWidth;
        dynamicHeight = document.getElementById("PlaylistWrapper").clientHeight;

        var browser=navigator.appName;
        if (browser=="Microsoft Internet Explorer")
            window.resizeTo(dynamicWidth,dynamicHeight+118);   
        else if (browser=="Netscape")
            window.resizeTo(dynamicWidth+16,dynamicHeight+95);
        else
            window.resizeTo(dynamicWidth+16,dynamicHeight+95);
    }
}

////--------------------------------------------- utilities functions

function sec2str(sec)
{
    var hh = Math.floor(sec/3600) % 24;
    sec = sec % 3600;

    var mm = Math.floor(sec/60)
    sec = sec % 60;

    //return hh + "." + (mm <= 9 ? "0" + mm : mm) + "." + (sec <= 9 ? "0" + sec : sec);
    return hh + ":" + (mm <= 9 ? "0" + mm : mm);
}

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]);
        mm = parseInt(splits[1]);
        ss = parseInt(splits[2]);
    }
    // mm:ss
    else
    {
        hh = 0;
        mm = parseInt(splits[0]);
        ss = parseInt(splits[1]);
    }
    
    return hh*3600 + mm*60 + ss;
}

////------------------------------------------------------ MixStream flash player


////------------------------------------------------------ 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);
*/

