debug="on";
phpDir = "http://www.codesplunk.com/nr/php/";
var nextLink = "http://www.codesplunk.com?";

function checkNoneChecked()
{
  var checked = false;
  var arr = new Array( 'ra', 'rb', 'rc', 'rd' );

  for( a=0; a<4; a+= 1 )
  {
    val = document.getElementById( arr[a] );
    if( val != null && val.checked == true ) checked = true;
  }

  if( checked == true ) return true;
  else return false;
}

var loginID ="none";
var tv      ="p";
var correct = -1;
var qi="default";
function darts()
{
  if( checkNoneChecked() == false ) return;
  var a = xmlDocument.getElementsByTagName( "a" );

  var r="d";
  var ans = getData( a[0] ).substr( 0, 1 ).toLowerCase();
  if(( ans == 'a' ) || ( ans == 'b' ) || ( ans == 'c' ) || ( ans == 'd' ))
  {
    if( document.getElementById( 'r' + ans ).checked == true )
    {
      if( correct == -1 && loginID != "none" )
      {
        points = parseInt(points) + parseInt(1);
        correct = 1;
        display( signed() );
      }
      correct = 1;
      r = "<font color=green>Correct</font>";
    } else 
    {
      if( correct == -1 && loginID != "none" )
      {
        correct = 0;
        display( signed() );
      }
      correct = 0;
      r="<font color=red>Incorrect</font> The correct answer is '" + ans + "' ";
    }
  } else r="There is no answer for this question.";

  displayIt('res' , r + "<br><br>", "clear" );

  //  the following delay is necessary to prevent the browser from rendering after waiting for the request to get back.
  setTimeout( 'recordIt()', 500 );
}

function recordIt()
{
  commXMLDocument( 0, none, phpDir + "record.php", "l=" + loginID + "&p=" + tv + "&qi=" + qi  + "&c=" + correct );
}

function showGadget()
{
  document.getElementById( 'div0' ).innerHTML = "<script src='http://gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/112049494056302249686/codesplunk9.xml&amp;synd=open&amp;w=280&amp;h=275&amp;title=Programming+Question+of+the+day&amp;border=%23ffffff%7C3px%2C1px+solid+%23999999&amp;output=js'></script>";
}

function getStr( key )
{
  var href = document.location.href;
  var kloc = href.indexOf(key + "=" );
  if( kloc == -1 ) return '';
  var eloc = href.indexOf('&', kloc);
  if( eloc == -1 ) eloc = href.length;
  return href.substring( kloc + key.length + 1, eloc);
}

var gmain = "";  //  this will be main page if one of the four main pages
function loadLinks( main )
{
  gmain = main;
  var sit = getStr( 'si' );
  if( document.getElementById("nav") != null )
    document.getElementById("nav").selectedIndex = sit;

  loginID  = getStr( "loginID" ).toLowerCase();
  if( loginID== '' ) loginID = "none";
  tv       = unEncrypt( getStr( "tv" ));
  points   = getStr( 'points' );

  var spos = document.location.href.indexOf('questions') + 10;
  var epos = document.location.href.indexOf('.html');
  qi       = document.location.href.substring( spos, epos );

  if( gmain != "mainpage" && gmain != "indexpage" ) displayIt( 'hreflinks', bk );
  if( loginID == 'none' && gmain != 'mainpage' && gmain != 'indexpage' )
    displayIt( 'otrack', "<div id='track'><center>Track your progress by signing in!</center></div><br>" );

  prepQuestion();
}

function signed()
{
  //  Linux firefox somehow renders 5 pixels lower then the windows and mac equivalent... strange.
  var top;
  if( navigator.platform.substr( 0, 5 ) == "Linux" && 
      navigator.userAgent.indexOf( "Firefox" ) != -1 ) topCoord = -31;
  else topCoord = -23;

  return  "<div style=''><table><tr><td><div style='position: relative; top: -20px; z-index: 20;'><table bgcolor=white border=4 cellpadding=0 ><tr><td><font size=7 ><b>&nbsp " + points + " &nbsp</b></font>" + 
"</td></tr></table></div></td><td><div id='loginDisplay' style='position: relative; top: " + topCoord + "; z-index:10;'><font size=3> &nbsp Logged in as: &nbsp<a href='http://www.codesplunk.com/nr/php/myaccount.php?loginID=" + loginID + "&tv=" + Encrypt( tv ) + "&points=" + points + "'>" + 
loginID + "</a><br> &nbsp " + displayPrevious() + "<a href='javascript: logout()'>log out</a></font></div></td><td width=10></td></tr></table></div>";
}

