// cafe signup specific routines

// global definitions
var activetab ='who';
var tx;
var slotchanged = 0;

// DEBUG function to pop an AJAX request in an alert box
function AjaxAlert (url) {
  window.status = 'Action: ' + url;
  AjaxRequest.get( {
    'url':url,
    'onSuccess':
      function(req) {
        window.status = '';
        alert (req.responseText);
        }
    });
  };

function getCookie(name) {
  if (document.cookie.length>0) {
    start=document.cookie.indexOf(name+'=');
    if (start!=-1) {
      end=document.cookie.indexOf(";",start);
      if (end==-1) end=document.cookie.length;
      return unescape(document.cookie.substring(start+name.length+2,end));
      };
    };
  return '';
  };

function init () {
  var OK = '?OK=1';
  var browser = navigator.userAgent + " [" + navigator.appVersion + "]";
  var cookie;
  document.getElementById('browser').innerHTML = browser;
  if (navigator.cookieEnabled) {
    document.getElementById('cookies').innerHTML="Cookies Enabled";
    }
  else {
    document.getElementById('cookies').className="notice";
    document.getElementById('cookies').innerHTML="Cookies NOT Enabled!";
    OK = '';
    };
  document.getElementById('ajax').innerHTML='Waiting on Session ID...';
  AjaxRequest.get( {
    'url':'session.php' + OK,
    'onSuccess':
    function(req) {
      window.status = req.responseText;
      cookie = getCookie('PHPSESSID').toUpperCase();
      if (cookie!='') {
        document.getElementById('ajax').className='';
        document.getElementById('ajax').innerHTML=cookie;
        };
      }
    } );
  };

// boolean function tests if enter key pressed
function rtnKey(evt) {
  evt = (evt) ? evt : event;
  var code = (evt.charCode) ? evt.charCode :
    ((evt.which) ? evt.which : evt.keyCode);
  return (code==13 || code==3);
  };

// performs the tab switching for manage and worker pages. This routine
// actually only changes the style of the tabs to give the appearance of
// changing tabs. The currently active tab state is maintained in the
// global variable actvetab.
// The function requires a tab name that corresponds to a <div> with
// that ID. A respective URL must be defined in the switch statement.
// Optional params may be passed to the script.
function currenttab (tab,params) {
  // disable any scheduled tab change
  clearTimeout(tx);
  // hidden input field in tabbox holds type of request: manage or worker
  var mode = document.getElementById('usertype').value;
  // define optional params. Page type is always sent.
  if (typeof(params) == 'undefined' ) {
    params = '?type=' + mode;
    }
  else {
    params = '?type=' + mode + '&' + params;
    };
  // match a tab name with a URL
  var url;
  switch (tab) {
    case 'who': 	url='credentials.php'; break;
    case 'signup': 	url='choices.php'; break;
    case 'schedule': 	url='schedule.php'; break;
    case 'master': 	url='master.php'; break;
    case 'database': 	url='database.php'; break;
    case 'print': 	url='print.php'; break;
    case 'mail': 	url='email.php'; break;
    case 'help': 	url='help.php'; break;
    default:
      document.getElementById('tabcontents').innerHTML =
        "UNDEFINED TAB: currenttab(): '" + tab + "'";
    };
  // change tab appearances to move activetab.
  document.getElementById(activetab).className = "unselected";
  activetab = tab;
  document.getElementById(activetab).className = "selected";
  document.getElementById('tabcontents').innerHTML = "Please wait...";
  //alert ("URL: "+url+params);
  // Get contents for tab by AJAX - always loaded into same <div>
  AjaxRequest.get( {
    'url':url+params,
    'onSuccess':
      function(req) {
        document.getElementById('tabcontents').innerHTML =
          req.responseText;
        //if (activetab=='who') { jumpto(); };
        }
    });
  };

// routine to autoswitch to signup tab after successfully validated
function jumpto (tab) {
  // hidden input field in tabbox holds type of request: manage or worker
  var mode = document.getElementById('usertype').value;
  if (typeof(tab) == 'undefined' ) {
    if (mode=='manage') { tab='master'; } else { tab='signup'; };
    };
  var ok = 1;
  if (activetab=='who') {
    // user cell in credentials table holds the return status.
    // if it is 0, then user has not been authenticated don't jump
    try { ok = document.getElementById('user').innerHTML; }
    catch(err) {  };
    };
  if (ok>=1) {
    // jump to tab in 2 seconds.
    tx = setTimeout("currenttab('"+tab+"')",5000);
    };
  };

