/*
 * Pantalla pedir Telefono
 */
define([
	"dojo/on",
	"dojo/dom",
	"dojo/dom-attr",
	"dijit/registry",
	"handsoft/utils",
	"handsoft/soap",
	"handsoft/message_dialog",
	"dojo/ready"], function(on, dom, domAttr, registry, utils, soap, message_dialog, ready){

	ready(function(){
		var ask_code_submit = dom.byId("ask_code_submit");
		var ask_code_resend = dom.byId("ask_code_resend");
		var ask_code_input = dom.byId("ask_code_input");
		var ask_code_phone = dom.byId("ask_code_phone");
		
		/*
		 * Al verificar el codigo (y obtener el token)
		 */
		on(ask_code_submit, "click", function(evt){
			var code = registry.byId("ask_code_input").get("value");
			var phone = domAttr.get("ask_code_phone", "title");
			
			//Validar codigo
			if (!utils.validarCodigo(code)){
				message_dialog.show("No parece un c&oacute;digo v&aacute;lido.");
				
				return false;
			}
			
			utils.setAskCodeStatus(false, false);
			
			// Verifico codigo via SOAP
			soap.call("VerifyCode", {msin: phone, code:code}, function(response){					
				// Guardo el GUID
				utils.saveGUID(response);
				
				var v = registry.byId("ask_code");
				v.performTransition('homepage', 1, "fade", null);

			}, function(error_code, optional_message){
				if (error_code == "7"){
					/* Numero de intentos de verificar codigo aclanzado, reiniciar */
		
					var v = registry.byId("ask_code");
					v.performTransition('ask_phone', 1, "fade", null, function(){
						message_dialog.show("L&iacute;mite de intentos para verificar el c&oacute;digo excedido.");
					});
				} else {
					message_dialog.show(utils.formatError(error_code));
				}
				
				utils.setAskCodeStatus(true, false);
			});
			
			return true;
		});
		
		/*
		 * Reenviar el codigo de verificacion
		 */
		on(ask_code_resend, "click", function(evt){
			var phone = domAttr.get("ask_code_phone", "title");
			
			soap.call("SendCode", {msin: phone}, function(response){
				message_dialog.show("Se ha enviado de nuevo el c&oacute;digo");

			}, function(error_code, optional_message){
				message_dialog.show(utils.formatError(error_code));	
			});
		});
	});
});