function displayPrevious()
{
  if( gmain == "mainpage" || gmain == "myaccount" || gmain == "indexpage" ) return "";
  if( correct < 0 ) cstring = 'unanswered';
  if( correct == 0 ) cstring = '<font color="red">incorrect</font>';
  if( correct == 1 ) cstring = '<font color="green">correct</font>';
  return "reco=" + cstring + " &nbsp";
}

var agt=navigator.userAgent.toLowerCase();
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
function logout()
{
  loginID = "none";
  password= "none";
  points  = -1;

  if( is_ie == true ) reAdjustPositions( "0px" );
  document.location = document.location.href.substr( 0, document.location.href.indexOf( '?' ));
}

function reAdjustPositions( topPos )
{
    var objs = new Array( "hbot", "left", "hreflinks", "right", "div0", "div1" );
    for( var a=0; a < objs.length; a += 1 )
    {
      var tobj = document.getElementById( objs[a] );
      if( tobj != null )
      {
	 if( objs[a] == "hreflinks" && gmain != "mainpage" )
         {} else { 
 	   tobj.style.position="relative";
           tobj.style.top     = topPos;
         }
      }
    }
}

function loadUserGraphics()
//  draw "you are logged in as: xxx or login pannel/no sign up.  plus the total number of points you have accumulated.
{
  var inner;
  if( loginID != "none" )
    inner = signed();
  else inner = '<div style="position: relative; top: 4px; left: -5px;"><table cellspacing=0 cellpadding=0 ><TR><TD align=right >Login<input type="text" ID="loginID" style="width: 50px;" maxlength=10 /> &nbsp Password<input type="password" ID="password" onBlur=\'if( document.getElementById( "sbutton" ) != null ) document.getElementById("sbutton").focus()\' onKeyPress="if(checkEnter(event)) signIn2()" style="width: 50px;" maxlength=16 />'+
'<input onKeyPress="if(checkEnter(event)) signIn2()" id="sbutton" type = "button" value = "Sign In" onclick = "signIn2()"  >'+
' &nbsp<a href="javascript: hover()"></td><td>' + 
'<table cellspacing=0 cellpadding=0 ><tr><td><font size=2 style="line-height: 78%"><a href="javascript: noneed()">Sign In<br>without signup</font></a></font></td></tr><table></TD></TR></TABLE></div>';

  display( inner );

  if( loginID != "none" && is_ie == true ) reAdjustPositions( "-42px" );
}

function display( inner )
{ 
    var disString = "<table cellpadding=-2 cellspacing=0 width=100% ><tr><td width=44%></td>" + 
    "<td valign=top align=center width=12%><font size=5 face=tahoma><b>CodeSplunk</b></font></td><td valign=top width=44% align='right' >" + 
    inner + "</td></tr></table>";

    displayIt( 'loggedIn', disString, 'clear' );
}

function noneed()
{
  var d = "<table bgcolor='white' cellpadding=18 border=3 width=240 ><tr><td>You will automatically get an account the first time you login.  After you log in, any questions you answer or submit will be saved.  By logging in you agree to the <a href=\"javascript: openTerms();\">terms of service</a> &nbsp &nbsp <a href=\"javascript: clearNoNeed()\">close</a></td></tr></table>";
  displayIt( 'signIn', d, 'clear' );
}

function openTerms()
{
  window.open( 'http://www.codesplunk.com/nr/HTML/cterms.html', 'win2', 'width=800,height=600,scrollbars=yes');
}

function clearNoNeed()
{
  displayIt( 'signIn', ' ', 'clear' );
}

function signIn2()
{
  var l = document.getElementById( 'loginID' ).value.toLowerCase();
  var p = document.getElementById( 'password' ).value.toLowerCase();
  tv    = p;
  if( p.length < 6 && p != "p" )
  {
    alert( "Password must be at least 6 characters in length" ); return; 
  }
  if( l == '' || p == '' )
  {
    alert( "loginID and Password cannot be blank." ); return; 
  }
  commXMLDocument( 0, afterLogin, phpDir + "ltonic.php", "l=" + l + "&p=" + p + "&qi=" + qi );
}

function afterLogin()
{
  document.cookie = '';
  correct      = getData( xmlDocument.getElementsByTagName( 'correct' )[0] );
  loginID      = getData( xmlDocument.getElementsByTagName( 'loginID' )[0] );
  var response = getData( xmlDocument.getElementsByTagName( 'response' )[0] );
  points       =  getData( xmlDocument.getElementsByTagName( 'points' )[0] );

  if( response == "valid password" || response == "created new account" )
  {
    loginID = document.getElementById( 'loginID' ).value.toLowerCase();
    loadUserGraphics();
    displayIt( "track", ' ', 'clear' );
  } 
  if( response == "invalid password" )
    alert( "that loginID already has an account, incorrect password." );
}

