//La funcion class es del autor jClass2k
var Class = function(current, previous) {
    //Creamos el metodo superclass sera un objeto que tendra como
    //puntero las funciones la clase padre esto es para los casos que se
    //desee acceder aun metodo publico de la clase padre desde cualquier
    //lugar
    current.superclass = new Object();
    //Comprobamos si tenemos una Class que extender.
    previous = typeof previous == 'undefined' ? {} : previous.prototype;
    //Extendemos con las propiedades de la Class anterior
    for (p in previous) {
        //cargamos las funciones a superclass
        if (typeof previous[p] == 'function') current.superclass[p] = previous[p];
        //Si no existe la propiedad la añadimos
        if (typeof current[p] == 'undefined') current[p] = previous[p];
        //Si es una función
        else if (typeof previous[p] == 'function') {
            //añadimos this.parent() a la función de la Class actual.
            current[p] = (function(tmp) {
                var _parent = function() {
                    this.parent = _parent.parent;
                    return tmp.apply(this, arguments);
                }
                return _parent;
            })(current[p]);
            //Igualamos this.parent() al método de la Class anterior.
            current[p].parent = previous[p];
        }
    }
    // Construimos el contenedor
    var construct = function() {
        if (this.init) this.init.apply(this, arguments);
    }
    // Le aplicamos los métodos extendidos
    construct.prototype = current;
    // asignamos un constructor
    construct.constructor = Class;
    //Devolvemos el constructor.
    return construct;
};

var EncuestasEvent = new Class(
(function() {
    var onattachEventos = function(objevent, funcionrecive, nameevento) {
        $(objevent).bind(nameevento,{scope:funcionrecive.scope,eventobject :funcionrecive.eventobject},funcionrecive.handleEvent);
    };
    var onfireEventListen = function(pevent,pdata){
        $.each(this.listiner, function(key, value) {
                var handler = value;
                if(handler.eventlisten == pevent){
                        var oListen = {
                                scope:handler.objlisten
                        };
                        handler.eventcallback.apply(oListen,[pdata]);
                }
        })
    };
    return {
            init: function(){
                this.listiner = new Array();
            },
            firenEventListener:function(pevent,pdata){
                    onfireEventListen.apply(this,[pevent,pdata]);
            },
            addEventListeners:function(plisten,peventlisten,pcallback){
                this.listiner.push({objlisten:plisten,eventlisten:peventlisten,eventcallback:pcallback});
            },
            attachEventos:function(objevent, funcionrecive, nameevento){
                var listener = {
                    scope       :   this,
                    eventobject :   objevent,
                    handleEvent :   funcionrecive
                };
                onattachEventos(objevent,listener, nameevento);
            }
    }
})());

var EncuestasVote = new Class(
(function(){
		var onexecuterequest = function($urlREST){
			var $scope  = this;
			var $url    = $urlREST;
                        $.ajax({url:$url,
                                global:false,
                                dataType:"json",
                                contentType:"application/json; charset=utf-8",
                                success:function($data){
                                        handlersuccess.apply($scope,[$data]);
                                },
                                error:function($result){
                                    if($result.status == "200"){
                                            $data = eval("q=" + $result.responseText);
                                            handlersuccess.apply($scope,[$data]);
                                    }else{
                                            handlererror.apply($scope,[$result]);
                                    }
                                }
                        });
		}

		var handlersuccess=function(e){
                    var arg = {value:e.data};
                    this.firenEventListener('completerequest',arg);
		}

		var handlererror=function(result){
                    //Error en ejecucion
                    alert('en este momento no podemos procesar su voto, vuelva intentarlo dentro de unos minutos.');
		}

		return {
			init:function(){
                            this.parent();
			},
			executerequest:function($urlREST){
                            onexecuterequest.apply(this,[$urlREST]);
			}
		}

})(),EncuestasEvent);

