/**************************************************************************************************************************************************/	

function log( s ){
/*	var logdiv = document.getElementById("logdiv");						
	logdiv.innerHTML += s + "<br>";*/
}
function clearLog(){
	/*var logdiv = document.getElementById("logdiv");						
	logdiv.innerHTML = '';*/
}

function enumrate( o ){
	forEach (o, function(object) {
		forEach (object, log); 
	});		
}


Array.prototype.contains = function( item ) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == item){
			return true;
		}
	}			
	return false;
};
Array.prototype.indexOf = function( item ) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] === item){
			return i;
		}
	}			
	return -1;
};

/**************************************************************************************************************************************************/

function FeedController( a_maxresults ){
	var self = this;
	this.items = new Array();
	this._requests = new Array();
	this._activerequests = new Array();
	this._historyI = 0;
	this._timeFrom = 0;		
	this._fid = null;
	this._maxresults = a_maxresults || 100;
}

FeedController.prototype.onCommStart = null;
FeedController.prototype.onCommComplete = null;
FeedController.prototype.onRequestChange = null;

FeedController.prototype.showAll = function(){
	if (this._fid != null){
		clearTimeout(this._fid);
		this._fid = null;
	}	
	var self = this;
	for (var i = this._requests.length-1; i>=0; i--){
		this._requests[i].setEnabled( true );
	}	
	
	if (this.onRequestChange != null){
		this.onRequestChange();
	}
	
	this._fid = setTimeout(function() { self.restart(); }, 2000);		
}

FeedController.prototype.show = function( rq ){
	if (this._fid != null){
		clearTimeout(this._fid);
		this._fid = null;
	}	
	var self = this;
	for (var i = this._requests.length-1; i>=0; i--){
		this._requests[i].setEnabled( rq == this._requests[i] );
	}	
	
	if (this.onRequestChange != null){
		this.onRequestChange();
	}
	
	this._fid = setTimeout(function() { self.restart(); }, 2000);		
}

FeedController.prototype.toggle = function( rq ){
	if (this._fid != null){
		clearTimeout(this._fid);
		this._fid = null;
	}	
	var self = this;
	
	rq.setEnabled( ! rq.isEnabled() );
	
	var alldisabled = true;
	
	for (var i = this._requests.length-1; i>=0; i--){
		if (this._requests[i].isEnabled()){
			alldisabled = false;
			break;
		}
	}	
	
	if (alldisabled){
		rq.setEnabled(true);
	}
	
	if (this.onRequestChange != null){
		this.onRequestChange();
	}
	
	this._fid = setTimeout(function() { self.restart(); }, 2000);		
}

FeedController.prototype.delayedRestart = function( nw ){
	if (this._fid != null){
		clearTimeout(this._fid);
		this._fid = null;
	}	
	var self = this;
	this._fid = setTimeout(function() { self.restart(); }, 2000);		
}

FeedController.prototype.restart = function(){
	log("FeedController restart "+this._requests.length);
	this.clear();
	this._activerequests = new Array();
	this._historyI = 0;	
	
	if (this.onCommStart != null){
		this.onCommStart();
	}
		
	var numactive = 0;
	for (var i = this._requests.length-1; i>=0; i--){	
		if (this._requests[i].isEnabled()){
			numactive++;
		}
	}

	for (var i = this._requests.length-1; i>=0; i--){	
		if (this._requests[i].isEnabled()){
			this._activerequests.push( this._requests[i] );
			this._requests[i].init( Math.floor(this._maxresults/numactive) );
		}
	}
}	

FeedController.prototype.update = function( a_ignoreActive ){		
	this.clear();	
	if (a_ignoreActive == true){		
		this._activerequests = new Array();		
	} else {	
		if (this._activerequests.length > 0){
			return;
		}	
	}
	
	if (this.onCommStart != null){
		this.onCommStart();
	}	
	
	for (var i = this._requests.length-1; i>=0; i--){
		if (this._requests[i].isEnabled()){
			this._requests[i].update();
		}
	}
}

