<?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->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->formDef0)
        $this->formDef0 = json_encode($entry->formDef0);
      else
        $this->formDef0 = '{}';
        
//$cnt = count($this->formDefs);
//print_r ("vcnt:$cnt");     

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

      if (isset($entry->formData))
        $this->formData = json_encode($entry->formData);
      else
        $this->formData = '{}';
//print_r ($this->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;

      if (isset($entry->disableCommit)) 
        $this->disableCommit = $entry->disableCommit;
      else
        $this->disableCommit = false;

    }
  }
  
  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 str = '$this->summaryId';
var summaryId$this->scope = (isNaN (str)) ? str : parseInt (str);
var fkeyId$this->scope = 0;
var formDefs$this->scope = [];
formDefs$this->scope[0]  = JSON.parse('$this->formDef0');
formDefs$this->scope[1]  = JSON.parse('$this->formDef1');
var currDef$this->scope = 0;

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

for (var i=0; i<formData$this->scope.length; i++) {
  if (formData$this->scope[i].action == 'sendid') {
//alert (formData$this->scope[i].field + '|' + formData$this->scope[i].sequent + '|' + formData$this->scope[i].sequent_frm + '|' + formData$this->scope[i].sequent_upd + '|' + formData$this->scope[i].sequent_ent);
    formData$this->scope[i].sequent = toObject$this->scope (formData$this->scope[i].sequent); 
    formData$this->scope[i].sequent_frm = toObject$this->scope (formData$this->scope[i].sequent_frm); 
    formData$this->scope[i].sequent_upd = toObject$this->scope (formData$this->scope[i].sequent_upd); 
    formData$this->scope[i].sequent_ent = toObject$this->scope (formData$this->scope[i].sequent_ent); 
    formData$this->scope[i].sequent_chk = toObject$this->scope (formData$this->scope[i].sequent_chk); 
//alert ('sequent:' + formData$this->scope[i].sequent.length);    
  }
}

$(document).ready(function() {
//alert (selectId$this->scope + ' sequent_ent');
  if ('$this->panelLevel' == 'panel0' || '$this->panelLevel' == 'panel1')
    row$this->scope (selectId$this->scope, 'sequent_ent');
//  document.getElementById('tag$this->scope').click();  
});

function toObject$this->scope (str) {
  var obj = {};
  if (str.length > 0) {
    var ele = str.split(',');
    for (var j=0;j<ele.length;j++) {
      var propval =  ele[j].split(':');
      var prop = propval[0];
      var val = propval[1];
      obj[prop] = val;
    }
  }    
  return obj;
}

function processForm$this->scope () {
//  document.getElementById('valmsg$this->scope').innerHTML = '';
  var valid$this->scope = [];
  valid$this->scope.fields = '';
  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]['dbcolumn'] == 'fkid' || 
        formData$this->scope[i]['dbcolumn'] == 'id') {
      valid$this->scope.fields += ampersand + formData$this->scope[i]['dbcolumn'] +
                '=' + formData$this->scope[i]['newvalue'];
      ampersand = '&';            
    }

       
    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 += ampersand + formData$this->scope[i]['dbcolumn'] +
                '=' + formData$this->scope[i]['newvalue'];
      ampersand = '&';            

      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']) {
      document.getElementById('cnfmsg$this->confirmModal').innerHTML = 
        formData$this->scope[i]['label'] + ': ' + formData$this->scope[i]['dbvalue'] + ' to ' + 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;
    row$this->scope (0, 'sequent');
  }    

  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)
    $('#modal$this->confirmModal').modal('show'); 
}

function confirm$this->iterator (okay) {
  if (okay)    
    put$this->scope ();
//  else
//   row$this->scope (selectId$this->scope, 'sequent_ent');
}

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

function com$this->scope (message) {
  var key = Object.keys(message);
//alert ('com$this->scope:' + key + ' ' + message[key][0]);
  if (key == 'fkeyId') {
    fkeyId$this->scope = message[key][0];
    formDefs$this->scope[currDef$this->scope].fkid = fkeyId$this->scope;
//    if (fkeyId$this->scope == 0) {
      row$this->scope (0, 'sequent_chk');
//    }
  }

  else if (key == 'summaryId') {
    summaryId$this->scope = message[key][0];
    formDefs$this->scope[currDef$this->scope].sumid = summaryId$this->scope;
    selectId$this->scope = 0
    row$this->scope (0, 'sequent_chk');  
  }
  
  else if (key == 'selectId') {
    formDefs$this->scope[currDef$this->scope].fkid = fkeyId$this->scope;
    row$this->scope (message[key][0], 'sequent_chk');  
  }
}

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

function set$this->iterator (value, text) {
  selectId$this->scope = value;
}

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

