function dgi (id) {
  return document.getElementById(id);
}

function toggleSiblings(node)
{
  nodes = node.parentNode.childNodes;
  for (i = 0; i < nodes.length; i++) {
    if (nodes.item(i).className == 'colapsable' && node != nodes.item(i)) {
      nodes.item(i).style.display = nodes.item(i).style.display == 'none'? 'block': 'none';
      hidden = nodes.item(i).style.display == 'none'? true: false;
    }
  }
  loadXMLDoc('../Default/EstadoGui?'+node.id+'='+hidden, bogus);
}

function recheckCategorias()
{
  sel_sect = document.getElementById('sector');
  sel_cate = sel_sect.form.categoria;
  sel_cate.options.length = 0;
  for (cat in categorias) {
    if (sel_sect.selectedIndex >= 0) {
      id_sect = categorias[cat][0];
      if (document.getElementById('s'+id_sect) && document.getElementById('s'+id_sect).selected) {
        option = new Option(categorias[cat][1], cat);
        option.id = 'c' + cat;
        option.className = 's' + id_sect;
        sel_cate.options[sel_cate.options.length] = option;
      }
    } else {
      option = new Option(categorias[cat][1], cat);
      option.id = 'c' + cat;
      option.className = 's' + id_sect;
      sel_cate.options[sel_cate.options.length] = option;
    }
  }
}

function recheckProductos()
{
  sel_cate = document.getElementById('categoria');
  sel_prod = sel_cate.form.producto;
  sel_prod.options.length = 0;
  if (sel_cate.options.length > 0) {
    for (prod in productos) {
      id_cate = productos[prod][0];
      if (sel_cate.selectedIndex >= 0) {
        if (document.getElementById('c'+id_cate) && document.getElementById('c'+id_cate).selected) {
          option = new Option(productos[prod][1], prod);
          option.className = 'c' + id_cate;
          sel_prod.options[sel_prod.options.length] = option;
        }
      } else {
        if (document.getElementById('c'+id_cate)) {
          option = new Option(productos[prod][1], prod);
          option.className = 'c' + id_cate;
          sel_prod.options[sel_prod.options.length] = option;
        }
      }
    }
  }
}

function updateSectorCategoria() {
  id_sector = document.getElementById('categoria').options[document.getElementById('categoria').selectedIndex].className.substring(1);
  document.getElementById('sp' + id_sector).selected = true;
}

function updateCategoriaProducto() {
  id_categoria = document.getElementById('producto').options[document.getElementById('producto').selectedIndex].className.substring(1);
  document.getElementById('cp' + id_categoria).selected = true;
}

function agregarScp() {

  sel_prod = document.getElementById('producto');

  idx_prod = sel_prod.selectedIndex;

  if (idx_prod < 0) {
    alert('Debe seleccionar un producto');
    return false;
  }

  sel_scp = document.getElementById('scp');

  for (i = 0; i < sel_prod.options.length; i++) {

  	if (sel_prod.options[i].selected) {

		  id_categoria = dgi('c' + sel_prod.options[i].className.substr(1)).value;
		  id_sector    = dgi('s' + dgi('c' + id_categoria).className.substr(1)).value;

		  option = new Option(dgi('s' + id_sector).text.substr(0,3) + ' : '
		                      + dgi('c' + id_categoria).text.substr(0,15) + ' : '
		                      + sel_prod.options[i].text,
		                        sel_prod.options[i].value + '|'
		                      + sel_prod.options[i].text + '|'
		                      + id_categoria + '|'
		                      + dgi('c' + id_categoria).text + '|'
		                      + id_sector);

		  sel_scp.options[sel_scp.options.length] = option;

		}

	}

  sel_prod.selectedIndex = -1;
}

function validarForm (f) {
  pasa = true;
  labels = f.getElementsByTagName('label');
  for (i = 0; i < labels.length; i++) {
    if (labels[i].className == 'req') {
      control = document.getElementById(labels[i].htmlFor);
      if (control.value == '' && control.type != 'hidden' && control.disabled == false) {
        if (pasa) control.focus();
        labels[i].style.color = 'red';
        pasa = false;
      } else {
        labels[i].style.color = 'black';
      }
    }
  }
  if (!pasa) alert('Uno o más campos obligatorios no han sido llenados.');
  return pasa;
}