FeedController.prototype.next = function(){		
	if (this.gotNext()){
		this.clear();
		this._activerequests = new Array();
		this._historyI++;
		
		if (this.onCommStart != null){
			this.onCommStart();
		}
		
		for (var i = this._requests.length-1; i>=0; i--){
			if (this._requests[i].isEnabled() && this._requests[i].gotMorePages()){
				this._activerequests.push( this._requests[i] );
				this._requests[i].next();
			}
		}
	}
}

FeedController.prototype.previous = function(){		
	if (this.gotPrevious()){
		this.clear();
		this._activerequests = new Array();
		this._historyI--;
		
		if (this.onCommStart != null){
			this.onCommStart();
		}
		
		for (var i = this._requests.length-1; i>=0; i--){
			if (this._requests[i].isEnabled()){
				this._activerequests.push( this._requests[i] );
				this._requests[i].previous();
			}
		}
	}
}

FeedController.prototype.gotNext = function(){		
	var result = false;
	for (var i = this._requests.length-1; i>=0; i--){
		if (this._requests[i].isEnabled() && this._requests[i].gotMorePages()){
			result = true;
			break;			
		}
	}
	return result;
}

FeedController.prototype.gotPrevious = function(){		
	return (this._historyI > 0);	
}

FeedController.prototype.clear = function(){		
	this._activerequests = new Array();
	for (var i=this.items.length-1; i>=0; i--){			
		this.items[i].destroy();
		this.items.splice(i,1);
	}
}
	
FeedController.prototype.addRequest = function( fq ){	
	var self = this;
	if (!this._requests.contains(fq)){					
		fq.setResponseCallback( function(param){ self.onRequestResponse( param ); } );			
		//fq.setFilter( this._filter );		
		this._requests.push( fq );				
		return true;
	} else {
		return false;
	}		
}

FeedController.prototype.removeRequest = function( fq ){	
	if (this._requests.indexOf(fq) >= 0){	
		if (this._activerequests.indexOf( fq ) >= 0){
			this._activerequests.splice(this._activerequests.indexOf(fq), 1);
		}	
		this._requests.splice(this._requests.indexOf(fq), 1);
		for (var i=this.items.length-1; i>=0; i--){			
			for (var j=0; j<fq.items.length; j++){					
				if (this.items[i].data.id == fq.items[j].id){
					this.items[i].destroy();
					this.items.splice(i,1);
					break;							
				}
			}
		}
		fq.destroy();						
		return true;
	} else {
		return false;
	}
	this.render();
}

FeedController.prototype.onRequestResponse = function( fq ){
	log("onRequestResponse:"+fq.items.length+" "+this._activerequests.length+" "+this._activerequests.indexOf(fq));						
	
	if (this._activerequests.indexOf( fq ) >= 0){
	
		this._activerequests.splice(this._activerequests.indexOf(fq), 1);
		
		var skipped = 0;
		for (var j=0; j<fq.items.length; j++){
			var newitem = true;
			for (var i=0; i<this.items.length; i++){
				if (this.items[i].data.id == fq.items[j].id){
					newitem = false;
					break;
				}
			}
			
			if (newitem){
				//this.items.push( new fq._renderer( fq.items[j], fq ) );				
			} else {
				skipped++;
			}
		}

		this.render();		

		if (this._activerequests.length == 0){
			if (this.onCommComplete != null){
				this.onCommComplete();
			}
		}
			
	} else {
	
		log("not in activerequests");
		
	}
}

FeedController.prototype.render = function(){
	for (var i=0; i<this.items.length; i++){
		this.items[i].hide();
	}
	
	this.items.sort( FeedDisplayItemSort );

	for (var i=0; i<this.items.length; i++){
		this.items[i].show();
	}
}

FeedController.prototype.destroy = function(){
	clearInterval(this._iid);		
	clearInterval(this._fid);		
	for (var i = this._requests.length-1; i>=0; i--){
		this.removeRequest(this._requests[i]);
	}		
}
/**************************************************************************************************************************************************/

function FeedRequest( a_url, a_renderer ){		
	var self = this;
	this._url = a_url;
	this._renderer = a_renderer;
	this._retries = 0;
	this._maxRetries = 5;
	this._timeLow = 0;
	this._timeHigh = 0;
	this._req = 0;		
	this._numitems = 10;				
	this._feed = null;
	this._error = false;
	this._errorMessage = '';
	this._busy = false;
	this._responseCallback = null;
	this._history = new Array();
	this._history.push('');
	this._historyI = 0;			
	this.items = new Array();	
	this._enabled = true;
}

