/*
Copyright (c) 2009, Max Froumentin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * The name of this source code's contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var g_questionLang, g_answerLang, g_prefix, g_nbCards, g_n;
var g_intervalInSeconds=5;
var g_mode="both";
var g_userAnswer=document.getElementById('userAnswer');
var g_intervalElement=document.getElementById('interval');
var g_modeElement=document.getElementById('mode');
var g_questionsElement=document.getElementById('questions');
var g_settingsElement=document.getElementById('settings');
var g_timeout;
var g_message=document.getElementById('message');
var g_question=document.getElementById('question');
var g_answer=document.getElementById('answer');

function run()
{
  var intervalOption, intervalPref='', modePref;
  if (window.widget)
  {
     // this is a widget, so retrieve preferences using widget preferences
    intervalPref = widget.preferenceForKey('intervalInSeconds');
    modePref = widget.preferenceForKey('mode');
  }
  else
  {
    // this is a web page, so get preferences from cookies
    intervalPref = readCookie('intervalinseconds');
    modePref = readCookie('mode');
  }

  g_intervalInSeconds = (intervalPref && intervalPref!='')?parseInt(intervalPref):5;
  intervalOption = document.getElementById("i"+g_intervalInSeconds);
  intervalOption.selected=true;

  g_mode=(modePref && (modePref == '2to1' || modePref == '1to2' || modePref == 'both'))?modePref:'both';
  document.getElementById('m'+g_mode).selected=true;


    g_nbCards=g_cards.words.length;
    document.getElementById("m1to2").innerHTML=g_cards.languages[0]+" to "+g_cards.languages[1];
    document.getElementById("m2to1").innerHTML=g_cards.languages[1]+" to "+g_cards.languages[0];
    document.getElementById("subtitle").innerHTML=g_cards.title;
    document.getElementById("freq").innerHTML=intervalOption.text;
    switch (g_mode)
    {
        case "1to2": g_questionLang=0; break;
        case "2to1": g_questionLang=1; break;
    }
    g_prefix=g_cards.languages[g_questionLang];
    g_answerLang=1-g_questionLang;
    document.getElementById("themode").innerHTML = (g_mode=="both") ? "both" :
    g_cards.languages[g_questionLang]+" to "+g_cards.languages[g_answerLang];

    ask();
}

function ask()
{
    var questionText="n/a";
    var n;

    clearTimeout(g_timeout);

    if (g_mode=="both")
    {
        g_questionLang = Math.floor(2*Math.random());
        g_answerLang=1-g_questionLang;
        g_prefix=g_cards.languages[g_answerLang];
    }

    // find a random question
    while (questionText==="n/a")
    {
        n = Math.floor(g_nbCards * Math.random());
        questionText=g_cards.words[n][g_questionLang];
    }
    g_question.innerHTML="<p>What's "+g_cards.languages[g_answerLang]+" for:</p><p id='questionText'><em>"+questionText+"</em></p>";
    g_answer.style.display="none";
    g_answer.innerHTML="<p id='answerText'><em>"+g_cards.words[n][g_answerLang]+"</em></p>";

  (window.widget) ? widget.getAttention() : alert("What's "+g_cards.languages[g_answerLang]+" for: \n'"+questionText+"'");
}

function showMessage(text)
{
    g_message.innerHTML="<p>"+text+"</p>";
    setTimeout('message.innerHTML=""',3000);
}

function showAnswer()
{
    g_answer.style.display="block";
    g_timeout=setTimeout(ask,g_intervalInSeconds*1000);
}

function updateSettings()
{
    g_intervalInSeconds=g_intervalElement[g_intervalElement.selectedIndex].value;
    g_mode=g_modeElement[g_modeElement.selectedIndex].value;

  // save preferences
  if (window.widget)
  {
    // either in the widget storage
    widget.setPreferenceForKey(g_intervalInSeconds, 'intervalInSeconds');
    widget.setPreferenceForKey(g_mode, 'mode');
  }
  else
  {
    // or as a cookie
    createCookie("intervalinseconds",g_intervalInSeconds);
    createCookie("mode",g_mode);
  }

    g_settingsElement.style.display = "none";
    g_questionsElement.style.display = "block";
    clearTimeout(g_timeout);
    run();
}

function toggleSettings()
{
    if (g_settingsElement.style.display=="none")
    {
        g_settingsElement.style.display =  "block";
        g_questionsElement.style.display = "none";
    }
    else
    {
      g_settingsElement.style.display = "none";
      g_questionsElement.style.display = "block";
    }
}

/* cookie functions from PPK: http://www.quirksmode.org/js/cookies.html */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

