/*********************************************************/
/*************** KANJI RADICAL DICTIONARY ****************/
/*********************************************************/

// maintain an array of the 
// radicals selected states and
// a global count of selected
var KAD__TOTAL_RADICALS = 252;
var kad__radicals = new Array(KAD__TOTAL_RADICALS+1);
var kad__selected = 0;

// flag that indicates if
// a search is in progress
var kad__searching = false;

// define some text strings in
// an easily editable location
var KAD__TEXT_ERROR = 'Error.';
var KAD__TEXT_NO_KANJI_FOUND = 'No matching kanji found.';
var KAD__TEXT_DEFAULT_SUMMARY = 'Select radicals to begin search.';

// slideout help effects
var kad__radical_helpFx;

// address of the server which 
// handles all ajax http requests
var KAD__SERVER = 'radical.php';




/*********** TOP SECTION (RADICAL GRID) **************/
/*****************************************************/

function kad__reset_search()
{
  // this function resets the radical grid
  // and clears search results when no selections
  // are made or when the reset link is clicked
  for (var i=1; i<=KAD__TOTAL_RADICALS; i++) 
  {
    // ignore missing radicals and go to next one
    if (kad__radicals[i] == undefined) continue;        
    
    // cache the element
    var el = $('rad-'+i);
    
    // update css styles to deselect and enable all radicals
    if (el.hasClass('disabled')) el.removeClass('disabled');    
    if (el.hasClass('selected')) el.removeClass('selected');    
    kad__radicals[i].selected = false;
  }
  
  // no radicals are
  // selected on reset
  kad__selected = 0;
  
  // we need to empty previous results and
  // display the message for no search yet
  $('kad-pg-radical-kanji-results').empty();
  $('kad-pg-radical-no-results').removeClass('hidden');
  
  // also remove all contents of the 
  // details section without any search
  kad__kanji_detail_show_section(null);
  
  // return the top text
  // to its default state
  kad__show_summary(null);
}

function kad__start_search()
{
  // this function makes an ayncrhonous
  // request for the selected radicals
  
  // compose an object with
  // data which will be 
  // translated into post
  var post = new Object;
  post.action = 'search';
  
  // initialize an array which
  // will hold all selected ids
  var selected = new Array();
  
  // loop across all defined radicals and check
  // their selected states and add to selected
  for (var i=1; i<=KAD__TOTAL_RADICALS; i++)
  {
    if (!(kad__radicals[i] instanceof Object)) continue;
    if (kad__radicals[i].selected) selected[selected.length] = i;
  }
  
  // compose a delimited list of ids
  post.selected = selected.join(',');
  
  // activate our search in progress indicates and flag
  $('kad-pg-radical-searching').removeClass('hidden');
  $('kad-pg-radical-summary').addClass('hidden');  
  kad__searching = true;
  
  // execute the ayschronous request using library functions available and setting complete function
  var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__search_complete }).post(post);
}