var Encuestas = new Class(
(function(){
        var oncompletereadstatistics = function(e){
            var $owner      = this.scope;
            var $jsonresult = e.value;
            var arg = {htmlstatistics:$jsonresult.htmlstatistics, arraystatistics:$jsonresult.arraystatistics ,totalvote:$jsonresult.totalvote};
            $owner.firenEventListener('oncompletereadstatistics',arg);
        }
        var oncompletevote = function(e){
            var $owner          = this.scope;
            var $vote           = Number($owner.getNumberVote()) + 1;
            var $jsonresult     = e.value;
            $owner.resultvote   = $jsonresult.result;
            $owner.maxvote      = $jsonresult.maxvote;
            switch ($owner.resultvote){
                case 0:
                    alert('No existe identificador de proceso');
                    break;
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    $owner.setNumberVote($vote);
                    break;
                default:
                    break;
            }
            $($owner.osubmit).css('display','');
            if($owner.resultvote == 3){
                $($owner.options ).each(
                function($index,$value){
                  var $option = $value;
                  if($option.checked){
                      $option.checked = false;
                  }
                  if($option.selectedIndex){
                     $option.selectedIndex = 0;
                  }
                }
                );
                var arg = {objsubmit:$($owner.osubmit),options:$owner.options,result:$owner.resultvote};
                $owner.firenEventListener('oncompletevotesubmit',arg);
            }
        };
	var onhandleeventsend = function(e){
            var $owner          = e.data.scope;
            if ($owner.selectedoption == -1) {
                alert('Seleccione una opcion valida');
                return;
            }
            var $request        = new EncuestasVote();
            if (Number($owner.getNumberVote())==0 || Number($owner.getNumberVote())< $owner.maxvote ){
                $($owner.osubmit).css('display','none');
                var protocol = window.location.protocol;
                var hostname = window.location.hostname;
                var port     = window.location.port;
                var $url      = protocol + '//' + hostname + ((port && port.length > 0)?':' + port:'') + '/encuesta/vote/' + $owner.id_encuesta + '/' + $owner.selectedoption;
                $request.addEventListeners($owner,'completerequest',oncompletevote);
                $request.executerequest($url);
            }else{
                var arg = {objsubmit:$($owner.osubmit),options:$owner.options,result:1};
                $owner.firenEventListener('oncompletevotesubmit',arg);
            }
	};
        var onhandleeventselectoption   = function(e){
            var $owner                  = e.data.scope;
            var $obj                    = e.data.eventobject;
            $owner.selectedoption       = $obj.value;
	};
        var oncreateCookie = function(name,value,days){
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                expires = "; expires="+date.toGMTString();
            }
            else{
                expires = "";
            }
            document.cookie = name + this.idkeyobject +"="+value+expires+"; path=/";
        };
        var onreadCookie = function(name) {
            var nameEQ = name + this.idkeyobject + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++){
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        };
        var oneraseCookie = function(name) {
            oncreateCookie.apply(this,[name,"",-1]);
        };
        var onreadstatistics = function(){
            var $owner       = this;
            var statistics   = new EncuestasVote();
            statistics.addEventListeners(this,'completerequest',oncompletereadstatistics);
            var protocol = window.location.protocol;
            var hostname = window.location.hostname;
            var port     = window.location.port;
            var $url     = protocol + '//' + hostname + ((port && port.length > 0)?':' + port:'') + '/encuesta/statistics/' + $owner.id_encuesta;
            statistics.executerequest($url);
        }
        return{
            init:function($idencuesta){
                //var d = new Date()
				//String(d.getTime());
                this.idkeyobject = $idencuesta; 
                this.parent();
                this.options        = new Array();
                this.selectedoption = -1;
                this.resultvote     = -1;
                this.maxvote = 999999;
                this.id_encuesta  = $idencuesta;
                this.osubmit = null;
            },
            registeroptions:function($idselect){
                var $owner = this;
                var $objselects = document.getElementById($idselect);
                var $lista = ($objselects.options)?$objselects.options:null;
                if($lista){
                    $($lista).each(
                        function($index,$value){
                            var $option = $value;
                            $owner.options.push($option);
                        }
                    );
                }else{
                    $owner.options.push($objselects);
                }
                this.attachEventos($objselects,onhandleeventselectoption,'change');
            },
            registersubmit:function($idsubmit){
                this.osubmit = document.getElementById($idsubmit);
                this.attachEventos(this.osubmit,onhandleeventsend,'click');
            },
            setNumberVote:function($value){
                oneraseCookie.apply(this,['vote']);
                oncreateCookie.apply(this,['vote',$value,1]);
            },
            getNumberVote:function(){
				var valor = onreadCookie.apply(this,['vote']);
				if(valor == null){
					valor = 0;
				}else{
					valor = Number(valor);
				} 
                return valor;
            },
            readstatistics:function(){
                return onreadstatistics.apply(this,[]);
            }
        }
})(),EncuestasEvent);

