/*
 *  (c) Copyright 2005
 *      Broadcast Electronics 
 *      All rights reserved.
 */

//=============================================================================================
//                  SoniXtream Library
//=============================================================================================

// TODO: dynamically set
// SESSION_PING_URL
// AD_SERVER
// COVERART_SERVER
// TUNER_ID
// ROOT_URL
// sessionPingMod
// channel_list

function SoniXtreamProperties() {
    this.Clear = SoniXtreamProperties_Clear;

    this.Clear();
}

function SoniXtreamProperties_Clear() {
    this.Title = "";
    this.Artist ="";
    this.Duration = 0;
    this.CoverArt = "";
    this.adURL = "";
    this.ecommerceURL = "";
    this.Category = "";
    this.SegmentTitle = "";
    this.isAd = false;
    this.unknownEventType = "";
    this.unknownEventData = "";
}

function SoniXtream(station, format) {
    this.StationName = station;
    this.StationDescription = "";
    this.StationURL = "";
    this.Channels = new Array();

    this.NowPlaying = new SoniXtreamProperties();
    this.NextSong = new SoniXtreamProperties();
    this.Commercial = new SoniXtreamProperties();

    this.Close = SoniXtream_Close;
    this.Ping = SoniXtream_Ping;
    this.SelectChannel = SoniXtream_SelectChannel;
    this.WM_Event = SoniXtream_WM_Event;
    this.WM_CurrentItemChanged = SoniXtream_WM_CurrentItemChanged;
    this.WM_Playing = SoniXtream_WM_Playing;

    // private stuff
    this.sessionPingTimer = -1;
    //this.sessionPingMod = xxx
    //insert [sessionPing] image

    SoniXtream_LoadChannelInfo(this, SNXChannelInfo);
    this.SelectChannel(format);
    this.sessionPingTimer = setInterval(this.Ping, 300000);
}

function SoniXtream_Close() {
    var elem = document.images["sessionPing"];
    if (elem) elem.src = SESSION_PING_URL + "?tunerId=" + TUNER_ID + "&aff=" + aff_alias + "&f=" + format_alias + "&cmd=close";
    if (this.sessionPingTimer != -1)
        clearInterval(this.sessionPingTimer);
    this.sessionPingTimer = -1;
}

function SoniXtream_Ping() {
    if((this.sessionPingNo % sessionPingMod)== 0) {
        var cbt = new Date();
        cbt = cbt.getTimezoneOffset() + cbt.getTime();
        // Keep Alive ping for the clamp
        var elem = document.images["sessionPing"];
        if (elem) elem.src = SESSION_PING_URL + "?tunerId=" + TUNER_ID + "&aff=" + aff_alias + "&f=" + format_alias + "&cmd=update&u=" + String(cbt);
        this.sessionPingNo = 1;
    } else {
        this.sessionPingNo = this.sessionPingNo + 1;
    }
}

function SoniXtream_SelectChannel(channelName) { // TODO: this is not channel name right now
    debugOutput(2, "SelectChannel:" + channelName);
    for (i = 0; i < this.Channels.length; i++) {
        if (this.Channels[i].Name == channelName) {
	    this.Channel = this.Channels[i];
	    return this.Channel.Url;
	}
    }

    return null;
}

function SoniXtream_WM_Playing(v) {
    playStateChanged(v);
}

