$(document).ready(
  function () {
    // get the node id from where we left it in the header
    var nodeid=$("div#nodeid/").val();
    var nodedata;
    // load the current state of the checkboxes once on loading page
    $.getJSON("/ajaxchecklist/loadall/"+nodeid, 
	function(json) {
          nodedata=json;
          //alert(json);
          for( i=0; i < json.length; i++ ) {
             if (json[i].state == "1") {
               $("#"+json[i].qid).attr("checked","true");
             } else {
               $("#"+json[i].qid).removeAttr("checked");
             }
          }

        });
    // setup an onclick for each checkbox that writes it state back to the database
    // when toggled. The label text is turned red while writing to the db.
    $("div.ajaxchecklist/div.form-item/>").each(
	function () {
           $(this).click( 
              function () {
                var thislabel=$(this).parent();
                var colorbefore=$(thislabel).css("color");
                if ( $(this).attr("checked") == undefined ) {
                   $(thislabel).css("color","red"); 
                   $.get("/ajaxchecklist/save/"+nodeid+"/"+$(this).attr("id")+"/0",
			function() {
                          $(thislabel).css("color",colorbefore); 
                        });
                } else {
                   $(thislabel).css("color","red"); 
                   $.get("/ajaxchecklist/save/"+nodeid+"/"+$(this).attr("id")+"/1",
                     function() {
                       $(thislabel).css("color",colorbefore); 
                     });
                }
              });
        });
  }
);
