(function() {
    biooncology = {};
})();

document.observe("dom:loaded", function(ev) {	
    var nf = new biooncology.NewsFeed();
});


/** NewsItem Class - Represents a feed and holds the timestamp and all news items for that feed. 
 *  Dependencies: Prototype
 */
biooncology.NewsItem = Class.create({

      /** @constructor */
        initialize: function() {
            this.timeStamp = "";
            this.newsItems = [];
        },
        toString: function() {
            return "[object NewsItem]";
        }
});


/** NewsFeed Class - Represents the tabbed news display and stores all the raw data.
 *  Dependencies: Prototype, ext-tabs.js (and Ext CSS files), utf8.js
 */
biooncology.NewsFeed = Class.create({

      /** @constructor */
        initialize: function() {
            this.tabs = new Array();
            this.JSONDataFeed = new Array();
            this.changeCounter = 0;
            this.JSONData();
        },
        Version: "1.0",
        toString: function() {
            return "[object NewsFeed]";
        }
});

/**  
 *  NewsFeed Class Variables to store the URIs to the news source and display pages.
 */
biooncology.NewsFeed.prototype.newsSourceURI = "/bioonc-ws/service/news.list";
biooncology.NewsFeed.prototype.newsDisplayURI = "news-feed/index.html?path=";


/**
 *  Method to render the Ext.Panel
 */
biooncology.NewsFeed.prototype.create = function(){

     /*this.NewsPanel = new Ext.TabPanel({
        renderTo: "news-feed",
        activeTab: 0,
        width: 217,
        height: 'auto',
        plain: true,
        autoShow: true,
        listeners:{
          beforetabchange : this.onClick.bind(this)
        },
        defaults: {
          autoScroll: false,
          autoHeight: true
        },
        items: [{
                 contentEl:'reuters-feed',
                 cls: 'first-tab',
                 listeners: { 
                              activate: this.onActivate.bind(this),
                              deactivate: this.onDeactivate.bind(this),
                              beforehide: this.onHide.bind(this)
                             }
               },{
                 contentEl: 'bioonc-feed', 
                 cls: 'second-tab',
                 style:{opacity:0},
                 listeners: { 
                              activate: this.onActivate.bind(this), 
                              deactivate: this.onDeactivate.bind(this),
                              beforehide: this.onHide.bind(this)
                            }
                 }]
      });*/
     
      //this.tabs[0] = this.NewsPanel.getTabEl(0).parentNode;
      //this.tabs[0].childElements()[0].addClassName('reuters-tab');
      //this.tabs[0].childElements()[1].addClassName('bioonc-tab');
      //this.tabs[1] = this.createDummyTabs();
      //this.NewsPanel.doLayout();
      this.buildNewsDisplay();
      
      //adding class to differnt pages
      if(location.href.match(/news-feed/)) $('news-feed').addClassName('detail-page');
      
      //auto change //
      //since IE dosen't let setTimeout to pass extra arguments so made them array
      this.autoChangeStage = 0;
      this.autoChanges = new Array();
      this.autoChanges[0] = [setTimeout(this.autoClick.bind(this),6000),1];
      this.autoChanges[1] = [setTimeout(this.autoClick.bind(this),10000),0];
};

/**
 *  Method to create a copy of the entire tab(ul)
 */
biooncology.NewsFeed.prototype.createDummyTabs = function(){
    var TabsCopy = this.tabs[0].cloneNode(true);
    TabsCopy.setStyle({position:'absolute',top:0, left:0, display: 'none'});
    TabsCopy.addClassName('flip');
    this.tabs[0].parentNode.appendChild(TabsCopy);
    return TabsCopy;
}

/**
 *  Method to automatically animate the tab display
 */
biooncology.NewsFeed.prototype.autoClick = function(){
  if (this.autoChanges[this.changeCounter]) {
    if (this.autoChangeStage == this.changeCounter) { //checking if how many times the tab was changed and if it matches with how many times it should be clicked automatically 
      this.NewsPanel.activate(this.NewsPanel.getComponent(this.autoChanges[this.changeCounter][1]));
      this.autoChangeStage++;
    } else {
      for (var i = 0; i < this.autoChanges.length; i++) {
        if (this.autoChanges[i][0]) window.clearTimeout(this.autoChanges[i][0]);
      }
    }
  }
};

biooncology.NewsFeed.prototype.onActivate = function(tab){
    if(tab.body){ 
      this.fadeIn(tab.body.dom.parentNode.parentNode);
      if(this.tabs[0]) this.fadeIn(this.tabs[0]);
    };
};

biooncology.NewsFeed.prototype.onDeactivate = function(tab){
    if(tab.body){
      this.fadeOut(tab.body.dom.parentNode.parentNode);
      this.fadeOut(this.tabs[1]);
    };
};

biooncology.NewsFeed.prototype.onHide = function(tab){
    if(tab)return false;
};

biooncology.NewsFeed.prototype.onClick = function(panel, nTab, cTab){
    if (cTab) {
      flip(this.tabs[1]);
      this.tabs[1].setOpacity(1);
      this.tabs[1].show();
      this.tabs[0].setOpacity(0);
      flip(this.tabs[0]);
      
      if(this.changeCounter<2) this.changeCounter++;
    };
    
    function flip(ulEl){
      if(ulEl.hasClassName('flip')){
        ulEl.removeClassName('flip');
      }else{
        ulEl.addClassName('flip');
      }; 
    };

};

