<?php 

class formDataHandler {
  private $scope;
  private $position;
  private $label;
  private $formDefs;
  private $confirmModal;

  public function __construct ($entry) {
    if (isset($entry)) {
      $this->scope    = $entry->scope;
      $this->selectId = $entry->selectId;
      $this->headText = $entry->headText;
      $this->bodyText = $entry->bodyText;
      $this->disabled = $entry->disabled;
      $this->iterator = $entry->iterator;
      $this->label    = $entry->label;
      $this->defLab   = explode ("_", $entry->label)[0];
      
      if (isset($entry->panelLevel))
         $this->panelLevel = $entry->panelLevel;
      else
        $this->panelLevel = "";


      if (isset($entry->summaryTable))
        $this->summaryTable = $entry->summaryTable;
      else
        $this->summaryTable = "";

      if (isset($entry->imageCapture))
        $this->imageCapture = $entry->imageCapture;
      else
        $this->imageCapture = "";

      if (null !== $entry->formDefs)
        $this->formDefs = json_encode($entry->formDefs);
      else
        $this->formDefs = '{}';
//$cnt = count($this->formDefs);
//print_r ("vcnt:$cnt");     

      if (null !== $entry->formAlts)
        $this->formAlts = json_encode($entry->formAlts);
      else
        $this->formAlts = '{}';

      if (isset($entry->formData)) {
        $this->formData = json_encode($entry->formData);
      }
      if (isset($entry->selectId))
        $this->selectId = $entry->selectId;
      else
        $this->selectId = 0;

      if (isset($entry->summaryId))
        $this->summaryId = $entry->summaryId;
      else
        $this->summaryId = 0;

      if (isset($entry->filterId))
        $this->filterId = $entry->filterId;
      else
        $this->filterId = 0;

      if (isset($entry->position) && $entry->position == "left")
        $this->position = "left";
      else
        $this->position = "right";
    
      if (isset($entry->confirmModal)) 
        $this->confirmModal = $entry->confirmModal;
      else
        $this->confirmModal = 0;

//      $this->comSelectId = "";
//      if (null !== $entry->comSelectId) {
//        $controls = explode(",", $entry->comSelectId);
//        for ($i=0; $i<count($controls); $i++) {
//          $this->comSelectId .= "com" . $controls[$i] . "(msgContent); ";
//        }
//      }    
    }
  }
  
  public function outputLayout() {
  
$html = "

<button id='fdh$this->iterator' class='btn btn-inverse' value='$this->label' 
  onclick='processForm$this->scope();' style='float:$this->position;'>
  $this->defLab
</button>

    ";
  	return $html;
  }
  
