// create the 'news' object
var news = {

  // this will hold the JSON data
  newsData : null,

  // this is the area where the data will be displayed
  newsArea : null,
 
  // this will reference the body tag; we will modify its id attribute
  theBody : null,
  
  // this will hold the number of news headings retrieved this time
  totalNewsItems : null,
  
  // this will hold the number of news headings retrieved last time
  oldNewsItems : null,

  init : function() {
    
    if (!document.createElement && !document.getElementsByTagName) { return; }

    // isolate tags in the document
    news.newsArea = document.getElementById('newsholder');
    news.theBody = document.getElementsByTagName('body')[0];
    
    // send the request for the JSON data
    util.sendRequest('news_fade.txt?' + Math.random(), news.holdNewsResults);
    
    // set the interval for data refresh
    var newsRefresh = setInterval(news.pullNewData, 10000);
    
  },
  
  // pull the news data again
  pullNewData : function() {
    util.sendRequest('news_fade.txt?' + Math.random(), news.holdNewsResults);
  },
  
  lastModified: null, prevMod : null, firstFade : true,

	// store the JSON data in the newsData property of this object
  holdNewsResults : function(xhr) {
    var jsonData = xhr.responseText;
    news.newsData = eval("(" + jsonData + ")");
		news.lastModified = xhr.getResponseHeader('Last-Modified');
    news.populateNews();
  },
  
  // output the news headings into the page
  populateNews : function() {

    news.newsArea.innerHTML = '';
      
    var newsHeader = document.createElement('h2');
    var headerTxt = document.createTextNode('News Headlines');
    news.newsArea.appendChild(newsHeader).appendChild(headerTxt);
    
    news.totalNewsItems = news.newsData.newsItems.length;

    for (var i=0; i<news.totalNewsItems; i++) {
        var newPara = document.createElement('p');
        var newLink = document.createElement('a');
        var lineBreak = document.createElement('br');
        var newsTitle = document.createTextNode(news.newsData.newsItems[i].heading);
        newLink.href = news.newsData.newsItems[i].url;
        newPara.appendChild(newLink).appendChild(newsTitle);
        news.newsArea.appendChild(newPara);
    }

    // check to see if if is the first time through, and if so, show fade
    // after the first time, only show fade if new data pulled in
    if (news.firstFade) {news.firstFade = false;news.prevMod = news.lastModified;news.fade('begin');}
    else if (news.prevMod < news.lastModified) {news.fade('begin');}
		news.prevMod = news.lastModified;
    
  },
  
  // cycle through background colors for the news area by assigning different id values to the body
  fade : function(state) {
    if (news.firstFade) {}
    switch(state) {
    
      case "begin": 
       news.theBody.id = 'darker1';
       var fadeState1 = setTimeout('news.fade("darker2")', 100);
       break;
    
      case "darker2":
       news.theBody.id = state; 
       var fadeState2 = setTimeout('news.fade("darker3")', 100);          
       break;
    
      case "darker3": 
       news.theBody.id = state;  
       var fadeState3 = setTimeout('news.fade("darker4")', 100); 
       break;
 
       case "darker4": 
        news.theBody.id = state;  
        var fadeState3 = setTimeout('news.fade("darker5")', 100); 
        break;
 
       case "darker5": 
        news.theBody.id = state;  
        var fadeState3 = setTimeout('news.fade("lighter4")', 100); 
        break;
 
      case "lighter4":
       news.theBody.id = 'darker4'; 
       var fadeState4 = setTimeout('news.fade("lighter3")', 100);          
       break;

      case "lighter3":
       news.theBody.id = 'darker3'; 
       var fadeState5 = setTimeout('news.fade("lighter2")', 100);          
       break;

      case "lighter2":
       news.theBody.id = 'darker2'; 
       var fadeState5 = setTimeout('news.fade("lighter1")', 100);          
       break;
       
      case "lighter1":
       news.theBody.id = 'darker1'; 
       var fadeState5 = setTimeout('news.fade("normal")', 100);          
       break;       
    
      case "normal": news.theBody.id = '';
   
    }
  }

}

var util = {

  // pass the url of the data file, the function that will receive it, and whether data is being posted (optional)
  sendRequest : function(url,func,postData) {
    
    // xhr will represent the XMLHttpRequest object
    var xhr = util.createXMLHttpObject();
    
    // if that does not work out, then it will be null and the function will exit
    if (!xhr) { return; }
    
    // if the optional postData is indicated, then use "POST"
    var method = (postData) ? "POST" : "GET";
    
    // open the request
    xhr.open(method, url, true);
    
    // set a unique request header for detection purposes
    xhr.setRequestHeader('User-Agent','XHR');
    
    // if data is being posted, set the appropriate Content-Type
    if (postData) {
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    }
    
    xhr.onreadystatechange = function() {
      
      // unless the request is Completed, ignore the readystatechange event
      if (xhr.readyState != 4) { return; }
      
      // if there is an error in the data transmission, show an alert
      if (xhr.status != 200 && xhr.status != 304) {
         alert('HTTP error ' + xhr.status);
         return;
      }
      
      // pass the XMLHttpRequest object to holdNewsResults()
      func(xhr);
    }
    
    // if we have already completed the request, stop the function so as not
    // to send it again
    if (xhr.readyState == 4) { return; }
    
    // if we use "GET" then postData will be null
    xhr.send(postData);
  },
	
  // all the various cross-browser options for creating the XMLHttpRequest object  
  XHRoptions : [
   function () {return new XMLHttpRequest()},
   function () {return new ActiveXObject("Msxml2.XMLHTTP")},
   function () {return new ActiveXObject("Msxml3.XMLHTTP")},
   function () {return new ActiveXObject("Microsoft.XMLHTTP")}
  ],

  // try out each option until one works
  createXMLHttpObject : function() {
    var xmlhttp = false;
    for (var i=0;i<util.XHRoptions.length;i++) {
      try { xmlhttp = util.XHRoptions[i](); }
      catch (e) { continue; }
      break;
    }
    return xmlhttp;
  },

  addEvent : function(obj, type, func) {
    if (obj.addEventListener) {obj.addEventListener(type, func, false);}
    else if (obj.attachEvent) {
      obj["e" + type + func] = func;
      obj[type + func] = function() {obj["e" + type + func] (window.event);}
      obj.attachEvent("on" + type, obj[type + func]);
    }
    else {obj["on" + type] = func;}
  }

}

util.addEvent(window,'load',news.init);