﻿/// <reference name="MicrosoftAjax.js"/>
Type.registerNamespace("aorta.playmeweb.webcontrols");

aorta.playmeweb.webcontrols.Player = function() {
    aorta.playmeweb.webcontrols.Player.initializeBase(this);

    this._id = null;
    this._player = null;
    this._musica = null;
    this._status = null;
    this._volumeSize = 10;
    this._autoPlay = true;
    this._canal = null;
    this._timerID = null;
    this._logAcesso = null;
    this._tipoPlayer = null;
    this._erro = null;
    this._tempoChamadaPadrao = 60000;

    this._showMusicInfoDelegate = null;
    this._playDelegate = null;
    this._stopDelegate = null;
    this._statusChangedDelegate = null;
    this._playStateChangeDelegate = null;
    this._mensagemErro = null;

    this._obterInfoMusicaDelegate = null;
    this._obterUrlStreamDelegate = null;
    this._obterInfoMusicaSucessoCallbackDelegate = null;
    this._obterInfoMusicaFalhaCallbackDelegate = null;
    this._obterUrlStreamSucessoCallbackDelegate = null;
    this._obterUrlStreamFalhaCallbackDelegate = null;

    this._gravarLogAcessoDelegate = null;
    this._gravarLogSaidaDelegate = null;
    this._gravarLogAcessoSucessoCallbackDelegate = null;
}

