DynWrite = function(id, string)
{
    document.getElementById(id).innerHTML = string;
}

function TWidgetDisplay()
{
    var isPageLoaded    = false;
    var adAreaBusy      = false;
    var coverPicStatus  = 0; //0=nothing, 1=loading, 2=ready
    var noSilverLight   = false;

    this.cbVideoBegin = function(type, args, me)
    {
        adAreaBusy = true;
        setVisibility('idCoverAd', false);
        setVisibility('idTextAd', false);
    }

    this.cbVideoEnd = function(type, args, me)
    {
        adAreaBusy = false;
    }

    this.cbRestore = function(type, args, me)
    {
        adAreaBusy = false;

        //Must we display cover pic?
        if(coverPicStatus==2)
            this.ShowCoverPic();
        //Otherwise, show banners if cover pic is not loading
        else if(coverPicStatus==0)
           this.ShowCoverAd();
    }

    this.cbStationData = function(type, args, me)
    {
        var station = args[0];
        DynWrite('idStationName', station['name']);
    }

    this.cbDisplayMedia = function(type, args, me)
    {
        var media = args[0];

        if (typeof(media['artist']) != 'undefined') DynWrite('idArtist',media['artist']);
        else DynWrite('idArtist', '');
        if (typeof(media['title']) != 'undefined') DynWrite('idTitle',media['title'] + ' (' + media['mmss'] +')');
        else DynWrite('idTitle', 'No information available');

        DynWrite('idBuyLink_href','Buy Track');
        document.getElementById('idBuyLink_href').href = media['buycd'];
        setVisibility('idBuyLink', true);

        coverPicStatus = 0;
        setVisibility('idCoverPic',false);
        if((media['picture']!=null) && (media['picture']!='') && (media['picture'].indexOf("://")!=-1))
        {
            var imgCoverPic = document.getElementById('imgCoverPic');
            imgCoverPic.src = media['picture'];
            imgCoverPic.title = media['artist']+' - '+media['title'];
            coverPicStatus = 1;
        }
        else
        {
            this.ShowCoverAd();
        }
    }

    this.cbDisplayAds = function(type, args, me)
    {
        var ad = args[0];

        DynWrite('idArtist','Commercial Break');
        DynWrite('idTitle',ad['title']);

        if(ad['clickurl']!=null && ad['clickurl']!='')
        {
            DynWrite('idBuyLink_href','Click to visit Sponsor');
            document.getElementById('idBuyLink_href').href = ad['clickurl'];
            setVisibility('idBuyLink', true);
        }
        else setVisibility('idBuyLink', false);

        //Hide banner/text-ad areas
        setVisibility('idCoverAd', false);
        setVisibility('idTextAd', false);
        setVisibility('idCoverPic',false);

        //See if we can display new Banner/Text-ads
        //Since we share the same area with the video ads
        //we can only do so if no video is being displayed
        if(ad['hasvideo']!='yes')
        {
            if(ad['coverID']>0)
            {
                adAreaBusy = true;
                setVisibility('idCoverAd', true);
                doitall.streamads.DisplayInID(document.getElementById('idCoverAd'), ad, 'cover');
            }
            else if(ad['textID']>0)
            {
                adAreaBusy = true;
                setVisibility('idTextAd', true);
                doitall.streamads.DisplayInID(document.getElementById('idTextAd'), ad, 'text');
            }
        }
    }

    this.cbPlayerLoaded = function(type, args, me)
    {
        //Resize player to make up the difference in size between WMP and Silverlight player controls
        if(doitall.player.isControllable() && doitall.player.getPlayer().getContextName()!='TWMPlayer')
        {
            doitall.player.setSize(doitall.player.width, 50);
        }

        if(doitall.player.isControllable())
        {
            //Open player
            //doitall.player.Open('http://wm5.spacialnet.com/science1/canned/canned-localmedia-v4.wma');
            //doitall.player.mediaurl
        }
        else
        {
            //Show Silverlight Message
            noSilverLight = true;
            this.showSilverLightWarning();

            //TODO: Re-create WMP player with auto-start enabled
        }

        //Hide initial loading page
        doitall.player.onBuffering.fire(100);
    }

    this.cbBuffering = function(type, args, me)
    {
        var bufferProgress = args[0];
        DynWrite('idStatus','Buffering ('+bufferProgress+'%)');
        setVisibility('idStatusRow',(bufferProgress!=100));

        if (bufferProgress == 100 && noSilverLight) this.showSilverLightWarning();
    }

    this.cbNoGateway = function()
    {
        this.ShowCoverAd();
    }

    this.ShowCoverAd = function()
    {
        //Hide banner/text-ad areas
        setVisibility('idTextAd', false);
        setVisibility('idCoverPic',false);

        //Show cover ad area
        setVisibility('idCoverAd', true);
        var idCoverAd = document.getElementById('idCoverAd');
        idCoverAd.innerHTML = '<iframe src="http://sa-m.streamads.com/view?t=b&pid='+doitall.publisherID+'&o=html&zid=2&bs=300,250&ct=_blank" width="300" height="250" frameborder="0" scrolling="no" allowtransparency="true"></iframe>';
    }

    this.ShowCoverPic = function()
    {
        if(!adAreaBusy)
        {
            //Hide all advertisement areas
            setVisibility('idCoverAd', false);
            setVisibility('idTextAd', false);

            //Show cover picture
            setVisibility('idCoverPic',true);
        }
        else
        {
            //If ad is busy, then we have to wait for cbRestore
            coverPicStatus = 2; //If ad is busy, then we have to wait for cbRestore
        }
    }

    this.showSilverLightWarning = function()
    {
        document.getElementById('idStatusRow').innerHTML = "<a href='http://www.microsoft.com/silverlight/install.aspx' target='_blank'>Install <b>Silverlight</b> for a better experience!</a>";
        setVisibility('idStatusRow', true);
    }
}