function kad__search_complete(obj, text)
{
  // this function is called when a
  // search request is completed
  // ensure we have valid response
  if (!(obj instanceof Object)) {
    kad__show_summary(KAD__TEXT_ERROR);
    
    // remove the loading indicator and show summary
    $('kad-pg-radical-searching').addClass('hidden');
    $('kad-pg-radical-summary').removeClass('hidden');
    
    // we are done searching
    kad__searching = false;
    return;
  }
  
  // just assume no matches found when result not an array
  if (!(obj.kanji instanceof Array)) obj.kanji = new Array();
  
  // add profiling
  // data if available
  if (obj.elapsed)
  {
    var el = $('kad-pg-radical-profile');
    if (el) el.set('text', obj.elapsed+'s');
  }
  
  // determine what message to
  // display along top of grid
  var found = obj.kanji.length;
  if (found)
    kad__show_summary(found+' kanji found.', true);
  else kad__show_summary(KAD__TEXT_NO_KANJI_FOUND);
  
  // now empty the results area of the page and extract
  // a reference to the template used to construct results
  var results = $('kad-pg-radical-kanji-results').empty();
  var templ = $('kad-pg-radical-kanji-template');
  
  // loop across kanji in search results
  for (var i=0; i<obj.kanji.length; i++)
  {
    // clone the template and make clone visible
    var kanji = templ.clone().removeClass('hidden');

    // extract the anchor tag which will contain
    // the glyph and construct proper behavior
    var arr = kanji.getChildren('a.kanji-glyph');
    if (arr[0])
    {
      // prepare the kanji glyph link by
      // setting the text of the link and
      // adding the proper handler which
      // allows the default action as well
      // as requests kanji details loaded
      arr[0].set('text', obj.kanji[i]);
      arr[0].store('kanji', obj.kanji[i]);
      arr[0].addEvent('click', function(e) {
          e = new Event(e).stop();
          
          // prepare simply post
          // data requesting detail
          var post = new Object();
          post.action = 'kanjidetail';
          post.kanji = this.retrieve('kanji');
          post.more = 0;
          
          // display the activity indicator until loading operation done
          kad__kanji_detail_show_section('kad-pg-radical-loading-detail');
          
          // execute the ayschronous request using library functions available and setting the proper complete function
          var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__kanji_detail_load_complete }).post(post);
        });
    }
    
    // extract and prepare the proper kanji checkbox value
    var arr = kanji.getChildren('input.kanji-checkbox');
    if (arr[0]) arr[0].value = obj.kanji[i];
    
    // finally insert the
    // kanji html into results
    kanji.inject(results);    
  }
  
  // prepare a copy of the add to list controls which we will insert after all kanji
  var controls = $('kad-pg-radical-kanji-add-to-list').clone().removeClass('hidden');
  
  // assemble the message and loading indicator containers
  // by applying an identifier which can be used for access
  var arr = controls.getChildren('div.kanji-adding');
  if (arr[0]) arr[0].set('id', 'kad-pg-radical-kanji-adding');
  var arr = controls.getChildren('div.kanji-add-result');
  if (arr[0]) arr[0].set('id', 'kad-pg-radical-kanji-add-result');
  
  // extract the add to list button from the controls and attach ajax
  // functionality to process clicks and execute the add operation
  var arr = controls.getChildren('div.kadc-add-to-list-controls'); 
  if (arr[0]) arr = arr[0].getChildren('input.add-button');
  if (arr[0]) arr[0].addEvent('click', function(e) {
      e = new Event(e).stop();
      
      // initialize an object
      // which will be sent as
      // posted variable data
      var post = new Object();
      post.action = 'addmultiplekanji';
      post.kanji = '';
      
      // extract all checkboxes and build a string of kanji characters for all checked items
      var arr = $$('div#kad-pg-radical-kanji-results div.kanji-result input.kanji-checkbox');
      if (arr) for (var i=0; i<arr.length; i++) if (arr[i].checked) post.kanji += arr[i].value;
      
      // extract the list id to which we are adding from the current select value of drop-down
      var arr = $$('div#kad-pg-radical-kanji-results div.kadc-add-to-list-controls .list-id');
      if (arr[0]) post.list = arr[0].value;
      
      // display the activity indicator until operation done
      $('kad-pg-radical-kanji-adding').removeClass('hidden');
      $('kad-pg-radical-kanji-add-result').addClass('hidden');
      
      // execute the ayschronous request using library functions available and setting the proper complete function
      var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__kanji_add_to_list_complete }).post(post);
    });
    
  // dynamically create a specialized select all button for the kanji displayed as the similar button used on other pages cannot have two instances
  var button = new Element('input', { 'type':'button', 'name':'selectall', 'class':'kanji-select-all-button select-all', 'value':'Select All' });
      button.addEvent('click', function(e) {
          e = new Event(e).stop();
          
          // based on the current state
          // of the button we will take
          // the appropriate action next
          if (this.hasClass('select-all'))
          {
            // add proper label and style
            this.value = 'Deselect All';
            this.addClass('deselect-all').removeClass('select-all');
            var state = true;
          }
          else
          {
            // add proper label and style
            this.value = 'Select All';
            this.addClass('select-all').removeClass('deselect-all');
            var state = false;
          }
          
          // after determining if we are selecting or deselecting locate and adjust all checkboxes
          var arr = $$('div#kad-pg-radical-kanji-results div.kanji-result input.kanji-checkbox');
          if (arr) for (var i=0; i<arr.length; i++) { arr[i].checked = state; }
        });
  
  // dynamically insert the newly created
  // select all button before other controls
  var arr = controls.getChildren('div');  
  if (arr[0]) arr[0].grab(button, 'top');
  
  // add the controls to
  // the end of the results
  results.adopt(controls);
  
  // after the results are composed hide the no 
  // results container and adjust the details section    
  $('kad-pg-radical-no-results').addClass('hidden');
  kad__kanji_detail_show_section('kad-pg-radical-no-detail');
  
  // now process the information that was provided
  // which indicates which radicals are neighbors
  // of the radicals that have already been selected
  var enabled = new Array(KAD__TOTAL_RADICALS+1);
  for (var i=1; i<=KAD__TOTAL_RADICALS; i++) enabled[i] = false;
  for (var i=0; i<obj.neighbors.length; i++)
    enabled[obj.neighbors[i]] = true;
 
  // loop across all radical html elements 
  // and adjust styling based on enabled state
  for (var i=1; i<=KAD__TOTAL_RADICALS; i++) 
  {
    // we can ignore radicals that are missing or selected
    if (!(kad__radicals[i] instanceof Object)) continue;
    if (kad__radicals[i].selected) continue;
    
    // use the proper css class to indicate the radical is enabled or disabled
    if (enabled[i]) $('rad-'+i).addClass('enabled').removeClass('disabled');
    else $('rad-'+i).addClass('disabled').removeClass('enabled');
  }
  
  // remove the loading indicator and show summary
  $('kad-pg-radical-searching').addClass('hidden');
  $('kad-pg-radical-summary').removeClass('hidden');
  
  // we are done searching
  kad__searching = false;
}

