// Funcion de comprobacion de enteros.
function isInteger(s)
{
    var i;
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}

// Funcion que hace la llamada ajax para mostrar el carrito de solicitudes.
function mostrar_carrito_solicitudes(accion, ayuda, control)
{
    if (accion == 'delete')
    {
        keys = document.getElementsByName('keys');
        num_keys = keys.length;
        ids = '';
        for(i = 0; i < num_keys; i++)
        {
            if (keys[i].checked)
            {
                if (ids == '')
                    ids = keys[i].value;
                else
                    ids = ids + '_' + keys[i].value;
            }
        }
        parametros = '&accion=delete&ids='+ids;
    }
    else if (accion == 'add')
    {
        parametros = '&accion=add&id='+id;
    }
    else
    {
        parametros = '';
    }
    parametros += '&ayuda='+ayuda;
    parametros += '&c='+control;

    load_url = '/restaurantes/do_ajax?pg_action=carrito_solicitudes' + parametros;

    YAHOO.util.Connect.asyncRequest("get", load_url, {
          timeout: 10000,
          success: function(o) {
             if (o.responseText != '')
             {
                 $('carrito_solicitudes').style.display = '';
                 if (control == 'restaurante')
                 {
                    $('boton_reservar_arriba').style.display = 'none';
                 }
             }
             else
             {
                 if (control == 'restaurante')
                 {
                     $('boton_reservar_arriba').style.display = '';
                 }
             }
             $('carrito_solicitudes').innerHTML = o.responseText;
          },
          failure: function() {
             return false;
          }
    });
}

// Funcion para entrar en el primer paso del carrito de solicitudes.
function enviar_solicitud_carrito()
{
	document.carrito_form.pg.value = 'carrito_solicitudes_paso1';
	document.carrito_form.submit();
}

// Funcion para visualizar los menus del carrito de solicitudes.
function changedisp(whatdiv, whatdisp, whatcover)
{
	if (whatcover == '')
	{
	    document.getElementById(whatdiv).style.display = whatdisp;
	}
	else
	{
		if (whatdisp == 'block')
		{
			document.getElementById(whatdiv).style.display = 'block';
			document.getElementById(whatcover).style.top=document.getElementById(whatdiv).style.top;
			document.getElementById(whatcover).style.left=document.getElementById(whatdiv).style.left;
			document.getElementById(whatcover).style.width=document.getElementById(whatdiv).offsetWidth;
			document.getElementById(whatcover).style.height=document.getElementById(whatdiv).offsetHeight;
			document.getElementById(whatcover).style.display = 'block';
		}
		else
		{
			document.getElementById(whatcover).style.display = 'none';
			document.getElementById(whatdiv).style.display = 'none';
		}
	}
}

function continuar_paso2()
{
    document.carrito_solicitudes_form.pg.value = 'carrito_solicitudes_paso2';
    document.carrito_solicitudes_form.accion.value = '';
    document.carrito_solicitudes_form.id_solicitud.value = '';
    document.carrito_solicitudes_form.submit();
    return true;
}

function continuar_paso3()
{
	if (document.registro.nombre.value == '')
	   errores.push(new Error('14', '044', '001'));
	if (document.registro.apellidos.value == '')
	   errores.push(new Error('14', '044', '002'));
	if (document.registro.telefono.value == '')
	   errores.push(new Error('14', '044', '003'));
	if (document.registro.email.value == '')
	   errores.push(new Error('14', '044', '004'));
	else if (!isEmail(document.registro.email.value))
	   errores.push(new Error('14', '044', '005'));
	if (document.registro.email.value != document.registro.email_repetido.value)
	   errores.push(new Error('14', '044', '007', "El e-mail repetido no coincide con el e-mail introducido."));
    if (errores.cuantos() > 0)
    {
        // errores.showLayer();
        errores.show();
        return;
    }
	else
	{
        document.registro.pg.value='carrito_solicitudes_paso3';
        document.registro.accion.value='';
        document.registro.submit();
        return true;
    }
}

function continuar_paso4()
{
    if (!document.carrito_solicitudes_form.acepto.checked)
    {
	   errores.push(new Error('14', '044', '006'));
    }
    if (errores.cuantos() > 0)
    {
        // errores.showLayer();
        errores.show();
        return;
    }
	else
	{
        document.carrito_solicitudes_form.pg.value = 'carrito_solicitudes_paso4';
        document.carrito_solicitudes_form.accion.value = '';
        document.carrito_solicitudes_form.submit();
        return true;
	}
}

function delete_solicitud(id, pg)
{
    document.carrito_solicitudes_form.pg.value = pg;
    document.carrito_solicitudes_form.accion.value = 'delete';
    document.carrito_solicitudes_form.id_solicitud.value = id;
    document.carrito_solicitudes_form.submit();
    return true;
}

function isEmail(strEmail)
{
    validRegExp = /^[^@]+@[^@]+\.[a-z]{2,}$/i;
    if (strEmail.search(validRegExp) == -1)
   	{
        return false;
   	}
    return true;
}

