
function delete_fridge(layer){
	
	document.getElementById(layer).value="";
	document.getElementById("from_fridge").submit();
	
}

function alerta_suscripcion(){
	
		document.getElementById("alerta_suscripcion").style.display="none";
		
	}
	
// images social 

function images_recepes(){

	if( (document.getElementById("title").value=="")||(document.getElementById("photo").value=="") ){	
	
		document.getElementById("alerta_suscripcion").innerHTML="<span class='ko'>Falta o el t&iacute;tilo o la foto</span>";
	
	}else{
		
		document.getElementById("form_images_recipes").submit();
			
	}
}

function video_recepes(){
	
	
	if( (document.getElementById("title").value=="")||(document.getElementById("url").value=="")){	
	
		document.getElementById("alerta_suscripcion").innerHTML="<span class='ko'>Falta o el t&iacute;tilo o la URL</span>";
	
	}else{
		
		var cadena = document.getElementById('url').value;
		
		if(cadena.indexOf('www.youtube.com/watch?v=')!=-1){
			
			document.getElementById("form_images_recipes").submit();
			
		}else{
			
			document.getElementById("alerta_suscripcion").innerHTML="<span class='ko'>No es una URL v&aacute;lida</span>";
			
		}
	}
}

function send_coment_images(id_multimedia, type){
	
		if(document.getElementById('comentario').value!=""){
		
			var url = "/social/insert.php?case=cometario_multimedia&id_multimedia="+id_multimedia+"&comentario="+document.getElementById('comentario').value+"&type="+type;
		
			send_ajax(url, 'contenedor_comentario');
			
			document.getElementById('comentario').value="";
		
		}else{
		
			alert("Puedes poner un comentario, gracias");	
		
		}
	
}

function send_coment_images_publico(id_multimedia, type){
	
		if(document.getElementById('comentario').value!=""){
		
			var url = "/social/insert.php?case=cometario_multimedia_publico&id_multimedia="+id_multimedia+"&comentario="+document.getElementById('comentario').value+"&type="+type;
		
			send_ajax(url, 'contenedor_comentario');
			
			document.getElementById('comentario').value="";
		
		}else{
		
			alert("Puedes poner un comentario, gracias");	
		
		}
	
}

// faebook

function fbs_click(synlink, title) {
		
		u="http://www.vinosyrecetas.com/"+synlink; 
		t=title;
		window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
		
}

// noticias


function mostrar_news(mostrar, ocultar){
	

	document.getElementById(mostrar).style.display='block';
	document.getElementById(ocultar).style.display='none';	
	
}

function result_friedge(ini,limit, query_s, capa){
	
	document.getElementById("a_result_friedge_"+ini).style.display='none';
	
	var url = "/insert_ddbb.php?origen=friedge&ini="+ini+"&limit="+limit+"&query_s="+query_s;
		
	send_ajax(url,capa);	
}

//meridaje 

function refresc_meridaje(id_receta){
	
	var url = "/insert_ddbb.php?origen=refresc_meridaje&id_receta="+id_receta;
		
	send_ajax(url, 'box_wine');	
	
}

function meridaje(id_receta, id_vino){
	
	var url = "/insert_ddbb.php?origen=meridaje&id_receta="+id_receta+"&id_vino="+id_vino;
		
	send_ajax(url, 'box_wine');
	
	url = "/insert_ddbb.php?origen=muestra_meridaje&id_receta="+id_receta;
		
	send_ajax(url, 'box_maridaje');
	
}

function meridaje_public(id_receta, id_vino){
	
	var url = "/insert_ddbb.php?origen=meridaje&id_receta="+id_receta+"&id_vino="+id_vino;
	
	send_ajax(url, 'regen_list');
	
	hidde_layer('relative');
	
	document.getElementById('wine_m').value="";
	
}


function get_refresh_maridaje_recipe(id_wine){
	
	var url ="insert_ddbb.php?origen=refersh_wine&id_wine="+id_wine;	
	
	send_ajax(url, "box_wine_maridage");
	
}

function gen_result_wine_maridage(capa){
	
	document.getElementById('relative').style.display="block";
	
	var url ="insert_ddbb.php?origen=result_wine_maridage&wine_m="+document.getElementById('wine_m').value+"&id_recipe="+document.getElementById('id_recipe').value;
	
	send_ajax(url, capa);
	
}

function gen_result_search(capa){
	
	var string = document.getElementById('search').value;
	
	if(string.length>3){
		
		//document.getElementById('search_result').style.display="block";
	
		var url ="insert_ddbb.php?origen=result_recipe&search="+document.getElementById('search').value+"&type_search="+document.getElementById('type_search').value;
	
		send_ajax(url, capa);
	
	}else{
		
		
		//document.getElementById('search_result').style.display="none";
		
	}
	
}

function hidde_layer(capa){
	
	document.getElementById(capa).style.display="none";
	
}

function send_search(capa){
	
	document.getElementById(capa).submit();
}

function swat_type_search(type){
	
	document.getElementById('search_recipe').className="";
	document.getElementById('search_wine').className="";
	document.getElementById('search_restaurant').className="";
	//document.getElementById('search_cellear').className="";
	//document.getElementById('search_news').className="";
	
	document.getElementById('search').value = "busca tus "+document.getElementById(type).innerHTML;
	
	document.getElementById(type).className="select";
	
	document.getElementById('type_search').value=type;
	
}

// recuperar pass

function recover_pass(capa){

	var url ="insert_ddbb.php?origen=recuperar_pass&email="+document.getElementById('recover_email').value;	
	
	send_ajax(url, capa);	
}

// votar


function votar(capa, id_receta){
	
	var url = "/insert_ddbb.php?origen=votar&id_receta="+id_receta;
		
	send_ajax(url, capa);	
	
}

function votar_public(capa, type, id_receta){
	
	var url = "/insert_ddbb.php?origen=votar&id_receta="+id_receta+"&type="+type;
	
	document.getElementById('vote').style.backgroundPosition="-67px -0px";
	
	document.getElementById('vote').onclick = stopEvent;
	
	send_ajax(url, capa);	
	
}

function votar_public_image(capa, id_multimedia){
	
	var url = "/insert_ddbb.php?origen=votar_image&id_multimedia="+id_multimedia;
	
	document.getElementById('vote').style.backgroundPosition="-66px -0px";
	
	document.getElementById('vote').onclick = stopEvent;
	
	send_ajax(url, capa);	
	
}

function stopEvent(e) {
    if (!e) e = window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
}

function votar_imagen(capa, id_multimedia){
	
	var url = "/social/insert.php?case=votar_imagen&id_multimedia="+id_multimedia;
		
	send_ajax(url, capa);	
	
	
}

// restaurantes

function cargar_valor(valor){
	
	
	document.getElementById("valor").value = valor;
	
	
}


