
/*
* calculate needed time for given resources or
* calculate produced resources in given time
* in /game/resources
*
*
* Array Structure:
*
* // resource X (iridium: 0, holzium: 1, oxygen:  2)
*    resourceData[x]   = new Array();
*        resourceData[x][0] = ${iridiumValue};     // 0: depot
*        resourceData[x][1] = ${resources/0/prod}; // 1: production
*        resourceData[x][2] = 0;                   // 2: input
*        resourceData[x][3] = 0;                   // 3: needed time
*        resourceData[x][4] = "iridium";        // 4: field name for input
*/

function calc_resources(keyValue) {

    // choose form
    var thisForm = document.forms['resource_form'];

    // look which part is given
    switch (keyValue) {
        // the resource value is given
        case 'quantity':
            // save last changes in form
            lastChange = "quantity";
            // get input from input fields
            for (i=0;i<3;i++){
                resourceData[i][2] = parseInt(thisForm.elements[resourceData[i][4]].value);
            }
            // set wrong input to null
            for (i=0;i<3;i++){
                if (isNaN(resourceData[i][2])) {
                    resourceData[i][2] = 0;
                }
            }
            // calc all times for each resource type
            // calc with depot values
            if (thisForm.use_depot.checked == true) {
                // calc time
                for (i=0;i<3;i++){
                    resourceData[i][3] = (resourceData[i][2] - resourceData[i][0]) / resourceData[i][1];
                }
            // cals without depot values
            } else {
                for (i=0;i<3;i++){
                    resourceData[i][3] = resourceData[i][2] / resourceData[i][1];
                }
            }
            // invalid times are set to to null
            for (i=0;i<3;i++){
                if (isNaN(resourceData[i][3])) {
                    resourceData[i][3] = 0;
                }
            }
            // check production
            for (i=0;i<3;i++){
                // null production
                if (resourceData[i][1] == 0) {
                    // null time
                    resourceData[i][3] = 0;
                    // write info to form
                    thisForm.elements[resourceData[i][4]].value = "Keine Produktion";
                }
            }
            // get bigest time
            var bigestTime = 0;
            bigestTime = Math.max(resourceData[0][3],resourceData[1][3]);
            bigestTime = Math.max(bigestTime,resourceData[2][3]);

            // calc time for greates production time
            if (bigestTime >= 0) {
                var hours = Math.floor(bigestTime);
                var m = (bigestTime - hours) * 60;
                var minutes = Math.floor(m);
                var s = (m - minutes) * 60;
                var seconds = Math.floor(s);
           // on negative production time set needed time to null
            } else {
                var hours = 0;
                var minutes = 0;
                var seconds = 0;
            }
            // write result to form
            thisForm.hours.value = hours;
            thisForm.minutes.value = minutes;
            thisForm.seconds.value = seconds;
            break;

        // time is given: how many resources were produced
        case 'time':
            // save last changes in form
            lastChange = "time";

            // get given seconds
            var inputSeconds = parseInt(thisForm.seconds.value);
            // get given minutes
            var inputMinutes = parseInt(thisForm.minutes.value);
            // get given hours
            var inputHours = parseInt(thisForm.hours.value);
            // check input
            if(isNaN(inputSeconds)) {
                // wrong input is set to null
                inputSeconds = 0;
            }
            // check this input too
            if(isNaN(inputMinutes)) {
                // wrong input is set to null
                inputMinutes = 0;
            }
            // check input again
            if(isNaN(inputHours)) {
                // wrong input is set to null
                inputHours = 0;
            }

            var timeSum = (inputSeconds/3600) + (inputMinutes/60) + inputHours;
            // fill resource fields calculated with bigest time
            if (thisForm.use_depot.checked == true) {
                for (i=0;i<3;i++){
                    // null production
                    thisForm.elements[resourceData[i][4]].value = parseInt((timeSum * resourceData[i][1]) + resourceData[i][0]);
                }
            } else {
                for (i=0;i<3;i++){
                    // null production
                    thisForm.elements[resourceData[i][4]].value = parseInt(timeSum * resourceData[i][1]);
                }
            }
            break;
    }
}
/*
$(document).ready(function(){
    $("#tabContainer > ul").tabs({ cookie: { expires: 30 } });

    $(".tooltip").cluetip({
        width: 'auto',
        showTitle: false,
        // effect and speed for opening clueTips
        fx: {
            open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'
            openSpeed:  ''
        },
        // settings for when hoverIntent plugin is used
        hoverIntent: {
            sensitivity:  1,
            interval:     0,
            timeout:      0
        }
    });
    $(".info").cluetip({
        splitTitle: '|',
        showTitle:  false,
        positionBy: 'mouse',
        local:      true,
        cursor:     'auto',
        width:      'auto',
        fx: {
            open:       'fadeIn', // can be 'show' or 'slideDown' or 'fadeIn'
            openSpeed:  'slow'
        },
        // settings for when hoverIntent plugin is used
        hoverIntent: {
            sensitivity:  5,
            interval:     500,
            timeout:      0
        }
    });
});
*/

