  var landscape = true;
  var countries = null;
  var hash = null;
  var asia = new Array();
  var africa = new Array();
  var europe = new Array();
  var northAmerica = new Array();
  var southAmerica = new Array();
  var oceania = new Array();
  var quizRegion = null;
  var quiz = null;
  var questions = 3;
  
  function setup() {
    if (window.orientation != undefined) {
      landscape = window.orientation == 0;
    }
    else {
      landscape = window.innerWidth < window.innerHeight;    
    }  
    setTimeout(function() {window.scrollTo(0, 1)}, 1);
    updateMap("w", "");
    loadCountries();
    $("Loading").style.display = "none";
    $("List").style.display = "block";
  }
  
  function updateMap(region, country) {
    var area = "world";
    var index = 0;
    while (index < region.length) {
      switch(region[index++]) {
        case "a": area = "asia"; 
                  break;
        case "f": area = "africa"; 
                  break;
        case "e": area = "europe"; 
                  break;
        case "m": area = "middle_east"; 
                  break;
        case "s": area = "south_america"; 
                  break;
        case "u": area = "usa"; 
                  break;
        case "w": area = "world"; 
                  break;
        default: continue;          
      }
      break;            
    }
    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.area, country.code);
    $("MapType").innerHTML = "";
    var types = country.area;
    var count = 0;
    for (var i = 0; i < types.length; i++) {
    	var title = "World";
    	switch (types[i]) {
    	  case "a": title = "Asia";
    	            break;
    	  case "f": title = "Africa";
    	            break;
    	  case "e": title = "Europe";
    	            break;
    	  case "m": title = "Middle East";
    	            break;
    	  case "s": title = "South America";
    	            break;
    	  case "w": title = "World";
    	            break;
    	  case "u": title = "USA";
    	            break;
    	  case "n": continue;
    	            break;
    	  case "o": continue;
    	            break;
    	  case "0": continue;
    	            break;
    	  default: continue;          
    	}
    	var link = document.createElement("a");
    	$("MapType").appendChild(link);
    	if (i == 0) {
    	  link.className = "typeSelected";
    	  $("MapType").selected = link;    	  
    	}
    	else {
    	  link.className = "typeUnselected";
    	}
    	link.innerHTML = title;
    	link.type = types[i];
    	link.onclick = function() {
    	  $("MapType").selected.className = "typeUnselected";
    	  $("MapType").selected = this;
    	  this.className = "typeSelected";
    	  updateMap(this.type, country.code);
    	}
    	count++;
    }
    if (count < 2) {
      $("MapType").style.visibility = "hidden";
    }
    else {
      $("MapType").style.visibility = "visible";      
    }
  }
  
  function nextQuiz() {
    var region = quizRegion;
    var country = null;
    do {
      var index = Math.floor(Math.random() * region.length);
      if (region[index].area.indexOf("0") < 0) {
        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(region) {
    questions = Math.min(parseInt($("Questions").value), region.length);
    quizRegion = region;    
    $("QuizSection").style.display = "block";
    $("Content").style.display = "none";
    $("Score").innerHTML = "";
    $("WrongCountries").innerHTML = "";
    $("Results").style.display = "none";
    quiz = new Object();
    quiz.total = 0;
    quiz.correct = 0;
    showNextQuiz();
    setTimeout(function() {window.scrollTo(0,1)}, 1);
  }  
  
  function closeQuiz() {
    location.reload();
    $("QuizSection").style.display = "none";
    $("Content").style.display = "block";    
    setTimeout(function() {window.scrollTo(0,1)}, 1);
  }
  
  function showNextQuiz() {  
    $("MapTitle").innerHTML = "Which Country?";
    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 (this.isSolution) {
    	    this.style.color = "#80FF80";
    	    this.style.fontWeight = "bold";
    	    $("MapTitle").innerHTML = "Correct!";
    	    quiz.correct++;
    	  }
    	  else {
    	    this.style.color = "red";
    	    $("MapTitle").innerHTML = "Sorry, 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);
          };  
          $("WrongCountries").appendChild(li);
          $("Results").style.display = "block";
    	  }
   	    quiz.total++;
   	    updateScore();
    	  $("NextQuiz").style.display = "inline";    	  
    	};
    }
  }
  
  function openWikipedia(country) {
    window.open("http://en.wikipedia.org?search=" + encodeURIComponent(country) + "&go=Artikel", "_blank");
  }
  
  function updateScore() {
    $("Score").innerHTML = quiz.correct + " correct answers / " + quiz.total 
      + " questions (" + parseInt(quiz.correct / quiz.total * 100) + "%)";
  } 
  
  function loadCountries() {
    var request = new XMLHttpRequest();
    request.open("GET", "countries.csv", false);
    request.send(null);
    if (request.status == 200 || request.status == 0) {
      var lines = request.responseText.split("\n");
      countries = new Array(lines.length);
      hash = new Object();
      for (var i = 0; i < lines.length; i++) {
      	var line = lines[i];
      	var start = 0;
      	if (line[0] == '"') {
      	  start = line.indexOf('"', 1);
      	}
      	var index = line.indexOf(",", start);
      	if (index > 0) {
      	  var country = new Object();
      	  country.title = modifyTitle(line.substring(0, index));
      	  country.code = line.substring(index + 1, index + 3);
      	  country.area = "w";
      	  if (lines.length > index + 3) {
      	    country.area = line.substring(index + 4) + country.area;
      	  }
      	  countries[i] = country;
      	  hash[country.code] = country;
      	  switch (country.area[0]) {
      	    case "a": asia.push(country);
      	              break; 
      	    case "f": africa.push(country);
      	              break; 
      	    case "e": europe.push(country);
      	              break; 
      	    case "n": northAmerica.push(country);
      	              break; 
      	    case "s": southAmerica.push(country);
      	              break; 
      	    case "o": oceania.push(country);
      	              break; 
      	  }
      	}
      }
    }
  }
  
  function modifyTitle(title) {
    title = title.replace(/\"/g, "");
    var result = "";
    var words = title.toLowerCase().split(' ');
    for (var i = 0; i < words.length; i++) {
    	var word = words[i];
    	if (word.length > 0) {
    	  word = word[0].toUpperCase() + word.substring(1);
    	  result += word + " ";
    	}  
    }
    return result;
  }
  
	function orientationChanged() {
    if (window.orientation != undefined) {
      landscape = window.orientation == 0;
    }
    else {
      landscape = window.innerWidth < window.innerHeight;    
    }  
    setTimeout(function() {window.scrollTo(0,1)}, 1);
    updateMap(quiz.solution.area, quiz.solution.code);
  }
	  
  function $(id) {
    return document.getElementById(id);
  } 
  
  function tellFriend() {
    var body = "Hi,<br><br>I just stumbled upon this iPhone country quiz application:" +
        "<br><br>http://countryquiz.speedymarks.com<br><br>" +
        "Test your knowledge and see whether you can spot all countries on the map." +
        "<br><br>Best regards";
    window.open("mailto:?subject=Country Quiz on the iPhone&body=" + body, "_self");  
  }

  function debug(msg) {
    var e = document.getElementById("Debug");
    e.innerHTML += msg + "<br>";
  }
