/**
* NTG Vota
* Newtenberg.com
* @version v0.2
* @author Alejandro Vera <alevera@newtenberg.com>
*/

/**
* Clase NTGVota
* Maneja votacion de un elemento (articulo, noticia, etc)
* @param {String} code codigo de la votacion
* @param {String} id identificador del elemento a votar
* @param {NTGVota.Config} config configuracion
* @constructor
*/
function NTGVota (code,id,config) {
	if (!code || !id) {throw "No se entrego identificador valido de votacion (code,id)";}
	/**
	* Codigo de la votacion
	* @type String
	*/
	this.code = code;
	/**
	* Identificador del elemento que se vota
	* @type String
	*/
	this.id = id;
	/**
	* Valores actuales
	* p: promedio,
	* n: total de votos,
	* vs: [{v: valor , n: cantidad},{...},...]
	*/
	this.current = {};

	/**
	* Configuracion de la votacion
	* @type NTGVota.Config
	*/
	this.config = new NTGVota.Config(config);
	if (!this.config) {throw "No se encuentra configuracion";}

	/**
	* Despliega urna de votacion
	*/
	this.showBase = function() {
		var id = this.id;
		var code = this.code;

		//Valida e instancia tema
		var theme = NTGVota.getTheme(this.config.themeid);
		if (!theme) {throw "No existe tema '"+this.config.themeid+"' registrado";}

		// Obtengo urna desde plantilla del tema
		var strHTML = theme.getUrn(this.code,this.id);
		document.getElementById('ntgvota_'+code+'_'+id).innerHTML = strHTML;

		if (this.config.show_current) {
			// Agrego script para ver valor actual (modelo crossbrowser)
	        	var currscr = document.createElement('script');
	        	currscr.src = NTGVota.Path+'/current.php?code='+code+'&id='+id+'&rand='+Math.random();
			currscr.type = "text/javascript";
	        	document.getElementsByTagName("head")[0].appendChild(currscr);
		}

		// hago una llamada para preparar la votacion
		// mecanismo para evitar fraudes y llamadas de robots
		$.get(NTGVota.Path+'/vota.php',{ "code" : code , "id" : id });
	}

	/**
	* Ejecuta votacion
	* @param {Number} value valor del voto
	*/
	this.vota = function(value) {
		var code = this.code;
		var id = this.id;
		//Valida e instancia tema
		var theme = NTGVota.getTheme(this.config.themeid);
		if (!theme) {throw "No existe tema '"+this.config.themeid+"' registrado";}

		theme.showWait(code,id);

		$.ajax({
			type:'POST',
			url:NTGVota.Path+'/vota.php',
			data:{ "code" : code , "id" : id , "value" : value, "action" : "vote"} ,
			success:function(datos) {
				if (!datos) {
					theme.writeMsg(code,id,NTGVota.Messages.AJAXERROR);
					return;
				}
				var currv = eval('('+datos+')');
				if (currv.id && currv.id == id) {
					theme.writeMsg(code,id,NTGVota.Messages.VOTESUCCESS);
					NTGVota.setCurrent(currv);
					//Patch: Agrega tracking para ChileClic
					if (CCTrack && CCTrack.id) {
						CCTrack.click("Valorar");
					}
				} else if (currv.error == 'already-voted') {
					theme.writeMsg(code,id,NTGVota.Messages.VOTEALREADY);
				} else {
					theme.writeMsg(code,id,NTGVota.Messages.VOTEERROR);
				}
			},
			error:function(xhr,text,err) {
				theme.writeMsg(code,id,NTGVota.Messages.AJAXERROR);
			}
		      })
	}
}

/**
* Metodo de clase que inicia el despliegue de la "urna"
* @param {String} code codigo de la votacion
* @param {String} id identificador del elemento a votar
* @param {NTGVota.Config} config configuracion
*/
NTGVota.display = function (code,id,config) {

	// Validamos configuracion o cargamos la por defecto
	config = new NTGVota.Config(config);

	// Se carga jquery
	NTGVota.loadJQuery();

	// Se carga estilo del tema
	var cssNode = document.createElement('link');
	cssNode.type = 'text/css'; cssNode.rel = 'stylesheet';
	cssNode.href = NTGVota.Path+'/themes/'+config.themeid+'/style.css';
	document.getElementsByTagName("head")[0].appendChild(cssNode);

	// Se carga plantilla del tema
	document.write('<script src="'+NTGVota.Path+'/themes/'+config.themeid+'/template.js" type="text/javascript"></script>');

	// Se registra la votacion
	NTGVota.registerVotation(new NTGVota(code,id,config));

	// Se inicializa contenedor
	document.write('<div id="ntgvota_'+code+'_'+id+'" class="ntgvota_container"></div>');

	// Se configura inicializador al cargar pagina
	document.write('<script type="text/javascript">$(document).ready(function(){NTGVota.getVotation("'+code+'","'+id+'").showBase();});</script>');
}

