
/**
 *
 * Model section
 *
 **/

var lstGaleria = [];

function Galeria() {
	this.url          = '';
	this.id_contenido = '';
	this.fecha        = new Date();
	this.nombre       = '';
	this.descripcion  = '';
	this.imagen       = '';
	this.seleccion    = '';
}

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

IcomParserInicio.prototype._ToGaleriaArray = 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 Galeria();
			item.url = element['@url'];
			item.id  = item.url.split('entries/')[1];
			item.id_contenido = element.id_contenido;
			item.fecha        = new Date(element['@created_at']);
			item.nombre       = element.nombre;
			item.descripcion  = element.descripcion;
			item.seleccion    = element.seleccion;
			try { item.imagen = element.imagen_portada['@url']; } catch(e) { console.error("looks like there is no such image: ", e); }
			lstGaleria.push(item);
		});
		lstGaleria.reverse();
	} catch (e) {
		console.error("Parsing error:", e); 
	}
	root = null;
}

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];
}

/*
 *
 * Gallery logic
 *
 */

function getGaleriaElement(element, index) {
	//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">Galería</span><br>' +
			'                       <span>' + element.nombre + '</span>' +
			'               </td>' +
			'               <td class="hora-noticia">' + element.fecha.getDate() + ' de ' + getMonthByIndex(element.fecha.getMonth()) + '</td>' +
			'       </tr>' +

			'       <tr>' +
			'               <td class="galeria" colspan="3">' +
			'       			<a href="galeria.html?id=' + element.id_contenido + '"><img src="' + element.imagen + '" /></a>' +
			'               </td>' +
			'       </tr>' +

			'       <tr>' +
                        '		<td class="galeria-portada-cabecera" colspan="3">' + element.descripcion + '</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() {
}*/

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

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

/**
Download galleries from the server
**/

function _downloadGaleria() {
	var oReq = new XMLHttpRequest({mozSystem: true});
	oReq.open("GET", "https://api.storageroomapp.com/accounts/5127b2ad0f660245fa00106c/collections/5130f9b10f6602368e002649/entries.json?auth_token=iazyariHhoxQnisc4UyX&per_page=50&page=1&order=asc", true);
	oReq.timeout = 20000;
	oReq.ontimeout = function (e) {
		_showError('Verifica tu conexión a Internet');
	}
	oReq.onerror = function (e) {
		_showError("Algo anda mal :'(\nIntentalo más tarde.");
	}
	oReq.onload = function(e) {
		var parser = new IcomParserInicio(this.responseText);
		parser._ToGaleriaArray();
		lstGaleria.forEach(function (element, index, array) {
			document.getElementById("div-main").appendChild(getGaleriaElement(element, index));
		});
		_hideLoader();
	}
	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);
	};
}