
/**
 *
 * Model section
 *
 **/

var lstFeedInicio = [];

function FeedInicio() {
	this.url = '';
	this.tipo = '';
	this.idFeed = '';
	this.titulo = '';
	this.subtitulo = '';
	this.descripcion = '';
	this.fecha = '';
	this.imagen = '';
	this.contadorOriginal = '';
	this.youtube = '';
}

function IcomParserInicio(json) {
	this.JSON_STRING = json;
}

IcomParserInicio.prototype._ToFeedInicioArray = function () {
	var root = null;
	try {
		root = JSON.parse(this.JSON_STRING);
		var resources = root.array.resources;
		resources.forEach(function(element, index, array) {
			var item = new FeedInicio();
			item.url = element['@url'];
			item.id = item.url.split('entries/')[1];
			item.tipo = getTipo(element.tipo);
			item.titulo = element.titulo;
			item.subtitulo = element.subtitulo;
			item.descripcion = element.descripcion;
			item.contadorOriginal = element.contador;
			item.youtube = element.youtube;
			item.fecha = new Date(element['@created_at']);
			try { item.imagen = element.imagen['@url']; } catch(e) { console.error("looks like there is no such image: ", e); }
			if(item.tipo == 'Noticias' || item.tipo == 'Promoción' || item.tipo == 'Clip de Vídeo' || item.tipo == 'Galería' )
			lstFeedInicio.push(item);
			console.log(lstFeedInicio.length);
		});
	} catch (e) {
		console.error("Parsing error:", e); 
	}
}

function getTipo(tipo) {
	var NOTICIA = 'noticia';
	var PROXIMO_PARTIDO = 'proximopartido';
	var PROMOCION = 'promocion';
	var VIDEO = 'video';
	var GALERIA = 'galeria';
	if(tipo == NOTICIA)
		return 'Noticias';
	if(tipo == PROXIMO_PARTIDO)
		return 'Próximo partido';
	if(tipo == PROMOCION)
		return 'Promoción';
	if(tipo == VIDEO)
		return 'Clip de Vídeo';
	if(tipo == GALERIA )
		return 'Galería';
	return 'Mi selección';
}

function getElapsedTimeFromNow(date) {
	console.log( date.toUTCString() + ' -------- ' + new Date().toUTCString());
	var rightNow = new Date(new Date().toUTCString());
	var elapsed = new Date(rightNow - date);
	var elapsedDays = elapsed.getUTCDate();
	if( elapsedDays == 0 )
		return 'Hace unos momentos';
	if( elapsedDays == 1 )
		return 'Ayer';
	return 'Hace ' + elapsedDays + ' dias';
}

function getElementWithArguments(tag, keys, values, content) {
	var newElement = document.createElement(tag);
	keys.forEach(function(element, index, array) {
		newElement.setAttribute(element, values[index]);
	});
	if( content == null )
		return newElement;
	newElement.innerHTML = content;
	return newElement;
}

function getMonthByIndex(index) {
	var months = ['Enero', 'Febrero', 'Marzo',  'Abril', 'Mayo',  'Junio', 'Julio',  'Agosto', 'Septiembre',  'Octubre', 'Noviembre', 'Diciembre'];
	return months[index];
}

/*
 *
 * Persistant API
 *
 */

function FeedPersistantSaveVote(key, value) {
	window.localStorage.setItem(key, value);
}

function FeedPersistantReadVote(key) {
	return window.localStorage.getItem(key);
}

function FeedPersistantRemoveVote(key) {
	window.localStorage.removeItem(key);
}

/*
 *
 * Feed logic
 *
 */