function newValue$this->scope (message) {
  document.getElementById('valmsg$this->scope').innerHTML = '';
  var source = '';
  var key = Object.keys(message);
  if (message[key][2] == 'formentry')
    source = 'sequent_frm';
  else
    source = message[key][2];
//alert ('newValue: ' + key +  ': ' + message[key][0] + ' ' + source);    

  for (var i=0; i < formData$this->scope.length; i++) {
  
    if (formData$this->scope[i]['field'] == key) {
      formData$this->scope[i]['newvalue'] = message[key][0];
      formData$this->scope[i]['newtext'] = message[key][1];
//alert (formData$this->scope[i]['action'] + ' new action ' + formData$this->scope[i]['field']);

      var formControl = modForm$this->scope (formData$this->scope[i], source);

      if (formControl.action == 'sendid') 
        prcAction$this->scope (formControl, message[key][0], message[key][1], source);

      else if (formControl.action == 'switch') 
        switchForm$this->scope (control.sequent, value, text);

      if (formControl.commit == 1)
        processForm$this->scope();
    }
  }    
}

// Populate detail form
function setForm$this->scope (selectId, dbResult, source) {
  var setType;
  for (var i=0; i<formData$this->scope.length; i++) {
    var column = formData$this->scope[i]['dbcolumn']; 
//if (column == 'id')
//alert ('$this->scope id>fks:' + dbResult[column]);
//alert ('setform col:' + formData$this->scope[i]['field'] + ' ' + column + '#' + dbResult[column] + '#' + selectId + formData$this->scope[i]['sequent'].length);

    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'];
    
    var field = formData$this->scope[i]['field'];
    var setField = 'set' + field; 
    var setFunction = setField + '';

//alert (setField + ' ' + dbResult[column] + ':' + dbResult[column+'_text'] + ':');
    multiFunction[setField][setFunction] (dbResult[column],dbResult[column+'_text']);

    var formControl = modForm$this->scope (formData$this->scope[i], source);
//alert (field + ':' + formControl.action);    
    if (formControl.action == 'sendid') {
//      alert ('field:' + formControl.field + ' ' +  formData$this->scope.length);    
      prcAction$this->scope (formControl, dbResult[column], dbResult[column+'_text'], source);
//      alert ('finish:' + formControl.field + ' ' +  formData$this->scope.length);    
    }
  }
}

function modForm$this->scope (control, source) {
  return control;
}

function prcAction$this->scope (control, value, text, source) {
//alert ('prc:$this->scope ' + control.action + ' ' + source);
//alert ('src:' + source);  
  sendCom$this->scope (control.sequent, value, text);
  var seq = control[source];
  sendCom$this->scope (seq, value, text);
}
 
function sendCom$this->scope (sequents, value, text) {
  var keys = Object.keys(sequents);
//  if ('$this->scope' == 'frmProjectParcel') {
//    alert ('$this->scope:sendCom:' + keys.length + ' ' + keys[0] + keys[1]); 
//  }
    for (var i=0; i<keys.length; i++) {
      var key = keys[i];
      var idx = sequents[key]
      var comField = 'com' + key; 
      var comFunction = comField + '';
//alert ('idx:' + idx + ':' + comField + ' ' + value);
      var msgContent = [];
      msgContent[idx] = [value, text, comField, '$this->scope', 'send id'];
      multiFunction[comField][comFunction] (msgContent);
  }
}

function switchForm$this->scope (sequent, value, text) {
  var keys = Object.keys(sequent);

  if (currDef$this->scope != value) {
     currDef$this->scope = value;
     row$this->scope (0, 'sequent_frm');
  }     
}

function frmCommit$this->scope (sequent, value, text) {
  var keys = Object.keys(sequent);
//  if (value > 0)
}
// 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->scope (selectId, source) {
//alert ('form row:' + selectId);
//alert('row$this->scope sumid:' + formDefs$this->scope[currDef$this->scope].sumid + ' ' + selectId);
  if (selectId == 0) { 
//alert ('in if');  
    $('#del$this->iterator').prop('disabled', true);
    $('#fdh$this->iterator').html($('#fdh$this->iterator').prop('value').split('_')[0]);
    $('#fdh$this->iterator').prop('disabled', $this->disableCommit);
    $('.tog$this->iterator').prop('disabled', true);
    $('[class^=$this->panelLevel]').each(function(){ $(this).slideUp('slow'); });

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

//alert (selectId);	
    var xhr = new XMLHttpRequest();
    var params = 'selectid=' + selectId + '&' + 'fkeyid=' + fkeyId$this->scope;

    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, source);
      }
    }
    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[0]);      
      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) {
      var response = JSON.parse(xhr.responseText);
      row$this->scope (response, 'sequent_upd')
    }  
  }
  xhr.send(params);
}

function del$this->iterator() {

  var params = setData$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);
//      formDefs$this->scope[currDef$this->scope].fkid = response;
      $('#del$this->iterator').prop('disabled', true);
      row$this->scope (0, 'sequent_upd')
    }
  }  
  xhr.send(params);
}


    ";
    return $script;
  }
}

?>
