// JavaScript Document

$(document).ready(function(){
	
	/********************************************************/
		
		$("#descripcion").click(function(){
			$("#descripcion").removeClass('bg_descripcion');
		})
		
		$("#descripcion").focus(function(){
			$("#descripcion").removeClass('bg_descripcion');
		})
		
		$("#titulo_recomendacion").click(function(){
			$("#titulo_recomendacion").removeClass('bg_titulo');
		})
		
		$("#titulo_recomendacion").focus(function(){
			$("#titulo_recomendacion").removeClass('bg_titulo');
		})
		
		
		$("#url_image").click(function(){
			$("#url_image").removeClass('bg_pega_html');
		})
		
		
		$("#url_video, #url_post").click(function(){
			$(this).removeClass('bg_pega_url');
		})
		
		
		
		
	/********************************************************/
	
	var src_orignal = '';
	
	$(".rollover").hover(
		function(){
			var new_src = this.alt;
			src_orignal = $(this).attr("src");
			$(this).attr("src",new_src);
		},
		function(){
			$(this).attr("src",src_orignal);
		})		
	
	
	
	$(".numeric").numeric();
	
	
	
	$("#registro").submit(function(e){
			
			var error = false;					   
			var selecionado = false;
			var selecionado2 = false;
			var selecionado3 = false;
			var existe = false;
			var existe2 = false;
			var existe3 = false;
			var step   = $("#next").val();
			var extrastep   = $("#next2").val();
			
			$("#registro .obligatorio").each(function(){
						
						
						var label = this.title
						var value = $(this).val();		
						var nImg  = $("#numeroImagen").val();
					
						
						if ((!value) || (value == 0)){
								alert("Por favor, "+label);
								$(this).focus();
								error = true;
								return false;
						}
					 
					 
								
						if (!error){
							$(".valid_mail").each(function(){
														var value = $(this).val();
														if (isEmailAddress(value)==false){
															alert("El campo "+label+" es invalido");
															$(this).focus();
															error = true;
															return false;
														}
							
							   })
						}
			})
			
			
			
			$(".radio_btn").each(function(){
						existe = true;
						var value = $(this).attr("checked");	
						if (value){
							selecionado = true;
						}
			})
			
			$(".radio_btn2").each(function(){
						existe2 = true;
						var value = $(this).attr("checked");	
						if (value){
							selecionado2 = true;
						}
			})
			
			
				
				if (!selecionado && existe){
						error = true;
						alert("Por favor, dinos cual es tu nivel de ingl\u00e9s");
						return false;
				}
				
				$(".radio_btn3").each(function(){
						existe3 = true;
						var value = $(this).attr("checked");	
						if ($(this).val() == 2  && value){
							if (!$("#otro_idioma").val()){
								alert("¿Qué otro idioma hablas?");
								error = true;
								$("#otro_idioma").focus();
								return false;
							}
						}
				})
			
			
			$(".idiomaPost").each(function(){
						existe = true;
						var value = $(this).attr("checked");	
						if (value){
							selecionado = true;
							$("#idioma_post_Id").val($(this).val());
						}
						
			})
			
			
			if (!selecionado && existe){
						error = true;
						alert("Por favor, dinos en que idioma escribres tu recomendaci\xF3n ?");
						return false;
			}
			
			
			selecionado = false;
			existe = false;

			$(".poblaciones").each(function(){
						existe = true;
						var value = $(this).attr("checked");	
						if (value){
							selecionado = true;
							$("#poblacion_ID").val($(this).val());
						}
					
			})
		
			
			if (!selecionado && existe){
						error = true; 
						alert("Por favor, dinos en qu\u00e9  isla est\u00e1  situada tu recomendaci\xF3n ?");
						return false;
			}
			
			var categorias = '';
			selecionado = false;
			existe = false;
			
			$(".categorias").each(function(){
						existe = true;
						var value = $(this).attr("checked");	
						if (value){
							if (!categorias)
									categorias = $(this).val();
								else
									categorias += ','+$(this).val()
						}
					
					if (!categorias) 
							selecionado = false;
						else
							$("#idCategorias").val(categorias)
			})
			
			
			if (!selecionado && existe && !categorias){
						error = true; 
						alert("Por favor, debe seleccionar almenos un tipo de recomendaci\xF3n");
						return false;
			}
			
			/*
				if (!selecionado2 && existe2){
						error = true;
						alert("Por favor, dinos dónde prefieres hacer el casting");
						return false;
				}
				*/
								
				/*
				$(".nombre").each(function(){
					var info = $(this).val();
					var id 	 = this.id.split("_");
					if (info){
						var email = $("#email_"+id[1]).val();
						if ((isEmailAddress(email)==false) || (!email)){
								alert("Falate el email de tu amigo.");
								$("#email_"+id[1]).focus();
								error = true;
								return false;
							}
					}
				})
				*/
				
				if (step=="step4" || (extrastep)){
						
					
						
						var nacido      = $("#nacido").val();
						var empadronado = $("#empadronado").val();
					
						if ((nacido==0)  &&  (empadronado==0) ){
							alert("Por Favor, elige un lugar de las Islas Canarias");
							error = true;
							return false;
						}
				}
				
				if ($("#condiciones")){
					if ($("#condiciones").attr("checked")==false){
						alert("confirma que aceptas las condiciones de participaci\xF3n");
						error = true;
					}
				}
							
				if (error)
					e.preventDefault();
		})
	
	
		$(".confirmacion").click(function(e){
					var info = this.title;
					var res;
					if (!info)
						  info = '¿Deseas eliminar este registro?';
					res = confirm(info);
					if (res==false)
						e.preventDefault();
			})
	
	
		$(".add_imagen").click(function(){
														
										
				    var value = $("#url_image").val();
					var error = "";
					if (value) {
					
					// Verifica que el string comporte el SRC, y que el enlace empeza por "http" y acaba por "jpg o png"
					if( value.search(/http/) != "-1"  && ( value.search(/jpg"/) != "-1" || value.search(/png/) != "-1" )) 
					{
					value = value.split('src="');
					value = value[1].split('"');
					value = value[0];
					}
					else {
					error = "El c\xF3digo HTML no es v\xE1lido, la imagen debe ser una URL a un fichero jpg o png";
					}
					}
					else {
					error = "Falta el c\xF3digo HTML de Flickr o Picasa.";
					}
					if (error!=""){
					alert(error);
					error="";
				}else{
					$(this).append('<img src="images/ajaxloader.gif" width="15" height="15" align="baseline" id="loadImage1" />')
					$("#add_image").hide();
					$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=add_image&url="+value,
								success: function(msg){
									//alert(msg);
									if (msg != "X999"){
										
											$("#add").append('<div class="block_media_pic" id="BLOCK'+msg+'"><img src="'+value+'" width="100" height="85" />\
												              <img src="images/espanol/eliminar.jpg" width="83" height="23" align="texttop"  class="pointer" onclick="elimnar_imagen('+msg+')"  /><br class="clear" /></div>')
										var Numero = $("#numeroImagen").val();
										$("#numeroImagen").val(parseInt(Numero) + 1);
										loadImagesIframe(msg);
										}else{
											alert("S\xF3lo se permiten 3 Imagenes por recomendaci\xF3n.");
									}
								},complete: function(){
									$("#loadImage1").remove();
									$("#url_image").val('')
									$("#add_image").show();
								}
					});
			   }
		})
	
		$(".add_video").click(function(){
									   
				if ($("#add_video").attr("src")=="images/espanol/eliminar.jpg"){
						var id = $("#url_video_id").val();
						if (id){
							elimnar_youtube(id);
							return;
						}
						
				}					   
									   
				var value = $("#url_video").val();
				if (!value){
					alert('Falta el enlace al video');
				}else{
					$(this).append('<img src="images/ajaxloader.gif" width="15" height="15" align="baseline" id="loadImage2" />')
					$("#add_video").hide();
					$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=add_video&url="+value,
								success: function(msg){
									if (msg != "X999"){
											 $("#url_video_id").val(msg);
											 $("#add_video").attr("src","images/espanol/eliminar.jpg")
										}else{
											alert("S\xF3lo se permite 1 video");
									}
								},complete: function(){
									$("#loadImage2").remove();
									$("#add_video").show();
								}
					});
				}
		})
		
		$(".add_post").click(function(){
					
				if ($("#add_post").attr("src")=="images/espanol/eliminar.jpg"){
						var id = $("#url_post_id").val();
						if (id){
							elimnar_post(id);
							return;
						}
						
				}					   
									   
				var value = $("#url_post").val();
				if (!value){
					alert('Falta la url de la post');
				}else{
					$(this).append('<img src="images/ajaxloader.gif" width="15" height="15" align="baseline" id="loadImage3" />')
					$("#add_post").hide();
					$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=add_post&url="+value,
								success: function(msg){
									if (msg != "X999"){
											 $("#url_post_id").val(msg);
											 $("#add_post").attr("src","images/espanol/eliminar.jpg")
										}else{
											alert("S\xF3lo se permite 1 post");
									}
								},complete: function(){
									$("#loadImage3").remove();
									$("#add_post").show();
								}
					});
				}
		})
		
			
		new AjaxUpload('#upload_button_id', {
		  // Location of the server-side upload script
		  // NOTE: You are not allowed to upload files to another domain
		  action: 'picasa.php',
		  // File upload name
		  name: 'upload_imagen',
		  // Additional data to send
		 // data: {
			//example_key1 : 'example_value',
			//example_key2 : 'example_value2'
		  //},
		  // Submit file after selection
		  autoSubmit: true,
		  // The type of data that you're expecting back from the server.
		  // HTML (text) and XML are detected automatically.
		  // Useful when you are using JSON data as a response, set to "json" in that case.
		  // Also set server response type to text/html, otherwise it will not work in IE6
		  responseType: false,
		  // Fired after the file is selected
		  // Useful when autoSubmit is disabled
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onChange: function(file, extension){
			  
			  	if (! (extension && /^(jpg|png|jpeg|gif)$/.test(extension))){
                        // extension is not allowed
                        alert('Error: archivo invalido');
                        // cancel upload
                        return false;
                }

			  
			  
				var numero = $("#numeroImagen").val();
				if (numero ==3){
			    	alert("S\xF3lo se permiten 3 Imagenes por recomendaci\xF3n.");
					return false;
				}else
					return true;
		  },
		  // Fired before the file is uploaded
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onSubmit: function(file, extension) {
				$("#upload_button_id").hide();
				$("#load_image").append('<div id="div_imagen"> Cargando Imagen ...</div');
				deshabilitar();
		  },
		  // Fired when file upload is completed
		  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		  // @param file basename of uploaded file
		  // @param response server response
		  onComplete: function(file, response) {
			 
			 $("#div_imagen").remove(); 
			 $("#upload_button_id").show();
			 if (response == '666'){
				alert("Error: La imagen excede el tama\xF1o permitido (1Mb)");
				return ;
			 }
			  
			 
			 $.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=add_image&url="+response,
								success: function(msg){
									if (msg != "X999"){
											$("#add").append('<div class="block_media_pic" id="BLOCK'+msg+'"><div class="picImage"><img src="'+response+'" width="100" height="85" /></div>\
												              <img src="images/espanol/eliminar.jpg" width="83" height="23" align="texttop"  class="pointer" onclick="elimnar_imagen('+msg+')"  /><br class="clear" /></div>')
										var Numero = $("#numeroImagen").val();
										$("#numeroImagen").val(parseInt(Numero) + 1);
										loadImagesIframe(response)
										}else{
											alert("S\xF3lo se permiten 3 Imagenes por recomendaci\xF3n.");
									}
								},complete: function(){
									$("#loadImage1").remove();
									$("#url_image").val('')
									$("#add_image").show();
									habilitar();
								}
					});
		  	 // alert(response);
		  }
		});
		
			
		
		/***************************************************************************************************************/
		new AjaxUpload('#upload_button_id2', {
		  // Location of the server-side upload script
		  // NOTE: You are not allowed to upload files to another domain
		  action: 'ZendTube/youtube.php',
		  // File upload name
		  name: 'archivo',
		  // Additional data to send
		 // data: {
			//example_key1 : 'example_value',
			//example_key2 : 'example_value2'
		  //},
		  // Submit file after selection
		  autoSubmit: true,
		  // The type of data that you're expecting back from the server.
		  // HTML (text) and XML are detected automatically.
		  // Useful when you are using JSON data as a response, set to "json" in that case.
		  // Also set server response type to text/html, otherwise it will not work in IE6
		  responseType: false,
		  // Fired after the file is selected
		  // Useful when autoSubmit is disabled
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onChange: function(file, extension){
				if ($("#add_video").attr("src")=="images/espanol/eliminar.jpg"){
					alert("S\xF3lo se permite 1 video");
					return false
				}
		  },
		  // Fired before the file is uploaded
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onSubmit: function(file, extension) {
			  	$("#upload_button_id2").hide();
				$("#load_video").append('<div id="div_video"> Cargando Video ...</div');
				deshabilitar();
		  },
		  // Fired when file upload is completed
		  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		  // @param file basename of uploaded file
		  // @param response server response
		  onComplete: function(file, response) {
			
			if (response != "X9999"){
					$.ajax({
										type   : "POST",
										url    : "ajax.php",
										data   : "act=add_video&url="+response,
										success: function(msg){
											if (msg != "X999"){
													 $("#url_video_id").val(msg);
													 $("#add_video").attr("src","images/espanol/eliminar.jpg")
												}else{
													alert("S\xF3lo se permite 1 video");
											}
										},complete: function(){
											$("#loadImage2").remove();								
										}
							});
			
			
			$("#div_video").remove();
			$("#upload_button_id2").show();
			$("#url_video").val(response);
				habilitar();
			}else{
				$("#div_video").remove();
				$("#upload_button_id2").show();
				alert("Se ha producido un error durante la carga.");
				habilitar();
			}
		  }
		});
		
		/**************************************************************************************************************/
		
		
})

