var isOnline = 0;

/*
 * utitlities
 *
 */
 
function getStringOfMaxLength( srcString, maxLength )
{
	if ( !srcString ) return "";
	if ( srcString.length <= maxLength ) return srcString;
	
	var parts = new Array();
	var	newStr = "";
	var tmpStr = "";
	var	index = 0;
	
	parts = srcString.split(' ');
	while ( newStr.length <= maxLength && index < parts.length )
	{
		tmpStr = parts[index];
		
		var	testStr = newStr + " " + tmpStr;
		if ( testStr.length > maxLength ) break;
		
		newStr = newStr + " " + tmpStr;
		
		index++;
	}
	
	if ( newStr != srcString ) return newStr + "[...]";
	return newStr;
}

function stripHTML(src)
{
	if ( !src ) return "";
	return getStringOfMaxLength( src.replace(/(<([^>]+)>)/ig,""), 300 );
}

/*
 * CWArticle
 *
 */
 
function CWArticle( parentFeed, xml, type )
{
	this.feedType						= type; // "atom", "rss", "none"
	this.feed 							= parentFeed;
	this.xml 							= xml;

	// functions
	this.getTitle						= _CWArticleGetTitle;
	this.getSummary						= _CWArticleGetSummary;
	this.getURL							= _CWArticleGetURL;
	this.getAuthor						= _CWArticleGetAuthor;
	this.getPublicationDate				= _CWArticleGetPubDate;
	
	var	pbdte = this.getPublicationDate();
	this._pubDate = Date.parse(pbdte);

}

function _CWArticleGetAuthor()
{
	if ( !this.xml ) return null;
	
	var	items = this.xml.childNodes;
	for ( var i = 0; i < items.length; i++ )
	{
		var	item = items[i];
		if ( item.nodeName == "author" || 
			 item.nodeName == "dc:creator" )
		{
			
			if ( item.hasChildNodes )
				return stripHTML( item.childNodes[0].nodeValue ); 
		}
		
	}
	
	return null;
}

function _CWArticleGetPubDate()
{
	if ( !this.xml ) return null;
	
	var	items = this.xml.childNodes;
	for ( var i = 0; i < items.length; i++ )
	{
		var	item = items[i];
		if ( item.nodeName == "pubDate" || 
			 item.nodeName == "published" )
		{
			
			if ( item.hasChildNodes )
				return stripHTML( item.childNodes[0].nodeValue ); 
		}
		
	}
	
	return null;
}

function _CWArticleGetURL()
{
	if ( !this.xml ) return "";
	
	var	items = this.xml.getElementsByTagName("link");
	if ( items.length <= 0 ) return "";
	
	var	linkItem = items[0];
	
	if ( linkItem.hasAttribute("href") ) return linkItem.getAttribute("href");
	
	if ( linkItem.hasChildNodes ) 
		return linkItem.childNodes[0].nodeValue;

	return "";
}

function _CWArticleGetTitle()
{
	if ( !this.xml ) return "";
	
	var	items = this.xml.getElementsByTagName("title");
	if ( items.length <= 0 ) return "";
	
	var	titleItem = items[0];
	if ( titleItem.hasChildNodes ) return stripHTML( titleItem.childNodes[0].nodeValue );
	
	return "Untitled";
}

function _CWArticleGetSummary()
{

	if ( !this.xml ) return "No Summary";
	
	var	items = this.xml.getElementsByTagName("description");
	if ( items.length > 0 )
	{
		if ( items[0].hasChildNodes() )
			return stripHTML( items[0].childNodes[0].nodeValue );
	}
	

	// content encoded maybe
	// check for content encoded
	items = this.xml.childNodes;
	for ( var w = 0; w < items.length; w++ )
	{
		if ( items[w].nodeName == "content:encoded" )
		{
			var	contentEncodedNode = items[w];
			if ( contentEncodedNode.hasChildNodes )
			{
				var	cdataNode = contentEncodedNode.childNodes[0];
				return stripHTML( cdataNode.nodeValue );
				
			}
		} 
		else if ( items[w].nodeName == "atom:summary" )
		{
			var	summaryNode = items[w];
			if ( summaryNode.hasChildNodes )
			{
				var	textNode = summaryNode.childNodes[0];
				return stripHTML( textNode.nodeValue );
				
			}
		}
	}
	
	
	// mus be content from atom
	items = this.xml.getElementsByTagName("content");
	if ( items.length <= 0 ) return "";
	
	var	contentItem = items[0];
	var	outData = "";
	
	if ( contentItem.firstChild.nodeName == "#cdata-section" )
	{
		outData = contentItem.firstChild.nodeValue;
	}
	else
	{
		if ( contentItem.firstChild )
		{
			if ( contentItem.firstChild.nodeName == "#text" )
			{
				if ( contentItem.childNodes.length > 1 )
				{
								
					if ( contentItem.childNodes[1].nodeName == "#cdata-section" )
					{
						outData = contentItem.childNodes[1].nodeValue;
					}
					else
					{
						outData = contentItem.firstChild.nodeValue;
					}
				}
				else
				{
					outData = contentItem.firstChild.nodeValue;
				}
			}
			else
				outData = contentItem.firstChild.innerHTML;
		}
	}

	return stripHTML(outData);
}


/*
 * CWFeed
 *
 */

