/**
* @author   $Author: martijn $
* @revision $Revision: 169 $
* @date     $Date: 2010-04-10 19:31:43 +0200 (Sat, 10 Apr 2010) $
*/
// counts the nr of chars in the shoutname and shouttext field
function updateTextLimitCounter()
{
	shoutTextLength = document.getElementById('shouttext').value.length;
	shoutNameLength = document.getElementById('shoutname').value.length
	totalLength     = shoutTextLength + shoutNameLength;
	
	document.getElementById('textLimitCounter').value = maxTotalLength - totalLength;
}
// updates how many chars are left and trims when max is reached
function trimFieldLength(fieldEl) 
{
	if(totalLength > maxTotalLength)
	{
		//alert('too long, trim it'); 
		fieldEl.value = fieldEl.value.substring(0, (fieldEl.value.length - totalLength + maxTotalLength - 1));
	}	
}

function sendShout(action)
{
    // clear previous feedback 
    $('#shoutfeedback').empty();
    
 	shoutnameEl = document.getElementById('shoutname');
	shouttextEl = document.getElementById('shouttext');

	// everything filled in?
	validated   = validateShout(shoutnameEl, shouttextEl); 
	if(validated == true)
	{
		// submit, and on success refresh all the shouts
		$.post(
		    action, 
		    $("#shoutboxform").serialize(), // serialize the form input for the post
		    function() { 
		        window.clearTimeout(shoutsLoopTimer); // zet de timer even uit zodat ie opnieuw begint en niet midden in ververst
		        shoutsLoop(); // en opnieuw aan om the refresehen zodat de nieuwe shout gehaald en getoond wordt
		    }, 
		    'html'
		);
		
		// reset text and counter
		shouttextEl.value = '';
		shouttextEl.focus();
		updateTextLimitCounter();
		
		// scroll to the top
		$('#shoutcontainer').scrollTop(0);
	}
}
/**
 * Reads the last known last id and inserts all new shouts from that id on and stores the new last id
 * 
 */
function pergeShouts()
{
   $.get(
       '/shoutbox/shouts/id/' + lastId, '', 
       function(liShouts) { 
            $('#shouts').prepend(liShouts); // buiten de li's die hier terugkomen, kan er ook js tussen zitten dat moet worden uitgevoerd
       }, 
       'html'
   );
   // when new shouts are found, the lastId gets updated
}

/** 
 * zet een loop aan die om de 5 sec shouts vanaf lastId ophaalt
 */
function shoutsLoop()
{
    pergeShouts();
    // repeat this in 5 secs
    shoutsLoopTimer = window.setTimeout(shoutsLoop, 5000);
    
}

function validateShout(shoutnameEl, shouttextEl)
{
	validated = true;
	
	if(shoutnameEl.value.length == 0 )
	{
		shoutnameEl.className = 'error';
		validated = false;
	}	
	else
	{
		shoutnameEl.className = 'text';	
	}
	
	if ( shouttextEl.value.length == 0)
	{
		shouttextEl.className = 'error';
		validated = false;
	}	
	else
	{
		shouttextEl.className = 'textarea';	
	}
	
	
	
	return validated;
}