function validar_login()
{
    if (document.identificacion.email.value == '')
        errores.push(new Error('14', '044', '004'));
	else if(!isEmail(document.identificacion.email.value))
        errores.push(new Error('14', '044', '005'));
    if (errores.cuantos() > 0)
    {
        // errores.showLayer();
        errores.show();
        return;
    }
	else
    {
		document.identificacion.comentarios.value = document.registro.comentarios.value;
		document.identificacion.submit();
	}
}

// Funcion para añadir al carrito una solicitud desde la ficha.
function add_solicitud_carrito(form, ayuda, control)
{
    // La fecha esta preseleccionada y no necesita comprobacion.
    // La hora esta preseleccionada y no necesita comprobacion.

    // Verificar que se haya introducido los pax, sea un valor entero y superior a 10,
    // y que no sea superior a lo que puede el restaurante.
    if ($(form).pax.value == '') errores.push(new Error('14', '043', '002'));
    else if (!isInteger($(form).pax.value)) errores.push(new Error('14', '043', '003'));
    else if ($(form).pax.value < 11) errores.push(new Error('14', '043', '004'));
    else if (parseInt($(form).pax.value) > parseInt($(form).max_pax_grupos.value))
    {
        errores.push(new Error('14', '043', '007'));
    }

    // Verificar que se ha seleccionado un menu.
    if ($(form).menus[$(form).menus.selectedIndex].value == 0) errores.push(new Error('14', '043', '006'));

    // Comprobacion de que la fecha de solicitud este como minimo un dia en el futuro.
    /*
    var limit1 = new Date();
    var limit2 = new Date();
  	limit1.setDate(limit1.getDate() + 1);
   	var evento_date = new Date();
   	evento_date.setTime(Date.parse($(form).fecha.value));
   	limit2.setYear(evento_date.getFullYear());
   	limit2.setMonth(evento_date.getMonth());
   	limit2.setDate(evento_date.getDate());
   	var resta2 = limit2 - limit1;
   	resta2 = Math.round(resta2/1000/60/60/24);
   	if (resta2 < 0) errores.push(new Error('14', '043', '005'));
    */

   	// Si ha habido errores, avisar, sino continuar.
    if (errores.cuantos() > 0)
    {
        // errores.showLayer();
        errores.show();
        return false;
    }
	else
    {
        // Hacer llamada ajax.
        parametros = '&accion=add&id=' + $(form).id_restaurante.value + "-" + $(form).menus[$(form).menus.selectedIndex].value + "-" + $(form).fecha.value + " " + $(form).hora.value + "-" + $(form).pax.value;
        if ($(form).comisionista.value != '')
        {
            parametros += '&comisionista=' + $(form).comisionista.value;
        }
        parametros += '&ayuda='+ayuda;
        parametros += '&c='+control;

        load_url = '/restaurantes/do_ajax?pg_action=carrito_solicitudes' + parametros;
        YAHOO.util.Connect.asyncRequest("get", load_url, {
              timeout: 10000,
              success: function(o) {
                 if (o.responseText != '')
                 {
                     $('carrito_solicitudes').style.display = '';
                     if (control == 'restaurante')
                     {
                        $('boton_reservar_arriba').style.display = 'none';
                     }
                 }
                 else
                 {
                     if (control == 'restaurante')
                     {
                         $('boton_reservar_arriba').style.display = '';
                     }
                 }

                 $('carrito_solicitudes').innerHTML = o.responseText;
              },
              failure: function() {
                 return false;
              }
        });
        // Ir al carrito de solicitudes.
        location.href = '#listadealternativas';
        // No hace falta hacer submit del formulario.
        return false;
	}
}

function check_reserva_indiv(form)
{
	str_err = '';

	// Comprobamos que el nº de personas no sea 0:
	if($(form).pax[$(form).pax.selectedIndex].value == 0)
		str_err = 'Debe seleccionar el número de personas\n';
	
    // Comprobamos si ha seleccionado algún menu:
    if ($(form).menus[$(form).menus.selectedIndex].value == -1)
    	str_err += 'Debe seleccionar el Tipo de reserva\n';
    
    if(str_err == '')
	    $(form).submit();
    else
    	alert(str_err);
}

function viewCondiciones(titulo,texto,url,alto,ancho)
{

    ancho?width=ancho:width="650px";
    alto?height=alto:height="410px";

    oPanel = new YAHOO.widget.Panel("panel",{ width:width,
        height:height,
        underlay:"none",
        close:true,
        draggable:false,
        fixedcenter:true,
        zIndex:1000});
    oPanel.setHeader(titulo?titulo:"LEE ATENTAMENTE");
    if(url)
    {
        YAHOO.util.Connect.asyncRequest('GET',texto,{
            success:function(response)
                {
                    html=response.responseText;
                    oPanel.setBody('<div style="overflow:auto;height:380px;">'+html+'</div>');
                    oPanel.render(document.body);
                    oPanel.show();
                }
        });
    }else{
        oPanel.setBody('<div style="overflow:auto;height:380px;">'+texto+'</div>');
        oPanel.render(document.body);
        oPanel.show();
    }
}