function kad__show_summary(text, link)
{
  // this shortcut function displays a provided
  // message on the top of the grid and optionally
  // shows the link to jump to search results
  if (!text) text = KAD__TEXT_DEFAULT_SUMMARY;
  
  // when instructed show the link to results
  var el = $('kad-pg-radical-jump-to-results');
  if (el) {
    if (link) el.removeClass('hidden');
    else el.addClass('hidden');
  }
  
  // simply set the text of proper element
  var el = $('kad-pg-radical-summary-text');
  if (el) el.set('text', text);
}




/*********** MIDDLE SECTION (SEARCH RESULTS) **************/
/**********************************************************/

function kad__kanji_add_to_list_complete(obj, text)
{
  // this function is called after an asynchronous
  // action to add kanji from the search results
  // has completed and a message is ready to show
  // ensure that the object response has valid vars
  if (!(obj instanceof Object)) obj = new Object();  
  if (!obj.message) obj.message = 'Error.';
  
  // we can immediately hide the activity indicator
  $('kad-pg-radical-kanji-adding').addClass('hidden');
  
  // we are going to add a link to the beginning
  // of the notice or error message to allow clear  
  var close = new Element('a', { 'href':'#' });
  close.set('text', '[clear]');
  close.addEvent('click', function(e) {
      e = new Event(e).stop();
    
      // respond to close action by ensuring all action divs
      // are hidden although the adding indicator already is
      $('kad-pg-radical-kanji-add-result').addClass('hidden');
      $('kad-pg-radical-kanji-adding').addClass('hidden');
    });
  
  // extract the container into which the message
  // will be placed then continue building elements
  var el = $('kad-pg-radical-kanji-add-result');
  
  // set the proper coloring of the message based on type
  if (obj.success) el.addClass('notice').removeClass('error');
  else el.addClass('error').removeClass('notice');
  
  // remove any previous
  // contents of the 
  // result message
  // container 
  el.empty();
  
  // insert the message and the 
  // closing link html element
  el.set('text', ' '+obj.message);
  el.grab(close, 'top');
  el.removeClass('hidden');
  
  // when an item is added to 
  // a new list we must reload
  // the drop down lists so
  // check for this condition
  if (obj.refresh)
  {
    // create the post data
    // which tells our server
    // to sends the current
    // user kanji list of lists
    var post = new Object();
    post.action = 'refreshddm';
    post.type = 'kanji';
  
    // execute the ayschronous request using library functions available and setting the proper complete function
    var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__kanji_ddm_reload_complete }).post(post);
  }
}