function valid_login(){
			
				var email = $("#user_login").val();
				var pass = $("#user_pass").val();
				
				if (email && pass){
						if (isEmailAddress(email)==false){
								$("#user_login").focus()
								alert("El email es invalido.");
								return false;
						}
				}else{
					alert("Por favor, introduce tus datos de acceso.");
					return false;
				}
				return true;
				
}

function habilitar(){
	$("#next_step").show();
}

function deshabilitar(){
	$("#next_step").hide();
}



function elimnar_imagen(id){
	var res = confirm("\xBF Desea eliminar esta imagen ?");
		if (res){
					$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=del_image&url="+id,
								complete:function(){
									$("#BLOCK"+id).fadeOut().remove();
								}
					});
					$("#BLOCK"+id).remove();
		}
		
		var Numero = $("#numeroImagen").val();
		
		if (Numero!=0){
				Numero = (Numero - 1);
				$("#numeroImagen").val(Numero);
		}
}

function elimnar_youtube(id){
	var res = confirm("\xBF Desea eliminar este video ?");
		if (res){
					$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=del_video&url="+id,
								complete:function(){
									$("#url_video").val('');
									$("#add_video").attr("src","images/anadir.png");
								}
					});
					
		}
}

function elimnar_post(id){
	var res = confirm("\xBF Desea eliminar este post ?");
		if (res){
					$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=del_post&url="+id,
								complete:function(){
									$("#url_post").val('');
									$("#add_post").attr("src","images/anadir.png");
								}
					});
					
		}
}