function decryptCharcode(n,start,end,offset)    {
    n = n + offset;
    if (offset > 0 && n > end)    {
    n = start + (n - end - 1);
    } else if (offset < 0 && n < start)    {
    n = end - (start - n - 1);
    }
    return String.fromCharCode(n);
}
    // decrypt string
function decryptString(enc,offset)    {
    var dec = "";
    var len = enc.length;
    for(var i=0; i < len; i++)    {
    var n = enc.charCodeAt(i);
    if (n >= 0x2B && n <= 0x3A)    {
        dec += decryptCharcode(n,0x2B,0x3A,offset);    // 0-9 . , - + / :
    } else if (n >= 0x40 && n <= 0x5A)    {
        dec += decryptCharcode(n,0x40,0x5A,offset);    // A-Z @
    } else if (n >= 0x61 && n <= 0x7A)    {
        dec += decryptCharcode(n,0x61,0x7A,offset);    // a-z
    } else {
        dec += enc.charAt(i);
    }
    }
    return dec;
}
    // decrypt spam-protected emails
function linkTo_UnCryptMailto(s)    {
    location.href = 'mailto:'+decryptString(s,-6);
}
function decryptCharcode(n,start,end,offset)    {
    n = n + offset;
    if (offset > 0 && n > end)    {
    n = start + (n - end - 1);
    } else if (offset < 0 && n < start)    {
    n = end - (start - n - 1);
    }
    return String.fromCharCode(n);
}
    // decrypt string
function decryptString(enc,offset)    {
    var dec = "";
    var len = enc.length;
    for(var i=0; i < len; i++)    {
    var n = enc.charCodeAt(i);
    if (n >= 0x2B && n <= 0x3A)    {
        dec += decryptCharcode(n,0x2B,0x3A,offset);    // 0-9 . , - + / :
    } else if (n >= 0x40 && n <= 0x5A)    {
        dec += decryptCharcode(n,0x40,0x5A,offset);    // A-Z @
    } else if (n >= 0x61 && n <= 0x7A)    {
        dec += decryptCharcode(n,0x61,0x7A,offset);    // a-z
    } else {
        dec += enc.charAt(i);
    }
    }
    return dec;
}
    // decrypt spam-protected emails
function linkTo_UnCryptMailto(s)    {
    location.href = 'mailto:'+decryptString(s,-6);
}


/* regeneriert das captcha bild*/
function regenerateCaptcha() {
    var ci = document.getElementById('captchacode');
    if(ci) {
           ci.src=ci.src+"1";
    }
}

/* don't sent form without captcha klick ;) this is called twice if actually clicked - once by input
 * and once by form */
var canSubmitLoginForm = false;
function submitLoginForm(fromCode) {
    if(fromCode) {
        canSubmitLoginForm = true;
        return true;
    }
    if(canSubmitLoginForm != true) {
        alert('Sicherheitscode vergessen?');
        return false;
    } else {
        return true;
    }
}

