/*
 * Functiones Comunes
 */
define([
	"dojo/on",
	"dijit/registry",
	"dojo/dom",
	"dojo/dom-construct",
	"dojo/dom-attr"], function(on, registry, dom, domConstruct, domAttr){
	var guid_storage_key = 'guid';
	
	var connected = true;//false;
	
	return {
		setAskPhoneStatus: function(enable, reset_input){
			registry.byId("ask_phone_submit").set("label", (enable ? "ENVIAR" : "Enviado c&oacute;digo, espere..."));
			registry.byId("ask_phone_input").set("disabled", !enable);
			registry.byId("ask_phone_submit").set("disabled", !enable);
			
			if(reset_input){
				registry.byId("ask_phone_input").set("value", "");
			}
		},
		setAskCodeStatus: function(enable, reset_input){
			registry.byId("ask_code_submit").set("label", (enable ? "CONTINUAR" : "Verificando c&oacute;digo, espere..."));
			registry.byId("ask_code_input").set("disabled", !enable);
			registry.byId("ask_code_submit").set("disabled", !enable);
			
			if(reset_input){
				registry.byId("ask_code_input").set("value", "");
			}
		},
		setFavouriteStatus: function(added){
			registry.byId("results_favourite_button").set("label", (added ? "GUARDAR FAVORITO" : "ELIMINAR FAVORITO"));
		},
		displayResults: function(title, data){			
			var scroll = registry.byId("results_scroll");
			var text = this.nl2br(data, false);
			var v = registry.byId("homepage");
			
			var n=text.split("<br>");
			
			var display_text = "";
			
			domConstruct.empty("results_list");
			
			for(i=1; i<=n.length; i++)
			{
				var response = n[i-1];
				
				if ((response != '') && (response != '\n') && (response != '\n') && (response != "\r\n")){
					var node = domConstruct.create("div", {
						"class": "result-list-item",
						"innerHTML": "<strong>Opci&oacute;n #"+i+": </strong>" + response,
					}, "results_list");
				}
			}
			
			scroll._at.labelNode.innerHTML = title;
			
			//text
			
			scroll.scrollTo({x:0, y:0});
			
			v.performTransition('results', 1, "fade", null);
		},
		makeResultListClickable: function(linea){
			var items = dojo.query("#results_list div.result-list-item");
			
			items.forEach(function(entry, i){
				var matches = entry.innerHTML.match(/parada \d+/i);
				
				var n_parada = 0;
				
				if ((matches !== null) && (matches.length > 0)){
					n_parada = matches[0].substring(7);
				}
				
				domAttr.set(entry, "data-parada", n_parada);
				domAttr.set(entry, "data-linea", linea);
				
				on(entry, "click", function(evt){
					var parada = domAttr.get(this, "data-parada");
					var linea = domAttr.get(this, "data-linea");
					if (parada && (parada != "0")){
						registry.byId("consulta_1_linea").set("value", linea);
						registry.byId("consulta_1_parada").set("value", parada);
						
						// Activar solapa Por parada
						expand_parada = true;
								
						// Redirigir al Home
						var v = registry.byId("results");
						v.performTransition('homepage', 1, "fade", null);
					}
				});
			});
			
			
		},
		validarCel: function(numero){
			/* Valida un numero Movistar y retorna
			 * un numero usable por los servicios: 59893XXXXXX
			 */
			var phone = numero.toString();
			
			/* Quito espacios */
			phone = phone.split(' ').join('');
			
			if (/^(093|094|095)\d{6}$/.test(phone)){
				//095097766
				phone = "598" + phone.substring(1, 9);
				return phone;
			} else if (/^(93|94|95)\d{6}$/.test(phone)){
				//95097766
				phone = "598" + phone;
				return phone;
			} else if (/^(598093|598094|598095)\d{6}$/.test(phone)){
				//598 095097766
				phone = "598" + phone.substring(4, 12);
				return phone;
			} else if (/^(59893|59894|59895)\d{6}$/.test(phone)){
				//598 95097766
				phone = "598" + phone.substring(3, 11);
				return phone;
			} else if (/^(\+598093|\+598094|\+598095)\d{6}$/.test(phone)){
				//+598 095097766
				phone = "598" + phone.substring(5, 13);
				return phone;
			} else if (/^(\+59893|\+59894|\+59895)\d{6}$/.test(phone)){
				//+598 95097766
				phone = "598" + phone.substring(4, 12);
				return phone;
			}
			
			return false;
		},
		validarInteger: function(numero){
			/* Valida que sea un numero */
			var numberFormat = /^\d+$/;
			
			if (numberFormat.test(numero)){
				return true;
			}
			
			return false;
		},
		isEmpty: function(string){
			return (string == "");
		},
		validarCodigo: function(code){
			/* Valida el codigo ingresado (el enviado via SMS) */
			
			//return this.validarInteger(code);
			
			return !this.isEmpty(code);
		},
		getGUID: function(){
			/* Retorna el GUID para usar en la consultas */
			var guid = window.localStorage.getItem(guid_storage_key);
			
			return (guid === false ? false : guid);
		},
		saveGUID: function(guid){
			/* Guarda el GUIDpara usar en la consultas */
			window.localStorage.setItem(guid_storage_key, guid);
		},
		clearGUID: function(){
			/* Borrar el GUID/numero, si los servicios asi lo indicaran 
			 * (para forzar una re-verificacion de telefono */
			window.localStorage.removeItem(guid_storage_key);
		},
		nl2br: function (str, is_xhtml) {
			var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>';
			
			return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
		},
		capitalise: function (texto)
		{
		    return texto.charAt(0).toUpperCase() + texto.slice(1);
		},
		formatError: function(error_code){
			if (error_code == "-3"){
				return "Error de Servidor (#3). Pruebe de nuevo";
			} else if (error_code == "-2"){
				return "Error de Servidor (#2). Pruebe de nuevo";
			} else if (error_code == "-1"){
				return "Error de comunicaci&oacute;n. Pruebe de nuevo";
			} else if (error_code == "1"){
				//return "N&uacute;mero de m&oacute;vil inv&aacute;lido";
				return "El servicio no está soportado en tu operador m&oacute;vil";
			} else if (error_code == "2"){
				return "Identificador inv&aacute;lido";
			} else if (error_code == "3"){
				return "Codigo inv&aacute;lido";
			} else if (error_code == "4"){
				return "Parada o L&iacute;nea inv&aacute;lida";
			} else if (error_code == "5"){
				return "Error del sistema. Pruebe de nuevo";
			} else if (error_code == "6"){
				return "Timeout";
			} else if (error_code == "7"){
				return "El l&iacute;mite de env&iacute;o de c&oacute;digos se ha excedido. Reintente en 24 horas";
			} else if (error_code == "8"){
				return "Registro via 3G no disponible";
			} else {
				return "Error desconocido";
			}
		},
		formatResult: function(entry){
			/* Devuelve una cadena para mostar el usuario */
			if (entry.query == "GetBusPredictionWithBusStop"){
				return "L&iacute;nea: #" + entry.params.line + " - Parada: " + entry.params.stop;
			} else if (entry.query == "GetBusPrediction"){
				return "L&iacute;nea #" + entry.params.line;
			} else if (entry.query == "GetBusStopNumber"){
				var street = this.capitalise(entry.params.street);
				return street + " - L&iacute;nea #" + entry.params.line; 
			}
			return null;
		}
	};
});

