// PLUGINS

function utf8_decode(e){var t=[],n=0,r=0,i=0,s=0,o=0,u=0;e+="";while(n<e.length){i=e.charCodeAt(n);if(i<=191){t[r++]=String.fromCharCode(i);n++}else if(i<=223){s=e.charCodeAt(n+1);t[r++]=String.fromCharCode((i&31)<<6|s&63);n+=2}else if(i<=239){s=e.charCodeAt(n+1);o=e.charCodeAt(n+2);t[r++]=String.fromCharCode((i&15)<<12|(s&63)<<6|o&63);n+=3}else{s=e.charCodeAt(n+1);o=e.charCodeAt(n+2);u=e.charCodeAt(n+3);i=(i&7)<<18|(s&63)<<12|(o&63)<<6|u&63;i-=65536;t[r++]=String.fromCharCode(55296|i>>10&1023);t[r++]=String.fromCharCode(56320|i&1023);n+=4}}return t.join("")}



// Config
var CONFIG = {
	WS_DATA:{
		'idAplicacion': 0,
		WS_URLS:{
			autoLogin: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/LoginAutomatico',
			externalLogin: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/ValidarCodigoActivacion',
			getCodigoActivacion: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/GetCodigoActivacion',
			obtenerDatosRecargaFacil: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Recargas.svc/obtenerDatosRecargaFacil',
			hacerRecargaFacil: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Recargas.svc/hacerRecargaFacil',
			getConsultaSaldo: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Common.svc/getConsultaSaldo',
			obtenerDatoExtensionCredito: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Recargas.svc/obtenerDatoExtensionCredito',
			solicitarPaquete: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Recargas.svc/solicitarPaquete',
			consultarTransaccion: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Recargas.svc/consultarTransaccion',	
	    	solicitarPaqueteATercero: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Recargas.svc/solicitarPaqueteATercero',
			getCategoriasFaq: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Common.svc/getCategoriasFaq',
			getFaqByCategoriaId: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.Common.svc/getFaqByCategoriaId',
		    autenticarUsuarioPortal: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/autenticarUsuarioPortal',
		   	registrarUsuarioPortal: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/registrarUsuarioPortal',
			recuperarClavePortal:	'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/recuperarClavePortal',
			getResumenCalls: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getResumenCalls',
			getResumenSMS: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getResumenSMSs',
			getResumenData: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getResumenData',
			getCallsInfo: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getCallsInfo',
			getSMSsInfo: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getSMSsInfo',
			getCallsInfo: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getCallsInfo',
            getDataInfo: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getDataInfo',
			getUltimaFactura:'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getUltimaFactura',	
			getArchivoUltimaFactura: 'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.MiMovistar.svc/getArchivoUltimaFactura',
		    cambiarClavePortal:'http://mobileapps.movistar.com.uy/MobileappsServicesTesting/Movistar.MobileApps.Services.ExternalAuthentication.svc/cambiarClavePortal'
		}
},
	CHAT:{
		CHAT_MOBILE_URL: 'http://chat.movistar.com.uy/WebAPI812/SimpleSamples812/ChatMobileFFNativa/HtmlChatFrameSet.jsp?nombre=<nombreIngresado>&apellido=<apellidoIngresado>&numero=<numeroDeLinea>',
	},
	CONNECTION:{
		INTENTS: 3,
		INTERVAL: 300,
	}
};


// Lang
var LANG = {
	'checkAccountSuccess': 'Recibirás un SMS con tu saldo actual.',
	'checkAccountFail': 'Ocurrió un error, vuelva a intentar.',
	'codeSent': 'El código de activación fue enviado satisfactoriamente',
	'loading': 'Cargando',
	'phoneInputError': 'Debes ingresar un celular Movistar válido.',
	'codeInputError': 'Debes ingresar un código de activación.',
	'chatInitInputError': 'Debes ingresar nombre y apellido',
};


// Loading UI
(function(ns){
	ns.show = function(){
		document.querySelector('#loading').classList.add('active');
	};
	ns.hide = function(){
		document.querySelector('#loading').classList.remove('active');
	};
}(window.LOADING = window.LOADING || {}));


// NAVIGATOR
(function(ns){
	ns.changePage = function(newPageId){
		var activePage = document.querySelector('section.page.active');
		if(activePage!=null){
			activePage.classList.remove('active');
		}
		document.querySelector('#'+newPageId).classList.add('active');
	};
	ns.backPageView = function(){};
	ns.userHomeView = function(){};
	var backBtn = document.querySelector('#back_btn');
	backBtn.onclick = function(){
		ns.backPageView();
	};

	ns.moreInfoPageView = function(){};
	var moreInfoBtn = document.querySelector('#more_info_btn');
	moreInfoBtn.onclick = function(){
		ns.moreInfoPageView();
	};
	ns.showBackBtn = function(){
		backBtn.classList.add('active');
	};
	ns.hideBackBtn = function(){
		backBtn.classList.remove('active');
	};
	ns.showMoreInfoBtn = function(){
		moreInfoBtn.classList.add('active');
	};
	ns.hideMoreInfoBtn = function(){
		moreInfoBtn.classList.remove('active');
	};
}(window.NAVIGATOR = window.NAVIGATOR || {}));


// CONNECTION
(function(ns){
	var checkOnlineIntent = 0;
	var checkOnlineTimeout;
	ns.checkOnlineCallback = function(){};
	ns.checkOnlineCallbackParams = {};
	ns.checkOnline = function(){
		if (!navigator.onLine) {
			/*
			if(checkOnlineIntent<=CONFIG.CONNECTION.INTENTS){
				LOADING.show();
				clearTimeout(checkOnlineTimeout);
				checkOnlineIntent++;
				checkOnlineTimeout = setTimeout(ns.checkOnline, CONFIG.CONNECTION.INTERVAL);
			}else{
				LOADING.hide();
				checkOnlineIntent = 0;
				NAVIGATOR.changePage('offline');
			}
			*/
			LOADING.hide();
			checkOnlineIntent = 0;		 
			NAVIGATOR.changePage('offline');
		}else{
			LOADING.hide();
			checkOnlineIntent = 0;
			ns.checkOnlineCallback(ns.checkOnlineCallbackParams);
		}
	};
	var checkOnlineIntentAlert = 0;
	var checkOnlineTimeoutAlert;
	ns.checkOnlineCallback = function(){};
	ns.checkOnlineCallbackParams = {};
	ns.checkOnlineAlert = function(){
		if (!navigator.onLine) {
			/*
			if(checkOnlineIntent<=CONFIG.CONNECTION.INTENTS){
				LOADING.show();
				clearTimeout(checkOnlineTimeout);
				checkOnlineIntent++;
				checkOnlineTimeout = setTimeout(ns.checkOnline, CONFIG.CONNECTION.INTERVAL);
			}else{
				LOADING.hide();
				checkOnlineIntent = 0;
				NAVIGATOR.changePage('offline');
			}
			*/
			LOADING.hide();
			checkOnlineIntentAlert = 0;		 
			//NAVIGATOR.changePage('offline');
			alert("No fue posible conectarse a internet, por favor verifica tu conexión.");						
		}else{
			LOADING.hide();
			checkOnlineIntentAlert = 0;
			ns.checkOnlineCallback(ns.checkOnlineCallbackParams);
		}
	};
}(window.CONNECTION = window.CONNECTION || {}, LOADING, NAVIGATOR, CONFIG));


// WebServiceCaller
(function(ns, CONFIG, LOADING, CONNECTION){
	var xhr;
	var requestCallback = function(response){};
	var requestHandler = function(){
		if(xhr.readyState==4){
			var jsonResponse = false;
			try{
				jsonResponse = JSON.parse(xhr.responseText);
			}catch(e){}
			var response = {
				'responseText': xhr.responseText || false,
				'jsonResponse': jsonResponse,
				'errorDescription': xhr.getResponseHeader('CustomStatusDescription') || false,
			};
			LOADING.hide();
			requestCallback(response);
		}
	};
	var doSendRequest = function(params){
	
		var url = params['url'] || null;
		var data = params['data'] || null;
		var callback = params['callback'] || null;
		var userdata = params['userdata'] || null;
		requestCallback = callback || function(){};
		userdata = userdata || null;
		xhr = new XMLHttpRequest({mozSystem: true});
		xhr.open('POST', url, true);
		xhr.setRequestHeader('X-MovApplicationId', CONFIG.WS_DATA.idAplicacion);
		if(userdata && userdata.token){
			xhr.setRequestHeader('X-MovToken', userdata.token);
		}
		xhr.setRequestHeader('Content-Type', 'application/json');
		xhr.onreadystatechange = requestHandler;
		xhr.send(JSON.stringify(data));
		LOADING.show();
	};

var doSendRequestReload = function(params){
		var url = params['url'] || null;
		var data = params['data'] || null;
		var callback = params['callback'] || null;
		var userdata = params['userdata'] || null;
		 
		requestCallback = callback || function(){};
		userdata = userdata || null;
			
	};

	ns.sendRequest = function(url, data, callback, userdata, flag){
	
		CONNECTION.checkOnlineCallbackParams = {
			url: url,
			data: data,
			callback: callback,
			userdata: userdata,
			flag: flag,
		}
		if(flag === true)
		CONNECTION.checkOnlineCallback = doSendRequestReload;
		else	
		CONNECTION.checkOnlineCallback = doSendRequest;
 
		CONNECTION.checkOnlineAlert();
	};
}(window.WSCaller = window.WSCaller || {}, CONFIG, LOADING, CONNECTION));

// MovistarAPI
(function(ns, WSCaller, CONFIG){
	var WS_URLS = CONFIG.WS_DATA.WS_URLS;
	var SESSION_USERDATA = null;
	var SESSION_PORTALUSERDATA = null;
	var SESSION_ACTUALMONTH = 0;
	var SESSION_NUMEROCUENTA = 0;	
	var SESSION_EMAIL = 0;
	var SESSION_PAGINA = 1;
	
	var intentAutoLoginCallback;
	var intentAutoLoginHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false || !response.jsonResponse.LoginAutomaticoResult){
			result = false;
		}else{
			SESSION_USERDATA = response.jsonResponse.LoginAutomaticoResult;
		}
		intentAutoLoginCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.intentAutoLogin = function(data, callback){
		SESSION_USERDATA = null;
		intentAutoLoginCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.autoLogin, data, intentAutoLoginHandler);
	};



	var externalLoginCallback;
	var intentExternalLoginHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false || !response.jsonResponse.ValidarCodigoActivacionResult){
			result = false;
		} else {
		    //#1.1
			SESSION_USERDATA = response.jsonResponse.ValidarCodigoActivacionResult;
			localStorage.setItem('usuario', JSON.stringify(response.jsonResponse.ValidarCodigoActivacionResult));
			var currentdate = new Date();
			var date = Date.now();
			var d = new Date(date);
			localStorage['fecha'] = d;
		}
		externalLoginCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.intentExternalLogin = function(data, callback){
		SESSION_USERDATA = null;
		externalLoginCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.externalLogin, data, intentExternalLoginHandler);
	};

	var sendActivationCodeCallback;
	var sendActivationCodeHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
		sendActivationCodeCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.sendActivationCode = function(data, callback){
		SESSION_USERDATA = null;
		sendActivationCodeCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.getCodigoActivacion, data, sendActivationCodeHandler);
	};

	var sendPrePaidOrderCallback;
	var sendPrePaidOrderHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
 
		sendPrePaidOrderCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};


	ns.sendPrePaidOrder = function(data, callback){
		sendPrePaidOrderCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.hacerRecargaFacil, data, sendPrePaidOrderHandler, SESSION_USERDATA);
	};

	var checkTransactionStatusCallback;
	var checkTransactionStatusHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}


		checkTransactionStatusCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.checkTransactionStatus = function(data, callback){
	 
		checkTransactionStatusCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.consultarTransaccion, data, checkTransactionStatusHandler, SESSION_USERDATA, true);
	};

	var sendAnotherPhoneOrderCallback;
	var sendAnotherPhoneOrderHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
		 
		sendAnotherPhoneOrderCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.sendAnotherPhoneOrder = function(data, callback){
		sendAnotherPhoneOrderCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.solicitarPaqueteATercero, data, sendAnotherPhoneOrderHandler, SESSION_USERDATA,false);
	};

	var sendControlledAccountOrderCallback;
	var sendControlledAccountOrderHandler = function(response){
		var result = true;
	
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		
		// Diego Si no da error en primer lugar navega a la pantalla de exito
		// Si despues llega a dar un error muestra un popup
		if(result === true){
       
    	  NAVIGATOR.changePage('transaction_success');  
        }else
        {  
        // Si ya da error de primera te muestra la pagina de error.	  
    	
    	  var x = document.querySelector('#transaction_messages');
          x.textContent = "";
          x.textContent = utf8_decode(response.errorDescription);
          NAVIGATOR.changePage('transaction_error');  
        }

		}
 

		sendControlledAccountOrderCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.sendControlledAccountOrder = function(data, callback){
		sendControlledAccountOrderCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.solicitarPaquete, data, sendControlledAccountOrderHandler, SESSION_USERDATA);
	};

	var controlledAccountOptionsCallback;
	var controlledAccountOptionsHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
		controlledAccountOptionsCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.getControlledAccountOptions = function(data, callback){
		controlledAccountOptionsCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.obtenerDatoExtensionCredito, data, controlledAccountOptionsHandler, SESSION_USERDATA);
	};

	var prePaidAmountsCallback;
	var prePaidAmountsHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
		prePaidAmountsCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.getPrePaidAmounts = function(data, callback){
		prePaidAmountsCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.obtenerDatosRecargaFacil, data, prePaidAmountsHandler, SESSION_USERDATA);
	};

	var checkAccountCallback;
	var checkAccountHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}			
		checkAccountCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.checkAccount = function(data, callback){
		checkAccountCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.getConsultaSaldo, data, checkAccountHandler, SESSION_USERDATA);
	};

	var getFaqsCategoryCallback;
	var getFaqsCategoryHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
		
		getFaqsCategoryCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.getFaqsCategory = function(data, callback){
		getFaqsCategoryCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.getFaqByCategoriaId, data, getFaqsCategoryHandler, SESSION_USERDATA);
	};

	var getFaqsCallback;
	var getFaqsHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
		NAVIGATOR.changePage('faqs');
		getFaqsCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	ns.getFaqs = function(data, callback){
		getFaqsCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.getCategoriasFaq, data, getFaqsHandler, SESSION_USERDATA);
	};

	ns.getSessionUserdata = function(){
		return SESSION_USERDATA;
	};

	ns.setSessionUserdata = function (data) {

	    SESSION_USERDATA = data;
	};

	ns.getSessionPortalUserdata = function(){
		return SESSION_PORTALUSERDATA;
	};


	ns.setSessionPortalUserdata = function (data) {
	    SESSION_PORTALUSERDATA = data;

	}
	ns.getSessionActualMonth = function(){
		return SESSION_ACTUALMONTH;
	};


    ns.setSessionActualMonth = function(data){
		 SESSION_ACTUALMONTH = data;
	};

	ns.getEmail = function(){
		return SESSION_EMAIL;
	};


    ns.setEmail = function(data){
		  
		 SESSION_EMAIL = data;		  
	
	};



	ns.getSessionNumeroCuenta = function(){
		return SESSION_NUMEROCUENTA;
	};


    ns.setSessionNumeroCuenta = function(data){
		 SESSION_NUMEROCUENTA = data;
	};

	ns.getSessionPagina = function(){
		return SESSION_PAGINA;
	};


    ns.setSessionPagina = function(){
		 SESSION_PAGINA = SESSION_PAGINA + 1;
	};
	
	ns.setSessionResetPagina = function(){
		 SESSION_PAGINA = 1;
	};

 



	ns.InitializeSessionPortalUserdata = function(){
		SESSION_PORTALUSERDATA = null;		 
	};
	ns.validatePhone = function(phone){
		var re = new RegExp("(093|094|095)+[0-9]{6}");
		return re.test(phone);
	};

 
    var sendPrePaidOrderCallbackSS;
	var sendPrePaidOrderHandlerSS = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
 
	 
		sendPrePaidOrderCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.sendPrePaidOrderSS = function(data, callback){
		sendPrePaidOrderCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.solicitarPaquete, data, sendPrePaidOrderHandlerSS, SESSION_USERDATA);
	};


	var intentautenticarUsuarioPortalCallback;
	var intentautenticarUsuarioPortalHandler = function(response){
		var result = true;
		//var resultData = data.response.autenticarUsuarioPortalResult;
		
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false || !response.jsonResponse.autenticarUsuarioPortalResult){
			result = false;
		}else{
			if (response.jsonResponse.autenticarUsuarioPortalResult.status){
			SESSION_PORTALUSERDATA = response.jsonResponse.autenticarUsuarioPortalResult;		
			}
			

		}

  
		intentautenticarUsuarioPortalCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendIntentAutenticarUsuarioPortal = function(data, callback){ 
       
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		intentautenticarUsuarioPortalCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.autenticarUsuarioPortal, data, intentautenticarUsuarioPortalHandler,SESSION_USERDATA);
	};





