/*
	Por Leonardo Vidarte
	lvidarte[arroba]gmail.com
	Pagina/12 Web
*/

function class_clipping(url, title, section) {
	
	/* Propiedades */
	this.url = url;
	this.title = title;
	this.section = section;
	this.last_add = false;
	this.visited = false;

	/* Métodos */
	this.link = link;
	this.get_date = get_date;

	/* Desarrollo */
	function link(id) {
		return this.get_date() + '<a href="' + this.url + '">' + unescape(this.title) + '</a>';
	}

	function get_date() {
		rx = new RegExp('([0-9]{4})-([0-9]{2})-([0-9]{2}).html');
		x = rx.exec(this.url);
		if (x != null) return '<span class="clip_date">'+x[3]+'-'+x[2]+'-'+x[1].substr(2,4)+'</span>';
		else return '';
	}
}


function class_clippings() {

	/* Propiedades */
	this.clippings = new Array();
	this.sections = new Array();
	this.sections[0] = new Array('elpais','El pa&iacute;s','/diario/elpais/index.html');
	this.sections[1] = new Array('economia','Econom&iacute;a','/diario/economia/index.html');
	this.sections[2] = new Array('sociedad','Sociedad','/diario/sociedad/index.html');
	this.sections[3] = new Array('elmundo','El mundo','/diario/elmundo/index.html');
	this.sections[4] = new Array('opinion','Opini&oacute;n','/diario/opinion/index.html');
	this.sections[5] = new Array('espectaculos','Espect&aacute;culos','/diario/espectaculos/index.html');
	this.sections[6] = new Array('cultura','Cultura','/diario/cultura/index.html');
	this.sections[7] = new Array('ciencia','Ciencia','/diario/ciencia/index.html');
	this.sections[8] = new Array('deportes','Deportes','/diario/deportes/index.html');
	this.sections[9] = new Array('psicologia','Psicolog&iacute;a','/diario/psicologia/index.html');
	this.sections[10] = new Array('universidad','Universidad','/diario/universidad/index.html');
	this.sections[11] = new Array('artes','Pl&aacute;stica','/diario/artes/index.html');
	this.sections[12] = new Array('placer','Placer','/diario/placer/index.html');
	this.sections[13] = new Array('discos','Discos','/diario/discos/index.html');
	this.sections[14] = new Array('videos','Videos','/diario/videos/index.html');
	this.sections[15] = new Array('escrito','Escrito &amp; Le&iacute;do','/diario/escrito/index.html');
	this.sections[16] = new Array('especiales','Especiales','/diario/especiales/index.html');
	this.sections[17] = new Array('contratapa','Contratapa','/diario/contratapa/index.html');
	this.sections[18] = new Array('ultimas','Ultimas Noticias','/diario/ultimas/index.html');
	this.sections[19] = new Array('pirulo','Pirulo de Tapa','/diario/principal/pirulo/index.html');

	this.mark = 20; // Posicion en que empiezan los suples

	this.sections[20] = new Array('cash','Cash','/diario/suplementos/cash/index.html');
	this.sections[21] = new Array('espectaculos','Cultura &amp; Espect&aacute;culos','/diario/suplementos/espectaculos/index.html');
	this.sections[22] = new Array('futuro','Futuro','/diario/suplementos/futuro/index.html');
	this.sections[23] = new Array('las12','Las/12','/diario/suplementos/las12/index.html');
	this.sections[24] = new Array('libero','L&iacute;bero','/diario/suplementos/libero/index.html');
	this.sections[25] = new Array('libros','Radar Libros','/diario/suplementos/libros/index.html');
	this.sections[26] = new Array('m2','M2','/diario/suplementos/m2/index.html');
	this.sections[27] = new Array('no','NO','/diario/suplementos/no/index.html');
	this.sections[28] = new Array('radar','Radar','/diario/suplementos/radar/index.html');
	this.sections[29] = new Array('rosario','Rosario/12','/diario/suplementos/rosario/index.html');
	this.sections[30] = new Array('satira','S&aacute;tira','/diario/suplementos/satira/index.html');
	this.sections[31] = new Array('turismo','Turismo','/diario/suplementos/turismo/index.html');
	
	this.cookie_name = 'clippingspag12=';
	this.expires = 365; // Dias que se almacenara la cookie
	this.sep_clippings = '|'; // Separador de recortes
	this.sep_ut = '&'; // Separador de URL y titulo

	/* Métodos */
	this.add = add;
	this.check_size = check_size;
	this.get_section = get_section;
	this.del = del;
	this.del_selected = del_selected;
	this.del_all = del_all;
	this.search = search;
	this.sort_by = sort_by;
	this.arrays2string = arrays2string;
	this.get_date = get_date;
	this.read_cookie = read_cookie;
	this.load_cookie = load_cookie;
	this.write_cookie = write_cookie;
	this.total = total;
	this.show = show;
	this.check_selected = check_selected;
	
	/* Desarollo */
	function add(url, title) {
		if (this.check_size(url, title) >= 0) {
			var clip = this.search(url, 'url');
			if (clip == -1) {
				var id = this.search(true, 'last_add');
				if (id >= 0) this.clippings[id].last_add = false;
				/* Reemplazo las comillas tipográficas por comunes */
				var rx = new RegExp('%9[34]', 'g');
				title = title.replace(rx, '%22');
				var new_clipping = new class_clipping(url, title, this.get_section(url));
				this.clippings.unshift(new_clipping);
				this.clippings[0].last_add = true;
				this.sort_by('title');
				this.sort_by('section');
				this.write_cookie();
				this.total();
				var clippings_container = new get_obj('clippings_container');
				if (clippings_container.style.display == '') this.show();
			}
			else {
				var aviso = 'La nota que seleccionó ya estaba en su carpeta de recortes ';
				aviso += 'bajo el siguiente título:\n' + unescape(this.clippings[clip].title);
				aviso += '\n\nPara más información consulte la ayuda.';
				alert(aviso);
			}
		}
	}

	function check_size(url, title) {
		if (this.clippings.length) {
			var cookie = '';
			cookie += this.cookie_name + this.arrays2string();
			if (url && title) cookie += this.sep_clippings + escape(url) + this.sep_ut + title;
			cookie += '; expires=' + this.get_date(7) + '; path=/';
			if (cookie.length < 4096) return Math.ceil(cookie.length * 100 / 4096);
			return -1;
		}
		return 0;
	}
	
	function get_section(url) {
		var split_url = url.split('/');
		for (var i = 0; i < split_url.length; i++) {
			for (var j = 0; j < this.sections.length; j++) {
				if (split_url[i] == this.sections[j][0])
					return j;
			}
		}
		return null;
	}

	/* Método actualmente sin uso */
	function del(id) {
		if (confirm('Se eliminará:\n' + this.clippings[id].title)) {
			this.clippings.splice(id, 1);
			this.write_cookie();
			this.total();
			this.show();
		}
	}

	function del_selected() {
		if (confirm('Se eliminarán los recortes seleccionados')) {
			var id = this.search(true, 'last_add');
			if (id >= 0) this.clippings[id].last_add = false;
			var length = this.clippings.length;
			if (length == 1) {
				if (document.form_clippings.id_clipping.checked)
					this.clippings.splice(document.form_clippings.id_clipping.value, 1);
			}
			else {
				var j = 0;
				for (var i = 0; i < length; i++) {
					if (document.form_clippings.id_clipping[i].checked) {
						// Uso j porque splice() cambia los índices al eliminar
						this.clippings.splice(document.form_clippings.id_clipping[j].value, 1);
					}
					else j++;
				}
			}
			this.write_cookie();
			this.total();
			this.show();
		}
	}

	function del_all() {
		if (confirm('Se eliminarán todos los recortes')) {
			this.clippings.splice(0, this.clippings.length);
			this.write_cookie();
			this.total();
			this.show();
		}
	}

	function search(subject, element) {
		for (var i = 0; i < this.clippings.length; i++)
			if (eval('this.clippings['+i+'].'+element) == subject) return i;
		return -1;
	}

	function sort_by(element) {
		var i = this.clippings.length - 1;
		var ordenado = false;
		while (i > 0 && !ordenado) {
			ordenado = true;
			for (var j = 0; j < i; j++) {
				if (eval('this.clippings[j].'+element) > eval('this.clippings[j+1].'+element)) {
					var aux = this.clippings[j];
					this.clippings[j] = this.clippings[j+1];
					this.clippings[j+1] = aux;
					ordenado = false;
				}
			}
			i--;
		}
	}

	function read_cookie(name) {
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++) {
			var cookie = cookies[i];
			while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
			if (cookie.indexOf(name) == 0) return cookie.substring(name.length, cookie.length);
		}
		return null;
	}
	
	function load_cookie() {
		var cookie = this.read_cookie(this.cookie_name);
		var clippings_toc = new get_obj('clippings_toc');
		if (cookie) {
			this.clippings.splice(0, this.clippings.length);
			var array_clippings = cookie.split(this.sep_clippings);
			for (var i = 0; i < array_clippings.length; i++) {
				var datos = array_clippings[i].split(this.sep_ut);
				var new_clipping = new class_clipping(unescape(datos[0]), datos[1], this.get_section(unescape(datos[0])));
				this.clippings.unshift(new_clipping);
			}
			this.sort_by('title');
			this.sort_by('section');
		}
		this.total();
		var html = '<a href="javascript:;" onclick="toc_clippings()" title="" onmouseover="cambiar(\'clips_abrir\',\'clips_abrir_on\')" onmouseout="cambiar(\'clips_abrir\',\'clips_abrir_off\')"><img name="clips_abrir" src="/commons/imgs/clips_abrir_off.gif" alt="" /></a>';
		clippings_toc.obj.innerHTML = html;
	}

	function write_cookie() {
		var cookie = '';
		cookie += this.cookie_name + this.arrays2string() + '; ';
		cookie += 'expires=' + this.get_date(this.expires) + '; ';
		cookie += 'path=/';
		document.cookie = cookie;
	}

	function arrays2string() {
		var cad = '';
		for (var i = 0; i < this.clippings.length; i++) {
			cad += escape(this.clippings[i].url) + this.sep_ut + this.clippings[i].title;
			if (i < this.clippings.length - 1) cad += this.sep_clippings;
		}
		return cad;
	}

	function get_date(days) {
		var date = new Date();
		if (days) {
			date.setTime(date.getTime() + (days*24*60*60*1000));
			return date.toGMTString();
		}
		else return days;
	}
	
	function total() {
		var clippings_total = new get_obj('clippings_total');
		var html = 'Mis Recortes: ' + this.clippings.length;
		html += '<span style="color:#888">&nbsp;&nbsp;[' + this.check_size() + '%]</span>';
		clippings_total.obj.innerHTML = html;
	}

	function show() {
		var clippings_folder = new get_obj('clippings_folder');
		var del_selected = new get_obj('del_selected');
		var del_all = new get_obj('del_all');
		var clip_help = new get_obj('clip_help');
		var html = '';
		var actual_section = -1;
		var news_printed = false;
		var suples_printed = false;
		if (this.clippings.length) {
			for (var i = 0; i < this.clippings.length; i++) {
				if (this.clippings[i].section < this.mark && !news_printed) {
					html += '<tr><td colspan="2"><h5>';
					html += '<img src="/commons/imgs/folder.gif" alt="" style="display:inline" />';
					html += '<a href="/diario/secciones/index.html">';
					html += 'Secciones</a></h5></td></tr>';
					news_printed = true;
				}
				if (this.clippings[i].section >= this.mark && !suples_printed) {
					if (news_printed) html += '<tr><td colspan="2">&nbsp;</td></tr>';
					html += '<tr><td colspan="2"><h5>';
					html += '<img src="/commons/imgs/folder.gif" alt="" style="display:inline" />';
					html += '<a href="/diario/suplementos/index.html">';
					html += 'Suplementos</a></h5></td></tr>';
					suples_printed = true;
				}

				if (this.clippings[i].section != actual_section) {
					html += '<tr><td colspan="2"><h6><a href="';
					html += this.sections[this.clippings[i].section][2] + '">';
					html += this.sections[this.clippings[i].section][1] + '</a></h6></td></tr>';
					actual_section = this.clippings[i].section;
				}

				html += '<tr><td><input type="checkbox" name="id_clipping" value="' + i;
				html += '" onclick="clippings.check_selected()"></td>';
				html += '<td>' + this.clippings[i].link() + '</td></tr>';
			}
			id = this.search(true, 'last_add');
			if (id >= 0 && this.clippings.length > 1) {
				var last = '<tr><td colspan="2"><div id="last_clip"><div id="lct">';
				last += 'Ultimo, guardado en '+this.sections[this.clippings[id].section][1]+':</div>';
				last += '<div id="lcl">' + this.clippings[id].link() + '</div></div></td></tr>';
				html = last + html;
			}
		}
		else {
			/* Texto para la carpeta vacía */
			html += '<tr><td>&bull;&nbsp;</td><td class="no_clips">';
			html += 'No hay notas en su carpeta de recortes.</td></tr>';
			html += '<tr><td>&bull;&nbsp;</td><td class="no_clips">';
			html += 'Para guardar una nota haga click en el &iacute;cono ';
			html += '<img src="/commons/imgs/cut.gif" alt="" style="display:inline"> ';
			html += 'que se encuentra junto a la misma.</td></tr>';
			html += '<tr><td>&bull;&nbsp;</td><td class="no_clips">';
			html += 'Puede consultar la ayuda detallada haciendo click en ';
			html += 'el signo <b>?</b> que se encuentra en la parte inferior derecha ';
			html += 'de la carpeta de recortes.</td></tr>';
		}

		html = '<form name="form_clippings"><table>' + html + '</table></form>';
		clippings_folder.obj.innerHTML = html;

		html = '<img src="/commons/imgs/trash_off.gif">&nbsp;Seleccionados';
		del_selected.obj.innerHTML = html;

		if (this.clippings.length) {
			html = '<img src="/commons/imgs/trash_on.gif">&nbsp;<a href="javascript:;" onclick="clippings.del_all()" title="">Todos</a>';
			del_all.obj.innerHTML = html;
		}
		else {
			html = '<img src="/commons/imgs/trash_off.gif">&nbsp;Todos';
			del_all.obj.innerHTML = html;
		}

		html = '<a href="/usuarios/ayuda.php" title="Ayuda">?</a>';
		clip_help.obj.innerHTML = html;
	}

	function check_selected() {
		var del_selected = new get_obj('del_selected');
		var i = 0;
		var encontrado = 0;
		var html = '<img src="/commons/imgs/trash_off.gif">&nbsp;Seleccionados';
		if (this.clippings.length == 1) {
			if (document.form_clippings.id_clipping.checked) {
				html  = '<img src="/commons/imgs/trash_on.gif">&nbsp;<a href="javascript:;" onclick="clippings.del_selected()" title="">';
				html += 'Seleccionados</a>';
			}
		}
		else {
			while (i < this.clippings.length && !encontrado) {
				if (document.form_clippings.id_clipping[i].checked) {
					encontrado = 1;
					html  = '<img src="/commons/imgs/trash_on.gif">&nbsp;<a href="javascript:;" onclick="clippings.del_selected()" title="">';
					html += 'Seleccionados</a>';
				}
				i++;
			}
		}
		del_selected.obj.innerHTML = html;
	}
}



