
var _URL = "http://localhost";
var _PORT = 60535;

var g_ctx = {

  "driver_login_state" : "driver",

  "driver" : "",
  "pin" : "",
  "paddle" : "",

  "current_ui" : "ui_login",

  "ui_change_timeoutid": -1,

  "bulkfare" : "",
  "bulkfare_count" : "",

  "x": ""
};

function _api_fail() {
  console.log(">>api fail");
  return true;
}

function _api_tick() { }

function _api_request(action, param, cb_ok, cb_fail, cb_neterr) {
  var idx = 0;
  var param_name = [], param_val = [];

  var req = new XMLHttpRequest();
  //var url = _URL + ":" + _PORT + "/req";
  var url =  "/req";
  var varstr = "action=" + action;

  for (var x in param) {
    param_name.push(x);
    param_val.push(param[x]);
  }

  for (var ii=0; ii<param_name.length; ii++) {
    varstr += "&" + param_name[ii] + "=" + param_val[ii];
  }

  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      if (req.status == 200) {

        var fulltxt = req.responseText;
        var resp = req.responseText.split(" ");

        if ((resp.length>=2) && (resp[0] == "ok"))  {
          if (typeof cb_ok !== "undefined") {
            cb_ok(fulltxt);
          }
          return;
        }

        if (typeof cb_fail !== "undefined") {
          cb_fail(fulltxt);
        }

      }
      else if (typeof cb_fail !== "undefined") { cb_fail(); }

    }
  };

  req.addEventListener("error", _api_fail);
  req.addEventListener("abort", _api_fail);
  //req.addEventListener("load", _api_tick);
  //req.addEventListener("progress", _api_tick);

  req.onerror = function() { console.log("network error"); };

  try {
  req.open("POST", url, true);
  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  req.send(varstr);
  } catch (er) {
    console.log(">>>>>>ERROR", er);
  }

}



function _block_status_window(ui_id) {
  var ele = document.getElementById(ui_id + "_status");
  ele.ondragstart = function() { return false; }
  ele.onselectstart = function() { return false; }
  ele.onmousedown = function() { return false; }
  ele.ondragstart = function() { return false; }

  var rect = ele.getBoundingClientRect();
  var block_ele = document.getElementById(ui_id + "_blockwindow");
  block_ele.style.width = rect.width;
  block_ele.style.height = rect.height;
  block_ele.style.bottom = rect.bottom;
  block_ele.style.left = rect.left;
  block_ele.style.top = rect.top;
  block_ele.style.right = rect.right;
  block_ele.style.x = rect.x;
  block_ele.style.y = rect.y;
}


function _switch_ui(to) {
  var ele;

  console.log(">>>to", to);

  if (g_ctx.ui_change_timeoutid > 0) {
    window.clearTimeout(g_ctx.ui_change_timeoutid);
    g_ctx.ui_change_timeoutid = -1;
  }

  var from = g_ctx.current_ui;

  ele = document.getElementById(from);
  ele.style.display = "none";

  ele = document.getElementById(to);
  ele.style.display = "block";

  g_ctx.current_ui = to;

  if ((to == "ui_main") ||
      (to == "ui_login")) {
    _block_status_window(to);
  }

}

function _hide_ui(from) {
  var ele = document.getElementById(from);
  ele.style.display = "none";
}

function _hide_ui_element(from) {
  var ele = document.getElementById(from);
  ele.style.display = "none";
}

function _show_ui(to) {
  var ele = document.getElementById(to);
  ele.style.display = "block";

  g_ctx.current_ui = to;

  // put pane over status window to prevent highlights,
  // copy/pasting, etc.
  //
  if ((to == "ui_main") ||
      (to == "ui_login")) {
    _block_status_window(to);
  }

}

function _show_ui_element(to) {
  var ele = document.getElementById(to);
  ele.style.display = "block";
}

//------------

