/* vim: set foldmethod=marker: */
/* vim: set tabstop=3: */
/* vim: set nu: */
/*
	Por Leonardo Vidarte
	lvidarte[arroba]gmail.com
	Pagina/12 Web
*/


// {{{ CLASS class_clipping
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 '';
	}
}
// CLASS class_clipping }}}
// {{{ CLASS class_clippings
function class_clippings() {

	// {{{ Properties
	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
	this.user_logged = false;
	this.user_name = '';
	// Properties }}}
	
	// {{{ Methods
	this.add = add;
	this.insert = insert;
	this.check_size = check_size;
	this.get_section = get_section;
	this.del = del;
	this.del_selected = del_selected;
	this.get_not_deleted = get_not_deleted;
	this.del_all = del_all;
	this.search = search;
	this.sort_by = sort_by;
	this.read_cookie = read_cookie;
	this.load_cookie = load_cookie;
	this.import_clips = import_clips;
	this.get_old_clips = get_old_clips;
	this.write_cookie = write_cookie;
	this.arrays2string = arrays2string;
	this.get_date = get_date;
	this.total = total;
	this.show = show;
	this.check_selected = check_selected;
	this.check_user = check_user;
	this.save = save;
	this.init_toc = init_toc;
	this.httpxml = httpxml;
	// Methods }}}
	
	// {{{ add()
	function add(url, title) {
		if (this.check_size(url, title) >= 0) {
			var clip = this.search(url, 'url');
			if (clip == -1) {
				if (this.user_logged) { 
					var clips = this.arrays2string();
					if (clips.length) clips += this.sep_clippings;
					clips += escape(url) + this.sep_ut + title.replace(/%9[34]/g, '%22');
					this.save('insert', clips, url, title);
				}
				else { this.insert(url, title); }
			}
			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);
			}
		}
		else {
			var aviso = 'Su carpeta de recortes está llena.';
			aviso += '\n\nPara más información consulte la ayuda.';
			alert(aviso);
		}
	}
	// add() }}}
	// {{{ insert()
	function insert(url, title) {
		var id = this.search(true, 'last_add');
		if (id >= 0) this.clippings[id].last_add = false;
		//Reemplazo las comillas tipográficas por comunes
		title = title.replace(/%9[34]/g, '%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.total();
		var clippings_container = new get_obj('clippings_container');
		if (clippings_container.style.display == '') this.show();
		this.write_cookie();
	}
	// insert() }}}
	// {{{ check_size()
	function check_size(url, title) {
		if (this.clippings.length) {
			var 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;
	}
	// check_size() }}}
	// {{{ get_section()
	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;
	}
	// get_section() }}}
	// {{{ del()
	function del(method) {
		switch(method) {
			case 'selected' : this.clippings = this.get_not_deleted('array'); break;
			case 'all'		 :	this.clippings.splice(0, this.clippings.length); break;
		}
		this.total();
		this.show();
		this.write_cookie();
	}
	// del() }}}
	// {{{ del_selected()
	function del_selected() {
		if (confirm('Se eliminarán los recortes seleccionados')) {
			if (this.user_logged) { this.save('del_selected', this.get_not_deleted('string')); }
			else { this.del('selected'); }
		}
	}
	// del_selected() }}}
	// {{{ get_not_deleted()
	function get_not_deleted(such_as) {
			var aux_clips = new Array();
			for (var length=0; length < this.clippings.length; length++) {
				aux_clips[length] = this.clippings[length];
				aux_clips[length].last_add = false;
			}
			if (aux_clips.length == 1) {
				if (document.form_clippings.id_clipping.checked)
					aux_clips.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
						aux_clips.splice(document.form_clippings.id_clipping[j].value, 1);
					}
					else j++;
				}
			}
			switch (such_as) {
				case 'array' :		return aux_clips;
				case 'string' :	var cad = '';
										for (var i=0; i < aux_clips.length; i++) {
											cad += escape(aux_clips[i].url) + this.sep_ut + aux_clips[i].title;
											if (i < aux_clips.length - 1) cad += this.sep_clippings;
										}
										return cad;
			}
	}
	// get_not_deleted() }}}
	// {{{ del_all()
	function del_all() {
		if (confirm('Se eliminarán todos los recortes')) {
			if (this.user_logged) { this.save('del_all', ''); }
			else { this.del('all'); }
		}
	}
	// del_all() }}}
	// {{{ search()
	function search(subject, element) {
		for (var i = 0; i < this.clippings.length; i++)
			if (this.clippings[i][element] == subject) return i;
		return -1;
	}
	// search() }}}
	// {{{ sort_by()
	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 (this.clippings[j][element] > 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--;
		}
	}
	// sort_by }}}
	// {{{ read_cookie()
	function read_cookie(cookie_name) {
		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(cookie_name) == 0)
				return cookie.substring(cookie_name.length, cookie.length);
		}
		return null;
	}
	// read_cookie() }}}
	// {{{ load_cookie()
	function load_cookie() {
		this.check_user();
		var cookie = this.read_cookie(this.cookie_name);
		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 section = this.get_section(unescape(datos[0]));
				if (this.user_logged) datos[1] = datos[1].replace(/\+/g,'%20');
				var new_clipping = new class_clipping(unescape(datos[0]), datos[1], section);
				this.clippings.unshift(new_clipping);
			}
			this.sort_by('title');
			this.sort_by('section');
		}
		this.total();
		this.init_toc();
	}
	// load_cookie() }}}
	// {{{ import_clips()
	function import_clips() {
		var clips = this.get_old_clips();
		if (clips) {
			this.clippings.splice(0, this.clippings.length);
			var array_clippings = clips.split(this.sep_clippings);
			for (var i = 0; i < array_clippings.length; i++) {
				var datos = array_clippings[i].split(this.sep_ut);
				var section = this.get_section(unescape(datos[0]));
				var new_clipping = new class_clipping(unescape(datos[0]), datos[1], section);
				this.clippings.unshift(new_clipping);
			}
			this.sort_by('title');
			this.sort_by('section');
			this.total();
			this.show();
			this.write_cookie();
		}
	}
	// import_clips() }}}
	// {{{ get_old_clips()
	function get_old_clips() {
		var old_clips = this.read_cookie('clippingspag12');
		old_clips = old_clips.replace(/\|/g,this.sep_clippings);
		old_clips = old_clips.replace(/\&/g,this.sep_ut);
		return old_clips;
	}
	// get_old_clips() }}}
	// {{{ write_cookie()
	function write_cookie() {
		var cookie = this.cookie_name + '=' + this.arrays2string() + '; ';
		if (this.expires) cookie += 'expires=' + this.get_date(this.expires) + '; ';
		cookie += 'path=/';
		document.cookie = cookie;
	}
	// write_cookie() }}}
	// {{{ arrays2string()
	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;
	}
	// arrays2string() }}}
	// {{{ get_date()
	function get_date(days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days*24*60*60*1000));
			return date.toGMTString();
		}
		else return null;
	}
	// get_date() }}}
	// {{{ total()
	function total() {
		var clippings_total = new get_obj('clippings_total');
		var cLoading = new get_obj('clippings_user');
		if (this.user_logged) {
			var html = '<acronym title="Recortes de '+this.user_name+'">';
			html += '<img src="/commons/imgs/user.gif" /></acronym>';
		}
		else {
			var html = '<a href="/usuarios/ayuda.php#news" title="Nuevo! ';
			html += 'recortes personales para usuarios registrados">';
			html += '<img src="/commons/imgs/new.gif" /></a>';
		}
		cLoading.obj.innerHTML = html;
		var html = 'Mis Recortes: ' + this.clippings.length;
		html += '<span style="color:#888">&nbsp;&nbsp;[' + this.check_size() + '%]</span>';
		clippings_total.obj.innerHTML = html;
	}
	// total() }}}
	// {{{ show()
	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" style="padding-top:10px"><h5>';
					else 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 */
			var user = (this.user_logged) ? '<b>'+this.user_name+'</b>, no' : 'No';
			html += '<tr><td>&bull;&nbsp;</td><td class="no_clips">';
			html += user + ' 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 += '<b><a class="azul" href="/usuarios/ayuda.php" title="Ayuda">?</a></b></td></tr>';
			if (this.user_logged && this.read_cookie('clippingspag12')) {
				html += '<tr><td>&bull;</td><td class="no_clips"><b>Se encontraron recortes guardados en su antigua carpeta.</b> ';
				html += '¿Desea importarlos a su caperta personal?<br />Si, <a class="azul" ';
				html += 'href="javascript:;" onclick="clippings.save(\'import\',\''+this.get_old_clips()+'\')" ';
				html += 'title="Importa todos los recortes antiguos">importar recortes</a></td></tr>';
			}
		}
		
		var news = '';
		/*
		if (!this.user_logged) {
			news += '<div style="padding-right:5px;padding-bottom:5px;text-align:center">----&nbsp;&nbsp;';
			news += '<a href="/usuarios/ayuda.php#news" title="Recortes personales para usuarios registrados" ';
			news += 'class="azul" style="font-weight:bold;font-style:normal;font-size:10px">';
			news += 'Nueva funcionalidad !</a>&nbsp;&nbsp;----</div>';
		}
		*/

		html = news + '<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;';
			html += '<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;
	}
	// show() }}}
	// {{{ check_selected()
	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;';
				html += '<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;';
					html += '<a href="javascript:;" onclick="clippings.del_selected()" title="">';
					html += 'Seleccionados</a>';
				}
				i++;
			}
		}
		del_selected.obj.innerHTML = html;
	}
	// check_selected() }}}
	// {{{ check_user()
	function check_user() {
		var user = read_cookie('usuario');
		if (user) {
				this.cookie_name = unescape(user);
				this.expires = 0;
				this.sep_clippings = '___clip___';
				this.sep_ut = '___ut___';
				this.user_logged = true;
				this.user_name = read_cookie('nombre');
				return this.cookie_name;
		}
		return null;
	}
	// check_user() }}}
	// {{{ save()
	function save(method, clips, url, title) {
		var http = this.httpxml();
		if (http) {
			var POST="clippings="+clips+"&PHPSESSID="+this.read_cookie('PHPSESSID');
			http.open('POST', '/usuarios/clippings.php', true);
        	http.setRequestHeader("Method", "POST /usuarios/clippings.php HTTP/1.1");
     		http.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			http.onreadystatechange = function() {
				var cLoading = new get_obj('clippings_user');
				if (http.readyState == 4 && http.status == 200) {
					if (http.responseText == '0') {
						alert('No fue posible guardar sus recortes');
						var html = '<acronym title="Sus recortes no pudieron ser guardados">';
					}
					else { 
						var html = '<acronym title="Sus recortes fueron guardados">';
						switch (method) {
							case 'insert' 			:	clippings.insert(url, title); break;
							case 'del_selected'	:	clippings.del('selected'); break;
							case 'del_all' 		:	clippings.del('all'); break;
							case 'import'			:	clippings.import_clips(); break;
						}
					}
					html += '<img src="/commons/imgs/user.gif" /></acronym>';
					cLoading.obj.innerHTML = html;
				}
				else {
					var html = '<acronym title="Guardando sus recortes...">';
					html += '<img src="/commons/imgs/loading.gif" alt="saving" /></acronym>';
					cLoading.obj.innerHTML = html;
				}
			};
			http.send(POST);
			//http.send(null); (solo para GET)
		}
		else {
			var aviso = 'Su navegador no soporta la función para guardar sus recortes personales.';
			aviso += '\n\nPara más información consulte la ayuda.';
			alert(aviso);
		}
	}
	// save() }}}
	// {{{ init_toc()
	function init_toc() {
		var clippings_toc = new get_obj('clippings_toc');
		var html = '<a href="javascript:;" onclick="toc_clippings()" title="" ';
		html += 'onmouseover="cambiar(\'clips_abrir\',\'clips_abrir_on\')" ';
		html += 'onmouseout="cambiar(\'clips_abrir\',\'clips_abrir_off\')">';
		html += '<img name="clips_abrir" src="/commons/imgs/clips_abrir_off.gif" alt="" /></a>';
		clippings_toc.obj.innerHTML = html;
	}
	// init_toc() }}}
	// {{{ httpxml()
	function httpxml() {
		var xmlhttp;
	  	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (e) { try { xmlhttp = new XMLHttpRequest(); }
		catch (e) { xmlhttp = false; } } }
		if (!xmlhttp) return null;
		return xmlhttp;
	}
	// httpxml() }}}
}
// CLASS class_clippings }}}

// {{{ toc_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';
	}
}
// toc_clippings() }}}

/* Creo una instancia de la clase class_clippings().
   El objeto 'clippings' es el que uso en todo el sitio */
var clippings = new class_clippings();