function send_coment(id_restaurante, synlink, iden_user){
	
	if(document.getElementById('valor').value!=""){
	
		if(document.getElementById('comentario_restaurante').value!=""){
		
			var url = "/insert_ddbb.php?origen=cometario_restaurante&id_restaurante="+id_restaurante+"&iden_user="+iden_user+"&comentario="+document.getElementById('comentario_restaurante').value+"&synlink="+synlink+"&valor="+document.getElementById('valor').value;
		
			send_ajax(url, 'result_comentario');
			
			document.getElementById('comentario_restaurante').value="";
		
		}else{
		
		alert("Puedes poner un comentario, gracias");	
		
	}
		
	}else{
		
		alert("Puedes dar una valoración, gracias");	
		
	}
	
}

function rollover_votacion(valor){

	switch(valor){
		
			
		case 0:
				
				switch(document.getElementById("valor").value){
					
					case "1":
					
						
						document.voto_2.src='/images/icono_voto_receta_cocina.png';
						document.voto_3.src='/images/icono_voto_receta_cocina.png';
						document.voto_4.src='/images/icono_voto_receta_cocina.png';
						document.voto_5.src='/images/icono_voto_receta_cocina.png';
						
					
					break;
					
					case "2":
					
						document.voto_3.src='/images/icono_voto_receta_cocina.png';
						document.voto_4.src='/images/icono_voto_receta_cocina.png';
						document.voto_5.src='/images/icono_voto_receta_cocina.png';
					
					break;
					
					case "3":
					
						document.voto_4.src='/images/icono_voto_receta_cocina.png';
						document.voto_5.src='/images/icono_voto_receta_cocina.png';
					
					break;
					
					case "4":
					
						document.voto_5.src='/images/icono_voto_receta_cocina.png';
						
					
					break;
					
					case "5":
					
					
					break;
					
					default:
					
						document.voto_1.src='/images/icono_voto_receta_cocina.png';
						document.voto_2.src='/images/icono_voto_receta_cocina.png';
						document.voto_3.src='/images/icono_voto_receta_cocina.png';
						document.voto_4.src='/images/icono_voto_receta_cocina.png';
						document.voto_5.src='/images/icono_voto_receta_cocina.png';
					
					break;
				}
					
		break;
		
		
		case 1:
		
			document.voto_1.src='/images/icono_voto_receta_cocina_r.png';
		
		break;
		
		case 2:
		
			document.voto_1.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_2.src='/images/icono_voto_receta_cocina_r.png';
		
		break;
		
		case 3:
		
			document.voto_1.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_2.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_3.src='/images/icono_voto_receta_cocina_r.png';
		
		break;
		
		case 4:
		
			document.voto_1.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_2.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_3.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_4.src='/images/icono_voto_receta_cocina_r.png';
		
		break;
		
		case 5:
		
			document.voto_1.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_2.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_3.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_4.src='/images/icono_voto_receta_cocina_r.png';
			document.voto_5.src='/images/icono_voto_receta_cocina_r.png';
		
		break;
		
		
	}
	
}


function cargar_localidad_social(capa){

	if(document.getElementById('provincia').value!=""){
		
		var url = "../insert_ddbb.php?origen=localidad_social&provincia="+document.getElementById('provincia').value;
		
		send_ajax(url, capa);
	}
	
}

function cargar_localidad(capa){

	if(document.getElementById('provincia').value!=""){
		
		var url = "insert_ddbb.php?origen=localidad&provincia="+document.getElementById('provincia').value;
		
		send_ajax(url, capa);
	}
	
}


function borrar_textarea_comentario(texto){
	
	if(texto=="escribe tu comentario"){
		
		document.getElementById('comentario').value='';
		
	}
	
}

function borrar_textarea_comentario_restaurante(texto){
	
	if(texto=="escribe tu comentario"){
		
		document.getElementById('comentario_restaurante').value='';
		
	}
	
}


function cut_value(capa){
					
	var value = document.getElementById(capa).value;
				
	arra_value = value.split("                        ");
				
	document.getElementById(capa).value = arra_value[0];
}
				
				

function  refresc(){

	var url = "/social/insert.php?case=refresc";
	
	send_ajax(url, 'divFoto');
	
}

// comment 


function view_comment_motion(capa){
	
	document.getElementById(capa).style.display='block';
	
	
}

function view_motion_user(capa){
	
	document.getElementById("a_motion_"+capa).style.display='none';	
	
	document.getElementById(capa).style.display='block';
	
	
}



function view_more_motions(capa, ini, count, id_user_profile){
	
		document.getElementById("a_"+ini).style.display='none';
		
		var url = "insert.php?case=view_more_motions&ini="+ini+"&count="+count+"&id_user_profile="+id_user_profile;
		
		send_ajax(url, capa);
	
}

function view_more_motions_profile(capa, ini, count, id_user_profile){
	
		document.getElementById("a_"+ini).style.display='none';
		
		var url = "insert.php?case=view_more_motions_profile&ini="+ini+"&count="+count+"&id_user_profile="+id_user_profile;
		
		send_ajax(url, capa);
	
}

function insert_comment(id_comment, capa, text){
	

	if(document.getElementById(text).value!=""){
		
		
		var url = "insert.php?case=commnet_motion&id_comment="+id_comment+"&text="+document.getElementById(text).value;
		
		send_ajax(url, capa);
		
		document.getElementById(text).value="";
	}
	
	
}


// mensajes 

function enviar_mensaje(){

	var flag = 1;
	
	var text_error = "";
	
	if(document.getElementById("text").value=="Escribir mensaje")document.getElementById("text").value="";
	
	if(document.getElementById("id").value == ''){
		
		flag = 0;
		
		text_error = "<br /><div class='ko'>&iquest;A qui&eacute;n se lo ev&iacute;as?</div>";
		
	}
	
	if(document.getElementById("subject").value == ''){
		
		flag = 0;
		
		text_error = text_error + "<br /><div class='ko'>Pon alg&uacute;n asunto al mensaje, gracias</div>";
		
	}
	
	if(document.getElementById("text").value == ''){
		
		flag = 0;
		
		text_error = text_error +  "<br /><div class='ko'>Algo de texto en el mensaje, gracias</div>";
		
		
	}
	
	if(flag == 0){
		
		document.getElementById("result").innerHTML  = text_error;
	
	}else{
		
			var url = "insert.php?case=send_message&id_send="+document.getElementById('id').value+"&subject="+document.getElementById("subject").value+"&text="+document.getElementById("text").value;
		
			document.getElementById('users_input').value = "";
			
			document.getElementById('subject').value = "";
			
			document.getElementById('text').value = "";
	
			send_ajax(url, 'result');
			
		
	}
	
}

function send_recipe(layer){
		
	var url = "../insert_ddbb.php?origen=send_recipe&id_recipe="+document.getElementById('id_recipe').value+"&sunombre="+document.getElementById("sunombre").value+"&sumail="+document.getElementById("sumail").value+"&tunombre="+document.getElementById("tunombre").value+"&messaje="+document.getElementById("messaje").value+"&type="+document.getElementById("type").value;
	
	document.getElementById('messaje').value = "";
			
	document.getElementById('sunombre').value = "";
			
	document.getElementById('sumail').value = "";
	
	send_ajax(url, layer);
	
}