function addLike(source, index) {
	console.log("adding like... ");
	if(!navigator.onLine) {
		_showError('Verifica tu conexión a Internet');
		return;
	}
	var element = lstFeedInicio[index];
	var vote = FeedPersistantReadVote(element.id);
	if(vote != null) {
		alert('¡Ya has votado por esta sección!');
		return;	
	}

	var lastScore = new XMLHttpRequest({mozSystem: true});
	lastScore.onload = function() {
		var updatedObject = JSON.parse(this.responseText);
		var currentContador = updatedObject.entry.contador;
		var likes = currentContador.split('|')[0];
		var dislikes = currentContador.split('|')[1];
		console.log(likes + '-->' + (parseInt(likes) + 1) + ' - ' + dislikes );

		var likesUpdater = new XMLHttpRequest({mozSystem: true});
		likesUpdater.onload = function() {
			var liked = JSON.parse(this.responseText);
			var newContador = liked.entry.contador;
			var newLikes = newContador.split('|')[0];
			var newDislikes = newContador.split('|')[1];
			console.log('updated = ' + newLikes+ ' - ' + newDislikes );
		};
		likesUpdater.open("PUT", element.url + '.json?auth_token=iazyariHhoxQnisc4UyX', true);
		likesUpdater.setRequestHeader('Content-type', 'application/json');
		likesUpdater.timeout = 20000;
		likesUpdater.ontimeout = function () {
			_showError("Algo anda mal :'(\nIntentalo más tarde.");
			FeedPersistantRemoveVote(element.id);
			source.setAttribute('class', 'btn-like');
			source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
		}
		likesUpdater.onerror = function (e) {
			_showError('Verifica tu conexión a Internet');
			FeedPersistantRemoveVote(element.id);
			source.setAttribute('class', 'btn-like');
			source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
		}
		likesUpdater.send('{"entry":{"contador":"' + (parseInt(likes) + 1) + '|' + (dislikes) + '"}}');

	};
	lastScore.open("GET", element.url + '.json?auth_token=iazyariHhoxQnisc4UyX', true);
	lastScore.timeout = 20000;
	lastScore.ontimeout = function () {
		_showError("Algo anda mal :'(\nIntentalo más tarde.");
		FeedPersistantRemoveVote(element.id);
		source.setAttribute('class', 'btn-like');
		source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
	}
	lastScore.onerror = function (e) {
		_showError('Verifica tu conexión a Internet');
		FeedPersistantRemoveVote(element.id);
		source.setAttribute('class', 'btn-like');
		source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
	}
	lastScore.send();
	source.setAttribute('class', 'btn-like-pressed');
	source.childNodes[0].innerHTML = (parseInt(element.contadorOriginal.split('|')[0]) + 1);
	FeedPersistantSaveVote(element.id, 'true');
}

function addDislike(source, index) {
	console.log("adding dislike... " + index);
	if(!navigator.onLine) {
		_showError('Verifica tu conexión a Internet');
		return;
	}
	var element = lstFeedInicio[index];
	var vote = FeedPersistantReadVote(element.id);
	if(vote != null) {
		alert('¡Ya has votado por esta sección!');
		return;	
	}

	var lastScore = new XMLHttpRequest({mozSystem: true});
	lastScore.onload = function() {
		var updatedObject = JSON.parse(this.responseText);
		var currentContador = updatedObject.entry.contador;
		var likes = currentContador.split('|')[0];
		var dislikes = currentContador.split('|')[1];
		console.log(likes+ ' - ' + dislikes + '-->' + (parseInt(dislikes) + 1));

		var likesUpdater = new XMLHttpRequest({mozSystem: true});
		likesUpdater.onload = function() {
			var liked = JSON.parse(this.responseText);
			var newContador = liked.entry.contador;
			var newLikes = newContador.split('|')[0];
			var newDislikes = newContador.split('|')[1];
			console.log('updated = ' + newLikes+ ' - ' + newDislikes );
		};
		likesUpdater.open("PUT", element.url + '.json?auth_token=iazyariHhoxQnisc4UyX', true);
		likesUpdater.setRequestHeader('Content-type', 'application/json');
		likesUpdater.timeout = 20000;
		likesUpdater.ontimeout = function () {
			_showError("Algo anda mal :'(\nIntentalo más tarde.");
			FeedPersistantRemoveVote(element.id);
			source.setAttribute('class', 'btn-like');
			source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
		}
		likesUpdater.onerror = function (e) {
			_showError('Verifica tu conexión a Internet');
			FeedPersistantRemoveVote(element.id);
			source.setAttribute('class', 'btn-like');
			source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
		}
		likesUpdater.send('{"entry":{"contador":"' + likes + '|' + (parseInt(dislikes) + 1) + '"}}');
	};
	lastScore.open("GET", element.url + '.json?auth_token=iazyariHhoxQnisc4UyX', true);
	lastScore.timeout = 20000;
	lastScore.ontimeout = function () {
		_showError("Algo anda mal :'(\nIntentalo más tarde.");
		FeedPersistantRemoveVote(element.id);
		source.setAttribute('class', 'btn-like');
		source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
	}
	lastScore.onerror = function (e) {
		console.error(e.target.status);
		_showError('Verifica tu conexión a Internet');
		FeedPersistantRemoveVote(element.id);
		source.setAttribute('class', 'btn-like');
		source.childNodes[0].innerHTML = element.contadorOriginal.split('|')[0];
	}
	lastScore.send();
	source.setAttribute('class', 'btn-nolike-pressed');
	source.childNodes[0].innerHTML = (parseInt(element.contadorOriginal.split('|')[1]) + 1);
	FeedPersistantSaveVote(element.id, 'false');
}

