var opiniones_editadas=1; //dejar en 1 para correcto funcionamiento
var total_opiniones_seleccionadas = 0; //por defecto, no hemos seleccionado nada   
var ids_en_uso = new Array();
    
function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;
}

//carga campo de form buscador con contenido de elemento <a> que lo ha invocado
function cargarFormValue(field_id,obj) {
    //borramos los valores de busqueda actuales
    borrarFormValues('form_buscador');
    $(field_id).value = obj.innerHTML;
    $('form_buscador').submit();
}

//borra todos los valores del form_id que no sean de tipo 'hidden','submit', 'button'
function borrarFormValues(form_id) {
    elems = Form.getElements($(form_id));
    $A(elems).each(function(child) {
        if(child.type != 'hidden' && child.type != 'submit' && child.type != 'button')
        child.value="";
    });
    return true;
}

//comprueba que al menos un campo de la busqueda de admin contenga valores
function comprobarSearch(form_id) {
    busqueda_correcta = false;
    elems = Form.getElements($(form_id));
    $A(elems).each(function(child) {
        if(child.type != 'hidden' && child.type != 'submit' && child.type != 'button' && child.value != 'void') {
            if(child.value != '') busqueda_correcta = true;
        }
    });
    if(busqueda_correcta == true) {
        $(form_id).submit(); 
    }else {
        alert('Al menos has de rellenar un criterio de busqueda');
    }
}

//envia todos los formularios
function sendAllFormsOpinion() {
    //primero paramos el monitor de opiniones por editar (Ajax.PeriodicalUpdater que esta en editar.tpl)
    pendientes_editar.updater.stop();
    //mostramos imagen de waiting...
    Element.hide($('batch_enviar_forms'));
    Element.show($('waiting_atrapalo'));
    //enviamos los forms en bateria, en modo sincrono
    forms = document.getElementsByTagName('form');
    $A(forms).each(function(child) {
        if(child.name != 'index_menu_form') {
            submitFormByAjax(child);
        }
    });
    //volvemos a arrancar el updater
    pendientes_editar.updater.start();
    var categoria_producto = $('categoria_producto').value;
    var subproducto = $('subproducto').value;
    var nueva_url = $('referer').value;
    //if(nueva_url == "") {
    var nueva_url = '/opiniones/index.php?pg=editarnuevas&categoria_producto='+categoria_producto+'&subproducto='+subproducto;
    //}
    // alert(nueva_url);
    document.location.href = nueva_url; 
    return true;
}

function aumentaOpinionesEditadas() {
    //aumentamos en 1 el marcador de opiniones editadas
    $('opiniones_editadas').innerHTML = opiniones_editadas++;   
}

function removeElement(id_form) {
    if($(id_form)) {   
        Element.remove($(id_form));
    }
}

//elimina un form de la vista de edicion (accion posponer edicion)
function removeForm(e) {
    id_posponer_edicion = Event.element(e).id;
    //devuelve posponer_editar_125 => 125
    var id_final = id_posponer_edicion.substring(17,id_posponer_edicion.length);
    //aumentamos listado de opiniones que ya se han visto
    if (!in_array(id_final, ids_en_uso)) {
      ids_en_uso[ids_en_uso.length] = id_final;
    }
    ids_en_uso_str = getIdsEnUso();
    //ahora obtenemos el nombre del form que hemos de quitar del DOM
    var id_form = 'form_opinion_'+id_final;
    var cod_producto_actual = $(id_form).cod_producto.value;
    var subproducto = $(id_form).subproducto.value;
    //El siguiente efecto (fade) ya se encarga de eliminar el form del DOM
    Effect.Fade($(id_form));
    Element.remove($(id_form));
    //------------------------------------
    //envia el form usando Ajax
    new Ajax.Request("recupera_opinion.php", {
      method : 'post',
      parameters : 'ids_en_uso='+ids_en_uso_str+'&cod_producto='+cod_producto_actual+'&subproducto='+subproducto,
      onComplete: function (resp) {
       if (resp.responseText == "error") {
         alert("¡No se ha podido recuperar una nueva opinion!");        
       } else {
           var opiniones = eval(resp.responseText);
           construyeForm(opiniones[0]); //aunque solamente tengamos 1 valor, hay que acceder al array
       }
      } 
    });
    Event.stop(e);
    //------------------------------------
}

//envia form de opiniones en background
function sendFormOpinion(e) {
  //recuperamos el id del objeto form para referenciarlo
  form_obj = Event.element(e);
  id_form = Event.element(e).id;
  ids_en_uso_str = getIdsEnUso();
  
//  form_elements = Form.getElements($(id_form));
//  text_opinion = $(form_elements)[4].value;
 //envia el form usando Ajax
 var parametros_form = Form.serialize(form_obj);
 new Ajax.Request("guarda_opinion.php", {
   method : 'post',
   parameters : parametros_form+'&ids_en_uso='+ids_en_uso_str,
   onComplete: function (resp) {
    if (resp.responseText == "error") {
      alert("¡No se ha podido modificar la opinion!");        
    } else {
        //todo bien, efecto de animacion y eliminamos el nodo del DOM
        Effect.Pulsate($(id_form), {duration: 1});
        //borramos las sugerencias, si las hay
        removeElement('tabla_sugerencias');
        //ponemos un timeout para eliminar el elemento del dom cuando haya acabado el evento
        setTimeout('removeElement(id_form)',1200);
        //aumentamos en 1 el marcador de opiniones editadas
        aumentaOpinionesEditadas();        
        //hemos recogido nueva_opinion automaticamente (JSON)
        var opiniones = eval(resp.responseText);
        construyeForm(opiniones[0]); //aunque solamente tengamos 1 valor, hay que acceder al array
    }
   } 
 });
 Event.stop(e);
}

//vamos a iterar por todo el document para ver los ids de opinion
//que no nos ha de enviar el guardar_opinion mediante JSON, ya que 
//al estar en el documento actual no queremos que se repitan
function getIdsEnUso() {
    if(ids_en_uso.length == 0) {
        //recogemos ids_en_uso por primera vez
        var elems = document.getElementsByTagName('form')
        $A(elems).each(function(child) {
            var elem_name = child.name;
            if(elem_name.search('form_opinion_') != -1) {
                ids_en_uso[ids_en_uso.length] = elem_name.substring(13);
            }
        });
    }
    //convertimos a str
    if(ids_en_uso.length != 0) {
      return ids_en_uso.join(',');
    }else {
      return '';
    }
}

function submitFormByAjax(form_obj) {
     id_form = form_obj.id;
     
     // submit the form using Ajax
     new Ajax.Request("guarda_opinion.php", {
       method : 'post',
       asynchronous: false,
       parameters : Form.serialize(form_obj)+'&modo=guardar_solamente',
       onComplete: function (resp) {
        if (resp.responseText == "error") {
          alert("¡No se ha podido modificar la opinion!");        
        }else {
          //aumentamos en 1 el marcador de opiniones editadas
          aumentaOpinionesEditadas();             
        }
       } 
     });
}