/**
* Asigna resultados actuales de la votacion y los muestra con el tema configurado
*/
NTGVota.setCurrent = function (data) {
	if (!data || !data.id || !data.code) {
		throw "Error en Datos : ids invalidos";
	}
	var vot = NTGVota.getVotation(data.code,data.id);
	if (!vot) {
		throw "Error en Datos : votacion no esta registrada";
	}
	vot.current = {'p':data.current , 'count':data.count, 'voted':data.voted, 'counts':data.counts};
	var theme = NTGVota.getTheme(vot.config.themeid);
	theme.showCurrent(vot.code,vot.id);
}

/**
* Web Path de NTGVota
* @type String
*/
NTGVota.Path = '/ntgvota';

/**
* Arreglo con las votaciones de la pagina (pueden ser varias)
* @type Array
*/
NTGVota.Votations = new Array();

/**
* Metodo de clase que registra una votacion
* @param {NTGVota} votation votacion a registrar
*/
NTGVota.registerVotation = function (votation) {
	if (votation && votation.code && votation.id) {
		NTGVota.Votations[votation.code+'_'+votation.id] = votation;
	}
}
/**
* Metodo de clase que obtiene una votacion
* @param code codigo de la votacion
* @param id identificador del elemento a votar
* @return {NTGVota} votacion
*/
NTGVota.getVotation = function (code,id) {
	return NTGVota.Votations[code+'_'+id];
}

/**
* Arreglo con los temas (pueden ser varios)
* @type Array
*/
NTGVota.Themes = new Array();

/**
* Metodo de clase que registra un tema
* @param theme tema a registrar
*/
NTGVota.registerTheme = function (theme) {
	if (theme && theme.id) {
		NTGVota.Themes[theme.id] = theme;
	}
}

/**
* Metodo de clase que obtiene un tema
* @param themeid identificador (nombre corto) del tema
* @return tema
*/
NTGVota.getTheme = function (themeid) {
	return NTGVota.Themes[themeid];
}

/**
* Variable para marcar si ha sido cargado ya jquery
* @type Number
*/
NTGVota.jquery_loaded = 0;

/**
* Carga jquery, solamente si no ha sido cargado
*/
NTGVota.loadJQuery = function() {
	if (!NTGVota.jquery_loaded) {
		document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>');
		NTGVota.jquery_loaded = 1;
	}
}

/**
* Mensajes por defecto
* @constructor
*/
NTGVota.Messages = function() {};
/**
* Mensaje por de saludo inicial de la votacion
* @type String
*/
NTGVota.Messages.GREETING = "";

/**
* Mensaje de error al fallar peticion Ajax
* @type String
*/
NTGVota.Messages.AJAXERROR = "No se pudo contactar con servicio de votacion";
/**
* Mensaje de error al efectuar votacion exitosa
* @type String
*/
NTGVota.Messages.VOTESUCCESS = "Su voto fue procesado exitosamente";
/**
* Mensaje de error al fallar votacion
* @type String
*/
NTGVota.Messages.VOTEERROR = "No se pudo procesar su voto, intente mas tarde";
/**
* Mensaje de error por votacion repetida
* @type String
*/
NTGVota.Messages.VOTEALREADY = "Usted ya ha votado";

/**
* Configuracion de votacion
* @param {NTGVota.Config} config Configuracion de votacion
* <pre>
* Configuracion por defecto:
* {
* 	"type":"discrete",
* 	"show_current":1,
* 	"load_jquery":1,
* 	"themeid":"stars",
* 	"lang":"es",
* 	"values":[
* 		{"value":1,"title":"Muy Malo"},
* 		{"value":2,"title":"Malo"},
* 		{"value":3,"title":"Regular"},
* 		{"value":4,"title":"Bueno"},
* 		{"value":5,"title":"Muy Bueno"}
* 	]
* }
* </pre>
* @constructor
*/
NTGVota.Config = function(config) {
	if (!config) {config = {};}
        /**
        * Tipo de cuantificacion discreta/continua
	* @type String
        */
        this.type = config.type;
	if (typeof(this.type) == 'undefined') {this.type = "discrete";}
        /**
        * Indica si debe o no mostrar el resultado cuando se muestra la urna.
	* @type Number
        */
        this.show_current = config.show_current;
	if (typeof(this.show_current) == 'undefined') {this.show_current = 1;}
        /**
        * Indica si debe o no cargar la biblioteca JQuery.
	* @type Number
        */
	this.load_jquery = config.load_jquery;
	if (typeof(this.load_jquery) == 'undefined') {this.load_jquery = 1;}
        /**
        * Identificador del tema que se usa
	* @type String
        */
        this.themeid = config.themeid;
	if (typeof(this.themeid) == 'undefined') {this.themeid = "stars";}
        /**
        * Identificador del idioma que se usa
	* @type String
        */
        this.lang = config.lang;
	if (typeof(this.lang) == 'undefined') {this.lang = "es";}
        /**
        * Arreglo de Valores de elementos de votacion. Cada elemento contiene un valor numerico (value) y un texto (title).
	* @example ej. [{"value":1,"title":"uno"},{"value":2,"title":"dos"}]
	* @type Array
        */
        this.values = config.values;
	if (typeof(this.values) == 'undefined') {this.values = [
							{"value":1,"title":"Muy Malo"},
							{"value":2,"title":"Malo"},
							{"value":3,"title":"Regular"},
							{"value":4,"title":"Bueno"},
							{"value":5,"title":"Muy Bueno"}
						];}
}


