/**
 *	 JavaScript Document
 * 
 */

/*created for : Paolo Viera R.*/
var sprytextfield1;
var sprytextfield2;
var sprytextfield3;
var sprytextfield4;
var sprytextfield5;
var sprypassword1;
var spryconfirm1;
var sprytextfield8;
var sprypassword3;
var pasaventana = '';
var pasaclave = '';
function submitSimple() {
    document.buscadorSimple.submit();
}

/* /created for : Paolo Viera R.*/
function MM_findObj(n, d){ //v4.01
    var p, i, x;
    if (!d) 
        d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) 
        x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) 
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) 
        x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) 
        x = d.getElementById(n);
    return x;
}

function MM_preloadImages(){ //v3.0
    var d = document;
    if (d.images) {
        if (!d.MM_p) 
            d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++) 
            if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
    }
}

function MM_showHideLayers(){ //v9.0
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) 
        with (document) 
if (getElementById && ((obj = getElementById(args[i])) != null)) {
            v = args[i + 2];
            if (obj.style) {
                obj = obj.style;
                v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v;
            }
            obj.visibility = v;
        }
}

function MM_swapImgRestore(){ //v3.0
    var i, x, a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) 
        x.src = x.oSrc;
}

function MM_swapImage(){ //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3) 
        if ((x = MM_findObj(a[i])) != null) {
            document.MM_sr[j++] = x;
            if (!x.oSrc) 
                x.oSrc = x.src;
            x.src = a[i + 2];
        }
}

function MM_changeProp(objId, x, theProp, theValue){ //v9.0
    var obj = null;
    with (document) {
        if (getElementById) 
            obj = getElementById(objId);
    }
    if (obj) {
        if (theValue == true || theValue == false) 
            eval("obj.style." + theProp + "=" + theValue);
        else 
            eval("obj.style." + theProp + "='" + theValue + "'");
    }
}

function MM_goToURL(){ //v3.0
    var i, args = MM_goToURL.arguments;
    document.MM_returnValue = false;
    for (i = 0; i < (args.length - 1); i += 2) 
        eval(args[i] + ".location='" + args[i + 1] + "'");
}

//otras funciones

function formularioContacto(){
    sw = 0;
    motivo = "";
    if (!vacio($('#CNT_nombreyapellidos').val())) {
        $('#msgCNT_nombreyapellidos').html("Ingrese su nombre y Apellidos");
        sw = 1;
    }
    if (!vacio($('#CNT_email').val())) {
        $('#msgCNT_email').html("Ingrese su email");
        sw = 1;
    }
    else {
        if (!verificaEmail($('#CNT_email').val())) {
            $('#msgCNT_email').html("E-mail no válido");
            sw = 1;
        }
    }
    if (!vacio($('#CNT_telefono').val())) {
        $('#msgCNT_telefono').html("Ingrese su teléfono");
        sw = 1;
    }
    if (!vacio($('#CNT_ciudad').val())) {
        $('#msgCNT_ciudad').html("Ingrese su ciudad");
        sw = 1;
    }
    if (sw == 0) {
        $(".pantalla").css({
            'position': 'absolute',
            'top': '0',
            'left': '0',
            'z-index': '5555',
            'width': '100%',
            'height': '120%',
            'background': 'url(/wp-content/themes/gourmet/images/fondo.png)',
            'cursor': 'pointer'
        });
        $(".pantalla").html("<div style='height:200px;top:190px;'><img src='/wp-content/themes/gourmet/images/ajax-loader.gif' width='30px' height='30px'></div>");
        
        if ($("#CNT_motivorelacion_1").is(':checked')) 
            motivo = motivo + "&CNT_motivorelacion_1=" + $('#CNT_motivorelacion_1').val();
        if ($("#CNT_motivorelacion_2").is(':checked')) 
            motivo = motivo + "&CNT_motivorelacion_2=" + $('#CNT_motivorelacion_2').val();
        if ($("#CNT_motivorelacion_3").is(':checked')) 
            motivo = motivo + "&CNT_motivorelacion_3=" + $('#CNT_motivorelacion_3').val();
        if ($("#CNT_motivorelacion_4").is(':checked')) 
            motivo = motivo + "&CNT_motivorelacion_4=" + $('#CNT_motivorelacion_4').val();
        if ($("#CNT_motivorelacion_5").is(':checked')) 
            motivo = motivo + "&CNT_motivorelacion_5=" + $('#CNT_motivorelacion_5').val();
         
        $.ajax({
            type: 'POST',
            url: '/wp-content/themes/gourmet/sendContacto.php',
            data: "CNT_nombreyapellidos=" + $('#CNT_nombreyapellidos').val() + "&CNT_email=" + $('#CNT_email').val() + "&CNT_telefono=" + $('#CNT_telefono').val() + "&CNT_ciudad=" + $('#CNT_ciudad').val() + "&CNT_comentario=" + $('#CNT_comentario').val() + motivo,
            statusCode: {
                404: function(){
                    $('#error').html("No se encontró la página, puede intentar nuevamente. ");
                }
            },
            error: function(){
                $('#error').html("Ha ocurrido un error, intentelo nuevamente");
            },
            success: function(data){
                $('#registrarse').html(data);
                $('#registrarse').toggle('show');
                $('#formContact')[0].reset();
                $(".pantalla").html("");
            }
        });
    }
    
    return false;
}