biooncology.NewsFeed.prototype.fadeOut = function(el){
    new Effect.Opacity(el, {from: 1, to: 0, duration: 1 });
    var tb = this.tabs[1];

    new PeriodicalExecuter(function(pe){
         el.style.zIndex = 1;
         tb.hide();
         pe.stop();
        },1); 
}

biooncology.NewsFeed.prototype.fadeIn = function(el){ 
    el.style.zIndex = 10;
    new Effect.Opacity(el, {from: 0,to: 1,duration: 1});  
};

/**
 *  Method to build the markup for each feed.
 */
biooncology.NewsFeed.prototype.buildNewsDisplay = function(){

	var _getMonthString = function(month){
		switch (month) {
			case 0:
				return "Jan";
				break;
			case 1:
				return "Feb";
				break;
			case 2:
				return "Mar";
				break;
			case 3:
				return "Apr";
				break;
			case 4:
				return "May";
				break;
			case 5:
				return "Jun";
				break;
			case 6:
				return "Jul";
				break;
			case 7:
				return "Aug";
				break;
			case 8:
				return "Sep";
				break;
			case 9:
				return "Oct";
				break;
			case 10:
				return "Nov";
				break;
			case 11:
				return "Dec";
				break;
		}
	}
	
	for (var feed in this.JSONDataFeed){
	  
    if (parseInt(feed) >= 0){
      var newsListItems = "";
      var newsList = "reuters-feed-news-items";
      var timeStamp = "reuters-feed-timestamp";
			var dtTimeStamp = new Date(this.JSONDataFeed[parseInt(feed)].timeStamp.substring(0,this.JSONDataFeed[parseInt(feed)].timeStamp.indexOf(" ")).replace(/\-/g,"/"));
			var timeStampHours = this.JSONDataFeed[parseInt(feed)].timeStamp.substring(this.JSONDataFeed[parseInt(feed)].timeStamp.indexOf(" "),this.JSONDataFeed[parseInt(feed)].timeStamp.lastIndexOf(":"));
			var timeZone = this.JSONDataFeed[parseInt(feed)].timeStamp.substring(this.JSONDataFeed[parseInt(feed)].timeStamp.lastIndexOf(" "),this.JSONDataFeed[parseInt(feed)].timeStamp.length);
			var TIMEZONE = (timeZone.indexOf("7")!=-1) ? "PDT" : "PST"; 
			
      /*if (parseInt(feed) == 1){
        timeStamp = "bioonc-feed-timestamp";
        newsList = "bioonc-feed-news-items";
      }*/
      for (var newsItem in this.JSONDataFeed[0].newsItems){
        if (parseInt(newsItem)>=0 && parseInt(newsItem)<=4){
          newsListItems += "<li><p><a href=\""+sitePath+this.JSONDataFeed[parseInt(feed)].newsItems[parseInt(newsItem)].path+"\">"+Utf8.decode(this.JSONDataFeed[parseInt(feed)].newsItems[parseInt(newsItem)].title)+"</a><span>&nbsp;</span></p></li>";

        }
      }
      //jq$(timeStamp).innerHTML = _getMonthString(dtTimeStamp.getMonth())+" "+dtTimeStamp.getDate()+", "+dtTimeStamp.getFullYear()+", "+timeStampHours+" "+TIMEZONE;

      jq$("#bioonc-feed-news-items").append(newsListItems);  
    }
  }
	
	var arNewsFeedBody = $('news-feed').getElementsByClassName('news-body');
	arNewsFeedBody[0].setStyle({height: "320px"});
}

/**
 *  Method to populate each feed with its timestamp and news items.
 */
biooncology.NewsFeed.prototype.buildNewsItems = function(feed){
  var tempJSONData;
  var ni = new biooncology.NewsItem();
  
  for (var item in feed.items){
    if ((feed.items[item].nodePath && feed.items[item].headline) !== undefined){
      tempJSONData = "{\"title\": "+feed.items[item].headline.toJSON()+", \"path\": \""+this.newsDisplayURI+feed.items[item].nodePath+"\"}";
      ni.newsItems[parseInt(item)] = tempJSONData.evalJSON();
    }
  }
  ni.timeStamp = feed.updateTime;
  return ni;
};

/**
 *  Method to get the JSON data.
 */
biooncology.NewsFeed.prototype.JSONData = function(){
  try {
    tempResponse = new Ajax.Request((this.newsSourceURI), {
      method: 'get',
      onSuccess: function(transport) {
        var tempResponse = transport.responseText.evalJSON();        
        for (var feedInfo in tempResponse){ 
          this.JSONDataFeed.push(this.buildNewsItems(tempResponse[feedInfo]));
        }
        this.create();
        jQuery(document).bind('newsLoaded', function() {
          googleAnalytics.trackNews();
        });
        jQuery(document).trigger('newsLoaded');
        jQuery(document).unbind('newsLoaded');
      }.bind(this)
    });
  }
  catch(e){
    console.error(e);
  }
};

