// Add element script.
//

function addElement() 
{
  // Number of rows in contact info
  var contact_rows = 6;

  var table = document.getElementById('yht_table');

  var insert_index = -1;
  var contact_count = 0;
  for (index = 0; index < table.rows.length; index++) 
  {
    if ( table.rows[index].id == 'yhteystiedot')
    {
      insert_index= index + 1;
    }
    if ( table.rows[index].id == 'yhteystieto_valinta')
    {
      contact_count++;
    }
  }

  // Create array
  var new_contact_items = new Array();
  for (clone_index = 0; clone_index < contact_rows; clone_index++)
  {
    // Clone row and childNodes
    var cloned_item = table.rows[insert_index + clone_index].cloneNode(true);
    
    // Clear content of textfields
    for ( child_index in cloned_item.childNodes )
    {
      cloned_item.childNodes[child_index].value = "";
      for ( child_index2 in cloned_item.childNodes[child_index].childNodes )
      {
        if ( cloned_item.childNodes[child_index].childNodes[child_index2].type == 'text' )
        {
          var fieldname = cloned_item.childNodes[child_index].childNodes[child_index2].name;
          fieldname = fieldname.substring(0, fieldname.lastIndexOf("["));
          fieldname = fieldname + "[" + contact_count + "]";
          
          cloned_item.childNodes[child_index].childNodes[child_index2].name = fieldname;
          cloned_item.childNodes[child_index].childNodes[child_index2].value = "";
          cloned_item.childNodes[child_index].childNodes[child_index2].className = "";
        }
        if ( cloned_item.childNodes[child_index].childNodes[child_index2].type == 'select-one' )
        {
          var fieldname = cloned_item.childNodes[child_index].childNodes[child_index2].name;
          fieldname = fieldname.substring(0, fieldname.lastIndexOf("["));
          fieldname = fieldname + "[" + contact_count + "]";
          
          cloned_item.childNodes[child_index].childNodes[child_index2].name = fieldname;
          cloned_item.childNodes[child_index].childNodes[child_index2].value = -1;
          cloned_item.childNodes[child_index].childNodes[child_index2].className = "";
        }
        
      }
    }
    
    new_contact_items.push(cloned_item);
  }

  // Add items to the table
  for ( arr_index in new_contact_items )
  {
    table.insertBefore(new_contact_items[new_contact_items.length - arr_index - 1], table.rows[insert_index]);
  }
}