function kad__kanji_ddm_reload_complete(obj, text)
{
  // this function is called after an asynchronous
  // request to fetch the current user kanji lists
  // has completed and drop-down needs refreshing
  
  // since this request is non-critical
  // ensure we have a proper response
  // otherwise just abort and do nothing
  if (!(obj instanceof Object)) return;
  if (!obj.success) return;
  if (!(obj.options instanceof Array)) return;
  
  // extract the drop-down menu from the html content and empty it, abort if we cannot find it  
  var arr = $$('div#kad-pg-radical-kanji-results div.kadc-add-to-list-controls select.list-id');
  if (!arr[0]) return; else var ddm = arr[0];
  ddm.empty();
  
  // now simply loop through the options
  // that have been provided in the response
  // and rebuild all the drop-down elements
  for (var i=0; i<obj.options.length; i++)
    ddm.grab(new Element('option', {'value':obj.options[i].value, 
                                    'text':obj.options[i].text, 
                                    'selected':(obj.options[i].value == obj.selected)}));
}




/*********** LOWER SECTION (KANJI DETAILS) ****************/
/**********************************************************/

function kad__kanji_detail_load_complete(obj, text)
{
  // this function is called after an attempt to
  // load kanji details has been completed and will
  // display all details using templates provided
  // on the page or will display the proper error
  if (!(obj instanceof Object)) obj = new Object();
  
  // first check to
  // see if the response
  // has indicated failure
  if (!obj.success)
  {
    // in this case just show error message and stop our operations
    kad__kanji_detail_show_section('kad-pg-radical-error-detail');
    return;
  }
  
  // extract and clone the details template in preparation for building all kanji data
  var details = $('kad-pg-radical-kanji-detail-template').clone().removeClass('hidden');
  
  // prepare the basic kanji information
  // by inserting response data into template
  var el = details.getElement('div.glyph');
  if (el) el.set('text', obj.glyph);
  var el = details.getElement('div.readings .on-reading .text');
  if (el) el.set('text', obj.on);
  var el = details.getElement('div.readings .kun-reading .text');
  if (el) el.set('text', obj.kun);
  var el = details.getElement('div.readings .meaning .text');
  if (el) el.set('text', obj.meaning);

  // construct the proper url for the sod and soda
  // images for this kanji by appending the identifier
  var el = details.getElement('div.soda-image img');
  if (el) el.src += obj.id;
  var el = details.getElement('div.sod-image img');
  if (el) el.src += obj.id;
  
  // in preparation for building the table of compounds we will clone all the elements
  // that have been provided in the template relating to the compound table then empty
  // the compound table and rebuild its contents using the components extracted here
  var none_available = details.getElement('table.compounds tr.no-compounds').clone();
  var compound_template = details.getElement('table.compounds tr.compound').clone();
  var select_all_button = details.getElement('table.compounds tr.select-all-button').clone();
  var more_link = details.getElement('table.compounds tr.more-link').clone();
  var table = details.getElement('table.compounds tbody');
  table.empty();
  
  // extract the add controls from the template and give
  // the loading indicator and message container unique ids
  var add_to_list = details.getElement('div.add-to-list');
  var el = add_to_list.getElement('div.vocab-adding');
  if (el) el.set('id', 'kad-pg-radical-vocab-adding');
  var el = add_to_list.getElement('div.vocab-add-result');
  if (el) el.set('id', 'kad-pg-radical-vocab-add-result');
  
  // extract the add to list button and attach ajax
  // functionality to process clicks and execute add
  var el = add_to_list.getElement('input.add-button'); 
  if (el) el.addEvent('click', function(e) {
      e = new Event(e).stop();
      
      // initialize an object
      // which will be sent as
      // posted variable data
      var post = new Object();
      post.action = 'addvocab';
      post.vocab = new Array();
      
      // extract all checkboxes and build an array of dictionary identifiers for all checked 
      var arr = $$('div#kad-pg-radical-some-detail table.compounds input.vocab-checkbox');
      if (arr) for (var i=0; i<arr.length; i++) if (arr[i].checked) post.vocab[post.vocab.length] = arr[i].value;
      
      // now create a delimited list
      post.vocab = post.vocab.join(';');
      
      // extract the list id to which we are adding from the current select value of drop-down
      var arr = $$('div#kad-pg-radical-some-detail div.kadc-add-to-list-controls .list-id');
      if (arr[0]) post.list = arr[0].value;
      
      // display the activity indicator until operation done
      $('kad-pg-radical-vocab-adding').removeClass('hidden');
      $('kad-pg-radical-vocab-add-result').addClass('hidden');
      
      // execute the ayschronous request using library functions available and setting the proper complete function
      var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__vocab_add_to_list_complete }).post(post);
    });
  
  // perform a a few tests
  // on the data received
  // to ensure its valid
  var no_compounds = false;
  if (!obj.compounds) no_compounds = true;
  if (!(obj.compounds instanceof Array)) no_compounds = true;
  if (!obj.compounds.length) no_compounds = true;
  
  // display the special
  // empty message or
  // the compound table
  if (no_compounds)
  {
    // a special element has
    // been provided for empty
    table.grab(none_available);
    add_to_list.addClass('hidden');
  }
  else
  {
    // loop across all available compounds and
    // add table rows for each one to the page    
    for (var i=0; i<obj.compounds.length; i++)
    {
      // first get the template row for the data
      var compound = compound_template.clone();
      
      // alternate adding the shading class to rows
      if (i % 2) compound.addClass('kadc-shaded-row');
      
      // extract the checkbox from the template and assign
      // the proper value to it representing the vocab item
      var el = compound.getElement('td.checkbox input');
      if (el) el.value = 'D-'+obj.compounds[i].id;
      
      // now analyze the kanji string for the 
      // vocab if available and link the chars
      var el = compound.getElement('td.kanji');
      var kanji = obj.compounds[i].kanji;
      var ids = obj.compounds[i].kanji_ids;
      if (kanji instanceof Array)
      {
        // loop across each character in
        // the kanji string and check to 
        // see if the character has an id
        // in the kanji database then link
        for (var j=0; j<kanji.length; j++)

          // look at the 
          // corresponding
          // identifier
          if (ids[j])
          {
            // we have a linkable kanji character so build the html
            // anchor tag with the proper action for loading new data
            var a = new Element('a', {'href':'#', 'text':kanji[j]});
            a.store('kanji', kanji[j]);
            a.addEvent('click', function(e) {
              e = new Event(e).stop();
              
              // prepare simple post
              // data requesting detail
              var post = new Object();
              post.action = 'kanjidetail';
              post.kanji = this.retrieve('kanji');
              post.more = 0;
              
              // display the activity indicator until loading operation done
              kad__kanji_detail_show_section('kad-pg-radical-loading-detail');
              
              // execute the ayschronous request using library functions available and setting the proper complete function
              var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__kanji_detail_load_complete }).post(post);
              
            });
            
            // add the anchor
            // in the cell
            el.grab(a);
          }
          
          // otherwise just add the 
          // plan text of the character
          else el.appendText(kanji[j]);
      }
      
      // now extract the kana cell for compound
      // and link to examples if they are available
      var el = compound.getElement('td.kana');
      if (obj.compounds[i].examples)
      {
        // compose the html link to the examples for this vocabulary item and direct the link to open a new window when clicked
        var a = new Element('a', {'href':('/dictionary/examples.php?level=dictionary&id='+obj.compounds[i].id), 'target':'_blank', 
                                  'text':obj.compounds[i].kana});
        el.grab(a);
      }
      
      // when no examples are present just insert
      // the text of the kana string in the cell
      else el.set('text', obj.compounds[i].kana);
        
      // the definition has been prepared and can
      // be inserted directly into the table cell
      var el = compound.getElement('td.definition');
      if (el) el.set('text', obj.compounds[i].definition);
      
      // after the row is 
      // composed add it
      table.grab(compound);
    }
    
    // dynamically assign an action to the select all button
    // for the vocab displayed in the kanji detail section
    var el = select_all_button.getElement('td input');
    el.addEvent('click', function(e) {
      e = new Event(e).stop();
      
      // based on the current state
      // of the button we will take
      // the appropriate action next
      if (this.hasClass('select-all'))
      {
        // add proper label and style
        this.value = 'Deselect All';
        this.addClass('deselect-all').removeClass('select-all');
        var state = true;
      }
      else
      {
        // add proper label and style
        this.value = 'Select All';
        this.addClass('select-all').removeClass('deselect-all');
        var state = false;
      }
      
      // after determining if we are selecting or deselecting locate and adjust checkboxes
      var arr = $$('div#kad-pg-radical-some-detail table.compounds input.vocab-checkbox');
      if (arr) for (var i=0; i<arr.length; i++) { arr[i].checked = state; }
    });
    
    // whenever there is at least 
    // one compound add this button
    table.grab(select_all_button);
    
    // determine if the more link should be present by analyzing the
    // number of compounds we are displaying versus what is available
    if ((obj.compounds_available > 5) && (obj.compounds.length <= 5)) 
    {
      // store the kanji character in the link
      // element and create an event when clicked
      // to reload the details with more compounds
      var el = more_link.getElement('td.link a');
      el.store('kanji', obj.glyph);
      el.addEvent('click', function(e) {
          e = new Event(e).stop();
          
          // prepare simply post
          // data requesting detail
          var post = new Object();
          post.action = 'kanjidetail';
          post.kanji = this.retrieve('kanji');
          post.more = 1;
          
          // display the activity indicator until loading operation done
          kad__kanji_detail_show_section('kad-pg-radical-loading-detail');
          
          // execute the ayschronous request using library functions available and setting the proper complete function
          var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__kanji_detail_load_complete }).post(post);
        });
       
      // add the more link 
      // as last table row 
      table.grab(more_link);
    }      
  }
  
  // after the kanji details are prepared
  // insert them onto the page after clear
  $('kad-pg-radical-some-detail').empty();
  $('kad-pg-radical-some-detail').grab(details);
  
  // after all page building is complete display the details
  kad__kanji_detail_show_section('kad-pg-radical-some-detail');
}