function testEmail (email) {
  if ('' == email || email.indexOf('@') <= 0)
    return false;
  else
    return true;
}

function buscarEnSelect (value, sel_id) {
  options = dgi(sel_id).options;
  for (i = 0; i < options.length; i++) {
  	if (value == options[i].value)
  	  return true;
  }
  return false;
}

function agregarASelect (option, sel_id) {
  options = dgi(sel_id).options;
  options[options.length] = option;
}

var myrules = {
  '#otrodoc_form #contenido_url' : function(i) {
    i.onclick = function() {
      document.getElementById('url').disabled    = false;
      document.getElementById('upload').disabled = true;
    }
  },
  '#otrodoc_form #contenido_upload' : function(i) {
    i.onclick = function() {
      document.getElementById('url').disabled    = true;
      document.getElementById('upload').disabled = false;
    }
  },
  'form' : function(f) {
    f.onsubmit = function() {
      return validarForm(f);
    }
  },
  'a.borrar' : function(a) {
    a.onclick = function() {
      return confirm('¿Desea realmente eliminar este ítem?');
    }
  },
  'legend.colapsable' : function(legend) {
    legend.onclick = function() {
      toggleSiblings(legend);
    }
  },
  '#institucion' : function(select) {
    select.onchange = function() {
      switch(select.options[select.options.selectedIndex].className) {
        case 'archivo':
          document.getElementById('archivo').style.display             = 'block';
          document.getElementById('url').style.display                 = 'none';
          document.getElementById('archivo_consulta_publica').disabled = false;
          document.getElementById('url_consulta_publica').disabled     = true;
          break;
        case 'url':
          document.getElementById('archivo').style.display             = 'none';
          document.getElementById('url').style.display                 = 'block';
          document.getElementById('archivo_consulta_publica').disabled = true;
          document.getElementById('url_consulta_publica').disabled     = false;
          break;
        default:
          document.getElementById('archivo').style.display             = 'none';
          document.getElementById('url').style.display                 = 'none';
          document.getElementById('archivo_consulta_publica').disabled = true;
          document.getElementById('url_consulta_publica').disabled     = true;
          break;
      }
    }
  },
  '#form_emails' : function(f) {
  	f.onsubmit = function() {
  	  seleccionarTodo('informes');
  	  seleccionarTodo('bcn');
  	  return validarForm(f);
  	}
  },
  '#form_documento' : function(f) {
    f.onsubmit = function() {

      seleccionarTodo('scp');
      if (!validarForm(f)) return false;
      dgi('rm_scp').value = rm_scp;
      dgi('rm_doc').value = rm_doc;

      f.categorias_modificados.value  = categorias_modificados;
      f.productos_modificados.value   = productos_modificados;
      f.categorias_borrados.value     = categorias_borrados;
      f.productos_borrados.value      = productos_borrados;

    }
  },
  '.tipo_doc' : function(s) {
    s.onchange = function() {
      index = s.selectedIndex;
      tipo  = s.options[index].value;
      nmod  = s.id.substr(1);
      //alert('nmod='+nmod+',tipo='+tipo);
      switch (tipo) {
        case 'n':
          dgi('m'+nmod+'_div_b').style.display = 'none';
          dgi('m'+nmod+'_div_u').style.display = 'none';
          dgi('m'+nmod+'_div_a').style.display = 'none';
          dgi('m'+nmod+'_c_b').disabled = true;
          dgi('m'+nmod+'_c_u').disabled = true;
          dgi('m'+nmod+'_c_a').disabled = true;
          break;
        case 'b':
          if (es_admin) {
            dgi('m'+nmod+'_div_b').style.display = 'block';
            dgi('m'+nmod+'_c_b').disabled = false;
          }
          dgi('m'+nmod+'_div_u').style.display = 'none';
          dgi('m'+nmod+'_div_a').style.display = 'none';
          dgi('m'+nmod+'_c_u').disabled = true;
          dgi('m'+nmod+'_c_a').disabled = true;
          break;
        case 'u':
          dgi('m'+nmod+'_div_b').style.display = 'none';
          dgi('m'+nmod+'_div_u').style.display = 'block';
          dgi('m'+nmod+'_div_a').style.display = 'none';
          dgi('m'+nmod+'_c_b').disabled = true;
          dgi('m'+nmod+'_c_u').disabled = false;
          dgi('m'+nmod+'_c_a').disabled = true;
          break;
        case 'r':
          dgi('m'+nmod+'_div_b').style.display = 'none';
          dgi('m'+nmod+'_div_u').style.display = 'none';
          dgi('m'+nmod+'_div_a').style.display = 'block';
          dgi('m'+nmod+'_c_b').disabled = true;
          dgi('m'+nmod+'_c_u').disabled = true;
          dgi('m'+nmod+'_c_a').disabled = false;
          break;
      }
    }
  },
  '#agregar_modificacion' : function(b) {
    b.onclick = function() {
    	modificacion    = dgi('encabezado').cloneNode(true);
    	modificacion.id = 'modificacion_' + num_modif;

      elements = modificacion.getElementsByTagName('legend');
      elements[0].firstChild.nodeValue = 'Modificacion #' + num_modif;

      elements = modificacion.getElementsByTagName('input');
      elements[0].value         = '_';
      elements[1].id            = 'nombre_' + num_modif;
      elements[1].value         = '';
      elements[2].id            = 'titulo_' + num_modif;
      elements[2].value         = '';
      elements[3].id            = 'm' + num_modif + '_c_b';
      elements[3].disabled      = true;
      elements[4].id            = 'm' + num_modif + '_c_u';
      elements[4].disabled      = true;
      elements[5].id            = 'm' + num_modif + '_c_a';
      elements[5].disabled      = true;
      elements[6].style.display = 'block';
      elements[6].id            = 'rm_' + num_modif;

      elements = modificacion.getElementsByTagName('select');
      elements[0].id            = 'dia_' + num_modif;
      elements[1].id            = 'mes_' + num_modif;
      elements[2].id            = 'anyo_' + num_modif;
      elements[3].id            = 'm' + num_modif;
      elements[3].selectedIndex = 0;

      elements = modificacion.getElementsByTagName('textarea');
      elements[0].id    = 'descripcion_' + num_modif;
      elements[0].value = '';

      elements = modificacion.getElementsByTagName('label');
      elements[0].htmlFor  = 'nombre_' + num_modif;
      elements[2].htmlFor  = 'dia_' + num_modif;
      elements[3].htmlFor  = 'mes_' + num_modif;
      elements[4].htmlFor  = 'anyo_' + num_modif;
      elements[5].htmlFor  = 'titulo_' + num_modif;
      elements[6].htmlFor  = 'descripcion_' + num_modif;
      elements[7].htmlFor  = 'm' + num_modif;
      elements[8].htmlFor  = 'm' + num_modif + '_c_b';
      elements[9].htmlFor  = 'm' + num_modif + '_c_u';
      elements[10].htmlFor = 'm' + num_modif + '_c_a';

      elements = modificacion.getElementsByTagName('div');
      elements[0].id            = 'm' + num_modif + '_div_n';
      elements[0].style.display = 'none';
      elements[1].id            = 'm' + num_modif + '_div_b';
      elements[1].style.display = 'none';
      elements[2].id            = 'm' + num_modif + '_div_u';
      elements[2].style.display = 'none';
      elements[3].id            = 'm' + num_modif + '_div_a';
      elements[3].style.display = 'none';

    	dgi('contenedor_modificaciones').appendChild(modificacion);
      Behaviour.apply();
      num_modif++;
    }
  },
  'input.remover_modificacion' : function (b) {
    b.onclick = function() {
      if (!confirm('¿Está seguro de que desea eliminar esta modificación?')) {
        return false;
      }
      div_to_remove = dgi('modificacion_' + b.id.substr(3));
      elements = div_to_remove.getElementsByTagName('input');
      rm_doc += elements[0].value + '&';
      dgi('contenedor_modificaciones').removeChild(div_to_remove);
      Behaviour.apply();
    }
  },
  '#agregar_mi_categoria' : function(a) {
  	a.onclick = function() {
  		if (dgi('sector').selectedIndex < 0) {
  			alert('Debe escoger primero el sector al cual pertenecerá la categoría.');
  			return false;
  		}
  		id_sector = dgi('sector').options[dgi('sector').selectedIndex].value;
  		nueva = prompt('Nombre de la nueva categoría', '');
  		if (null == nueva) return false;
  		option = new Option(nueva, '_' + id_nuevas_cate);
  		option.className = 's' + id_sector;
      option.id = 'c_' + id_nuevas_cate;
  		dgi('categoria').options[dgi('categoria').options.length] = option;
  		categorias['_' + id_nuevas_cate] = new Array(id_sector, nueva);
  		id_nuevas_cate++;
  		return false;
  	}
  },
  '#agregar_mi_producto' : function(a) {
  	a.onclick = function() {
  		if (dgi('categoria').selectedIndex < 0) {
  			alert('Debe escoger primero la categoría al cual pertenecerá el producto.');
  			return false;
  		}
  		id_categoria = dgi('categoria').options[dgi('categoria').selectedIndex].value;
  		nuevo = prompt('Nombre del nuevo producto', '');
  		if (null == nuevo) return false;
  		option = new Option(nuevo, '_' + id_nuevos_prod);
  		option.className = 'c' + id_categoria;
  		dgi('producto').options[dgi('producto').options.length] = option;
  		productos['_' + id_nuevos_prod] = new Array(id_categoria, nuevo);
      id_nuevos_prod++;
  		return false;
  	}
  },
  '#agregar_scp' : function(b) {
    b.onclick = function() {
      agregarScp();
    }
  },
  '#eliminar_scp' : function(b) {
    b.onclick = function() {
      rm_scp += eliminarElegidosDeSelect('scp');
    }
  },
  '#producto' : function(sel_prod) {
    sel_prod.onchange = function() {
      if (dgi('categoria_pertenece')) updateCategoriaProducto();
    }
  },
  '#categoria' : function(sel_cate) {
    sel_cate.onchange = function() {
      recheckProductos();
      if (dgi('sector_pertenece')) updateSectorCategoria();
    }
  },
  '#sector' : function(sel_sect) {
    sel_sect.onchange = function() {
      recheckCategorias();
      recheckProductos();
    }
  },
  'a.editar_sector' : function(a) {
    a.onclick = function() {
      index = document.getElementById('sector').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un sector');
        return false;
      }
      sector    = document.getElementById('sector').options[index].text;
      id_sector = document.getElementById('sector').options[index].value;
      if (id_sector == '?') {
        alert('Debe aceptar los cambios antes de modificar este sector');
        return false;
      }
      nombre = prompt('Nuevo nombre', sector);
      if (null == nombre) return false;
      document.getElementById('sector').options[index].text = nombre;
      sectores[id_sector][1] = nombre;
      sectores_modificados += id_sector + '|' + nombre + '&';
      return false;
    }
  },
  'a.editar_categoria' : function(a) {
    a.onclick = function() {
      index = document.getElementById('categoria').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un categoria');
        return false;
      }
      categoria    = document.getElementById('categoria').options[index].text;
      id_categoria = document.getElementById('categoria').options[index].value;
      if (id_categoria == '?') {
        alert('Debe aceptar los cambios antes de modificar esta categoría');
        return false;
      }
      nombre = prompt('Nuevo nombre', categoria);
      if (null == nombre) return false;
      document.getElementById('categoria').options[index].text = nombre;
      categorias[id_categoria][1] = nombre;
      categorias_modificados += id_categoria + '|' + nombre + '&';
      return false;
    }
  },
  'a.editar_producto' : function(a) {
    a.onclick = function() {
      index = document.getElementById('producto').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un producto');
        return false;
      }
      producto    = document.getElementById('producto').options[index].text;
      id_producto = document.getElementById('producto').options[index].value;
      if (id_producto == '?') {
        alert('Debe aceptar los cambios antes de modificar este producto');
        return false;
      }
      nombre = prompt('Nuevo nombre', producto);
      if (null == nombre) return false;
      document.getElementById('producto').options[index].text = nombre;
      productos[id_producto][1] = nombre;
      productos_modificados += id_producto + '|' + nombre + '&';
      return false;
    }
  },
  'a.borrar_sector' : function(a) {
    a.onclick = function() {
      index = document.getElementById('sector').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un sector');
        return false;
      }
      id_sector = document.getElementById('sector').options[index].value;
      if (id_sector == '?') {
        alert('Debe aceptar los cambios antes de eliminar este sector');
        return false;
      }
      if (!confirm('¿Está seguro de que desea borrar este ítem?')) return false;
      document.getElementById('sector').options[index] = null;
      sectores_borrados += id_sector + '&';
      return false;
    }
  },
  'a.borrar_categoria' : function(a) {
    a.onclick = function() {
      index = document.getElementById('categoria').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un categoria');
        return false;
      }
      id_categoria = document.getElementById('categoria').options[index].value;
      if (id_categoria == '?') {
        alert('Debe aceptar los cambios antes de eliminar esta categoría');
        return false;
      }
      if (!confirm('¿Está seguro de que desea borrar este ítem?')) return false;
      document.getElementById('categoria').options[index] = null;
      categorias_borrados += id_categoria + '&';
      return false;
    }
  },
  'a.borrar_producto' : function(a) {
    a.onclick = function() {
      index = document.getElementById('producto').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un producto');
        return false;
      }
      id_producto = document.getElementById('producto').options[index].value;
      if (id_producto == '?') {
        alert('Debe aceptar los cambios antes de eliminar este producto');
        return false;
      }
      if (!confirm('¿Está seguro de que desea borrar este ítem?')) return false;
      document.getElementById('producto').options[index] = null;
      productos_borrados += id_producto + '&';
      return false;
    }
  },
  'a.agregar_sector' : function(a) {
    a.onclick = function() {
      nombre = prompt('Nombre del nuevo sector:');
      if (null == nombre) return false;
      select = document.getElementById('sector');
      select.options[select.options.length] = new Option(nombre, '?');
      sectores_agregados += nombre + '&';
      sectores.push(nombre);
      return false;
    }
  },
  'a.agregar_categoria' : function(a) {
    a.onclick = function() {
      select_sector = document.getElementById('sector');
      if (select_sector.selectedIndex < 0) {
        alert('Debe elegir el sector al cual pertenecerá la nueva categoría');
        return false;
      }
      id_sector = select_sector.options[select_sector.selectedIndex].value;
      if (id_sector == '?') {
        alert('Debe aceptar los cambios antes de agregar categorías a este sector');
        return false;
      }
      nombre = prompt('Nombre de la nueva categoría:');
      if (null == nombre) return false;
      select = document.getElementById('categoria');
      option = new Option(nombre, '?');
      option.className = 's' + id_sector;
      select.options[select.options.length] = option
      categorias_agregados += id_sector + '|' + nombre + '&';
      categorias.push(nombre);
      return false;
    }
  },
  'a.agregar_producto' : function(a) {
    a.onclick = function() {
      select_categoria = document.getElementById('categoria');
      if (select_categoria.selectedIndex < 0) {
        alert('Debe elegir la categoría a la cual pertenecerá el nuevo producto');
        return false;
      }
      id_categoria = select_categoria.options[select_categoria.selectedIndex].value;
      if (id_categoria == '?') {
        alert('Debe aceptar los cambios antes de agregar productos a esta categoría');
        return false;
      }
      nombre = prompt('Nombre del nuevo producto:');
      if (null == nombre) return false;
      select = document.getElementById('producto');
      option = new Option(nombre, '?');
      option.className = 'c' + id_categoria;
      select.options[select.options.length] = option;
      productos_agregados += id_categoria + '|' + nombre + '&';
      productos.push(nombre);
      return false;
    }
  },
  '#sector_pertenece' : function(s) {
    s.onchange = function() {
      index = document.getElementById('categoria').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un categoria');
        return false;
      }
      id_categoria = document.getElementById('categoria').options[index].value;
      if ('?' == id_categoria) {
        alert('Debe aceptar los cambios antes de modificar esta categoría');
        return false;
      }
      id_sector = document.getElementById('sector_pertenece').options[document.getElementById('sector_pertenece').selectedIndex].value;
      id_sectores_cambiados += id_categoria + '|' + id_sector + '&';
      document.getElementById('categoria').options[index].className = 's' + id_sector;
      categorias[id_categoria][0] = id_sector;

      return false;
    }
  },
  '#categoria_pertenece' : function(s) {
    s.onchange = function() {
      index = document.getElementById('producto').selectedIndex;
      if (index < 0) {
        alert('Debe elegir un producto');
        return false;
      }
      for (i = 0; i < dgi('producto').options.length; i++) {
        if (dgi('producto').options[i].selected) {
          id_producto = document.getElementById('producto').options[i].value;
          if ('?' == id_producto) {
            alert('Debe aceptar los cambios antes de modificar estos productos');
            return false;
          }
        }
      }
      for (i = 0; i < dgi('producto').options.length; i++) {
        if (dgi('producto').options[i].selected) {
          id_producto  = document.getElementById('producto').options[i].value;
          id_categoria = document.getElementById('categoria_pertenece').options[document.getElementById('categoria_pertenece').selectedIndex].value;
          id_categorias_cambiados += id_producto + '|' + id_categoria + '&';
          document.getElementById('producto').options[i].className = 'c' + id_categoria;
          productos[id_producto][0] = id_categoria;
        }
      }

      return false;
    }
  },
  '#admin_categorizaciones' : function(f) {
    f.onsubmit = function() {
      f.sectores_modificados.value    = sectores_modificados;
      f.categorias_modificados.value  = categorias_modificados;
      f.productos_modificados.value   = productos_modificados;

      f.sectores_borrados.value       = sectores_borrados;
      f.categorias_borrados.value     = categorias_borrados;
      f.productos_borrados.value      = productos_borrados;

      f.sectores_agregados.value      = sectores_agregados;
      f.categorias_agregados.value    = categorias_agregados;
      f.productos_agregados.value     = productos_agregados;

      f.id_sectores_cambiados.value   = id_sectores_cambiados;
      f.id_categorias_cambiados.value = id_categorias_cambiados;
    }
  },
  '#agregar_email_informe' : function(b) {
    b.onclick = function() {
      email = dgi('new_informe').value;
      if (!testEmail(email)) {
        alert('La dirección de E-Mail no parece válida');
        dgi('new_informe').focus();
        return false;
      }
      if (buscarEnSelect(email, 'informes')) {
        alert('La dirección de E-Mail ya está incluida');
        dgi('new_informe').focus();
        return false;
      }
      option = new Option(email, email);
      agregarASelect(option, 'informes');
      dgi('new_informe').value = '';
      dgi('new_informe').focus();
    }
  },
  '#agregar_email_bcn' : function(b) {
    b.onclick = function() {
      email = dgi('new_bcn').value;
      if (!testEmail(email)) {
        alert('La dirección de E-Mail no parece válida');
        dgi('new_bcn').focus();
        return false;
      }
      if (buscarEnSelect(email, 'bcn')) {
        alert('La dirección de E-Mail ya está incluida');
        dgi('new_bcn').focus();
        return false;
      }
      option = new Option(email, email);
      agregarASelect(option, 'bcn');
      dgi('new_bcn').value = '';
      dgi('new_bcn').focus();
    }
  },
  '#eliminar_emails_informes' : function(b) {
    b.onclick = function() {
      eliminarElegidosDeSelect('informes');
    }
  },
  '#eliminar_emails_bcn' : function(b) {
    b.onclick = function() {
      eliminarElegidosDeSelect('bcn');
    }
  },
  '#back' : function(b) {
    b.onclick = function() {
      history.back(-1);
    }
  },
  '.expande_prods' : function(e) {
  	e.onclick = function() {
  		id = e.id.substr(1);
  		dgi('p'+id).style.display = dgi('p'+id).style.display == 'none'? 'block': 'none';
  	}
  },
  '#ayuda_rtchile_mostrar' : function(c) {
  	c.onclick = function() {
  		dgi('div_ayuda_rtchile_mostrar').style.display = 'none';
  		dgi('fs_ayuda_rtchile').style.display = 'block';
  	}
  },
  '#ayuda_rtchile_ocultar' : function(l) {
  	l.onclick = function() {
  		dgi('fs_ayuda_rtchile').style.display = 'none';
  		dgi('div_ayuda_rtchile_mostrar').style.display = 'inline';
  	}
  }
};

Behaviour.register(myrules);