function enviar_mensaje_receta_vino(){

	var flag = 1;
	
	var text_error = "";
	
	if(document.getElementById("text").value=="Escribir mensaje")document.getElementById("text").value="";
	
	if(document.getElementById("id").value == ''){
		
		flag = 0;
		
		text_error = "<br /><div class='ko'>&iquest;A qui&eacute;n se lo ev&iacute;as?</div>";
		
	}
	
	if(document.getElementById("subject").value == ''){
		
		flag = 0;
		
		text_error = text_error + "<br /><div class='ko'>Pon alg&uacute;n asunto al mensaje, gracias</div>";
		
	}
	
	if(document.getElementById("text").value == ''){
		
		flag = 0;
		
		text_error = text_error +  "<br /><div class='ko'>Algo de texto en el mensaje, gracias</div>";
		
		
	}
	
	if(flag == 0){
		
		document.getElementById("result").innerHTML  = text_error;
	
	}else{
		
			var url = "insert.php?case=send_message&id_send="+document.getElementById('id').value+"&subject="+document.getElementById("subject").value+"&text="+document.getElementById("text").value+"&type="+document.getElementById("type").value+"&id_receta="+document.getElementById("id_recipe").value;
		
			document.getElementById('users_input').value = "";
			
			document.getElementById('subject').value = "";
			
			document.getElementById('text').value = "";
	
			send_ajax(url, 'result');
			
		
	}
	
}


function enviar_sugerencia_amigos(id_friend){
	
	if(document.getElementById('ids_friend').value!=""){
		
		var url = "insert.php?case=send_suggest_friend&ids_friend="+document.getElementById("ids_friend").value+"&id_friend="+id_friend;
		
		send_ajax(url, 'result');
		
	}else{
	
		
		document.getElementById("result").innerHTML = "<br /><div class='ko'>Selecciona alg&uacute;n amigo</div>";	
		
	}
	
}

function enviar_respuesta(){

	if(document.getElementById("text").value==""){
		
		document.getElementById("result").innerHTML  = "<br /><div class='ko'>Algo de texto en el mensaje, gracias</div>";
		
	}else{
	
		var url = "insert.php?case=send_reply&id_subject="+document.getElementById("id_subject").value+"&text="+document.getElementById("text").value;
		
		document.getElementById('text').value = "";
		
		send_ajax(url, 'box_messages');
		
	}
	
	
}


// amigos

function on_setInterval(capa){
	
		document.getElementById(capa).innerHTML="";
		
}
	
function enviar_solicitud(tipo){

		if(tipo == 'name'){
					
				if(document.getElementById('id').value!=""){
					
					var url = "insert.php?case=send_request&id_user="+document.getElementById('id').value+"&message="+document.getElementById("message").value;
				
					document.getElementById('users_input').value = "";
					
					document.getElementById("message").value = "";
					
					send_ajax(url, 'result');
					
					setInterval("on_setInterval('result')",3000);
					
				}else{
					
					document.getElementById('error_name').innerHTML="<div class='ko'>Introduce el nombre de quien quieres se amigo!";
					
					setInterval("on_setInterval('error_name')",3000);
					
				}
		}else{
		
			if(document.getElementById('email_friend').value!=""){
					
					var url = "insert.php?case=send_request_email&email_friend="+document.getElementById('email_friend').value+"&message_email="+document.getElementById("message_email").value;
					
					document.getElementById('email_friend').value = "";
					
					document.getElementById("message_email").value = "";
					
					send_ajax(url, 'result');
					
					setInterval("on_setInterval('result')",3000);
					
			}else{
			
				document.getElementById('error_email').innerHTML="<div class='ko'>Introduce el email de quien quieres se amigo!";	
				
				setInterval("on_setInterval('error_email')",3000);
			}
		
	}	
		
}


function verificar_formularios(){
	
	
		if( (verificar_datos('user','verificar_user')) && (verificar_datos('login','verificar_login')) && (verificar_datos('mail','verificar_mail')) && (verificar_datos('name','verificar_name')) && (verificar_datos('surname','verificar_surname')) && (verificar_datos('city','verificar_city')) && (verificar_datos('province','verificar_province')) ){
			
			document.getElementById("from_user").submit();
	}
	
}

function nuevo_ajax(){
	
	
	//Crear una variable de Bool para comprobar si se esta usando Internet Explorer.
	var xmlhttp = false;
	
	//Comprobar si se esta usando IE.
	try {
		//Si la version de javascript es superior a la 5.
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		
	} catch (e) {
		//Si no, utilizar el tradicional objeto ActiveX.
		try {
			//Si se esta usando Internet Explorer.
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		
		} catch (E) {
			//En caso contrario no se debe estar usando Internet Explorer.
			xmlhttp = false;
		}
	}
	
	//Si no se esta usando IE, crear una instancia ActiveX del objeto.
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		
		xmlhttp = new XMLHttpRequest();
		
	}
	
	return xmlhttp;
	
}


function borrar_campo(capa){
	
	
	document.getElementById(capa).value="";
	
}

function send_you_are_doing(capa, id){
	
	var url = "insert.php?case=you_are_doing&text="+document.getElementById("text_you_are_doing").value+"&id="+id;
	
	send_ajax(url, capa);
	
}

function view_comment(capa, id_recipe, type){
	
	if(document.getElementById(capa).innerHTML==""){
		
		document.getElementById("btn_comment_"+id_recipe).innerHTML= "<a href='#' class='icono_comment' onclick='view_comment_hidde(\""+capa+"\", \""+id_recipe+"\", \""+type+"\"); return false;'>ocultar comentarios</a>";
	
	}else{
		
		document.getElementById("btn_comment_"+id_recipe).innerHTML= "<a href='#' class='icono_comment' onclick='view_comment(\""+capa+"\", \""+id_recipe+"\", \""+type+"\"); return false;'>ver comentarios</a>";
	}
	
	var url = "insert.php?case=view_comment&id_recipe="+id_recipe+"&type="+type;
	
	send_ajax(url, capa);
	
}


function view_comment_hidde(capa, id_recipe, type){
	
	if(document.getElementById(capa).innerHTML==""){
		
		document.getElementById("btn_comment_"+id_recipe).innerHTML= "<a href='#' class='icono_comment' onclick='view_comment_hidde(\""+capa+"\", \""+id_recipe+"\", \""+type+"\"); return false;'>ocultar comentarios</a>";
	
	}else{
		
		document.getElementById("btn_comment_"+id_recipe).innerHTML= "<a href='#' class='icono_comment' onclick='view_comment(\""+capa+"\", \""+id_recipe+"\", \""+type+"\"); return false;'>ver comentarios</a>";
	}
	
	document.getElementById(capa).innerHTML="";
	
}