function construyeForm(opinion) {
    //ahora montamos en el DOM el nuevo form y lo colocamos al final
    var html = DomBuilder.apply();

    //decodificamos la opinion y el pseudonimo 
    text_opinion = unescape(opinion.opinion);
    text_pseudonimo = unescape(opinion.pseudonimo);

    //parseado de fechas
    var fecha_parts = opinion.fecha.split(" ");
    var fecha_tmp = fecha_parts[0];
    var fecha_tmp_parts = fecha_tmp.split("-");
    var fecha_ES = fecha_tmp_parts[2]+'-'+fecha_tmp_parts[1]+'-'+fecha_tmp_parts[0];
    
    //obtenemos label de reserva asociada
    if(opinion.reserva == 0) {
       opinion.reserva = 's/r';
    }else if(opinion.reserva == 1) {
       opinion.reserva = 'migrada';
    }
    
    //obtenemos url de ver datos de pedido para HOT
    if(opinion.cod_producto == 'HOT' && opinion.reserva > 1) {
       id_pedido_html = html.A({href: 'https://admin.atrapalo.com/hoteles/index.php?pg=pedidos&accion=details&id_pedido='+opinion.reserva, target: '_blank'},' '+opinion.reserva)
    }else {
       id_pedido_html = html.SPAN(opinion.reserva)
    }
    
    // Por si vienen vacio...
    if(opinion.poblacion == null)   
        opinion.poblacion = '--';
    if( (opinion.valoracion_media == null) || (opinion.valoracion_media == 0) )   
        opinion.valoracion_media = '0';
                    
    var form = html.FORM({id: 'form_opinion_'+opinion.id_opinion, 
                          name: 'form_opinion_'+opinion.id_opinion, 
                          onsubmit: 'return false;'},
                          html.FIELDSET({'class' : 'opinion_fieldset'},
                                           html.LEGEND(opinion.nombre_producto),
                                           html.TABLE({'class' : 'opinion_table', 
                                                       cellpadding : '0',
                                                       cellspacing : '0'},
                                                       html.THEAD(),
                                                       html.TBODY(
                                                           html.TR(
                                                                html.TD({colspan: '4'},
                                                                    html.STRONG('Población: '),
                                                                    html.SPAN(opinion.poblacion),
								                                    html.SPAN(' '),
                                                                    html.STRONG('Proveedor: '),
                                                                    html.SPAN(opinion.nombre_proveedor)),
                                                                html.TD({width: '10'}),
                                                                html.TD(
                                                                    html.STRONG('Fecha Opinión: '),
                                                                    html.SPAN(fecha_ES))
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '4'}, html.STRONG('Reserva asociada: '), id_pedido_html),
                                                                html.TD({width: '10'}),
                                                                html.TD(html.STRONG('Experiencia general: '), html.SPAN(opinion.valoracion_media+''))
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '6'}, html.STRONG('Objectivo principal de la reserva: '), html.SPAN(opinion.objectivo_principal_reserva+''))
                                                                ),                                                                
                                                            html.TR(
                                                                html.TD({colspan: '6'}, html.STRONG('Los integrantes de la reserva eran: '), html.SPAN(opinion.integrantes_reserva+''))
                                                                ),                                                                
                                                            html.TR(
                                                                html.TD({colspan: '6'}, html.STRONG('Recomendarias a tu mejor amigo?: '), html.SPAN(opinion.html_recomendacion_amigo+''))
                                                                ),                                                                
                                                            html.TR(
                                                                html.TD({colspan: '6'}, 
                                                                    html.STRONG('Me gustó: '),                                                                     
                                                                    html.INPUT({type: 'text',
                                                                                name: 'megusto',
                                                                                size: '70',
                                                                                value: opinion.megusto
                                                                               }))
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '6'}, 
                                                                    html.STRONG('No me gustó: '),                                                                     
                                                                    html.INPUT({type: 'text',
                                                                                name: 'nomegusto',
                                                                                size: '70',
                                                                                value: opinion.nomegusto
                                                                               }))
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '6'}, 
                                                                    html.STRONG('Titulo: '),                                                                     
                                                                    html.INPUT({type: 'text',
                                                                                name: 'titulo',
                                                                                size: '70',
                                                                                value: opinion.titulo_opinion
                                                                               }))
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '4'},
                                                                    html.TEXTAREA({id: opinion.id_opinion,
                                                                                   name: 'opinion',
                                                                                   cols: '70',
                                                                                   rows: '5'},text_opinion)),
                                                                html.TD({width: '10'}),
                                                                html.TD(html.STRONG('Valoración: '),
                                                                        html.BR(),
                                                                        html.TABLE({'class': 'opinion_valoracion',
                                                                                    cellpadding: 0,
                                                                                    cellspacing: 0},
                                                                                    html.TBODY({id: 'valoraciones_container_'+opinion.id_opinion},
                                                                                        html.TR(
                                                                                            html.TD(' '),
                                                                                            html.TD(),
                                                                                            html.TD(' '),
                                                                                            html.TD()
                                                                                        )
                                                                                    )
                                                                                   )
                                                                        )
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '4'},
                                                                    html.INPUT({type: 'checkbox',
                                                                                onclick: 'this.form.opinion.value=this.form.opinion.value.toLowerCase();'
                                                                               }),
                                                                    ' Pasar opinión a minúsculas    ',
                                                                    html.INPUT({type: 'checkbox',
                                                                                id: 'posponer_edicion_'+opinion.id_opinion
                                                                               }),
                                                                    ' Posponer edición    ',
                                                                    html.INPUT({type: 'checkbox',
                                                                                id: 'enviado_a_proveedor_'+opinion.id_opinion,
                                                                                name: 'enviado_a_proveedor'
                                                                               }),
                                                                    ' Enviar a proveedor'                                                                     
                                                                ),                                                               
                                                                html.TD({colspan: '2'})
                                                            ),                                                                                                                                                                                                 
                                                            html.TR(
                                                                html.TD({colspan: '4'},
                                                                    html.BR()
                                                                ),
                                                                html.TD(),
                                                                html.TD()                                                                     
                                                                ),                                                                
                                                            html.TR(
                                                                html.TD({colspan: '4'},
                                                                    html.SPAN('Nombre: '),
                                                                    html.INPUT({type: 'text',
                                                                                name: 'pseudonimo',
                                                                                size: '15',
                                                                                value: text_pseudonimo
                                                                               }),
                                                                    html.SPAN(' '),
                                                                    html.A({href: 'mailto:'+opinion.email_usuario},opinion.email_usuario),
                                                                    html.SPAN('  '),
                                                                    html.A({href: 'http://secure.atrapalo.com/admin/visor_admin.php3?pg=ver_usuario&idusuario='+opinion.id_usuario, target: '_blank'},' (ver datos usuario)')                                                                    
                                                                    ),
                                                                html.TD({colspan: '2'}
                                                                    )
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '6'},
                                                                    html.SPAN('Nº opiniones en este producto: '),
                                                                    html.SPAN(opinion.num_opiniones_usuario_producto+' | '),
                                                                    html.SPAN('Nº opiniones total: '),
                                                                    html.SPAN(opinion.num_opiniones+'')
                                                                    )
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '4'},
                                                                        html.STRONG('Idioma: '),
                                                                        html.SELECT({name: 'cod_idioma', id: 'cod_idioma_'+opinion.id_opinion},
                                                                            html.OPTION({value: 'es'},'Castellano'),
                                                                            html.OPTION({value: 'it'},'Italiano'),
                                                                            html.OPTION({value: 'fr'},'Francés'),
                                                                            html.OPTION({value: 'en'},'Inglés'),
                                                                            html.OPTION({value: 'ca'},'Catalán')),
                                                                        html.STRONG(' Estado: '),
                                                                        html.SELECT({name: 'nuevo_estado'},
                                                                            html.OPTION({value: '8'},'Queja'),
                                                                            html.OPTION({value: '4'},'Sobre Atrapalo'),
                                                                            html.OPTION({value: '3'},'No publicable'),
                                                                            html.OPTION({value: '2', selected: 'selected'},'Publicable'),
                                                                            html.OPTION({value: '1'},'Home'))
                                                                ),
                                                                html.TD({colspan: '2'})
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '6'},
                                                                    html.BR())
                                                                ),
                                                            html.TR(
                                                                html.TD({colspan: '6'},
                                                                    html.DIV({align: 'center'},
                                                                        html.INPUT({type: 'submit',
                                                                                    name: 'guardar',
                                                                                    value:'Guardar',
                                                                                    'class': 'red'}),
                                                                        html.INPUT({type: 'hidden',
                                                                                    name: 'id_opinion',
                                                                                    value: opinion.id_opinion}),
                                                                        html.INPUT({type: 'hidden',
                                                                                    name: 'estado',
                                                                                    value: opinion.estado}),
                                                                        html.INPUT({type: 'hidden',
                                                                                    name: 'cod_producto',
                                                                                    value: opinion.cod_producto}),
                                                                        html.INPUT({type: 'hidden',
                                                                                    name: 'subproducto',
                                                                                    value: opinion.subproducto})
                                                                        )
                                                                    )
                                                                )                                                                                                                                                                                                                                                                                                                                                                                
                                                          )
                                                   ),html.BR()
                         )
    );
    $('listado_opiniones').appendChild(form);
    
    //hack para determinar el cod_idioma
    if(opinion.cod_idioma == 'es') cod_idioma_selectedIndex = 0;
    if(opinion.cod_idioma == 'it') cod_idioma_selectedIndex = 1;
    if(opinion.cod_idioma == 'fr') cod_idioma_selectedIndex = 2;
    if(opinion.cod_idioma == 'en') cod_idioma_selectedIndex = 3;
    if(opinion.cod_idioma == 'ca') cod_idioma_selectedIndex = 4;
    //cambiamos combo cod_idioma al idioma correspondiente
    $('cod_idioma_'+opinion.id_opinion).selectedIndex=cod_idioma_selectedIndex;
    
    //ahora le colocamos las valoraciones al TBODY container_valoraciones
    if(opinion.valoraciones != null)
    {
        var html2 = DomBuilder.apply();
	    opinion.valoraciones.each(
	        function(item, index) {
	            var valoracion_html = html2.TR(
	                                           html2.TD('  '),
	                                           html2.TD(html2.SPAN(item.descripcion_categoria)),
	                                           html2.TD(' '),
	                                           html2.TD(html2.SPAN(item.valoracion))
	                                          );
	            $('valoraciones_container_'+opinion.id_opinion).appendChild(valoracion_html);                                
	        }
	    );
	}

    // Si la opinion tiene sugerencias:
    if(opinion.sugerencias != null)
    {
	    if(opinion.sugerencias.length > 0)
	    {
	        // Creamos la tabla_sugerencias
	        var html3 = DomBuilder.apply();
	        var tabla_sug = html3.TABLE({id: 'tabla_sugerencias', 'class':'sugerencias_table_admin'},
	                                html3.THEAD(),
	                                html3.TBODY({id:'body_sugerencias'}, 
	                                    html3.TR(
	                                         html3.TH({colspan: '6'}, html3.SPAN('Sugerencias del Viajero (se aprobarán conjuntamente con la opinión)') )
	                                    )
	                                )
	                              );
	        $('listado_opiniones').appendChild(tabla_sug);

	        // Para cada sugerencia, creamos una fila en la tabla, con un formulario sug_form dentro.
	        var html4 = DomBuilder.apply();
	        opinion.sugerencias.each
	        (
	            function(item, index) 
	            {
	                var indice = index + 1;
	                var cat_nombre = '?'
	                if (sugerencias_array != 'null')
	                   cat_nombre = sugerencias_array[item.id_categoria_sugerencia];
	                
	                var sugerencia_html = html4.TR({id: item.id_sugerencia}, 
	                                         html4.TD({colspan: '6'},
	                                              // Formulario sug_form 
						                          html4.FORM({id: 'sug_form'+item.id_sugerencia, method: 'post', action: '#', onsubmit: 'return false;'},
					                                      // Tabla sugerencias_indiv
								                          html4.TABLE({'class' :'sugerencias_indiv'},
                                                          // Cabecera
								                             html4.TR(
								                               html4.TH({'colspan': '2'}, html4.STRONG('Sugerencia '+indice+':') )
								                             ),
                                                             html4.TR(
                                                               // Columna Izquierda
                                                               html4.TD( 
                                                                    html4.DIV({'class':'floatl width20'}, 'Categoría'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.SPAN(cat_nombre) ), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'Título'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_titulo', value:item.titulo, type:'text', maxlength:'100', size:'45'}) ), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'Sugerencia'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.TEXTAREA({id:'sug_texto', 'class':'sugerencia_textarea'},item.texto) ), 
                                                                    html4.DIV({'class':'clear padding2'})
                                                               ),
                                                               // Columna Derecha
                                                               html4.TD(
                                                                    html4.DIV({'class':'floatl width20'}, 'Direccion'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_direccion', value:item.direccion, type:'text', maxlength:'100', size:'45'})), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'Población'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_poblacion', value:item.poblacion, type:'text', maxlength:'100', size:'45'})), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'Website'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_website', value:item.website, type:'text', maxlength:'100', size:'45'})), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'E-Mail'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_mail', value:item.mail, type:'text', maxlength:'100', size:'45'})), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'Contacto'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_contacto', value:item.contacto, type:'text', maxlength:'100', size:'45'})), 
                                                                    html4.DIV({'class':'clear padding2'}),
                                                                    html4.DIV({'class':'floatl width20'}, 'Teléfono'),
                                                                    html4.DIV({'class':'floatl width80'}, html4.INPUT({id:'sug_telefono', value:item.telefono, type:'text', maxlength:'100', size:'45'})), 
                                                                    html4.DIV({'class':'clear padding2'})
                                                                    )
                                                             ),
                                                             // Pie
                                                             html4.TR(
                                                               html4.TD({colspan:'2'},
                                                                    html4.P({'class':'sugerencia_links'}, 
                                                                        html4.A({href:'javascript:void(0)', onclick:'admin_actualizar_sugerencia('+item.id_sugerencia+')'}, 'Actualizar'), 
                                                                        html4.SPAN(' | '),
                                                                        html4.A({href:'javascript:void(0)', onclick:'admin_eliminar_sugerencia('+item.id_sugerencia+')'}, 'Eliminar')
                                                                    )
                                                               )
                                                             )
								                          )
                                                        )
	                                                 )
	                                               );
	                $('body_sugerencias').appendChild(sugerencia_html);
	            }
	        );
	    }
    }

    //aumentamos listado de opiniones que ya se han visto
    if (!in_array(opinion.id_opinion, ids_en_uso)) {
      ids_en_uso[ids_en_uso.length] = opinion.id_opinion;
    }
  
    //finalmente, le conectamos los eventos a observar
    setTimeout(function() {
        watcheaNuevoEvento('form_opinion_'+opinion.id_opinion,'posponer_edicion_'+opinion.id_opinion);
    },1500);
}