// This function calls the credentials routine for user validation.
function checkuser (who,method) {
  // hidden input field in tabbox holds type of request: manage or worker
  var mode = document.getElementById('usertype').value;
  if (mode=='manage') { jump='master'; } else { jump='signup'; };
  // get user credentials: params specify input text fields
  // method also differeniates whether a phone or password.
  var name = document.getElementById(who).value;
  var authentication = document.getElementById(method).value;
  // digest passwords so no cleartext passed across internet...
  // dvc: although it presently does not use salt.
  if (method=='pwmd5') { authentication = hex_md5(authentication); };
  var options='';
  if (method=='phone') {
    options = "&owner="+choice('member')+
      "&email="+escape(document.getElementById('email').value);
    };
  // display action message so user know is informed if it takes long.
  document.getElementById('tabcontents').innerHTML =
    "<p><em>VALIDATING CREDENTIALS: </em></p>" +
    '<p class="indent">NAME: ' + name + '<br />' +
    method.toUpperCase()+': ' + authentication + '<br />' +
    "Please Wait...</p>";
  var url = 'credentials.php?type='+mode+'&name=' + name +
      '&'+method+'='+authentication+options;
  //alert ("URL: "+url);
  // AJAX  request to authenticate and reflect status
  AjaxRequest.get( {
    'url':url,
    'onSuccess':
      function(req) {
        document.getElementById('tabcontents').innerHTML =
          req.responseText;
        jumpto();
        }
    });
  };

// Database routines...

// this function updates the form edit fields with the data from the
// last selected ID or click on an idx value
function setindex(idx) {
  // The ID list box displays current database index, idx
  // idx is not necessarily the 'selected index' of ID if there
  // are missing database id values. The 'selected index' of ID
  // is not needed except to update its display value.
  element=document.getElementsByName('ID');
  if (element.length>1) {
    // Firefox returns options list elements.
    for (i=0;i<element.length;i++) {
      if (element[i].value==idx) {
        element[i].selected=true;
        element.text = element[i].value;
        };
      };
    }
  else {
    // IE returns select element.
    element=document.getElementById('ID');
    for (i=0;i<element.options.length;i++) {
      if (element.options[i].value==idx) {
        element.selectedIndex=i;
        };
      };
    };
  // one by one get indexed field boxes and load into field boxes
  var obj_idx;
  var flist = document.getElementById('fieldlist').value.split("|");
  var debug = 'ID: ' + idx + "\n";
  for (var i = 0; i < flist.length; i++) {
    obj_idx = flist[i] +'_'+idx;
    if (idx=='NULL') {
      // null index defines a new entry so clear fields.
      document.getElementById(flist[i]).value = '';
      debug += flist[i] + ": " + "" + "\n";
      }
    else {
      document.getElementById(flist[i]).value =
        document.getElementById(obj_idx).innerHTML;
      debug += flist[i] + ": " + document.getElementById(obj_idx).innerHTML + "\n";
      };
    };
  // move focus to first input field.
  // dvc: this does not work
  if (chkd('DEBUG')) { alert(debug); };
  document.getElementById(flist[0]).focus();
  document.getElementById(flist[0]).select();
  };

// This routine implements database changes...
function dbchange() {
  var table = document.getElementById('tablename').innerHTML;
  var flist = document.getElementById('fieldlist').value.split("|");
  var id = choice('ID');
  // build the parameter string
  var params = "?change=1&table="+table+"&id="+id;
  var param;
  for (var i = 0; i < flist.length; i++) {
    param = document.getElementById(flist[i]).value;
    if (param!='') {
      params = params + "&"+flist[i]+'='+escape(param);
      };
    };
  if (chkd('DEBUG')) {
    params += "&DEBUG=1";
    alert(params);
    };
  // inform user of action
  document.getElementById('tabcontents').innerHTML =
    "Please wait...";
  //alert ("PARAMS: "+params);
  // update page contents pending change via AJAX
  AjaxRequest.get( {
    'url':'database.php'+params,
    'onSuccess':
      function(req){
        document.getElementById('tabcontents').innerHTML =
          req.responseText;
        }
    });
  };

// this function updates email list
function elist () {
  //var obj = document.getElementById(s).value;
  var params = "?action=select";
  params += "&startday=" + choice('startday');
  params += "&endday=" + choice('endday');
  // notify user of action
  document.getElementById('notification').innerHTML = "Please wait...";
  AjaxRequest.get( {
    'url':'email.php'+params,
    'onSuccess':
      function(req){
        document.getElementById('notification').innerHTML =
          req.responseText;
        }
    });
  };

// Signup actions