function kad__kanji_detail_show_section(id)
{
  // this function encapsulates the process of toggling the details section to show section content and hiding all others
  if (id == 'kad-pg-radical-no-detail') $(id).removeClass('hidden'); else $('kad-pg-radical-no-detail').addClass('hidden');
  if (id == 'kad-pg-radical-loading-detail') $(id).removeClass('hidden'); else $('kad-pg-radical-loading-detail').addClass('hidden');
  if (id == 'kad-pg-radical-error-detail') $(id).removeClass('hidden'); else $('kad-pg-radical-error-detail').addClass('hidden');
  if (id == 'kad-pg-radical-some-detail') $(id).removeClass('hidden'); else $('kad-pg-radical-some-detail').addClass('hidden');
}

function kad__vocab_add_to_list_complete(obj, text)
{
  // this function is called after an asynchronous
  // action to add vocab from the detail section
  // has completed and a message is ready to show
  // ensure that the object response has valid vars
  if (!(obj instanceof Object)) obj = new Object();
  if (!obj.message) obj.message = 'Error.';
  
  // we can immediately hide the activity indicator
  $('kad-pg-radical-vocab-adding').addClass('hidden');
  
  // we are going to add a link to the beginning
  // of the notice or error message to allow clear  
  var close = new Element('a', { 'href':'#' });
  close.set('text', '[clear]');
  close.addEvent('click', function(e) {
      e = new Event(e).stop();
    
      // respond to close action by ensuring all action divs
      // are hidden although the adding indicator already is
      $('kad-pg-radical-vocab-add-result').addClass('hidden');
      $('kad-pg-radical-vocab-adding').addClass('hidden');
    });
  
  // extract the container into which the message
  // will be placed then continue building elements
  var el = $('kad-pg-radical-vocab-add-result');
  
  // set the proper coloring of the message based on type
  if (obj.success) el.addClass('notice').removeClass('error');
  else el.addClass('error').removeClass('notice');
  
  // remove any previous
  // contents of the 
  // result message
  // container 
  el.empty();
  
  // insert the message and the 
  // closing link html element
  el.set('text', ' '+obj.message);
  el.grab(close, 'top');
  el.removeClass('hidden');
  
  // when an item is added to 
  // a new list we must reload
  // the drop down lists so
  // check for this condition
  if (obj.refresh)
  {
    // create the post data
    // which tells our server
    // to sends the current
    // user vocab list of lists
    var post = new Object();
    post.action = 'refreshddm';
    post.type = 'vocab';
  
    // execute the ayschronous request using library functions available and setting the proper complete function
    var request = new Request.JSON({ url: KAD__SERVER, onComplete: kad__vocab_ddm_reload_complete }).post(post);
  }
}