function watcheaNuevoEvento(form_id,posponer_id) {
    Event.observe($(form_id), "submit", sendFormOpinion, false);
    Event.observe($(posponer_id), "click", removeForm, false); 
}

//cambia estado de la opinion a publicable/no publicable
function togglePublicable(obj,id_opinion) {
    if($(obj).checked == 1) {
        nuevo_estado = 2; //publicable
    }else {
        nuevo_estado = 3; //no publicable
    }
    //desactivamos el checkbox de home    
    $('opinion_'+id_opinion+'_home').checked = 0;
    
    new Ajax.Request("actualiza_opinion.php", {
     onSuccess : function(resp) {
     },
     onFailure : function(resp) {
         
     },
     onComplete: function (resp) {
      if (resp.responseText == "successful") {
        Effect.Pulsate($('opinion_'+id_opinion), {duration: 1});
      } else {
        alert("¡No se ha podido actualizar el estado de la opinion!");
      }
     },         
     parameters : "id_opinion="+id_opinion+"&nuevo_estado="+nuevo_estado+"&cod_producto="+cod_producto
    });
    //Despues de 1 segundo y milesimas (tras effect.pulsate) cambiamos el color del fondo
    //si se trata de una opinion no publicable
    setTimeout('togglePublicableAuxiliar('+nuevo_estado+','+id_opinion+')',1200);    
}

