function addTo(name)
{
    var toField = document.getElementById( "to" );            
	if ( toField.value.length == 0 )
	{
		toField.value = name;
	}
	else
	{
		// check for duplicates - case sensitive and does not consider 'Glenn Eve' vs 'Glenn Even'
		if ( toField.value.search( name ) != -1 )
		{
			return;
		}
		
		// append with comma separator
		if ( toField.value.charAt( toField.value.length - 1 ) != ',' )
		{
			toField.value += ',';
		}
		toField.value += ' ' + name;
	}
	
	changedTo();
}

function changedTo()
{
	summariseTo();
	resizeTo();
	summariseCost();
}

function changedBody()
{
	summariseBody();
	summariseCost();
}

function resizeTo()
{
    var toField = document.getElementById( "to" );            
    var desiredRows = toField.value.length / toField.cols;
	desiredRows = Math.ceil( desiredRows );
	desiredRows = Math.max( 2, desiredRows );
	desiredRows = Math.min( desiredRows, 5 );
	
    toField.rows = desiredRows;
}

function summariseTo()
{
    var toField = document.getElementById( "to" );
	var candidates = toField.value.split( "," );
	var people = 0;
	for ( var i = 0; i < candidates.length; ++i )
	{
		// At least one char
		if ( candidates[i].search( /\w/ ) != -1 )
		{
			++people;
		}
	}
	var term = "people";
	if ( people == 1 )
	{
		term = "person";
	}
	
	var s = document.getElementById( "to_summary" );
	s.innerHTML = people + " " + term;
}

function summariseBody()
{	
    var bodyField = document.getElementById( "body" );
	// Limit the length of messages to 300
	if ( bodyField.value.length > 300 )
	{
		bodyField.value = bodyField.value.substr( 0, 300 );
	}
	
	var s = document.getElementById( "body_summary" );
	var term = "characters";
	if ( bodyField.value.length == 1 )
	{
		term = "character";
	}
	s.innerHTML = bodyField.value.length + " " + term;
}

function summariseCost()
{
    var toField = document.getElementById( "to" );
    var bodyField = document.getElementById( "body" );
    var deliveryConfirmationField = document.getElementById( "deliveryConfirmation" );

	// Count the number of To entries
	var candidates = toField.value.split( "," );
	var people = 0;
	for ( var i = 0; i < candidates.length; ++i )
	{
		// At least one char
		if ( candidates[i].search( /\w/ ) != -1 )
		{
			++people;
		}
	}
	
	// Delivery confirmation
	if ( deliveryConfirmationField.checked == true )
	{
		people = people * 2;
	}

	// Count the number of message blocks	
	var singleMessageBlockSize = 160;
	var multiMessageBlockSize = 150;
	var messageBlocks = 1;
	if ( bodyField.value.length > singleMessageBlockSize )
	{
		messageBlocks = Math.ceil( bodyField.value.length / multiMessageBlockSize );
	}
	
	var cost = people * messageBlocks;
	
	var s = document.getElementById( "cost_summary" );
	var term = "credits";
	if ( cost == 1 )
	{
		term = "credit";
	}
	s.innerHTML = cost + " " + term;
}