function view_maridaje(capa, id_recipe, id_user_profile, type){
	
	if(document.getElementById(capa).innerHTML==""){
		
		document.getElementById("btm_maridaje_"+id_recipe).innerHTML= "<a href='#' class='icono_marriage' onclick='view_marriage_hidde(\""+capa+"\", \""+id_recipe+"\", \""+id_user_profile+"\", \""+type+"\"); return false;'>ocultar maridaje</a>";
	
	}else{
		
		document.getElementById("btm_maridaje_"+id_recipe).innerHTML= "<a href='#' class='icono_marriage' onclick='view_maridaje(\""+capa+"\", \""+id_recipe+"\", \""+id_user_profile+"\", \""+type+"\"); return false;'>ver maridaje</a>";
	}
	
	var url = "insert.php?case=view_marriage&id_recipe="+id_recipe+"&type="+type+"&id_user_profile="+id_user_profile;
	
	send_ajax(url, capa);
	
}


function view_marriage_hidde(capa, id_recipe,id_user_profile, type){
	
	if(document.getElementById(capa).innerHTML==""){
		
		document.getElementById("btm_maridaje_"+id_recipe).innerHTML= "<a href='#' class='icono_marriage' onclick='view_marriage_hidde(\""+capa+"\", \""+id_recipe+"\", \""+id_user_profile+"\", \""+type+"\"); return false;'>ocultar maridaje</a>";
	
	}else{
		
		document.getElementById("btm_maridaje_"+id_recipe).innerHTML= "<a href='#' class='icono_marriage' onclick='view_maridaje(\""+capa+"\", \""+id_recipe+"\", \""+id_user_profile+"\", \""+type+"\"); return false;'>ver maridaje</a>";
	}
	
	document.getElementById(capa).innerHTML="";
	
}


function view_send(capa, id_recipe, type){
	

	var url = "insert.php?case=view_send&id_recipe="+id_recipe+"&type="+type;
	
	send_ajax(url, capa);
	
}


function delete_favorites(id_recipe){
	

	if(confirm("¿Estas seguro que ya no la queires en tus favoritos?")){
			   
		var url = "insert.php?case=delete_favorites&id_recipe="+id_recipe;
		
		//send_ajax(url, "box_recipes");
		
		var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById("box_recipes");
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
							
							myLytebox.updateLyteboxItems();
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
		
	}
}

function delete_message(id_subject){
	

	if(confirm("¿Estas seguro que quieres borrar el mensaje?")){
			   
		var url = "insert.php?case=delete_message&id_subject="+id_subject;
	
		send_ajax(url, "box_messages");
	}
}


function delete_send_message(id_subject){
	

	if(confirm("¿Estas seguro que quieres borrar el mensaje?")){
			   
		var url = "insert.php?case=delete_send_message&id_subject="+id_subject;
	
		send_ajax(url, "box_messages");
	}
}




function delete_friends(id_friend){
	

	if(confirm("¿Estas seguro que ya no queires ser su amigo?")){
			   
		var url = "insert.php?case=delete_friends&id_friend="+id_friend;
	
		send_ajax(url, "box_friends");
	}
}


function ok_friends_request(id_friend){
	
		var url = "insert.php?case=ok_friends_request&id_friend="+id_friend;
	
		send_ajax(url, "box_friends");
	
}

function delete_friends_request(id_friend){
	

	if(confirm("&iquest;Estas seguro que no queires ser su amigo?")){
			   
		var url = "insert.php?case=delete_friends_request&id_friend="+id_friend;
	
		send_ajax(url, "box_friends");
	}
}


function delete_favorites_wine(id_wine){
	

	if(confirm("&iquest;Estas seguro que ya no lo queires en tus favoritos?")){
			   
		var url = "insert.php?case=delete_favorites_wine&id_wine="+id_wine;
	
		send_ajax(url, "box_recipes");
	}
}



function send_ajax(url, capa){
	
		var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(capa);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
	
}

function info_ok(string,estado){
	
		//esta o ok o ko
	
		return "<span class='"+estado+"'>"+string+"</span>";
	}


function add_favorites(layer, type, id_register){
	

	var url = "insert_ddbb.php?type="+type+"&id_register="+id_register+"&origen=add_favorites";
	
	send_ajax(url, layer);
	
}

function insertar_favoritos_vino(objID, id_user, id_wine){

				var url = "insert_ddbb.php?id_user="+id_user+"&id_wine="+id_wine+"&origen=mis_favoritos_vino";
					
					
				var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(objID);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
	
}




function insertar_favoritos(objID, id_user, id_receta){

				var url = "insert_ddbb.php?id_user="+id_user+"&id_receta="+id_receta+"&origen=mis_favoritos";
					
				var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(objID);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
							
						} 
					}
				
				}
				
				xmlhttp.send(null);
	
}

function insertar_favoritos_social(objID, id_user,id_receta){

				var url = "../insert_ddbb.php?id_user="+id_user+"&id_receta="+id_receta+"&origen=mis_favoritos";
					
				var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(objID);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
							
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
	
}

function insertar_vinos_favoritos_social(objID, id_user,id_vino){

				var url = "../insert_ddbb.php?id_user="+id_user+"&id_wine="+id_vino+"&origen=mis_favoritos_vino";
					
				var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(objID);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
							
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
	
}

function enviar_mail_social(serverPage, objID, mail, comentario, procedencia, id_receta, tipo) {
		   
				var url = serverPage+"?mail="+mail+"&comentario="+comentario+"&procedencia="+procedencia+"&id_receta="+id_receta+"&suscribirse=false&tipo="+tipo;
					
				var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(objID);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
		
	}
	
function enviar_mail(serverPage, objID, mail, comentario, procedencia, id_receta, suscribirse) {
		   
				var url = serverPage+"?mail="+mail+"&comentario="+comentario+"&procedencia="+procedencia+"&id_receta="+id_receta+"&suscribirse="+suscribirse;
					
				var xmlhttp = nuevo_ajax();
				
				var obj = document.getElementById(objID);
				
				xmlhttp.open("GET", url);
				
				xmlhttp.onreadystatechange = function() {
					
					if(xmlhttp.readyState == 1){
						
							obj.innerHTML = "Cargando...";	
							
					} else {
					
						if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
							
							obj.innerHTML = xmlhttp.responseText;
					
						} 
					}
				
				}
				
				xmlhttp.send(null);
		
	}
	
	
function isEmail(smail) {
	
	var re=/^[a-z0-9\-\.]+@[a-z0-9\-\.]+\.[a-z]{2,}$/i;
	
	if(smail.match(re))	{
		
		return false;
		
	} else {
				
		return true;
		
	}
}



function enter_user_pass(capa,url){
	
	var url_string;
	
	url_string = "?user="+document.getElementById("user").value+"&pass="+document.getElementById("pass").value+"&"+url;
	
	alert (url_string);
	
}


function cambiar_view_recetas(modo,url){
	
	var new_url = "/"+modo+"/"+url;

	alert(new_url);
	
	document.location.href=new_url;
	
	
}


// enviar a un amogo


function recuperarPass(){
	
		var url = "/recuperar_pass.php";

		window.open(url,this.target,"width=650, height=350,top=0,left=0,toolbar=no,location=no,status=no, menubar=no");
	
}

