<?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;

      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 = "";
    }    
  }
  
  public function outputLayout() {

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

    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) {
      $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 class='sel$this->field' $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 = "

var context$this->form = $this->contexts;

$(document).ready(function() {

  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].idx & context$this->form[i].filter) > 0) && (context$this->form[i].selectid > 0) && (refinePos == -1)) {
      refinePos = i;
      refineIdx = context$this->form[i].idx
    }
  }

 get$this->field (context$this->form[0].field, context$this->form[0].summaryid, context$this->form[0].selectid, context$this->form[0].type, context$this->form[0].attr);

  for (var i=1; i<context$this->form.length; i++) {
    if (refineIdx & context$this->form[i].refine) {
      tab$this->form (context$this->form[idx-1].field, context$this->form[idx-1].summaryid);
      refineIdx = context$this->form[i].idx;
    }
  }  

});

$(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) {
  var idx = index.indexOf('1');
  context$this->form[idx].selectid = value;

  // de-select: re-gen summary from previous filter
  if (context$this->form[idx].selectid == 0 && idx > 0) {
    for (var i=idx-1; i>=0; i--) {
      if (index & context$this->form[idx].filter)
        tab$this->form (context$this->form[i].field, context$this->form[i].summaryid);
    }    
  }  
  // select a filter selector: generate summary
  else if (index & context$this->form[idx].filter) {
    tab$this->form (context$this->form[idx].field, context$this->form[idx].selectid);
  }      

  // refine all flagged selectors to the right
  for (var i=idx+1; i<context$this->form.length; i++) {
    context$this->form[i].summaryid = value;
    if (index & context$this->form[i].refine) {
      if (context$this->form[i].type == 'SUMMARY') {
        tab$this->form (context$this->form[i].field, context$this->form[i].summaryid);
      }
      else {
        context$this->form[i].summaryid = value;
        get$this->field (context$this->form[i].field, context$this->form[i].summaryid, context$this->form[i].selectid, context$this->form[i].type, context$this->form[i].attr);
        value = 0;
        index = context$this->form[i].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) {
  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].selectid, 100, 'sequent_frm', context$this->form[i].field, 'refresh selectid - field'];
//      newValue$this->form (msgContent);

    var index = parseInt(context$this->form[i].idx,2)    
      status$this->field.setBits (context$this->form[i].selectid, 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 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) {
    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 (type == 'SELECT') {
          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;
        }
        else if (type == 'HEADER') {
          var divId = 'event' + attr;
          document.getElementById(divId).innerHTML='Work Event: ' +response[0].text;
        }
      }    
    }
    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;
  }
}

?>