var elements_with_popups = [];
var timerID = false;
var text_to_reveal = '';


document.observe("dom:loaded", function() {
  init_money_spinners();
  init_revealing_text();
});

function secs_to_time(seconds,asshort) {
  seconds = Math.ceil(seconds);
  if (asshort) {
    if (seconds < 60)
      return ""+seconds+" Sek.";
    else
      return ""+Math.floor(seconds / 60)+":" + (seconds % 60 < 10 ? "0"+seconds % 60 : seconds%60);
  }
  if (seconds < 60)
    return ""+seconds+" Sekunden";
  else if (seconds < 3600)
    return ""+Math.floor(seconds / 60)+":" + (seconds % 60 < 10 ? "0"+seconds % 60 : seconds%60) + " Minuten";
  else {
    var hours = Math.floor(seconds / 3600);
    var mins = Math.floor(seconds % 3600 / 60);
    return ""+hours+" Stunden und "+mins+" Minuten";
  }


}


var elements_to_reveal = []
var texts_to_reveal = []
var reveal_done = false;


function add_recursivly_to_reveal_list(element) {

  if (element.nodeType == Node.ELEMENT_NODE && element.nodeName != 'BR') {
    // When we hide the elemets here discovering them later does not work properly.
    // I'm not sure which elements are the problems but at least B,I and P do not work.
    // As we mostly use those elements and not other elements in quests I disabled it totaly for now.
    //$(element).hide();
  }
  elements_to_reveal.push(element)
  if (element.nodeType == Node.TEXT_NODE) {
    texts_to_reveal.push(element.data)
    element.data = '';
  }
  else texts_to_reveal.push('')
  if (element.nodeType != Node.ELEMENT_NODE) return;

  var i
  var childs = element.childNodes
  for (i = 0; i < childs.length; i++) {
    add_recursivly_to_reveal_list(childs[i])
  }
}

function init_revealing_text() {
  
  var text_elm = $$('.reveal_text').first();
  if (!text_elm) return;
  $$('.after_reveal_text').each(Element.hide);
  text_elm.style.height = text_elm.getHeight() + 'px';
  $$('.reveal_text').each(add_recursivly_to_reveal_list);

  text_elm.up().observe('click', instant_reveal);
  reveal_a_character();
}

function instant_reveal() {
  var i
  if (reveal_done) return;
  reveal_done = true;
  for(i=0;i<elements_to_reveal.length;i++) {
    if (elements_to_reveal[i].nodeType == Node.ELEMENT_NODE) $(elements_to_reveal[i]).appear();
    else {
      elements_to_reveal[i].data += texts_to_reveal[i]
    }
  }
  $$('.after_reveal_text').each(Element.appear);

}

function reveal_a_character() {
  if (reveal_done) return;
  if (elements_to_reveal[0].nodeType == Node.ELEMENT_NODE) {
    $(elements_to_reveal[0]).show();
  }
  if (texts_to_reveal[0] == '') {
    texts_to_reveal.shift();
    elements_to_reveal.shift();
  }
  if (texts_to_reveal.length == 0 && elements_to_reveal.length == 0) {
    $$('.after_reveal_text').each(Element.appear);
    reveal_done = true;
    return;
  }
  var c = texts_to_reveal[0].slice(0,1);
  texts_to_reveal[0] = texts_to_reveal[0].slice(1);

  elements_to_reveal[0].data += c;

  window.setTimeout(reveal_a_character, c == ' ' ? 0 : 1);

}

function init_money_spinners() {
  $$('input.moneychooser').each(function(elm) {
    //elm.observe('change', function() {update_moneyspinner_for(elm)})
    update_moneyspinner_for(elm);

    add_observer_to_spinner_button(elm, elm.name+'_g_p', 10000);
    add_observer_to_spinner_button(elm, elm.name+'_s_p', 100);
    add_observer_to_spinner_button(elm, elm.name+'_c_p', 1);
    add_observer_to_spinner_button(elm, elm.name+'_g_m', -10000);
    add_observer_to_spinner_button(elm, elm.name+'_s_m', -100);
    add_observer_to_spinner_button(elm, elm.name+'_c_m', -1);

  });
}

function add_observer_to_spinner_button(input, elmname, amount) {
  $(elmname).observe('mousedown', function(event) {
    start_money_updating(input,amount,0,10000000);
  });
  $(elmname).observe('mouseup', function(event) {
    stop_money_updating();
  });
  $(elmname).observe('mouseout', function(event) {
    stop_money_updating();
  });
}

function start_money_updating(elm, amount, counter, max) {
  var t = 200;
  if (counter > 3) t = 100;
  if (counter > 8) t = 50;
  if (counter > 13) t = 25;
  if (counter > 99) t = 10;

  elm.value = Math.min(Math.max(parseFloat(elm.value, 10)+amount,0),max);
  update_moneyspinner_for(elm);

  timerID = setTimeout(function() {start_money_updating( elm, amount, counter+1, max);}, t);
}

function stop_money_updating() {
  if (timerID) clearTimeout(timerID);
}

function update_moneyspinner_for(elm) {
  elm = $(elm);
  var val = elm.value;
  var coppers = val % 100;
  var silver = Math.floor((val % 10000) / 100);
  var gold = Math.floor(val / 10000);
  $(elm.name + '_g').innerHTML = gold;
  $(elm.name + '_s').innerHTML = silver;
  $(elm.name + '_k').innerHTML = coppers;
}

function init_form_defaults() {
  var active_color = '#000'; // Colour of user provided text
  var inactive_color = '#999'; // Colour of default text

  Event.observe( window, 'load', function () {
    var default_values = new Array();
    $$("input.defaults").each( function (s) {
      $(s).setStyle({color: inactive_color});
      $(s).observe( 'focus', function () {
        if (!default_values[s.id]) {
          default_values[s.id] = s.value;
        }
        if (s.value == default_values[s.id]) {
          s.value = '';
          $(s).setStyle({color: active_color});
        }
        $(s).observe( 'blur', function () {
          if (s.value == '') {
            $(s).setStyle({color: inactive_color});
            s.value = default_values[s.id];
          }
        });
      });
    });
  });

}


function post(url, params) {
  if (typeof(params) != 'String') params = params.toQueryString();
  new Ajax.Request(url, {
    asynchronous:true, evalScripts:true, parameters:params + '&authenticity_token=' + encodeURIComponent(window._token)
  });
}

function isdefined( variable)
{
  return (typeof(window[variable]) == "undefined")?  false: true;
}

function post_to(url) {
  var f = document.createElement('form');
  f.style.display = 'none';
  f.method = 'POST';
  f.action = url;

  var m = document.createElement('input');
  m.setAttribute('type', 'hidden');
  m.setAttribute('name', 'authenticity_token');
  m.setAttribute('value', window._token);

  document.body.appendChild(f);

  f.appendChild(m);
  f.submit();
}

var ajax_running = 0;

function show_ajax_spinner(){
  if(ajax_running++ == 0){
    $('ajax_spinner').show();
  }
}
function hide_ajax_spinner(){
  if(--ajax_running == 0 ){
    $('ajax_spinner').hide();
  }
}