function SoniXtream_WM_Event(evType, evData) {
    if (debugLevel >= 2) debugOutput(2, "WM_Event " + evType + ":" + evData);
    evType = evType.toLowerCase();
    var args;

    if (evType == "alert") {
        args = new SoniXtreamProperties();
        args.Title = evData;
        TunerEvent(this, "alert", args);
    } else if (evType == "reload") {
        TunerEvent(this, "reload", new SoniXtreamProperties);
    } else if (evType == "prebufferad") {
        args = new SoniXtreamProperties();
        args.Duration = evData;
        TunerEvent(this, "preBufferAd", args);
    } else if (evType == "playad") {
        args = new SoniXtreamProperties();
        args.Duration = evData;
        TunerEvent(this, "playAd", args);
        this.Ping();
    } else if (evType == "preBufferadbreak") {
        args = new SoniXtreamProperties();
        args.Duration = evData;
        TunerEvent(this, "preBufferAdBreak", args);
    } else if (evType == "playadbreak") {
        args = new SoniXtreamProperties();
        args.Duration = evData;
        TunerEvent(this, "playAdBreak", args);
    } else if (evType == "tuner") {
        var dataArr = evData.split("|");
        if (dataArr.length >= 3) {
            var evStr = dataArr[0];
            //code = dataArr[1];

            switch (evStr) {
                case "NextEvent": args = this.NextSong; break;
                case "CurrentEvent": args = this.NowPlaying; break;
                case "Commercial": args = this.Commercial; break;
                default: args = new SoniXtreamProperties(); break;
            }

            args.Artist = dataArr[2];
            args.Title = dataArr[3];
            args.CoverArt = dataArr.length > 3 ? dataArr[4] : "";
            args.CoverArt = cleanupCoverArt(args.CoverArt, false);

            args.adURL = "";    // GetCurrentLink
            args.ecommerceURL = ""; // GetCurrentURL
            args.isAd = false;

            // grab named arguments
            for (i = 5; i < dataArr.length; i++) {
                var sep = dataArr[i].indexOf("=");
                // if equal sign is present and not first character
                if (sep > 0) {
                    var name = dataArr[i].substring(0, sep);
                    var value;
                    if (sep < (dataArr[i].length - 1))
                        value = dataArr[i].substring(sep + 1);
                    args[name] = value;
                }
            }

            switch (evStr) {
                case "NextEvent":
                    TunerEvent(this, "nextSong", args);
                    break;
                case "CurrentEvent":
                    TunerEvent(this, "nowPlaying", args);
                    this.Ping();
                    break;
                case "Commercial":
                    TunerEvent(this, "commercial", args);
                    this.Ping();
                default:
                    TunerEvent(this, evStr, args);
                    break;
            }
        } else {
            switch (evStr) {
                case "NextEvent": break;
                case "CurrentEvent": break;
                default:
                    TunerEvent(this, evData, args);
                    break;
            }
        }
    } else {
        args = new SoniXtreamProperties();
        args.unknownEventType = evType;
        args.unknownEventData = evData;
        TunerEvent(this, "unknown", args);
    }
}

function cleanupCoverArt(s,removeParams)
{
    if (s == null) s = "";

    // trim whitespace
    var x = s;
    x = x.replace(/^\s*/, "");
    x = x.replace(/\s*$/, "");

    // remove parameters
    if (removeParams) {
        var paramChar = x.indexOf("?");
        if (paramChar != -1)
            x = x.substring(0, paramChar);
    }

    // supply default URL
    if ((x != "") && (x.indexOf("http://") == -1))
        x = COVERART_SERVER + "/" + x

    return x;
}

function SoniXtream_WM_CurrentItemChanged(player, curMedia)
{
    debugOutput(2, "WM_CurrentItemChanged");
    var curMedia = player.currentMedia;
    if (curMedia != null) {
        var h = curMedia.getItemInfo("Sonixtream/VideoHeight");
        var w = curMedia.getItemInfo("Sonixtream/VideoWidth");
	if ((h > 0) && (w > 0))  {
	    player.style.height = h;
	    player.style.width = w;
	    player.style.visibility = "visible";
	} else {
	    player.style.visibility = "hidden";
	    player.style.height = 0;
	    player.style.width = 0;
	}
        this.NowPlaying.Title = curMedia.getItemInfo("Title");
        if (this.NowPlaying.Title == "getad") this.NowPlaying.Title = "";

        this.NowPlaying.Artist = curMedia.getItemInfo("Author");

        this.NowPlaying.CoverArt = curMedia.getItemInfo("CoverArt");
        if (this.NowPlaying.CoverArt == "") this.NowPlaying.CoverArt = curMedia.getItemInfo("Copyright");
        this.NowPlaying.CoverArt = cleanupCoverArt(this.NowPlaying.CoverArt, true);

        this.NowPlaying.adURL = curMedia.getItemInfo("adURL");
        if (this.NowPlaying.adURL == "") this.NowPlaying.adURL = curMedia.getItemInfo("Description");
        if (this.NowPlaying.adURL == "NEWS") this.NowPlaying.adURL = curMedia.getItemInfo("Rating");

        this.NowPlaying.ecommerceURL = curMedia.sourceURL;

        this.NowPlaying.isAd = curMedia.getItemInfo("ad");
        this.NextSong.Artist = curMedia.getItemInfo("upNext");
    } else {
        this.NowPlaying.Clear();
        this.NextSong.Clear();
    }
    TunerEvent(this, "nowPlaying", this.NowPlaying);
    TunerEvent(this, "nextSong", this.NextSong);
}

function ChannelInfo(genre,name,desc,station)
{
    this.Genre = genre;
    this.Name = name;
    this.Description = desc;
    this.Url = PLG_SERVER + "?a=" + station + "&f=" + this.Name;
    this.Sponsor = AD_SERVER + "?scope=channel&site=" + station + "&format=" + this.Name;
}

function SoniXtream_LoadChannelInfo(snx,info)
{
    if (info.length == 0) return;

    var lastGenre = "";
    for (i = 0; i < info.length; i++) {
        var pieces = info[i].split('\t');
	snx.Channels[snx.Channels.length] = new ChannelInfo(pieces[0], pieces[2], pieces[1], snx.StationName);
    }
}