// this function updates the available slots as the user changes critera
function listslots () {
  //var obj = document.getElementById(s).value;
  //alert ("SELF: " + obj);
  var params = "?change=1";
  params += "&day=" + choice('DAY');
  params += "&shift=" + choice('SHIFT')
  params += "&job=" + choice('JOB')
  params += "&group=" + choice('GROUP')
  // notify user of action
  document.getElementById('openings').innerHTML = "Please wait...";
  AjaxRequest.get( {
    'url':'choices.php'+params,
    'onSuccess':
      function(req){
        document.getElementById('openings').innerHTML =
          req.responseText;
        }
    });
  };

// this commits the user signup choices
function commit () {
  var params = "action=commit";
  var checked = chkd('ck');
  var comment = document.getElementById('comment').value;
  if (checked!="") {
    params += "&ck=" + chkd('ck');
    if (comment!='') { params += "&comment=" + comment; };
    currenttab('schedule',params);
    }
  else {
    alert('You must select at least one available slot.');
    };
  };


// Print actions

// this function updates the available slots as the user changes critera
function daylist (frmt) {
  //alert ("FORMAT: "+frmt);
  if (frmt=='SHOW') { document.getElementById('date').disabled=false; return true; };
  if (frmt=='HIDE') { document.getElementById('date').disabled=true; return true; };
  document.getElementById('group').disabled= (frmt!='GRP');
  var mode = document.getElementById('usertype').value;
  var params = "?type="+mode+"&action=DAYLIST&style="+frmt;
  params += "&group=" + choice('group')
  // notify user of action
  document.getElementById('daylist').innerHTML = "Please wait...";
  AjaxRequest.get( {
    'url':'print.php'+params,
    'onSuccess':
      function(req){
        document.getElementById('daylist').innerHTML =
          req.responseText;
        }
    });
  return true;
  };


// Master schedule actions

// This function shows cell contents in the window status bar.
function peekslot (slot) {
  var params = "?peek="+slot;
  AjaxRequest.get( {
    'url':'slot.php'+params,
    'onSuccess':
      function(req){
        window.status = req.responseText;
        }
    });
  };

// This function fires a delayed event to see the contents of the cell
// in the status bar. If the cursor moves to a new cell before the delay
// then the event is cancelled and a new one invoked for the new cell.
// This cuts down on asynchronous requests made my a fast moving mouse.
// Action is inhibited while the popup window is visible.
function seeslot (slot) {
  clearTimeout(tx);
  if (!(document.getElementById('slotpopup').style.visibility=="visible")) {
    tx = setTimeout("peekslot("+slot+");",2000);
    };
  };

function positionslot (slot,corner) {
  var coords = findPos(slot);
  var hx=document.getElementById('slotpopup').offsetHeight;
  if (corner=="bottom") {
    coords[1] -= hx;
    if (coords[1]<0) { coords[1]=0; };
    };
  document.getElementById('slotpopup').style.left = coords[0]+'px';
  document.getElementById('slotpopup').style.top = coords[1]+'px';
  //document.getElementById('slotpopup').style.bottom = coords[1]+'px';
  //alert ("SLOT...\nX: "+coords[0]+"\nY: "+coords[1] + "\nH: "+ hx);
  };

// This function synthesizes a popup to view and change contents.
function popslot (slot, update) {
  clearTimeout(tx);
  // is this first time or update,
  // update=1 => refresh; update=0 => changes and closes popup.
  if (typeof(update)=='undefined') {
    update = '';
    }
  else {
    update = "&update="+update;
    };
  var params = "?pop="+slot+update;
  if (update) {
    // get the rest of the parameters
    var changes = "&owner="+choice('OWNER');
        changes += "&status="+choice('STATUS');
    // the remaining parameters may not be avaialble, if not throughs error.
    try {
      changes += "&name="+document.getElementById('name').value;
      changes += "&phone="+document.getElementById('phone').value;
      changes += "&email="+document.getElementById('email').value;
      changes += "&member="+choice('MEMBER');
      }
      catch(err) {};
    params += changes;
    };
  positionslot(slot,"top");
  document.getElementById('slotnumber').innerHTML=slot;
  document.getElementById('slotcontents').innerHTML="Please wait...";
  document.getElementById('slotpopup').style.visibility="visible";
  AjaxRequest.get( {
    'url':'slot.php'+params,
    'onSuccess':
      function(req){
        document.getElementById('slotcontents').innerHTML =
          req.responseText;
        positionslot(slot,"bottom");
        if (document.getElementById('slotflag').value) {
          // fields changed so set flag to make master update
          document.getElementById('slotindicator').innerHTML = '*';
          slotchanged = 1;
          };
        if (update=='&update=0') { closeslot(); };
        }
    });
  };

// This function closes (i.e. hides) the slotpopup window.
function closeslot () {
  document.getElementById('slotpopup').style.visibility="hidden";
  if (slotchanged) {
    slotchanged = 0;		// clear flag
    currenttab('master');	// reload the master schedule
    };
  };