  public function outputScript() {
		
    $script = "

if (multiFunction === undefined)
  var multiFunction = [];

var formDefs$this->scope  = JSON.parse('$this->formDefs');
var formAlts$this->scope  = JSON.parse('$this->formAlts');
var formData$this->scope  = $this->formData;
var filterId$this->scope  = $this->filterId;
var summaryId$this->scope = $this->summaryId;
var selectId$this->scope  = '$this->selectId';
var msgSource$this->scope;

$(document).ready(function() {

  if (selectId$this->scope > 0) {
    var msgContent = [];
    msgContent.selectId = [selectId$this->scope,'', 'selectId', '$this->scope', 'page entry'];
    newValue$this->iterator (msgContent);
  }
  else if (selectId$this->scope > 0)
    row$this->scope (selectId$this->scope);
  else
    setForm$this->scope (0, formDefs$this->scope);
});

function processForm$this->scope () {
  document.getElementById('valmsg$this->scope').innerHTML = '';
  var valid$this->scope = [];
  valid$this->scope.fields = 'summaryid=' + summaryId$this->scope;
  valid$this->scope.message = '';
  valid$this->scope.mandatoryCheck = false;
  valid$this->scope.uniqueCheck = false;
  valid$this->scope.confirmCheck = false;
  
  var ampersand = '';
  var dash = '';
  
  for (var i=0; i < formData$this->scope.length; i++) {

//alert (formData$this->scope[i]['field'] + ' m:' + formData$this->scope[i]['mandatory']
//       + ' t:' + formData$this->scope[i]['uniquekey'] +  ' c:' + formData$this->scope[i]['confirm'] 
//       + ' db:' + formData$this->scope[i]['dbvalue'] + ' new:' + formData$this->scope[i]['newvalue']);
       
    if (formData$this->scope[i]['mandatory'] == 1 
        && formData$this->scope[i]['newvalue'] == 0) {
      valid$this->scope.message += dash + 'Missing ' + formData$this->scope[i]['label'];
      dash = '&#8212';
      valid$this->scope.mandatoryCheck = true;
    }
    if (formData$this->scope[i]['uniquekey'] == 1) {
 
      valid$this->scope.fields += '&' + formData$this->scope[i]['dbcolumn'] +
                '=' + formData$this->scope[i]['newvalue'];

      if (formData$this->scope[i]['dbvalue'] != formData$this->scope[i]['newvalue'])
        valid$this->scope.uniqueCheck = true;
    }
    if (formData$this->scope[i]['confirm'] == 1 && formData$this->scope[i]['dbvalue'] != 0 && formData$this->scope[i]['dbvalue'] != formData$this->scope[i]['newvalue']) {
      valid$this->scope.confirmCheck = true;
    }
  }
  
  submit$this->scope (valid$this->scope);
}

function submit$this->scope (valid) {

//alert(valid.mandatoryCheck + ' ' + valid.uniqueCheck + ' ' +  valid.confirmCheck + ' ' + valid.message);

  if (!(valid.mandatoryCheck || valid.uniqueCheck || valid.confirmCheck))
    put$this->scope ();
  else if (valid.mandatoryCheck)
    document.getElementById('valmsg$this->scope').innerHTML = valid.message;
  else if (valid.uniqueCheck && valid.message == '') {
    key$this->scope (valid);
  }
  else if (valid.uniqueCheck) {
    document.getElementById('valmsg$this->scope').innerHTML = valid.message;
  }
  else if (valid.confirmCheck)
    $('#cnfModal$this->iterator').modal('show'); 
}

function confirm$this->iterator (okay) {
  if (okay)    
    put$this->scope ();
}

function isEmpty(obj) {
  for(var key in obj) {
    if (obj.hasOwnProperty(key))
      return false;
  }
  return true;
}

function com$this->iterator (message) {

  var key = Object.keys(message); 
logMessage ('<td>' +  message[key][3] + '</td><td>$this->scope</td><td>' + key +  '</td><td>' + message[key][0] + '</td><td>' + message[key][2] + '</td><td>' + message[key][4] + '</td>');  

  if (key == 'selectId') {
    selectId$this->scope = message[key][0];

    if (selectId$this->scope > 0) {
      $('#del$this->iterator').prop('disabled', false);
      $('#fdh$this->iterator').html($('#fdh$this->iterator').prop('value').split('_')[1]);
      $('.tog$this->iterator').prop('disabled', false);
    }

    else {
      $('#del$this->iterator').prop('disabled', true);
      $('#fdh$this->iterator').html($('#fdh$this->iterator').prop('value').split('_')[0]);
      $('.tog$this->iterator').prop('disabled', true);
      $('[class^=$this->panelLevel]').each(function(){ $(this).slideUp('slow'); });
    }

    row$this->iterator (message[key][0]);

  }
  
  else if (key == 'summaryId') {
    summaryId$this->scope = message[key][0];
  }    
}

multiFunction['com$this->scope'] = {
  com$this->iterator: com$this->iterator
}; 

function newValue$this->scope (message) {
  var key = Object.keys(message);
  msgSource$this->scope = message[key][3];
logMessage ('<td>' +  message[key][3] + '</td><td>$this->scope</td><td>' + key +  '</td><td>' + message[key][0] + '</td><td>' + message[key][2] + '</td><td>' + message[key][4] + '</td>'); 
  for (var i=0; i < formData$this->scope.length; i++) {
alert ('new:' + key +  ':' + message[key][0] + ' ' + message[key][1] + ' ' + formData$this->scope[i]['field']);    
    if (formData$this->scope[i]['field'] == key) {
      formData$this->scope[i]['newvalue'] = message[key][0];
      formData$this->scope[i]['newtext'] = message[key][1];

      if (formData$this->scope[i]['action'] == 'sendid') {
        var noUpdate = true;
        if (message[key][3] == '$this->iterator')
          noUpdate = false;
        sendMessages$this->scope ('{' + formData$this->scope[i]['sequent'] + '}', message[key][0], message[key][1], noUpdate);
      }    
      else if (formData$this->scope[i]['action'] == 'switch') 
        switchForm$this->scope ('{' + formData$this->scope[i]['sequent'] + '}', message[key][0], message[key][1]);
      else if (formData$this->scope[i]['action'] == 'commit')
        processForm$this->scope();
      else if (formData$this->scope[i]['action'] == 'timetype')
        calcTime$this->scope (formData$this->scope[i]['sequent']);
    }
  }    
}

function sendMessages$this->scope (sendIds, value, text, noUpdateId) {
  var sendIdsArray = (new Function('return [' + sendIds + '];')());
  var props = Object.keys(sendIdsArray[0]);
//alert ('$this->scope prop:' + props);
  for (j=0; j<props.length; j++) {
alert ('prop:' + props[j] + ' ' + sendIdsArray[0][props[j]] + ' ' + value + ' ' + noUpdateId);
//alert (props[j]);
    if (!(sendIdsArray[0][props[j]] == 'updateId' && noUpdateId)) {
      var comField = 'com' + props[j]; 
      comFunction = comField + '';
      var msgContent = [];
      msgContent[sendIdsArray[0][props[j]]] = [value, text, sendIdsArray[0][props[j]], msgSource$this->scope, 'send id'];
//logMessage ('<td>$this->scope</td><td>' +  keyField + '</td><td>' + keyField + '</td><td>' + message[key][0] +  '</td><td>' + 'sendIdsArray[0][props[j]]' + '</td><td>send id</td>');  
      multiFunction[comField][comFunction] (msgContent);
    }
  }
}

function switchForm$this->scope (switches, value, text) {
  var switchsArray = (new Function('return [' + switches + '];')());
  var props = Object.keys(switchsArray[0]);
//alert ('$this->scope prop:' + props);
//  for (j=0; j<props.length; j++) {
//alert ('value:' + value + ' prop:' + props[j] + ' ' + switchsArray[0][props[j]]);
//alert (props[j]);
    if (value == 0)
      setForm$this->scope(0, formDefs$this->scope);
    else
      setForm$this->scope(0, formAlts$this->scope);
    
//  }    
}

function calcTime$this->scope (type) {

  if (type == 'D') {
    for (i=0; i < formData$this->scope.length; i++) {
      if (formData$this->scope[i]['action'] == 'timetype') {
        var timeType = formData$this->scope[i]['sequent']
        if (timeType == 'S' || timeType == 'E' || timeType == 'B') {
          formData$this->scope[i]['newvalue'] = '00:00';        
          var setField = 'set' + formData$this->scope[i]['field']; 
          setFunction = setField + '';
//logMessage ('<td>$this->scope</td><td>' +  setField + '</td><td>' + setField + '</td><td>' + dbResult[column] +  '</td><td>' + setType + '</td><td>set form field</td>');  
          multiFunction[setField][setFunction] ('00:00','00:00');
        }
      }    
    }
  }

  else {
    var decimalStart = 0;
    var decimalEnd = 0;
    var breakDur = 0;
    var duration = '00:00';
    
    for (var i=0; i < formData$this->scope.length; i++) {
      if (formData$this->scope[i]['action'] == 'timetype') {
        var timeType = formData$this->scope[i]['sequent'];

        if (timeType == 'S') {
          var clockStart = String([formData$this->scope[i]['newvalue']]);        
          decimalStart = +(clockStart.substring(0,2)) + +(clockStart.substring(3,5)/60);
        }
      
        else if (timeType == 'E') {
          var clockEnd = String([formData$this->scope[i]['newvalue']]);        
          decimalEnd = +(clockEnd.substring(0,2)) + +(clockEnd.substring(3,5)/60);
        }
       
        else if (timeType == 'B')
          breakDur = String([formData$this->scope[i]['newvalue']]);        
      }
    }  

    if ((decimalEnd - decimalStart) - breakDur >= 0) {
      var decimalDiff = String(Number((decimalEnd - decimalStart) - breakDur).toFixed(2));
      duration = String('0' + decimalDiff).slice(-5);
    } 
    for (i=0; i < formData$this->scope.length; i++) {
      if ((formData$this->scope[i]['action'] == 'timetype') 
          && (formData$this->scope[i]['sequent'] == 'D')) {
        formData$this->scope[i]['newvalue'] = duration;         
        var setField = 'set' + formData$this->scope[i]['field']; 
        setFunction = setField + '';
//logMessage ('<td>$this->scope</td><td>' +  setField + '</td><td>' + setField + '</td><td>' + dbResult[column] +  '</td><td>' + setType + '</td><td>set form field</td>');  
        multiFunction[setField][setFunction] (duration, duration);

      }
    } 
  }
}
    
// Populate detail form
function setForm$this->scope (selectId, dbResult) {
  var setType;
  for (var i=0; i < formData$this->scope.length; i++) {
    var column = formData$this->scope[i]['dbcolumn']; 
alert ('col:' + formData$this->scope[i]['field'] + ' ' + column + ' ' + dbResult[column] + ' ' + selectId);
    if (selectId == 0) {
      setType = 'default';
      formData$this->scope[i]['dbvalue'] = 0;
      formData$this->scope[i]['dbtext'] = '';
    }
    else {
      setType = 'database';
      formData$this->scope[i]['dbvalue'] = dbResult[column];
      formData$this->scope[i]['dbtext'] = dbResult[column+'_text'];
    }
    formData$this->scope[i]['newvalue'] = dbResult[column];
    formData$this->scope[i]['newtext'] = dbResult[column+'_text'];
    
    if (column != 'id') {
      var setField = 'set' + formData$this->scope[i]['field']; 
      var setFunction = setField + '';

logMessage ('<td>$this->scope</td><td>' +  setField + '</td><td>' + setField + '</td><td>' + dbResult[column] +  '</td><td>' + setType + '</td><td>set form field</td>');  
//alert (setField + ' ' + dbResult[column] + ':' + dbResult[column+'_text'] + ':');
      multiFunction[setField][setFunction] (dbResult[column],dbResult[column+'_text']);

      if (formData$this->scope[i]['action'] == 'sendid')
        sendMessages$this->scope ('{' + formData$this->scope[i]['sequent'] + '}',  dbResult[column], dbResult[column+'_text']);
//      else if (formData$this->scope[i]['action'] == 'switch') 
//        switchForm$this->scope ('{' + formData$this->scope[i]['sequent'] + '}', dbResult[column], dbResult[column+'_text']);
    }
  }
}

// Populate detail form
function setData$this->scope () {
  var reqData = 'summaryid=' + summaryId$this->scope + '&' + 'filterid=' + filterId$this->scope;
  for (var i=0; i < formData$this->scope.length; i++) {
    reqData += '&' + formData$this->scope[i]['dbcolumn'] + '=' + formData$this->scope[i]['newvalue'] +
               '&' + formData$this->scope[i]['dbcolumn'] + '_text=' + formData$this->scope[i]['newtext'];
  }
  return reqData;
} 

// Ajax get form db data for selected summary row
function row$this->iterator (selectId) {
  if (selectId == 0) { 
//alert (selectId);	
    setForm$this->scope(selectId, formDefs$this->scope);
  }
  else {
//alert (selectId);	
    var xhr = new XMLHttpRequest();
    var params = 'selid=' + selectId;

    xhr.open('POST', 'ajax/row$this->scope.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {//Call a function when the state changes.
      if (xhr.readyState == 4 && xhr.status == 200) {
        var response = JSON.parse(xhr.responseText);
        setForm$this->scope(selectId, response);
      }
    }
    xhr.send(params);
  }
}

// Ajax get form db data for selected summary row
function key$this->scope (valid) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/key$this->scope.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {//Call a function when the state changes.
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText);
      valid.uniqueCheck = response[0];
      valid.message = response[1];
//alert (response[1]);      
      submit$this->scope (valid);
    }
  }
  xhr.send(valid.fields);
}

function put$this->scope() {
  var params = setData$this->scope ();
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/put$this->scope.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {//Call a function when the state changes.
    if (xhr.readyState == 4 && xhr.status == 200) {
      selectId$this->scope = JSON.parse(xhr.responseText);
      var msgContent = [];
      msgContent.$this->iterator = [selectId$this->scope,'', 'updateId', '$this->scope', 'updated row id'];
      newValue$this->iterator (msgContent);
    }  
  }
  xhr.send(params);
}

function del$this->iterator() {

  var params = 'id=' + selectId$this->scope
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/del$this->iterator.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {//Call a function when the state changes.

    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText);
      selectId$this->scope = 0;
      $('#del$this->iterator').prop('disabled', true);

      var msgContent = [];
      msgContent.$this->iterator = [selectId$this->scope,'', 'updateId', '$this->scope', 'updated row id'];
      newValue$this->iterator (msgContent);
    }
  }  
  xhr.send(params);
}


    ";
    return $script;
  }
}

?>