aorta.playmeweb.webcontrols.Player.prototype = {
    initialize: function() {
        aorta.playmeweb.webcontrols.Player.callBaseMethod(this, 'initialize');

        this._registerObject();

        //Delegates para os eventos do player
        this._showMusicInfoDelegate = Function.createDelegate(this, this.showMusicInfoHandler);
        this._playDelegate = Function.createDelegate(this, this.playHandler);
        this._stopDelegate = Function.createDelegate(this, this.stopHandler);
        this._statusChangedDelegate = Function.createDelegate(this, this.statusChangedHandler);
        this._playStateChangeDelegate = Function.createDelegate(this, this._playStateChangeHandler);

        //Método para setar o state do player quando tiver tocando com o windows media player plugin
        if (this._player) {
            if (this._player.attachEvent)
                this._player.attachEvent('playStateChange', this._playStateChangeDelegate);
            else if (this._player.addEventListener)
                this._player.addEventListener('playStateChange', this._playStateChangeDelegate, false);
        }

        //Delegates para as ações internas do player
        this._obterInfoMusicaDelegate = Function.createDelegate(this, this._obterInfoMusicaHandler);
        this._obterUrlStreamDelegate = Function.createDelegate(this, this._obterUrlStreamHandler);

        //Delegates de retorno para as chamadas assíncronas aos webservices
        this._obterInfoMusicaSucessoCallbackDelegate = Function.createDelegate(this, this._obterInfoMusicaSucessoRetornoHandler);
        this._obterInfoMusicaFalhaCallbackDelegate = Function.createDelegate(this, this._obterInfoMusicaFalhaRetornoHandler);
        this._obterUrlStreamSucessoCallbackDelegate = Function.createDelegate(this, this._obterUrlStreamSucessoRetornoHandler);
        this._obterUrlStreamFalhaCallbackDelegate = Function.createDelegate(this, this._obterUrlStreamFalhaRetornoHandler);

        //Delegates para as ações de log de acesso
        this._gravarLogAcessoDelegate = Function.createDelegate(this, this._gravarLogAcessoHandler);
        this._gravarLogSaidaDelegate = Function.createDelegate(this, this._gravarLogSaidaHandler);
        this._gravarLogAcessoSucessoCallbackDelegate = Function.createDelegate(this, this._gravarLogAcessoSucessoCallbackHandler);

        //Sys.Application.add_init(this._gravarLogAcessoDelegate);
        Sys.Application.add_unload(this._gravarLogSaidaDelegate);

        if (this.get_autoPlay() == true) {
            this.play();
        }
    },

    dispose: function() {
        aorta.playmeweb.webcontrols.Player.callBaseMethod(this, 'dispose');

        //Sys.Application.remove_init(this._gravarLogAcessoDelegate);
        Sys.Application.remove_unload(this._gravarLogSaidaDelegate);
    },

    _setarPlayer: function(result) {
        this._player = result.ref;
    },

    _registerObject: function() {
        var divContent = document.createElement('div');
        divContent.id = this.get_id() + 'Content';
        document.body.appendChild(divContent);

        if (this.get_tipoPlayer() == "FlashPlayer") {
            if (swfobject.getFlashPlayerVersion().major == 0) {
                var noflash = document.createElement('div');
                noflash.id = "noflash";
                noflash.innerHTML = '<div id="myAlternativeContent" class="mensagemTop" ><a href="http://www.adobe.com/go/getflashplayer" target="_blank">Para ouvir esta rádio é necessário instalar o Flash Player. Clique aqui para instalar.</a></div>';
                document.body.appendChild(noflash);
            }
            else {
                var params = { quality: 'high', scale: 'noscale', wmode: 'transparent', allowscriptaccess: 'always', bgcolor: '#FFFFFF' };
                var flashvars = {};
                var attributes = { id: this.get_id() + 'Player' };
                swfobject.embedSWF(this.get_urlPlayer(), this.get_id() + 'Content', '1', '1', '10', this.get_urlExpressInstall(), flashvars, params, attributes, Function.createDelegate(this, this._setarPlayer));
            }
        }
        else {
            var so = new WMPObject('', this.get_id() + 'Player', '0', '0');
            so.addParam('AutoPlay', 'false');
            so.addParam('TransparentAtStart', '0');
            so.addParam('SendPlayStateChangeEvents', 'TRUE');
            so.addParam('ShowControls', '0');
            so.addParam('ShowDisplay', '0');
            so.addParam('autoStart', '0');
            so.addParam('autoSize', '0');
            so.addParam('uiMode', 'invisible');
            so.addParam('volume', '50');
            so.addParam('ShowStatusBar', '1');
            so.addParam('DisplayBackColor', 'red');
            so.write(this.get_id() + 'Content');
            this._player = $get(this.get_id() + 'Player');
        }
    },

    //##############################################################
    // Eventos
    //##############################################################

    add_showMusicInfo: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.showMusicInfo" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().addHandler('showMusicInfo', handler);
    },

    remove_showMusicInfo: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.showMusicInfo" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().removeHandler('showMusicInfo', handler);
    },

    add_play: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.play" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().addHandler('play', handler);
    },

    remove_play: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.play" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().removeHandler('play', handler);
    },

    add_stop: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.stop" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().addHandler('stop', handler);
    },

    remove_stop: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.stop" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().removeHandler('stop', handler);
    },

    add_statusChanged: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.statusChanged" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().addHandler('statusChanged', handler);
    },

    remove_statusChanged: function(handler) {
        /// <summary locid="E:J#aorta.playmeweb.webcontrols.Player.statusChanged" />
        var e = Function._validateParams(arguments, [{ name: "handler", type: Function}]);
        if (e) throw e;
        this.get_events().removeHandler('statusChanged', handler);
    },

    //##############################################################
    // Métodos Privados
    //##############################################################

    //Método para setar o state do player quando tiver tocando com o windows media player plugin
    _playStateChangeHandler: function(state) {
        switch (state) {
            case 1:
                this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.parado);
                break;
            case 3:
                this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.tocando);
                break;
            default:
                this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.carregando);
                break;
        }
    },

    _gravarLogAcessoHandler: function() {
        //(string idUsuario, string idCanal, string browserEVersao, string so)
        aorta.playmeweb.webcontrols.services.Player.GravarLogAcesso(this.get_ip(), this.get_canal(), this.get_browser(), this.get_so(), this._gravarLogAcessoSucessoCallbackDelegate);
    },

    _gravarLogAcessoSucessoCallbackHandler: function(logAcesso) {
        this.set_logAcesso(logAcesso);
    },

    _gravarLogSaidaHandler: function() {
        aorta.playmeweb.webcontrols.services.Player.RegistrarSaida(this.get_logAcesso());
    },

    _obterInfoMusicaHandler: function() {
        aorta.playmeweb.webcontrols.services.Player.ObterInfoMusica(this.get_canal(), this._obterInfoMusicaSucessoCallbackDelegate, this._obterInfoMusicaFalhaCallbackDelegate);
    },

    _obterInfoMusicaSucessoRetornoHandler: function(musica) {
        this._musica = musica;

        if (this._timerID)
            clearInterval(this._timerID);

        if (this._musica.OcorreuErro == true || this._musica.TempoProximaAtualizacao <= 0) {
            this._timerID = setInterval(this._obterInfoMusicaDelegate, this._tempoChamadaPadrao);
        }
        else {
            this._timerID = setInterval(this._obterInfoMusicaDelegate, this._musica.TempoProximaAtualizacao);
            this._showMusicInfoDelegate();
        }
    },

    _obterInfoMusicaFalhaRetornoHandler: function(erro, contexto, funcaoErro) {
        if (erro != null)
            Sys.Debug.trace('Ocorreu o seguinte erro na função \'' + funcaoErro + '\': ' + erro.get_message())

        //this._erro.show("Ops! Erro ao obter informações da música.");

        window.setTimeout(this._obterInfoMusicaDelegate, this._tempoChamadaPadrao);
    },

    _obterUrlStreamHandler: function() {
        aorta.playmeweb.webcontrols.services.Player.ObterUrlStream(this.get_canal(), this.get_tipoPlayer(), this._obterUrlStreamSucessoCallbackDelegate, this._obterUrlStreamFalhaCallbackDelegate);
    },

    _obterUrlStreamSucessoRetornoHandler: function(url) {
        this.get_player().tocar(url);
        this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.tocando);
        this._playDelegate();
    },

    _obterUrlStreamFalhaRetornoHandler: function(erro, contexto, funcaoErro) {
        if (erro != null)
            Sys.Debug.trace('Ocorreu o seguinte erro na função \'' + funcaoErro + '\': ' + erro.get_message())

        //this._erro.show("Ops! Erro ao obter o áudio.");

        window.setTimeout(this._obterUrlStreamDelegate, 60000);
    },

    _setStatus: function(status) {
        this._status = status;
        this._statusChangedDelegate();
    },
    //##############################################################
    // Métodos Públicos
    //##############################################################

    showMusicInfoHandler: function() {
        //chama os outros handlers caso tenha
        var handler = this.get_events().getHandler("showMusicInfo");
        if (handler) handler(this, Sys.EventArgs.Empty);
    },

    playHandler: function() {
        //chama os outros handlers caso tenha
        var handler = this.get_events().getHandler("play");
        if (handler) handler(this, Sys.EventArgs.Empty);
    },

    stopHandler: function() {
        //chama os outros handlers caso tenha
        var handler = this.get_events().getHandler("stop");
        if (handler) handler(this, Sys.EventArgs.Empty);
    },

    statusChangedHandler: function() {
        //chama os outros handlers caso tenha
        var handler = this.get_events().getHandler("statusChanged");
        if (handler) handler(this, Sys.EventArgs.Empty);
    },

    play: function() {
        if (this.get_player()) {
            this._obterInfoMusicaDelegate();
            this._obterUrlStreamDelegate();
            //registrar log
            this._gravarLogAcessoDelegate();
        }
    },

    stop: function() {
        if (this.get_player()) {
            this.get_player().parar();
            clearInterval(this._timerID);
            this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.parado);
            this._stopDelegate();
            //registrar saída
            this._gravarLogSaidaDelegate();
        }
    },

    volumeUp: function() {
        var curVolume = this.get_volume();
        var newVolume = (curVolume + this.get_volumeSize());
        newVolume = (newVolume < 100) ? newVolume : 100;
        this.set_volume(newVolume);
    },

    volumeDown: function() {
        var curVolume = this.get_volume();
        var newVolume = (curVolume - this.get_volumeSize());
        newVolume = (newVolume > 0) ? newVolume : 0;
        this.set_volume(newVolume);
    },
    //##############################################################
    // Propriedades
    //##############################################################
    get_status: function() {
        /// <value type="aorta.playmeweb.webcontrols.EstadoPlayer" locid="P:J#aorta.playmeweb.webcontrols.Player.status"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._status;
    },

    get_volume: function() {
        /// <value type="Number" locid="P:J#aorta.playmeweb.webcontrols.Player.volume"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this.get_player() ? this.get_player().getVolume() : 0;
    },
    set_volume: function(value) {
        //value = Number.parseInvariant(value);
        var e = Function._validateParams(arguments, [{ name: "value", type: Number}]);
        if (e) throw e;

        if (this.get_volume() == 0 && value > 0)
            this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.tocando);

        if (this.get_player())
            this.get_player().setVolume(value);

        if (this.get_volume() == 0)
            this._setStatus(aorta.playmeweb.webcontrols.EstadoPlayer.mudo);
    },

    get_player: function() {
        /// <value type="Object" locid="P:J#aorta.playmeweb.webcontrols.Player.player"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._player;
    },
    set_player: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", mayBeNull: true}]);
        if (e) throw e;
        this._player = value;
    },

    get_volumeSize: function() {
        /// <value type="Number" locid="P:J#aorta.playmeweb.webcontrols.Player.volumeSize"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._volumeSize;
    },
    set_volumeSize: function(value) {
        value = Number.parseInvariant(value);
        var e = Function._validateParams(arguments, [{ name: "value", type: Number}]);
        if (e) throw e;
        this._volumeSize = value;
    },

    get_autoPlay: function() {
        /// <value type="Boolean" locid="P:J#aorta.playmeweb.webcontrols.Player.autoPlay"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._autoPlay;
    },
    set_autoPlay: function(value) {
        value = Boolean.parse(value);
        var e = Function._validateParams(arguments, [{ name: "value", type: Boolean}]);
        if (e) throw e;
        this._autoPlay = value;
    },

    get_urlPlayer: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.urlPlayer"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._urlPlayer;
    },
    set_urlPlayer: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._urlPlayer = value;
    },

    get_urlExpressInstall: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.id"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._urlExpressInstall;
    },
    set_urlExpressInstall: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._urlExpressInstall = value;
    },

    get_id: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.id"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._id;
    },
    set_id: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._id = value;
    },

    get_canal: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.canal"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._canal;
    },
    set_canal: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._canal = value;
    },

    get_ip: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.ip"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._ip;
    },
    set_ip: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._ip = value;
    },

    get_browser: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.browser"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._browser;
    },
    set_browser: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._browser = value;
    },

    get_so: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.so"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._so;
    },
    set_so: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._so = value;
    },

    get_host: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.host"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._host;
    },
    set_host: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: String}]);
        if (e) throw e;
        this._host = value;
    },

    get_musica: function() {
        /// <value type="Object" locid="P:J#aorta.playmeweb.webcontrols.Player.musica"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._musica;
    },
    set_musica: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", mayBeNull: true}]);
        if (e) throw e;
        this._musica = value;
    },

    get_logAcesso: function() {
        /// <value type="Object" locid="P:J#aorta.playmeweb.webcontrols.Player.logAcesso"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._logAcesso;
    },
    set_logAcesso: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", mayBeNull: true}]);
        if (e) throw e;
        this._logAcesso = value;
    },

    get_tipoPlayer: function() {
        /// <value type="Object" locid="P:J#aorta.playmeweb.webcontrols.Player.TipoPlayer"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._tipoPlayer;
    },
    set_tipoPlayer: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", mayBeNull: true}]);
        if (e) throw e;
        this._tipoPlayer = value;
    },

    get_erro: function() {
        /// <value type="String" locid="P:J#aorta.playmeweb.webcontrols.Player.erro"></value>
        if (arguments.length !== 0) throw Error.parameterCount();
        return this._erro;
    },
    set_erro: function(value) {
        var e = Function._validateParams(arguments, [{ name: "value", type: Sys.Component}]);
        if (e) throw e;
        this._erro = value;
    }
}

aorta.playmeweb.webcontrols.Player.registerClass('aorta.playmeweb.webcontrols.Player', Sys.Component);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();