function start_clock(init)
{
  last=0;
  d = new Date();
  versatz = (init * 1000) - (d.getTime());
  clock();
}


function clock()
{
  d = new Date();
  var t = d.getTime() + versatz;
  d.setTime(t);
  var stunde = d.getHours();
  var mint = d.getMinutes();

  if(stunde < 10)
    stunde = '0' + stunde;


  if(mint < 10)
    mint = '0' + mint;

  var sec = d.getSeconds();

  if(sec<10)
    sec = '0' + sec;

  if(sec != last)
  {
    last = sec;
    time.innerHTML = stunde + ':' + mint + ':' + sec;
  }
  window.setTimeout('clock()',200);
}

function number_format(number,laenge,sep,th_sep)
{
  number = Math.round(number * Math.pow(10, laenge)) / Math.pow(10,laenge);
  str_number = number + '';

  arr_int = str_number.split('.');

  if (!arr_int[0])
    arr_int[0] = '0';

  if (!arr_int[1])
    arr_int[1] = '';

  if (arr_int[1].length < laenge)
  {
    nachkomma = arr_int[1];
    for (i=arr_int[1].length+1; i <= laenge; i++)
      nachkomma += '0';
    arr_int[1] = nachkomma;
  }

  if (th_sep != '' && arr_int[0].length > 3)
  {
    Begriff = arr_int[0];
    arr_int[0] = '';

    for(j = 3; j < Begriff.length ; j+=3)
    {
      Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
      arr_int[0] = th_sep + Extrakt +  arr_int[0] + '';
    }
    str_first = Begriff.substr(0, (Begriff.length % 3 == 0)?3:(Begriff.length % 3));
    arr_int[0] = str_first + arr_int[0];
  }
  return arr_int[0]+sep+arr_int[1];
}

var menge = new Array();
/**
* timer script for timers / page reload after times
* e.g.
* _initTimer('sessiontimeout',100,'Session abgelaufen',true,'läuft ab in: ');
*/
var startupDate = new Date();
var timers = {};

function _initTimer(whereDiv,duration,finalText,reload,beforeText,workboard) {
    if(typeof workboard == 'undefined') { workboard = false; }
    if(dojo.byId(whereDiv)) {
        timers[whereDiv] = {'duration':duration,'finalText':finalText,'reload':reload,'beforeText':beforeText,'workboard':workboard};
    }
    checkTimer(whereDiv);
}

function checkTimer(id) {
    var stop = false;
    if(typeof(timers[id]) != 'undefined') {
        var n = new Date();
        var seconds = timers[id]['duration'];
        var remaining = seconds -Math.round((n.getTime()-startupDate.getTime())/1000.);
        remaining = Math.round(remaining);
        var minutes = 0;
        var hours = 0;
        if(remaining<0) {
            stop = true;
            dojo.byId(id).innerHTML = (timers[id]['finalText']);
            if(timers[id]['reload']) {
                document.location.href = document.location.href;
            }
            return;
        } else if(remaining > 59) {
            minutes = Math.floor(remaining/60);
            remaining=remaining-minutes*60;
        }
        if(minutes > 59) {
            hours = Math.floor(minutes/60);
            minutes = minutes - hours*60;
        }
        if(remaining < 10) {
            remaining = "0" + remaining;
        }
        if(minutes < 10) {
            minutes = "0" + minutes;
        }
    if(timers[id]['workboard']) { dojo.byId(id).innerHTML = (timers[id]['beforeText'] +hours+':'+minutes+':'+remaining); }
        else { dojo.byId(id).innerHTML = (timers[id]['beforeText'] + minutes +':'+remaining); }
    }
    if(!stop)
        window.setTimeout('checkTimer("'+id+'");',1000);
}
/*
$(document).ready(function(){
try {
  $(".nojs_handle").hide();
  $(".js_handle").show();
  if(!slimTrade) select_prices();
  toggleTransport(false);
} catch(e) {};
});
*/

