Type.registerNamespace('Devy.UI');

Devy.UI.Encuesta = function () {
    Devy.UI.Encuesta.initializeBase(this);

    //Miembros
    this._Container = null;
    this._CSSClass = "";

    this._IdEncuesta = 0;
    this._Nombre = "";
    this._Encuesta = null;

    this._Capcha = null;

    this._EncuestaFormContainer = null;
    this._cmdVotar = null;
    this._cmdVerResultados = null;

    this._ServicePortal = null;

    this._ServiceBussy = false;
    this._ServiceLastResult = "";
    this._ServiceLastError = "";

    this._events = null;
}

Devy.UI.Encuesta.prototype = {
    //*********************************************************************
    //Publicos
    set_Container: function (value) { this._Container = value; },
    get_Container: function () { return this._Container; },

    set_CSSClass: function (value) { this._CSSClass = value; },
    get_CSSClass: function () { return this._CSSClass; },

    set_Nombre: function (value) { this._Nombre = value; },
    get_Nombre: function () { return this._Nombre; },

    set_IdEncuesta: function (value) { this._IdEncuesta = value; },
    get_IdEncuesta: function () { return this._IdEncuesta; },


    initialize: function () {
        Devy.UI.Encuesta.callBaseMethod(this, 'initialize');

        this._initInterface();

        this._ServicePortal = Devy.UI.Encuestas.EncuestasService;
        this._BeginGetEncuesta();

        this._atachEvents();
    },

    dispose: function () {
        this._detachEvents();
        Devy.UI.Encuesta.callBaseMethod(this, 'dispose');
    },

    _atachEvents: function () {
        if (this._cmdVotar)
            $addHandlers(this._cmdVotar, { click: this._cmdVotarClick }, this);

        if (this._cmdVerResultados)
            $addHandlers(this._cmdVerResultados, { click: this._cmdVerResultadosClick }, this);

    },

    _detachEvents: function () {
        if (this._cmdVotar)
            $clearHandlers(this._cmdVotar);

        if (this._cmdVerResultados)
            $clearHandlers(this._cmdVerResultados);

    },

    //*********************************************************************
    //Event Handlers
    _cmdVotarClick: function (evt) {
        evt.preventDefault();

        this._Votar();
    },

    _cmdVerResultadosClick: function (evt) {
        evt.preventDefault();

        this._showResultadosDialog();
    },



    //*********************************************************************
    //Mis eventos    
    get_events: function () {
        if (!this._events) {
            this._events = new Sys.EventHandlerList();
        }
        return this._events;
    },

    _raiseEvent: function (eventName, eventArgs) {
        var handler = this.get_events().getHandler(eventName);

        var theEventArgs = null;
        if (handler) {
            if (!eventArgs) {
                theEventArgs = Sys.EventArgs.Empty;
            }
            else {
                theEventArgs = eventArgs;
            }

            handler(this, theEventArgs);
        }

        //Llamamos a defaultHandler si existe
        if (typeof (DevyEncuestaDefaultEventHandler) != "undefined")
            DevyEncuestaDefaultEventHandler(this, eventName, eventArgs);
    },

    

    _Votar: function () {
        if (this._ValidarVoto()) {

            var encuesta = this._Encuesta;
            var captcha = this._Capcha.get_Value();

            this._BeginVotar(encuesta, captcha);
        }
    },


    _ValidarVoto: function () {
        var error = "";

        if (!this._Capcha.get_Value())
            error = "Debe ingresar el código de verificación que aparece en la imagen";

        var optionChecked = false;
        var optionCheckBoxes = $('.EncuestaOpcionCheckBox', '.EncuestaOpciones');

        for (var i = 0; i < optionCheckBoxes.length; i++) {
            if (optionCheckBoxes[i].checked)
                optionChecked = true;

            optionCheckBoxes[i].__BusinessObject.Votar = optionCheckBoxes[i].checked;
        }

        if (!optionChecked)
            error = "Debe seleccionar al menos una opción";

        if (error) {
            Devy.Notifications.ShowError("Error", error)
            return false;
        }
        else
            return true;
    },

    _BeginGetEncuesta: function () {
        var ServiceData = new Array();
        ServiceData.Requester = this;

        this._ServicePortal.GetEncuesta(this._IdEncuesta,
                this._onGetEncuestaServerSuccess, this._onGetEncuestaServerError, ServiceData);
    },


    _onGetEncuestaServerSuccess: function (result, context, methodName) {
        context.Requester._Encuesta = result;
        context.Requester._updateEncuestaInterface();
    },
    _onGetEncuestaServerError: function (error, context, methodName) {
        //No hay nada por hacer
        context.Requester._Encuesta = null;
        context.Requester._updateEncuestaInterface();

        Sys.Debug.trace("Encuesta Error: " + error.get_message());
    },



    _BeginVotar: function (Encuesta, CaptchaCode) {
        var ServiceData = new Array();
        ServiceData.Requester = this;
        ServiceData.Encuesta = Encuesta;
        ServiceData.CaptchaCode = CaptchaCode;

        this._ServicePortal.Votar(Encuesta, CaptchaCode,
                this._onVotarServerSuccess, this._onVotarServerError, ServiceData);
    },

    _onVotarServerSuccess: function (result, context, methodName) {
        context.Requester._Encuesta = result;
        context.Requester._updateEncuestaInterface();

        //SetCokkie
        Devy.Util.SetCookie("DevyEncuestaVotadaId" + result.Id, true, 9999);

        if (context.Requester._Encuesta.ResultadosPublicos)
            context.Requester._showResultadosDialog();
        else
            Devy.Notifications.ShowMessage("Encuestas", "Gracias por participar en nuestra encuesta!");
    },
    _onVotarServerError: function (error, context, methodName) {
        Devy.Notifications.ShowError("Error al intentar procesar el voto", error.get_message());

        Sys.Debug.trace("Encuesta Error: " + error.get_message());
    },


    _initInterface: function () {
        var css = "Encuesta Encuesta" + this._IdEncuesta;
        if (this._CSSClass) css += " " + this._CSSClass;

        var tmpContainer = $('<div class="' + css + '">');


        /*Form Container*/
        this._EncuestaFormContainer = $('<div class="EncuestaFormContainer">')[0];
        tmpContainer.append(this._EncuestaFormContainer);

        /*Commands*/
        var commandsContainer = $('<div class="CommandsContainer">');

        this._cmdVotar = $('<a class="Command Votar" href="#"><span>Votar</span></a>')[0];
        $(this._cmdVotar).hide();
        commandsContainer.append(this._cmdVotar);

        this._cmdVerResultados = $('<a class="Cmd cmdVerResultados" href="#"><span>Ver resultados</span></a>')[0];
        $(this._cmdVotar).hide();
        commandsContainer.append(this._cmdVerResultados);

        tmpContainer.append(commandsContainer);



        $(this._Container).append(tmpContainer);
    },

    _updateEncuestaInterface: function () {
        var jqContainer = $(this._EncuestaFormContainer);
        jqContainer.empty();

        if (this._Encuesta) {

            if (this._Encuesta.Titulo)
                jqContainer.append('<h2 class="EncuestaTitulo">' + this._Encuesta.Titulo + '</h2>');

            if (this._Encuesta.ImagenURL)
                jqContainer.append('<img class="EncuestaImagen" src="' + this._Encuesta.ImagenURL + '" />');

            if (this._Encuesta.Consigna)
                jqContainer.append('<p class="EncuestaConsigna">' + this._Encuesta.Consigna + '</p>');


            var opcionesEncuesta = $('<ul class="EncuestaOpciones"></ul>');
            jqContainer.append(opcionesEncuesta);

            //Agregar las opciones
            for (var i = 0; i < this._Encuesta.Opciones.length; i++) {
                var opcion = this._Encuesta.Opciones[i];

                var opcionHtml = $('<li class="EncuestaOpcion ID' + opcion.Id + '"></li>');
                var optionRadioButton = $('<input type="radio" class="EncuestaOpcionCheckBox" name="Encuesta' + this._Encuesta.Id + '"></input>')[0]

                optionRadioButton.__BusinessObject = opcion;

                opcionHtml.append(optionRadioButton);

                if (opcion.ImagenURL)
                    opcionHtml.append('<img class="EncuestaOpcionImagen" src="' +  Devy.Util.ThumbNailURL(opcion.ImagenURL, 50,50,1) + '" />');

                if (opcion.Texto)
                    opcionHtml.append('<p class="EncuestaOpcionTexto">' + opcion.Texto + '</p>');


                opcionesEncuesta.append(opcionHtml);
            }

            if (!this._Encuesta.Votada) {
                //Captcha
                this._Capcha = $create(Devy.UI.Forms.Fields.Captcha,
                    { "Container": jqContainer[0],
                        "PropertyName": "CaptchaCode",
                        "HeaderText": "Ingrese el código que aparece en la imagen",
                        "BusinessObject": this,
                        "CaptchaProcessID": "VotarEncuestaId" + this._Encuesta.Id
                    },
                    {},
                    {});
                this._Capcha.PrepareToShow();

                $(this._cmdVotar).show();
            }
            else {
                $(this._cmdVotar).hide();
                jqContainer.append('<p class="EncuestaVotada">Usted ya ha participado en esta encuesta, muchas gracias!</p>');
            }

            if (this._Encuesta.ResultadosPublicos)
            {
                $(this._cmdVerResultados).show();

                if (this._ResultadosView)
                    this._ResultadosView.set_BusinessObject (this._Encuesta);
            }
            else
                $(this._cmdVerResultados).hide();

        }
        else {
            jqContainer.append('<p class="EncuestaError">Error al intentar obtener la encuesta</p>');
        }
    },

    _showResultadosDialog: function () {
        //Mostramos el dialogo
        $(this._getResultadosDialog()).dialog({
            modal: true,
            title: "Resultados de la encuesta",
            height: 500,
            width: 700,
            closeOnEscape: true,
            close: function () { $(this).dialog('destroy'); }
        });
    },

    _getResultadosDialog: function () {
        if (!this.ResultadosDialog) {
            
            this.ResultadosDialog = $('<div class="EncuestaResultadosDialog"></div>');

             this._ResultadosView = $create(Devy.UI.Admin.Publicidades.EncuestasResultadosView,
                    { "Container": this.ResultadosDialog[0],
                        "PropertyName": "Resultados",
                        "BusinessObject": this._Encuesta
                    },
                    {},
                    {});
            
        }
        return this.ResultadosDialog;
    }
}

Devy.UI.Encuesta.registerClass('Devy.UI.Encuesta', Sys.Component);