//--
var intentautenticarUsuarioPortalMiPerfilCallback;
	var intentautenticarUsuarioPortalMiPerfilHandler = function(response){
		var result = true;
		//var resultData = data.response.autenticarUsuarioPortalResult;
		
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false || !response.jsonResponse.autenticarUsuarioPortalResult){
			result = false;
		}else{
			if (response.jsonResponse.autenticarUsuarioPortalResult.status){
			SESSION_PORTALUSERDATA =  response.jsonResponse.autenticarUsuarioPortalResult;		
			}
			

		}

         
		intentautenticarUsuarioPortalMiPerfilCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendIntentAutenticarUsuarioPortalMiPerfil = function(data, callback){ 
         
        var userdata = MovistarAPI.getSessionUserdata();	   	   
	 
		intentautenticarUsuarioPortalMiPerfilCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.autenticarUsuarioPortal, data, intentautenticarUsuarioPortalMiPerfilHandler,SESSION_USERDATA);
	};



		var intentRegistrarUsuarioPortalCallback;
	    var intentRegistrarUsuarioPortalHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
  
		intentRegistrarUsuarioPortalCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescriptionf,
		});
	};
	
	ns.SendIntentRegistrarUsuarioPortal = function(data, callback){ 
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		intentautenticarUsuarioPortalCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.registrarUsuarioPortal, data, intentautenticarUsuarioPortalHandler,SESSION_USERDATA);
	};

 	var recuperarClavePortalHandlerCallback;
	var recuperarClavePortalHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
  
		intentrecuperarClavePortalCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendrecuperarClavePortal = function(data, callback){ 
       
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		intentrecuperarClavePortalCallback = callback || function(){};
		WSCaller.sendRequest(WS_URLS.recuperarClavePortal, data, recuperarClavePortalHandler,SESSION_USERDATA);
	};



	var ResumenLlamadaHandlerCallback;
	var ResumenLlamadaHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		}
  		 
  		 
		ResumenLlamadaHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendResumenLlamada = function(data, callback){ 
       
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		ResumenLlamadaHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getResumenCalls, data, ResumenLlamadaHandler,SESSION_USERDATA);
	};
	


	var ResumenSMSHandlerCallback;
	var ResumenSMSHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		ResumenSMSHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendResumenSMS = function(data, callback){ 
       
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		ResumenSMSHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getResumenSMS, data, ResumenSMSHandler,SESSION_USERDATA);
	};


	var ResumenDatosHandlerCallback;
	var ResumenDatosHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		ResumenDatosHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendResumenDatos = function(data, callback){ 
   
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		ResumenDatosHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getResumenData, data, ResumenDatosHandler,SESSION_USERDATA);
	};

	var VerDetalleSMSHandlerCallback;
	var VerDetalleSMSHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		VerDetalleSMSHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendVerDetalleSMS = function(data, callback){ 
   
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		VerDetalleSMSHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getSMSsInfo, data, VerDetalleSMSHandler,SESSION_USERDATA);
	};

	
	var VerDetalleLlamadaHandlerCallback;
	var VerDetalleLlamadaHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		VerDetalleLlamadaHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendVerDetalleLlamada = function(data, callback){ 
   
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		VerDetalleLlamadaHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getCallsInfo, data, VerDetalleLlamadaHandler,SESSION_USERDATA);
	};

	var VerDetalleDatosHandlerCallback;
	var VerDetalleDatosHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		VerDetalleDatosHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendVerDetalleDatos = function(data, callback){ 
   
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		VerDetalleDatosHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getDataInfo, data, VerDetalleDatosHandler,SESSION_USERDATA);
	};


	var ObtenerUltimaFacturaHandlerCallback;
	var ObtenerUltimaFacturaHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		 
		ObtenerUltimaFacturaHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.sendObtenerUltimaFactura = function(data, callback){ 
 
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		ObtenerUltimaFacturaHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getUltimaFactura, data, ObtenerUltimaFacturaHandler,SESSION_USERDATA);
	};





	var DescargarArchvioUltimaFacturaHandlerCallback;
	var DescargarArchvioUltimaFacturaHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		 
		DescargarArchvioUltimaFacturaHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.sendDescargarArchvioUltimaFactura = function(data, callback){ 
 
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		DescargarArchvioUltimaFacturaHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.getArchivoUltimaFactura, data, DescargarArchvioUltimaFacturaHandler,SESSION_USERDATA);
	};


 
	
	var CambiarContraseñaHandlerCallback;
	var CambiarContraseñaHandler = function(response){
		var result = true;
		if(response.responseText===false || response.jsonResponse===false || response.errorDescription!==false){
			result = false;
		} 
  		 
		CambiarContraseñaHandlerCallback({
			'response': response.jsonResponse,
			'responseText': response.responseText,
			'result': result,
			'errorDescription': response.errorDescription,
		});
	};
	
	ns.SendCambiarContraseña = function(data, callback){ 
   
        var userdata = MovistarAPI.getSessionUserdata();	   	   
		CambiarContraseñaHandlerCallback = callback || function(){};		
		WSCaller.sendRequest(WS_URLS.cambiarClavePortal, data, CambiarContraseñaHandler,SESSION_USERDATA);
	};
 
//#fin diego
}(window.MovistarAPI = window.MovistarAPI || {}, WSCaller, CONFIG));


