/*
 * FS Javascript Library
 *
 * Copyright (c) 2009 CFP Group www.cfp.co.uk
 * Author: HdotNET
 *
 */



// the ajax feed object.
// usage:
// objname = new FS_ajaxFeed(['htmlarea_id1','htmlarea_id2'],"/path/to/ajax/feed/",milliseconds);
// objname.loadAjaxData();
function FS_ajaxFeed(ajax_areas,ajax_url,ajax_refresh)
{
	this.ajax_areas=ajax_areas; // array of id's for the page areas containing id nodes to update with data
	this.ajax_url=ajax_url; // the ajax xml output url
	this.ajax_refresh=ajax_refresh;  // num of milliseconds to wait until refreshing the data
	//object load data method, peforms the ajax request to ajax_url
	this.loadAjaxData = function(){
		var get_url = false;
		var feed = this;
		if(this.ajax_areas.length){
			for(g=0;g<this.ajax_areas.length;g++)
			{
				if($('#'+this.ajax_areas[g]).length){
					get_url = true;
				}
			}
		}
		if(get_url)
		{
			// grab the data from our xml feed
			$.get(this.ajax_url, function(data)
			{
				feed.parseAjaxData(data); 
				if(typeof feed.debug == 'function') {
					// debug function exists, so we can now call it
					feed.debug();
				}				
				if(feed.ajax_refresh != null && feed.ajax_refresh > 0)
				{
					feed.refreshAjaxData(feed.ajax_refresh); // do it all again in whateer milliseconds
				}
				else
				{
					// just destroy the object
					feed = null;
				}
			});
		}
	};


	//object parse data method, iterates over xml nodes replacing items with the same id.
	this.parseAjaxData = function(data){
		items = $('ajax',data).children();
		for(c=0;c<items.length;c++){
			node_name = items[c].nodeName;
			node_value = $(items[c]).text();                        
			node_class = $(items[c]).attr("class");
			if(node_value.length > 0){
				$("#"+node_name).html(this.trim(node_value));
				if ( node_class != null ) {
					$("#"+node_name).addClass( node_class );
				}
			}
		}	
	};
	//object timeout method, ensures that only the relevant object is refreshed.
	this.refreshAjaxData = function (ms){
		var _self = this;
		setTimeout(function(ms){
		_self.loadAjaxData();
		}, ms);
	};
	this.trim = function(str)
	{
		return str.replace(/^\s+|\s+$/g, '');		
	}
	this.getTimeNow = function ()
	{
		var now = new Date();
		var hours = now.getHours();
		var minutes = now.getMinutes();
		var seconds = now.getSeconds();
		str = '';
		if (minutes < 10)
		{
			minutes = "0" + minutes;
		}
		if (seconds < 10)
		{
			seconds = "0" + seconds;
		}
		str = hours + ":" + minutes + ":" +seconds+" ";
		if(hours > 11)
		{
			str = str + "PM";
		} else {
			str = str + "AM";
		}
		return str;
	}
}
