var extraMatter = 0;
var mainMatter  = 1;
var selectionMode = extraMatter;

var errataIndex    = 0;
var nonerrataIndex = 1;
var unknownIndex   = 2;
var footnoteIndex  = 3;

var pageSemaphore = 0;

var pageNumber = 1;

var cookieLengthWarned = 0;

// Interface ///////////////////////////////////////////////////////////

function getBook( ) {
  var value = new String( "" + document.navigation.book.options[ document.navigation.book.selectedIndex ].value );
  return value;
}

function getSection( ) {
  if( selectionMode == extraMatter ) {
    return new String( "" + document.navigation.page.options[ document.navigation.page.selectedIndex ].value );
  }
  else {
    updateSectionNumber( );
    return pageNumber;
  }
}

function updatePageSelection( ) {
  var book = top.getCurrentBook( );
  var section = top.getCurrentSection( );

  if( top.trackPageChanges ) {
    if( book != "" ) {
      for( var i = 0; i < document.navigation.book.options.length; ++i ) {
	var bookOptionValue = new String( "" + document.navigation.book.options[ i ].value );
	if( bookOptionValue.indexOf( book ) != -1 ) {
	  document.navigation.book.selectedIndex = i;
	}
      }
    }

    if( section != "" ) {
      if( isNaN( section ) ) {
	for( var i = 0; i < document.navigation.page.options.length; ++i ) {
	  if( section == document.navigation.page.options[ i ].value ) {
	    document.navigation.page.selectedIndex = i;
	    switchMode( extraMatter );
	  }
	}
      }
      else {
	document.navigation.pagenumber.value = section;
        updateSectionNumber( );
	switchMode( mainMatter );
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////

function switchMode( mode ) {
  selectionMode = mode;
  document.navigation.selectMode[ mode ].checked = true;
}

function incrementPage( ) {
  ++pageNumber;
  document.navigation.pagenumber.value = pageNumber;

  switchMode( mainMatter );
  goToPage( );
}

function decrementPage( ) {
  --pageNumber;
  document.navigation.pagenumber.value = pageNumber;

  switchMode( mainMatter );
  goToPage( );
}

function goToPage( ) {
  top.setBook( getBook( ), getSection( ) );
  return true;
}

function updateSectionNumber( ) {
  pageNumber = parseInt( document.navigation.pagenumber.value );
}

function addCorrection( ) {
  var correction = new String( "" );
  var currentPageSelection = new String( "" );

  if( top.checkPageConsistency ) {
    // insert new consistency check
  }

  if( document.autogen.typeSelect[ errataIndex ].checked ) {
    correction += "(" + document.autogen.typeSelect[ errataIndex ].value + ") ";
  }
  else if( document.autogen.typeSelect[ nonerrataIndex ].checked ) {
    correction += "(" + document.autogen.typeSelect[ nonerrataIndex ].value + ") ";
  }
  else if( document.autogen.typeSelect[ unknownIndex ].checked ) {
    correction += "(" + document.autogen.typeSelect[ unknownIndex ].value + ") ";
  }
  else if( document.autogen.typeSelect[ footnoteIndex ].checked ) {
    correction += "(" + document.autogen.typeSelect[ footnoteIndex ].value + ") ";
  }

  var book = new String( "" + document.navigation.book.options[ document.navigation.book.selectedIndex ].value );
  correction += "" + getBook( ) + " " + getSection( );

  if( document.autogen.issue.value == "" ) {
    correction += ": ";
  }
  else {
    if( document.autogen.original.value == "" && document.autogen.corrected.value == "" ) {
      correction += " #" + parseInt( document.autogen.issue.value ) + ": ";
    }
    else if( confirm( "An issue number should only be specified for a comment to an already posted issue, not a new one. Discard the issue number and continue using original/corrected information?" ) ) {
      correction += ": ";
    }
    else return false;
  }

  if( testForReserved( document.autogen.original.value ) ) {
    correction += document.autogen.original.value;
  }
  else {
    alert( "Reserved string found in original (look for \"(...)\" or \"[...]\")" );
    return false;
  }

  if( testForReserved( document.autogen.corrected.value ) ) {
    if( document.autogen.corrected.value != "" ) {
      correction += " -> " + document.autogen.corrected.value;
    }
  }
  else {
    alert( "Reserved string found in corrected (look for \"(...)\" or \"[...]\")" );
    return false;
  }

  if( document.autogen.comment.value != " " && document.autogen.comment.value != "" ) {
    if( testForReserved( document.autogen.comment.value ) ) {
      if( document.submission.initials.value == "" ) {
       document.submission.initials.value = prompt( "Please enter your initials (e.g. \"jd\", \"bw\"):" );
      }
      correction += " [" + document.submission.initials.value + ": "+ document.autogen.comment.value + "]";
    }
    else {
      alert( "Reserved string found in comment (look for \"(...)\" or \"[...]\")" );
      return false;
    }
  }

  document.autogen.original.value = "";
  document.autogen.corrected.value = "";
  document.autogen.comment.value = "";
  document.autogen.issue.value = "";

  if( document.submission.message.value == " " ) document.submission.message.value = "";
  if( top.addCorrectionsToTop ) {
    document.submission.message.value = correction + "\n" + document.submission.message.value;
  }
  else {
    document.submission.message.value = document.submission.message.value + correction + "\n";
  }
  document.autogen.original.focus( );
  return false;
}

function controlsLoad( ) {
  document.navigation.pagenumber.value = pageNumber;
  if( top.bookCode ) {
    for( var i = 0; i < document.navigation.book.options.length; ++i ) {
      var bookOptionValue = new String( "" + document.navigation.book.options[ i ].value );
      if( bookOptionValue == top.bookCode ) {
        document.navigation.book.selectedIndex = i;
      }
    }
    var mainLocation = new String( "" + top.main.location );
    mainLocation = "" + mainLocation + "#" + top.bookCode;
    top.main.location = "" + mainLocation;
  }

  document.autogen.comment.value = "";
  document.submission.message.value = "";
  readUserInfo( );
  readLifeBoat( );
  window.setInterval( writeLifeBoat, 15000 );
  window.setInterval( pageTrack, 1000 );
}

function readLifeBoat( ) {
  var cookieName = new String( "LifeBoat=" );
  var cookies = new String( "" + document.cookie );
  var position = cookies.indexOf( cookieName );

  if( position != -1 ) {
    position += cookieName.length;
    var end = cookies.indexOf( ";", position );
    if( end == -1 ) end = cookies.length;
    var lbCookie = cookies.substring( position, end );
    if( lbCookie != "" ) document.submission.message.value = unescape( lbCookie );
  }
  return true;
}

function writeLifeBoat( ) {
  var cookieName = new String( "LifeBoat=" );
  var cookieValue = new String( "" + escape( document.submission.message.value ) );

  if( (cookieValue.length + cookieName.length) > 4096 ) { // cookie + name must be less than 4 KB
    if( cookieLengthWarned == 0 ) {
      alert( "Warning: corrections have exceeded maximum temporary\nstorage length. Please submit them or save them to file in case of\naccidental loss." );
      cookieLengthWarned = 1;
    }
  }
  else cookieLengthWarned = 0;

  var date = new Date();
  date.setTime( date.getTime() + 1000*60*60*24*365*1 ); // 1 year hence

  document.cookie = cookieName + cookieValue + "; expires=" + date.toGMTString();

  return true;
}

function readUserInfo( ) {
  var cookieName = new String( "UserInfo=" );
  var cookies = new String( "" + document.cookie );
  var position = cookies.indexOf( cookieName );

  if( position != -1 ) {
    position += cookieName.length;
    var end = cookies.indexOf( ";", position );
    if( end == -1 ) end = cookies.length;
    var uiCookie = cookies.substring( position, end );
    if( uiCookie != "" ) {
      eval( unescape( uiCookie ) );
    }
  }
  return true;
}

function writeUserInfo( ) {
  var cookieName = new String( "UserInfo=" );
  var cookieValue = new String( "" );

  cookieValue += "document.submission.fullname.value='" + top.codify( document.submission.fullname.value ) + "';";
  cookieValue += "document.submission.initials.value='" + top.codify( document.submission.initials.value ) + "';";
  cookieValue += "document.submission.email.value='" + top.codify( document.submission.email.value ) + "';";

  if( (cookieValue.length + cookieName.length) > 4096 ) { // cookie + name must be less than 4 KB
    alert( "Warning: user info has exceeded maximum storage length." );
  }

  var date = new Date();
  date.setTime( date.getTime() + 1000*60*60*24*365*1 ); // 1 year hence

  document.cookie = cookieName + escape( cookieValue ) + "; expires=" + date.toGMTString();

  return true;
}

function submitForm( ) {
  while( document.submission.fullname.value == "" ) {
    document.submission.fullname.value = prompt( "Please enter your full name (e.g. \"Joe Dever\" )" );
  }
  while( document.submission.initials.value == "" ) {
    document.submission.initials.value = prompt( "Please enter your initials (e.g. \"jd\" \"gc\")" );
  }
  while( document.submission.email.value == "" ) {
    document.submission.email.value = prompt( "Please enter your email (e.g. \"lonewolf@kai.com\" )" );
  }
  writeUserInfo( );

  if( top.viewedOnline( ) || (!top.viewedOnline( ) && confirm( "Connected to the internet?" )) ) {
    return true;
  }
  else return false;
}

function pageTrack( ) {
  if( top.trackPageChanges && pageSemaphore == 0 ) {
    updatePageSelection( );
  }
}

function upPageSemaphore( ) {
  ++pageSemaphore;
}

function downPageSemaphore( ) {
  --pageSemaphore;
}

function testForReserved( testString ) {
  testString = new String( "" + testString );
  if( testString.indexOf( "(er)" ) != -1 ||
      testString.indexOf( "(e)" )  != -1 ||
      testString.indexOf( "(ce)" ) != -1 ||
      testString.indexOf( "(re)" ) != -1 ||
      testString.indexOf( "(ne)" ) != -1 ||
      testString.indexOf( "(n)" )  != -1 ||
      testString.indexOf( "(cn)" ) != -1 ||
      testString.indexOf( "(rn)" ) != -1 ||
      testString.indexOf( "(ft)" ) != -1 ||
      testString.indexOf( "(f)" )  != -1 ||
      testString.indexOf( "(cf)" ) != -1 ||
      testString.indexOf( "(rf)" ) != -1 ||
      testString.indexOf( "(??)" ) != -1 ||
      testString.indexOf( "(?)" )  != -1 ||
      testString.indexOf( "[" )  != -1 ||
      testString.indexOf( "]" )  != -1 )
  {
    return false;
  }
  else return true;
}

function updateCharacter( ) {
  document.tools.characterBox.value = document.tools.characterSelect.options[ document.tools.characterSelect.selectedIndex ].text;
  return true;
}

