$(document).ready(function() {

  var selected_options = $('#edit-field-instelling-nid-nid option[selected="selected"]');
  if(selected_options.length) {
  	var selected = find(selected_options);
  }
  var results = $("#easyselect-results");
  var wrappersub = $("#edit-bvl-subsectors-wrapper");
  var wrappernode = $("#edit-bvl-nodes-wrapper");
  
  if (wrappersub.length) {
  	$("#edit-bvl-subsectors-wrapper").empty();
  }
  if (wrappernode.length) {
  	$("#edit-bvl-nodes-wrapper").empty();
  }
  
  if(results.length) {
	  var x = document.getElementById("edit-field-instelling-nid-nid");
	  var txt = '';
	  for (i=0;i<x.length;i++)
	  {
	  	if (x.options[i].selected) {
	  	  var element = '<span value="' + x.options[i].value + '">' + x.options[i].text + '</span>'; 
	      txt = txt + "\n" + element;
	    }
	  }
	  $("#easyselect-results").append(txt);
  }
  
  $("#easyselect-results span").click(function() {
    var att = this.getAttribute('value');
    $('#edit-field-instelling-nid-nid option[value="' + att + '"]').attr("selected", "");
    $(this).remove();
  });
  
  $("#edit-bvl-sectors").click(function() {
  	$("#easyselect").empty();
	var postdata = $('#node-form').serialize();  	
    $.ajax({
      type: "POST",
      url: path,
      cache: false,
      dataType: "json",    
      data: postdata,
      success: function(html){
        $("#easyselect").append(html.data);
        select_subsectors();
      }
    })
  });

});

  function select_subsectors() {
	$("#edit-bvl-subsectors").click(function() {
		var postdata = $('#node-form').serialize();  
	    $.ajax({
	      type: "POST",
	      url: path,
	      cache: false,
	      dataType: "json",    
	      data: postdata,
	      success: function(html){
	      	$("#easyselectsubsector").empty();
	        $("#easyselectsubsector").append(html.data);
	        select_node();
	      }
	    });
	  });
  }
	  
  function select_node() {
  	
	$("#edit-bvl-nodes").click(function() {  
	  var selected = this.selectedIndex;
	  check_selected(this.options[selected]);
	  
	  $('#edit-field-instelling-nid-nid option[value=""]').attr("selected", "");
	  $('#edit-field-instelling-nid-nid option[value="' + this.options[selected].value + '"]').attr("selected", "selected");
	  $("#easyselect-results span").click(function() {
	    var att = this.getAttribute('value');
	    $('#edit-field-instelling-nid-nid option[value="' + att + '"]').attr("selected", "");
	    $(this).remove();
	  });
	});
  }
  
  function check_selected(optionelement) {
    if (!$('#edit-field-instelling-nid-nid option[value="' + optionelement.value + '"]').attr('selected')) {
	  $("#easyselect-results").append('<span value="'+ optionelement.value + '">' + optionelement.text + '</span>');
	}
  }	  