function getNoticiaElement(element, index) {
	var vote = FeedPersistantReadVote(element.id);
	var buttonLikeClass = '';
	var buttonDislikeClass = '';
	if(vote != null) {
		if(vote == 'true') {
			buttonLikeClass = 'btn-like-pressed';
			buttonDislikeClass = 'btn-nolike';
		}else {
			buttonLikeClass = 'btn-like';
			buttonDislikeClass = 'btn-nolike-pressed';
		}
	} else {
		buttonLikeClass = 'btn-like';
		buttonDislikeClass = 'btn-nolike';
	}
	var root = getElementWithArguments(
			'div', ['class'], ['contenido'], 
			'<table class="noticia">' +
			'	<tr>' +
			'		<td class="tipo-noticia-img"><img src="img/noticia.jpg" /></td>' +
			'               <td class="titulo-noticia">'+
			'			<span class="titulo-rojo">' + element.tipo + '</span><br>' +
			'                       <span>' + element.subtitulo + '</span>' +
			'               </td>' +
			'               <td class="hora-noticia">' + element.fecha.getDate() + ' de ' + getMonthByIndex(element.fecha.getMonth()) + '</td>' +
			'       </tr>' +
			'       <tr>' +
			'       	<td class="noticia-cabecera" colspan="3">' + element.titulo + '</td>' +
			'       </tr>' +
			'       <tr>' +
			'               <td class="galeria" colspan="3">' +
			'       		<a href="detalles.html?id=' + element.id + '"><img src="' + element.imagen + '" /></a>' +
			'               </td>' +
			'       </tr>' +
			'</table>' +
			'<button onclick="addLike(this, ' + index + ')" class="' + buttonLikeClass + '"><span class="btn-social">' + element.contadorOriginal.split('|')[0] + '</span></button><button onclick="addDislike(this, ' + index + ')" class="' + buttonDislikeClass + '"><span class="btn-social">' + element.contadorOriginal.split('|')[1] + '</span></button><button class="btn-compartir"><span class="btn-social"></span></button>');
	return root;
}

function getGaleriaElement(element, index) {
	var vote = FeedPersistantReadVote(element.id);
	var buttonLikeClass = '';
	var buttonDislikeClass = '';
	if(vote != null) {
		if(vote == 'true') {
			buttonLikeClass = 'btn-like-pressed';
			buttonDislikeClass = 'btn-nolike';
		}else {
			buttonLikeClass = 'btn-like';
			buttonDislikeClass = 'btn-nolike-pressed';
		}
	} else {
		buttonLikeClass = 'btn-like';
		buttonDislikeClass = 'btn-nolike';
	}
	var galeria = JSON.parse(element.descripcion);
	var root = getElementWithArguments(
			'div', ['class'], ['contenido'], 
			'<table class="noticia">' +
			'	<tr>' +
			'		<td class="tipo-noticia-img"><img src="img/gal.jpg" /></td>' +
			'               <td class="titulo-noticia">'+
			'			<span class="titulo-rojo">' + element.tipo + '</span><br>' +
			'                       <span>' + element.subtitulo + '</span>' +
			'               </td>' +
			'               <td class="hora-noticia">' + element.fecha.getDate() + ' de ' + getMonthByIndex(element.fecha.getMonth()) + '</td>' +
			'       </tr>' +
			'       <tr>' +
                        '		<td class="galeria-cabecera" colspan="3">' + element.titulo + '</td>' +
			'       </tr>' +
			'       <tr>' +
                        '		<td class="galeria" colspan="3">' +
                        '    			<div class="imagen-1"><a href="galeria.html?id=' + galeria.idGaleria + '"><img src="' + galeria.imagenes[0].img + '" /></a></div>' +
                        '    			<div class="imagen-2"><a href="galeria.html?id=' + galeria.idGaleria + '"><img src="' + galeria.imagenes[1].img + '" /></a></div>' +
                        '		</td>' +
			'       </tr>' +
			'</table>' +
			'<button onclick="addLike(this, ' + index + ')" class="' + buttonLikeClass + '"><span class="btn-social">' + element.contadorOriginal.split('|')[0] + '</span></button><button onclick="addDislike(this, ' + index + ')" class="' + buttonDislikeClass + '"><span class="btn-social">' + element.contadorOriginal.split('|')[1] + '</span></button><button class="btn-compartir"><span class="btn-social"></span></button>');
	return root;
}

