var s = "";
var words = "...";

function t(s) {
	//console.log( s );
}

function type_text( text, target, height, rate, onComplete ) {

  // cache viewport height for later clipping
  $(target).height = height;
  
  if( ! text || ! target ) {
    return;
	}
  var lines = multi_line_from_div( text );
  setTimeout( function() { type_line( lines, target, rate, onComplete);}, rate);
}

function type_line( lines, target, rate, onComplete ) {
  if( ! lines || lines.length < 1 )
    return;
  
  // clip if necessary
  var lines_in_target = multi_line_from_div( target );
  if( lines_in_target && lines_in_target.length > $(target).height ) {
    t( "clipping" );
    lines_in_target.shift();
    $(target).innerHTML = lines_in_target.join("");
  }

  var line = lines.shift();
  line = line.substring( 1, line.length);

  t( line.length + " characters in line" );
  t( lines.length + " lines in story" );

  type_by_letter( line, lines, target, rate, onComplete );
}

function type_by_letter( line, lines, target, rate, onComplete ) {
  if( ! line || ! lines || line.length < 1 ) {
    t( "writing new line" );
    $(target).innerHTML += "\n"; 
    setTimeout( function() { type_line( lines, target, rate, onComplete);} , rate); // next line

		if( lines.length < 1 ) {
			if( onComplete )
				onComplete();
		}
  } else {
    var c = line.charAt(0);
    line = line.substring( 1, line.length);
    $(target).innerHTML += c;
    setTimeout( function() { type_by_letter( line, lines, target, rate, onComplete);} , rate);
  }
}

function multi_line_from_div( div ) {
  if( !div )
    return;
  var lines = $(div).innerHTML;
  if( lines )
    lines = lines.split( /$/m );
		if( lines && lines.length && lines[0].match( /^\s*$/ )) {
			t( "trimming empty initial line from " + div );
			lines.shift();
		}

	if( lines && lines.length > 1 && lines[lines.length-1].match( /^\s*$/ )) {
		t( "trimming empty final line from " + div );
		lines.pop();
	}
  return lines;
}

function intro() {
  type_text( "header_txt", "header",   18, 10, function() { body(); } );
}

function body() {
	type_text( "words",   "screen",   18, 10, 
	function() { type_text( "words_2", "screen_2", 18, 10,
	function() { type_text( "words_3", "screen_3", 18, 10 );	}
	 ); } );
  
	
}

function main() {
	intro();
}

