1 /**
  2 * NTG Vota
  3 * Newtenberg.com
  4 * @version v0.2
  5 * @author Alejandro Vera <[email protected]>
  6 */
  7 
  8 /**
  9 * Clase NTGVota
 10 * Maneja votacion de un elemento (articulo, noticia, etc)
 11 * @param {String} code codigo de la votacion
 12 * @param {String} id identificador del elemento a votar
 13 * @param {NTGVota.Config} config configuracion
 14 * @constructor
 15 */
 16 function NTGVota (code,id,config) {
 17 	if (!code || !id) {throw "No se entrego identificador valido de votacion (code,id)";}
 18 	/**
 19 	* Codigo de la votacion
 20 	* @type String
 21 	*/
 22 	this.code = code;
 23 	/**
 24 	* Identificador del elemento que se vota
 25 	* @type String
 26 	*/
 27 	this.id = id;
 28 	/**
 29 	* Valores actuales
 30 	* p: promedio,
 31 	* n: total de votos,
 32 	* vs: [{v: valor , n: cantidad},{...},...]
 33 	*/
 34 	this.current = {};
 35 
 36 	/**
 37 	* Configuracion de la votacion
 38 	* @type NTGVota.Config
 39 	*/
 40 	this.config = new NTGVota.Config(config);
 41 	if (!this.config) {throw "No se encuentra configuracion";}
 42 
 43 	/**
 44 	* Despliega urna de votacion
 45 	*/
 46 	this.showBase = function() {
 47 		var id = this.id;
 48 		var code = this.code;
 49 
 50 		//Valida e instancia tema
 51 		var theme = NTGVota.getTheme(this.config.themeid);
 52 		if (!theme) {throw "No existe tema '"+this.config.themeid+"' registrado";}
 53 
 54 		// Obtengo urna desde plantilla del tema
 55 		var strHTML = theme.getUrn(this.code,this.id);
 56 		document.getElementById('ntgvota_'+code+'_'+id).innerHTML = strHTML;
 57 
 58 		if (this.config.show_current) {
 59 			// Agrego script para ver valor actual (modelo crossbrowser)
 60 	        	var currscr = document.createElement('script');
 61 	        	currscr.src = NTGVota.Path+'/current.php?code='+code+'&id='+id+'&rand='+Math.random();
 62 			currscr.type = "text/javascript";
 63 	        	document.getElementsByTagName("head")[0].appendChild(currscr);
 64 		}
 65 
 66 		// hago una llamada para preparar la votacion
 67 		// mecanismo para evitar fraudes y llamadas de robots
 68 		$.get(NTGVota.Path+'/vota.php',{ "code" : code , "id" : id });
 69 	}
 70 
 71 	/**
 72 	* Ejecuta votacion
 73 	* @param {Number} value valor del voto
 74 	*/
 75 	this.vota = function(value) {
 76 		var code = this.code;
 77 		var id = this.id;
 78 		//Valida e instancia tema
 79 		var theme = NTGVota.getTheme(this.config.themeid);
 80 		if (!theme) {throw "No existe tema '"+this.config.themeid+"' registrado";}
 81 
 82 		theme.showWait(code,id);
 83 		$.post(NTGVota.Path+'/vota.php',
 84 			{ "code" : code , "id" : id , "value" : value, "action" : "vote"} ,
 85 			function(datos) {
 86 				if (!datos) {
 87 					theme.writeMsg(code,id,NTGVota.Messages.AJAXERROR);
 88 					return;
 89 				}
 90 				var currv = eval('('+datos+')');
 91 				if (currv.id && currv.id == id) {
 92 					theme.writeMsg(code,id,NTGVota.Messages.VOTESUCCESS);
 93 					NTGVota.setCurrent(currv);
 94 				} else if (currv.error == 'already-voted') {
 95 					theme.writeMsg(code,id,NTGVota.Messages.VOTEALREADY);
 96 				} else {
 97 					theme.writeMsg(code,id,NTGVota.Messages.VOTEERROR);
 98 				}
 99 			}
100 		      )
101 	}
102 }
103 
104 /**
105 * Metodo de clase que inicia el despliegue de la "urna"
106 * @param {String} code codigo de la votacion
107 * @param {String} id identificador del elemento a votar
108 * @param {NTGVota.Config} config configuracion
109 */
110 NTGVota.display = function (code,id,config) {
111 
112 	// Validamos configuracion o cargamos la por defecto
113 	config = new NTGVota.Config(config);
114 
115 	// Se carga jquery
116 	NTGVota.loadJQuery();
117 
118 	// Se carga estilo del tema
119 	var cssNode = document.createElement('link');
120 	cssNode.type = 'text/css'; cssNode.rel = 'stylesheet';
121 	cssNode.href = NTGVota.Path+'/themes/'+config.themeid+'/style.css';
122 	document.getElementsByTagName("head")[0].appendChild(cssNode);
123 
124 	// Se carga plantilla del tema
125 	document.write('<script src="'+NTGVota.Path+'/themes/'+config.themeid+'/template.js" type="text/javascript"></script>');
126 
127 	// Se registra la votacion
128 	NTGVota.registerVotation(new NTGVota(code,id,config));
129 
130 	// Se inicializa contenedor
131 	document.write('<div id="ntgvota_'+code+'_'+id+'" class="ntgvota_container"></div>');
132 
133 	// Se configura inicializador al cargar pagina
134 	document.write('<script type="text/javascript">$(document).ready(function(){NTGVota.getVotation("'+code+'","'+id+'").showBase();});</script>');
135 }
136 
137 /**
138 * Asigna resultados actuales de la votacion y los muestra con el tema configurado
139 */
140 NTGVota.setCurrent = function (data) {
141 	if (!data || !data.id || !data.code) {
142 		throw "Error en Datos : ids invalidos";
143 	}
144 	var vot = NTGVota.getVotation(data.code,data.id);
145 	if (!vot) {
146 		throw "Error en Datos : votacion no esta registrada";
147 	}
148 	vot.current = {'p':data.current , 'count':data.count, 'voted':data.voted, 'counts':data.counts};
149 	var theme = NTGVota.getTheme(vot.config.themeid);
150 	theme.showCurrent(vot.code,vot.id);
151 }
152 
153 /**
154 * Web Path de NTGVota
155 * @type String
156 */
157 NTGVota.Path = '/ntgvota';
158 
159 /**
160 * Arreglo con las votaciones de la pagina (pueden ser varias)
161 * @type Array
162 */
163 NTGVota.Votations = new Array();
164 
165 /**
166 * Metodo de clase que registra una votacion
167 * @param {NTGVota} votation votacion a registrar
168 */
169 NTGVota.registerVotation = function (votation) {
170 	if (votation && votation.code && votation.id) {
171 		NTGVota.Votations[votation.code+'_'+votation.id] = votation;
172 	}
173 }
174 /**
175 * Metodo de clase que obtiene una votacion
176 * @param code codigo de la votacion
177 * @param id identificador del elemento a votar
178 * @return {NTGVota} votacion
179 */
180 NTGVota.getVotation = function (code,id) {
181 	return NTGVota.Votations[code+'_'+id];
182 }
183 
184 /**
185 * Arreglo con los temas (pueden ser varios)
186 * @type Array
187 */
188 NTGVota.Themes = new Array();
189 
190 /**
191 * Metodo de clase que registra un tema
192 * @param theme tema a registrar
193 */
194 NTGVota.registerTheme = function (theme) {
195 	if (theme && theme.id) {
196 		NTGVota.Themes[theme.id] = theme;
197 	}
198 }
199 
200 /**
201 * Metodo de clase que obtiene un tema
202 * @param themeid identificador (nombre corto) del tema
203 * @return tema
204 */
205 NTGVota.getTheme = function (themeid) {
206 	return NTGVota.Themes[themeid];
207 }
208 
209 /**
210 * Variable para marcar si ha sido cargado ya jquery
211 * @type Number
212 */
213 NTGVota.jquery_loaded = 0;
214 
215 /**
216 * Carga jquery, solamente si no ha sido cargado
217 */
218 NTGVota.loadJQuery = function() {
219 	if (!NTGVota.jquery_loaded) {
220 		document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>');
221 		NTGVota.jquery_loaded = 1;
222 	}
223 }
224 
225 /**
226 * Mensajes por defecto
227 * @constructor
228 */
229 NTGVota.Messages = function() {};
230 /**
231 * Mensaje por de saludo inicial de la votacion
232 * @type String
233 */
234 NTGVota.Messages.GREETING = "";
235 
236 /**
237 * Mensaje de error al fallar peticion Ajax
238 * @type String
239 */
240 NTGVota.Messages.AJAXERROR = "No se pudo contactar con servicio de votacion";
241 /**
242 * Mensaje de error al efectuar votacion exitosa
243 * @type String
244 */
245 NTGVota.Messages.VOTESUCCESS = "Su voto fue procesado exitosamente";
246 /**
247 * Mensaje de error al fallar votacion
248 * @type String
249 */
250 NTGVota.Messages.VOTEERROR = "No se pudo procesar su voto, intente mas tarde";
251 /**
252 * Mensaje de error por votacion repetida
253 * @type String
254 */
255 NTGVota.Messages.VOTEALREADY = "Usted ya ha votado";
256 
257 /**
258 * Configuracion de votacion
259 * @param {NTGVota.Config} config Configuracion de votacion
260 * <pre>
261 * Configuracion por defecto:
262 * {
263 * 	"type":"discrete",
264 * 	"show_current":1,
265 * 	"load_jquery":1,
266 * 	"themeid":"stars",
267 * 	"values":[
268 * 		{"value":1,"title":"Muy Malo"},
269 * 		{"value":2,"title":"Malo"},
270 * 		{"value":3,"title":"Regular"},
271 * 		{"value":4,"title":"Bueno"},
272 * 		{"value":5,"title":"Muy Bueno"}
273 * 	]
274 * }
275 * </pre>
276 * @constructor
277 */
278 NTGVota.Config = function(config) {
279 	if (!config) {config = {};}
280         /**
281         * Tipo de cuantificacion discreta/continua
282 	* @type String
283         */
284         this.type = config.type;
285 	if (typeof(this.type) == 'undefined') {this.type = "discrete";}
286         /**
287         * Indica si debe o no mostrar el resultado cuando se muestra la urna.
288 	* @type Number
289         */
290         this.show_current = config.show_current;
291 	if (typeof(this.show_current) == 'undefined') {this.show_current = 1;}
292         /**
293         * Indica si debe o no cargar la biblioteca JQuery.
294 	* @type Number
295         */
296 	this.load_jquery = config.load_jquery;
297 	if (typeof(this.load_jquery) == 'undefined') {this.load_jquery = 1;}
298         /**
299         * Identificador del tema que se usa
300 	* @type String
301         */
302         this.themeid = config.themeid;
303 	if (typeof(this.themeid) == 'undefined') {this.themeid = "stars";}
304         /**
305         * Arreglo de Valores de elementos de votacion. Cada elemento contiene un valor numerico (value) y un texto (title).
306 	* @example ej. [{"value":1,"title":"uno"},{"value":2,"title":"dos"}]
307 	* @type Array
308         */
309         this.values = config.values;
310 	if (typeof(this.values) == 'undefined') {this.values = [
311 							{"value":1,"title":"Muy Malo"},
312 							{"value":2,"title":"Malo"},
313 							{"value":3,"title":"Regular"},
314 							{"value":4,"title":"Bueno"},
315 							{"value":5,"title":"Muy Bueno"}
316 						];}
317 }
318 
319