function togglePublicableAuxiliar(nuevo_estado,id_opinion) {
    obj = $('opinion_'+id_opinion);
    if(isObject(obj)) {
        if(nuevo_estado == 3) {
            setBackgroundColor(obj,'#efbcbc');
            obj.onMouseOut="setBackgroundColor(obj,'#efbcbc')";
        }else {
            setBackgroundColor(obj,'#eeeeee');
            obj.onMouseOut="setBackgroundColor(obj,'#eeeeee')";
        }
    }
}

function setBackgroundColor(obj,new_color) {
    if(!isObject(obj)) {
        obj = $(obj);
    }
    obj.style.backgroundColor=new_color;
}

function isObject(a) {
     return (typeof a == 'object' && !!a) || isFunction(a);
}

//cambia estado de la opinion a home/publicable
function toggleHome(obj,id_opinion) {
    opinion_node = 'opinion_'+id_opinion;
    if($(obj).checked == 1) {
        nuevo_estado = 1; //estado home
        $('opinion_'+id_opinion+'_publicable').checked = 0;            
    }else {
        nuevo_estado = 2; //estado publicable
        $('opinion_'+id_opinion+'_publicable').checked = 1;            
    }
    //desactivamos el checkbox de publicable

    
    new Ajax.Request("actualiza_opinion.php", {
     onSuccess : function(resp) {
       //alert("The response from the server is: " + resp.responseText);
     },
     onFailure : function(resp) {
     },
     onComplete: function (resp) {
      if (resp.responseText == "successful") {
        Effect.Pulsate($(opinion_node), {duration: 1});
      } else {
        alert("¡No se ha podido actualizar el estado de la opinion!");
      }
     },         
     parameters : "id_opinion="+id_opinion+"&nuevo_estado="+nuevo_estado
    });    
}

//CHECKBOX DE OPINIONES EN LISTADO
function modifica_opiniones() {
    var items = '';
    var elems = Form.getElements($('form_resultados'));
    $A(elems).each(function(child) {
        var elem_name = child.name;
        if(elem_name.search('editar_opinion') != -1 && child.checked == true) {
        items += child.value+",";
        }
    });    

    if(items == '') {
        alert("Debe seleccionar al menos una opinion");
        return false;
    }else {
        //quitamos la coma del final
        items = items.substring(0,items.length-1);
        $('opiniones_a_editar').value = items;
        //no cambiar por funciones prototype, que sino no funciona en IExplorer
        document.form_resultados.pg.value='editarseleccionadas';
        document.form_resultados.submit();
    }
}

function modificar_opinion(id_opinion) {
        $('opiniones_a_editar').value = id_opinion;
        //no cambiar por funciones prototype, que sino no funciona en IExplorer
        document.form_resultados.pg.value='editarseleccionadas';
        document.form_resultados.submit();        
}

function toggle_seleccion_opiniones() {
    var toggle_checkbox = $('seleccionar_todas');
    var elems = Form.getElements($('form_resultados'));
    
    if(toggle_checkbox.checked == true) {
        //las marcamos todas
        var new_state = 'true';
        
    }else {
        //las desmarcamos todas
        var new_state = '';
    }
    //recorremos todos los elementos y marcamos/desmarcamos    
    $A(elems).each(function(child) {
        var elem_name = child.name;
        if(elem_name.search('editar_opinion') != -1) {
        child.checked = new_state;
        }
    });   
}

//funciones de guardar opinion en opina.tpl y recomendarias.tpl
function sendAllForms(redir) {
    if(valoraciones_cambiadas == false) {
        if(confirm(val_no_cambiadas)) {
            sendAllFormsAux(redir);
        }
    }else {
        sendAllFormsAux(redir);
    }
    return true;
}

function sendAllFormsAux(redir) {
    //mostramos imagen de waiting...
    Element.hide($('batch_enviar_forms'));
    Element.show($('waiting_atrapalo'));
    
    var envia = false;
    $A(forms).each(function(child) {    
        //miramos si el nombre del form contiene el string 'ratingform'
        if(child.name.match('ratingform'))
        {
            if (child.formulario.value == 'opina')
            {
                if(checkForm(child)) {
                    sendFormHelper(child);
                    envia = true;                
                    }
            }
            else if (child.formulario.value == 'opigra')
            {
                    sendFormHelper(child);
                    envia = true;                
            }
            if (envia)
            {
                if (redir == 'opigra')
                    document.location.href = 'http://'+subdominio+'.'+dominio+'/'+str_opiniones+'/opigra?envia=1';
                    //document.location.href = "/"+str_opiniones+'/opigra';
                else if (redir == 'gracias')
                    document.location.href = 'http://'+subdominio+'.'+dominio+'/'+str_opiniones+'/gracias?envia=1';
                    //document.location.href = "/"+str_opiniones+'/gracias';
                else
                    document.location.href = redir;
            }
            else
            { 
                Element.hide($('waiting_atrapalo'));            
                Element.show($('batch_enviar_forms'));
            }
        }
    });
    
    return true;           
}
   
function sendFormHelper(form_obj) {
     // submit the form using Ajax, asynchronous = false es obligado
     new Ajax.Request('http://'+subdominio+'.'+dominio+'/'+str_opiniones+'/guardaopinion', {
       method : 'post',
       asynchronous: false,
       parameters : Form.serialize(form_obj),
       onComplete: function (resp) {
        if (resp.responseText == "error") {
          alert("¡No se ha podido guardar la opinion!");        
        }
       } 
     });
}