function _clear_ui_driver() {
  var ele;

  var u = ["driver", "pin"];

  for (var i=0; i<u.length; i++) {
    g_ctx[u[i]] = "";
    ele = document.getElementById("ui_driver_" + u[i]);
    ele.innerHTML = "";
    ele.style.background = "";
  }

  ele = document.getElementById("ui_driver_pin");
  ele.style.display = "none";

  ele = document.getElementById("ui_driver_pin_text");
  ele.style.display = "none";

}

function _clear_ui_paddle() {
  g_ctx.paddle = "";
  var ele = document.getElementById("ui_paddle_paddle");
  ele.innerHTML = "";
}

function _clear_ui_bulkaccept() {
  var ele;

  g_ctx.bulkfare = "";
  ele = document.getElementById("ui_bulkaccept_faretype");
  ele.innerHTML = "";

  g_ctx.bulkfare_count = "";
  ele = document.getElementById("ui_bulkaccept_count");
  ele.innerHTML = "";
}

function _login() {
  _switch_ui('ui_driver');
  g_ctx.driver_login_state = "driver";
  _clear_ui_driver();
  _clear_ui_paddle();
}

//------------
//------------


function _verify_driver() {
  var driver = g_ctx.driver;
  var pin = g_ctx.pin;

  _api_request("driverlogin", {"driver":driver, "pin":pin}, _verify_driver_ok, _verify_driver_fail);
  return;
}

function _verify_driver_ok()      { _switch_ui("ui_paddle"); }
function _verify_driver_fail()    { _switch_ui("ui_driverincorrect");  }
function _driver_incorrect(inp)  {
  _clear_ui_driver();
  _switch_ui("ui_driver");
}

//------------

function _driver_login(inp) {

  var uvar = "";
  if (g_ctx.driver_login_state == "driver")       { uvar = "driver"; }
  else if (g_ctx.driver_login_state == "pin")     { uvar = "pin"; }
  else {
    console.log("_driver_login: ERROR: unknown driver state \"" + g_ctx.driver_login_state + "\"");
    return;
  }

  var n = g_ctx[uvar].length;

  //if (inp == 'cancel') { _switch_ui('ui_driver', 'ui_login'); }
  if (inp == 'cancel') { _switch_ui('ui_login'); }
  else if (inp == 'ok')     {

    if (uvar == "driver") {
      g_ctx.driver_login_state = "pin";

      var ele;
      ele = document.getElementById("ui_driver_driver");
      ele.style.background = "#aaaaaa";

      ele = document.getElementById("ui_driver_pin");
      ele.style.display = "block";
      ele = document.getElementById("ui_driver_pin_text");
      ele.style.display = "block";

    }
    else if (uvar == "pin") {
      g_ctx.driver_login_state = "driver";


      //_verify_driver();
      //_switch_ui("ui_driver", "ui_driververify");

      _verify_driver();
      g_ctx.ui_change_timeoutid = window.setTimeout(function() {
        _switch_ui("ui_driververify");
      }, 150);

      return;
    }

  }

  // manage adding/subtracting/clearing relevant field
  //
  else if (inp == 'bksp')   { g_ctx[uvar] = g_ctx[uvar].substr(0, n-1); }
  else if (inp == 'clr')    { g_ctx[uvar]= ""; }
  else                      { g_ctx[uvar] += inp; }

  // Pin should not be displayed on screen.
  // Use '*' to hide it.
  //
  if (uvar == "pin") {
    var n = g_ctx[uvar].length;
    var x = "";
    for (i=0; i<n; i++) { x += "*"; }
    var ele = document.getElementById('ui_driver_' + uvar);
    ele.innerHTML = x;
  }

  // Otherwise update the displayed (driver number)
  //
  else {
    var ele = document.getElementById('ui_driver_' + uvar);
    ele.innerHTML = g_ctx[uvar];
  }

}

//------------
//------------