FeedRequest.prototype.init = function( a_num ){
	this._numitems = a_num || 5;	
	this._history = new Array();
	this._history.push('');
	this._historyI = 0;		
	this._retries = 0;
	this._send();
}

FeedRequest.prototype.update = function(){
	this._send();
}

FeedRequest.prototype.gotMorePages = function(){
	return (this._historyI < this._history.length-1);
}

FeedRequest.prototype.next = function(){
	if (this._historyI < this._history.length-1){
		this._historyI++;
		this._send();
	}
}

FeedRequest.prototype.previous = function(){
	if (this._historyI > 0 && this._history.length){
		this._historyI--;
		this._send();
	}
}

FeedRequest.prototype._retry = function(){
	log("----"+"RETRY ");
	this._retries++
	if (this._retries <= this._maxRetries){
		this._send();
	}
}

FeedRequest.prototype.setEnabled = function( a_value ){
	this._enabled = a_value;
	if (!a_value && this._feed != null){
		this.onResponse({error:1}, this._req);
	}
}
FeedRequest.prototype.isEnabled = function(){
	return this._enabled;
}
FeedRequest.prototype._send = function(){		
	if (this._rid != null ) {
		clearTimeout( this._rid );
		this._rid = null;
	}	
	
	var self = this;				
	
	this._req++;		
	
	var reqnum = this._req;

	this._feed = null;
	
	if (!this._enabled){
		this.onResponse({error:1}, reqnum);
	}

	var url = this._url;
	
	this._feed = new google.feeds.Feed( url );
	
	this._feed.setNumEntries( this._numitems );	
	
	this._feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
	
	this._feed.load( function( result ){ self.onResponse( result, reqnum ); } );
	
	this._rid = setTimeout(function() { self._retry(); }, 10000);
	
	this._busy = true;	
}

FeedRequest.prototype.onResponse = function ( result, reqnum ) {		
	log("----"+"RESPONSE REQ:"+this._req+" SYNC:"+(this._req == reqnum));
	var self = this;
	
	if (this._req == reqnum){
		
		this._error = (result.error) ? true : false;
	
		this.items = new Array();
		
		
		if (!this._error){
			
			clearTimeout( this._rid );
			
			this._rid = null;
			
			this._retries = 0;
			
			var entries = result.feed.entries;			
			
			for (var i = 0; i<entries.length; i++){
			
				this.items.push( new this._renderer( entries[i], this ) );
				
			}
						
		} else {
		
			log("----"+"ERROR loading "+this._url + "?n="+this._numitems);
			return;
			
		}
		
		this._busy = false;
		this._feed = null;
		
		if (this._responseCallback != null){
			this._responseCallback( this );
		}
		
	}
	
}

FeedRequest.prototype.setResponseCallback = function( f ){
	this._responseCallback = f;
}

FeedRequest.prototype.destroy = function(){
	log("----"+"DESTROY ");
	if(this._rid != null) {
		clearTimeout( this._rid );
		this._rid = null;
	}
	this._responseCallback = null;
	this._busy = false;
	this._feed = null;
	//this._filter = null;
	this._items = null;
	this._history = null;
}
/**************************************************************************************************************************************************/


/**************************************************************************************************************************************************/

function FeedDisplayItemSort( a, b ){
	return b.data.timestamp - a.data.timestamp;
}

/**************************************************************************************************************************************************/


var glNews;
var ytPlaylist;
var stcNews
var stcComments;

