/*Modificado por djmourino archivo mod_registro.php , script.js y votar.php*/
function error_html(msg,aFieldName){
	$("form.fformulario_registro #form_alert_"+aFieldName+"_msg").remove();
	$("form.fformulario_registro #"+aFieldName).after('<div id="form_alert_'+aFieldName+'_msg" class="error">'+msg+'</div>');	
}
	
function limpiar(aFieldName){
	$("form.fformulario_registro #form_alert_"+aFieldName+"_msg").remove();
	$("form.fformulario_registro #"+aFieldName).after('<div id="form_alert_'+aFieldName+'_msg" class="success">Correcto!!</div>');	
}

$(document).ready(function(){
	// Executed once all the page elements are loaded
	$("#enviarp").click(function(evento){
		evento.preventDefault();
		var str = $("form").serialize();
  
		$("#formenvio").fadeOut(600);
		$("#formenvio").html("</br></br></br></br>Editando perfil....."); 
		$("#formenvio").fadeIn(600);
	  
		$.ajax({
			type: "POST",
			url: "../votar.php?perfil",
			data: str , 
			/* Sending both the text and the parent of the comment */
			success: function(msg){
				/* PHP returns the automatically assigned ID of the new comment */
				$("#formenvio").fadeOut(600,0.1);
				$("#formenvio").html("</br></br></br></br><b>"+msg+"</b>"); 
				$("#formenvio").fadeIn(600);
			}
		});
	});

	$("form.fformulario_registro").submit(function(evento){
		evento.preventDefault();
		var error  = false;
		var formx  = this;
		var str    = $(this).serialize();
      	var filtro = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
		var c      = 0;

		if(!formx.nombre.value){
			error_html('Introduce el nombre','nombre');
			formx.nombre.focus();
			error = true;
		}else{
			limpiar('nombre');
		}
		
		if(!formx.usuario.value){
			error_html('Introduce el usuario','usuario');
			formx.usuario.focus();
			error = true;
		}else{
			limpiar('usuario');
		}
		
		if (!formx.password.value){
			error_html('Debe ingresar un password','password');
			formx.password.focus();
			error = true;
		}else
		if(formx.password.value != formx.password2.value){
			limpiar('password');
			error_html('Los dos passwords no son iguales','password2');
			formx.password.focus();
			formx.password2.focus();
			error = true;
		}else{
			limpiar('password');
			limpiar('password2');
		}
		
		if(!formx.email.value){
			error_html('Ingrese un email','email');
			formx.email.focus();
			error = true;
		}else{
			limpiar('email');
		}
		
		if(!filtro.test(formx.email.value)){
			error_html('Debe ingresar un email valido','email');
			formx.email.focus();
			error = true;
		}else{
			limpiar('email');
		}
		
		if(!formx.ocupacion.value){
			error_html('Ingrese una ocupacion','ocupacion');
			formx.ocupacion.focus();
			error = true;
		}else{
			limpiar('ocupacion');
		}
		
		if(formx.cp.value && (String(formx.cp.value) != Number(formx.cp.value) || String(formx.cp.value).length < 4)){
			error_html('Ingrese un codigo postal correcto','cp');
			formx.cp.focus();
			error = true;
		}else
		if(formx.cp.value){
			limpiar('cp');
		}else{
			$("#form_alert_cp_msg").remove();
		}
		
		if(!formx.fec_ncto.value){
			error_html('Escoja la fecha de nacimiento','fec_ncto');
			formx.fec_ncto.focus();
			error = true;
		}else{
			limpiar('fec_ncto');
		}
		
		if(!formx.sexo.value){
			error_html('Escoja el sexo','sexo');
			formx.sexo.focus();
			error = true;
		}else{
			limpiar('sexo');
		}
		
		if(!formx.sector.value){
			error_html('Escoja un sector','sector');
			formx.sector.focus();
			error = true;
		}else{
			limpiar('sector');
		}
		
		$('input.lista').each(function(i){
			if(this.checked)c++;
			this.onclick = function(){	
				if(this.checked){c++;}else{c--;}
				if(c<1){
					error_html('Escoja un interes como minimo','lista_');
					error = true;
				}else{
					limpiar('lista_');
				}
			}
			
			if(c<1){
				error_html('Escoja un interes como minimo','lista_');
				error = true;
			}else{
				limpiar('lista_');
			}
		});
		
		if(error == false){
			//alert("ok");
			$.ajax({
				type: "POST",
				url: "../votar.php?registro",
				data: str , 
				success: function(msg){
					//alert(msg);
					$("#formenvio").fadeOut(600);
					$("#formenvio").html('<b>'+msg+'</b>'); 
					$("#formenvio").fadeIn(600);
				}
			});
		}
	});	


	$("#login").click(function(evento){
		evento.preventDefault();
		var str = $("form").serialize();

      	$("#flogin").fadeOut(600);
	  	$("#flogin").html("</br></br></br></br>Comprobando usuario....."); 
	  	$("#flogin").fadeIn(600);
		
	  	$.ajax({
			type: "POST",
			url: "../votar.php?login",
			data: str , 
			/* Sending both the text and the parent of the comment */
			success: function(msg){
				/* PHP returns the automatically assigned ID of the new comment */
				$("#flogin").fadeOut(600,0.1);
	  			$("#flogin").html("</br></br></br></br><b>"+msg+"</b>"); 
	  			$("#flogin").fadeIn(600);
			}
		});
	});	
	
	$("#loginb").click(function(evento){
		evento.preventDefault();
	 	var str = $("form").serialize();

      	$("#floginb").fadeOut(600);
	  	$("#floginb").html("</br></br></br></br>Comprobando usuario....."); 
	  	$("#floginb").fadeIn(600);	
		
	  	$.ajax({
			type: "POST",
			url: "../votar.php?login",
			data: str , 
			/* Sending both the text and the parent of the comment */
			success: function(msg){
				/* PHP returns the automatically assigned ID of the new comment */
				$("#floginb").fadeOut(600,0.1);
	  			$("#floginb").html("</br></br></br></br><b>"+msg+"</b>"); 
	  			$("#floginb").fadeIn(600);
			}
		});
	});	

	$("#logout").click(function(evento){
		evento.preventDefault();

      	$("#flogin").fadeOut(600);
	  	$("#flogin").html("</br></br></br></br>Cerrando sesion....."); 
	  	$("#flogin").fadeIn(600);
	
	  	$.ajax({
			type: "POST",
			url: "../votar.php?logout",
			data: "", 
			/* Sending both the text and the parent of the comment */
			success: function(msg){
				/* PHP returns the automatically assigned ID of the new comment */
				$("#flogin").fadeOut(600,0.1);
	  			$("#flogin").html("<b>"+msg+"</b>"); 
	  			$("#flogin").fadeIn(600);
			}
		});
	});

	lastVal = totHistory;
	
	// Create the slider:
	$("#slider").slider({
		value:totHistory,
		min: 1,
		max: totHistory,
		animate: true,
		slide: function(event, ui){
			if(lastVal>ui.value)
				$(buildQ(lastVal,ui.value)).hide('fast').find('.addComment').remove();
				// Using buildQ to build the jQuery selector
				// If we are moving the slider backward, hide the previous comment
			else if(lastVal<ui.value)
				$(buildQ(lastVal,ui.value)).show('fast');
				// Otherwise show it
				lastVal = ui.value;
		}
	});
});