// MainApp
(function(ns, MovistarAPI, CONFIG, LANG, NAVIGATOR, LOADING, CONNECTION){
	var authFailViewInitialized = false;
	var authFailView = function(){


	    //#1.1
	    
	    if (localStorage['usuario'] == 'undefined') {
	    NAVIGATOR.changePage('auth_fail');
		NAVIGATOR.hideMoreInfoBtn();
		if(!authFailViewInitialized){
			var sendCodeBtn = document.querySelector('#send_code');
			sendCodeBtn.onclick = ns.sendCode;
			var validateCodeBtn = document.querySelector('#code_validation');
			validateCodeBtn.onclick = ns.validateCode;
			authFailViewInitialized = true;
		}
	    } else {
	        if (localStorage['usuario'] != undefined) {

	            var date = new Date(Date.now() - (30 * 24 * 3600 * 1000));
	            if (Date.parse(localStorage['fecha']) >= date) {

	                var datObj = JSON.parse(localStorage['usuario']);
	                MovistarAPI.setSessionUserdata(datObj);
	                gotoHomeView();
	            }
	            else {

	                MovistarAPI.setSessionUserdata(null);
	                MovistarAPI.getSessionPortalUserdata(null);
	                document.querySelector('#passw').value = "";
	                document.querySelector('#email').value = "";
	                localStorage.removeItem("passw");
	                localStorage.removeItem("email");
	                localStorage.removeItem("usuario");
	                localStorage.removeItem("fecha");

	                NAVIGATOR.changePage('auth_fail');
	                NAVIGATOR.hideMoreInfoBtn();
	                if (!authFailViewInitialized) {
	                    var sendCodeBtn = document.querySelector('#send_code');
	                    sendCodeBtn.onclick = ns.sendCode;
	                    var validateCodeBtn = document.querySelector('#code_validation');
	                    validateCodeBtn.onclick = ns.validateCode;
	                    authFailViewInitialized = true;
	                }
	            }


	        }
	        else {
	            NAVIGATOR.changePage('auth_fail');
	            NAVIGATOR.hideMoreInfoBtn();
	            if (!authFailViewInitialized) {
	                var sendCodeBtn = document.querySelector('#send_code');
	                sendCodeBtn.onclick = ns.sendCode;
	                var validateCodeBtn = document.querySelector('#code_validation');
	                validateCodeBtn.onclick = ns.validateCode;
	                authFailViewInitialized = true;
	            }
	        }
	    }
	    
	    };

	var confirmPrePaidOrderHandler = function(data){
		if(data.result){
			var resultData = data.response.hacerRecargaFacilResult;
			NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
			NAVIGATOR.showBackBtn();
			if(resultData.status){
			 
				NAVIGATOR.changePage('pre_paid_success');
				document.querySelector('#pre_paid_success_check_account').onclick = checkAccountView;
			}else{
			 
				document.querySelector('#pre_paid_error_description').innerHTML = resultData.descripcion;
				NAVIGATOR.changePage('pre_paid_error');
			}
		}
	};
	ns.confirmPrePaidOrder = function(){
		MovistarAPI.sendPrePaidOrder({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
			monto: document.querySelector('#pre_paid_amount').value,
		}, confirmPrePaidOrderHandler)
	};

	var checkAccountHandler = function(data){
		var feedbackElement = document.querySelector('#check_account_feedback');
		if(data.result){
			feedbackElement.innerHTML = LANG['checkAccountSuccess'];
		}else{
			feedbackElement.innerHTML = LANG['checkAccountFail'];
		}
	};
	var checkAccountView = function(){
	
		NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('check_account');
		var feedbackElement = document.querySelector('#check_account_feedback');
		feedbackElement.innerHTML = LANG['loading'];
		MovistarAPI.checkAccount({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
		}, checkAccountHandler);


	};
      
		var regFreeView = function(){
	   
	 
		document.querySelector('#reg_email').value = "";
		document.querySelector('#reg_Reemail_re').value = "";
		document.querySelector('#reg_full_name').value = "";
		document.querySelector('#reg_DateBorn').value = "";
		document.querySelector('#reg_Passw').value = "";

		var backBtn = document.querySelector('#back_btn');
	   	 backBtn.onclick = function(){
	   	 autoGestionView();
	    }   ;
 
 

        
		var refgreebtn = document.querySelector('#regFreeUserBtn');
		refgreebtn.onclick =  IntentRegistrarUsuarioPortal;
 




		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('regFree');
		
	};

		var MiPerfilregFreeView = function(){
	 
		var backBtn = document.querySelector('#back_btn');
	   	 backBtn.onclick = function(){
	   	 MiPerfilInfo();
	    };
        
		var refgreebtn = document.querySelector('#regFreeUserBtn');
		refgreebtn.onclick =  IntentRegistrarUsuarioPortal;

		NAVIGATOR.showBackBtn();
	    NAVIGATOR.hideMoreInfoBtn();	
		NAVIGATOR.changePage('regFree');
		
	};

	var OprtionPerfilView = function(){
	     
	     MovistarAPI.setSessionActualMonth(0);
		var backBtn = document.querySelector('#back_btn');
	   	 backBtn.onclick = function(){
	   	 gotoHomeView();
	    };

		var ResumenLlamadasBtnBtn = document.querySelector('#ResumenLlamadasBtn');
	   	ResumenLlamadasBtnBtn.onclick = ResumenLlamadaView;

	   	var ConsultarFacturaBtn = document.querySelector('#ConsultarFacturaBtn');
	   	ConsultarFacturaBtn.onclick = ObtenerUltimaFacturaView;
	


		var ResumenSMSBtn = document.querySelector('#ResumenSMSBtn');
	   	ResumenSMSBtn.onclick = ResumenSMSView;


   		var ResumenDatosBtn = document.querySelector('#ResumenDatosBtn');
	   	ResumenDatosBtn.onclick = ResumenDatosView;
  

 		var datosMes = document.querySelector('#datosMes'); 
        datosMes.textContent = getMonthString();

  		var smsMes = document.querySelector('#smsMes'); 
        smsMes.textContent = getMonthString();
		 
 		var llamadaMes = document.querySelector('#llamadaMes'); 
        llamadaMes.textContent = getMonthString();

 		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('OptionPerfil');
		 
	};


	var ResumenLlamadaView = function(){
	    NAVIGATOR.showBackBtn();
	//	NAVIGATOR.changePage('AutoGestionLlamadas');
		
		var backBtn = document.querySelector('#back_btn');
	    	 backBtn.onclick = function(){
	    	OprtionPerfilView();
	       };

		 IntentResumenLlamada();
		 


		var cambiarMesBtn = document.querySelector('#cambiarMesLlamdasBtn');
	   	    cambiarMesBtn.onclick = function(){
	     	NAVIGATOR.changePage('AutoGestionCambiarMes');
 		
            var backBtn = document.querySelector('#back_btn');
	    	 backBtn.onclick = function(){
	    	ResumenLlamadaView();
	        };			
	        
	        getMonth();	  

	        var PrimerMes = document.querySelector('#PrimerMes');
	     	var SegundoMes = document.querySelector('#SegundoMes');
	     	var TercerMes = document.querySelector('#TercerMes');
  
  			

	        var PrimerMesBtn = document.querySelector('#PrimerMesBtn'); 

	     	PrimerMesBtn.onclick =   function()
	     	{
	     		var llamadaMes = document.querySelector('#llamadaMes'); 
	     		llamadaMes.textContent = "DE " + PrimerMes.textContent;
	     		MovistarAPI.setSessionActualMonth(PrimerMes.value);	     		
	     		ResumenLlamadaView()

	     	};  	
	   		     	    			
	     	var SegundoMesBtn = document.querySelector('#SegundoMesBtn');
	     	SegundoMesBtn.onclick =  function()
	     	{
	     		var llamadaMes = document.querySelector('#llamadaMes'); 
	     		llamadaMes.textContent = "DE " + SegundoMes.textContent;
	     		MovistarAPI.setSessionActualMonth(SegundoMes.value);	     		 
	     		ResumenLlamadaView()
	     	};  	
	     	
	     	var TercerMesBtn = document.querySelector('#TercerMesBtn');
          	TercerMesBtn.onclick =  function()
	     	{
	     		var llamadaMes = document.querySelector('#llamadaMes'); 
	     		llamadaMes.textContent = "DE " + TercerMes.textContent;
	     		MovistarAPI.setSessionActualMonth(TercerMes.value);	     		
	     		ResumenLlamadaView()
	     	};  	
	    };

	   	var VerDetalleBtn = document.querySelector('#LlamadasVerDetalleBtn');
	   	VerDetalleBtn.onclick = DetalleLlamadaView;
	   
		
 	
	};


 	



	var ResumenSMSView = function(){	  
		var backBtn = document.querySelector('#back_btn');
	   	 backBtn.onclick = function(){
	   	 OprtionPerfilView();
	    };

		 IntentResumenSMS();

		 

	        var cambiarMesBtn = document.querySelector('#cambiarMesSMSBtn');
	   	    cambiarMesBtn.onclick = function(){
	     	NAVIGATOR.changePage('AutoGestionCambiarMes');
 			
 			var backBtn = document.querySelector('#back_btn');
	   	    backBtn.onclick = function(){
	   	    ResumenSMSView();
	        };

	        getMonth();	    

	        var PrimerMesBtn = document.querySelector('#PrimerMesBtn'); 		      			  	
	     	var PrimerMes = document.querySelector('#PrimerMes');
	     	var SegundoMes = document.querySelector('#SegundoMes');
	     	var TercerMes = document.querySelector('#TercerMes');

			

	     	PrimerMesBtn.onclick =   function()
	     	{
	     		var smsMes = document.querySelector('#smsMes'); 
	     		smsMes.textContent = "DE " + PrimerMes.textContent;
	     		MovistarAPI.setSessionActualMonth(PrimerMes.value);	     		
	     		ResumenSMSView()

	     	};  	
	   		     
	    			
	     	var SegundoMesBtn = document.querySelector('#SegundoMesBtn');
	     	SegundoMesBtn.onclick =  function()
	     	{
	     		var smsMes = document.querySelector('#smsMes'); 
	     		smsMes.textContent = "DE " + SegundoMes.textContent;
	     		MovistarAPI.setSessionActualMonth(SegundoMes.value);	     		 
	     		ResumenSMSView()
	     	};  	
	     	
	     	var TercerMesBtn = document.querySelector('#TercerMesBtn');
          	TercerMesBtn.onclick =  function()
	     	{
	     		var smsMes = document.querySelector('#smsMes'); 
	     		smsMes.textContent = "DE " + TercerMes.textContent;
	     		MovistarAPI.setSessionActualMonth(TercerMes.value);	     		
	     		ResumenSMSView()
	     	};  	
	    };
		 

     	var VerDetalleBtn = document.querySelector('#SMSVerDetalleBtn');
	   	VerDetalleBtn.onclick = DetalleSMSView;
	   

 		NAVIGATOR.showBackBtn();
	
		
	};


	var ResumenDatosView = function(){	    	

		    IntentResumenDATOS();
		   
		   	var backBtn = document.querySelector('#back_btn');
	  	 	backBtn.onclick = function(){
	  	 	OprtionPerfilView();
	    	};

	        var cambiarMesBtn = document.querySelector('#cambiarMesDatosBtn');
	   	    cambiarMesBtn.onclick = function(){
	     	NAVIGATOR.changePage('AutoGestionCambiarMes');

	     	var backBtn = document.querySelector('#back_btn');
		   	backBtn.onclick = function(){
		   	ResumenDatosView();
	    	};
			
	        getMonth();	 

	        var PrimerMes = document.querySelector('#PrimerMes');
	     	var SegundoMes = document.querySelector('#SegundoMes');
	     	var TercerMes = document.querySelector('#TercerMes');   

	        var PrimerMesBtn = document.querySelector('#PrimerMesBtn'); 		      			  	
	     	PrimerMesBtn.onclick =   function()
	     	{
	     		var datosMes = document.querySelector('#datosMes'); 
	     		datosMes.textContent = "DE " + PrimerMes.textContent;
	     		MovistarAPI.setSessionActualMonth(PrimerMes.value);	     		
	     		ResumenDatosView()

	     	};  	
	   		     	    			
	     	var SegundoMesBtn = document.querySelector('#SegundoMesBtn');
	     	SegundoMesBtn.onclick =  function()
	     	{
	     		var datosMes = document.querySelector('#datosMes'); 
	     		datosMes.textContent = "DE " + SegundoMes.textContent;
	     		MovistarAPI.setSessionActualMonth(SegundoMes.value);	     		 
	     		ResumenDatosView()
	     	};  	
	     	
	     	var TercerMesBtn = document.querySelector('#TercerMesBtn');
          	TercerMesBtn.onclick =  function()
	     	{
	     		var datosMes = document.querySelector('#datosMes'); 
	     		datosMes.textContent = "DE " + TercerMes.textContent;
	     		MovistarAPI.setSessionActualMonth(TercerMes.value);	     		
	     		ResumenDatosView()
	     	};  	
	    	};

    		var VerDetalleBtn = document.querySelector('#DatosVerDetalleBtn');
	   		VerDetalleBtn.onclick = DetalleDatosView;
	   
 			NAVIGATOR.showBackBtn();
			
	};


	var DetalleLlamadaView = function()
 	{
		//NAVIGATOR.changePage('VerDetalleSms');
 		var backBtn = document.querySelector('#back_btn');
	   	backBtn.onclick = function(){
	   	ResumenLlamadaView();
	    };

		var optionsContainer = document.querySelector('#VerDetalleSms_container');
        optionsContainer.innerHTML = "";
 		IntentVerDetalleLlamada();
 		NAVIGATOR.hideMoreInfoBtn();
	};

	var DetalleSMSView = function()
 	{
 		
 		var backBtn = document.querySelector('#back_btn');
	   	backBtn.onclick = function(){
	   	ResumenSMSView();
	    };

	    NAVIGATOR.hideMoreInfoBtn();
		var optionsContainer = document.querySelector('#VerDetalleSms_container');
        optionsContainer.innerHTML = "";
 		IntentVerDetalleSMS();
	};

	var DetalleDatosView = function()
 	{
 		//NAVIGATOR.changePage('VerDetalleSms');
 		var backBtn = document.querySelector('#back_btn');
	   	backBtn.onclick = function(){
	   	ResumenDatosView();
	    };
		var optionsContainer = document.querySelector('#VerDetalleSms_container');
        optionsContainer.innerHTML = "";
 		IntentVerDetalleDatos();
 		NAVIGATOR.hideMoreInfoBtn();
	};


	var ForgotPasswView = function(){
		var backBtn = document.querySelector('#back_btn');
	   	backBtn.onclick = function(){
	   	autoGestionView();
	    };

		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('forgotPasw');

		var forgotPaswbtn = document.querySelector('#forgotPaswBtn');
		forgotPaswbtn.onclick =	IntentrecuperarClavePortal;
		
	};
	var MiPerfilForgotPasswView = function(){
		var backBtn = document.querySelector('#back_btn');
	   	backBtn.onclick = function(){
	   	MiPerfilInfo();
	    };

		NAVIGATOR.showBackBtn();
	    NAVIGATOR.hideMoreInfoBtn();	
		NAVIGATOR.changePage('forgotPasw');

		var forgotPaswbtn = document.querySelector('#forgotPaswBtn');
		forgotPaswbtn.onclick =	IntentrecuperarClavePortal;
		
	};

	
	var ObtenerUltimaFacturaView = function(){
	  
	
	   IntentObtenerFactura();
	

	 
    };

	var TransactionId;
	var transactionStatusTimeout;
	var transactionStatusHandler = function(data){
     
		var status = data.response.consultarTransaccionResult;
	  
	 	if(status=='Success'){
		//	NAVIGATOR.changePage('transaction_success');
	        alert("La Recarga fue acreditada.");	
			document.querySelector('#transaction_success_check_account').onclick = checkAccountView
		}else if(status=='Failed'){
		    alert("Tu recarga no ha podido acreditarse, te enviamos más información por SMS");		
            document.querySelector('#transaction_success_check_account').onclick = checkAccountView	
		}else{
			clearTimeout(transactionStatusTimeout);
			transactionStatusTimeout = setTimeout(transactionStatus, 2000);
			//LOADING.show();
		}
	};

  
	var transactionStatus = function(){
	 
		MovistarAPI.checkTransactionStatus({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
			idTransaction: TransactionId,
		}, transactionStatusHandler);
	};

	var anotherPhoneOrderHandler = function(data){	
	
		if(data.result){
			var transactionId = data.response.solicitarPaqueteATerceroResult;
			
			if(transactionId!=null){
				NAVIGATOR.changePage('transaction_success');
				TransactionId = transactionId;
				LOADING.hide();
				transactionStatus();
			}else{
				document.querySelector('#another_phone_error_description').innerHTML = utf8_decode(data.errorDescription);
				NAVIGATOR.changePage('another_phone_error');
			}
		}
		else
			{		
				document.querySelector('#another_phone_error_description').innerHTML = utf8_decode(data.errorDescription);
				NAVIGATOR.changePage('another_phone_error');

			}
	};
	var anotherPhoneOrder = function(){
		var optionId = this.dataset['optionId'];
		var orderPhone = document.querySelector('#another_phone_phone').value;
      
		MovistarAPI.sendAnotherPhoneOrder({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
			idPaquete: optionId,
			destPhoneNumber: orderPhone,
		}, anotherPhoneOrderHandler);
	};
	var anotherPhoneOrderConfirmation = function(){
		
		var optionId = this.dataset['optionId'];
		var amount = this.dataset['amount'];
		var phone = document.querySelector('#another_phone_phone').value;
       
		var backBtn = document.querySelector('#back_btn');
	   	 backBtn.onclick = function(){
	   	 anotherPhoneView();
	    }   ;



		if(MovistarAPI.validatePhone(phone)){
		
			var btn = document.querySelector('#another_phone_confirm_order_btn');
			btn.dataset['optionId'] = optionId;
			btn.onclick = anotherPhoneOrder;
			document.querySelector('#another_phone_confirm_order_amount').innerHTML = amount;
			document.querySelector('#another_phone_confirm_order_phone').innerHTML = phone;
			NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
			NAVIGATOR.showBackBtn();
			NAVIGATOR.changePage('another_phone_confirm_order');
		}else{
			alert(LANG['phoneInputError']);
		}
	};

	var controlledAccountOrderHandler = function(data){
		if(data.result){
			var transactionId = data.response.solicitarPaqueteResult;
			if(transactionId!=null){
		 
			 	NAVIGATOR.changePage('transaction_success');
				document.querySelector('#transaction_success_check_account').onclick = checkAccountView;
				TransactionId = transactionId;
				transactionStatus();
			}else{
				document.querySelector('#controlled_account_error_description').innerHTML = utf8_decode(data.errorDescription);
				NAVIGATOR.changePage('controlled_account_error');
			}
		}
	};
	var controlledAccountOrder = function(){
		var optionId = this.dataset['optionId'];
		MovistarAPI.sendControlledAccountOrder({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
			idPaquete: optionId,
		}, controlledAccountOrderHandler);
	};

	var controlledAccountOrderConfirmation = function(){
  
		var optionId = this.dataset['optionId'];
		var amount = this.dataset['amount'];
		var btn = document.querySelector('#controlled_account_confirm_order_btn');
		btn.dataset['optionId'] = optionId;
		btn.onclick = sendPrePaidOrder;
		document.querySelector('#controlled_account_confirm_order_amount').innerHTML = amount;
		NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('controlled_account_confirm_order');
	};

	var controlledAccountOrderConfirmations = function(){
		 
		var optionId = this.dataset['optionId'];
		var amount = this.dataset['amount'];
		var btn = document.querySelector('#controlled_account_confirm_order_btn');
		btn.dataset['optionId'] = optionId;
		btn.onclick = controlledAccountOrder;
		document.querySelector('#controlled_account_confirm_order_amount').innerHTML = amount;
	//	NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
	
        var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	    controlledAccountView();
	    }   ;
		
		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('controlled_account_confirm_order');
	};

	var setControlledAccountOptions = function(optionsContainer, data, action){
		optionsContainer.innerHTML = '';
		var options = data.response.obtenerDatoExtensionCreditoResult;
			for(var x in options){
			var opt = document.createElement('a');
			opt.dataset['optionId'] = options[x].id;
			opt.dataset['amount'] = options[x].monto;
			opt.classList.add('controlled_account_option');
			opt.href = 'javascript:;';
			opt.innerHTML = '<div class="content-btn"><span class="text">RECARGA -</span><span class="number">$ '+options[x].monto+'</span></div>';
			optionsContainer.appendChild(opt);
		}
		

		var optionLinks = document.querySelectorAll('.controlled_account_option');
		for(var x in optionLinks){
			optionLinks[x].onclick = action;
	
		}
		
	};
	var anotherPhoneOptionsHandler = function(data){
		var optionsContainer = document.querySelector('#another_phone_options_container');
		setControlledAccountOptions(optionsContainer, data, anotherPhoneOrderConfirmation);
	};
	var anotherPhoneView = function(){
		var optionsContainer = document.querySelector('#another_phone_options_container');
		optionsContainer.innerHTML = '';
	    

		NAVIGATOR.showBackBtn();

	    var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	  	
  		var session = MovistarAPI.getSessionUserdata().AccountType;

  		if (session  == "CR")
  		{
  			homeView();
  		}else
  		{
			homeViewCCReload();
  		}
	  	

	  	
	    };


		NAVIGATOR.changePage('another_phone');
		NAVIGATOR.showMoreInfoBtn();
		MovistarAPI.getControlledAccountOptions({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
		}, anotherPhoneOptionsHandler);
	};

	var controlledAccountHandler = function(data){
		var optionsContainer = document.querySelector('#controlled_account_options_container');
		setControlledAccountOptions(optionsContainer, data, controlledAccountOrderConfirmations);
	};
	var controlledAccountInitialized = false;
	var controlledAccountView = function(){	
		NAVIGATOR.showMoreInfoBtn();
		NAVIGATOR.showBackBtn();
		
        var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){	    
	    homeViewCCReload();
	    };


		var optionsContainer = document.querySelector('#controlled_account_options_container');
		optionsContainer.innerHTML = '';		
		NAVIGATOR.changePage('controlled_account');
		
		MovistarAPI.getControlledAccountOptions({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
		}, controlledAccountHandler);     
	
		if(!controlledAccountInitialized){
			controlledAccountInitialized = true;
			document.querySelector('#controlled_account_check_account').onclick = checkAccountView;
			document.querySelector('#controlled_account_another_phone').onclick = anotherPhoneView;
			//document.querySelector('#map_btn').onclick = ns.mapView;
		}
	};

	var prePaidAmountsHandler = function(data){
		var amountsCmb = document.querySelector('#pre_paid_amount');
		amountsCmb.innerHTML = '';
		var minAmount = parseInt(data.response.obtenerDatosRecargaFacilResult.montoMinimo);
		var maxAmount = parseInt(data.response.obtenerDatosRecargaFacilResult.montoMaximo);
		var stepAmount = parseInt(data.response.obtenerDatosRecargaFacilResult.Step);
		var firstAmount = true; // TODO: esto es un parche por error en servicios min>max, dejo pasar el primero
		for(var amount = minAmount; firstAmount || amount<=maxAmount; amount+=stepAmount){
			firstAmount = false;
			var opt = document.createElement('option');
			opt.value = amount;
			opt.appendChild(document.createTextNode(amount));
			amountsCmb.appendChild(opt);
		}
	};
	var prePaidViewInitialized = false;
	var prePaidView = function(){
		NAVIGATOR.showBackBtn();
		NAVIGATOR.showMoreInfoBtn();
		NAVIGATOR.changePage('pre_paid');		 

        var backBtn = document.querySelector('#back_btn');
	   
	    backBtn.onclick = function(){
	    homeViewPPReload();
	    }   ;



		MovistarAPI.getPrePaidAmounts({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
		}, prePaidAmountsHandler);
		if(!prePaidViewInitialized){
			prePaidViewInitialized = true;
			document.querySelector('#confirm_pre_paid_order').onclick = ns.confirmPrePaidOrder;
			document.querySelector('#pre_paid_check_account').onclick = checkAccountView;
		}
	};

 