var plfc;
var glfc;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function PlayListRenderer( data, request ){		
	this.request = request;
	this.data = data;
	this.container = document.getElementById('feed2');
	this.obj = document.createElement("li");	

	var title = document.createElement("div");	
		title.className = 'playlistTitle';	
		title.innerHTML = data.title;
	this.obj.appendChild( title );
	
	var patt = /\?v=(\w{11})\&?/i 
	var vid = unescape(data.link).match(patt)[1];

	var video = document.createElement("div");	
		video.className = 'playlistVideo';	
		video.setAttribute('id', 'vid'+vid);		
		video.innerHTML = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width= \"200\" height=\"200\"><param name=\"movie\" value=\"http://www.youtube.com/v/"+vid+"&autoplay=0&rel=0&fs=1&color1=0x000000&color2=0x000000&border=0&loop=0\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/"+vid+"&autoplay=0&rel=0&fs=1&color1=0x000000&color2=0x000000&border=0&loop=0\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"200\" height=\"200\"></embed></object>";
	
	this.obj.appendChild( video );	
		
	var content = document.createElement("div");	
		content.className = 'playlistContent';	
		content.innerHTML = data.content;
	this.obj.appendChild( content );
			
	this.show();	
}

PlayListRenderer.prototype.hide = function(){		
	try {
		this.container.removeChild( this.obj );
	} catch (e){}
}

PlayListRenderer.prototype.show = function(){
	try {
		this.container.appendChild( this.obj );
	} catch (e){}
}

