$(document).ready(function() {

  $('.add_to_marked_button').click(function() {
    return add_to_clipboard();
  });

  $('.checkAll_1').click(function() {
    return toggle1();
  });

  $('.checkAll_2').click(function() {
    return toggle2();
  });

  $('.pager-link').click(function() {
    var text = $('.confirm_text').val();
    if ($('input.search_mark:checkbox:checked').size() > 0 && confirm(text)) {
     return !add_to_clipboard();
    }
    return true;
  });

  function add_to_clipboard() {
    // Get a list of record ids for whom the marked checkbox is set
    var ids = new Array();
    var i = 0;
    $('input.search_mark:checkbox:checked').each(function() {
      ids[i++] = $(this).val();
    });

    // POST the checked ids to the addClipboard page and update the corresponding checkboxes
    //$.post('/frontend_dev.php/en/search/AddClipboard', {'search_mark[]': ids}, function(data){
    $.post($('.mark-form').attr('action'), {'search_mark[]': ids}, function(data){
//      console.log("Posting to "+ $('.mark-form').attr('action'));
      if (data == "Success") {
        for(var i=0; i<ids.length; i++) {
          $("#search_txt_mark_" + ids[i]).hide();
          $("#search_mark_" + ids[i]).hide();
          $("#search_txt_marked_" + ids[i]).show();
          $("#search_mark_" + ids[i]).attr('checked', false);
        }
        var ml_count = $(".ml_count").text();
        var new_ml_count = Number(ml_count) + ids.length;
        $("label.btn.marked_count").text("(" + new_ml_count + ")");
      }
    });
    return false;
  }

  function toggle1() {
    // Get a list of record ids for whom the marked checkbox is set
    var ids = new Array();
    var i = 0;

    $('input.search_mark:checkbox').each(function() {
      ids[i++] = $(this).val();
    });

    if (!$('.checkAll_1').is(':checked')) {
        for(var i=0; i<ids.length; i++) {
          $("#search_mark_" + ids[i]).attr('checked', false);
        };
        $('.checkAll_2').attr('checked', false);
    } else {

      for(var i=0; i<ids.length; i++) {
          $("#search_mark_" + ids[i]).attr('checked', true);
      };
      $('.checkAll_2').attr('checked', true);
    }
    return true;
  }

  function toggle2() {
    // Get a list of record ids for whom the marked checkbox is set
    var ids = new Array();
    var i = 0;

    $('input.search_mark:checkbox').each(function() {
      ids[i++] = $(this).val();
    });

    if (!$('.checkAll_2').is(':checked')) {
        for(var i=0; i<ids.length; i++) {
          $("#search_mark_" + ids[i]).attr('checked', false);
        };
        $('.checkAll_1').attr('checked', false);
    } else {

      for(var i=0; i<ids.length; i++) {
          $("#search_mark_" + ids[i]).attr('checked', true);
      };
      $('.checkAll_1').attr('checked', true);
    }
    return true;
  }

});