function checkEnter(e, next){ //e is event object passed from function invocation
  var characterCode;  // literal character code will be stored in this variable

  if(e && e.which){ //if which property of event object is supported (NN4)
    e = e;
    characterCode = e.which;
  }
  else{
  e = event;
  characterCode = e.keyCode ;
  }

  if(characterCode == 13){
    //if generated character code is equal to ascii 13 (if enter key)
    //  submit form
  return true;
  } else return false;
}

var qnum = "default";
function onLanguageSelect()
{
   qnum = "newLanguageSelected";
   prepQuestion();
}

function getSuffix()
{
  return "&loginID=" + loginID + "&tv=" + Encrypt( tv ) + "&points=" + points;
}

function gotoUrl( str )
{
  document.location = str.replace( '#', '%23' ) + "?" + getSuffix();
}

function nextQuestion()
{
  document.location = nextLink.replace( '#', '%23' ) + getSuffix();
}

var pageStatus = "new";
var si=3;
var language="default";
function prepQuestion()
//  precondition: all the values in the arr must be valid and a page must exist for each of those values
//  it is genXml's responsibility to make sure these values are always correct
{
  var qn = 1;
  var nav  = document.getElementById("nav");
  if( nav != null )
  {
    language = nav.value;
    si       = nav.selectedIndex;
    sub      = document.getElementById( 'divSubject' );
    if( sub != null && sub.innerHTML.toLowerCase() == nav.value.toLowerCase() ) 
	qnum = "";  //  a new language was not selected, the same one was selected as last time.
  }

  if(  document.getElementById("divQuestion") == null ) qn = 1;
  else qn =  document.getElementById("divQuestion").innerHTML;
  qn      = parseInt(1) + parseInt( qn );

  for( var z=0; z <  totalLangs; z ++ )
    if( arr[z][0].toLowerCase() == language.toLowerCase() ) break;

  if( qn > arr[z][1] ) qn = 1;

  if( qnum == "newLanguageSelected" ) 
    q = language.toLowerCase() + "1.html";
  else
    q = language.toLowerCase() + qn + ".html";

  if( si == 0 )
  {
    //  the following will later be embedded inside the head/script tags of each of the html pages.
    var l    = 0; var c = 1;
    var rtot = Math.ceil( Math.random() * totalPages );

    for( var i=0; i < 1000; i += 1 )
    { //  l is out of bounds here, need to check.
      if( i == rtot ) break;
      if( c < arr[l][1] ) c += 1;
      else 
      {
         l += 1;
         c =  1;
      }
    }
    
    var q= arr[l][0].toLowerCase() + c + ".html";
  }
  
  if( q == '' ) nextLink='http://www.codesplunk.com'; //  this should not happen, but error out gracefully anyways
  else nextLink ="http://www.codesplunk.com/nr/questions/" + q + "?si=" + si; 

  //  the following delay is necessary to prevent the browser from rendering after waiting for the request to get back.
  if( qnum != "newLanguageSelected" ) 
  setTimeout( 'countPoints()', 100 );
}

function loadTops()
{
  commXMLDocument( 0, displayTops, phpDir + "getPoints.php", "l=" + loginID );
}

function displayTops()
{
  var names  = xmlDocument.getElementsByTagName( "l" );
  var points = xmlDocument.getElementsByTagName( "p" );
  var dis = "<table border=3 width=240 ><tr><td>Name</td><td>Points</td></tr>";
  for( var z=0; z < 14; z += 1 )
    dis += "<tr><td>" + getData( names[z] ) + "</td><td>" + getData( points[z] ) + "</td></tr>";

  dis += "</table>";
  displayIt( "tops", dis, "clear" );
}

function countPoints()
{
  //  if the points are not -1 then we can omit that DB function
  commXMLDocument( 0, refer, phpDir + "countPoints.php", "loginID=" + loginID + "&questionID=" + qi + "&points=" + points);
}

//  the following is true when on one of the main 4 pages where there are no questions, thus we don't need to get the correct value
//  Also don't need to get the correct value 
var points=-1;
var correct=-2;
function refer()
{
  points = getData( xmlDocument.getElementsByTagName( 'points' )[0] ); 
  correct= getData( xmlDocument.getElementsByTagName( 'correct')[0] );
  loadUserGraphics();

  if( pageStatus == "new" && document.referrer != "" && document.referrer != "test" && document.referrer.indexOf( 'codesplunk' ) == -1 )
  {
    commXMLDocument( 0, none, phpDir + "referrer.php", "ref=" + document.referrer );
    pageStatus = "already sent";
  }
}