function invitarAmigo(capa){


	if( (document.getElementById("nombre_amigo").value!="")&&(document.getElementById("nombre_amigo").value!="Su nombre!!")||(!isEmail(document.getElementById("mail_amigo").value))){
		
	
		document.getElementById(capa).innerHTML="<span style'color#900;'>Mensaje enviado, muchas gracias</span>";
	
		var url = "/mensaje_enviado.php?nombre="+document.getElementById("nombre_amigo").value+"&email="+document.getElementById("mail_amigo").value;
		
		window.open(url,this.target,"width=650, height=300,top=0,left=0,toolbar=no,location=no,status=no, menubar=no");
		
		document.getElementById("nombre_amigo").value="Su nombre!!";
		
		document.getElementById("mail_amigo").value="Su email!!";
		
	}else{
		
		document.getElementById(capa).innerHTML="<span style'color#900;'>Algo va mal!!</span>";
	}
}

function invitarAmigo2(capa){


	if( (document.getElementById("nombre_amigo").value!="")&&(document.getElementById("nombre_amigo").value!="Su nombre!!")||(!isEmail(document.getElementById("mail_amigo").value))&&(document.getElementById("mail_amigo").value!="")){
		
	
		document.getElementById(capa).innerHTML="<span style'color#900;'>Mensaje enviado, muchas gracias</span>";
	
		var url = "/mensaje_enviado.php?nombre="+document.getElementById("nombre_amigo").value+"&email="+document.getElementById("mail_amigo").value+"&message="+document.getElementById("message").value;
		
		send_ajax(url, capa);
		
		document.getElementById("nombre_amigo").value="";
		
		document.getElementById("mail_amigo").value="";
		
		document.getElementById("message").value="";
		
	}else{
		
		document.getElementById(capa).innerHTML="<span class='ko'>Algo va mal!!</span>";
	}
}

function tabular(e,obj) { 
  
  var tecla=(document.all) ? e.keyCode : e.which; 
  
  if(tecla!=13){
	  
	  	return; 
  }
  
  var frm=obj.form; 
  
  for(var i=0;i<frm.elements.length;i++){  
  
  if(frm.elements[i]==obj){  

		if(i==frm.elements.length-1){
			
			i=-1;
			
		}
	  
  		break;
  	} 
  
  frm.elements[i+1].focus(); 
  
	}
  return false; 
} 


// envios formularios



function enviar_formulario_post(url,capa,valores){

  			var ajax=nuevo_ajax();
	
          var capaContenedora = document.getElementById(capa);
	 		
		var direccion =url+valores;
		
         ajax.open ('GET',direccion , true);
		 
         ajax.onreadystatechange = function() {
        
					
					if(ajax.readyState == 1){
						
							capaContenedora.innerHTML = "<br /><br />Guardando...";	
							
					} else {
					
						if ( ajax.readyState == 4 && ajax.status == 200 ) {
							
								capaContenedora.innerHTML = ajax.responseText;
								
							
						} 
					}
				
				}
				
         	ajax.send(null);
        
			return;
		 
		
}




function guardar(formulario, contenedor){
	
	var combo = document.getElementById(formulario);
   
   var cantidad = combo.length;
   
   var parametros="?";
   
   for (var i = 0; i < cantidad-1; i++) {
     
        parametros+=combo.elements[i].name+"="+combo.elements[i].value+"&";
        
   }
   
   parametros+=combo.elements[i].name+"="+combo.elements[i].value

	
   enviar_formulario_post('insert_ddbb.php', contenedor, parametros);
    
  
	
}

function envia_formulario(formulario, contenedor){
	

		//document.getElementById(formulario).submit();
		
		guardar(formulario, contenedor);
}

function poner_sexo(sexo){
	
	document.getElementById('sexo').value=sexo;
	
}


function poner_visible(visible){
	
	document.getElementById('visible').value=visible;
	
}



function validarMail(capa,contenedor){
	
	if(!isEmail(capa.value)){
		
		document.getElementById(contenedor).innerHTML=info_ok("Correo correcto!","ok");
		document.getElementById('correcto').value='si';
		
	}else{
	
		document.getElementById(contenedor).innerHTML=info_ok("Correo incorrecto!","ko");
		document.getElementById('correcto').value='no';
	}
	
}



function enviar_comentario_publico(id_recipe, type, layer){
	

	if( (document.getElementById('comentario').value=="")||(document.getElementById('comentario').value=="escribe tu comentario")){
	
		document.getElementById(layer).innerHTML=info_ok("Mejor que comentes algo, no?","ko");	
		
	}else{
		
		var url = "insert_ddbb.php?origen=send_commnet&comment="+document.getElementById('comentario').value+"&id_recipe="+id_recipe+"&type="+type;
	
		send_ajax(url, layer);
		
		document.getElementById("comentario").value="";
	}
	
}

function enviar_comentario(comentario, capa,contenedor,id_receta, suscribirse){

		
		if( (document.getElementById(comentario).value!="")&&(document.getElementById(comentario).value!="escribe tu comentario") ){
			
			if(!document.getElementById(suscribirse).checked){
				
					enviar_mail('enviar_mail.php', contenedor , document.getElementById(capa).value,document.getElementById(comentario).value,'comentario',id_receta, document.getElementById(suscribirse).checked);
				
			}else if(isEmail(document.getElementById(capa).value)){
				
					document.getElementById(contenedor).innerHTML=info_ok("Correo incorrecto!","ko");
					
					
			}else{
				
				enviar_mail('enviar_mail.php', contenedor , document.getElementById(capa).value,document.getElementById(comentario).value,'comentario',id_receta, document.getElementById(suscribirse).checked);
				
				document.getElementById("comentario").value="";
			}
			
		}else{
		
			document.getElementById(contenedor).innerHTML=info_ok("No hay comentarios!, no se puede enviar","ko");
		}
		
	}
	
	
	function enviar_comentario_social(comentario, capa,contenedor,id_receta, tipo){

		if(document.getElementById(comentario).value!=""){
			
				enviar_mail_social('../enviar_mail.php', contenedor , document.getElementById(capa).value,document.getElementById(comentario).value,'comentario',id_receta, tipo);
				
				document.getElementById("comentario").value="";
			
		}else{
		
			document.getElementById(contenedor).innerHTML=info_ok("No hay comentarios!, no se puede enviar","ko");
		}
		
	}

// Resetar Formulario

function reset_formulario(formulario){
	
	document.getElementById(formulario).reset();
	
}


// FORMULARIO SOLO NUMEROS

function onlyNumbersDano(evt){
	
        var keyPressed = (evt.which) ? evt.which : event.keyCode
        return !(keyPressed > 31 && (keyPressed < 48 || keyPressed > 57));
}
	  


// LINKS EXTERNOS

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;
																																												
																																												