function _verify_paddle() {
  var paddle = g_ctx.paddle;

  _api_request("paddleinput", {"paddle":paddle}, _verify_paddle_ok, _verify_paddle_fail);
  return;
}

function _verify_paddle_ok()    { _switch_ui("ui_main"); }
function _verify_paddle_fail()  { _switch_ui("ui_paddleunknown"); }
function _paddle_unknown(inp)   {
  _clear_ui_paddle();
  _switch_ui("ui_paddle");
}

//------------

function _paddle_input(inp) {
  var n = g_ctx.paddle.length;

  if (inp == 'cancel')    { _switch_ui('ui_login'); }
  else if (inp == 'ok')   {
    _verify_paddle();

    g_ctx.ui_change_timeoutid = window.setTimeout(function() {
      _switch_ui("ui_paddleverify");
    }, 150);

    return;
  }
  else if (inp == 'bksp') { g_ctx.paddle = g_ctx.paddle.substr(0, n-1); }
  else if (inp == 'clr')  { g_ctx.paddle = ""; }
  else                    { g_ctx.paddle  += inp; }

  // Otherwise update the displayed (driver number)
  //
  var ele = document.getElementById('ui_paddle_paddle');
  ele.innerHTML = g_ctx.paddle;
}

//-------------
//-------------
//-------------

function _main_prv() {
  console.log("prv");
  _api_request("prevstop");
}

function _main_nxt() {
  console.log("nxt");
  _api_request("nextstop");
}

function _fare_adult() {
  console.log("fare adult");
  _api_request("fare", {"fare":"adult","count":1});
}

function _fare_youth() {
  console.log("fare youth");
  _api_request("fare", {"fare":"youth","count":1});
}

function _fare_half() {
  console.log("fare half");
  _api_request("fare", {"fare":"half","count":1});
}

function _fare_bike() {
  console.log("fare bike");
  _api_request("fare", {"fare":"bike","count":1});
}

function _fare_wheelchair() {
  console.log("fare wheelchair");
  _api_request("fare", {"fare":"wheelchair","count":1});
}

function _fare_transfer() {
  console.log("fare transfer");
  _api_request("fare", {"fare":"transfer","count":1});
}

//-------------
//-------------
//-------------

function _main_bulk() {
  _show_ui_element("ui_bulk_misc_tab");
  _hide_ui_element("ui_bulk_passes_tab");
  _switch_ui("ui_bulk");
}

function _main_menu() {
  _switch_ui("ui_fareoverride");
}

//-------------
//-------------
//-------------


function _bulkaccept_ok() {
  console.log("bulkfare:", g_ctx.bulkfare, ", count:", g_ctx.bulkfare_count);
  _switch_ui("ui_main");

  _api_request("fare",{"fare":g_ctx.bulkfare,"count":g_ctx.bulkfare_count});
}

function _bulkaccept_cancel() {
  _switch_ui("ui_main");
}

function _bulkaccept_input(inp) {
  var n = g_ctx.bulkfare_count.length;

  if (inp == 'cancel')    { _switch_ui('ui_main'); }
  else if (inp == 'ok')   { _bulkaccept_ok(); return; }
  else if (inp == 'bksp') { g_ctx.bulkfare_count = g_ctx.bulkfare_count.substr(0, n-1); }
  else if (inp == 'clr')  { g_ctx.bulkfare_count = ""; }
  else                    { g_ctx.bulkfare_count += inp; }

  // Otherwise update the displayed (driver number)
  //
  var ele = document.getElementById('ui_bulkaccept_count');
  ele.innerHTML = g_ctx.bulkfare_count;
}


//-------------
//-------------
//-------------

function _cb_status(inp) {
  //console.log("_cb_status>>\n", inp);

  var fields = inp.substr(3).split(";");
  var fv = {};

  for (var ii=0; ii<fields.length; ii++) {
    var kv = fields[ii].split("=");
    fv[kv[0]] = kv[1];
  }

  //for (var x in fv) { console.log(x, ";;;", fv[x]); }


}