function guardaOpinion() {
     Element.hide($('batch_enviar_forms'));
     Element.show($('waiting_atrapalo'));  
     // submit the form using Ajax, asynchronous = false es obligado
     new Ajax.Request('http://'+subdominio+'.'+dominio+'/'+str_opiniones+'/guardaopinion', {
       method : 'post',
       asynchronous: false,
       //parameters : Form.serialize(form_obj),
       onComplete: function (resp) {
        if (resp.responseText == "error") {
          alert("¡No se ha podido guardar la opinion!");        
        }
        else
          document.location.href = 'http://'+subdominio+'.'+dominio+'/'+str_opiniones+'/gracias?envia=1';
       } 
     });
}

function checkForm(form_obj){
    allok = 1;
    val_exp = 0;
    
    for (var i=0; i < form_obj.experienciageneral.length; i++)
    {
        if (form_obj.experienciageneral[i].checked)
        {
            val_exp = 1;
        }
    }
    if (val_exp == 0)
    {
        allok = 0;
        alert(val_no_experiencia);
    }
    
    if (Trim(form_obj.opinion.value) == "")
    {
        allok = 0;
        alert(val_no_texto);
    }
    //if (Trim(form_obj.pseudonimo.value) == "") allok = 0;
    
    if ( allok == 1 ) {
        return true; 
    }else {
        return false;
    }

}

function checkFormRecomend(form_obj){
    allok = 1;
    //alert(form_obj.amigo.value);
    //if (Trim(form_obj.amigo.value) == "") allok = 0;
    
    if ( allok == 1 ) {
        return true; 
    }else {
        return false;
    }

}



//maguilar: funciones TRIM
function Trim(TRIM_VALUE){
    if(TRIM_VALUE.length < 1){
    return"";
    }
    TRIM_VALUE = RTrim(TRIM_VALUE);
    TRIM_VALUE = LTrim(TRIM_VALUE);
    if(TRIM_VALUE==""){
        return "";
    }
    else{
    return TRIM_VALUE;
    }
} 