//============================================================
/***
 * Autor: Cristian González G.
 * Función que valida un rut
 * */
//============================================================
function esrut(variable,digit)
{
	Sum = 0;
	digito = 0;
	factor = 2;
	largo = variable.length;
	while (largo !== 0)
	{
		Sum = Sum + (variable.substring(largo, largo-1) * factor);
		if (factor == 7)
			{
				factor = 2;
			}
		else
		{
			factor = factor + 1;
		}
		largo = largo - 1;
	}
	d = 11 - Sum % 11;
	if (d == "10")
	{
		digito = "K";
        }
	else 
	{
		if (d == "11")
		{
			digito = 0;
		}
		else
		{
			digito = d;
		}
	}	
	if (digito == digit)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function trim(str)
{
//===================
//Elimina los espacios en blanco de los lados de un texto
//===================
  	return str.replace(/^\s*|\s*$/g,"");
}
//=========================================================
/***
Modificado por Cristián González G. 04-05-2011
Descripcion : envia la acción ajax de registro de formulario
*/
//=========================================================
function postRegistrame(updating)
{
	if (updating == undefined) updating = false;
    sw = 1;
    //==========================================
    // validacion de rut
    //==========================================
    var valorRut = $('#REG_RUT').val();
    var digito = $('#REG_DIGITO').val();
    valorRut = valorRut.replace('.','');
    valorRut = valorRut.replace('.','');
   
    $('#REG_RUT').value = valorRut;
    if(trim(valorRut)=='')
    {
    	//alert('');
    	$('#msgRut').html("Debe ingresar su rut");
    	sw=0;
    }
    if(trim(digito)=='')
    {	
    	$('#msgRut').html("Debe ingresar el digito verificador");
    	sw=0;
    }
    
    if(isNaN(valorRut))
    {
    	 $('#msgRut').html("El rut no es correcto");
    	 sw=0;
    }
    else
    {
    	if(isNaN(digito))
    	{
    		if(digito.toUpperCase()!='K')
    		{
    			 $('#msgRut').html("El digito verificador no es correcto");
    			 sw=0;
    		}
    	}
    }
    
    if(!esrut(valorRut,digito))
    {
    	 $('#msgRut').html("El rut no es correcto");
    	 sw=0;
    }
    
    //cambio por otro validador de rut
    /*if (!verificaRut($('#REG_RUT').val(), $('#REG_DIGITO').val())) 
    {
        $('#msgRut').html("El rut no es válido");
        sw = 0;
    }*/
    
    if (!$('#REG_NOMBRE').val()) {
        $('#msgNombre').html("Ingrese su nombre");
        sw = 0;
    }
    
    if (!$('#REG_APELPAT').val()) {
        $('#msgapellidoPaterno').html("Ingrese su Apellido");
        sw = 0;
    }
    
    
    if (!$('#REG_APELMAT').val()) {
        $('#msgapellidoMaterno').html("Ingrese su Apellido");
        sw = 0;
    }
    
    if (!$('#REG_TELEFONO').val()) {
        $('#msgtelefono').html("Ingrese su telefono");
        sw = 0;
    }
    
    if (!$('#REG_CLAVE').val()) {
        $('#msgclave').html("Ingrese su clave");
        sw = 0;
    }
    
    if (!$('#confClave').val()) {
        $('#msgconfClave').html("Confirme su clave");
        sw = 0;
    }
    
    if($('#REG_CLAVE').val()!=$('#confClave').val())
    {
    	$('#msgclave').html("las caves ingresadas no coinciden");
    	sw=0;
    }
    
    if($('#confNewsletter').is(':checked')) {
    	newsletter = 1;
    } else {
    	newsletter = 0;
    }
    
  
    
    var validos = "abcdefghijklmnopqrstuvwxyz0123456789";
   
    var campo = $('#REG_CLAVE').val();
    
	   var letra;
	   var bien = true;
	   for (var i=0; i<campo.length; i++) 
	   {
		   letra=campo.charAt(i).toLowerCase();
		   if (validos.indexOf(letra) == -1)
		   {
			   bien=false;
		   }
	   }
	   if (!bien) 
	   {
		   sw = 0;
		   $('#msgclave').html("Ha ingresado caracteres no permitidos.");
	   }
      
    
    if (sw == 1) {
    	
    	if (updating) {
    		data = "sct=1";
    	} else {
            data = "sct=0";
    	}
    	data += "&REG_RUT=" + valorRut + '&REG_DIGITO=' + $('#REG_DIGITO').val() + '&REG_NOMBRE=' + $('#REG_NOMBRE').val() + '&REG_APELPAT=' + $('#REG_APELPAT').val() + '&REG_APELMAT=' + $('#REG_APELMAT').val() + '&REG_AREA=' + $('#REG_AREA').val() + '&REG_CLAVE=' + $('#REG_CLAVE').val() + '&REG_TELEFONO=' + $('#REG_TELEFONO').val() + '&emailOut=' + $('#emailOut').val() + "&REG_NEWSLETTER="+newsletter;
        $.ajax({
            type: 'POST',
            url: '/resgitra-usuarios-gourmet/',
            data: data,
            statusCode: {
                404: function(){
                    $('#error').html("Error Grave ");
                }
            },
            error: function(){
                $('#error').html("Ha ocurrido un error, intentelo nuevamente");
            },
            success: function(data){
                $('#registrarse').html(data);
                // $('#registrarse').toggle('show');
                $('#registrarse')[0].reset();
                // $(".pantalla").html("");
            }
        });
    
    }
    
    
}

function update_user(data) {
}

function register_user(data) {
    $.ajax({
        type: 'POST',
        url: '/resgitra-usuarios-gourmet/',
        data: "REG_RUT=" + valorRut + '&REG_DIGITO=' + $('#REG_DIGITO').val() + '&REG_NOMBRE=' + $('#REG_NOMBRE').val() + '&REG_APELPAT=' + $('#REG_APELPAT').val() + '&REG_APELMAT=' + $('#REG_APELMAT').val() + '&REG_AREA=' + $('#REG_AREA').val() + '&REG_CLAVE=' + $('#REG_CLAVE').val() + '&REG_TELEFONO=' + $('#REG_TELEFONO').val() + '&emailOut=' + $('#emailOut').val() + "&sct="+$('#sct').val()+"&REG_NEWSLETTER="+newsletter,
        data: data,
        statusCode: {
            404: function(){
                $('#error').html("Error Grave ");
            }
        },
        error: function(){
            $('#error').html("Ha ocurrido un error, intentelo nuevamente");
        },
        success: function(data){
            $('#registrarse').html(data);
            // $('#registrarse').toggle('show');
            $('#registrarse')[0].reset();
            // $(".pantalla").html("");
        }
    });
	
}

function openFormsRegister(type){
	var errorCode = 0;
	var mensajes = ["Debes ingresar tu email",
					"Por favor ingresa un mail válido.",
					"Este mail ya está registrado.\nPara actualizar tu clave selecciona actualizar datos."];
	var userEmail = $('#email').val();
	if (console) console.log("userEmail: " + userEmail);
	if ( userEmail == "Email" ||
		 userEmail == mensajes[0] ||
		 userEmail == mensajes[1] ||
		 userEmail == mensajes[2] ||
		 !vacio(userEmail)
		)
		errorCode = 1;
    else if (!verificaEmail(userEmail)) errorCode = 2;
	else verficarExisteEmail(type, userEmail, mensajes[2]);

	if (errorCode == 0) {
		return true;
	} else {
		alert(mensajes[errorCode - 1]);
		return false;
	}
}
function muestraPantalla() {
	 $(".pantalla").css({
	    'position': 'fixed',
	    'top': '0',
	    'left': '0',
	    'z-index': '5555',
	    'width': '100%',
	    'height': '100%',
	    'background': 'url(/wp-content/themes/gourmet/images/fondo.png)',
	    'cursor': 'pointer'
	});
	showClock(true);
}
/**
 * Muestra pantalla de confirmación para cuando se borra un favorito
 */
function showConfirmation(type, post_id) {
	switch (type) {
		case 'product':
			msg = "¿Estás seguro que quieres eliminar este producto de tus Productos Favoritos?";
			break;
		case 'recipe':
			msg = "¿Estás seguro que quieres eliminar esta receta de tus Recetas Favoritas?";
			break;
	};
 	if ($('#confirmation').length == 0) {
		$('.pantalla').append('<div id="confirmation"></div>');
	}
 	html = "<div id='mensaje'>";
 	html += msg;
 	html += "</div>\n";
 	html += "<div id='botones'>\n";
 	html += ' <input type="button" value="si" onclick="delete_fav(\''+post_id+'\', \''+type+'\', true);"/><input type="button" value="no" onclick="closeWin();"/>\n';
 	html += "</div>";
 	$('#confirmation').html(html);
 	$('#confirmation').toggle(true);
}
/**
 * esconde o muestra el relojito de carga
 * @param flag boolean.
 */
function showClock(flag) {
	if (flag == undefined) flag = true;
	if (flag) {
		$(".pantalla").html("<div style='height:200px;top:190px;'><img src='/wp-content/themes/gourmet/images/ajax-loader.gif' width='30px' height='30px'></div>");
	} else {
		$(".pantalla").html("");

	}
}

function showResult(htmlResponse, target) {
	//alert("registrarse " + target + "\n" + htmlResponse);
	$(target).html(htmlResponse);
	$(target).toggle(false);
	$(target).toggle('slow');
	showClock(false);
}

function muestraLogin(redirect) {
	muestraPantalla();
	$.ajax({
		type: 'POST',
		url: '/formulario-de-login/?redirect='+redirect,
		success: function (txtdata) {
			showResult(txtdata, "#registrarse");
		}
	});
}

function muestraFormularioRegistro(type, userEmail, userPass) {
	
	if (userPass != undefined) {
		data = {
				user: userEmail,
				pass: userPass,
				action: "update"
				
		};
	} else {
		data = {
				user: userEmail,
				action: "register",
				type: type
		};
	}
	muestraPantalla();
    $.ajax({
        type: 'POST',
        url: '/formulario-de-registro/',
        data: data,
        success: function(txtdata){
        
            showResult(txtdata, '#registrarse');
            cargaEmailDiv();
        }
    });

}

function openFormsActualiza(){
    $(".pantalla").css({
        'position': 'fixed',
        'top': '0',
        'left': '0',
        'z-index': '5555',
        'width': '100%',
        'height': '100%',
        'background': 'url(/wp-content/themes/gourmet/images/fondo.png)',
        'cursor': 'pointer'
    });
    $(".pantalla").html("<div style='height:400px;top:290px;'><img src='/wp-content/themes/gourmet/images/ajax-loader.gif' width='30px' height='30px'></div>");
    $.ajax({
        type: 'POST',
        url: "/actualiza-registro/",
        success: function(txtdata){
        	showResult(txtdata, '#registrarse');
            
            cargaEmailDiv();
        }
    });
}


function efectToggleRegistro(){
    $('#registrarse').toggle('show');
    $(".pantalla").html("");
    //carga validadores
}

function efectToggle(){
    $('#registrarse').toggle('show');
    $(".pantalla").html("");
}

function cargaEmailDiv(){
	var email = $('#email').val();
	if (email == 'Email') email = '';
    $('#emailView').html(email);
    if ($('#emailOut').val() == '') $('#emailOut').val(email);
}


function closeWin(typeReboot){
    $("#registrarse").toggle(500);
    $(".pantalla").html("");
    $(".pantalla").css({
        'z-index': '1',
        'width': '0%',
        'height': '0%'
    });
    if (typeReboot) 
        self.location = "/";
}

function close_win_reload() {
	closeWin(false);
	location.reload(true);
}


// validacion de rut e email y campos vacios

function vacio(q){
    for (i = 0; i < q.length; i++) {
        if (q.charAt(i) != " ") 
            return true;
    }
    return false;
}

function verificaRut(rut, digito){

    var miRut = new String(rut);
    
    //Eliminiamos los puntos
    
    miRut = miRut.replace(/\./g, "");
    
    //alert(miRut);
    
    var miDigito = new String(digito);
    
    //Convertimos el verificador en mayusculas
    
    miDigito = miDigito.toUpperCase();
    
    //alert(miRut.substring(1,2));
    
    largo = miRut.length;
    
    //alert(largo);
    
    multi = 2;
    
    suma = 0;
    
    for (i = 0; i < largo; i++) {
    
        posCaracter = largo - i;
        
        if (multi > 7) {
        
            multi = 2;
            
        }
        
        caracter = new Number(miRut.substring(posCaracter, posCaracter - 1));
        
        producto = caracter * multi;
        
        suma = suma + producto;
        
        //alert(caracter+"*"+multi+"="+producto);
        
        multi++;
        
    }
    
    resultado = suma / 11;
    
    diferencia = Math.round((resultado - Math.floor(resultado)) * 11);
    
    verificador = Math.abs(diferencia - 11);
    
    if (verificador == 10) {
    
        verificador = "K";
        
    }
    
    if (verificador > 10) {
    
        verificador = 0;
        
    }
    
    //alert(verificador+"=="+miDigito);
    
    return (verificador == miDigito);
    
}

function verificaEmail(theMail){

    return (theMail.indexOf("@") > -1 && theMail.indexOf(".") > -1);
    
}

function unionIngrediente(){
    document.ingrediente.s.value = document.ingrediente.a.value + " " + document.ingrediente.b.value + " " + document.ingrediente.c.value;
}

function statusBusqueda(a, b, c){
    document.ingrediente.a.value = a;
    document.ingrediente.b.value = b;
    document.ingrediente.c.value = c;
}



function isNumeric(num){
    if (isNaN(num)) {
        return (false);
    }
}

function limpInput(inputname){
    $('#' + inputname).html("");
}

function maximo(obj, e){
    ma = 500; //nº máximo de caracteres 
    tecla = (document.all) ? e.keyCode : e.which;
    if (obj.value.length == ma && tecla != 8) 
        return false;
}




// VALIDACION FORMULARIO DE CONTACTO
function gourmet_init_page(template_directory){
	return;
	
	if (template_directory == null) template_directory = wp_template_directory;
    MM_preloadImages(template_directory + '/images/home-hover.gif', template_directory + '/images/mail-hover.gif');
	/*console.log("template directory: " + template_directory);
   //preload images for menu
	MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:template_directory+"/SpryAssets/SpryMenuBarDownHover.gif", imgRight:template_directory+"/SpryAssets/SpryMenuBarRightHover.gif"});
	*/
}

function salto(mail,clave)
{
	pasaventana = mail;
	pasaclave = clave;
	 $(".pantalla").css({
         'position': 'absolute',
         'top': '0',
         'left': '0',
         'z-index': '5555',
         'width': '100%',
         'height': '120%',
         'background': 'url(/wp-content/themes/gourmet/images/fondo.png)',
         'cursor': 'pointer'
     });
     $(".pantalla").html("<div style='height:200px;top:190px;'></div>");
     $.ajax({
         type: 'POST',
         url: "/formulario-de-registro/",
         data: "EMAIL="+ mail,
         success: function(txtdata){
         	
             $('#registrarse').html(txtdata);
             //cargaEmailDiv();
             //setTimeout("efectToggleRegistro()", 80);
             
             
         }
     });
}
/**
 * @autor Alvaro Quezada
 * @param mail a verificar contra la base de datos de contactos.
 */
function verficarExisteEmail(type, email, mensajeError)
{
	
	if (console) console.log("email: " + email);
	if ($.ajax == null) {
		alert("la funcion ajax no está disponible;");
		return false;
	}
	
	
	var result = $.ajax({
		type: "POST",
		url: "/wp-admin/admin-ajax.php",
		data: {
			email:email,
			action:'existe_email'
		},
		success: function(resultado){
			if (resultado == '1') {
				alert(mensajeError);
			} else {
				muestraFormularioRegistro(type, email);
			}
   		},
   		dataType: "text"	
   	});
			
}

function verificaClave()
{
	var mail = $('#correo').val();
	var clave = $('#clave4').val();
	if ($.ajax == null) {
		alert("la funcion ajax no está disponible;");
		return false;
	}
	//alert("mail: "+mail+"\n"+"clave: "+clave);
	//alert("ajax url: "+ ajax_object.ajaxurl);
	var result = $.ajax({
		type: "POST",
		url: "/wp-admin/admin-ajax.php",
		data: {
			ing:mail,
			clav:clave,
			action:'verificar_clave'
		},
		success: function(resultado){
			if (resultado == '0') {
				$('#mensaje').html("La clave ingresada no es correcta");;
			} else {
				//validaUsuario();
				
				actualizarDatos(mail, clave);
			}
   		},
   		dataType: "text"
 	});
}

/**
 * 
 * @param mail string el mail del usuario
 * @param clave string la clave de ingreso
 */
function actualizarDatos(mail, clave) {
	muestraFormularioRegistro("update", mail, clave);
}

function recuperarClave()
{
	var mail = $('#correo').val();
	if ($.ajax == null) {
		alert("la funcion ajax no está disponible;");
		return false;
	}
	var result = $.ajax({
		type: "GET",
		url: "/wp-admin/admin-ajax.php",
		data: {
			correobuscado: mail,
			action: "recuperar_clave"
		},
		success: function(resultado){
		
			if (resultado == '1') {
				recuperar_finalizar(0);
			} else if (resultado == '-2') {
				recuperar_finalizar(1);
			} else {
				recuperar_finalizar(2);
			}
   		},
   		dataType: "text"
 	});
}

function print_preview() {
	var new_url = window.location.pathname + "?print_preview=true";
	var h = Math.round(screen.height * 0.6);
	var print_win = window.open(new_url, "print_preview", "height="+h+", width=600, scrollbars=yes, toolbar=no, location=no, directories=no, status=no, menubar=no, copyhistory=no");
	
}


// mi goourmet - favoritos
function delete_fav_recipe(id) {delete_fav(post_id, 'recipe');}
function delete_fav_product(id) {delete_fav(post_id, 'product');}

function delete_fav(post_id, type, confirmed) {
	if (confirmed == undefined) confirmed = false;
	
	if (!confirmed) {
		
		muestraPantalla();
		showConfirmation(type, post_id);
	} else {
		$.ajax({
			type: 'POST',
			url:'/favoritos/',
			data: 'post_id='+post_id+'&type='+type+'&action=delete',
			dataType: 'html',
	        statusCode: {
	            404: function(){
	                $('#error').html("Error Grave ");
	            }
	        },
	        error: function(){
	            $('#error').html("Ha ocurrido un error, intentelo nuevamente");
	        },
	        success: function(txtdata){
	        	// reload
	        	location.reload();
	        }
			
		});
	}
}

function add_fav_recipe(post_id) {add_fav(post_id, 'recipe');}
function add_fav_product(post_id) {add_fav(post_id, 'product');}

function add_fav(post_id, type) {
	muestraPantalla();
	date = get_current_date();
	$.ajax({
		type: 'POST',
		url:'/favoritos/',
		data: 'post_id='+post_id+'&type='+type+'&action=add&date='+date,
		dataType: 'html',
        statusCode: {
            404: function(){
                $('#error').html("Error Grave ");
            }
        },
        error: function(){
            $('#error').html("Ha ocurrido un error, intentelo nuevamente");
        },
        success: function(txtdata){
           showResult(txtdata, '#registrarse');
          
        }
	});
}

function hide_add_fav_button() {
	$('#add-fav-button').hide('fast');
}
/**
 * Devuelve la fecha actual en el formato dd/mm/yyyy
 */
function get_current_date(){
	var now = new Date();
	var d = now.getDate();
	if (d<10) d = '0'+d;
	var m = now.getMonth() +1;
	if (m<10) m = '0'+m;
	var y = now.getFullYear();
	return d+"/"+m+"/"+y;
}


/**
 * Verifica la existencia del email en la base de datos
 **/
function checkMailExists(email, msgOut) {
	$(msgOut).html('Verificando...	');
	
	if (!verificaEmail(email)) {
		$(msgOut).html('El mail está mal escrito');
		return {code:-1, msg:'mail mal formado'};
	};
	
	if ($.ajax == null) {
		alert("la funcion ajax no está disponible;");
		return {code:-2, msg:"Ajax no disponible"};
	}
	
	var jqxhr = $.ajax({
		type: "POST",
		url: "/wp-content/themes/gourmet/validaEmail.php",
		data: "email="+email,
		dataType: "script"
 	});
	
	jqxhr.done(function (data) {
		$(msgOut).html('');
		// existeEmail se setea en el script
		if (existeEmail) {
			$(msgOut).html('El email ya está registrado');
		}
	});
	

	jqxhr.fails ( function(obj, textStatus) {
		alert('error: '+ textStatus);
	});
	
}

function change()
{
	var texto = '';
	texto = texto + '<h1 class="ventana">Recuperar Clave</h1>';
	texto = texto + '<div class="borde-top" style="margin-bottom:14px;"></div>';
	texto = texto + '<div id="campos" class="fila">';
	texto = texto + '	<span id="sprytextfield8">';
	texto = texto + '<label class="lb1">Email</label>';
	texto = texto + '	<div class="bx2">';
	texto = texto + '	<input name="correo" type="text" class="an2" id="correo" />';
	texto = texto + '	</div>';
	texto = texto + '	<span class="textfieldRequiredMsg"></span> ';
	texto = texto + '	<span class="textfieldInvalidFormatMsg"></span>';
	texto = texto + '	</span>';
	texto = texto + '	</div>';
	texto = texto + '<div id="enviar-button">';
	texto = texto + '	<input name="enviar" type="button" class="btn-rojo-short" id="enviar" value="Enviar" onClick="javascript:recuperarClave();"/>';
	texto = texto + '	<p>';
	texto = texto + '<div id="mensaje"><span class="msgRut"></span></div>';
	texto = texto + '</p>';
	texto = texto + '<div >';
	texto = texto + '</div>';
	texto = texto + '</div>';
	texto = texto + '		<div class="close"><a href="javascript:closeWin();"><img src="/wp-content/themes/gourmet/images/close.png" width="27" height="26"></a></div>';
	texto = texto + '</div>';
	document.getElementById('contenedor').innerHTML = texto;
}

function recuperar_finalizar(val)
{
	
	var correoRec = document.getElementById('correo').value;
	var sw = true;
	if(trim(correoRec)=='')
	{
		document.getElementById('mensaje').innerHTML = '<span class="msgRut">Debes ingresar tu correo.</span>';
		sw = false;
	}
	else
	{
		if(!verificaEmail(correoRec))
		{
			document.getElementById('mensaje').innerHTML = '<span class="msgRut">El mail ingresado no es correcto.</span>';
			sw = false;
		}
	}
	if(sw==true)
	{
		var mensajes = ['Hemos enviado tu clave por correo.<br><br>',
		                'Este correo no está registrado<br><br>',
		                'Ha sucedido un error al tratar de recuperar tu clave.<br><br>'
		                ];

		var texto = '';
		texto = texto + '<h1 class="ventana">Recuperar Clave</h1>';
		texto = texto + '<div class="borde-top" style="margin-bottom:14px;"></div>';
		texto = texto + '<div>';
		//texto = texto + '	<span id="sprytextfield8">';
		texto = texto + '<label class="lb1"></label>';
		texto = texto + '	<div class="padd">';
		
		texto += mensajes[val];
		
		texto = texto + '	</div>';
		/*texto = texto + '	<span class="textfieldRequiredMsg"></span> ';
		texto = texto + '	<span class="textfieldInvalidFormatMsg"></span>';
		texto = texto + '	</span>';*/
		texto = texto + '	</div>';
		texto = texto + '<div style="margin:0px 0px 12px 105px">';
		texto = texto + '	<input name="enviar" type="button" class="btn-rojo-short" id="enviar" value="Cerrar" onClick="javascript:closeWin();"/>';
		texto = texto + '	<p>';
		texto = texto + '<div id="mensaje"><span class="msgRut"></span></div>';
		texto = texto + '</p>';
		texto = texto + '<div >';
		texto = texto + '</div>';
		texto = texto + '</div>';
		texto = texto + '		<div class="close"><a href="javascript:closeWin();"><img src="/wp-content/themes/gourmet/images/close.png" width="27" height="26"></a></div>';
		texto = texto + '</div>';
		document.getElementById('contenedor').innerHTML = texto;
		ocument.form4.correobuscado.value = correoRec;
		//document.form4.submit();

	}
	
}

function ajax_login() {
	log = $("#loginform #log").val();
	pwd = $("#loginform #pwd").val();
	
	// temporary disable the button
	$("#loginform #submit").attr("disabled", "true");
	
	showClock(true);
	$.ajax({
		type: 'POST',
		url:  '/wp-admin/admin-ajax.php',
		data: {
			action: 'login',
			log: log,
			pwd: pwd
		},
		dataType: 'json',
		beforeSend: function(x) {
			if (x && x.overrideMimeType) {
				x.overrideMimeType("application/json;charset=UTF-8")
			};
		},
		success : function(data) {
			ajax_login_callback(data);
		},
		complete: function (jqXHR, textStatus) {
			showClock(false);
			$("#loginform #submit").removeAttr('disabled');
		},
		error:function (jqXHR, textStatus, errorThrown){
		    alert("ERROR: " + JSON.stringify(jqXHR) + "\nstatus: " + textStatus +"\nTrown:  "+errorThrown );
		}
	});
}

function ajax_login_callback(data) {
	if (data.code == 'error') alert(data.message);
	else login_bienvenida(data.username);
}

function login_bienvenida(username) {
	contenido = "<div id='mensaje'>\n";
	contenido += "<p>Bienvenido/a " + username+", ahora puedes guardar tus recetas y productos favoritos en Mi Gourmet.</p>\n";
	contenido += "</div>\n";
	contenido += "<div id='botones'>\n";
	contenido += "<a href='/mi-gourmet/' class='button'>Mi Gourmet</a>\n";
	contenido += "<a href='javascript:close_win_reload();' class='button'>Continuar</a>\n";
	$("#login #contenedor").html(contenido);
}

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}


$(document).ready(
	function () {
		var $_GET = getQueryParams(document.location.search);
		
		if ($_GET['subscribe']) muestraFormularioRegistro('mi-gourmet'); 
	}
);

