$$(document).ready(init);

function init(){
	formSubmit();

	$$('#btn-response-back').on('click', function(){
		backToMainView();
	});
}

function openResponseView(){
	$$('#main-view').removeClass('current');
	$$('#main-view').addClass('left');

	$$('#response-view').removeClass('right');
	$$('#response-view').addClass('current');
}

function backToMainView(){
	$$('#main-view').removeClass('left');
	$$('#main-view').addClass('current');

	$$('#response-view').removeClass('current');
	$$('#response-view').addClass('right');
}

function formSubmit(){
	var card, corredor;

	$$('#consulta-sur').on('click', function(){
		corredor = 'sur';
		card = $$('#input-card').val();
		LoadingHelper.show();
		getBalance(card, corredor);

	});

	$$('#consulta-norte').on('click', function(){
		corredor = 'norte';
		card = $$('#input-card').val();
		LoadingHelper.show();
		getBalance(card, corredor);
	});
}

function getBalance(card, corredor){
	var url = "http://api.ragostini.com/saldoexpress/saldo/"+card+"/"+corredor;
	var xhr = new XMLHttpRequest({mozSystem: true});
	xhr.open("GET", url, false);
	xhr.onreadystatechange = function () {
		if (xhr.status === 200 && xhr.readyState === 4) {
			var result = JSON.parse(xhr.responseText);

			if(result.error){
				LoadingHelper.hide();
				alert(result.error);

			}
			else{
				$$('#output-card').html(result.tarjeta);
				$$('#output-corredor').html('Corredor '+corredor);
				$$('#output-balance').html('B/. '+result.saldo);
				$$('#output-date').html(result.ultimaTransaccion.fecha[1] + '<br />' + result.ultimaTransaccion.hora);
				
				LoadingHelper.hide();
				openResponseView();

			}
		}
	}

	xhr.onerror = function () {
		LoadingHelper.hide();
	    console.debug('Se ha producido un error inesperado.');
	};

	xhr.send();
}

var LoadingHelper = {
	elementId: '#loading',
	show: function(){
		$$(this.elementId).css('display', 'block');
		$$('#submit-buttons a').attr('aria-disabled', true);
	},
	hide: function(){
		$$(this.elementId).css('display', 'none');
		$$('#submit-buttons a').attr('aria-disabled', false);
	}
}
