/* Control section for locality chooser */

function fillSelect(id,loc_parent,xid,fill_callback)
{
  elem = $(id);

  if (elem == undefined) return 0;

  while ( elem.firstChild ) {
    elem.removeChild(elem.firstChild);
  }

  count = 1;
  for ( i in locs )
  {
    elem.options[0] = new Option(' - '+CHOOSE_TXT+' -',-1);
    // elem.options[0] = new Option('',-1);

    if ( locs[i].parent == loc_parent )
    {
      elem.options[count] = new Option(locs[i].name,locs[i].id);
      count++;
    }
  }
  elem.selectedIndex = 0;

  if (count == 1) {
    elem.style.display = 'none';
    xid += 1;
    tmp_el = $('loc'+xid+'_row');
    while (tmp_el != undefined) {
      tmp_el.style.display = 'none';
      xid += 1;
      tmp_el = $('loc'+xid+'_row');
    }
  }

  if ( fill_callback != undefined ) {
    fill_callback();
  }

  return count-1;
}

function selectClicked(elem, fill_callback, callback)
{
  x = parseInt(elem.getAttribute('x-id'),10);
  el2 = 'locality'+(x+1);

  tmp_parent = $(elem.id);
  sid = tmp_parent.selectedIndex;
  my_parent = tmp_parent.options[sid].value;

  cnt = fillSelect(el2,my_parent,x,fill_callback);

  if ( cnt > 0 )
  {
    $(el2).style.display = 'block';
    $('loc'+(x+1)+'_row').style.display = '';
  }
  if ( callback != undefined ) {
    callback();
  }
}

function Locality(id,name,parent)
{
  this.id = id;
  this.name = name;
  this.parent = parent;
}

function preselectLocality(id)
{
  pole = Array();
  count = 0;
  loc_parent = id;

  // check if it exists
  found = false;
  for ( i in locs )
  {
    if ( locs[i].id == id )
      found = true;
  }
  if ( found == false )
  {
    return;
  }

  while ( loc_parent != 0 )
  {
    for ( i in locs )
    {
      if ( locs[i].id == loc_parent )
      {
        loc_parent = locs[i].parent;
        pole[count] = locs[i].id;
        count+=1;
      }
    }
  }

  pocet_cyklu = 1;
  for ( prvek = pole.length-1 ; prvek >= 0; prvek-- )
  {
    if (pocet_cyklu==1)
      fillSelect('locality'+pocet_cyklu,0);
    else
      fillSelect('locality'+pocet_cyklu,pole[prvek+1]);

    select = $('locality'+pocet_cyklu);
    for ( i = 0; i < select.options.length; i++ )
    {
      if ( select.options[i].value == pole[prvek] )
        select.options.selectedIndex = i;
    }

    $('loc'+pocet_cyklu+'_row').style.display = '';

    pocet_cyklu++;
  }
  return;
}

