// JavaScript Document

// Carga de documento

$(document).ready(function() {
			
			// Es explorer ??
		  if($.browser.msie) {
			  			// Si es así se utiliza innerShiv
						$.get('wiseri_rss_widget/rss_widget.html', function(data) {
						$(innerShiv(data), false).appendTo('#wiseriWGRSS')
						RSSwidget.loadXML("wiseri_rss_widget/xmlget.php");
						RSSwidget.intervalID = setInterval( function(){ RSSwidget.loadXML(RSSwidget.readPath)}, RSSwidget.refreshT * 60000 );
						});
				} else {
							// Otros navegadores (safari, chrome, firefox)
							$('#wiseriWGRSS').load( 'wiseri_rss_widget/rss_widget.html', function(){
														RSSwidget.loadXML("wiseri_rss_widget/xmlget.php");
														RSSwidget.intervalID = setInterval( function(){ RSSwidget.loadXML(RSSwidget.readPath)}, RSSwidget.refreshT * 60000 );
													});
				}
 });


/**
 * Clase RSSwidget
 */
var RSSwidget = {
		xmlData:	{},					// Objeto de datos XML
		nodes:		new Array(),		// Lista de nodos para <li>
		
		// -- Objeto de variables globales, se accederá con top.RSSwidget.xoXXXXX --
		auxSt:		"",
		searchSt:	"",
		readPath:	"wiseri_rss_widget/xmlget.php", //Ruta de lectura de datos
		
		// -- Eventos --
		onLoad:		new function(){},	// Evento de Carga se puede redireccionar a cualquier función
		refreshT:	15,					// Intervalo de refresco de información en minutos
		intervalID: 0					// Identificador de intervalo
		};
		
	/**
	 * Cargador XML
	 * @param url
	 */
	RSSwidget.loadXML = function loadXML(url) {
		
		$('#navigation_content').animate({left:'0%'},5	, function(){});
		$('#loading').fadeIn("slow");
		
		// Comprueba si hay búsqueda activa para que no se borre con el intervalo
		if(RSSwidget.searchSt != "") url += '?query=' + escape(RSSwidget.searchSt); 
		
		$.ajax({
            type:			"POST",
            url:			url,
			dataType:		"script xml",
			contentType:	"application/x-www-form-urlencoded",
			cache:			false,
			async:			true,
			success:		function(data) {
									
									var xml;

									// ¿ Es explorer?
									if($.browser.msie) {
										xml = new
										ActiveXObject('Microsoft.XMLDOM');
										xml.async = false;
										xml.loadXML(data);
										
									} else {
										xml = data;
									}
				
									RSSwidget.xmlData = xml;
									RSSwidget.processReqChange(xml);
								}
								
			
       		}); //close $.ajax(

		};
	
	
	
	/**
	 * Procesa datos rss/xml y los traduce a xml dentro de la capa de contenido
	 * @param xml	objeto xml
	 */
	RSSwidget.processReqChange = function(xml){
		
		var nuevoAlto = "";							// Calculo de nuevo alto para widget en función de la capa 'wiseriWGRSS'
		
		$('#wiseriWGRSS li').remove();
        $(xml).find('item').each(function(index){
				
				// -- Crea objeto para recopilar datos de cada 'ITEM' del XML. --
				var item = {};
				
				// -- Se está buscando un valor?? --
				if(RSSwidget.searchSt == ""){
					// Valor NO encontrado
					$(this).children().each(function(index){
						switch(index){
							case 0:
								item.title = $(this).text();
							break;
							case 1:
								item.url = $(this).text();
							break;
							case 2:
								item.content = $(this).text();
							break;
							}
						});
				} else {
							// Valor encontrado
							// El orden de los campos con la opción 'query' cambia
							$(this).children().each(function(index){
								switch(index){
									case 0:
										item.title = $(this).text();
									break;
									case 2:
										item.url = $(this).text();
									break;
									case 1:
										item.content = $(this).text();
									break;
									}
								});
							}
							
				RSSwidget.nodes.push(item);
	        	
				// -- Añade línea con nueva oferta --
				var item = $('#wiseriWGRSS ul').append("<li><a href='#'><h3 style='color:#000000;'>" +  $(this).find('title').text() + "</h3><p style='color:#000000;'>" +  $(this).find('pubDate').text() + "</p></a></li>" );
								
				
        }); //close each(
		
		
		// -- Aplica evento de 'click' de ratón a a las ofertas --
		$('#wiseriWGRSS ul').find('a').each( function(index){
			
			this.idx = index;
			$(this).click( function() {
					$('#wiseriWGRSS #title').html(RSSwidget.nodes[this.idx].title);
					$('#wiseriWGRSS #description').html(RSSwidget.nodes[this.idx].content);
					//RSSwidget.trace( this.idx +": " + RSSwidget.nodes[index].content);
					$('#wiseriWGRSS #navigation_content').animate({left:'-100%'},500, function(){});
				});	
		});
		
		// -- Calcula alto del widget dinámicamente --
		nuevoAlto = String( parseInt($('#wiseriWGRSS').css('height')) - 195) + "px";
		$('#wiseriWGRSS #offers_ov').css('height', nuevoAlto );
		$('#wiseriWGRSS #description_ov').css('height', nuevoAlto );
		$('#wiseriWGRSS #navigation_ov').css('height', String(parseInt(nuevoAlto) + 48) );
		
		// -- Muestra ofertas y desaparece capa del cargador --
		$('#wiseriWGRSS #loading').fadeOut("slow");
		
	  //RSSwidget.onLoad(); // -- Fin de interpretación de datos >> evento de continuar    	
	    
	};
	
	/**
	 * Búsqueda (Resetea el intevalo de auto-refresco al tiempo establecido)
	 * param msg	cadena de búsqueda cogida del input
	 */
	RSSwidget.search = function (msg){
			delete RSSwidget.nodes;
			RSSwidget.nodes = new Array;
			RSSwidget.searchSt = msg;
			
			// Reinicia intervalo de tiempo antes de buscar.
			clearInterval(RSSwidget.intervalID);
			RSSwidget.loadXML("wiseri_rss_widget/xmlget.php");
			RSSwidget.intervalID = setInterval( function(){ RSSwidget.loadXML(RSSwidget.readPath)}, RSSwidget.refreshT * 60000 );
	};
	
	/**
	 * Traza mensaje
	 * @param msg
	 */
	RSSwidget.trace = function (msg){
		
		//Firefox users can use the 'Firebug' extension's console.
		if(window.console){
			console.log(msg);			
		} else {
			//alert(msg);
			}
			
		};