function getVideoElement(element, index) {
	var vote = FeedPersistantReadVote(element.id);
	var buttonLikeClass = '';
	var buttonDislikeClass = '';
	if(vote != null) {
		if(vote == 'true') {
			buttonLikeClass = 'btn-like-pressed';
			buttonDislikeClass = 'btn-nolike';
		}else {
			buttonLikeClass = 'btn-like';
			buttonDislikeClass = 'btn-nolike-pressed';
		}
	} else {
		buttonLikeClass = 'btn-like';
		buttonDislikeClass = 'btn-nolike';
	}
	var root = getElementWithArguments(
			'div', ['class'], ['contenido'], 
			'<table class="noticia">' +
			'	<tr>' +
			'		<td class="tipo-noticia-img"><img src="img/gal.jpg" /></td>' +
			'               <td class="titulo-noticia">'+
			'			<span class="titulo-rojo">' + element.tipo + '</span><br>' +
			'                       <span>' + element.subtitulo + '</span>' +
			'               </td>' +
			'               <td class="hora-noticia">' + element.fecha.getDate() + ' de ' + getMonthByIndex(element.fecha.getMonth()) + '</td>' +
			'       </tr>' +
			'       <tr>' +
			'               <td class="galeria" colspan="3">' +
			'			<iframe width="290" height="187" src="http://www.youtube.com/embed/' + element.youtube + '" frameborder="0" allowfullscreen></iframe>' +
			'               </td>' +
			'       </tr>' +
			'       <tr>' +
			'       	<td class="noticia-cabecera" colspan="3">' + element.titulo + '</td>' +
			'       </tr>' +
			'</table>' +
			'<button onclick="addLike(this, ' + index + ')" class="' + buttonLikeClass + '"><span class="btn-social">' + element.contadorOriginal.split('|')[0] + '</span></button><button onclick="addDislike(this, ' + index + ')" class="' + buttonDislikeClass + '"><span class="btn-social">' + element.contadorOriginal.split('|')[1] + '</span></button><button class="btn-compartir"><span class="btn-social"></span></button>');
	return root;
}

function ShowResults() {
	lstFeedInicio.forEach(function (element, index, array) {
		var NOTICIA = 'Noticias';
		var PROXIMO_PARTIDO = 'Próximo partido';
		var PROMOCION = 'Promoción';
		var VIDEO = 'Clip de Vídeo';
		var GALERIA = 'Galería';
		if(element.tipo == NOTICIA) {
			document.getElementById("div-main").appendChild(getNoticiaElement(element, index));
			return;
		}
		if(element.tipo == VIDEO) {
			document.getElementById("div-main").appendChild(getVideoElement(element, index));
			return;
		}
		if(element.tipo == GALERIA) {
			document.getElementById("div-main").appendChild(getGaleriaElement(element, index));
			return;
		}
		document.getElementById("div-main").appendChild(getNoticiaElement(element, index));
	});
}

function _hideLoader() {
  document.getElementById('form-dialog').style.display = 'none';
}

function _showError(error) {
  //document.getElementById('div-main').innerHTML = error;
  alert(error);
}

/**
Download news feed from the server
**/

function reqListener () {
	var parser = new IcomParserInicio(this.responseText);
	parser._ToFeedInicioArray();
	ShowResults();
	_hideLoader();
}

function _downloadFeedInicio() {
	var oReq = new XMLHttpRequest({mozSystem: true});
	oReq.onload = reqListener;
	//oReq.open("GET", "https://api.storageroomapp.com/accounts/5127b2ad0f660245fa00106c/collections/51ae23440f66025a40000a89/entries.json?auth_token=iazyariHhoxQnisc4UyX", true);
	oReq.open("GET", "https://api.storageroomapp.com/accounts/5127b2ad0f660245fa00106c/collections/51ae23440f66025a40000a89/entries.json?auth_token=iazyariHhoxQnisc4UyX&order=desc&sort=fecha", true);
	oReq.timeout = 20000;
	oReq.ontimeout = function () {
		_showError("Algo anda mal :'(\nIntentalo más tarde.");
	}
	oReq.onerror = function (e) {
		_showError('Verifica tu conexión a Internet');
	}
	oReq.send();
}

function _openBannerInBrowser(URL) {
	var activity = new MozActivity({
		name: "view",
		data: {
			type: "url",
			url: URL
		}
	});
	activity.onsuccess = function() {
		console.log("url opened succesfully :P");
	};
	activity.onerror = function() {
		console.log(this.error);
	};
}