function sugerirReceta(){
	
	var estado=0;
	
	
	if( (document.getElementById('tipo_1').checked==false) && (document.getElementById('tipo_2').checked==false) && (document.getElementById('tipo_3').checked==false) ){
		
		estado =1;
		
		document.getElementById('t_tipo').className="error";
			
	}else{ 
	
		document.getElementById('t_tipo').className="texto_verde_color";
		
	
	} 
	
	if(document.getElementById('titulo').value==""){
	
		estado =1;
		
		document.getElementById('t_titulo').className="error";
			
	}else{ 
	
		document.getElementById('t_titulo').className="texto_verde_color";
		
	
	} 
	if(document.getElementById('categoria').value=="nada"){
	
		estado =1;
		
		document.getElementById('t_categoria').className="error";
			
	}else{ 
	
		document.getElementById('t_categoria').className="";
		
	
	} 
	
	
	if(document.getElementById('ingredientes').value==""){
	
		estado =1;
		
		document.getElementById('ingredientes').className="error";
		
		document.getElementById('t_ingredientes').className="error";
			
	}else{ 
	
		document.getElementById('ingredientes').className="";
		
		document.getElementById('t_ingredientes').className="texto_verde_color";
	
	} 
	
	
	
	if(document.getElementById('elaboracion').value==""){
	
		estado =1;
		
		document.getElementById('elaboracion').className="error";
		
		document.getElementById('t_elaboracion').className="error";
			
	}else{ 
	
		document.getElementById('elaboracion').className="";
		
		document.getElementById('t_elaboracion').className="texto_verde_color";
	
	}
	
	if(estado==1){
		
				alert("Has de rellenar todos los datos");
	
	}else{
		
						document.from_sugerir_receta.submit();
			
	}
	
	
}


function mostrar_menu(capa,capa_text){
	
	if(document.getElementById(capa).style.display=="none"){document.getElementById(capa).style.display='block';}else{document.getElementById(capa).style.display='none';}
	
	if(document.getElementById(capa_text).className=='enlace_h_selec'){document.getElementById(capa_text).className='enlace_h';}else{document.getElementById(capa_text).className='enlace_h_selec';}
	
}

function mostrar_ocultar(capa){
	
	if(document.getElementById(capa).style.display=="none"){document.getElementById(capa).style.display='block';}else{document.getElementById(capa).style.display='none';}
	
}


function mostrar_campo_trucos(){
	
	if(document.getElementById('cat_tricks').value=="news"){
		
		document.getElementById('new_cat').style.display='block';

		document.getElementById('height_new_cat').style.height="58px";
	
	}else{
		
		document.getElementById('new_cat').style.display='none';
		
		document.getElementById('height_new_cat').style.height="0px";
	}
	
}

// FUNCIONES IMPRIMIR

function imprSelec_only(id){
	
	document.getElementById('selector').style.display='none';
	var ficha = document.getElementById(id);
	var ventimp = window.open(' ', 'popimpr');
	ventimp.document.write( ficha.innerHTML );
	ventimp.document.close();
	ventimp.print( );
	ventimp.close();
	document.getElementById('selector').style.display='block'; 
  } 
  
  
  	function impri(iden){
			
				var ventana = window.open('/apps/print.php?id='+iden+'&mode=receta&seccion=T','','width=600,height=550,top=120,left=100,toolbar=no,location=no,status=no,menubar=no;scrollbars=yes');
				
				
	}
	
	function impri_vino(iden){
			
				
				var ventana = window.open('/apps/print.php?id='+iden+'&mode=vino','','width=600,height=550,top=120,left=100,toolbar=no,location=no,status=no,menubar=no;scrollbars=yes');
				
				
				
	}
			
	function tipo_imprimir(secc){
	
				document.getElementById('imprimir').value=secc;
	
	}
			

// FIN FUNCIONES IMPRIMIR

function mostrarCapa(master,capa){
	

	if(document.getElementById(master).checked){document.getElementById(capa).style.display='block';}else{document.getElementById(capa).style.display='none';}

}

function ocultarCapa(mostrar,ocultar){
	
	document.getElementById(mostrar).style.display='block';
	document.getElementById(ocultar).style.display='none';

}

function swap_capa(capa, imagen){
	

	if(document.getElementById(capa).style.display=="none"){
			
			document.getElementById(capa).style.display='block';
			
			document.getElementById(imagen).src="images/esconder_ficha_cata_r.gif";	
			
	}else{
			
			document.getElementById(capa).style.display='none';
			
			document.getElementById(imagen).src="images/ver_ficha_cata_r.gif";	
		
	}
	
	
	
}



function swap_capa_over(capa, imagen){
	
	
	
	if(document.getElementById(capa).style.display=="none"){
			
			document.getElementById(imagen).src="images/ver_ficha_cata_r.gif";		
			
	}else{
			
			document.getElementById(imagen).src="images/esconder_ficha_cata_r.gif";

	}
	
	
	
}


function swap_capa_out(capa, imagen){
	

	if(document.getElementById(capa).style.display=="none"){
			
			document.getElementById(imagen).src="images/ver_ficha_cata_n.gif";		
			
	}else{
			
			document.getElementById(imagen).src="images/esconder_ficha_cata_n.gif";

	}
	
	
	
}




function  suscribirse(contenedor){


	if(!isEmail(document.getElementById('mail').value)){
		
		if(contenedor=="suscribete_escribir_receta"){
			
			enviar_mail('enviar_mail.php', contenedor , document.getElementById('mail').value,'','suscribete_escribir_receta','','');	
			
		}else{
			
			enviar_mail('enviar_mail.php', contenedor , document.getElementById('mail').value,'','suscribete','','');
		
		}
	
	}else{
	
		validarMail(document.getElementById('mail'),"resultado_ins");
		
	}
}

function  redirigir(){


	window.location="/"+document.getElementById('id').value; 
}

function  redirigir_social(type){

	switch(type){
		
		case "recipes_user":
		
			window.location="/social/recipes-friends.php?friend="+document.getElementById('id').value; 
		
		break;
		
		case "restaurants":
		
			window.location="/social/"+document.getElementById('id_restauarnt').value; 
		
		break;
		
		case "recipes":
		
			window.location="/social/"+document.getElementById('id').value; 
		
		break;
		
	}
}

function  redirigir_restaurant(){
	
	document.getElementById("nombre_restaurante").value="";
	
	window.location="/"+document.getElementById('id_restauarnt').value; 
}


function  buscar(){

	document.form_buscador.submit();
	
}

function buscar_mod(pagina, capa){
	
	
	var url = "http://www.vinosyrecetas.com/";
	
	window.location=url+document.getElementById(capa).value; 
	
}
	
function  buscar_pais(){

	window.location="http://www.vinosyrecetas.com/"+document.getElementById("sel_pais").value; 
	
}

function mostrar_calendario(){
	
	if(document.getElementById('calendario').style.display=='block'){
		
		document.getElementById('calendario').style.display='none';
	
	}else{
		
			document.getElementById('calendario').style.display='block';
	}
}