function kad__vocab_ddm_reload_complete(obj, text)
{
  // this function is called after an asynchronous
  // request to fetch the current user vocab lists
  // has completed and drop-down needs refreshing

  // since this request is non-critical
  // ensure we have a proper response
  // otherwise just abort and do nothing
  if (!(obj instanceof Object)) return;
  if (!obj.success) return;
  if (!(obj.options instanceof Array)) return;
  
  // extract the drop-down menu from the html content and empty it, abort if we cannot find it  
  var arr = $$('div#kad-pg-radical-some-detail div.kadc-add-to-list-controls select.list-id');
  if (!arr[0]) return; else var ddm = arr[0];
  ddm.empty();
  
  // now simply loop through the options
  // that have been provided in the response
  // and rebuild all the drop-down elements
  for (var i=0; i<obj.options.length; i++)
    ddm.grab(new Element('option', {'value':obj.options[i].value, 
                                    'text':obj.options[i].text, 
                                    'selected':(obj.options[i].value == obj.selected)}));
}








window.addEvent('domready', function() {
  
  
  /*********** TOP SECTION (RADICAL GRID) **************/
  /*****************************************************/
  
  // establish the click handlers for all radical boxes in the grid adding the
  // proper functionality for responding to new selections and execute search
  var kad__radical_boxes = $$('div#kad-pg-radical div.radical-grid a.radical');
  kad__radical_boxes.addEvent('click', function(e) {
    e = new Event(e).stop();
    
    // ignore all clicks on disabled boxes
    if (this.hasClass('disabled')) return;
    
    // no changes to search in
    // progress so we will abort
    if (kad__searching) return;
    
    // now determine the current
    // selected state of the radical
    // that has received the click
    if (this.hasClass('selected'))
    {
      // we will need to deselect 
      // extract the integer id from
      // the html element identifier
      var arr = this.id.split('-');      
      var id = parseInt(arr[1]);
      
      // update global information vars
      kad__radicals[id].selected = false;      
      kad__selected--;
      
      // adjust the css properties
      this.removeClass('selected');
      
      // handle the special case where no radicals
      // are selected and reset the radical grid
      if (kad__selected <= 0) kad__reset_search();
            
      // otherwise execute search
      // based on the new selections
      else kad__start_search();
    }
    else
    {
      // we will need to select this
      // radical so first get id value
      var arr = this.id.split('-');      
      var id = parseInt(arr[1]);
      
      // update global information vars
      kad__radicals[id].selected = true;      
      kad__selected++;
      
      // adjust the css properties
      this.addClass('selected');
      
      // search kanji based
      // on new selections
      kad__start_search();
    }
  });
  
  // establish the slide out/in effects for the page details
  kad__radical_helpFx = new Fx.Slide('kad-pg-radical-intro');
  kad__radical_helpFx.hide();
  $('kad-pg-radical-help').addEvent('click', function(e) { 
    e = new Event(e).stop();
    $('kad-pg-radical-intro').removeClass('hidden');
    kad__radical_helpFx.toggle();
  });
  
  // enable the reset button by 
  // establishing call to function
  var el = $('kad-pg-radical-reset');
  if (el) el.addEvent('click', function(e) {
    e = new Event(e).stop();
    kad__reset_search();
  });
  
  // initialize the array of radical selected
  // states taking care to leave missing radicals
  // undefined within the array of radical objects
  for (var i=1; i<=KAD__TOTAL_RADICALS; i++) 
    if ($('rad-'+i))
    {
      kad__radicals[i] = new Object();
      kad__radicals[i].selected = false;
    }
  
  // show default summary
  // after page is loaded
  kad__show_summary(null);
  
});