function contact()
{
  document.getElementById('div0').innerHTML = "<center><img src='http://www.codesplunk.com/nr/images/emvail2.bmp'></img></center>";
}

function home()
{
  document.location = "http://www.codesplunk.com";
}

var keyupCheck250 = "onkeyup=\'checkLength( this, 250 )\' ";
function createOneQuestion()
{
  var q = '<center><table><tr><td>Multiple Choice Question: <BR>' +
    '<form style="whitespace: nowrap; display: inline;">' +
    '<TEXTAREA ' + keyupCheck250 + ' name=text1 id="ta"' +
    ' cols=70 rows=2></TEXTAREA><BR><BR>' +
    answer( 'ans', 'a' ) +
    answer( 'ans', 'b' ) +
    answer( 'ans', 'c' ) +
    answer( 'ans', 'd' ) +
    "<br>Enter Correct answer letter here:" +
    "<input type='text' id='correctAnswer" + 
    "' size=2 maxlength=1 > <br>Programming language: " + 
    "<div id='language' style='whitespace: nowrap; display: inline;' ></div> &nbsp " +
    "<input type='button' value='submit' onclick='submitQuestion()' >" +
    "</form><br><br><div id='res'></div></td></tr></table></center>";

    var el = document.getElementById( 'div0' );
    if( is_ie == true && gmain == "indexpage" && el != null ) 
        el.style.top      = "0px";

    displayIt( "div0", q, "clear" );
    commXMLDocument( 0, getLanguages, phpDir + "getLanguages.php", "" );
}

function getLanguages()
{
  var languages = xmlDocument.getElementsByTagName( "l" );
  var h = "<select id='languageSel'><option value='choose a language'>choose a language</option>";
  for( var i=0; i<languages.length; i += 1 )
    h += "<option value='" + getData( languages[i] ) + "'> " + 
          getData( languages[i] ) + "</option>";

  h += "</select>";
  displayIt( "language", h, "clear" );
}

function submitQuestion()
{
  if( document.getElementById('languageSel').selectedIndex == 0 ) 
  {  alert( 'select a programming language.' ); return; }
  if( get( "ta" ) == '' )
  {  alert( 'question cannot be blank' ); return; }
  if( get( "ansa" ) == '' )
  {  alert( 'answer a cannot be blank' ); return; }
  if( get( "ansb" ) == '' )
  {  alert( 'answer b cannot be blank' ); return; }
  if( get( "correctAnswer" ) == '' )
  {  alert( 'correct answer cannot be blank' ); return; }

  commXMLDocument( 0, subResponse, phpDir + "subQuestion.php", 
  "question=" + get( "ta" ) + "&ansa=" + get( "ansa" ) + 
  "&ansb=" + get( "ansb" ) + "&ansc=" + get( "ansc" ) + 
  "&ansd=" + get( "ansd" ) + "&correctAnswer=" + get('correctAnswer').toLowerCase() +
  "&language=" + encodeBrackets( document.getElementById('languageSel').value ) + 
  "&author=" + loginID );
}

function subResponse()
{
  points = parseInt( points ) + parseInt( 10 );
  displayIt( "res", "<font color=green>Your entry has been submitted.</font>", "clear" );
  document.getElementById( 'ta' ).value = "";
  document.getElementById( 'ansa' ).value = "";
  document.getElementById( 'ansb' ).value = "";
  document.getElementById( 'ansc' ).value = "";
  document.getElementById( 'ansd' ).value = "";
  document.getElementById( 'correctAnswer' ).value = "";
  document.getElementById( 'language' ).value = "";
  if( loginID != 'none' ) display( signed() );
}

function answer( strId, letter )
{
  strLetterId = strId + letter;
  var retStr = "&nbsp&nbsp " + letter + ")" + "&nbsp&nbsp " +   "<input type='text' name=textdff1 id='" +
  strLetterId + "' size=60 maxlength=110 ><br>";

  return retStr; 
}

//  just fo rpurposes of encoding the url at the address bar so people can't see your password while you use hte computer
//  not fo rman in the middle attacks
function Encrypt(theText) {
  var alpha   = "89asdfso8fuw8r3r34o8fsdof8sufsd8fudnvnoasdf8sudfasfowe8r9384573risejfasdf";
  var newText = "";
  for( var a = 0; a<theText.length; a += 1 )
    newText += theText.charAt( a ) + alpha.charAt( a );
  return newText; 
}