function time2string(time)
{
  var hours = Math.floor(time/3600);
  var m = (time - hours*3600);
  var minutes = Math.floor(m/60);
  var s = (m - minutes*60);
  var seconds = Math.floor(s);
  if (minutes < 10) minutes = '0' + minutes;
  if (seconds < 10) seconds = '0' + seconds;
  result = hours + ":" + minutes + ":" + seconds;
  return result;
}
function FlyTime(WhichForm)
{
  speed = 0;
  speed_start_flag = true;
  for (i=small_trans_index;i<=big_trans_index;i++)
  {
    if (WhichForm.elements["p_fleet["+i+"]"])
    {
      if (WhichForm.elements["p_fleet["+i+"]"].value > 0)
      {
        curr_speed = p_speed[i] + t_increase[p_tech[i]] * user_techs[p_tech[i]];
        if ((curr_speed < speed) || speed_start_flag)
        {
          speed_start_flag = false;
          speed = curr_speed;
        }
      }
    }
  }

  if (speed)
    return Math.round(tc_distance/speed * 3600);
  else
    return "";
}

function computeFlyingTime(id, distance)
{
  var speed = p_speed[id] + t_increase[p_tech[id]] * user_techs[p_tech[id]];
  return Math.round(distance/speed * 3600);
}

function showFlyingTime(formular, there, back)
{
  var speedThere = "";
  var speedBack = "";

  if (there)
    speedThere = time2string(computeFlyingTime(formular.up.value, tc_distance));
  if (back)
    speedBack = time2string(computeFlyingTime(formular.down.value, tc_distance));

  if (there && back)
    formular.duration.value = speedThere + " (" + speedBack + ")";
  else
    formular.duration.value = speedThere + speedBack;
}

function Capacity(WhichForm)
{
  var capacity = 0;

  for (i=small_trans_index;i<=big_trans_index;i++)
    if (WhichForm.elements["p_fleet["+i+"]"])
    {
      capacity += WhichForm.elements["p_fleet["+i+"]"].value * Math.floor(p_capacity[i] *
          Math.pow(t_increase[plane_size],user_techs[plane_size]));
    }
  if (capacity)
    return capacity;
  else
    return "";
}

function Consumption(WhichForm)
{
  var consume = 0;

  for (i=small_trans_index;i<=big_trans_index;i++)
    if (WhichForm.elements["p_fleet["+i+"]"])
    {
      consume += Math.round(600 / 1000 * p_consumption[i] * Math.pow(t_increase[consumption],user_techs[consumption]) * WhichForm.elements["p_fleet["+i+"]"].value);
    }
  if (consume)
    return 2 * Math.ceil(consume);
  else
    return "";
}

function plane_trade_consumption(formular, there, back)
{
  var consume = 0;
  if (there)
    consume += Math.round(tc_distance * p_consumption[formular.up.value] *
        Math.pow(t_increase[consumption],user_techs[consumption]) *
        formular.sends.value / 1000);
  if (back)
    consume += Math.round(tc_distance * p_consumption[formular.down.value] *
        Math.pow(t_increase[consumption],user_techs[consumption]) *
        formular.gets.value / 1000);

  if (consume)
    consume = Math.ceil(consume);
  else
    consume = "";
  formular.show_consumption.value = consume;
}

var giving = true;

function toggleTransport(enable)
{
  document.getElementById("transportBlock").className = (enable ? "open" : "close");
}

function isResource(tradeID)
{
  return  tradeID == 'iridium' ||
          tradeID == 'holzium' ||
          tradeID == 'water'   ||
          tradeID == 'oxygen';
}

function getResIndex(chosenValue)
{
  if (isResource(chosenValue))
    switch(chosenValue)
    {
      case 'iridium':
        return 0;
      case 'holzium':
        return 1;
      case 'water':
        return 2;
      case 'oxygen':
        return 3;
    }
  else
    return eval(chosenValue) + 4;
}

function getIndex(chosenFromValue, chosenToValue)
{
  var i = getResIndex(chosenFromValue);
  var j = getResIndex(chosenToValue);
  return i * (array_size) + j;
}

