/*
 * Copyright 2006 Servelots Infotech Pvt. Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at:
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

/**
   This little Javascript reads the RSS feeds and displays them in a
   reasonably stylish form.
   Author : Srinivasa Raghavan & Surekha Sastry
**/

/* The Symbolic Constants that represent the xmlHttpResponse state */
var READY_STATE_UNINITIALIZED = 0;
var READY_STATE_LOADING = 1;
var READY_STATE_LOADED = 2;
var READY_STATE_INTERACTIVE = 3;
var READY_STATE_COMPLETE = 4;

/* The xmlHttpRequest object/variable */
var xmlHttpRequest = null;

/* This variable holds the feedConfigURL value */
var feedConfigURL = null;

/* This variable holds the feedURL value */
var feedURL = null;

/* This variable holds the currentFeedConfigItem among the number of
   feedConfig Items configured */
var curFeedConfigItem = new Array();

/* This variable holds the xmlFeedConfigTree returned by the xmlHttpResponse */
var feedConfigTree = null;

/* This variable holds the xmlFeedTree returned by the xmlHttpResponse */
var feedTree = null;

/* This variable is used to display/hide the "What's New?" block in
   the page. It is displayed if there are any feds at all(in which
   case this variable's value will be true), otherwise it is hidden(in
   which case this variable's value will be false) */
var rssFeedsExists = true;

/* Whether or not to show all the external feeds */
var externalFeedsShowAll = false;

/*Identify for which rss feed category selection is done */
var categoryNameField = null;
var selCatId = null;

var xmlreqs = new Array();

function CXMLReq(type, xmlhttp) 
{
  this.type = type;
  this.xmlhttp = xmlhttp; 
} 

var FEEDUrl = new Array();

var temp = null;

