  var landscape = false;
  var countries = null;
  var hash = null;
  var usa = new Array();
  var quiz = null;
  var isDone = false;
  var questions = 3;
  var cookie = null;
 
  function setup() {
    landscape = window.innerWidth < window.innerHeight;    
    if (window.orientation != undefined) {
      landscape = window.orientation == 0;
    }
    setTimeout(function() {window.scrollTo(0, 1)}, 1);
    updateMap("");
    loadCountries();
    cookie = new Cookie("StateQuizQuestions");
    if (cookie.get()) {
      $("Questions").value = cookie.get();
    }
    $("Loading").style.display = "none";
    $("Content").style.display = "block";
    startQuiz();
  }
  
  function updateMap(country) {
    var area = "usa";
    var chart = "http://chart.apis.google.com/chart?" 
                + "chs=" + (landscape ? "300x150" : "440x220")
                + "&chd=s:_&cht=t"
                + "&chtm=" + area 
                + "&chco=ffffff,ff0000,ff0000"
                + "&chld=" + country
                + "&chd=s:Af9"
                + "&chf=bg,s,303030"
    $("MapImage").src = chart;            
  }
  
  function selectCountry(country) {
    updateMap(country.code);
  }
  
  function nextQuiz() {
    isDone = false;
    questions = parseInt($("Questions").value);
    cookie.store("" + questions);
    var region = usa;
    var index = quiz.shuffled[quiz.nextIndex++];//Math.floor(Math.random() * region.length);
    quiz.nextIndex = quiz.nextIndex % region.length;
    var country = region[index];
    while (country == null);
    quiz.solution = country;
    var solutions = new Array(questions);
    var index = Math.floor(Math.random() * questions);
    solutions[index] = country;
    for (var i = 0; i < solutions.length; i++) {
      if (solutions[i] != null) {
        continue;
      }
      do {   	
        var exists = false;
        var index = Math.floor(Math.random() * region.length);
        for (var j = 0; j < solutions.length; j++) {
      	  if (solutions[j] == region[index]) {
      	    exists = true;
      	    break;
      	  }
      	}
      }
      while (exists);
      solutions[i] = region[index];
    }
    quiz.questions = solutions;
    return quiz;
  }
  
  function startQuiz() {
    $("Score").innerHTML = "";
    $("WrongStates").innerHTML = "";
    $("Results").style.display = "none";
    quiz = new Object();
    quiz.shuffled = new Array(usa.length);
    for (var i = 0; i < usa.length; i++) {
    	quiz.shuffled[i] = i;
    }
    shuffle(quiz.shuffled);
    quiz.nextIndex = 0;
    quiz.total = 0;
    quiz.correct = 0;
    showNextQuiz();
    setTimeout(function() {window.scrollTo(0,1)}, 1);
  }
  
  function shuffle(o) { 
   	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
   	return o;
  };
  
  function restartQuiz() {
    cookie.store($("Questions").value);
    location.reload();
  }
  
  function closeQuiz() {
    $("QuizSecion").style.display = "none";
    $("Content").style.display = "block";    
    setTimeout(function() {window.scrollTo(0,1)}, 1);
  }
  
  function showNextQuiz() {  
    $("MapTitle").innerHTML = "Which State?";
    nextQuiz();
    selectCountry(quiz.solution);
    $("Quiz").innerHTML = "";
    $("NextQuiz").style.display = "none";
    for (var i = 0; i < quiz.questions.length; i++) {
    	var question = quiz.questions[i]
    	var li = document.createElement("li");
    	$("Quiz").appendChild(li);
    	li.className = "quizEntry";
    	li.innerHTML = question.title;
    	li.country = question;
    	if (question == quiz.solution) {
    	  li.isSolution = true;
    	  $("Quiz").solution = li;
    	}  
    	li.onclick = function() {
        if (isDone) {
          //showNextQuiz();
          return;
        }
        isDone = true;
    	  if (this.isSolution) {
    	    this.style.color = "#80FF80";
    	    this.style.fontWeight = "bold";
    	    $("MapTitle").innerHTML = this.country.title + " is correct!";
    	    quiz.correct++;
    	  }
    	  else {
    	    this.style.color = "red";
    	    $("MapTitle").innerHTML = "Sorry, " + this.country.title +
    	        " is wrong!";
    	    $("Quiz").solution.style.background = "green";
    	    $("Quiz").solution.style.fontWeight = "bold";
    	    $("Quiz").solution.style.textDecoration = "blink";

    	    li = document.createElement("li");
          li.innerHTML = "<img src='wikipedia.png' width='16'>&nbsp;&nbsp;" + quiz.solution.title;          
          li.country = quiz.solution.title;
          li.onclick = function() {
            openWikipedia(this.country);
          };  
          $("WrongStates").appendChild(li);
          $("Results").style.display = "block";
    	  }
   	    quiz.total++;
   	    updateScore();
    	  $("NextQuiz").style.display = "inline";    	  
    	}
    }
  }
  
  function updateScore() {
    $("Score").innerHTML = quiz.correct + " correct answers / " + quiz.total 
      + " questions (" + parseInt(quiz.correct / quiz.total * 100) + "%)";
  } 
  
  function openWikipedia(country) {
    window.open("http://en.wikipedia.org?search=" + encodeURIComponent(country) + "&go=Artikel", "_blank");
  }
  
  function loadCountries() {
    var request = new XMLHttpRequest();
    request.open("GET", "states.txt", false);
    request.send(null);
    if (request.status == 200 || request.status == 0) {
      var lines = request.responseText.split("\n");
      usa = new Array(lines.length);
      hash = new Object();
      for (var i = 0; i < lines.length; i++) {
      	var line = lines[i];
      	var code = line.substring(0, 2);
      	var title = line.substring(3);
     	  var country = new Object();
      	country.title = title;
      	country.code = code;
      	country.area = "u";
      	usa[i] = country;
      	hash[country.code] = country;
      }
    }
  }
  
	function orientationChanged() {
    landscape = window.innerWidth < window.innerHeight;
    if (window.orientation != undefined) {
      landscape = window.orientation == 0;
    }
    //countrySelected();
    updateMap(quiz.solution.code);
    setTimeout(function() {window.scrollTo(0,1)}, 1);
  }
	  
  function $(id) {
    return document.getElementById(id);
  } 
  
  function tellFriend() {
    var body = "Hi,<br><br>I just stumbled upon this iPhone state quiz application:" +
        "<br><br>http://statequiz.speedymarks.com<br><br>" +
        "Test your knowledge and see whether you can spot all states on the map." +
        "<br><br>Best regards";
    window.open("mailto:?subject=State Quiz on the iPhone&body=" + body, "_self");  
  }

  function debug(msg) {
    var e = document.getElementById("Debug");
    e.innerHTML += msg + "<br>";
  }