function CWFeed( address, beginLoadingCallback, endLoadingCallback )
{
	// properties
	this.isLoaded						= false;
	this.isLoading						= false;
	this.hasErrors						= false;
	this.url 							= address;
	this.articles 						= new Array();
	this.xml							= undefined;
	this.request						= new XMLHttpRequest();
	this.request.feed					= this;
	this.request.onreadystatechange		= _CWFeedXMLHTTPRequestOnReadyStateChange;
	this.feedType						= "none"; // "atom", "rss", "none"
	
	// callback
	this.beginCallback					= beginLoadingCallback;
	this.endCallback					= endLoadingCallback;
	
	// private functions
	this._CWFeedRequestStateDidChange	= _CWFeedRequestStateDidChange;
	this._CWFeedLoadingErrorDidOccur	= _CWFeedLoadingErrorDidOccur;
	this._CWFeedParsingErrorDidOccur	= _CWFeedParsingErrorDidOccur;
	
	this._CWFeedParseFeed				= _CWFeedParseFeed;
	this._CWFeedParseRSSFeed			= _CWFeedParseRSSFeed;
	this._CWFeedParseAtomFeed			= _CWFeedParseAtomFeed;
	
	// functions
	this.loadFeed						= CWFeedLoad;
	this.numberOfArticles				= CWFeedGetNumberOfArticles;
	this.articleAtIndex					= CWFeedGetArticleAtIndex;
	
	this.getTitle						= CWFeedGetTitle;
}

// internal
function _CWFeedXMLHTTPRequestOnReadyStateChange()
{
	
	if ( this.feed )
		this.feed._CWFeedRequestStateDidChange();
	else
		window.console.log( this.feed );
}

function _CWFeedLoadingErrorDidOccur()
{
	window.console.log( "_CWFeedLoadingErrorDidOccur" );
	this.hasErrors = true;
}

function _CWFeedParsingErrorDidOccur()
{
	window.console.log( "_CWFeedParsingErrorDidOccur" );
	this.hasErrors = true;
}

function _CWFeedSortFunction(a,b)
{
	if ( a._pubDate == b._pubDate ) return 0;
	if ( a._pubDate > b._pubDate ) return -1;
	if ( a._pubDate < b._pubDate ) return 1;
	return 0;
}

function _CWFeedParseRSSFeed()
{
	this.feedType = "rss";
	
	//chek for channels
	var	channels = this.xml.getElementsByTagName("channel");
	if ( channels.length > 0 ) this.xml = channels[0];
	
	// get articles
	var	items = this.xml.getElementsByTagName("item");
	for ( var i = 0; i < items.length; i++ )
	{
		this.articles.push( new CWArticle(this,items[i],this.feedType) );
	}
	
	this.articles.sort(_CWFeedSortFunction);
}

function _CWFeedParseAtomFeed()
{
	this.feedType = "atom";
	
	// get articles
	var	items = this.xml.getElementsByTagName("entry");
	for ( var i = 0; i < items.length; i++ )
	{
		this.articles.push( new CWArticle(this,items[i],this.feedType) );
	}
	
	this.articles.sort(_CWFeedSortFunction);
}

function _CWFeedParseFeed()
{
	if ( this.xml.nodeName == "rss" )
	{
		this._CWFeedParseRSSFeed();
	}
	else if ( this.xml.nodeName == "feed" )
	{
		this._CWFeedParseAtomFeed();
	}
	else
	{
		this._CWFeedParsingErrorDidOccur();
	}
}

function _CWFeedRequestStateDidChange()
{
	if ( this.request.readyState == 4 )
	{
		this.isLoaded = true;
		this.isLoading = false;
		
		try
		{
			if ( this.request.responseXML )
			{
				this.xml = this.request.responseXML.documentElement;
				this._CWFeedParseFeed();
			}
			else if ( this.request.responseText )
			{
				parser = new DOMParser();
    			var xmlDoc = parser.parseFromString( this.request.responseText,"text/xml" );
    			if ( !xmlDoc )
					this._CWFeedLoadingErrorDidOccur();
				else
				{
					this.xml = xmlDoc.documentElement;
					this._CWFeedParseFeed();
				}
			}
			else
			{
				this._CWFeedLoadingErrorDidOccur();
			}
		}
		catch(err)
		{
			window.console.log(err);
			this._CWFeedLoadingErrorDidOccur();
		}
		if ( this.endCallback ) this.endCallback(this);
	}
}

// function
function CWFeedLoad()
{
	if ( this.isLoading == true ) return;
	
	this.isLoaded = false;
	this.isLoading = true;
	
	if ( isOnline )
	{
		var	feederPage = "feeder.php?feed=" + this.url;
		this.request.open("GET",feederPage,true);
	}
	else
	{
		this.request.open("GET",this.url,true);
	}

	this.request.send(null);
	
	if ( this.beginCallback ) this.beginCallback(this);
}

function CWFeedGetNumberOfArticles()
{
	if ( this.isLoaded == false || this.isLoading == true ) return 0;
	return this.articles.length;
}

function CWFeedGetArticleAtIndex(index)
{
	if ( this.isLoaded == false || this.isLoading == true ) return undefined;
	return this.articles[index];
}

function CWFeedGetTitle()
{
	if ( this.isLoaded == false || this.isLoading == true ) return "";
	if ( this.xml )
	{
		var	titleItems = this.xml.getElementsByTagName("title");
		if ( titleItems.length > 0 )
		{
			return titleItems[0].childNodes[0].nodeValue;
		}
	}
	return "";
}