function unEncrypt(theText) {
  newText = "";
  for( var a=0; a<theText.length; a+=2 )
    newText += theText.charAt( a );
  return newText;
}

var bk = '<center><a rel="nofollow" href="http://www.blinkbits.com/bookmarklets/save.php?v=1&amp;source_url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to BlinkBits"><img src="../iconss/blinkbits.jpg" alt="Post to BlinkBits" /></a> <a rel="nofollow" href="http://blogmarks.net/my/new.php?mini=1&amp;simple=1&amp;url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to BlogMarks"><img src="../iconss/blogmarks.jpg" alt="Post to BlogMarks" /></a> <a rel="nofollow" href="http://del.icio.us/post?v=2&amp;url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Del.icio.us"><img src="../iconss/delicious.jpg" alt="Post to Del.icio.us" /></a> <a rel="nofollow" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Digg"><img src="../iconss/digg.jpg" alt="Post to Digg" /></a> <a rel="nofollow" href="http://cgi.fark.com/cgi/fark/edit.pl?new_url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Fark"><img src="../iconss/fark.jpg" alt="Post to Fark" /></a> <a rel="nofollow" href="http://www.furl.net/storeIt.jsp?t=Programming Language Share and Review&amp;u=http%3A%2F%2Fcodesplunk.com" title="Post to Furl"><img src="../iconss/furl.jpg" alt="Post to Furl" /></a> <a rel="nofollow" href="http://www.google.com/bookmarks/mark?op=add&amp;bkmk=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Google"><img src="../iconss/google.jpg" alt="Post to Google" /></a> <a rel="nofollow" href="http://ma.gnolia.com/bookmarklet/add?url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Ma.gnolia"><img src="../iconss/magnolia.jpg" alt="Post to Ma.gnolia" /></a> <a rel="nofollow" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?t=Programming Language Share and Review&amp;u=http%3A%2F%2Fcodesplunk.com" title="Post to MyWeb"><img src="../iconss/myweb.jpg" alt="Post to MyWeb" /></a> <a rel="nofollow" href="http://www.netscape.com/submit/?U=http%3A%2F%2Fcodesplunk.com&amp;T=Programming Language Share and Review" title="Post to Netscape"><img src="../iconss/netscape.jpg" alt="Post to Netscape" /></a> <a rel="nofollow" href="http://netvouz.com/action/submitBookmark?url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to NetVouz"><img src="../iconss/netvouz.jpg" alt="Post to NetVouz" /></a> <a rel="nofollow" href="http://www.newsvine.com/_tools/seed&save?u=http%3A%2F%2Fcodesplunk.com&amp;h=Programming Language Share and Review" title="Post to Newsvine"><img src="../iconss/newsvine.jpg" alt="Post to Newsvine" /></a> <a rel="nofollow" href="http://reddit.com/submit?url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Reddit"><img src="../iconss/reddit.jpg" alt="Post to Reddit" /></a> <a rel="nofollow" href="http://www.scuttle.org/bookmarks.php/maxpower?action=add&amp;address=http%3A%2F%2Fcodesplunk.com&amp;description=Programming Language Share and Review" title="Post to Scuttle"><img src="../iconss/scuttle.jpg" alt="Post to Scuttle" /></a> <a rel="nofollow" href="http://www.shadows.com/features/tcr.htm?url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Shadows"><img src="../iconss/shadows.jpg" alt="Post to Shadows" /></a> <a rel="nofollow" href="http://simpy.com/simpy/LinkAdd.do?title=Programming Language Share and Review&amp;rel="nofollow" href=http%3A%2F%2Fcodesplunk.com" title="Post to Simpy"><img src="../iconss/simpy.jpg" alt="Post to Simpy" /></a> <a rel="nofollow" href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Slashdot"><img src="../iconss/slashdot.jpg" alt="Post to Slashdot" /></a> <a rel="nofollow" href="http://www.spurl.net/spurl.php?url=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Spurl"><img src="../iconss/spurl.jpg" alt="Post to Spurl" /></a> <a rel="nofollow" href="http://technorati.com/faves?add=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Technorati"><img src="../iconss/technorati.jpg" alt="Post to Technorati" /></a> <a rel="nofollow" href="http://wists.com/r.php?c=&amp;r=http%3A%2F%2Fcodesplunk.com&amp;title=Programming Language Share and Review" title="Post to Wists"><img src="../iconss/wists.jpg" alt="Post to Wists" /></a></center>';

