<?php 

class ContextSelector  {
  private $field;
  private $label;
  private $iterator;
  private $control;

  public function __construct($field) {
      
    if (isset($field)) {
      $this->field = $field->field;
      $this->width = $field->width;
      $this->form  = $field->form;
//print_r ('sel:');      
//print_r ($field->field);

      if (null !== $field->selectors) {
        $this->selectors = json_decode($field->selectors);
        $this->contexts = $field->selectors;
      }    
      else {
        $this->contexts = '{}';
        $this->selectors = '{}';
      }
      
//$sel = $this->selectors;
//$key = "selector";      
//print_r ('sel:');      
//print_r ($this->selectors);
//print_r ('con:');      
//print_r ($this->contexts);


      if (isset($field->label))
        $this->label = "<label>$field->label</label><br>";
      else
        $this->label = "";

      if (isset($field->selectId))
         $this->selectId = $field->selectId;
      else
        $this->selectId = 0;

      if (isset($field->complete))
         $this->complete = $field->complete;
      else
        $this->complete = 0;

    }    
  }
  
  public function outputLayout() {

   $key = "selector";      
   $layout = "
$this->label    
<table class='table table-condensed'>
  <thead>
    <tr>
    ";

//print_r ($this->selectors);  
    foreach ($this->selectors->$key as $selector) {
      $label = $selector->label;

      $layout .= "
      <th>
    $label
      </th>
        ";
   }
 
    $layout .= "
    </tr>
  </thead>    
  <tbody>
    <tr>
    ";

    foreach ($this->selectors->$key as $selector) {
      $index = $selector->idx;
      $field = $selector->field;
      $name  = $selector->summaryid;
      $value = $selector->selectid;
      $type =  $selector->type;
      $attr =  $selector->attr;
      $style = 'style=width:' . $selector->width .';'; 

      if ($type == "SELECT") {
        $layout .= "
      <td $style>
        <select id='$field' data-idx=$index name='$name' 
          class='sel$this->field' value='$value' $attr>
        </select>
      </td>
          ";
      }

      else if ($type == "SEARCH") {
        $layout .= "
      <td $style>
        <table style='border:1px solid black;'>
          <tr>
            <td style='width:80%'>
              <input id='$field' type='text' class='$this->field' name='$name'
                value='$value' data-idx=$index data-recid=$value $this->placeHolder
                onkeyup='res$this->field (this.value, this.id)' $attr>
            </td>
            <td style='width:20%'>
              <button id='clr$id' class='btn btn-inverse btn-xs' 
                style='width:50px;$this->clear'
                onclick=clr$this->field('$field');>Clear</button>
            </td>
          </tr>
        </table> 
        <div id='hnt$index' style='position:relative;'></div>
      </td>
        ";
      }

      else if ($type == "READONLY") {
        $layout .= "
      <td $style>
        <input id='$field' type='text' class='$this->field' name='$name'
          value='$value' data-idx=$index data-recid=$value readonly
          style='background-color:lightgrey'>
      </td>
        ";
      }
    }    

  
    $layout .= "
    </tr>
  </tbody>
</table>
    ";
 
    return $layout;
  }	