//#diego
 
	var prePaidInitialized = false;
	var prePaidViewSS = function(){
		NAVIGATOR.showMoreInfoBtn();
		var optionsContainer = document.querySelector('#pre_paid_options_container');
		optionsContainer.innerHTML = '';
		NAVIGATOR.hideBackBtn();
		NAVIGATOR.changePage('pre_paidSS');

		setPrePaidOptions(optionsContainer, null, prePaidOrderConfirmation);

		if(!prePaidInitialized){
			prePaidInitialized = true;
		//	document.querySelector('#pre_paid_check_account').onclick = checkAccountView;
			//document.querySelector('#map_btn').onclick = ns.mapView;
		}
	};


var setPrePaidOptions = function(optionsContainer, data, action){
		optionsContainer.innerHTML = '';
		var options = data || [{
			id: 'CARGA 20 SOS',
			monto: 20,
		},{
			id: 'CARGA 75 SOS',
			monto: 75,
		}];

		for(var x in options){
			var opt = document.createElement('a');
			opt.dataset['optionId'] = options[x].id;
			opt.dataset['amount'] = options[x].monto;
			opt.classList.add('pre_paid_option');
			opt.href = 'javascript:;';
			opt.innerHTML = '<div class="content-btn"><span class="text">RECARGA -</span><span class="number">$ '+options[x].monto+'</span></div>';
			optionsContainer.appendChild(opt);
		}
		var optionLinks = document.querySelectorAll('.pre_paid_option');
		for(var x in optionLinks){
			optionLinks[x].onclick = action;
		}

		NAVIGATOR.showBackBtn();
		 var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	    homeViewPPReload();
	    }   ;

	};


	var prePaidOrderConfirmation = function(){
		var optionId = this.dataset['optionId'];
		var amount = this.dataset['amount'];
		var btn = document.querySelector('#pre_paid_confirm_order_btn');
		btn.dataset['optionId'] = optionId;
		btn.onclick = prePaidOrder;
	
  var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	     prePaidViewSS();
	     }   ;

		document.querySelector('#pre_paid_confirm_order_amount').innerHTML = amount;
		NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
		NAVIGATOR.showBackBtn();
		NAVIGATOR.changePage('pre_paid_confirm_order');
	};

    var prePaidOrder = function(){
		var optionId = this.dataset['optionId'];
		MovistarAPI.sendPrePaidOrderSS({
			idAplicacion: CONFIG.WS_DATA.idAplicacion,
			idPaquete: optionId,
		}, prePaidOrderHandler);
	};

   var prePaidOrderHandler = function(data){
 
		if(data.result){
			var transactionId = data.response.solicitarPaqueteResult;
		 
			if(transactionId!=null){			 
			    NAVIGATOR.changePage('transaction_success'); 		
			     var recargaBalanceBtn = document.querySelector('#transaction_success_check_account');			  
		         recargaBalanceBtn.onclick =  checkAccountView;//ns.gotoHomeViewOld;		
				TransactionId = transactionId;
				transactionStatus();
			}else{
				document.querySelector('#pre_paid_error_description').innerHTML = utf8_decode(data.errorDescription);
				NAVIGATOR.changePage('pre_paid_error');
			}
		}
	};

    var intentautenticarUsuarioPortal = function(){		 
        var userdata = MovistarAPI.getSessionUserdata();	   
		var passw = document.querySelector('#passw').value;
		var email = document.querySelector('#email').value; 		 
		
		
	 
		MovistarAPI.SendIntentAutenticarUsuarioPortal({
			  	idAplicacion: CONFIG.WS_DATA.idAplicacion,			
			  	password: passw, 				  
				email:   email,
		}, intentautenticarUsuarioPortalHandler);
	};

	 var intentautenticarUsuarioPortalMiPerfil = function(){		 
    
		if (validarEmail()){
        
        var userdata = MovistarAPI.getSessionUserdata();	   
		var passw =  document.querySelector('#passw').value; //"5987"
        var email =  document.querySelector('#email').value; //"smartinez@overactiveinc.com"   		 
	   
		MovistarAPI.setEmail(email);
	 
		MovistarAPI.SendIntentAutenticarUsuarioPortalMiPerfil({
			  	idAplicacion: CONFIG.WS_DATA.idAplicacion,			
			  	password: passw, 				  
				email:   email,
		}, intentautenticarUsuarioPortalMiPerfilHandler);
		
		}else
		{
			alert("Debes ingresar un email válido");
		}
	
	};

    var validarEmail = function() {		 
       
    var mailres = true;
            var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
			
			var texto = document.querySelector('#email').value;

            var arroba = texto.indexOf("@", 0);
            if ((texto.lastIndexOf("@")) != arroba) arroba = -1;

            var punto = texto.lastIndexOf(".");

            for (var contador = 0 ; contador < texto.length ; contador++) {
                if (cadena.indexOf(texto.substr(contador, 1), 0) == -1) {
                    mailres = false;
                    break;
                }
            }

            if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (mailres == true) && (texto.indexOf("..", 0) == -1))
                mailres = true;
            else
                mailres = false;

            return mailres;
      
	};


	   var validarEmailWith = function( ) {		 
       
     		 var mailres = true;
            var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
			
			var texto = document.querySelector('#reg_email').value;

            var arroba = texto.indexOf("@", 0);
            if ((texto.lastIndexOf("@")) != arroba) arroba = -1;

            var punto = texto.lastIndexOf(".");

            for (var contador = 0 ; contador < texto.length ; contador++) {
                if (cadena.indexOf(texto.substr(contador, 1), 0) == -1) {
                    mailres = false;
                    break;
                }
            }

            if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (mailres == true) && (texto.indexOf("..", 0) == -1))
                mailres = true;
            else
                mailres = false;

            return mailres;
      
	};



   var intentautenticarUsuarioPortalMiPerfilHandler = function(data){
 		 
 		var resultData = data.response.autenticarUsuarioPortalResult;
 
        
      
		if(resultData.status){
		 
		  MiPerfilLoginSucces();

		  var checked = document.querySelector('#chksession') ;
		
		  if (checked.checked)	
		  {		 	
			   localStorage['passw']  = document.querySelector('#passw').value; 
		       localStorage['email'] = document.querySelector('#email').value;   
		       localStorage['phone'] = MovistarAPI.getSessionUserdata().PhoneNumber;
			  // MovistarAPI.setEmail(localStorage['email']);
			  
		  }
		}
		else
	    {  
 
 		  alert( resultData.descripcion);
 		  document.querySelector('#passw').value = ""; 
		  document.querySelector('#email').value = "";
 		  localStorage.removeItem('passw'); 
		  localStorage.removeItem('email'); 	
		  localStorage.removeItem('phone'); 

	    }
	};




   var intentautenticarUsuarioPortal = function(ppass, pemail){		 
    
		var email = document.querySelector('#email').value; //"smartinez@overactiveinc.com";
     
       	if (validarEmail()){
     
        var userdata = MovistarAPI.getSessionUserdata();	   
		var passw = document.querySelector('#passw').value; //"5987";
		var email = document.querySelector('#email').value; //"smartinez@overactiveinc.com";
      
		MovistarAPI.SendIntentAutenticarUsuarioPortal({
			  	idAplicacion: CONFIG.WS_DATA.idAplicacion,			
			  	password: passw, 				  
				email:   email,
		}, intentautenticarUsuarioPortalHandler);
		
		}
		else
		{
			 
			alert("Debes ingresar un email válido");
		}
		
		};
	


    var intentautenticarUsuarioPortalHandler = function(data){
 		var resultData = data.response.autenticarUsuarioPortalResult;

		if(resultData.status){
		  OprtionPerfilView();	
  
        MovistarAPI.setEmail(document.querySelector('#email').value);
		//Si esta checkeado guardo en localstorage
		var checked = document.querySelector('#chksession') ;

		if (checked.checked)	
		{		 	
			   localStorage['passw'] = document.querySelector('#passw').value; 
		       localStorage['email'] = document.querySelector('#email').value;    
		       localStorage['phone'] = MovistarAPI.getSessionUserdata().PhoneNumber;     
			  // MovistarAPI.setEmail(localStorage['email']);
		}
	    }
		else
	    {             
 		        		 	 		 	 
		 	 
		 		alert(resultData.descripcion);	
		 		document.querySelector('#passw').value = ""; 
				document.querySelector('#email').value = "";
		 		localStorage.removeItem('passw'); 
				localStorage.removeItem('email'); 	
				localStorage.removeItem('phone'); 		 	 				
	    }
	};

	

   var MiPerfilLoginSucces = function(){		 
 	    NAVIGATOR.showBackBtn();
		//NAVIGATOR.showMoreInfoBtn();		 
		NAVIGATOR.changePage('MiperfilLoginSucces');

		var logoutbtn = document.querySelector('#MiperfilLogOut');
		logoutbtn.onclick = function(){	  			
	    MovistarAPI.InitializeSessionPortalUserdata()	
	    	  localStorage.removeItem('passw'); 
		      localStorage.removeItem('email'); 	
		      localStorage.removeItem('phone');
		      document.querySelector('#email').value = ""
		      document.querySelector('#passw').value = ""
      
	     
	    MiPerfilInfo();
	   
	    };

		var changepass = document.querySelector('#MiPerfilChangePasswLogOut');
		changepass.onclick = function(){	  			
	  
	 	  ChangePasswView();
	    
	    };




	  //  MiPerfilRegFreeLogOut


		var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){	    
	   	 ns.moreInfoView();
	    };
	};

   var ChangePasswView = function(){		     
      NAVIGATOR.changePage('changepass');
      var changepassbtn = document.querySelector('#changePassBtn');
      changepassbtn.onclick = IntentCambiarContraseña;

	};
  
    var IntentRegistrarUsuarioPortal = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   




			//var foo = document.querySelector('#reg_DateBorn').value;
		var email = document.querySelector('#reg_email').value;
		 
		if (validarEmailWith()){
			var reg_email = document.querySelector('#reg_email').value;
			var reg_Reemail_re = document.querySelector('#reg_Reemail_re').value;
		
			if (reg_Reemail_re != reg_email){
				alert("Los correos electronicos no coinciden");
				return;
			}

			var reg_full_name = document.querySelector('#reg_full_name').value;
		
			if ( reg_full_name == ""){
				alert("Ingresa tu nombre completo");
				return;
			}
	
			var date = document.querySelector('#reg_DateBorn').value + "";

			if (date == ""){
				alert("Ingresa tu fecha de nacimiento");	
				return;
			}

		 
			var elem = date.split('-');  
			var año = elem[0];  
			var mes = elem[1];  
			var dia = elem[2];

			date = dia + "/" +  mes + "/" + año;
		 
			 
			MovistarAPI.SendIntentRegistrarUsuarioPortal({
				nombre: document.querySelector('#reg_full_name').value,						
			    password: document.querySelector('#reg_Passw').value, 				  
				fechaNacimiento: date,
				email: document.querySelector('#reg_email').value, 				  
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, IntentRegistrarUsuarioPortalHandler);
	
		}else
	
		{		
			alert("Debes ingresar un email válido");
		}

	};
  
        var IntentRegistrarUsuarioPortalHandler = function(data){
 		var resultData = data.response.registrarUsuarioPortalResult;
     	var pass = document.querySelector('#reg_Passw').value;
		var email = document.querySelector('#reg_email').value;
 		 
			if(resultData.status && data.errorDescription == false ){
               document.querySelector('#passw').value = pass; 
		       document.querySelector('#email').value = email;				 
				 
				 	intentautenticarUsuarioPortal(pass, email );			 		 		 
			}
			else
	    	{	 

 		  			alert(resultData.descripcion);
	    	}
	};


	  var IntentrecuperarClavePortal = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
	  // document.querySelector('#forgopassEmail').value = "";	 
		//alert(document.querySelector('#forgopassEmail').value);
			MovistarAPI.SendrecuperarClavePortal({				 		  
				email: document.querySelector('#forgopassEmail').value, //document.querySelector('#forgopassEmail').value  
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, IntentrecuperarClavePortalHandler);
	};
  
        var IntentrecuperarClavePortalHandler = function(data){
 		var resultData = data.response.recuperarClavePortalResult;
    	//	var pass = document.querySelector('#reg_Passw').value;
		//	var email = document.querySelector('#reg_email').value;
	 
			if(resultData.status){
				
				alert("Se ha enviado un mail a tu casilla de correo con una nueva contraseña"); 	intentautenticarUsuarioPortal(pass, email );			 		 		 
			}
			else
	    	{	             
 		  		 alert(resultData.descripcion);
	    	}
	};



	  var IntentResumenLlamada = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
        var monthDiff = MovistarAPI.getSessionActualMonth();	  		
			MovistarAPI.SendResumenLlamada({				 		  
				MonthDiff:  monthDiff, 
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, ResumenLlamadaHandler);
	};
  
    var ResumenLlamadaHandler = function(data){
 		
 		var resultData = data.response.getResumenCallsResult.segundosSalientes;

       if(data.errorDescription == false){  
        
        	NAVIGATOR.changePage('AutoGestionLlamadas');

			var saliente = document.querySelector('#MinutosSalientes');
       	    saliente.textContent = "Minutos Salientes: " + convertirSegundos(data.response.getResumenCallsResult.segundosSalientes);
			//data.response.getResumenCallsResult.segundosSalientes
			var entrante = document.querySelector('#MinutosEntrantes');
        	entrante.textContent = "Minutos Entrantes: " + convertirSegundos(data.response.getResumenCallsResult.segundosEntrantes);	
	  
	  	    var dt = new Date();
			var fecha = document.querySelector('#LLAMADAFecha');
			var dia = parseInt(dt.getDate()) - 2;		 
	 
	 		 
       		fecha.textContent = "Actualizado al " +  dia +	"/"	 +  parseInt(dt.getMonth() + 1);		        
        }
    	else
    	{
    		alert(utf8_decode(data.errorDescription));
    	}
  	     
	};

  
  var IntentResumenSMS = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
	   var monthDiff = MovistarAPI.getSessionActualMonth();	  
	 
			MovistarAPI.SendResumenSMS({				 		  
				MonthDiff: monthDiff, 
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, ResumenSMSHandler);
	};
  
        var ResumenSMSHandler = function(data){
 		
 		var resultData = data.response.getResumenSMSsResult;		
 	
 	if(data.errorDescription == false){  
  
			 NAVIGATOR.changePage('AutoGestionMensajes');
 	  		 var saliente = document.querySelector('#SMSSalientes');
       		 saliente.textContent = "SMS Enviados: " + data.response.getResumenSMSsResult.smsEnviados;
		 
		     var entrante = document.querySelector('#SMSEntrantes');
             entrante.textContent = "SMS Recibidos: " + data.response.getResumenSMSsResult.smsRecibidos;	
	   
	         var dt = new Date();
		     var fecha = document.querySelector('#SMSFecha');
		     var dia = parseInt(dt.getDate()) - 2;
		 
	         fecha.textContent = "Actualizado al " +  dia +	"/"	 +  parseInt(dt.getMonth() + 1);	
		 }
    	 else
    	 {
    		 alert(utf8_decode(data.errorDescription));
         }
	};

	 var IntentResumenDATOS = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
		 var monthDiff = MovistarAPI.getSessionActualMonth();	   
			MovistarAPI.SendResumenDatos({				 		  
				MonthDiff: monthDiff, 
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, ResumenDatosHandler);
	};
  
        var ResumenDatosHandler = function(data){
 
 	  	var resultData = data.response.getResumenDataResult;
 		
 		if(data.errorDescription == false){  

				

			NAVIGATOR.changePage('AutoGestionDatos');	
	 	  	var saliente = document.querySelector('#Datossalientes');
	        saliente.textContent = "Cantidad de Datos: " +  kbytes2mbytes(data.response.getResumenDataResult.datosTransferidos);
			 
			var descargas = document.querySelector('#Descargas');
	        descargas.textContent = "Contenidos Descargados " + data.response.getResumenDataResult.cantContenidos;	

	        var Mms = document.querySelector('#Mms');
	        Mms.textContent = "Cantidad de MMS: " + data.response.getResumenDataResult.cantMMS;	
		   
		    var dt = new Date();
			var fecha = document.querySelector('#DatosFecha');
			var dia = parseInt(dt.getDate()) - 2;
			 		 
	        fecha.textContent = "Actualizado al " +  dia +	"/"	 +  parseInt(dt.getMonth() + 1);; 

         }
    	 else
    	 {
    		 alert(utf8_decode(data.errorDescription));
         }
	};


        function kbytes2mbytes(kbytes) {
            var sizes = [ 'KB', 'MB', 'GB', 'TB'];
            if (kbytes == 0) return '0 KB';
            var i = parseInt(Math.floor(Math.log(kbytes) / Math.log(1024)));
            if (i == 0) return kbytes + ' ' + sizes[i];
            return (kbytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
           
        };

		 var IntentVerDetalleSMS = function(){		     
		       var userdata = MovistarAPI.getSessionUserdata();	   
			   var monthDiff = MovistarAPI.getSessionActualMonth();	   
			   MovistarAPI.setSessionResetPagina()
					MovistarAPI.SendVerDetalleSMS({				 		  
					    NumPagina: 1,
						MonthDiff: monthDiff,
						CantPorPagina: 30,
						idAplicacion:   CONFIG.WS_DATA.idAplicacion,

				}, VerDetalleSMSHandler);
		 };
		  
        var VerDetalleSMSHandler = function(data)
        {	 
		var resultData = data.response.getSMSsInfoResult;
		 
		if(data.errorDescription == false){
 
		if (data.response.getSMSsInfoResult== null || data.response.getSMSsInfoResult == ""){			 
			 var smsMes = document.querySelector('#smsMes').textContent;    
		     alert("No hay sms correspondientes al mes de " + smsMes.toLowerCase());
			 return		
		 }
			var getMoreBtn = document.querySelector('#getMoreBtn');
			getMoreBtn.style.visibility='visible';
			NAVIGATOR.changePage('VerDetalleSms');	
			var smsMes = document.querySelector('#smsMes'); 
		
	    var anio; 		 
 
		if ( smsMes.textContent.replace("DE", "")  == " Diciembre" || getMonthString() == " Noviembre" )
		{			 
 
			if (getMonthString() == "Enero" || getMonthString() == "Febrero")
			{
				anio = new Date().getFullYear() - 1;
			}else
			{
				anio = new Date().getFullYear();
			}
		
		}else
		{
			anio = new Date().getFullYear();
		}
	 


		var optionsContainer = document.querySelector('#VerDetalleSms_container');
		optionsContainer.innerHTML = '<p class="title_detail_big">DETALLE DE SMS</p> - <p class="title_detail_small">' + smsMes.textContent.replace("DE","") +' ' + anio +'</p>';
		optionsContainer.innerHTML = optionsContainer.innerHTML + '<div class="spacer_details">';
  	 		
		var options = data.response.getSMSsInfoResult;
		var opt = document.createElement('table');
		opt.setAttribute("id", "smsTable");
		opt.setAttribute("class","details_table_sms");
				
		opt.innerHTML = opt.innerHTML + '<tr> <th>Día</th> <th>Hora</th> <th>Tipo</th> <th>Número</th> </tr>';
		
		var origen =  MovistarAPI.getSessionUserdata().PhoneNumber;
				 
		for(var x in options){
				 var img = '';
		 	 	 	 
		 		 if ("09" + options[x].origen == origen)
				 {			 
					img = '<img src="img/msj_saliente.png" />';
				 } else
				 {
				 	img = '<img src="img/msj_entrante.png" />';		 
				 }

				var jsonDate = options[x].fecha;	
				var tiempo = new Date(parseInt(jsonDate.substr(6)));

			    var month = parseInt(tiempo.getMonth() + 1);
			    var dia = parseInt(tiempo.getDate());	
			   
		 		if (dia < 10)
		 		{
		 			dia = "0" + String(dia) 
		 		}

		 		if (month < 10)
		 		{
		 			month = "0" + String(month) 
		 		}

			    var da =  "" +  dia +	"/"	 +  month;		 
			    var h = parseInt(tiempo.getHours());
			    var m = parseInt(tiempo.getMinutes());
			    var hora =  "" +  h +	":"	 +  m;

					opt.innerHTML = opt.innerHTML + '<tr > <td>' + da + '</td> <td>' + hora +  '</td> <td>' + img + '</td> <td class="blue">'+ options[x].origen+' </td> </tr>';		   
	    } 		
 
  		optionsContainer.appendChild(opt);  
	    
	    var VerDetalleSms = document.querySelector('#VerDetalleSms');		 		 
			var getMoreBtn = document.querySelector('#getMoreBtn');
			getMoreBtn.onclick = function(){			 
			MovistarAPI.setSessionPagina();
			IntentVerDetalleMoreSMS();
		};

		}
		else
		{ 		   
			alert(utf8_decode(data.errorDescription));	 
		}

	};

	 var IntentVerDetalleMoreSMS = function(){		     
		       var userdata = MovistarAPI.getSessionUserdata();	   
			   var monthDiff = MovistarAPI.getSessionActualMonth();	   
				var pagina = MovistarAPI.getSessionPagina()
					MovistarAPI.SendVerDetalleSMS({				 		  
					    NumPagina: pagina,
						MonthDiff: monthDiff,
						CantPorPagina: 30,
						idAplicacion:   CONFIG.WS_DATA.idAplicacion,

				}, VerDetalleMoreSMSHandler);
		 };
		  
        var VerDetalleMoreSMSHandler = function(data){	 
		var resultData = data.response.getSMSsInfoResult;
		 
		if(data.errorDescription == false){
 
		if (data.response.getSMSsInfoResult== null || data.response.getSMSsInfoResult == ""){			 			 		     
			 var getMoreBtn = document.querySelector('#getMoreBtn');
			 getMoreBtn.style.visibility='hidden';
			 var scroll = document.querySelector('#verdetallesms');
			 var cantidad = MovistarAPI.getSessionPagina();
			 var px = Math.floor(2000 * cantidad );		 			 
			 window.scrollBy(0,px);  
    		 scrolldelay = setTimeout('pageScroll()',100);  
			 return		
		}
				 		
		var optionsContainer = document.querySelector('#smsTable');
		 	
		var options = data.response.getSMSsInfoResult;
	 
		var origen =  MovistarAPI.getSessionUserdata().PhoneNumber;
				 
		for(var x in options){
				
				var tr = document.createElement('tr');
				var img = '';
		 	 	 	 
		 		 if ("09" + options[x].origen == origen)
				 {			 
					img = '<img src="img/msj_saliente.png" />';
				 } else
				 {
				 	img = '<img src="img/msj_entrante.png" />';		 
				 }

				var jsonDate = options[x].fecha;	
				var tiempo = new Date(parseInt(jsonDate.substr(6)));

			    var month = parseInt(tiempo.getMonth() + 1);
			    var dia = parseInt(tiempo.getDate());	
			   
		 		if (dia < 10)
		 		{
		 			dia = "0" + String(dia) 
		 		}

		 		if (month < 10)
		 		{
		 			month = "0" + String(month) 
		 		}

			    var da =  "" +  dia +	"/"	 +  month;		 
			    var h = parseInt(tiempo.getHours());
			    var m = parseInt(tiempo.getMinutes());
			    var hora =  "" +  h +	":"	 +  m;

				tr.innerHTML =  '<tr > <td>' + da + '</td> <td>' + hora +  '</td> <td>' + img + '</td> <td class="blue">'+ options[x].origen+' </td> </tr>';		   
				optionsContainer.appendChild(tr);
	    } 		   	 

		
			    var scroll = document.querySelector('#verdetallesms');
			    var cantidad = MovistarAPI.getSessionPagina();
			    var px = Math.floor(1500 * cantidad );		 			 
			    window.scrollBy(0,px);  
    			scrolldelay = setTimeout('pageScroll()',100);  
		}
		else
		{ 		   
			alert(utf8_decode(data.errorDescription));	 
		}

	};
 


	 var IntentVerDetalleLlamada = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
	   var monthDiff = MovistarAPI.getSessionActualMonth();	   
		 MovistarAPI.setSessionResetPagina();
			MovistarAPI.SendVerDetalleLlamada({				 		  
			    NumPagina: 1,
				MonthDiff: monthDiff,
				CantPorPagina: 30,
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, VerDetalleLlamadaHandler);
	 };
  
        var VerDetalleLlamadaHandler = function(data){
		 
	 		var resultData = data.response.getCallsInfoResult;
         	
	 		if(data.errorDescription == false){

	 		if (data.response.getCallsInfoResult== null || data.response.getCallsInfoResult == ""){
			    var a =  document.querySelector('#llamadaMes').textContent;
				alert("No hay llamadas correspondientes al mes de " + a.toLowerCase());
			return
			
			}

					var getMoreBtn = document.querySelector('#getMoreBtn');
			 getMoreBtn.style.visibility='visible';
			NAVIGATOR.changePage('VerDetalleSms');
			var llamadaMes = document.querySelector('#llamadaMes'); 
			
			var anio;
	 

			if ( llamadaMes.textContent.replace("DE", "")  == " Diciembre" || llamadaMes.textContent.replace("DE", "")  == " Noviembre" )
			{
				 

				if (getMonthString() == "Enero" || getMonthString() == "Febrero")
				{
					anio = new Date().getFullYear() - 1;
				}else
				{
					anio = new Date().getFullYear();
				}
			
			}else
			{
				anio = new Date().getFullYear();
			}


			var optionsContainer = document.querySelector('#VerDetalleSms_container');
			optionsContainer.innerHTML = '<p class="title_detail_big">DETALLE DE LLAMADAS</p> - <p class="title_detail_small">' + llamadaMes.textContent.replace("DE", "") +' ' + anio +'</p>';
		    optionsContainer.innerHTML = optionsContainer.innerHTML + '<div class="spacer_details">';
			
			//optionsContainer.innerHTML = "";

			var options = data.response.getCallsInfoResult;//[{"descripcion":"Transf. a Voice Mail","destino":"59894007684","duracion":20,"fecha":"\/Date(1386943062000-0200)\/","origen":"*********","sentido":"Entrante"},{"descripcion":"Transf. a Voice Mail","destino":"59894007684","duracion":20,"fecha":"\/Date(1387215322000-0200)\/","origen":"*********","sentido":"Entrante"}];//data.response.getCallsInfo;			
			var opt = document.createElement('table');
	    	opt.setAttribute("class","details_table");			 
			opt.setAttribute("id", "llamadaTable");

			opt.innerHTML = '<tr> <th>Día</th> <th>Tipo</th> <th>Número</th> <th>Duración</th> </tr>';
			
			var destino =  MovistarAPI.getSessionUserdata().PhoneNumber;
					 
			 for(var x in options){
					 var img = '';
					 var numero = '';
			 	 
			 		 if (options[x].sentido == "Entrante")
					 {			 
						img = '<img src="img/llamada_entrante.png" />';
						numero = options[x].origen;
					 } else
					 {
					 	img = '<img src="img/llamada_saliente.png" />';
					 	numero = options[x].destino;
					 }
					
					var jsonDate = options[x].fecha;
					var tiempo = new Date(parseInt(jsonDate.substr(6)));
				    var month = parseInt(tiempo.getMonth() + 1);
				    var dia = parseInt(tiempo.getDate());	
				  
					if (dia < 10)
			 		{
			 			dia = "0" + String(dia) 
			 		}

			 		if (month < 10)
			 		{
			 			month = "0" + String(month) 
			 		}


				    var da =  "" +  dia +	"/"	 +  month;	
 					var duracion = convertirSegundosSinString(options[x].duracion);
					opt.innerHTML = opt.innerHTML + '<tr > <td>' + da + '</td> <td>' + img + '</td> <td class="green">' + numero  +  '</td>  <td>'+  duracion +' </td> </tr> ';		   
			 } 		
	 
		   //opt.innerHTML = opt.innerHTML + ' ';
	  		optionsContainer.appendChild(opt);

			var getMoreBtn = document.querySelector('#getMoreBtn');
					getMoreBtn.onclick = function(){			 
					MovistarAPI.setSessionPagina();
					IntentVerDetalleMoreLlamada();
			};


	  		}
	  		 else
	  		 { 		   
	  		  	 alert(utf8_decode(data.errorDescription));	 
			 }
	};



	 var IntentVerDetalleMoreLlamada = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
	   var monthDiff = MovistarAPI.getSessionActualMonth();	   
		 var pagina = MovistarAPI.getSessionPagina()
			MovistarAPI.SendVerDetalleLlamada({				 		  
			    NumPagina: pagina,
				MonthDiff: monthDiff,
				CantPorPagina: 30,
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, VerDetalleLlamadaMoreHandler);
	 };
  
        var VerDetalleLlamadaMoreHandler = function(data){
		 
	 		var resultData = data.response.getCallsInfoResult;
         	
	 		if(data.errorDescription == false){

	 		if (data.response.getCallsInfoResult== null || data.response.getCallsInfoResult == ""){
			 		 
			 	var getMoreBtn = document.querySelector('#getMoreBtn');
			 	getMoreBtn.style.visibility='hidden';
			 	var scroll = document.querySelector('#verdetallesms');
			    var cantidad = MovistarAPI.getSessionPagina();
			    var px = Math.floor(2000 * cantidad );		 			 
				window.scrollBy(0,px);  
	    		scrolldelay = setTimeout('pageScroll()',100);  
				   
			return
			
			}

			  
			var optionsContainer = document.querySelector('#llamadaTable');
			 
			var options = data.response.getCallsInfoResult;//[{"descripcion":"Transf. a Voice Mail","destino":"59894007684","duracion":20,"fecha":"\/Date(1386943062000-0200)\/","origen":"*********","sentido":"Entrante"},{"descripcion":"Transf. a Voice Mail","destino":"59894007684","duracion":20,"fecha":"\/Date(1387215322000-0200)\/","origen":"*********","sentido":"Entrante"}];//data.response.getCallsInfo;			
		 
			var destino =  MovistarAPI.getSessionUserdata().PhoneNumber;
					 
			 for(var x in options){
					 var tr = document.createElement('tr');

					 var img = '';
					 var numero = '';
			 	 
			 		 if (options[x].sentido == "Entrante")
					 {			 
						img = '<img src="img/llamada_entrante.png" />';
						numero = options[x].origen;
					 } else
					 {
					 	img = '<img src="img/llamada_saliente.png" />';
					 	numero = options[x].destino;
					 }
					
					var jsonDate = options[x].fecha;
					var tiempo = new Date(parseInt(jsonDate.substr(6)));
				    var month = parseInt(tiempo.getMonth() + 1);
				    var dia = parseInt(tiempo.getDate());	
				  
					if (dia < 10)
			 		{
			 			dia = "0" + String(dia) 
			 		}

			 		if (month < 10)
			 		{
			 			month = "0" + String(month) 
			 		}


				    var da =  "" +  dia +	"/"	 +  month;	
 					var duracion = convertirSegundosSinString(options[x].duracion);
					
					tr.innerHTML =  '<tr > <td>' + da + '</td> <td>' + img + '</td> <td class="green">' + numero  +  '</td>  <td>'+  duracion +' </td> </tr> ';		   
					optionsContainer.appendChild(tr);
			 } 		
	 		
	 		 var scroll = document.querySelector('#verdetallesms');
			 var cantidad = MovistarAPI.getSessionPagina();
			 var px = Math.floor(2000 * cantidad );		 			 
			 window.scrollBy(0,px);  
    		 scrolldelay = setTimeout('pageScroll()',100);  
		 
	  		
	  		}
	  		 else
	  		 { 		   
	  		  	 alert(utf8_decode(data.errorDescription));	 
			 }
	};





	 var IntentVerDetalleDatos = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
	   var monthDiff = MovistarAPI.getSessionActualMonth();	   
	   MovistarAPI.setSessionResetPagina()
			MovistarAPI.SendVerDetalleDatos({				 		  
			    NumPagina: 1,
				MonthDiff: monthDiff,
				CantPorPagina: 30,
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, VerDetalleDatosHandler);
	};
  
        var VerDetalleDatosHandler = function(data){
 
		
		if(data.errorDescription == false){

		if (data.response.getDataInfoResult== null || data.response.getDataInfoResult == ""){
			 var a =  document.querySelector('#datosMes').textContent;
			alert("No hay datos correspondientes al mes de " + a.toLowerCase());
			return
					
		}
				var getMoreBtn = document.querySelector('#getMoreBtn');
			 getMoreBtn.style.visibility='visible';
	  	var datosMes = document.querySelector('#datosMes'); 
       

		var anio;
 

		if ( datosMes.textContent.replace("DE", "")  == " Diciembre" || getMonthString() == " Noviembre" )
		{
			 

			if (getMonthString() == "Enero" || getMonthString() == "Febrero")
			{
				anio = new Date().getFullYear() - 1;
			}else
			{
				anio = new Date().getFullYear();
			}
		
		}else
		{
			anio = new Date().getFullYear();
		}




		NAVIGATOR.changePage('VerDetalleSms');
		var optionsContainer = document.querySelector('#VerDetalleSms_container');
		optionsContainer.innerHTML = '<p class="title_detail_big">DETALLE DE DATOS</p> - <p class="title_detail_small">' +  datosMes.textContent.replace("DE", "") +' ' + anio +'</p>';
		optionsContainer.innerHTML = optionsContainer.innerHTML + '<div class="spacer_details">';
  	
		//optionsContainer.innerHTML = "";
		var options = data.response.getDataInfoResult;
		var opt = document.createElement('table');
		opt.setAttribute("class","details_table_data");
		opt.setAttribute("id", "datosTable");
		//opt.classList.add('faqs_category_question');
		opt.innerHTML = '<tr> <th>Día</th> <th>Valor</th> <th>Unidad</th></tr>';
		
		var destino =  MovistarAPI.getSessionUserdata().PhoneNumber;
				 
		for(var x in options){		  	  
		
		var jsonDate = options[x].fecha;
	
		var tiempo = new Date(parseInt(jsonDate.substr(6)));
		//document.write(k + "<br/>");

	    var month = parseInt(tiempo.getMonth() + 1);
	    var dia = parseInt(tiempo.getDate());	
	  
		if (dia < 10)
 		{
 			dia = "0" + String(dia) 
 		}

 		if (month < 10)
 		{
 			month = "0" + String(month) 
 		}


	    var da =  "" +  dia +	"/"	 +  month;	

			opt.innerHTML = opt.innerHTML + '<tr > <td>' + da + '</td> <td>' + options[x].valor + '</td> <td>' + options[x].unidad  +  '</td>  </tr> ';		   
	    } 		
 
	 
  		optionsContainer.appendChild(opt);
  	 	 		
		var getMoreBtn = document.querySelector('#getMoreBtn');
			getMoreBtn.onclick = function(){			 
			MovistarAPI.setSessionPagina();
			IntentVerDetalleMoreDatos();
		};


		}
		else
		{ 		   
			alert(utf8_decode(data.errorDescription));	 
		}

	};




 	var IntentVerDetalleMoreDatos = function(){		     
       var userdata = MovistarAPI.getSessionUserdata();	   
	   var monthDiff = MovistarAPI.getSessionActualMonth();	   
	   var pagina = MovistarAPI.getSessionPagina()
	 
			MovistarAPI.SendVerDetalleDatos({				 		  
			    NumPagina: pagina,
				MonthDiff: monthDiff,
				CantPorPagina: 30,
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, VerDetalleDatosMoreHandler);
	};
  
    var VerDetalleDatosMoreHandler = function(data){
 
		if(data.errorDescription == false){

		if (data.response.getDataInfoResult== null || data.response.getDataInfoResult == ""){
				var getMoreBtn = document.querySelector('#getMoreBtn');
			 	getMoreBtn.style.visibility='hidden';
			 	var scroll = document.querySelector('#verdetallesms');
			    var cantidad = MovistarAPI.getSessionPagina();
			    var px = Math.floor(2000 * cantidad );		 			 
			    window.scrollBy(0,px);  
    		    scrolldelay = setTimeout('pageScroll()',100);  
			return				
		}
 
		var options = data.response.getDataInfoResult;
	 
		var optionsContainer = document.querySelector('#datosTable');
 
		 
		var destino =  MovistarAPI.getSessionUserdata().PhoneNumber;
				 
		for(var x in options){		  	  
			
		//alert("tiene");	
				var tr = document.createElement('tr');
				var jsonDate = options[x].fecha;
			
				var tiempo = new Date(parseInt(jsonDate.substr(6)));
			    var month = parseInt(tiempo.getMonth() + 1);
			    var dia = parseInt(tiempo.getDate());	
			  
				if (dia < 10)
		 		{
		 			dia = "0" + String(dia) 
		 		}

		 		if (month < 10)
		 		{
		 			month = "0" + String(month) 
		 		}


			    var da =  "" +  dia +	"/"	 +  month;	

				//opt.innerHTML = opt.innerHTML + '<tr > <td>' + da + '</td> <td>' + options[x].valor + '</td> <td>' + options[x].unidad  +  '</td>  </tr> ';		   
	  			  tr.innerHTML =  '<tr > <td>' + da + '</td> <td>' + options[x].valor + '</td> <td>' + options[x].unidad  +  '</td>  </tr> ';		   
	  			//tr.innerHTML =  '<tr > <td>' + da + '</td> <td>' + hora +  '</td> <td>' + img + '</td> <td class="blue">'+ options[x].origen+' </td> </tr>';		   
				optionsContainer.appendChild(tr);
	    } 		
  		 	 var scroll = document.querySelector('#verdetallesms');
			 var cantidad = MovistarAPI.getSessionPagina();
			 var px = Math.floor(2000 * cantidad );		 			 
			 window.scrollBy(0,px);  
    		 scrolldelay = setTimeout('pageScroll()',100);  
	   // opt.innerHTML = opt.innerHTML + '</table>';
  		//optionsContainer.appendChild(opt);

  	    //var VerDetalleSms = document.querySelector('#VerDetalleSms');		 		 
	


		}
		else
		{ 		   
			alert(utf8_decode(data.errorDescription));	 
		}

	};







	    var IntentObtenerFactura = function(){		     
        var userdata = MovistarAPI.getSessionUserdata();	   
	  
	 		if (MovistarAPI.getSessionUserdata().numberOfAccounts > 1 || MovistarAPI.getSessionUserdata().numberOfAccounts == null){
	 				var numeroCuenta = prompt("Ingresa tu número de cliente si tu número de cliente es 1234-5, debes ingresar 12345");
						if (numeroCuenta == null || numeroCuenta == "")
							return;

			}else
			{		
					numeroCuenta = null;
			}		
	

		MovistarAPI.setSessionNumeroCuenta(numeroCuenta);
	  

	    var monthDiff = MovistarAPI.getSessionActualMonth();	   
		    	MovistarAPI.sendObtenerUltimaFactura({				 		  
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,
			    numeroCuenta: numeroCuenta,						
	    	}, IntentObtenerFacturaHandler);
	    };
  
        var IntentObtenerFacturaHandler = function(data){	 	
    	var resultData = data.response.getUltimaFacturaResult;
		 
	

		if(data.errorDescription == false){
        	
        	var facturatxt = document.querySelector('#facturatxt');
	    	facturatxt.innerHTML = resultData.numero;
			var vencimientotxt = document.querySelector('#vencimientotxt');
	    	vencimientotxt.innerHTML = resultData.fecha_vencimiento;
			
			var importetxt = document.querySelector('#importetxt');
	    	importetxt.innerHTML = "$ " +  resultData.monto;


    
			NAVIGATOR.showBackBtn();
			NAVIGATOR.changePage('ultimaFactura');
					 
			var backBtn = document.querySelector('#back_btn');
			backBtn.onclick = function(){
			OprtionPerfilView();
			};
			  
	        var autoGestionBtn = document.querySelector('#auto_gestion1');			  
	        autoGestionBtn.onclick =  IntentDescargarArchivoFactura;//ns.gotoHomeViewOld;		

    	}
    	else
    	{
    		alert(utf8_decode(data.errorDescription));
    	}
    };



       var IntentDescargarArchivoFactura = function(){		     
    		
    	  alert("Próximamente se  podrá descargar la factura");   				
	 
	    };
  
        var IntentDescargarArchivoFacturaHandler = function(data){	 	
     
   		};


 
//#finDiego

	var autoLoginCallback = function(data){
		if(data.result){
		    gotoHomeView();
		    //#1.1
		    var userdata = MovistarAPI.getSessionUserdata();
		    var datObj = JSON.parse(localStorage['usuario']);
		    if (datObj.PhoneNumber != userdata.PhoneNumber) {
		        // MovistarAPI.setSessionUserdata(null);
		        MovistarAPI.getSessionPortalUserdata(null);
		        document.querySelector('#passw').value = "";
		        document.querySelector('#email').value = "";		       
		        localStorage.removeItem("passw");
		        localStorage.removeItem("email");
		        localStorage.removeItem("usuario");
		        localStorage.removeItem("fecha");
		    }
		    //#1.1
		}else{
			authFailView();
		}
	};
	ns.autoLogin = function(){
		MovistarAPI.intentAutoLogin({}, autoLoginCallback);
	};

	var sendCodeCallback = function(data){
		if(data.result){
			document.querySelector('#code').classList.remove('hidden');
			document.querySelector('#code_validation').classList.remove('hidden');
			alert(LANG['codeSent']);
		}else{
			var errorText = utf8_decode(data.errorDescription);
			alert(errorText);
		}
	};
	ns.sendCode = function(){
		document.querySelector('#code').classList.add('hidden');
		document.querySelector('#code_validation').classList.add('hidden');
		
		var codeValue = document.querySelector('#code').value;
		var phoneValue = document.querySelector('#phone').value;
		if(MovistarAPI.validatePhone(phoneValue)){
			MovistarAPI.sendActivationCode({
				idAplicacion: CONFIG.WS_DATA.idAplicacion,
				numeroTelefono: phoneValue,
			}, sendCodeCallback);
		}else{
			alert(LANG['phoneInputError']);
		}
	};

	var gotoHomeView = function(){
	  
	    NAVIGATOR.userHomeView = homeView
	  
	    homeView();
	};

	var gotoHomeReload = function(){		 
 
		var userdata = MovistarAPI.getSessionUserdata();
		switch(userdata.AccountType){
			case 'PP':
				NAVIGATOR.userHomeView = homeViewPPReload;		 
				homeViewPPReload();
				break;
			case 'CC':
				NAVIGATOR.userHomeView = homeViewCCReload;
			    homeViewCCReload();	 
				break;
			case 'CR':
				NAVIGATOR.userHomeView = anotherPhoneView;				 
				anotherPhoneView();
				break;
		}

	};

	var gotoHomeSOS = function(){
		var userdata = MovistarAPI.getSessionUserdata();
 
		switch(userdata.AccountType){
			case 'PP':
				NAVIGATOR.userHomeView = prePaidView;
				prePaidViewSS();
				break;
			case 'CC':
				NAVIGATOR.userHomeView = controlledAccountView;
				controlledAccountViewSS();
				break;
			case 'CR':
				NAVIGATOR.userHomeView = anotherPhoneView;
				anotherPhoneViewSS();
				break;
		}
	};

    var gotoEasyReload = function(){
		
		var userdata = MovistarAPI.getSessionUserdata();
		switch(userdata.AccountType){
			case 'PP':
				NAVIGATOR.userHomeView = prePaidView;		 
				prePaidView();
				break;
			case 'CC':			 
				controlledAccountView();
				break;
			case 'CR':
				NAVIGATOR.userHomeView = anotherPhoneView;				 
				anotherPhoneView();
				break;
		}
	};

	var validateCodeCallback = function(data){
		if(data.result){	
			gotoHomeView();
		}else
		{
			alert(utf8_decode(data.errorDescription));
		}
	};
	ns.validateCode = function(){
		var codeValue = document.querySelector('#code').value;
		if(codeValue!=''){
			MovistarAPI.intentExternalLogin({
				idAplicacion: CONFIG.WS_DATA.idAplicacion,
				numeroTelefono: document.querySelector('#phone').value,
				codigoActivacion: codeValue,
			}, validateCodeCallback);
		}else{
			alert(LANG['codeInputError']);	
		}
	};

	var offlineViewInitialized = false;
	ns.offlineView = function(){
		NAVIGATOR.hideMoreInfoBtn();
		if(!offlineViewInitialized){
			document.querySelector('#offline_reintent').onclick = function(){
				NAVIGATOR.changePage('splash');
				CONNECTION.checkOnlineCallback = ns.autoLogin;
				CONNECTION.checkOnline();
			};
			document.querySelector('#offline_exit').onclick = function(){
				window.close();
			};
			offlineViewInitialized = true;
		}
	};

	var hideFooter = function(){
		document.querySelector('footer').style.display = 'none';
	};
	var showFooter = function(){
		document.querySelector('footer').style.display = 'block';
	};

	ns.init = function(){
		NAVIGATOR.changePage('splash');
		CONNECTION.checkOnlineCallback = ns.autoLogin;
		CONNECTION.checkOnline();
		MainApp.offlineView();
		NAVIGATOR.moreInfoPageView = ns.moreInfoView;

		var textInputs = document.querySelectorAll('.input_text');
		for(var x in textInputs){
			textInputs[x].onfocus = hideFooter;
			textInputs[x].onblur = showFooter;
		}
	};

	var faqsCategoryHandler = function(data){
		NAVIGATOR.changePage('faqs_category');
		var optionsContainer = document.querySelector('#faqs_category_container');
		var options = data.response.getFaqByCategoriaIdResult;
		for(var x in options){
			var opt = document.createElement('a');
			opt.href = 'javascript:;';
			opt.classList.add('faqs_category_question');
			opt.innerHTML = '<div class="faq-title"><span>'+options[x].pregunta+'</span><img src="img/ic-arrow-right-blue.png" /></div>';
			optionsContainer.appendChild(opt);

			var optText = document.createElement('div');
			optText.classList.add('faq-text');
			optText.innerHTML = options[x].respuesta;
			optionsContainer.appendChild(optText);
		}

		var optionLinks = document.querySelectorAll('.faqs_category_question');
		for(var x in optionLinks){
			optionLinks[x].onclick = function(){
				var answer = this.nextElementSibling;
				if(answer.style.display == 'block'){
					this.classList.remove('active');
					answer.style.display = 'none';
				}else{
					this.classList.add('active');
					answer.style.display = 'block';
				}
			};
		}
	};
	var faqsCategoryView = function(categoryId){
		NAVIGATOR.backPageView = ns.faqsView;
		
		document.querySelector('#faqs_category_container').innerHTML = '';
		MovistarAPI.getFaqsCategory({
			idCategory: categoryId
		}, faqsCategoryHandler);
	};

	var faqsHandler = function(data){
		var optionsContainer = document.querySelector('#faqs_container');
		var options = data.response.getCategoriasFaqResult;
		for(var x in options){
			var opt = document.createElement('a');
			opt.dataset['optionId'] = options[x].id;
			opt.classList.add('faq_category');
			opt.href = 'javascript:;';
			opt.innerHTML = '<div class="faq-title-category"><span>'+options[x].descripcion+'</span><img src="img/ic-arrow-right-blue.png" /></div>';
			optionsContainer.appendChild(opt);
		}
		var optionLinks = document.querySelectorAll('.faq_category');
		for(var x in optionLinks){
			optionLinks[x].onclick = function(){
				faqsCategoryView(this.dataset['optionId']);
			};
		}
	};
	ns.faqsView = function(){		
		NAVIGATOR.backPageView = ns.moreInfoView;
		NAVIGATOR.showBackBtn();
		
		document.querySelector('#faqs_container').innerHTML = '';
		MovistarAPI.getFaqs({}, faqsHandler);
	};

	ns.ChangeLine = function () {

	    var datObj = MovistarAPI.getSessionUserdata();

	    var r = confirm("¿Esta seguro que desea cambiar el número de la línea actual (" + datObj.PhoneNumber + ")?");
	    if (r == true) {
	        MovistarAPI.intentAutoLogin({}, autoLoginCallback);
	        MovistarAPI.setSessionUserdata(null);
	        MovistarAPI.setSessionPortalUserdata(null);
	        document.querySelector('#passw').value = "";
	        document.querySelector('#email').value = "";
	        localStorage.removeItem("passw");
	        localStorage.removeItem("email");
	        localStorage.removeItem("usuario");
	        localStorage.removeItem("fecha");
	        var codeInput = document.querySelector('#code');
	        codeInput.value = '';
	        var phoneInput = document.querySelector('#phone');
	        phoneInput.value = '';
	    }


	};

	var moreInfoInitialized = false;
	ns.moreInfoView = function(){
		//NAVIGATOR.backPageView = NAVIGATOR.userHomeView;
		NAVIGATOR.showBackBtn();
		
  		 

		var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){	    
	   	 
	    //NAVIGATOR.changePage('homeMiMovistar');
	      homeView();
	    };

		NAVIGATOR.hideMoreInfoBtn();
	
		NAVIGATOR.changePage('more_info');
		if(!moreInfoInitialized){
			moreInfoInitialized = true;
			document.querySelector('#more_info_faqsbtn').onclick = ns.faqsView;
			document.querySelector('#more_info_cambiarLinea').onclick = ns.ChangeLine;

		    //document.querySelector('#more_info_map').onclick = ns.mapView;
		   
  			var miperfilbtn = document.querySelector('#miperfilbtn');			  
			miperfilbtn.onclick =  MiPerfilInfo;//ns.gotoHomeViewOld;		
			
			document.querySelector('#more_info_facebook').onclick = function(){
				var openURL = new MozActivity({
					name: "view",
					data: {
						type: "url",
						url: 'http://www.facebook.com/MovistarUruguay?v=wall'
					}
				});
			};
			document.querySelector('#more_info_twitter').onclick = function(){
				var openURL = new MozActivity({
					name: "view",
					data: {
						type: "url",
						url: 'https://twitter.com/Movistar_UY'
					}
				});
			};
		}
	};  

	

	var HomeViewInitialized = false;
	var homeView = function(){
		NAVIGATOR.hideBackBtn();
		NAVIGATOR.showMoreInfoBtn();
		NAVIGATOR.changePage('homeMiMovistar');
 
		var recargaBtn = document.querySelector('#reload_orderm');			  
		recargaBtn.onclick =  gotoHomeReload;//ns.gotoHomeViewOld;		

        var recargaOtherBtn = document.querySelector('#reload_other_phone');			  
		recargaOtherBtn.onclick =  anotherPhoneView;//ns.gotoHomeViewOld;		


        var recargaSOSBtn = document.querySelector('#reload_SOS');			  
		recargaSOSBtn.onclick =  gotoHomeSOS;//ns.gotoHomeViewOld;		

        var recargaBalanceBtn = document.querySelector('#reload_balance');			  
		recargaBalanceBtn.onclick =  checkAccountView;//ns.gotoHomeViewOld;		


        var recargaBalanceBtn = document.querySelector('#AtentionClient');			  
		recargaBalanceBtn.onclick =  chatHomeView;//ns.gotoHomeViewOld;		

 
        var autoGestionBtn = document.querySelector('#auto_gestion');			  
		autoGestionBtn.onclick =  autoGestionView;//ns.gotoHomeViewOld;		
	};

	var homeViewCRReloadInitialized = false;
	var homeViewCRReload = function(){
		NAVIGATOR.showBackBtn();
	 
		//NAVIGATOR.showMoreInfoBtn();
		NAVIGATOR.changePage('homeViewCRReload');
        var reload_easyBtn = document.querySelector('#reloadCR_easy');			  
		reload_easyBtn.onclick = gotoEasyReload;	 
	};

	
	var MiPerfilInfoInitialized = false;
	var MiPerfilInfo = function(){
	

	if(MovistarAPI.getSessionPortalUserdata()=== null){
	
	NAVIGATOR.changePage('OptionPerfilMoreInfo');	 

    var MiperfilLoginBtn = document.querySelector('#MiperfilLogin');			  
	MiperfilLoginBtn.onclick =  MiPerfilautoGestionView;//ns.gotoHomeViewOld;		
 		 		
   	var forgotPasswBtn = document.querySelector('#MiPerfilForgotPassw');			  
	forgotPasswBtn.onclick = MiPerfilForgotPasswView;	

    var regFreeBtnbtn = document.querySelector('#MiPerfilRegFree');			  
	regFreeBtnbtn.onclick = MiPerfilregFreeView;

 
	}else
	{

		MiPerfilLoginSucces();
 
	}
 
	
	var backBtn = document.querySelector('#back_btn');
	backBtn.onclick = function(){	    
	ns.moreInfoView();
	 
	};
 
};


    var homeViewCCReloadInitialized = false;
	var homeViewCCReload = function(){
		NAVIGATOR.showBackBtn();
		//NAVIGATOR.showMoreInfoBtn();		 
		
		var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){	    
	    //NAVIGATOR.changePage('homeMiMovistar');
	    homeView();
	    };

		NAVIGATOR.changePage('homeViewCCReload');
        var reload_easyBtn = document.querySelector('#reloadCC_easy');			  
		reload_easyBtn.onclick = gotoEasyReload;			
	};

    var homeViewPPReloadInitialized = false;
    var homeViewPPReload = function(){
	 
		//NAVIGATOR.backPageView = ns.homeMiMovistaruserHomeView;
		NAVIGATOR.showBackBtn();			
        var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	    //NAVIGATOR.changePage('homeMiMovistar');
	    homeView();
	    };
		NAVIGATOR.changePage('homeViewPPReload');
        var reload_easyBtn = document.querySelector('#reloadPP_easy');			  
		reload_easyBtn.onclick = gotoEasyReload;

		var reload_SosBtn = document.querySelector('#Check_balance');			  
		reload_SosBtn.onclick = checkAccountView;			
	};

        var autoGestionInitialized = false;
     	var autoGestionView = function(){
 
 		
 		var Portaluserdata = MovistarAPI.getSessionPortalUserdata();
 	 	 



 		if (Portaluserdata === null){ 		 
			
			if (localStorage['email'] != undefined   &&  localStorage['phone'] == MovistarAPI.getSessionUserdata().PhoneNumber )
 			{
			 document.querySelector('#passw').value = localStorage['passw']; 
		     document.querySelector('#email').value = localStorage['email']; 	 

			 intentautenticarUsuarioPortal();

 			}else
 			{
 				NAVIGATOR.changePage('autoGestion');
 			}
		 
 		}else
 		{
 		  
 				OprtionPerfilView();
 
 		}
		NAVIGATOR.showMoreInfoBtn();		 
		NAVIGATOR.showBackBtn();  	

	    var regFreeBtnbtn = document.querySelector('#regFreeBtn');			  
		regFreeBtnbtn.onclick = regFreeView;

	    var ingresarbtn = document.querySelector('#ingresarbtn');			  
		ingresarbtn.onclick = intentautenticarUsuarioPortal;
		 		
    	var forgotPasswBtn = document.querySelector('#forgotPassBtn');			  
		forgotPasswBtn.onclick = ForgotPasswView;		

		var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	     homeView();
	    } ;
	};

	 var MiPerfilautoGestionInitialized = false;
     var MiPerfilautoGestionView = function(){
  	
 

 		var Portaluserdata = MovistarAPI.getSessionPortalUserdata();
	  
 		if (Portaluserdata === null){
			if (localStorage['email'] != undefined   &&  localStorage['phone'] == MovistarAPI.getSessionUserdata().PhoneNumber )
 			{
			 document.querySelector('#passw').value = localStorage['passw']; 
		     document.querySelector('#email').value = localStorage['email']; 	 
           
                MovistarAPI.setEmail(localStorage['email']);
				intentautenticarUsuarioPortalMiPerfil();

 			}else
 			{
 				NAVIGATOR.changePage('autoGestion');
 			}
		 
 		}else
 		{
			MiPerfilLoginSucces();
 		 
 		}
		NAVIGATOR.hideMoreInfoBtn();		 
		NAVIGATOR.showBackBtn();  	

	    var regFreeBtnbtn = document.querySelector('#regFreeBtn');			  
		regFreeBtnbtn.onclick = regFreeView;

	    var ingresarbtn = document.querySelector('#ingresarbtn');			  
		ingresarbtn.onclick = intentautenticarUsuarioPortalMiPerfil;
		 		
    	var forgotPasswBtn = document.querySelector('#forgotPassBtn');			  
		forgotPasswBtn.onclick = ForgotPasswView;		

		var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	     MiPerfilInfo();
	    } ;
	};




