<?php 

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

  public function __construct($entry) {

    if (isset($entry)) {
      $this->scope = $entry->scope;
      $this->width = $entry->width;
      $this->form  = $entry->form;
      $this->iterator = $entry->iterator;
//print_r ('it:');      
//print_r ($this->iterator);

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

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

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

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

    }    
  }
  
  public function outputLayout() {

    $layout = "
$this->label    
<table class='table table-condensed'>
  <thead>
    <tr>
    ";
  
    foreach ($this->selectors as $selector) {
      if ($selector->type != "HEADER") {
        $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->index;
        $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->scope' 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->scope' name='$name'
              value='$value' data-idx=$index data-recid=$value $this->placeHolder
              onkeyup='res$this->scope (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->scope('$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->scope' 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 = 000;
SelectStatus.prototype.clear = 0;

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

var complete$this->scope = parseInt('$this->complete', 2);

var context$this->iterator = $this->contexts;
var selectId$this->scope = $this->selectId;
var summaryKey$this->scope = '';

$(document).ready(function() {
  var completeInd = 0;
  var summaryInd = 1;

  for (var i=context$this->iterator.length-1; i>=0; i--) {
    if (((context$this->iterator[i].index & context$this->iterator[i].refine) > 0) && (context$this->iterator[i].selid > 0) && summaryInd == 1) {
//alert (context$this->iterator[i].field + ' ' + ((context$this->iterator[i].index & context$this->iterator[i].refine) > 0) + ' ' + context$this->iterator[i].sumid + ' ' + summaryInd);
      summaryInd = 0;
      var msgContent = [];
      msgContent[context$this->iterator[i].field] = [context$this->iterator[i].selid, '', 'sequent_ent', context$this->iterator[i].field, 'entry selid - field'];
      newValue$this->iterator (msgContent);
//alert ('s:' + selectId$this->scope);      
      var msgContent = [];
      msgContent.$this->iterator = [selectId$this->scope, context$this->iterator[i].field, 'sequent_frm', context$this->iterator[i].field, 'entry selid - form'];
      newValue$this->iterator (msgContent);
    }
  }
  
  for (var i=0; i<context$this->iterator.length; i++) {
    get$this->scope (context$this->iterator[i].field, context$this->iterator[i].sumid,
      context$this->iterator[i].selid, context$this->iterator[i].type, context$this->iterator[i].attr);
//  var index = parseInt(context$this->iterator[i].index,2)    
//    status$this->scope.setBits (context$this->iterator[i].selid, context$this->iterator[i].index);
//    completeInd = (status$this->scope.complete == complete$this->scope) ? 1 : 0;
//alert ('on ' + status$this->scope.complete);    
//    var msgContent = [];
//    msgContent.$this->scope = [completeInd, '', 'sequent_frm', 'cxt', 'selector complete'];
//    newValue$this->iterator (msgContent);
  }
});

$(document).on('change', '.sel$this->scope', function (e) {
  var index = $(this).attr('data-idx');
//alert (index);  
  var value = $(this).val();
//  var text  = $(this).find('option:selected').text();
//  $(this).attr('value', value);
  cas$this->scope (value, index);
}); 

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

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

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

function cas$this->scope (value, index) {
  var idx = index.indexOf('1');
  var filterLen = context$this->iterator[idx].filter.length
  context$this->iterator[idx].selid = value;
  var msgContent = [];
  msgContent.$this->iterator = [0, '', 'sequent_frm', context$this->iterator[idx].field, 'cas selid - def'];
  newValue$this->iterator (msgContent);
  get$this->scope (context$this->iterator[idx].field, 0, value, context$this->iterator[idx].type, context$this->iterator[idx].attr);

  var msgContent = [];
  msgContent[context$this->iterator[idx].field] = [value, '', 'sequent_ent', context$this->iterator[idx].field, 'selected selid'];
  newValue$this->iterator (msgContent);

//  status$this->scope.setBits (value, index);
//  completeInd = (status$this->scope.complete == complete$this->scope) ? 1 : 0;
//alert ('in ' + status$this->scope.complete);    
//  var msgContent = [];
//  msgContent.$this->scope = [completeInd, '', 'sequent_ent', '', 'new cas value'];
//  newValue$this->iterator (msgContent);

  for (var id=idx+1; i<filterLen; i++) {
    if (index & context$this->iterator[i].filter) {
      var msgContent = [];
      msgContent[context$this->iterator[i].field] = [value, '', 'sequent_ent', context$this->iterator[i].field, 'selected selid'];
      newValue$this->iterator (msgContent);
    }  
//      var msgContent = [];
//      msgContent.$this->iterator = [0, '', 'sequent_ent', context$this->iterator[i].field, 'FORM selid'];
//      newValue$this->iterator (msgContent);
      get$this->scope (context$this->iterator[i].field, 0, value, context$this->iterator[i].type, context$this->iterator[i].attr);
  }  
}

function send$this->scope (value, text) {
//alert ('send');
  var msgContent = [];
  msgContent.$this->scope = [value, text, 'sequent_ent', '---', 'new pat value'];
  newValue$this->iterator (msgContent);
}

function set$this->scope (dbValue, dbText) {
//alert ('set cs:' + dbValue);    
 
  if (dbValue == 0) {
//   for (var i=0; i<context$this->iterator.length; i++) {
//      var msgContent = [];
//      msgContent[context$this->iterator[i].field] = [context$this->iterator[i].selid, '', 'sequent_frm', context$this->iterator[i].field, 'refresh selid - field'];
//      newValue$this->iterator (msgContent);

//    var index = parseInt(context$this->iterator[i].index,2)    
//      status$this->scope.setBits (context$this->iterator[i].selid, context$this->iterator[i].index);
//      completeInd = (status$this->scope.complete == complete$this->scope) ? 1 : 0;
//     if (completeInd > 0) {
//        var msgContent = [];
//        msgContent.$this->scope = [completeInd, '', 'sequent_frm', 'cxt', 'selector complete'];
//        newValue$this->iterator (msgContent);
//      }    
//    }  
  }
  else if (dbValue > 0) {
//    var summaryInd = 1;
//    for (var i=context$this->iterator.length-1; i>=0; i--) {
//      if (((context$this->iterator[i].index & context$this->iterator[i].refine) > 0) && (context$this->iterator[i].selid > 0) && summaryInd == 1) {
//alert (context$this->iterator[i].field + ' ' + ((context$this->iterator[i].index & context$this->iterator[i].refine) > 0) + ' ' + context$this->iterator[i].sumid + ' ' + summaryInd);
//       summaryInd = 0;
//        var msgContent = [];
//        msgContent[context$this->iterator[i].field] = [context$this->iterator[i].selid, '', 'sequent_ent', context$this->iterator[i].field, 'entry selid - field'];
//        newValue$this->iterator (msgContent);
//alert ('s:' + selectId$this->scope);      
//        var msgContent = [];
//        msgContent.$this->iterator = [dbValue, context$this->iterator[i].field, 'sequent_frm', context$this->iterator[i].field, 'entry selid - form'];
//        newValue$this->iterator (msgContent);
//      }
//    }  
  }
}

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

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

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

function gen$this->scope(options) {
  var optId;
  var text;
  var layout = '<option value=0>Select</option>';

  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->scope (field, sumid, selid, type, attr) {
//alert (field + ' ' + sumid + ' ' + selid + ' ' + type);
//  if (sumid == 0)
//    document.getElementById(field).innerHTML = '';

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

    xhr.open('POST', 'ajax/get$this->scope.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') {
          document.getElementById(field).innerHTML = gen$this->scope(response);
          $('#'+field+' option[value='+selid+']').prop('selected',true);
        }
        else if (type == 'SEARCH') {
          document.getElementById(field).value = response[0].text;
        }
        else if (type == 'READONLY') {
//alert ('readonly:' + response[0].id);      
          document.getElementById(field).value = response[0].text;
          var msgContent = [];
          msgContent[field] = [response[0].id, '', 'sequent_frm', field, 'new r-o value'];
          newValue$this->iterator (msgContent);
        }
        else if (type == 'HEADER') {
          var divId = 'event' + attr;
//alert (divId);      
          document.getElementById(divId).innerHTML='Work Event: ' +response[0].text;
          var msgContent = [];
          msgContent[field] = [response[0].id, '', 'sequent_frm', field, 'new hdr value'];
          newValue$this->iterator (msgContent);
        }
        }
      }    
    }
    xhr.send(params);
}

// generate hint list
function hnt$this->scope(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->scope(' + args + ');\">' + inner + '</a><br>';
  }	
  return layout;
} 
 
// live search query for current pattern text 
function res$this->scope (pattern, id) {
  if (pattern.length == 0) { 
    document.getElementById('hnt$this->scope').innerHTML='';
    document.getElementById('hnt$this->scope').style.border='0px';
  }

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

    xhr.open('POST', 'ajax/res$this->scope.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)

//        if (pattern.length == 1) { 
//          send$this->scope (0, pattern);
//        }   
     
        document.getElementById('hnt' + id).innerHTML=hnt$this->scope(response, id);
        document.getElementById('hnt' + id).style.border='1px';
      }
    }  
    xhr.send(params);
  }  
}

function ses$this->scope (id) {
  var params =  'selectid=' + id;

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/ses$this->scope.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)
      
    for (var j=0; j<response.length; j++) {
          var selector = response[j].selector;
          var selectId = response[j].selectid;
//alert (selector + ' ' + selectId);
      $('#'+ selector +' option[value='+ selectId +']').prop('selected',true);
    }  

    }
  }  
  xhr.send(params);
}

function fky$this->scope (id) {
  var params =  'selectid=' + id;

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/fkey$this->scope.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)
    }
  }  
  xhr.send(params);
}


    "; 
    return $script;
  }
}

?>