function verificar_datos(capa,contenedor){
	
	var estado = true;
	
	switch(capa){
		
		
		case "user":
				
				
			if(document.getElementById(capa).value==""){
				
				document.getElementById(contenedor).innerHTML = info_ok("falta por rellenar",'ko');
				
				estado = false;
					
			}else{
				
				document.getElementById(contenedor).innerHTML = info_ok("Correcto",'ok');
			}
		
		break;
		
		case "mail":
				
				
			if(document.getElementById(capa).value==""){
				
					document.getElementById(contenedor).innerHTML = info_ok("falta por rellenar",'ko');
					
				estado = false;					
					
			}else{
				
				if(isEmail(document.getElementById('mail').value)){
					
					document.getElementById(contenedor).innerHTML = info_ok("correo incorrecto",'ko');
				
				estado = false;					
						
				}else{
					
					document.getElementById(contenedor).innerHTML = info_ok("Correcto",'ok');
				}
			}
		
		break;
		
		default:
		
			if(document.getElementById(capa).value==""){
				
				document.getElementById(contenedor).innerHTML = info_ok("falta por rellenar",'ko');
					
				estado = false;
								
			}else{
				
				document.getElementById(contenedor).innerHTML = info_ok("Correcto",'ok');
			}
		
		break;
	
	}
	
	return estado;
	
}


function  enviarAmigo(){
	
	var estado=0;
	
	
	if(document.getElementById('tunombre').value==""){    
	
		estado =1;
		
		document.getElementById('t_tunombre').className="error";
		
		document.getElementById('tunombre').className="error";
		
	}else{
		
		document.getElementById('t_tunombre').className="";
		
		document.getElementById('tunombre').className="";
		
	}
	
	if(document.getElementById('sunombre').value==""){    
	
		estado =1;
		
		document.getElementById('t_sunombre').className="error";
		
		document.getElementById('sunombre').className="error";
		
	}else{
		
		document.getElementById('t_sunombre').className="";
		
		document.getElementById('sunombre').className="";
		
	}
	
	if( (isEmail(document.getElementById('tumail').value)) || (document.getElementById('tumail').value=="") ){    
	
		estado =1;
		
		document.getElementById('t_tumail').className="error";
		
		document.getElementById('tumail').className="error";
		
	}else{
		
		document.getElementById('t_tumail').className="";
		
		document.getElementById('tumail').className="";
		
	}
	
	if( (isEmail(document.getElementById('sumail').value)) || (document.getElementById('sumail').value=="") ){    
	
		estado =1;
		
		document.getElementById('t_sumail').className="error";
		
		document.getElementById('sumail').className="error";
		
	}else{
		
		document.getElementById('t_sumail').className="";
		
		document.getElementById('sumail').className="";
		
	}
	
	
	
	if(estado==0){
		
		if(document.getElementById('suma').value==document.getElementById('suma_text').value){    
	
			document.from_enviar_amigo.submit();
		
		}else{
			
				alert("Responde la pregunta de seguridad, gracias");		
		}
		
	
	}else{
	
		alert("Rellene todos los datos");
		
	}
}

function retall_name_suggest(input){
	
	var string = input.split("->");
	
	string = strip_tags(string[0]);
	
	return string;
	
}

function strip_tags (input, allowed) {
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}
// sub

/**
 *  author:		Timothy Groves - http://www.brandspankingnew.net
 *	version:	1.2 - 2006-11-17
 *              1.3 - 2006-12-04
 *              2.0 - 2007-02-07
 *              2.1.1 - 2007-04-13
 *              2.1.2 - 2007-07-07
 *              2.1.3 - 2007-07-19
 *
 */


if (typeof(bsn) == "undefined")
	_b = bsn = {};


if (typeof(_b.Autosuggest) == "undefined")
	_b.Autosuggest = {};
else
	alert("Autosuggest is already set!");












_b.AutoSuggest = function (id, param)
{
	// no DOM - give up!
	//
	if (!document.getElementById)
		return 0;
	
	
	
	
	// get field via DOM
	//
	this.fld = _b.DOM.gE(id);

	if (!this.fld)
		return 0;
	
	
	
	
	// init variables
	//
	this.sInp 	= "";
	this.nInpC 	= 0;
	this.aSug 	= [];
	this.iHigh 	= 0;
	
	
	
	
	// parameters object
	//
	this.oP = param ? param : {};
	
	// defaults	
	//
	var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:500, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 25};
	for (k in def)
	{
		if (typeof(this.oP[k]) != typeof(def[k]))
			this.oP[k] = def[k];
	}
	
	
	// set keyup handler for field
	// and prevent autocomplete from client
	//
	var p = this;
	
	// NOTE: not using addEventListener because UpArrow fired twice in Safari
	//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
	
	this.fld.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
	this.fld.onkeyup 		= function(ev){ return p.onKeyUp(ev); };
	
	this.fld.setAttribute("autocomplete","off");
};
















_b.AutoSuggest.prototype.onKeyPress = function(ev)
{
	
	var key = (window.event) ? window.event.keyCode : ev.keyCode;



	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	
	var bubble = 1;

	switch(key)
	{
		case RETURN:
			this.setHighlightedValue();
			bubble = 0;
			break;

		case ESC:
			this.clearSuggestions();
			break;
	}

	return bubble;
};



_b.AutoSuggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;
	


	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//

	var ARRUP = 38;
	var ARRDN = 40;
	
	var bubble = 1;

	switch(key)
	{


		case ARRUP:
			this.changeHighlight(key);
			bubble = 0;
			break;


		case ARRDN:
			this.changeHighlight(key);
			bubble = 0;
			break;
		
		
		default:
			this.getSuggestions(this.fld.value);
	}

	return bubble;
	

};








_b.AutoSuggest.prototype.getSuggestions = function (val)
{
	
	// if input stays the same, do nothing
	//
	if (val == this.sInp)
		return 0;
	
	
	// kill list
	//
	_b.DOM.remE(this.idAs);
	
	
	this.sInp = val;
	
	
	// input length is less than the min required to trigger a request
	// do nothing
	//
	if (val.length < this.oP.minchars)
	{
		this.aSug = [];
		this.nInpC = val.length;
		return 0;
	}
	
	
	
	
	var ol = this.nInpC; // old length
	this.nInpC = val.length ? val.length : 0;
	
	
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	//
	var l = this.aSug.length;
	if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
	{
		var arr = [];
		for (var i=0;i<l;i++)
		{
			if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
				arr.push( this.aSug[i] );
		}
		this.aSug = arr;
		
		this.createList(this.aSug);
		
		
		
		return false;
	}
	else
	// do new request
	//
	{
		var pointer = this;
		var input = this.sInp;
		clearTimeout(this.ajID);
		this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
	}

	return false;
};





_b.AutoSuggest.prototype.doAjaxRequest = function (input)
{
	// check that saved input is still the value of the field
	//
	if (input != this.fld.value)
		return false;
	
	
	var pointer = this;
	
	
	// create ajax request
	//
	if (typeof(this.oP.script) == "function")
		var url = this.oP.script(encodeURIComponent(this.sInp));
	else
		var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
	
	if (!url)
		return false;
	
	var meth = this.oP.meth;
	var input = this.sInp;
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
	var onErrorFunc = function (status) { alert("AJAX error: "+status); };

	var myAjax = new _b.Ajax();
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
};





