<?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 = $field->selectors;
        $this->contexts = json_encode($field->selectors);
      }    
      else {
        $this->contexts = '{}';
        $this->selectors = '{}';
      }

      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() {

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

//print_r ($this->selectors);  
    foreach ($this->selectors as $selector) {
      if ($selector->type != "SUMMARY") {
        $label = $selector->label;

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

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

    $firstOf = true;
    $idx = 0;
    foreach ($this->selectors as $selector) {
      if ($selector->type != 'FORM') {
        $index = $selector->idx;
        $field = $selector->field;
        $name  = $selector->sumid;
        $value = $selector->selid;
        $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>
          ";
        }
      $idx++;  
      }
    }    

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

  public function outputScript() {

	  $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 = $this->contexts;
var selectId$this->field = $this->selectId;
var summaryKey$this->field = '';

$(document).ready(function() {
  var sender = null;
  var refinePos = -1;
  var refineIdx = 0; 

  // From right to left, find the first selector that can generate the summary 
  for (var i=context$this->form.length-1; i>=0; i--) {
    if ((context$this->form[i].type != 'SUMMARY') && ((context$this->form[i].idx & context$this->form[i].filter) > 0) && (context$this->form[i].selid > 0) && (refinePos == -1)) {
      refinePos = i;
      refineIdx = context$this->form[i].idx
    }
  }

 get$this->field (context$this->form[0].field, context$this->form[0].sumid, context$this->form[0].selid, context$this->form[0].type, context$this->form[0].attr);
 status$this->field.setBits (context$this->form[0].selid, context$this->form[0].idx);
 sender = 'cxt' + context$this->form[0].field;

  for (var i=1; i<context$this->form.length; i++) {
//alert (refineIdx  + ' ' + context$this->form[i].refine + ' ' + context$this->form[i].sumid + ' ' + context$this->form[i].selid);
    if (refineIdx & context$this->form[i].refine) {
      if (context$this->form[i].type == 'SUMMARY') {
//alert ('SUMM: ' + sender + ' newValue' + context$this->form[i].targetform);      
        var msgContent = [];
        msgContent[context$this->form[i].field] = [sender, context$this->form[i].sumid, context$this->form[i].selid, context$this->form[i].field, 'rdy refine'];
        eval ('newValue' + context$this->form[i].targetform + '(msgContent)');
        refineIdx = context$this->form[i].idx;
        sender = 'cxt' + context$this->form[i].field;
      }
      else {
        get$this->field (context$this->form[i].field, context$this->form[i].sumid, context$this->form[i].selid, context$this->form[i].type, context$this->form[i].attr);
//        value = 0;
        refineIdx = context$this->form[i].idx;
        sender = 'cxt' + context$this->form[i].field;
        status$this->field.setBits (context$this->form[i].selid, context$this->form[i].idx);
      }
    }  
  }    

  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 +  ' ' + context$this->form[i].field + ' ' + context$this->form[i].sumid +  ' ' + context$this->form[i].selid);
  }
  var cascadePos = index.indexOf('1');
  var completeInd = (status$this->field.complete == complete$this->field) ? 1 : 0;
  var sender = 'cxt' + context$this->form[cascadePos].field;
  context$this->form[cascadePos].selid = value;

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

  // de-select: re-gen summary from previous filter
  if (context$this->form[cascadePos].selid == 0 && cascadePos > 0) {
    for (var i=cascadePos-1; i>=0; i--) {
      if (index & context$this->form[cascadePos].filter) {
        cascadePos = i
        sender = 'cxt' + context$this->form[cascadePos].field;
        index  = context$this->form[cascadePos].idx;
        value  = context$this->form[cascadePos].selid;
      }    
    }    
  } 

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

  // refine all flagged selectors to the right
  for (var i=cascadePos+1; i<context$this->form.length; i++) {
 //alert ('refine:' + i + ' '  + value + ' ' + index + '&' + context$this->form[i].refine + ' ' + context$this->form[i].targetform + ' ' + context$this->form[i].field + ' ' + context$this->form[i].type);
    if (index & context$this->form[i].refine) {
      context$this->form[i].sumid = value;
      if (context$this->form[i].type == 'SUMMARY') {
        var msgContent = [];
//alert ('cas eval:' + sender + ' ' + context$this->form[i].field + ' ' + context$this->form[i].sumid + ' ' + context$this->form[i].targetform);
        msgContent[context$this->form[i].field] = [sender, context$this->form[i].sumid, context$this->form[i].idx, context$this->form[i].field, 'cas refine'];
        eval ('newValue' + context$this->form[i].targetform + '(msgContent)');
//        newValue$this->form (msgContent);
      }
      else {
        get$this->field (context$this->form[i].field, context$this->form[i].sumid, context$this->form[i].selid, context$this->form[i].type, context$this->form[i].attr);
//        value = 0;
        index = context$this->form[i].idx;
      }
    }  
  }  

//  context$this->form[idx].selid = value;

//alert (value + ' ' + context$this->form[cascadePos].idx);
  // check complete and update complete indicator
  status$this->field.setBits (value, context$this->form[cascadePos].idx);
  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 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) {
  if (dbValue == 0) {
   for (var i=0; i<context$this->form.length; i++) {
      var msgContent = [];
      msgContent[context$this->form[i].field] = [context$this->form[i].selid, 100, 'sequent_frm', context$this->form[i].field, 'refresh selid - field'];
//      newValue$this->form (msgContent);

    var index = parseInt(context$this->form[i].idx,2)    
      status$this->field.setBits (context$this->form[i].selid, context$this->form[i].idx);
      var completeInd = (status$this->field.complete == complete$this->field) ? 1 : 0;
     if (completeInd > 0) {
        var msgContent = [];
        msgContent.$this->field = [completeInd, 100, 'sequent_ent', 'cxt', 'selector complete'];
//        newValue$this->form (msgContent);
      }    
    }  
  }
}

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, sumid, selid, type, attr) {
//alert ('get:' + field + ' ' + sumid + ' ' + selid + ' ' + type + ' ' + attr);

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

    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 (sumid > 0) {
        if (type == 'SELECT') {
//alert (field);        
          document.getElementById(field).innerHTML = gen$this->field(response);
          $('#'+field+' option[value='+selid+']').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;
  }
}

?>