//---------------------#CHAT

var chatHomeInitialized = false;
	var chatHomeView = function(){
		NAVIGATOR.changePage('chat_home');
 
		NAVIGATOR.showMoreInfoBtn();		 
		NAVIGATOR.showBackBtn();
  		 
		var backBtn = document.querySelector('#back_btn');
	    backBtn.onclick = function(){
	     homeView();
	    };
        
		var nameInput = document.querySelector('#chat_home_name');		
		var lastnameInput = document.querySelector('#chat_home_lastname');
			 
		nameInput.value = '';		    
		lastnameInput.value = '';
		//if(!chatHomeInitialized){		 
			var initBtn = document.querySelector('#chat_home_init');		 
			initBtn.onclick = ns.launchChat;
			chatHomeInitialized = true;
		//}
	}; 

	ns.launchChat = function(){
	
	    var nameInput = document.querySelector('#chat_home_name');
		var lastnameInput = document.querySelector('#chat_home_lastname');
		var name = nameInput.value;
		var lastname = lastnameInput.value;
 
		if(name=='' || lastname==''){
			alert(LANG['chatInitInputError']);
		}else{
			var url = getChatMobileURL(name, lastname);
			ns.chatView(url);
		}
	};

	var getChatMobileURL = function(name, lastname){
		 
		var url = CONFIG.CHAT.CHAT_MOBILE_URL;		
		url = url.replace('<nombreIngresado>', name);	 
		url = url.replace('<apellidoIngresado>', lastname);		 
		var userdata = MovistarAPI.getSessionUserdata();		
		url = url.replace('<numeroDeLinea>', userdata.PhoneNumber);
		 
		return url;
	};

       ns.chatView = function(url){
		var url = url || false;
	

		if(!url){
			chatHomeView();
		}else{
			NAVIGATOR.changePage('chat_view');
			NAVIGATOR.pageClosedActions = chatClosedActions;		 
			NAVIGATOR.showBackBtn();
		
		   var backBtn = document.querySelector('#back_btn');
	       backBtn.onclick = function(){
	  	   
		  	var ok = confirm("¿Desea finalizar el chat?");
						if (ok == null || ok == "")
							return;
	  	   chatHomeView();
	     };
			var container = document.querySelector('#chat_view_container');
			container.innerHTML = '';
			var iframe = document.createElement('iframe');
			iframe.src = url;
			iframe.id = 'chat_view_iframe';
			iframe.setAttribute('sandbox', 'allow-same-origin allow-top-navigation allow-forms allow-scripts');
			iframe.style.overflowX = 'hidden';
			iframe.frameBorder = 0;
			container.appendChild(iframe);

			var sendBtn = document.querySelector('#chat_view_send');
			sendBtn.onclick = ns.sendChatMessage;
		}
	}

	var chatClosedActions = function(){
		ns.chatPost('#closesession#');
		var container = document.querySelector('#chat_view_container');
		container.innerHTML = '';
	};


 	var IntentCambiarContraseña = function(){		     
     	 
      	var userdata = MovistarAPI.getSessionUserdata();	   
	  	var monthDiff = MovistarAPI.getSessionActualMonth();	   
		var email = MovistarAPI.getEmail();
	
		var passw = document.querySelector('#changepass_passw').value;	
		var newchangePass = document.querySelector('#changepass_new_passw').value; 		 
		var confirnewchangePass = document.querySelector('#changepass_confirm_new_passw').value; 		 
		 
		

		if (newchangePass == confirnewchangePass){
			MovistarAPI.SendCambiarContraseña({				 		  
			    nuevoPassword: newchangePass,
				password: passw,
				email: email,
				idAplicacion:   CONFIG.WS_DATA.idAplicacion,

		}, CambiarContraseñaHandler);

		}else{
			alert("Las contraseñas no coinciden")
		}
	};
  
        var CambiarContraseñaHandler = function(data){
		 var resultData = data.response.cambiarClavePortalResult;
         	
	 		if(resultData.status ){
	 			
	 			 localStorage['passw']  = document.querySelector('#changepass_confirm_new_passw').value; 
				 document.querySelector('#changepass_passw').value = "";	
		         document.querySelector('#changepass_new_passw').value =""; 		 
		         document.querySelector('#changepass_confirm_new_passw').value =""; 		 
		
				 alert("Su contraseña fue modificada")


			
			}else
			{
				alert(resultData.descripcion);
			}	 
		};



	var getMonth = function( ){

	     var dt = new Date();
		 
		var month = parseInt(dt.getMonth() + 1);
	
		switch (month)
		{
 		case   1: 
 		      				var PrimerMesBtn = document.querySelector('#PrimerMes'); 		      			  	
	     	 				PrimerMesBtn.textContent = "Enero";
	     	 				PrimerMesBtn.value = 0; 		    
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Diciembre";
	     	 				SegundoMesBtn.value = -1; 		      	
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
          	 				TercerMesBtn.textContent = "Noviembre";
          	 				TercerMesBtn.value = -2; 		      	
                            break; 
        case   2:  
        					var PrimerMesBtn = document.querySelector('#PrimerMes');
	     	 				PrimerMesBtn.textContent = "Febrero";
	     	 				PrimerMesBtn.value = 0; 		

	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Enero";
	     	 				SegundoMesBtn.value = -1; 	
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Diciembre";
	     	 				TercerMesBtn.value = -2; 
       						break;             
        case   3:  	
        					var PrimerMesBtn = document.querySelector('#PrimerMes');
   	 	  					PrimerMesBtn.textContent = "Marzo";
	     	 				PrimerMesBtn.value = 0; 		

	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Febrero";
	     	 				SegundoMesBtn.value = -1; 	

	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Enero";
	     	 				TercerMesBtn.value = -2; 
       						break;
        case   4: 
        					var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Abril";
        	 				PrimerMesBtn.value = 0; 	
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Marzo";
	     	 				SegundoMesBtn.value = -1; 
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Febrero";
       					    TercerMesBtn.value = -2; 
       						break;    
        case   5: 
        					var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Mayo";
        	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Abril";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Marzo";
	     	 				TercerMesBtn.value = -2;
       						break;       
        case   6: 
       						var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Junio";
        	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Mayo";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Abril";
	     	 				TercerMesBtn.value = -2;
       						break;
        case   7: 
        	 				var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Julio";
        	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Junio";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Mayo";
	     	 				TercerMesBtn.value = -2;
       						break;       		      
        case   8: 
        	 				var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Agosto";
        	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Julio";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Junio";
	     	 				TercerMesBtn.value = -2;
       						break;       		       										
        case   9: 
        	 				var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Septiembre";
        	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Agosto";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Julio";
	     	 				TercerMesBtn.value = -2;
       						break; 
		case   10: 
   	    	 				var PrimerMesBtn = document.querySelector('#PrimerMes');
   	    	 				PrimerMesBtn.textContent = "Octubre";
   	    	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Septiembre";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Agosto";
	     	 				TercerMesBtn.value = -2;
       						break; 
		case   11: 
        	 				var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Noviembre";
        	 				PrimerMesBtn.value = 0;
	     	 				
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Octubre";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Septiembre";
	     	 				TercerMesBtn.value = -2;
       						break; 
		case   12: 
        	 				var PrimerMesBtn = document.querySelector('#PrimerMes');
        	 				PrimerMesBtn.textContent = "Diciembre";
        	 				PrimerMesBtn.value = 0;
	     	 			
	     	 				var SegundoMesBtn = document.querySelector('#SegundoMes');
	     	 				SegundoMesBtn.textContent = "Noviembre";
	     	 				SegundoMesBtn.value = -1;
	     	 				
	     	 				var TercerMesBtn = document.querySelector('#TercerMes');
	     	 				TercerMesBtn.textContent = "Octubre";
	     	 				TercerMesBtn.value = -2;
       						break; 
             
  		defaultkey:  alert("Error inesperado");
  	    
  	}
	 		 
	
	};


	var getMonthString = function(){

	     var dt = new Date();
		 
		var month = parseInt(dt.getMonth() + 1);
	
		switch (month)
		{
 		case   1:  		      				 	      			  	
	     	 				return  "Enero";	     	 				      	
                       		 break; 
        case   2:  
        					return  "Febrero"; 
       						break;             
        case   3:   		 
   	 	  					return   "Marzo"; 
       						break;
        case   4: 
        					return   "Abril";        	 			
       						break;
      
        case   5: 
        				 
        	 				return  "Mayo";        	 			
       						break;
       
        case   6:       						 
        	 	 			return  "Junio";
  				 			break;
        case   7: 
        	 				return  "Julio";
       						break;       		
      
        case   8:         	 				
        	 				return  "Agosto";        	 				 
       						break;       		       										
        case   9:         	 				
        	 				return "Septiembre";        	 				 
       						break; 
		case   10: 
   	    	 				 
   	    	 				return "Octubre";   	    	 				 
       						break; 
		case   11: 
        	 				 
        	 				return "Noviembre";        	 			 
       						break; 
		case   12: 
        	 				 
        	 				return "Diciembre";        	 				 
       						break; 
             
  		defaultkey:  alert("Error inesperado");
  	    
  	    }	 		 
		       
	};

  
    var convertirSegundos = function(segundos) {
            var horas = Math.floor(segundos / 3600);
            var minutos= Math.floor((segundos - (horas * 3600)) / 60);
            var segundos = segundos - (horas * 3600) - (minutos * 60);
            var tiempo = "";
 

               if (horas != 0) {
                tiempo = horas + " hs ";
            } 
         

            if (minutos != 0 || tiempo !== "") {
                minutos = (minutos < 10 && tiempo !== "") ? "0" + minutos : String(minutos);
                tiempo += minutos + " min ";
            }
            else{ tiempo += minutos + " min "}
            if (tiempo === "") {
                tiempo = segundos + " sec";
            }
            else {
                tiempo += (segundos < 10) ? "" + segundos + " sec" : String(segundos) + " sec";
            }
            return tiempo;
     }

      var convertirSegundosSinString = function(segundos) {
           
            var horas = Math.floor(segundos / 3600);
            var minutos= Math.floor((segundos - (horas * 3600)) / 60);
            var segundos = segundos - (horas * 3600) - (minutos * 60);
            var tiempo = "";

            if (horas != 0) {
                tiempo = horas + ":";
            }else{tiempo = horas + "0:"}

            if (minutos != 0 || tiempo !== "") {
                minutos = (minutos < 10 && tiempo !== "") ? "0" + minutos : String(minutos);
                tiempo += minutos + ":";
            }
            else{ tiempo += minutos + "00:"}
            if (tiempo === "") {
                tiempo = segundos + ":";
            }
            else {
                tiempo += (segundos < 10) ? "0" + segundos : String(segundos) + "";
            }
            return tiempo;
     }

	ns.sendChatMessage = function(){
		
		var chatTextInput = document.querySelector('#chat_view_text');		
	
		ns.chatPost('#message#', chatTextInput.value);
		chatTextInput.value = '';
	};

	ns.chatPost = function(action, value){
		var value = value || '';
		var postMsg = action+value;
		var iframe = document.querySelector('#chat_view_iframe');
		iframe.contentWindow.postMessage(postMsg, 'http://chat.movistar.com.uy/');
	};


	var ChangeMonth = function(){
	    
		 
		
	};
 
 
}(window.MainApp = window.MainApp || {}, MovistarAPI, CONFIG, LANG, NAVIGATOR, LOADING, CONNECTION));

// Init
var init = function(MainApp){
	MainApp.init();
};
init(MainApp);