_b.AutoSuggest.prototype.setSuggestions = function (req, input)
{
	// if field input no longer matches what was passed to the request
	// don't show the suggestions
	//
	if (input != this.fld.value)
		return false;
	
	
	this.aSug = [];
	
	
	if (this.oP.json)
	{
		var jsondata = eval('(' + req.responseText + ')');
		
		for (var i=0;i<jsondata.results.length;i++)
		{
			this.aSug.push(  { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info }  );
		}
	}
	else
	{

		var xml = req.responseXML;
	
		// traverse xml
		//
		var results = xml.getElementsByTagName('results')[0].childNodes;

		for (var i=0;i<results.length;i++)
		{
			if (results[i].hasChildNodes())
				this.aSug.push(  { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') }  );
		}
	
	}
	
	this.idAs = "as_"+this.fld.id;
	

	this.createList(this.aSug);

};














_b.AutoSuggest.prototype.createList = function(arr)
{
	var pointer = this;
	
	
	
	
	// get rid of old list
	// and clear the list removal timeout
	//
	_b.DOM.remE(this.idAs);
	this.killTimeout();
	
	
	// if no results, and shownoresults is false, do nothing
	//
	if (arr.length == 0 && !this.oP.shownoresults)
		return false;
	
	
	// create holding div
	//
	var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});	
	
	var hcorner = _b.DOM.cE("div", {className:"as_corner"});
	var hbar = _b.DOM.cE("div", {className:"as_bar"});
	var header = _b.DOM.cE("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	
	
	
	// create and populate ul
	//
	var ul = _b.DOM.cE("ul", {id:"as_ul"});
	
	
	
	
	// loop throught arr of suggestions
	// creating an LI element for each suggestion
	//
	for (var i=0;i<arr.length;i++)
	{
		// format output with the input enclosed in a EM element
		// (as HTML, not DOM)
		//
		var val = arr[i].value;
		var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
		var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
		
		
		var span 		= _b.DOM.cE("span", {}, output, true);
		if (arr[i].info != "")
		{
			var br			= _b.DOM.cE("br", {});
			span.appendChild(br);
			var small		= _b.DOM.cE("small", {}, arr[i].info);
			span.appendChild(small);
		}
		
		var a 			= _b.DOM.cE("a", { href:"#" });
		
		var tl 		= _b.DOM.cE("span", {className:"tl"}, " ");
		var tr 		= _b.DOM.cE("span", {className:"tr"}, " ");
		a.appendChild(tl);
		a.appendChild(tr);
		
		a.appendChild(span);
		
		a.name = i+1;
		a.onclick = function () { pointer.setHighlightedValue(); return false; };
		a.onmouseover = function () { pointer.setHighlight(this.name); };
		
		var li = _b.DOM.cE(  "li", {}, a  );
		
		ul.appendChild( li );
	}
	
	
	// no results
	//
	if (arr.length == 0 && this.oP.shownoresults)
	{
		var li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
		ul.appendChild( li );
	}
	
	
	div.appendChild( ul );
	
	
	var fcorner = _b.DOM.cE("div", {className:"as_corner"});
	var fbar = _b.DOM.cE("div", {className:"as_bar"});
	var footer = _b.DOM.cE("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	//
	var pos = _b.DOM.getPos(this.fld);
	
	div.style.left 		= pos.x + "px";
	div.style.top 		= ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	div.style.width 	= this.fld.offsetWidth + "px";
	
	
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	//
	div.onmouseover 	= function(){ pointer.killTimeout() };
	div.onmouseout 		= function(){ pointer.resetTimeout() };


	// add DIV to document
	//
	document.getElementsByTagName("body")[0].appendChild(div);
	
	
	
	// currently no item is highlighted
	//
	this.iHigh = 0;
	
	
	
	
	
	
	// remove list after an interval
	//
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};















_b.AutoSuggest.prototype.changeHighlight = function(key)
{	
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	var n;

	if (key == 40)
		n = this.iHigh + 1;
	else if (key == 38)
		n = this.iHigh - 1;
	
	
	if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;
	
	
	this.setHighlight(n);
};



_b.AutoSuggest.prototype.setHighlight = function(n)
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
		this.clearHighlight();
	
	this.iHigh = Number(n);
	
	list.childNodes[this.iHigh-1].className = "as_highlight";


	this.killTimeout();
};


_b.AutoSuggest.prototype.clearHighlight = function()
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
	{
		list.childNodes[this.iHigh-1].className = "";
		this.iHigh = 0;
	}
};


_b.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHigh)
	{
		this.sInp = this.fld.value = this.aSug[ this.iHigh-1 ].value;
		
		// move cursor to end of input (safari)
		//
		this.fld.focus();
		if (this.fld.selectionStart)
			this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
		

		this.clearSuggestions();
		
		// pass selected object to callback function, if exists
		//
		if (typeof(this.oP.callback) == "function")
			this.oP.callback( this.aSug[this.iHigh-1] );
	}
};













_b.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
};

_b.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};







_b.AutoSuggest.prototype.clearSuggestions = function ()
{
	
	this.killTimeout();
	
	var ele = _b.DOM.gE(this.idAs);
	var pointer = this;
	if (ele)
	{
		var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
	}
};










// AJAX PROTOTYPE _____________________________________________


if (typeof(_b.Ajax) == "undefined")
	_b.Ajax = {};



_b.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
};



_b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{
	
	if (meth != "POST")
		meth = "GET";
	
	this.onComplete = onComp;
	this.onError = onErr;
	
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open(meth, url, true);
			this.req.send();
		}
	}
};


_b.Ajax.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			this.onComplete( this.req );
		} else {
			this.onError( this.req.status );
		}
	}
};










// DOM PROTOTYPE _____________________________________________


if (typeof(_b.DOM) == "undefined")
	_b.DOM = {};



/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return 0;
		
	for (var a in attr)
		ne[a] = attr[a];
	
	var t = typeof(cont);
	
	if (t == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (t == "string" && html)
		ne.innerHTML = cont;
	else if (t == "object")
		ne.appendChild( cont );

	return ne;
};



/* get element */
_b.DOM.gE = function ( e )
{
	var t=typeof(e);
	if (t == "undefined")
		return 0;
	else if (t == "string")
	{
		var re = document.getElementById( e );
		if (!re)
			return 0;
		else if (typeof(re.appendChild) != "undefined" )
			return re;
		else
			return 0;
	}
	else if (typeof(e.appendChild) != "undefined")
		return e;
	else
		return 0;
};



/* remove element */
_b.DOM.remE = function ( ele )
{
	var e = this.gE(ele);
	
	if (!e)
		return 0;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return 0;
};



/* get position */
_b.DOM.getPos = function ( e )
{
	var e = this.gE(e);

	var obj = e;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	var obj = e;
	
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop};
};










// FADER PROTOTYPE _____________________________________________



if (typeof(_b.Fader) == "undefined")
	_b.Fader = {};





_b.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return 0;
	
	this.e = ele;
	
	this.from = from;
	this.to = to;
	
	this.cb = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
};




_b.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
	var op = ieop / 100;
	
	if (this.e.filters) // internet explorer
	{
		try
		{
			this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.e.style.opacity = op;
	}
	
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.cb != undefined)
			this.cb();
	}
};



_b.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
};