PlayListRenderer.prototype.destroy = function(){
	this.hide();
	this.container = null;
	this.request = null;
	this.data = null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GoogleNewsRenderer( data, request ){		
	this.request = request;
	this.data = data;
	this.container = document.getElementById('feed1');
	this.obj = document.createElement("li");	

	var title = document.createElement("div");	
		title.className = 'newsTitleG';	
		title.innerHTML = "<a href=\""+data.link+"\" target=\"_blank\" >"+data.title+"</a>";
	this.obj.appendChild( title );
	
	var content = document.createElement("div");	
		content.className = 'newsContentG';	
		content.innerHTML = data.content;
	this.obj.appendChild( content );
			
	this.show();
}

GoogleNewsRenderer.prototype.hide = function(){		
	try {
		this.container.removeChild( this.obj );
	} catch (e){}
}

GoogleNewsRenderer.prototype.show = function(){
	try {
		this.container.appendChild( this.obj );
	} catch (e){}
}

GoogleNewsRenderer.prototype.destroy = function(){
	this.hide();
	this.container = null;
	this.request = null;
	this.data = null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function TotMomNewsRenderer( data, request ){		
	this.request = request;
	this.data = data;
	this.container = document.getElementById('feed3');
	this.obj = document.createElement("li");	

	var title = document.createElement("div");	
		title.className = 'newsTitleT';	
		title.innerHTML = data.title;
	this.obj.appendChild( title );
	
	var content = document.createElement("div");	
		content.className = 'newsContentT';	
		
		var cnt = data.content;
		
		cnt = cnt.replace(/<a [^>]+>Permalink<\/a>/, '');
		
		content.innerHTML = cnt;
	
	this.obj.appendChild( content );
			
	this.show();
}

TotMomNewsRenderer.prototype.hide = function(){		
	try {
		this.container.removeChild( this.obj );
	} catch (e){}
}

TotMomNewsRenderer.prototype.show = function(){
	try {
		this.container.appendChild( this.obj );
	} catch (e){}
}

TotMomNewsRenderer.prototype.destroy = function(){
	this.hide();
	this.container = null;
	this.request = null;
	this.data = null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function initialize(){

	plfc = new FeedController(30);							
	plfc.onCommStart = function(){
	}
	plfc.onRequestChange = function(){
	}
	plfc.onCommComplete = function(){	
	}
	plfc.addRequest( ytPlaylist = new FeedRequest( "http://www.dataport.com.au/stc/stc0011/playlist.php", PlayListRenderer ) );
	plfc.restart();		

	
	glfc = new FeedController(30);							
	glfc.onCommStart = function(){
	}
	glfc.onRequestChange = function(){
	}
	glfc.onCommComplete = function(){
		$('#feed2 img').each(function() {
			var maxWidth = 200; // Max width for the image        	
			var width = $(this).width();	
			var height = $(this).height();			
			if(width > maxWidth){
				var ratio = maxWidth / width;   // get ratio for scaling image
				$(this).css("width", maxWidth); // Set new width
				$(this).css("height", height * ratio);  // Scale height based on ratio            
			}
		});
		$('#feed2 embed').each(function() {
			var maxWidth = 200; // Max width for the image        	
			var width = $(this).width();	
			var height = $(this).height();			
			if(width > maxWidth){
				var ratio = maxWidth / width;   // get ratio for scaling image
				$(this).css("width", maxWidth); // Set new width
				$(this).css("height", height * ratio);  // Scale height based on ratio            
			}
		});
	}
	glfc.addRequest( ytPlaylist = new FeedRequest( "http://www.google.com/reader/public/atom/user/03757594379073504124/state/com.google/broadcast", GoogleNewsRenderer ) );
	glfc.restart();		
	

	tmfc = new FeedController(30);							
	tmfc.onCommStart = function(){
	}
	tmfc.onRequestChange = function(){
	}
	tmfc.onCommComplete = function(){
		$('#feed3 img').each(function() {
			var maxWidth = 200; // Max width for the image        	
			var width = $(this).width();	
			var height = $(this).height();			
			if(width > maxWidth){
				var ratio = maxWidth / width;   // get ratio for scaling image
				$(this).css("width", maxWidth); // Set new width
				$(this).css("height", height * ratio);  // Scale height based on ratio            
			}
		});
		$('#feed3 embed').each(function() {
			var maxWidth = 200; // Max width for the image        	
			var width = $(this).width();	
			var height = $(this).height();			
			if(width > maxWidth){
				var ratio = maxWidth / width;   // get ratio for scaling image
				$(this).css("width", maxWidth); // Set new width
				$(this).css("height", height * ratio);  // Scale height based on ratio            
			}
		});
	}
	tmfc.addRequest( stcNews = new FeedRequest( "http://stctotmom.posterous.com/rss.xml", TotMomNewsRenderer ) );
	tmfc.restart();		
	
	$('#commentinput').focus(function(){
		$('#commentinput').css("height", 100);
	});
	
	$('#commentinput').keyup(function(){
        var max = parseInt($(this).attr('maxlength'));
        if($(this).val().length > max){
            $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        } 
    });
	updateComments();
}

function updateComments(){
	$.get("getcomments.php", {}, function(response){		
		$('#feed4').html( response );
	});
}

var reporting = false;
var reports = new Array();

function reportComment( id ){
	if (reporting || reports[id]) return;
	
	if (confirm("Are you sure?")){
		var cid = id;
		reporting = true;
		$.ajax({
			  url: "reportcomment.php",
			  global: false,
			  type: "POST",
			  data: {
					cid : cid
			  },
			  error: function(XMLHttpRequest, textStatus, errorThrown){			
				reporting = false;
				alert('There was an error processing your request, please try again.');			
			  },
			  success: function(response){
				reports[cid] = true;
				reporting = false;
				if (response == 'ok'){
					alert('Report has been submitted.');
				} else {
					alert('There was an error processing your request, please try again.');			
				}			
			  }
		   }
		);	
	}
}

var posting = false;

function addComment(){
	if (posting) return;
	posting = true;
	$.ajax({
		  url: "postcomment.php",
		  global: false,
		  type: "POST",
		  data: {
				comment : document.getElementById('commentinput').value, 
				location : document.getElementById('locationinput').value,
				name : document.getElementById('nameinput').value
		  },
		  error: function(XMLHttpRequest, textStatus, errorThrown){
			alert('There was an error processing your request, please try again.');
			posting = false;
		  },
		  success: function(response){			
			posting = false;
			 if (response == 'ok'){				
				$('#commentinput').value = '';
				document.getElementById('commentinput').value = '';
				updateComments();
			} else {
				alert(response);
			}
		  }
	   }
	);		
}

var imagedir = 1;
var lastindex;
function changeBackgroundImage(interval,index){

	var numimages = $("#animationcontainer > div").size()

	if (index == null){
		index = 0;
	} else if (index >= numimages){
		index = numimages-2;
		imagedir = -1;
	} else if (index < 0 ){
		index = 1
		imagedir = 1;
	}
	
	$("#animationcontainer #img"+(index+1)).show();
	
	if (lastindex != null){
		$("#animationcontainer #img"+(lastindex+1)).hide();
	}
	
	lastindex = index;
	
	setTimeout("changeBackgroundImage("+interval+","+(index+imagedir)+")",interval);
}
