var items = null;

// FONCTION getTextOfNode
	function getTextOfNode (node) {
	    var buf = "";

	    // iterate through all child elements and collect all text to the buffer
	    var child = node.firstChild;
	    while (child != null) {
	        if (child.nodeType == 3 || child.nodeType == 4) {
	            // append text to buffer
	            if (buf != "") {
	                buf += " ";
	            }
	            buf += child.nodeValue;
	        }
	        child = child.nextSibling;
	    }
	    
	    // strip all tags from the buffer
	    var strippedBuf = "";
	    var textStartPos = -1;
	    var tagBalance = 0;
	    
	    // iterate through the text and append all text to the stripped buffer
	    // that is at a tag balance of 0
	    for (pos = 0; pos < buf.length; pos++) {
	        var c = buf.charAt(pos);
	        if (c == '<') {
            // entering a tag
            if (tagBalance == 0 && textStartPos != -1) {
            // everything up to here was valid text
            strippedBuf += buf.substring(textStartPos, pos);
            textStartPos = -1;
            }
            tagBalance++;
	        } else if (c == '>') {
            // leaving a tag
            tagBalance--;
            textStartPos = -1;
	        } else if (tagBalance == 0 && textStartPos == -1) {
            // first char of text
            textStartPos = pos;
	        }
	}
    
    // add remaining text - if any
    if (tagBalance == 0 && textStartPos != -1) {
        strippedBuf += buf.substring(textStartPos, pos);
    }
    
    return strippedBuf;
}

// DECODER URL.
function URLDecode (encodedString) {
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	while ((match = myregexp.exec(output)) != null
		             && match.length > 1
		             && match[1] != '') {
	binVal = parseInt(match[1].substr(1),16);
	thisString = String.fromCharCode(binVal);
	output = output.replace(match[1], thisString);
	}
	return output;
	}
	
// FONCTION POUR FORCER LES PRIVILEGES
function Ajax() 
{
	//	xmlHttpRequest object	
	var request = null;

    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try 
		{
			request = new XMLHttpRequest();
		
		} 
		catch(e) {
			request = null;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	request = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		request = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		alert('Failed to create XmlHttprequest');
				return null;
        	}
		}
    }
	
	return (request);
}

// FONCTION POUR VERIFIER SI LE FLUX EST PRET
function callback(response) {
	/*alert (response.Text)*/
}

function rss(){
    
    // create new XML HTTP request
    var httpReq = new Ajax();
   
    // set callback
    var self = this;
    httpReq.onreadystatechange = function() {
	    // complete request?
	    if (httpReq.readyState == 4) {
	        // attempt to get response status
	        var responseStatus = null;
	        try {
	            responseStatus = httpReq.status;
	        } catch (noStatusException) {}
	        
	        // handle the response and call the registered callback
	        //this.callback.call(this, this.handleResponse(responseStatus, this.httpReq.responseXML));
	        items = treatRss(httpReq);
			
	    	renderItems(items);
			$("#news").newsTicker() ;
	    }
	}

	// append the current time after the URL to bypass caches
	//var fullURL = "http://" + document.domain + "/proxy/rss.php?url=http://corp.webwag.com/?feed=rss2";
	var fullURL = "http://corp.webwag.com/?feed=rss2";

    if (fullURL.indexOf("?") == -1) {
        fullURL += "?";
    } else {
        fullURL += "&";
    }
    fullURL += "nocache=" + (new Date().getTime());
    
    // initiate the request
    httpReq.open("GET", fullURL, true);
    httpReq.send(null);
}

// FONCTION TRAITEMENT XML
function treatRss(response) {
	var xmlDoc 		= response.responseXML;
	var itemElements 	= xmlDoc.getElementsByTagName("item");
	var items			= [];
	
	for (var i = 0; i < itemElements.length; i++) {
		// TOUS LES CHAMPS DONT NOUS AVONS BESOIN
		var title = null;
		var date = null;
		var link = null;

		node = itemElements[i].firstChild;
		while (node != null) {
		
			if (node.nodeType == 1) {
				if (node.nodeName == "title") {
					// ITEM TITRE
					title = getTextOfNode(node);
				}
				else if (node.nodeName == "pubDate" || node.nodeName == "dc:date") {
					// ITEM DATE DE PUBLICATION
					d = getTextOfNode(node);
					var d = new Date(d);
					var curr_date = d.getDate();
					var curr_month = d.getMonth();
					var curr_year = d.getFullYear();
					date = curr_date + "-" + curr_month + "-" + curr_year;
				}
				else if (node.nodeName == "link") {
					// LIEN URL
					link = this.getTextOfNode(node);
				}
			}
			node = node.nextSibling;
		}
		
// CREER ITEM ET RAJOUTER DANS UN TABLEAU
	items.push({ title: title, date: date, link: link });
	}
	return items;
}
		
		
// RENDU D'UN ITEM.
		var buf ="";
		function renderItem(i) {
		var item = items[i];
		buf +="<li class='newsticker'>\
					<a href="+ items[i].link +">\
					<span class='date'>\ "+ items[i].date+" </span>\ "+ items[i].title +"</a>\</li>";
		return buf
		}
		
		
			function renderItems(items) {
		for (var i = 0; i < items.length; i++) 
			{
			var output = "";
			output += renderItem(i);
			}
			 document.getElementById("news").innerHTML=output;
		}