/* Creo una instancia de la clase class_clippings().
   El objeto 'clippings' es el que uso en todo el sitio */
var clippings = new class_clippings();


/* Funcion para abrir y cerrar la carpeta de clippings */
function toc_clippings() {
	var clippings_toc = new get_obj('clippings_toc');
	var clippings_container = new get_obj('clippings_container');
	if (clippings_container.style.display == 'none') {
		/* 1.Cierro cualquier menu desplegable */
		if (secs) {
			secs = 0;
			StartTheTimer();
		}
		/* 1.End */
		
		clippings_toc.obj.innerHTML = '<a href="javascript:;" onclick="toc_clippings()" title="" onmouseover="cambiar(\'clips_cerrar\',\'clips_cerrar_on\')" onmouseout="cambiar(\'clips_cerrar\',\'clips_cerrar_off\')"><img name="clips_cerrar" src="/commons/imgs/clips_cerrar_off.gif" alt="" /></a>';
		clippings_container.style.display = '';
		clippings.show();
	}
	else {
		clippings_toc.obj.innerHTML = '<a href="javascript:;" onclick="toc_clippings()" title="" onmouseover="cambiar(\'clips_abrir\',\'clips_abrir_on\')" onmouseout="cambiar(\'clips_abrir\',\'clips_abrir_off\')"><img name="clips_abrir" src="/commons/imgs/clips_abrir_off.gif" alt="" /></a>';
		clippings_container.style.display = 'none';
	}
}