//##############################################################################
function TPlayerWidget()
{
    this.pid = 0;
    this.sid = 0;
    this.mediaURL = null;
    this.useGateway = true;
    this.useSC = false;
    this.stationName = null;
    this.stationCoverPicURL = null;
    this.displayWidget = null;
    this.testingPhase = false;


    //## PUBLIC METHODS
    this.loadWidget_HTML = function()
    {
        if(this.sid<=0) { this.widgetError('SpacialNet/AudioRealm Station SID not specified.'); return false; }
        if(this.pid<=0) { this.widgetError('StreamAds Station PID not specified.'); return false; }

        var widgetHTML = '<div id="idPlayerWidget"><div id="idStationName">Loading station...</div><div id="idNowPlaying"><div id="idArtist">Please wait.</div><div id="idTitle">Stream will start shortly...</div><div id="idBuyLink"><a id="idBuyLink_href" href="#" target="_blank">Buy</a></div></div><div id="idPlayerSpace"></div><div id="idCoverArea" style="width: 320px; height: 250px;"><div style="display:none;" id="idCoverAd"></div><div style="display:none;" id="idTextAd"></div><div style="display:none;" id="idCoverPic"><img id="imgCoverPic" onload="ShowCoverPic();" onerror="ShowCoverAd();"></div><div id="idVideoArea"></div></div><div id="idStatusRow"><img id="idStatusImg" src="http://media.streamads.com/playersdk/v2/widgets/webplayer/widget1/images/loader-transparent.gif" align="absmiddle"><span id="idStatus">Loading ...</span></div></div>';
        document.write(widgetHTML);

        // Subscribe to onConfigure so that we can do configuration as soon as DOM is ready
        doitall.onConfigure.subscribe(this.doWidgetConfigure, this, true);

        // We call init to set up doitall and prepare the onConfigure event
        doitall.init();

        return true;
    }

    this.loadWidget_ASX = function(idWMPlayer)
    {
        isASX = true;
        internalPlayer = idWMPlayer;
        return this.loadWidget_HTML();
    }

    //## PRIVATE VARIABLES
    var isASX = false;
    var internalPlayer = null;

    //## PRIVATE METHODS
    this.widgetError = function(msg) { document.write('<font color="maroon">Error loading widget:</font> '+msg+'<br />'); }

    this.doWidgetConfigure = function()
    {
        this.InitializeWidget();
    }

    this.InitializeWidget = function()
    {
        this.displayWidget = new TWidgetDisplay();

        doitall.publisherID = this.pid;
        doitall.stationID = this.sid;
        doitall.player.mediaurl = this.mediaURL;
        doitall.useWMPOnChrome = this.useSC; //Use only if SHoutcast station!!
        doitall.useGateway = this.useGateway;

        if(this.testingPhase)
        {
            if(typeof(AdSense)!='undefined') AdSense.testingPhase = true;
            if(typeof(Lint)!='undefined') Lint.debugMode = true;
        }

        //Turn on all features we wish to use
        doitall.useDataPoller = true;
        doitall.useLocalMedia = true;

        //Turn off features we do not use
        doitall.preloadHistory = false; //We have no history display

        //Subscribe to events
        doitall.onMedia.subscribe(this.displayWidget.cbDisplayMedia, this.displayWidget, true);
        doitall.onAds.subscribe(this.displayWidget.cbDisplayAds, this.displayWidget, true);
        doitall.onStationData.subscribe(this.displayWidget.cbStationData, this.displayWidget, true);
        doitall.onRestore.subscribe(this.displayWidget.cbRestore, this.displayWidget, true);
        doitall.onVideoBegin.subscribe(this.displayWidget.cbVideoBegin, this.displayWidget, true);
        doitall.onVideoEnd.subscribe(this.displayWidget.cbVideoEnd, this.displayWidget, true);
        doitall.player.onLoaded.subscribe(this.displayWidget.cbPlayerLoaded, this.displayWidget, true);
        doitall.player.onBuffering.subscribe(this.displayWidget.cbBuffering, this.displayWidget, true);
        Gateway.onNoGateway.subscribe(this.displayWidget.cbNoGateway, this.displayWidget, true);

        //Register advertisement areas
        doitall.RegisterVideoArea('idVideoArea');

        //Load hard-coded station information
        if(this.stationName!=null)
        {
            doitall.loadStationInfo = false;
            var myStationData = {"name": this.stationName, "webpicturedir": this.stationCoverPicURL }
            if(typeof(dpStationInfoCallback)=="function") dpStationInfoCallback(myStationData);
        }
        else doitall.loadStationInfo = true;

        //Initialize external specified params
        this.InitParams();

        //If we are running inside ASX's HTMLView
        if(isASX)
        {
            //Avoid VISTA silence bug! And set other ASX specific behaviour
            doitall.isASX = true;

            //Hide Player Space as we won't be using it
            setVisibility('idPlayerSpace', false);

            //Attach player
            var wmplayer = new TWMPlayer();
            wmplayer.attachPlayer(internalPlayer);
            doitall.player.attachPlayer(wmplayer);
        }
        //Normal HTML page
        else
        {
            //Player settings
            doitall.RegisterPlayerSpace('idPlayerSpace');
            doitall.player.width = 320;
            doitall.player.height = 45;
            doitall.player.showcontrols = true;
            doitall.player.autostart = true;
        }
    }

    this.InitParams = function()
    {
        var params = ParseQueryStr();

        //Custom Media URL
        if((params['url']!=null) && (params['url']!=''))
        {
            doitall.player.mediaurl = params['url'];
        }

        //Specify if we have Shoutcast streams (So we can properly handle Chrome support)
        if((params['useSC']!=null) && (params['canned'].toLowerCase()=="y"))
        {
            //Use only if SHoutcast station!!
            doitall.useWMPOnChrome = true;
        }

        //Canned demo settings
        if((params['canned']!=null) && (params['canned'].toLowerCase()=="y"))
        {
            doitall.stationID = 61540;
            doitall.publisherID = 13100;
            doitall.player.mediaurl = 'http://wm5.spacialnet.com/science1/canned/canned-ps-a.wma';

            doitall.loadStationInfo = false;
            doitall.preloadHistory = false;
            doitall.useDataPoller = false;
            doitall.timeoutPadding = 5000;

            //Custom station data
            var mydata = {"name":"Player Demo Station","description":"Top Hits from around the world","website":"http://www.audiorealm.com","image":"http://media.streamads.com/playersdk/v2/widgets/webplayer/arplayer/canned/logo.png","genres":"Pop,Rock,Alternative","webpicturedir":"http://media.streamads.com/playersdk/v2/widgets/webplayer/arplayer/canned/"}
            if(typeof(dpStationInfoCallback)=="function") dpStationInfoCallback(mydata);
        }
    }
}
var playerWidget = new TPlayerWidget();
function ShowCoverPic() { playerWidget.displayWidget.ShowCoverPic(); }
function ShowCoverAd() { playerWidget.displayWidget.ShowCoverAd(); }