function show_relation()
{
  //var give_plane = false, get_plane = false;
  if (document.formular.up.value == document.formular.down.value)
  {
    document.formular.show_down.value = "";
    document.formular.show_up.value = "";
    toggleTransport(false);
    document.formular.show_consumption.value = "";
    document.formular.duration.value = "";
  }
  else
  {
    var index = getIndex(document.formular.up.value, document.formular.down.value);
    document.formular.show_up.value = prices_x[index];
    document.formular.show_down.value = prices_y[index];
    if (!isResource(document.formular.up.value) ||
        !isResource(document.formular.down.value))
    {
      toggleTransport(false);
      showFlyingTime(document.formular, !isResource(document.formular.up.value),
        !isResource(document.formular.down.value));
    }
    else
    {
      toggleTransport(true);
      document.formular.duration.value = "2 x  " + time2string(FlyTime(document.formular));
    }

    if (giving)
      show_gets();
    else
      show_give();
  }
}

function show_gets()
{
  giving = true;
  document.formular.value_source.value = "give";
  var gain;
  gain = Math.round(document.formular.sends.value) * document.formular.show_down.value / document.formular.show_up.value;
  if (gain > 0 && gain != "Infinity")
    document.formular.gets.value = Math.floor(gain);
  else
    document.formular.gets.value = "";
  if (isResource(document.formular.up.value) && isResource(document.formular.down.value))
    document.formular.show_consumption.value = Consumption(document.formular);
  else
    plane_trade_consumption(document.formular, !isResource(document.formular.up.value),
      !isResource(document.formular.down.value));
}

function show_give()
{
  giving = false;
  document.formular.value_source.value = "get";
  var gain;
    gain = Math.round(document.formular.gets.value) * document.formular.show_up.value / document.formular.show_down.value;
  if (gain > 0 && gain != "Infinity")
    document.formular.sends.value = Math.ceil(gain);
  else
    document.formular.sends.value = "";
  if (isResource(document.formular.up.value) && isResource(document.formular.down.value))
    document.formular.show_consumption.value = Consumption(document.formular);
  else
    plane_trade_consumption(document.formular, !isResource(document.formular.up.value),
      !isResource(document.formular.down.value));
}

function calculate_max_content()
{
  document.formular.duration.value = "2 x  " + time2string(FlyTime(document.formular));
  document.formular.show_max_content.value = Capacity(document.formular);
  document.formular.show_consumption.value = Consumption(document.formular);
}

function select_prices()
{
  var x = 0, y = 0, s = array_size;
  var chosen = document.showOnly.wareSelection.value;
  var give = document.showOnly.giveOrGet.value == "give";
  var name, v_close = "close", v_open = "open";
  //var name, v_close = "none", v_open = "block";
  while (x < s)
  {
    while (y < s)
    {
      if (x != y)
      {
        if (give)
          name = (x == chosen ? v_open : v_close);
        else
          name = (y == chosen ? v_open : v_close);
        document.getElementById("x" + x + "y" + y).className = name;
        //document.getElementById("x" + x + "y" + y).style.display = name;
      }
      y++;
    }
    x++;
    y = 0;
  }
}
try {

tinyMCE_GZ.init({
        plugins : 'inlinepopups,bbcodeets',
        themes : 'advanced',
        languages : 'en,de',
        disk_cache : true,
        debug : false
});

tinyMCE.init({
        theme : "advanced",
        mode : "textareas",
        plugins : "inlinepopups,bbcodeets",
        theme_advanced_buttons1 : "bold,italic,underline,undo,redo,link,unlink,image,forecolor,formatselect,removeformat,cleanup,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "bottom",
        theme_advanced_toolbar_align : "center",
        theme_advanced_blockformats : "p,blockquote",
        content_css : "css/bbcode.css",
        entity_encoding : "raw",
        add_unload_trigger : false,
        remove_linebreaks : false,
        inline_styles : false,
        convert_fonts_to_spans : false
});

} catch(e) {}