function RTrim(VALUE){
    var w_space = String.fromCharCode(32);
    var v_length = VALUE.length;
    var strTemp = "";
    if(v_length < 0){
        return"";
    }
    var iTemp = v_length -1;
    
    while(iTemp > -1){
        if(VALUE.charAt(iTemp) == w_space){
        }
        else{
            strTemp = VALUE.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;
    } 
    return strTemp;
} 

function LTrim(VALUE){
    var w_space = String.fromCharCode(32);
    if(v_length < 1){
        return"";
    }
    var v_length = VALUE.length;
    var strTemp = "";
    var iTemp = 0;
    
    while(iTemp < v_length){
        if(VALUE.charAt(iTemp) == w_space){
        }
        else{
            strTemp = VALUE.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    } 
    return strTemp;
}

//bug: 16903
function TratoRadio(grupo_radio)
{
    //al menos ha cambiado una valoracion
    valoraciones_cambiadas = true;
	if(!grupo_radio) return;

	for(var i=0; i<grupo_radio.length; i++){
		if(grupo_radio[i].checked == true){
  			valorConcepto(i+1, grupo_radio[i].name);
		}
	}
}

function labelNuevoConcepto(obj_str,valoracion_str) {
    document.getElementById(obj_str).innerHTML = valoracion_str;
}

function valorConcepto(tipo_categoria, nom_radio)
{
	switch(tipo_categoria)
	{
		case 0:   
			document.getElementById("tag_"+nom_radio).innerHTML = no_valorado;
			break;
		case 1:
			document.getElementById("tag_"+nom_radio).innerHTML = mal;
			break;
		case 2:
			document.getElementById("tag_"+nom_radio).innerHTML = regular;
			break;
		case 3:
			document.getElementById("tag_"+nom_radio).innerHTML = normal;
			break;
		case 4:
			document.getElementById("tag_"+nom_radio).innerHTML = bien;
			break;
		case 5:
			document.getElementById("tag_"+nom_radio).innerHTML = muy_bien;
			break;
	}
}
//fin bug
//-------------------------------------------

function valorActual(obj_str) {
   radio_obj = document.getElementsByName(obj_str);
   marca_no_valorado = true;
   for(i=0;i<radio_obj.length;i++) {
      if(radio_obj[i].checked == true) {
          marca_no_valorado = false;
          if(i+1 == 1) document.getElementById("tag_"+obj_str).innerHTML = mal;
          if(i+1 == 2) document.getElementById("tag_"+obj_str).innerHTML = regular;
          if(i+1 == 3) document.getElementById("tag_"+obj_str).innerHTML = normal;
          if(i+1 == 4) document.getElementById("tag_"+obj_str).innerHTML = bien;
          if(i+1 == 5) document.getElementById("tag_"+obj_str).innerHTML = muy_bien;
      }
   }
   if(marca_no_valorado == true) document.getElementById("tag_"+obj_str).innerHTML = no_valorado;
   return false;
}

// ----------------------------------------------------
// ----------------- SECCION RESPUESTAS ---------------
// ----------------------------------------------------


// ------------ Seccion: Listado respuestas -----------

var respuestas_editadas = 1;            //dejar en 1 para correcto funcionamiento
var total_respuestas_seleccionadas = 0; //por defecto, no hemos seleccionado nada   
var ids_respuestas_en_uso = new Array();

// Comprueba las fechas del buscador y si están correctas, lanza la busqueda de respuestas
function comprobar_enviar()
{
     var fecha_desde = document.form_buscador.fecha_desde.value;
     var fecha_hasta = document.form_buscador.fecha_hasta.value;
     var msg_error = '';
     
     // Comprobamos las fechas de consulta (yyyy/mm/dd)
     if ( fecha_desde != '')
     {
        var fda = fecha_desde.split('/');
        if(!isDate(fda[1]+'/'+fda[2]+'/'+fda[0]))
            msg_error += '- La fecha DESDE debe tener el formato (yyyy/mm/dd)\n';
     }
     
     if( fecha_hasta != '' )
     {
        var fha = fecha_hasta.split('/');
        if(!isDate(fha[1]+'/'+fha[2]+'/'+fha[0]))
            msg_error += '- La fecha HASTA debe tener el formato (yyyy/mm/dd)\n';
     }
     
     if ( (fecha_desde != '') && (fecha_hasta != '') && (msg_error == '') )
     {
         if (fecha_hasta < fecha_desde)
         {
            msg_error += '- La fecha DESDE ha de ser menor que la fecha HASTA\n';
         }
     }
     
     if(msg_error != '')
     {
        alert('Errores:\n'+msg_error);
     }
     else
     {
        document.form_buscador.submit();
     }
}

//cambia estado de la Respuesta a publicable/no publicable
function toggleRespuestaPublicable(obj,id_respuesta)
{
    if($(obj).checked == 1)
        nuevo_estado = '1'; //publicable
    else
        nuevo_estado = '0'; //no publicable
    
    new Ajax.Request("actualiza_respuesta.php", {
     onSuccess : function(resp) {},
     onFailure : function(resp) {},
     onComplete: function (resp) 
     {
	      if (resp.responseText == 1)
	      {
	        Effect.Pulsate($('respuesta_'+id_respuesta), {duration: 1});
	      }
	      else
	      {
	        alert("¡No se ha podido actualizar el estado de la respuesta! ("+resp.responseText+")");
	        // Lo dejo como estaba
		    if($(obj).checked == 1)    $(obj).checked = 0;
		    else                       $(obj).checked = 1;
	      }
     },         
     parameters : "id_respuesta="+id_respuesta+"&nuevo_estado="+nuevo_estado
    });
    
    //Despues de 1 segundo y milesimas (tras effect.pulsate) cambiamos el color del fondo
    //si se trata de una respuesta no publicable
    setTimeout('toggleRespuestaPublicableAuxiliar('+nuevo_estado+','+id_respuesta+')',1200);    
}

function toggleRespuestaPublicableAuxiliar(nuevo_estado,id_respuesta)
{
    obj = $('respuesta_'+id_respuesta);
    if(isObject(obj)) {
        if(nuevo_estado == 1) {
            setBackgroundColor(obj,'#efbcbc');
            obj.onMouseOut="setBackgroundColor(this,'#efbcbc')";
        }else {
            setBackgroundColor(obj,'#dffbd8');
            obj.onMouseOut="setBackgroundColor(this,'#dffbd8')";
        }
    }
}

function toggle_seleccion_respuestas() 
{
    var toggle_checkbox = $('seleccionar_todas');
    var elems = Form.getElements($('form_resultados'));
    
    if(toggle_checkbox.checked == true) {
        //las marcamos todas
        var new_state = 'true';
    }else {
        //las desmarcamos todas
        var new_state = '';
    }
    //recorremos todos los elementos y marcamos/desmarcamos    
    $A(elems).each(function(child) {
        var elem_name = child.name;
        if(elem_name.search('editar_respuesta_') != -1) {
            child.checked = new_state;
        }
    });   
}

function editar_respuesta(id_respuesta) 
{
	$('respuestas_a_editar').value = id_respuesta;
	document.form_resultados.pg.value='editarrespuestas';
	document.form_resultados.submit();
}

function editar_respuestas_seleccionadas() 
{
    var items = '';
    var elems = Form.getElements($('form_resultados'));
    $A(elems).each(function(child) {
        var elem_name = child.name;
        if(elem_name.search('editar_respuesta') != -1 && child.checked == true)
            items += child.value+",";
    });

    if(items == '') 
    {
        alert("Debe seleccionar al menos una respuesta para editar");
        return false;
    }
    else
    {
        //quitamos la coma del final
        items = items.substring(0,items.length-1);
        $('respuestas_a_editar').value = items;

        //no cambiar por funciones prototype, que sino no funciona en IExplorer
        document.form_resultados.pg.value='editarrespuestas';
        document.form_resultados.submit();
    }
}
// ------------ Sección: Editar Respuestas --------------

//envia form de respuesta en background
function sendFormRespuesta(e) 
{
	  //recuperamos el id del objeto form para referenciarlo
	  form_obj = Event.element(e);
	  id_form = Event.element(e).id;
	  ids_en_uso_str = getIdsRespuestasEnUso();

	  //envia el form usando Ajax
	  new Ajax.Request("guarda_respuesta.php", {
		   method : 'post',
		   parameters : Form.serialize(form_obj)+'&ids_en_uso='+ids_en_uso_str,
		   onComplete: function (resp) {
		    if (resp.responseText == "error") {
		      alert("¡No se ha podido modificar la respuesta!");        
		    } else {
		        //todo bien, efecto de animacion y eliminamos el nodo del DOM
		        Effect.Pulsate($(id_form), {duration: 1});
		        //ponemos un timeout para eliminar el elemento del dom cuando haya acabado el evento
		        setTimeout('removeElement(id_form)',1200);
		        //aumentamos en 1 el marcador de opiniones editadas
		        $('respuestas_editadas').innerHTML = respuestas_editadas++;        
		        //hemos recogido nueva_opinion automaticamente (JSON)
		        var respuestas = eval(resp.responseText);
		        //aunque solamente tengamos 1 valor, hay que acceder al array
		        construyeFormRespuesta(respuestas[0]);
		    }
		   } 
	 });
	 Event.stop(e);
}

//vamos a iterar por todo el document para ver los ids de respuesta
//que no nos ha de enviar el guardar_respuesta mediante JSON, ya que 
//al estar en el documento actual no queremos que se repitan
function getIdsRespuestasEnUso() 
{
    //recogemos ids_respuestas_en_uso por primera vez
    if(ids_respuestas_en_uso.length == 0) 
    {
        var elems = document.getElementsByTagName('form')
        $A(elems).each(function(child) {
            var elem_name = child.name;
            if(elem_name.search('form_respuesta_') != -1) {
                ids_respuestas_en_uso[ids_respuestas_en_uso.length] = elem_name.substring(15);
            }
        });
    }
    
    //convertimos a str
    if(ids_respuestas_en_uso.length != 0) {
      return ids_respuestas_en_uso.join(',');
    }else {
      return '';
    }
}

function construyeFormRespuesta(respuesta)
{
    //ahora montamos en el DOM el nuevo form y lo colocamos al final
    var html = DomBuilder.apply();
    
    //decodificamos la respuesta y el pseudonimo 
    text_opinion = unescape(respuesta.opinion);
    text_respuesta = unescape(respuesta.respuesta);
    
    var form = html.FORM({id: 'form_respuesta_'+respuesta.id_respuesta, 
                          name: 'form_respuesta_'+respuesta.id_respuesta, 
                          onsubmit: 'return false;'},
                          html.FIELDSET({'class' : 'respuesta_fieldset'},
                               html.LEGEND(respuesta.nombre),
                               html.P(html.STRONG('Fecha Respuesta: '), respuesta.fecha_resp),
                               html.P(html.STRONG('Email Usuario: '), html.A({href: 'mailto:'+respuesta.email}, respuesta.email)),
                               html.P(html.STRONG('Opinión: '), html.BR(), text_opinion),
                               html.P(html.STRONG('Respuesta: '), html.BR(), 
                                      html.TEXTAREA({id: respuesta.id_respuesta,
                                                     name: 'respuesta',
                                                     cols: '70',
                                                     rows: '5'},text_respuesta),
                                      html.INPUT({type: 'checkbox', onclick: 'this.form.respuesta.value=this.form.respuesta.value.toLowerCase();'}),' Pasar opinión a minúsculas'                                      
                                      ),
                               html.P(html.STRONG('Idioma: '),
                                      html.SELECT({name: 'cod_idioma', id: 'cod_idioma_'+respuesta.id_respuesta},
		                                          html.OPTION({value: 'es'},'Castellano'),
		                                          html.OPTION({value: 'it'},'Italiano'),
		                                          html.OPTION({value: 'fr'},'Francés'),
		                                          html.OPTION({value: 'en'},'Inglés'),
		                                          html.OPTION({value: 'ca'},'Catalán')),
                                      html.STRONG(' Estado: '),
                                      html.SELECT({name: 'nuevo_estado'},
		                                          html.OPTION({value: '0', selected: 'selected'},'Pendiente'),
		                                          html.OPTION({value: '1'},'Publicable'))
                                     ),
                               html.P({align: 'right'},html.INPUT({type: 'submit',
                                                                   name: 'Guardar',
                                                                   value:'Guardar',
                                                                   'class': 'red'})),
                               html.BR(),
                               html.INPUT({type: 'hidden',
                                           name: 'id_respuesta',
                                           value: respuesta.id_respuesta}),
                               html.INPUT({type: 'hidden',
                                           name: 'cod_producto',
                                           value: respuesta.cod_producto})
                           )
                         );
    $('listado_respuestas').appendChild(form);
    
    //cambiamos combo cod_idioma al idioma correspondiente
    if(respuesta.cod_idioma == 'es') cod_idioma_selectedIndex = 0;
    if(respuesta.cod_idioma == 'it') cod_idioma_selectedIndex = 1;
    if(respuesta.cod_idioma == 'fr') cod_idioma_selectedIndex = 2;
    if(respuesta.cod_idioma == 'en') cod_idioma_selectedIndex = 3;
    if(respuesta.cod_idioma == 'ca') cod_idioma_selectedIndex = 4;
    $('cod_idioma_'+respuesta.id_respuesta).selectedIndex=cod_idioma_selectedIndex;

    //aumentamos listado de respuestas que ya se han visto
    if (!in_array(respuesta.id_respuesta, ids_respuestas_en_uso))
      ids_respuestas_en_uso[ids_respuestas_en_uso.length] = respuesta.id_respuesta;
    
    //finalmente, le conectamos los eventos a observar
    setTimeout(function() {
        watcheaNuevaRespuesta('form_respuesta_'+respuesta.id_respuesta);
    },1500);
}

function watcheaNuevaRespuesta(form_id)
{
    Event.observe($(form_id), "submit", sendFormRespuesta, false);
}

//envia todos los formularios
function sendAllFormsRespuesta()
{
    //primero paramos el monitor de opiniones por editar (Ajax.PeriodicalUpdater que esta en editar.tpl)
    pendientes_editar.updater.stop();
    
    //mostramos imagen de waiting...
    Element.hide($('batch_enviar_forms'));
    Element.show($('waiting_atrapalo'));
    
    //enviamos los forms en bateria, en modo sincrono
    forms = document.getElementsByTagName('form');
    $A(forms).each(function(child) {
        if(child.name != 'index_menu_form')
            submitFormRespuestaByAjax(child);
    });
    
    //volvemos a arrancar el updater
    pendientes_editar.updater.start();

    //recargamos la url    
    var cod_producto = $('cod_producto_url').value;
    var subproducto = $('subproducto_url').value;
    var nueva_url = '/opiniones/index.php?pg=editarrespuestas&cod_producto='+cod_producto+'&subproducto='+subproducto;
    document.location.href = nueva_url;
     
    return true;
}

function submitFormRespuestaByAjax(form_obj)
{
     // submit the form using Ajax
     new Ajax.Request("guarda_respuesta.php", {
       method : 'post',
       asynchronous: false,
       parameters : Form.serialize(form_obj)+'&modo=guardar_solamente',
       onComplete: function (resp) 
       {
	        if (resp.responseText == "error")
	          alert("¡No se ha podido modificar la respuesta!");        
	        else
	          $('respuestas_editadas').innerHTML = respuestas_editadas++;
       } 
     });
}

// ----------------- QTF_VIAJES -------------------

function guardar_sugerencia()
{
    var id_sugerencia           = document.forms['sug_form'].id_sugerencia.value;
    if (id_sugerencia == '')    var accion = 'insert';
    else                        var accion = 'update';
            
    var id_opinion              = document.forms['sug_form'].id_opinion.value;
    var id_categoria_sugerencia = document.forms['sug_form'].sug_categoria.value;
    var id_destino              = document.forms['sug_form'].id_destino.value;
    var id_tipo_destino         = document.forms['sug_form'].id_tipo_destino.value;
    var cod_idioma              = document.forms['sug_form'].cod_idioma.value;
    var titulo                  = document.forms['sug_form'].sug_titulo.value;
    var texto                   = document.forms['sug_form'].sug_texto.value;
    var direccion               = document.forms['sug_form'].sug_direccion.value;
    var poblacion               = document.forms['sug_form'].sug_poblacion.value;
    var website                 = document.forms['sug_form'].sug_website.value;
    var mail                    = document.forms['sug_form'].sug_mail.value;
    var contacto                = document.forms['sug_form'].sug_contacto.value;
    var telefono                = document.forms['sug_form'].sug_telefono.value;

    var error_msg = '';

    // Comprobamos los campos del formulario    
    if(id_categoria_sugerencia == 0)
        error_msg += "- Elija una categoría de la sugerencia\n";
    if(titulo == '')
        error_msg += "- El título de la sugerencia es obligatorio\n";
    if(texto == '')
        error_msg += "- El texto de la sugerencia es obligatorio\n";
    if(telefono != '')
        error_msg += validate_phone(telefono);
    if(website != '')
        error_msg += validate_url(website);
    if(mail != '')
        error_msg += validate_mail(mail);
    
    if(error_msg != '')
    {
        alert('Se han encontrado los siguientes errores:\n'+error_msg);
    }
    else
    {
        var post_params =   "id_sugerencia="+id_sugerencia+
                            "&id_opinion="+id_opinion+
                            "&id_categoria_sugerencia="+id_categoria_sugerencia+
                            "&id_destino="+id_destino+
                            "&id_tipo_destino="+id_tipo_destino+
                            "&cod_idioma="+cod_idioma+
                            "&titulo="+titulo+
                            "&texto="+texto+
                            "&direccion="+direccion+
                            "&poblacion="+poblacion+
                            "&website="+website+
                            "&mail="+mail+
                            "&contacto="+contacto+
                            "&telefono="+telefono;
                            
        var callback ={ 
                timeout: 10000,
                success: function(o) 
                {
                    // Sugerencia insertada/actualizada correctamente
                    var id_sugerencia = parseInt(o.responseText);
                    if(id_sugerencia > 0)
                    {
                        // Limpiamos los campos del formulario
                        document.forms['sug_form'].id_sugerencia.value = '';
                        
                        document.forms['sug_form'].sug_categoria.value = 0;
					    document.forms['sug_form'].sug_titulo.value = '';
					    document.forms['sug_form'].sug_texto.value = '';
					    document.forms['sug_form'].sug_direccion.value = '';
					    document.forms['sug_form'].sug_poblacion.value = '';
					    document.forms['sug_form'].sug_website.value = '';
					    document.forms['sug_form'].sug_mail.value = '';
					    document.forms['sug_form'].sug_contacto.value = '';
                        document.forms['sug_form'].sug_telefono.value = '';
                        $('div_respuesta_sugerencia').innerHTML = '';
                        
                        if(accion == 'insert')
                        {
	                        // Insertamos una sugerencia en la tabla
	                        insertarSugerenciaTabla(id_sugerencia, id_categoria_sugerencia, titulo, texto);
	                    }
	                    else if (accion == 'update')
	                    {
	                       // Actualizamos la sugerencia en la tabla
	                       actualizarSugerenciaTabla(id_sugerencia, id_categoria_sugerencia, titulo, texto);
	                    }
                    }
                    // Error en la operación de la BBDD
                    else
                    {
	                    $('div_respuesta_sugerencia').innerHTML = o.responseText;
	                }
                }
            }
        // Llamada AJAX    
        YAHOO.util.Connect.asyncRequest("POST", "/"+str_opiniones+"/do_ajax?action=guardar_sugerencia", callback, post_params );
        
    }
}

function eliminar_sugerencia(id_sugerencia)
{
	var post_params = "id_sugerencia="+id_sugerencia;
	var callback ={ 
	        timeout: 10000,
	        success: function(o) 
	        {
	            // Sugerencia borrada correctamente
	            if(o.responseText > 0)
	            {
	                // Limpiamos los campos del formulario
	                $('div_respuesta_sugerencia').innerHTML = '';
	                // Borramos la sugerencia de la tabla
	                borrarSugerenciaTabla(id_sugerencia);
	            }
	            // Error en el borrado
	            else
	            {
	                $('div_respuesta_sugerencia').innerHTML = "Error SQL: No se ha encontrado la sugerencia";
	            }
	        }
	    }
	
	// Llamada AJAX
	YAHOO.util.Connect.asyncRequest("POST", "/"+str_opiniones+"/do_ajax?action=borrar_sugerencia", callback, post_params );
}


function editar_sugerencia(id_sugerencia)
{
    var post_params = "id_sugerencia="+id_sugerencia;
    var callback ={ 
            timeout: 10000,
            success: function(o) 
            {
                // Sugerencia editada correctamente
                if(o.responseText != 0)
                {
                    sugerencia_o = YAHOO.lang.JSON.parse(o.responseText);
                    // Rellenamos los campos del formulario
                    document.forms['sug_form'].sug_categoria.value  = sugerencia_o.id_categoria_sugerencia;
                    document.forms['sug_form'].sug_titulo.value     = sugerencia_o.titulo;
                    document.forms['sug_form'].sug_texto.value      = sugerencia_o.texto;
                    document.forms['sug_form'].sug_direccion.value  = sugerencia_o.direccion;
                    document.forms['sug_form'].sug_poblacion.value  = sugerencia_o.poblacion;
                    document.forms['sug_form'].sug_website.value    = sugerencia_o.website;
                    document.forms['sug_form'].sug_mail.value       = sugerencia_o.mail;
                    document.forms['sug_form'].sug_contacto.value   = sugerencia_o.contacto;
                    document.forms['sug_form'].sug_telefono.value   = sugerencia_o.telefono;
                    // Añadimos el id_sugerencia
                    document.forms['sug_form'].id_sugerencia.value  = sugerencia_o.id_sugerencia;
                    // Limpiamos
                    $('div_respuesta_sugerencia').innerHTML = '';
                }
                // Error al recuperar
                else
                {
                    $('div_respuesta_sugerencia').innerHTML = "Error SQL: No se ha podido editar la sugerencia";
                }
            }
        }
    
    // Llamada AJAX
    YAHOO.util.Connect.asyncRequest("POST", "/"+str_opiniones+"/do_ajax?action=recuperar_sugerencia", callback, post_params );
}

// ------------ Funciones para pintar en la tabla -----------

// Numero de filas en la tabla de Sugerencias
if (typeof num == "undefined")
{
    var num=1;
}

function insertarSugerenciaTabla(id_sug, col1, col2, col3)
{
    var elmTABLE = document.getElementById('tabla_sugerencias');
    var elmTR;
    var elmTD;
    var elmText;
    
    if(col2.length >= 20)
        col2 = col2.substr(0, 20)+'...';
    if(col3.length >= 50)
        col3 = col3.substr(0, 50)+'...';
    
    elmTR = elmTABLE.insertRow(num);
    elmTR.setAttribute("id", id_sug);
    
    elmTD = elmTR.insertCell(0);
    elmText = document.createTextNode(array_sug[col1]);
    elmTD.appendChild(elmText);
    
    elmTD = elmTR.insertCell(1);
    elmText = document.createTextNode(col2);
    elmTD.appendChild(elmText);
    
    elmTD = elmTR.insertCell(2);
    elmText = document.createTextNode(col3);
    elmTD.appendChild(elmText);

    elmTD = elmTR.insertCell(3);
    var htmlNode = document.createElement('span');
    htmlNode.innerHTML = "<a href='javascript:void(0)' onclick='eliminar_sugerencia("+id_sug+")'>Eliminar</a>";
    elmTD.appendChild(htmlNode);
    
    elmTD = elmTR.insertCell(4);
    var htmlNode = document.createElement('span');
    htmlNode.innerHTML="<a href='javascript:void(0)' onclick='editar_sugerencia("+id_sug+")'>Editar</a>";
    elmTD.appendChild(htmlNode);
    
    num++;
    var container = document.getElementById('sugerencias_container');
    if(num > 1 && jscss('check',container,'hidden'))
    {
        jscss('swap',container,'hidden','visible');
        jscss('swap',container,'none','block');
    }
}
 
function borrarSugerenciaTabla(id_sug)
{
	  var tr = document.getElementById(id_sug);
	  
	  if (tr) 
	  {
	    if (tr.nodeName == 'TR') 
	    {
	      var tbl = tr;
	      while (tbl != document && tbl.nodeName != 'TABLE') {
	        tbl = tbl.parentNode;
	      }
	 
	      if (tbl && tbl.nodeName == 'TABLE') 
	      {
	        while (tr.hasChildNodes()) {
	          tr.removeChild( tr.lastChild );
	        }
	        tr.parentNode.removeChild( tr );
	      }
	    }
	  }
    
    num--;
    var container = document.getElementById('sugerencias_container');
    if(num == 1 && jscss('check',container,'visible'))
    {
        jscss('swap',container,'visible','hidden');
        jscss('swap',container,'block','none');
    }
}


function actualizarSugerenciaTabla(id_sug, col1, col2, col3)
{
      var tr = document.getElementById(id_sug);
      
      if (tr) 
      {
        if (tr.nodeName == 'TR') 
        {
          var tbl = tr;
          while (tbl != document && tbl.nodeName != 'TABLE') {
            tbl = tbl.parentNode;
          }
     
          if (tbl && tbl.nodeName == 'TABLE') 
          {
			var tds = tr.cells;
			tds[0].innerHTML = array_sug[col1];
			tds[1].innerHTML = col2;
			tds[2].innerHTML = col3;
          }
        }
      }
}

/*
This example function takes four parameters:
	a:  defines the action you want the function to perform.
	o:  the object in question.
	c1: the name of the first class
	c2: the name of the second class

Possible actions are:
	swap:   replaces class c1 with class c2 in object o.
	add:    adds class c1 to the object o.
	remove: removes class c1 from the object o.
	check:  test if class c1 is already applied to object o and returns true or false.
*/
function jscss(a,o,c1,c2)
{
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

// ---------- VALIDACION DE CAMPOS --------

function validate_url(url)
{
     var regexp = /^(?:http:\/\/)?(?:[\w-]+\.)+[a-z]{2,6}$/
     
     if (regexp.test(url))
         return '';
     else
         return '- El campo Website es una dirección URL incorrecta\n';
}
function validate_mail(mail)
{
     var regexp = /(^[0-9a-zA-Z]+(?:[._][0-9a-zA-Z]+)*)@([0-9a-zA-Z]+(?:[._-][0-9a-zA-Z]+)*\.[0-9a-zA-Z]{2,3})$/
     
     if (regexp.test(mail))
         return '';
     else
         return '- El campo E-Mail es una dirección incorrecta\n';
}
function validate_phone(telefono)
{
     if (telefono.length >= 9)
         return '';
     else
         return '- El campo Teléfono es incorrecto\n';
}