function _cb_status_err(e) {
  console.log("ERROR: _cb_status_err:", e);
}

//-------------
//-------------
//-------------

function init() {

  // login
  //
  document.getElementById('ui_login_login').onclick = _login;
  document.getElementById('ui_driverincorrect_btn').onclick = _driver_incorrect;
  document.getElementById('ui_paddleunknown_btn').onclick = _paddle_unknown;;

  // main menu buttons
  //
  document.getElementById('ui_main_prv').onclick = _main_prv;
  document.getElementById('ui_main_nxt').onclick = _main_nxt;

  document.getElementById('ui_main_bulk').onclick = _main_bulk;
  document.getElementById('ui_main_menu').onclick = _main_menu;

  var simple_fares   = [ "adult", "youth", "half", "bike", "wheelchair", "transfer"];
  var simple_fares_f = [ _fare_adult, _fare_youth, _fare_half, _fare_bike, _fare_wheelchair, _fare_transfer];
  for (var ii=0; ii<simple_fares.length; ii++) {
    var fare = simple_fares[ii];
    document.getElementById('ui_main_' + fare).onclick = simple_fares_f[ii];
  }

  // bulk menu buttons
  //
  document.getElementById('ui_bulk_passes').onclick =
    function() {
      var ele;
      ele = document.getElementById("ui_bulk_misc");
      ele.classList.remove("highlight");
      ele = document.getElementById("ui_bulk_passes");
      ele.classList.add("highlight");

      _hide_ui_element("ui_bulk_misc_tab");
      _show_ui_element("ui_bulk_passes_tab");
    };

  document.getElementById('ui_bulk_misc').onclick =
    function() {
      var ele;
      ele = document.getElementById("ui_bulk_misc");
      ele.classList.add("highlight");
      ele = document.getElementById("ui_bulk_passes");
      ele.classList.remove("highlight");


      _show_ui_element("ui_bulk_misc_tab");
      _hide_ui_element("ui_bulk_passes_tab");
    };

  document.getElementById('ui_bulk_menu').onclick = function() { _switch_ui("ui_main"); }

  var bulk_pass = ["adult", "youth", "half", "event", "transfer", "interline",
                    "schoola", "schoolb", "schoolc", "orga", "orgb", "orgc"];
  var bulk_pass_name = ["Adult Cash", "Youth Cash", "Half Cash", "Special Event", "Transfer", "Interline",
                        "School A", "Sschool B", "School C", "Org A", "Org B", "Org C"];
  for (var i=0; i<bulk_pass.length; i++) {
    var p = bulk_pass[i];
    var u = bulk_pass_name[i];
    var ele = document.getElementById('ui_bulk_' + p);
    ele.onclick = (function(x,y) {
      return function() {
        _clear_ui_bulkaccept();
        g_ctx.bulkfare = x;
        _switch_ui("ui_bulkaccept");
        var ee = document.getElementById("ui_bulkaccept_faretype");
        ee.innerHTML = y;
      };
    })(p, u);
  }


  // bulk accept fares
  //
  document.getElementById('ui_bulkaccept_ok').onclick = _bulkaccept_ok;
  document.getElementById('ui_bulkaccept_cancel').onclick = _bulkaccept_cancel;


  // fareoverride menu buttons
  //
  document.getElementById('ui_fareoverride_passes').onclick =
    function() {
      var ele;
      ele = document.getElementById("ui_fareoverride_misc");
      ele.classList.remove("highlight");
      ele = document.getElementById("ui_fareoverride_passes");
      ele.classList.add("highlight");

      _hide_ui_element("ui_fareoverride_misc_tab");
      _show_ui_element("ui_fareoverride_passes_tab");
    };

  document.getElementById('ui_fareoverride_misc').onclick =
    function() {
      var ele;
      ele = document.getElementById("ui_fareoverride_misc");
      ele.classList.add("highlight");
      ele = document.getElementById("ui_fareoverride_passes");
      ele.classList.remove("highlight");

      _show_ui_element("ui_fareoverride_misc_tab");
      _hide_ui_element("ui_fareoverride_passes_tab");
    };

  document.getElementById('ui_fareoverride_menu').onclick = function() { _switch_ui("ui_main"); }
  document.getElementById('ui_fareoverride_logout').onclick =
    function() {
      _api_request("logout");
      _switch_ui("ui_login");
    }

  var override_pass = [ "adult", "youth", "half",
                        "bike", "wheelchair", "transfer",
                        "event", "interline",
                        "schoola", "schoolb", "schoolc",
                        "orga", "orgb", "orgc" ];
  for (var i=0; i<override_pass.length; i++) {
    var p = override_pass[i];
    var ele = document.getElementById("ui_fareoverride_" + p);
    ele.onclick = (function(x) {
      return function() { _api_request("fare", {"fare":x,"count":1}); };
    })(p);
  }


  var ui_page = [ "driver", "paddle", "bulkaccept" ];
  var ui_func = [ _driver_login, _paddle_input, _bulkaccept_input ];

  for (var idx=0; idx<ui_page.length; idx++) {

    var c = ui_page[idx];
    var f = ui_func[idx];

    for (var i=0; i<=9; i++) {
      document.getElementById('ui_' + c + '_' + i).onclick =
        (function(_f, x) { return function() { _f(x); } })(f, i);
    }
    document.getElementById('ui_' + c + '_' + 'bksp').onclick =
      (function(_f,x) { return function() { _f(x); } })(f, 'bksp');
    document.getElementById('ui_' + c + '_' + 'clr').onclick =
      (function(_f,x) { return function() { _f(x); } })(f, 'clr');
    document.getElementById('ui_' + c + '_' + 'ok').onclick =
      (function(_f,x) { return function() { _f(x); } })(f, 'ok');
    document.getElementById('ui_' + c + '_' + 'cancel').onclick =
      (function(_f,x) { return function() { _f(x); } })(f, 'cancel');

  }

  // set interval to check status every 1 second
  //
  var x = window.setInterval(function() { _api_request("status", {}, _cb_status, _cb_status_err); }, 1000);
  console.log(">>>", x);

  // try and reduce textarea highlighting, drag and drop/copy pasting,
  // and other bad behavor.
  //
  var ele;
  var block_ele;
  var rect;

  ele = document.getElementById("ui_login_status");
  ele.ondragstart = function() { return false; }
  ele.onselectstart = function() { return false; }
  ele.onmousedown = function() { return false; }
  ele.ondragstart = function() { return false; }

  rect = ele.getBoundingClientRect();
  block_ele = document.getElementById("ui_login_blockwindow");
  block_ele.style.width = rect.width;
  block_ele.style.height = rect.height;
  block_ele.style.bottom = rect.bottom;
  block_ele.style.left = rect.left;
  block_ele.style.top = rect.top;
  block_ele.style.right = rect.right;
  block_ele.style.x = rect.x;
  block_ele.style.y = rect.y;


  ele = document.getElementById("ui_main_status");
  ele.ondragstart = function() { return false; }
  ele.onselectstart = function() { return false; }
  ele.onmousedown = function() { return false; }
  ele.ondragstart = function() { return false; }

  rect = ele.getBoundingClientRect();
  block_ele = document.getElementById("ui_main_blockwindow");
  block_ele.style.width = rect.width;
  block_ele.style.height = rect.height;
  block_ele.style.bottom = rect.bottom;
  block_ele.style.left = rect.left;
  block_ele.style.top = rect.top;
  block_ele.style.right = rect.right;
  block_ele.style.x = rect.x;
  block_ele.style.y = rect.y;


}

init();
