<?php 
defined('PUBLIC_ACCESS') or die('Restricted Access');

class Tabulation  {

  public function __construct($field) {

    if (isset($field)) {
      $this->field = $field->field;
      $this->form  = $field->form;

      if (null !== $field->tableHeader)
        $this->tableHeader = $field->tableHeader;
      else
        $this->tableHeader = '[]';

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

  public function outputLayout() {
      
    $layout = "

<table class='table table-condensed'>
  <thead>
    <tr>
    ";

    for ($i=1; $i<count($this->tableHeader); $i++) {
      $colLabel = $this->tableHeader[$i];

      $layout .= "
      <th>$colLabel</th>  
      ";
    }    
  
    $layout .= "
    </tr>
  </thead>
  <tbody id='body$this->field'>      
  </tbody>  
</table>
    "; 


    return $layout;
  }	

  public function outputScript() {

	$script = " 
	
function gen$this->field (resp) {
  var inner = '';

  for (var i=0; i<resp.length; i++) {
    if (i == 0) {
      formFields = Object.keys (resp[i]);
    }
    
    inner += '<tr>';
    for (var j=0; j < formFields.length; j++) { 
      inner += '<td>' + resp[i][formFields[j]] + '</td>';
    } 
    inner += '</tr>';
  }

  return inner;
}

function tab$this->form (field, id) {
//  if (id == 0)
//    document.getElementById('body$this->field').innerHTML = '';

//  else {
    var params = 'id=' + id + '&' +  'field=' + field;
    var xhr = new XMLHttpRequest();

    xhr.open('POST', 'ajax/get$this->field.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)
      document.getElementById('body$this->field').innerHTML = gen$this->field(response);
      }
    }
    xhr.send(params);
//  }    
}

  ";

  return $script;
  }
}

?>