var totHistory = 0;
// Holds the number of comments

var positions = new Array();
var lastVal;

function addHistory(obj){
	/* Gets called on page load for each comment, and on comment submit */
	totHistory++;
	positions.push(obj.id);
}

function buildQ(from,to){
	/* Building a jQuery selector from the begin
		and end point of the slide */
	
	if(from>to){
		var tmp=to;
		to=from;
		from=tmp;
	}
	
	from++;
	to++;
	
	var query='';
	for(var i=from;i<to;i++){
		if(i!=from) query+=',';
		query+='.com-'+positions[i-1];
	}

	/* Each comment has an unique com-(Comment ID) class
		that we are using to address it */

	return query;
}

function addComment(where,parent,id){
	/*	This functions gets called from both the "Add a comment" button 
		on the bottom of the page, and the add a reply link.
		It shows the comment submition form */
		
	var $el;

	if($('.waveButton').length) return false;
	// If there already is a comment submition form
	// shown on the page, return and exit
	
	if(!where)
		$el = $('#commentArea');
	else
		$el = $(where).closest('.waveComment');

	if(!parent) parent=0;

	// If we are adding a comment, but there are hidden comments by the slider:
	
	$('.waveComment').show('slow');
	lastVal = totHistory;
	$('#slider').slider('option','value',totHistory);

	// Move the slider to the end point and show all comments
	

	var comment = '<div class="waveComment addComment">\
		\
		<div class="comment">\
			<div class="commentAvatar">\
			<img src="http://www.pagamiweb.com/usuarios/invitado.jpg" width="30" height="30" />\
			</div>\
			\
			<div class="commentText">\
			\
			<textarea class="textArea" rows="2" cols="70" name="" />\
			<div><input type="button" class="waveButton" value="Nuevo Comentario" onclick="addSubmit(this,'+parent+','+id+')" /> o <a href="" onclick="cancelAdd(this);return false">cancelar</a></div>\
			\
			</div>\
		</div>\
	\
	</div>';
	
	$el.append(comment);
	
	// Append the form
}

function cancelAdd(el)
{
	$(el).closest('.waveComment').remove();
}

function addSubmit(el,parent,id)
{
	/* Executed when clicking the submit button */
	
	var cText = $(el).closest('.commentText');
	var text = cText.find('textarea').val();
	var wC = $(el).closest('.waveComment');
	
	if(text.length<4)
	{
		alert("Su comentario e smuy corto!");
		return false;
	}
	
	$(el).parent().html('<img src="Images/ajax_load.gif" width="16" height="16" />');
	// Showing the loading gif animation
	var url=document.domain;
	// Send an AJAX request:
	$.ajax({
		type: "POST",
		url: "http://"+url+"/saveComment.php",
		data: "comment="+encodeURIComponent(text)+"&parent="+parent+"&id="+id,
		/* Sending both the text and the parent of the comment */
		success: function(msg){
			
			/* PHP returns the automatically assigned ID of the new comment */
			var ins_id = parseInt(msg);
			if(ins_id)
			{
				wC.addClass('com-'+ins_id);
				addHistory({id:ins_id});
				$('#slider').slider('option', 'max', totHistory).slider('option','value',totHistory);
				lastVal=totHistory;
			}
			
			transForm(text,cText);
			// Hiding the form and showing the comment
			
		}
	});
	
	

}



function transForm(text,cText)
{
	var tmpStr ='<span class="name">Texto pendiente de Validacion:</span> '+text;
	cText.html(tmpStr);
}
