$(document).ready(function() {
  
  $('#idEdition').change(function(){
    branchesFind();
  });
  
  //$('#city').change(function(){
//    branchesFind();
  //});
  
  $('#companyname').change(function(){
    branchesFind();
  });
  
  $('#zoeken_alle').click(function(){
    // we get the new 'checked' status here
    if (this.checked)
    {
      // store all checkbox states
      branches_selected = new Array(16);
      $('#branches_table').find('input').each(function(elementIndex,elementValue){
        if (elementIndex==0) return; // we can skip the first element, it is the 'ALL' checkbox, we don't need to store it
        branches_selected[elementIndex] = this.checked;
        this.checked = true; // check them all, we selected the 'ALL' checkbox
      });
    }
    else
    {
      for (i=1; i<branches_selected.length; i++)
      {
        $('#branch'+i).attr('checked', false);
        //$('#branch'+i).attr('checked', branches_selected[i]); // this is the restore function
      }
    }
  });



  $('#branches_table').find('input').each(function(elementIndex,elementValue){
    if (elementIndex==0) return;
    
    $(this).click(function(){
      $('#zoeken_alle').attr('checked',false);
    });
    
    //branches_selected = new Array(16);
    //branches_selected[branches_selected.length] = elementValue.name.substr(6);
  });

  var branches_selected = new Array();

  function branchesFind() {

    $.ajax({
      url: 'includes/vacature-vinden-branches.php',
      data: {
        idEdition: $('#idEdition').val(),
        
        companyname: $('#companyname').val()
      },
      cache: false,
      type: 'POST',
      complete: function(XMLHttpRequest, textStatus) {
        //console.log(XMLHttpRequest.responseText);
        
        objects = $('*', $('#branches_table'));
        for (i=0; i<objects.length; i++) 
        {
          if (objects[i].id.indexOf('branch')==0) {
            txt = $('#'+objects[i].id).html();
            strpos = txt.indexOf('(');
            txt = txt.substr(0,strpos);
            txt = txt + '(0)';
            $('#'+objects[i].id).html(txt);
          }
        }
        
        if (XMLHttpRequest.responseText != '')
        {
          branches = $.evalJSON(XMLHttpRequest.responseText);
          
          for (i=0; i<branches.length; i++) {
            //alert(branches[i].idBranch);
            txt = $('#branch'+branches[i].idBranch).html();
            strpos = txt.indexOf('(');
            txt = txt.substr(0,strpos);
            txt = txt + '('+branches[i].aantal+')';
            $('#branch'+branches[i].idBranch).html(txt);
          }
        }
      }
    });
  }
  
});