/** Returns the xmlHttpRequest object **/
function getXmlHttpRequest()
{
  if (window.XMLHttpRequest)
    {
      xmlHttpRequest = new XMLHttpRequest();
    }
  else if (typeof ActiveXObject != "undefined")
    {
      xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
  return xmlHttpRequest;
}

/** Returns the URL with which the current community is being accessed */
function getRequestURL()
{
  var url = new String(document.location);
  url = url.substring(0, url.indexOf("servlet"));
  return url;
}

/** This function is called by the 'onLoad' property of the body tag **/
function getFeeds(domainId, userAccessLevel)
{
  var feedsElement = document.getElementById("feeds");
  // Do all these RSS stuff only if we are in the homepage.  Only in
  // the home page the div with id feeds exists. This is the container
  // to display the rss feeds.
  if (feedsElement != null)
    {
      baseURL = getRequestURL() + "domain/" + domainId + "/";
      feedURL = baseURL + "xml/rss/" + domainId + "_" + userAccessLevel + ".xml";
      feedConfigURL = baseURL + "feedConfig.xml";
      sendHttpRequest(feedConfigURL);
    }
}


/** This function calls the 'url' using the method passed and calls
    'readyStateChangeCallback' in response **/
function sendHttpRequest(url, params, httpMethod)
{
  if (httpMethod == null)
    {
      httpMethod = "GET";
    }
  xmlHttpRequest = getXmlHttpRequest();
  if (xmlHttpRequest != null)
    {
      xmlHttpRequest.onreadystatechange = readyStateChangeCallback;
      xmlHttpRequest.open(httpMethod, url, true);
      xmlHttpRequest.setRequestHeader("Content-Type", "text/xml");
      xmlHttpRequest.send(params);
    }
}


/** This function is called in response to the xmlHttpRequest called
    in sendHttpRequest. This function checks if the RSS Feeds is
    configured and acts accordingly **/
function readyStateChangeCallback()
{
  var readyState = xmlHttpRequest.readyState;
  var data = null;
  if (readyState == READY_STATE_COMPLETE)
    {
      data = xmlHttpRequest.responseXML;
      if (data == null) // RSS Feeds are not configured
	{

	  rssFeedsExists = false;
	  if (!rssFeedsExists)
	    {
	      var element = document.getElementById("feeds");
	      element.style.display='none';
	    }
	}
      else
	{
	  feedConfigTree = data;
          readRssFeeds();
	}
    }
}

/** This function reads the RSS Feed from the feedURL and calls filterFeeds **/
function readRssFeeds()
{
  var xmlHttpRequest = getXmlHttpRequest();
  xmlHttpRequest.onreadystatechange = filterFeeds;
  xmlHttpRequest.open("GET", feedURL , true);
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml");
  xmlHttpRequest.send(null);   
}


/** Filters the feeds based on the config file if feeds exists **/
function filterFeeds()
{
  var readyState = xmlHttpRequest.readyState;
  var data = null;
  if (readyState == READY_STATE_COMPLETE)
    {
      data = xmlHttpRequest.responseXML;
      if (data == null)
	{

	  var message = "The Internal RSS Feeds are not generated for this Domain. Contact the Domain Administrator!";
	  setStatus(message, "IntExtFeeds");
	}
      else 
	{
	  feedTree = data;
	  displayExternalFeeds();
	}
      displayInternalFeeds(null, false);
    }
}

/** Process the internal feeds and calls printFeeds to display them. **/
function displayInternalFeeds(categoryName, showAll)
{
  var feedConfigItems = feedConfigTree.getElementsByTagName("feedConfig");
  var feedItems = feedTree.getElementsByTagName("item");
  var filteredFeeds = null;
  var content = "";
  var breakFlag = false;
  var externalFeedConfig = new Array();

  for (var i=0;i<feedConfigItems.length;i++)
    {
      filteredFeeds = new Array();
      filteredFeeds['heading'] = feedConfigItems[i].getAttribute('feedHeading');
      var feedTitleElement = feedConfigItems[i].firstChild;
      // If the internal feed doesn't have any heading and title, then
      // dont apply this config.
      if (feedTitleElement == null && filteredFeeds['heading'] == "")
	{
	  continue;
	}
      filteredFeeds['title'] = feedTitleElement.data;
      filteredFeeds['categoryName'] = feedConfigItems[i].getAttribute("categoryName");
      var curCatFeeds = new Array();
      var curConfigFeedItem = feedConfigItems[i];
      if (curConfigFeedItem.getAttribute("type") == "external")
	{
	  continue;
	}
      if (categoryName != null && 
	  curConfigFeedItem.getAttribute("categoryName") != categoryName)
	{
	  continue;
	}
      var feedCount = parseInt(curConfigFeedItem.getAttribute("feedCount"));

      for(var j=0;j<feedItems.length;j++)
	{
	  /*if (curCatFeeds.length == feedCount && !showAll)
	    {
	    break;
	    }*/
	  var curFeedItem = feedItems[j];
	  var feedCategories = curFeedItem.getElementsByTagName("category");
	  for(var k=0;k<feedCategories.length;k++)
	    {
	      var curCat = feedCategories[k].firstChild.data;
	      if (curCat == curConfigFeedItem.getAttribute('categoryName'))
		{
		  curCatFeeds.push(curFeedItem);
		  break;
		}
	    }
	}
      if (showAll)
	{
	  feedCount = curCatFeeds.length;
	}
      filteredFeeds['feeds'] = curCatFeeds;
      printFeeds(filteredFeeds, showAll, "IntExtFeeds", curConfigFeedItem.getAttribute("categoryId"), feedCount);
    }
}


/** Process the external site feeds and calls printFeeds to display them. **/
function displayExternalFeeds(divId, FeedUrl, showAll)
{
  temp = "";
  externalFeedsShowAll = showAll;
  var externalFeedConfigItems = feedConfigTree.getElementsByTagName("feedConfig");
  for (var i=0;i<externalFeedConfigItems.length;i++)
    {

      var feedType = externalFeedConfigItems[i].getAttribute("type");
      if (feedType == "external")
	{
	  var containerElement = document.getElementById("IntExtFeeds");
	  var extDivIdName = externalFeedConfigItems[i].getAttribute("feedHeading");
	  if (document.getElementById(divId) == null)
	    {
	      var extDivId = document.createElement("div");
	      extDivId.setAttribute("id", extDivIdName);
	      extDivId.setAttribute("class", "internal");
	      containerElement.appendChild(extDivId);
	    }

	  if(typeof(FeedUrl) != "undefined" )
	    {
	      curFeedConfigItem = new Array();
	      FEEDUrl = new Array();
	      xmlreqs = new Array();
	    }
	  curFeedConfigItem.push(externalFeedConfigItems[i]);
	  if(typeof(divId) != "undefined")
	    {
	      if(externalFeedConfigItems[i].getAttribute("feedHeading") == divId)
		{
		  temp = "nloop";
		}
	    }
	  var xmlHttpRequest = getXmlHttpRequest();
	  if(typeof(FeedUrl) == "undefined" )
	    {
	      var feedUrl = externalFeedConfigItems[i].getAttribute("url");
	      FEEDUrl.push(feedUrl);
	    }
	  else
	    {
	      var feedUrl = FeedUrl;
	      FEEDUrl.push(feedUrl);
	    }

	  // If the external feed url is specified in the feed config file
	  // If it is not specified, it means that external feeds are not required.
	  if (feedUrl != null && feedUrl != "")
	    {
	      rssFeedsExists = true;

	      xmlHttpRequest.onreadystatechange = externalFeedCallBack;
	      xmlHttpRequest.open("GET", feedUrl , true);
	      xmlHttpRequest.setRequestHeader("Content-Type", "text/xml");
	      xmlHttpRequest.send(null);
	      var xmlreq = new CXMLReq('', xmlHttpRequest);
	      xmlreqs.push(xmlreq);
	      if(temp == "nloop")
		{
		  break;
		}
	    }
	}
      else if (feedType == "internal")
	{
	  var containerElement = document.getElementById("IntExtFeeds");
	  var intDivIdName = externalFeedConfigItems[i].getAttribute("categoryId");
	  intDivIdName = "rss_" + intDivIdName;
	  if (document.getElementById(intDivIdName) == null)
	    {
	      //extDivIdName = "rss_" + extDivIdName;
	      var intDivId = document.createElement("div");
	      intDivId.setAttribute("id", intDivIdName);
	      intDivId.setAttribute("class", "internal");
	      containerElement.appendChild(intDivId);
	    }
	}
    }
}

/** Callback function for external feeds **/
function externalFeedCallBack()
{
  var data = null;
  if (typeof(window['xmlreqs']) == "undefined")
    return;
  for (var s=0; s < xmlreqs.length; s++) 
    {
      var readyState = xmlreqs[s].xmlhttp.readyState;
      if(readyState == 4)
	{
	  if (xmlreqs[s].xmlhttp.status == 200 || xmlreqs[s].xmlhttp.status == 304) 
	    {
	      var data = xmlreqs[s].xmlhttp.responseXML;

	      // The feed is configured, but the external feed cache file is
	      // not generated for some reason. So, display a message.
	      if (data == null)
		{
		  var message = "There is a problem reading the External Feed cache file. Please make sure that the externalfeed is cached or contact your Domain Administrator for more details";
		  setStatus(message, "IntExtFeeds");
		}
	      else
		{
		  rssFeedsExists = true;
		  var externalFeedTree = data;
		  var feedInfo = new Array();
		  feedInfo['heading'] = curFeedConfigItem[s].getAttribute("feedHeading");
		  feedInfo['title'] = curFeedConfigItem[s].firstChild.data;

		  feedInfo['feedUrl'] = FEEDUrl[s];

		  var extFeedItems = externalFeedTree.getElementsByTagName("item");
		  feedInfo['feeds'] = extFeedItems;
		  var feedCount = curFeedConfigItem[s].getAttribute("feedCount");

		  if (externalFeedsShowAll)
		    {
		      feedCount = extFeedItems.length;
		    }
		  printFeeds(feedInfo, externalFeedsShowAll, "IntExtFeeds", null, feedCount);
		}
	    }
	  else 
	    {
	      // error
	    }
	}
    }
}

/** Displays the feeds (internal/external) as list items **/
function printFeeds(feeds, showAllFeeds, containerId, curCatId, feedCount)
{
  var containerElement = document.getElementById(containerId);
  var curCat = "";
  var curFeedsCatName = feeds['categoryName'];
  if (curCatId == null)
    {

      curCatId = feeds['heading'];

    }
  // we need to prefix 'rss_' because in blues skin the categories in
  // category tree will also have the same id.
  else
    {
      curCatId = "rss_" + curCatId;
    }
  if (document.getElementById(curCatId) == null)
    {
      curCat = document.createElement("div");
      curCat.setAttribute("id", curCatId);
      curCat.setAttribute("class", "internal");
      containerElement.appendChild(curCat);
    }

  if (feeds['heading'] != null && feeds['heading'] != "")
    {
      content = '<span class="heading">' + feeds['heading'] + '</span> <br/>';
    } 
  content += '<div align="left"><span class="caption">' + feeds['title'] + '</span></div>';

  var feedItems = feeds['feeds'];
  
  if (feedItems.length == 0)
    {
      content += ' <br/> <span class="nofeeds">[ No feed items in this category ] </span><br/>';
    }
  if (feedItems.length != 0)
    {

      var hrefLink = "";
      var moreLink = "";
        
      if (showAllFeeds)
	{
	  if (curCatId == feeds['heading'])
	    {
	      var url = feeds['feedUrl'];
	      hrefLink = "javascript:displayExternalFeeds('"+ curCatId;
	      hrefLink += "','"+ url;
	      hrefLink += "', false);";
	    }
	  else 
	    {
	      hrefLink = "javascript:displayInternalFeeds('" + curFeedsCatName;
	      hrefLink += "', false);";
	    }

	  //  moreLink = "<a class=\"more\" href=\"#" + curFeedsCatName +"\" onClick=\"" + hrefLink + "\"> Limit Feeds </a>";
	  moreLink = "<a class=\"more\" href=\"" + hrefLink + "\"> Limit Feeds </a>";
	}
      else 
	{
	  if (curCatId == feeds['heading'])
	    {
	      var url = feeds['feedUrl'];
	      hrefLink = "javascript:displayExternalFeeds('"+ curCatId;
	      hrefLink += "','"+ url;
	      hrefLink += "', true);";
	    }
	  else 
	    {
	      hrefLink = "javascript:displayInternalFeeds('" + curFeedsCatName;
	      hrefLink += "', true);";
	    }

	  //moreLink = "<a class=\"more\" href=\"#" + curFeedsCatName + "\" onClick=\"" + hrefLink + "\"> Show all </a>";
	  if(feedItems.length > feedCount)
	    {
	      moreLink = "<div position=\"relative\"><a class=\"more\" href=\"" + hrefLink + "\"> Show all </a></div>";
	    }
	  /*      if (feedItems.length < feedCount)
		  {
		  moreLink = "<a class=\"more nomorefeeds\" title=\"No more feeds are available\"> Show all </a>";
		  }*/
  
	}
        
      content += moreLink;
    }
  var totalFeeds = feedItems.length;
  if (feedCount != null && feedItems.length > feedCount)
    {
      totalFeeds = feedCount;
    }
  content += '<ul>';
  for (var n=0; n < totalFeeds; n++)
    {
      var itemTitle = feedItems[n].getElementsByTagName('title').item(0).firstChild.data + '  ';
      var itemLink = feedItems[n].getElementsByTagName('link').item(0).firstChild.data;
      try 
	{ 
	  var itemPubDate = '['+feedItems[n].getElementsByTagName('pubDate').item(0).firstChild.data+'] ';
	} 
      catch (e) 
	{ 
	  var itemPubDate = '';
	}
      try
	{
	  var author = 'by ' + feedItems[n].getElementsByTagName('creator').item(0).firstChild.data + ' ';
	}
      catch (e)
	{
	  var author = '';
	}
      itemTitle = '<span class="title">' + itemTitle + '</span>';
      itemLink = '<a class="link" href="' + itemLink + '">'+itemTitle+'</a>';
      itemPubDate = '<br/><span class="pubdate">' + itemPubDate + '</span>';
      author = '<span class="author">' + author + '</span>';
      content += '<li class="feedItem">';
      content += itemLink + author + itemPubDate;
      //<a class="link" href="'+itemLink+'">'+itemTitle+'</a>' +itemPubDate +'<br/>';
      try
	{

	  var itemDesc = feedItems[n].getElementsByTagName('description').item(0).firstChild.data;
	}
      catch (e)
	{
	  var itemDesc ='';
	}
      content +=  '</li>';
    }
  content += '</ul>';

  document.getElementById(curCatId).innerHTML = content;

  rssFeedsExists = true;
}

function setStatus(statusMsg, msgContainerId)
{
  var statusContainer = document.getElementById(msgContainerId);
  var classattr = statusContainer.getAttribute("class");
  classattr += " status show";
  var statusText = document.createTextNode(statusMsg);
  statusText.setAttribute("class",classattr);
  statusContainer.appendChild(statusText);
}

function selectCategory(form, feedId, CategoryNameField, j)
{
  var feedType = document.getElementById(feedId);

  if(feedType.type=='select-one')
    {
      var type = feedType.options[feedType.selectedIndex].value;
      if(type=="internal")
	{
	  var ID = "url"+j;
	  var temp = document.getElementById(ID);
	  temp.style.display="none";
	  rssCat = document.getElementById("rssCat").style.display="block";

	  var formElements = form.elements;
	  for(var i=0; i<formElements.length; i++)
	    {
	      if(formElements[i].type=='checkbox')
		{
		  formElements[i].checked=false;
		}
	    }
	  categoryNameField = CategoryNameField;
	  selCatId = "selectedNodeIds"+j;
	}
      else
	{
	  var ID = "category"+j;
	  var temp = document.getElementById(ID);
	  temp.style.display="none";
	  rssCat = document.getElementById("rssCat").style.display="none";
	}
    }
}

function selectedCategory(categoryName, categoryId)
{
  document.getElementById(categoryNameField).value=categoryName; 
  document.getElementById(selCatId).value=categoryId;
}



