var _viewer = null;

/*
	ProcessTips		Used to process the AJAX Tip Request 
*/
function processTips() 
{
	if (_viewer==null) 
		return;			

	var response;
	alert(this.getType);
	if( this.readyState == 4){
		alert('ajax processing');		
		response = this.responseText;
	}
	else {
		return;
	}
	if (response.length > 0 )
	{	
		var newtips = eval( "(" + response + ")" );
		_viewer.addTips(newtips);
		if (_viewer.initialView)
		{
			_viewer.initialView = false;
			_viewer.show();
		}
	}	
}


/*  DT_Viewer - Used to collect and store unviewed Tips.  */
DT_Viewer = function(arr)
{
	this.newtips = arr;			/* An array of tip ids to show the user */
	this.user = false;
	this.total = arr.length;
	this.max = 0;				/* The number of tips we have stored  */
	this.current = 0;			/* The current tip pointer  */
	this.largest = 0;			/* The largest tips we've shown */
	this.tips = null;			/* An array of tip objects */
	this.initialView = true;	/* For one time action : call show after first load of tips comes in*/
	this.hasUpdated = null;		/* Keeps track of tips that have been updated */	


	/*
		Like()	- Put information in the user_actions database that user likes
				- Later can modify the database
	*/
	this.like = function() {
		// TODO - update db here
		updateFlag(CreateRequestObject(),this.newtips[this.current],2);
		this.displayNext();
	}

	/*
		Flag tip as not interested, and rearrange the set of tips:
		remove the current tip, and reset the list
	*/
	this.notInterested = function() {
		
		//alert('notInterested, cur: '+this.current+', total: '+this.total);
		interested(CreateRequestObject(),this.newtips[this.current],-1);
		if (this.current==0 && this.total==1)
		{			
			//alert('single tip, should set tip: '+this.newtips[this.current]+' to not interested');
			//interested(CreateRequestObject(),this.newtips[this.current],-1);
			setTimeout(window.location.reload(),1000);
		}
		if (this.current==0) {		
			//alert('at front');
			this.newtips = this.newtips.slice(1,this.total);
			this.tips = this.tips.slice(1,this.total);
		} else if (this.current==(this.total-1)) {
			//alert('at end total is: '+this.total+' length is: '+this.newtips.length);
			this.newtips = this.newtips.slice(0,this.total-1);
			this.tips = this.tips.slice(0,this.total-1);
		} else {
			var r1 = this.newtips.slice(0,this.current);
			this.newtips = r1.concat(this.newtips.slice(this.current+1,this.total));
			var r2 = this.tips.slice(0,this.current);
			this.tips = r2.concat(this.tips.slice(this.current+1,this.total));
		}
		this.total=this.newtips.length;
		this.current--; this.max--;
		//alert('notInterested, cur: '+this.current+', total: '+this.total);

		this.displayNext();
	}
	/* 
		Persist the stored flag state 
	*/
	this.toggleFlag = function() {
		// change the action line
		var tip = this.tips[this.current]
		if (tip.flagged) {
			tip.flagged = false;
			tip.byline = tip.byline.replace("flagged","unflagged");
			//alert('tip '+this.current+' is flagged - making not flagged - byline: '+tip.byline);

		} else {
			tip.flagged = true;
			tip.byline = tip.byline.replace("unflagged","flagged");
			//alert('tip '+this.current+' is not flagged - making flagged - byline: '+tip.byline);

		}
		this.refreshAction();
	};



	this.refreshAction = function() {
		if (this.tips[this.current].flagged) {
			$("#tip-actions").html('');
		} else {
			$("#tip-actions").html(this.tips[this.current].actionline);
		}
	}

	/* 
		Changes the currently displayed tip
		tip => tip[this.current]
		Responsible for setting up the state (prev AND/OR next disabled)
	*/
	this.show = function(update) {
		if (this.tips != null)
		{
			var curTip = this.tips[this.current];
			$("#tip-title").html('<h1>'+curTip.title+'</h1>');
			$("#tip-content").html(curTip.content);
			if (curTip.flagged) {
				//alert('tip is flagged - no action shown');
				$("#tip-actions").html('');				
			} else {
				$("#tip-actions").html(curTip.actionline);
			}
			$("#tip-byline").html(curTip.byline);
			$("#viewing-tip").html((this.current+1)+' out of '+this.total);	
			if (this.current==this.largest)
			{
				this.largest++;
				/* Only update when user hits 'next' */
				var id = this.newtips[this.current-1]
				this.updateHasSeen(id);
				/* Update two for the last tip */
				if (this.current==this.total)
				{
					var id = this.newtips[this.current]
					this.updateHasSeen(id);
				}
			}
		} 
	};


	/* 
		This Function updates the server value for has_seen
	*/
	this.updateHasSeen = function(id) {
		httpObj = CreateRequestObject();
		httpObj.open("post", "/budget/hasseen.php", true);
		var post = "tid="+id;
		httpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObj.setRequestHeader("Content-length", post.length);
		httpObj.setRequestHeader("Connection", "close");
		httpObj.onreadystatechange = function() { 
		}
		httpObj.send(post);

	};

	/* 
		Add More Tips to Tips Array 
	*/
	this.addTips = function(newtips) {
		if (this.tips != null)
		{
			this.tips = this.tips.concat(newtips);
		} else {
			this.tips = newtips;
		}	
		this.max = this.tips.length;
	};

	/*
		Called from displayNext() 
		prefetches more tips if needed 
	*/
	this.getMore = function() {
		if (this.max - this.current < 3)
		{		
			var diff = this.newtips.length - this.max;
			if (diff > 0)
			{
				//alert('in getMore');
				if (diff< 10) {					
					//alert('getting '+diff+'more tips: '+this.newtips.slice(this.max,this.max+diff));
					this.getTips(this.newtips.slice(this.max,this.max+diff));
					
				} else {
					//alert('getting 10 tips: '+this.newtips.slice(this.max,this.max+10));
					this.getTips(this.newtips.slice(this.max,this.max+10));
				}
			}
		}
	};

	/*
		Takes a comma deliminated string of numbers, and retrieves tips from server
	*/
	this.getTips = function(tips)
	{
		httpObj = CreateRequestObject();
		httpObj.open("post", "/budget/gettips.php", true);

		if (this.user) {	
			var post = "tips="+tips;
		} else {
			var post = "all=1&tips="+tips;
		}
		httpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObj.setRequestHeader("Content-length", post.length);
		httpObj.setRequestHeader("Connection", "close");
		//httpObj.onreadystatechange = processTips;
		httpObj.onreadystatechange = function() {
			if (_viewer==null) 
				return;			
			var response;
			if( httpObj.readyState == 4){
				response = httpObj.responseText;
			}
			else {
				return;
			}
			if (response.length > 0 )
			{	
				var newtips = eval( "(" + response + ")" );
				_viewer.addTips(newtips);
				if (_viewer.initialView)
				{
					_viewer.initialView = false;
					_viewer.show();
				}
			}	
		}
		httpObj.send(post);
	};

	/* 
		Display the next tip unless at the front of the tip list
	*/
	this.displayPrev = function() {
		if (!this.current==0) {
			this.current--;
			this.show();
		}
	};

	/* 
		Display the next tip unless at the end of the tip list
		Handle condition where there is one tip at the end.
		Handle condition where tip has been removed, and need to update display
	*/
	this.displayNext = function()  {
		if (!(this.current==this.newtips.length-1)) {
			this.current++; 
			this.show();
			this.getMore();			
		} else {
			this.show();
		}

	};
};

function makeViewer(arr)
{
	_viewer = new DT_Viewer(arr);
	_viewer.getMore(); 
}