  public function outputScript() {

    $key = "selector";      
    foreach ($this->selectors->$key as $selector) {
        
      $index = $selector->idx;
      $field = $selector->field;
      $name  = $selector->summaryid;
      $value = $selector->selectid;
      $type =  $selector->type;

      $script .= "
function set$field (dbValue, dbAttr) {
  var indexPos = '$index'.indexOf('1');
  var selector = context$this->form['selector'][indexPos];
  var completeInd = (status$this->field.complete == complete$this->field) ? 1 : 0;
  status$this->field.setBits (dbValue, selector.idx);

//alert('set $field ' + indexPos + ' ' + selector.summaryid + ' ' + selector.selectid + ' ' + dbValue + ' ' + dbAttr);

  if (selector.summaryid > 0 && selector.summaryid != dbAttr) {
    selector.selectid = dbValue;
    selector.summaryid = dbAttr;
    get$this->field (selector.field, selector.summaryid, selector.selectid, selector.type, selector.attr);
  }    

  var chkComplete= (status$this->field.complete == complete$this->field) ? 1 : 0;
  if (chkComplete != completeInd) {
    completeInd = chkComplete;
    var msgContent = [];
    msgContent.$this->field = ['$this->field', completeInd, 'complete', '$this->form', 'set complete'];
    newValue$this->form (msgContent);
  }  
}      

multiFunction['set$field'] = {
  set$field:set$field
};  
     ";    
  }

	  $script .= "

function SelectStatus (formid) {
  this.formid = formid; 

  this.setBits = function(id, idx) {
    var st = SelectStatus.prototype.complete;
    var index = parseInt(idx,2);
    if (id > 0) 
      SelectStatus.prototype.complete = index | st;
    else
      SelectStatus.prototype.complete = ~index & st;

    SelectStatus.fkey = id;
      
//alert (st + '-' + SelectStatus.prototype.complete + '-'+ index);
  };
  this.setClear = function(i) {
    SelectStatus.prototype.clear = i;
  };

}

SelectStatus.prototype.complete = 0000;
SelectStatus.prototype.clear = 0;

var status$this->field = new SelectStatus('$this->form');
status$this->field.form = '$this->form';
status$this->field.fkey = 0;

var complete$this->field = parseInt('$this->complete', 2);
//alert (complete$this->field);

var context$this->form = JSON.parse('$this->contexts');
var selectId$this->field = $this->selectId;

//  for (var i=0; i<context$this->form['SUMMARY'].length; i++) {
//alert (context$this->form['SUMMARY'][i].field);  
//  }

$(document).ready(function() {
  var fkyField = null;
  var summaryPos = 0;
  var refinePos = 0;
  var refineIdx = 0; 
  var Idx = 0; 
  var sumid = 0;

  // get the selectors that can generate the top level summary
  var refineBits = context$this->form['summary'][0].refine;

  // starting from right, find  
  var selectors = context$this->form['selector'].reverse();
  for (const selector of selectors) {
    if (((selector.idx & refineBits) > 0) && (selector.selectid > 0) && (refinePos == 0)) {
      fkyField = selector.field;
      context$this->form['summary'][0].summaryid = selector.selectid;
      refinePos = 1;
    }
  }

  selectors = context$this->form['selector'].reverse();
  for (const selector of selectors) {
//alert (selector.field + ' ' + selector.summaryid);
    if (selector.summaryid > 0)
      get$this->field (selector.field, selector.summaryid, selector.selectid, selector.type, selector.attr);
  }
 
  for (const summary of context$this->form['summary']) {
    if (summary.summaryid > 0) {
//      var msgContent = [];
//      msgContent[summary.field] = [fkyField, summary.summaryid, summary.selectid, summary.field, 'rdy refine'];
//      eval ('newValue' + summary.targetform + '(msgContent)');
      eval ('get' + summary.targetform + '(fkyField, summary.summaryid, summary.selectid)');
    }
  }
//  for (var i=0; i<context$this->form.length; i++) {
//   alert ('call cas:' + i +  ' ' + selector.field + ' ' + summary.summaryid +  ' ' + summary.selectid);
//  }

  var completeInd = (status$this->field.complete == complete$this->field) ? 1 : 0;
  var msgContent = [];
  msgContent.$this->field = ['$this->field', completeInd, 'complete', '$this->form', 'rdy complete'];
//  newValue$this->form (msgContent);
});

$(document).on('change', '.sel$this->field', function (e) {
  var index = $(this).attr('data-idx');
  var value = $(this).val();
  cas$this->field (value, index);
}); 

$(document).on('change', '#pat$this->field', function (e) {
  send$this->field (0, $(this).val());
});

function clr$this->field (index) {
  document.getElementById('hnt' + index).innerHTML='';
  document.getElementById('hnt' + index).style.border='0px';
  cas$this->field (0, index);
}  

// on clicking hint, send id and text to formdata
function clk$this->field (frmValue, frmAttr, field) {
  document.getElementById(field).value=frmAttr;
  document.getElementById(field).focus();
  document.getElementById('hnt' + field).innerHTML='';
  document.getElementById('hnt' + field).style.border='0px';
  cas$this->field (frmValue, field);
}

function cas$this->field (value, index) {

//  for (var i=0; i<context$this->form.length; i++) {
//   alert ('call cas:' + i +  ' ' + selector.field + ' ' + selector.summaryid +  ' ' + selector.selectid);
//  }

  var selector = context$this->form['selector'];
  var summary = context$this->form['summary'];
  var summaryid = 0;
  var summaryPos = 0;
  var refineBits = 0;
  var cascadePos = index.indexOf('1');
  var refinerIdx = parseInt(index,2);
  var msgSender = 'cxt' + context$this->form['selector'][cascadePos].field;
  var completeInd = (status$this->field.complete == complete$this->field) ? 1 : 0;
  status$this->field.setBits (value, context$this->form['selector'][cascadePos].idx);
  selector[cascadePos].selectid = value;
  summary[0].summaryid = value;
  
//alert (summary[0].summaryid + ' ' + msgSender);

  var msgContent = [];
  msgContent[selector[cascadePos].field] = [selector[cascadePos].field, selector[cascadePos].selectid, '', '$this->form', 'set cas fky'];
  newValue$this->form (msgContent);

  if (selector[cascadePos].idx & summary[0].refine) { 
//    var msgContent = [];
//    msgContent[summary[0].field] = [selector[cascadePos].field, summary[0].summaryid, summary[0].idx, summary[0].field, 'cas refine'];
//alert ('newValue' + summary[i].targetform);
//    eval ('newValue' + summary[0].targetform + '(msgContent)');
//alert ('get' + summary[0].targetform + '(selector[cascadePos].field, summary[0].summaryid, summary[0].selectid)');
  eval ('get' + summary[0].targetform + '(selector[cascadePos].field, summary[0].summaryid, summary[0].selectid)');
  }
  
  ref$this->field (cascadePos, refinerIdx);

  var chkComplete= (status$this->field.complete == complete$this->field) ? 1 : 0;
  if (chkComplete != completeInd) {
    completeInd = chkComplete;
    var msgContent = [];
    msgContent.$this->field = ['$this->field', completeInd, 'complete', '$this->form', 'selectors complete'];
    newValue$this->form (msgContent);
  }  
}

function ref$this->field (pos, idx) {
  var selector = context$this->form['selector'];
  for (var i=pos+1; i<selector.length; i++) {

//alert (i + ' ' + idx + ' ' + selector[i].refine);

    if (idx & selector[i].refine) {
      selector[i].summaryid = selector[pos].selectid;
      selector[i].selectid = 0;
      get$this->field (selector[i].field, selector[i].summaryid, selector[i].selectid, selector[i].type, selector[i].attr);

//alert (i + ' ' + selector.length);

      if (i < (selector.length - 1))
        ref$this->field (i+1, selector[i+1].idx);
    }
  }  
}

function send$this->field (value, attr) {
  var msgContent = [];
  msgContent.$this->field = [value, attr, 'sequent_ent', '---', 'new pat value'];
//  newValue$this->form (msgContent);
}

function set$this->field (dbValue, dbAttr) {

}

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

function com$this->field (message) {
  var key = Object.keys(message);
logMessage ('<td>com msg</td><td>' + key + '</td><td>' + message[key][0] + '</td><td>' + message[key][1] + '</td><td>' + message[key][2] +  '</td><td>' + message[key][4] + '</td><td>' + message[key][4] + '</td>');  
  if (key == 'selectId')
    get$this->field (message[key][1], '$this->displayId');
}  

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

function gen$this->field(options) {
  var optId;
  var text;
  var layout = '';

  for (var j=0; j<options.length; j++) {
    optId = options[j].id;
    text  = options[j].text;
    layout += '<option value=' + optId + '>' + text + '</option>';
  }    
  return layout;
} 

function get$this->field (field, summaryid, selectid, type, attr) {
//alert ('get:' + field + ' ' + summaryid + ' ' + selectid + ' ' + type + ' ' + attr);

    var xhr = new XMLHttpRequest();
    var params =  'field=' + field + '&' + 'summaryid=' + summaryid  + '&' + 'selectid=' + selectid ;

    xhr.open('POST', 'ajax/get$this->field.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var response = JSON.parse(xhr.responseText)
        if (summaryid > 0) {
        if (type == 'SELECT') {
//alert (field + ' si=' + summaryid);        
          document.getElementById(field).innerHTML = gen$this->field(response);
          $('#'+field+' option[value='+selectid+']').prop('selected',true);
        }
        else if (type == 'SEARCH') {
          document.getElementById(field).value = response[0].text;
        }
        else if (type == 'READONLY') {
          document.getElementById(field).value = response[0].text;
          var msgContent = [];
          msgContent[field] = [response[0].id, '', 'sequent_frm', field, 'new r-o value'];
//          newValue$this->form (msgContent);
        }
        else if (type == 'HEADER') {
          var divId = 'event' + attr;
          document.getElementById(divId).innerHTML='Work Event: ' +response[0].text;
          var msgContent = [];
          msgContent[field] = [response[0].id, '', 'sequent_frm', field, 'new hdr value'];
//          newValue$this->form (msgContent);
        }
        }
      }    
    }
    xhr.send(params);
}

// generate hint list
function hnt$this->field(list, id) {
  var layout='';

  for (var i=0; i<list.length; i++) {

    var inner = list[i].hint;
    args = list[i].id + ', \'' + inner + '\'' + ', \'' + id + '\'';

	layout += '<a href=\"#/\" onclick=\"clk$this->field(' + args + ');\">' + inner + '</a><br>';
  }	
  return layout;
} 
 
// live search query for current pattern text 
function res$this->field (pattern, id) {
  if (pattern.length == 0) { 
    document.getElementById('hnt$this->field').innerHTML='';
    document.getElementById('hnt$this->field').style.border='0px';
  }

  else {
    var xhr = new XMLHttpRequest();
    var params = 'pattern=' + pattern;

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

        document.getElementById('hnt' + id).innerHTML=hnt$this->field(response, id);
        document.getElementById('hnt' + id).style.border='1px';
      }
    }  
    xhr.send(params);
  }  
}

    "; 
    return $script;
  }
}

?>