function loadImages(){
	$.ajax({
								type   : "POST",
								url    : "ajax.php",
								data   : "act=load_image",
								success: function(msg){
										if (msg != "X999")
												$("#add").append(msg)
										}
				})
}

function isEmailAddress(correo){
		var s = correo;
		var filter=/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
		if (s.length == 0 ) return true;
		if (filter.test(s))
		return true;
			else
		return false;
}

function loadImagesIframe(url){
	//$("#loadImages").attr("src","http://picasaweb.google.com/data/feed/base/user/compartetufortuna/albumid/5383963928499493009?alt=rss&kind=photo&hl=es");
}

function fijar(msj , msj2 , CODE){
		
		if (CODE =="ES" || CODE =="Spain" || CODE =="España"){
			if (msj && msj2){
				$("#dir").html(msj);
				$("#ubicacion").val(msj);
				$("#latitudlongitud").val(msj2)
			    $("#buscador").animate({left:'758px'});
				parent.tb_remove();
			}
		}else{
			alert("Ubicaci\xF3n Invalida");
		}
}

function mapaInterno(){
			 $("#buscador").animate({left:'-1px'});
}

function compartir(tipo){
				$.ajax({
					type   : "POST",
					url    : "ajax.php",
					data   : "act=compartir&tipo="+tipo
				})
}