<?php 

class Selector  {
  private $field;
  private $form;
  private $label;
  private $selectId;
  private $options;

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

      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->options))
        $this->options = $field->options;
      else
        $this->options[] = NULL;

    }
  }
  
  public function outputLayout() {
  
    $layout = "
    
  $this->label    
  <select id='$this->field' $this->attribute>
     ";

    foreach ($this->options as $option) {
      $value = $option->id;
      $text  = $option->text;
 	  $attribute = "";	

      if ($value == $this->selectId)
        $attribute = " selected";

      $layout .= "
    <option value=" . $value . $attribute . " class='opt$this->field'>" . $text . "</option>";
  }
  
    $layout .= "
  </select>
	";
	return $layout;
  }	

  public function outputScript() {

    $script = "


$(document).ready(function() {
  var selectId = $this->selectId; 
  ses$this->field (selectId);
  set$this->form (selectId);
});

$(document).on('change', '#$this->field', function (e) {
  var selectId = $(this).val();
  ses$this->field (selectId);
  set$this->form (selectId);
}); 

function set$this->field (selectId) {
  ses$this->field (selectId);
  $('#$this->field option:selected').removeAttr('selected');;
  $('#$this->field option[value='+selectId+']').prop('selected',true);
}

function ses$this->field (selectId) {
  var params = 'selectid=' + selectId;
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/ses$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)
    }
  }
  xhr.send(params);
}


    "; 
    return $script;
  }
}

?>