var num=0;
$(".redondeado").corner();
$("#document").ready(function(){
$('#aniadir').bind("click",function () { aniadir(); });
$('#quitar').bind("click",function () { quitar(); });
$('#aceptar').bind("click",function () { aceptar(); });
aniadir();
aniadir();
aniadir();
var options = { 
    target:        '#tdResult', 
    url:  					"enviar.html",
    beforeSubmit:  	enviandoForm,
    success:       	respuestaRecibida
}; 
$('#frmAI').ajaxForm(options);
});
function enviandoForm(){
	$('#tdControles').hide();
	$('#tdResult').html("Enviando mensajes a los participantes");
}
function respuestaRecibida(){
}

function aniadir(){ 
	if(num==50){alert("El número máximo de amigos es 50"); return;}
	num++;
	var cadena="<tr id=\"tr"+num+"\"><td>"+num+"</td>";
	cadena+="<td><input type=\"text\" id=\""+num+"-nombre\" name=\""+num+"-nombre\" /></td>";
	cadena+="<td><input type=\"text\" id=\""+num+"-email\" name=\""+num+"-email\" /></td>";
	cadena+="<td><select id=\""+num+"-pareja\" name=\""+num+"-pareja\" >";
	cadena+="<option value=\"0\">Ninguno</option>";
	for(n=1;n<num;n++){
		cadena+="<option value=\""+n+"\">"+n+"</option>";
		$("#"+n+"-pareja").append("<option value=\""+num+"\">"+num+"</option>");
	}
	cadena+="</select></td></tr>";
	$("#tblAI tbody").append(cadena);
	$("#tblAI tbody tr:odd").css("background-color", "#dce8f1");
};

function quitar(){
	if(num==3){alert("El número mínimo de amigos es 3"); return;}
	$("#tblAI tbody tr:last").remove();
	for(n=1;n<num;n++){
		$("#"+n+"-pareja option:last").remove();
	}
	num--;
}
function aceptar(){
	error="";
	for(n=1;n<=num;n++){
		if($("#"+n+"-nombre").val()=="" || $("#"+n+"-email").val()==""){
			error+="Faltan datos por rellenar del amigo número "+n+"<br />";
			$("#tr"+n).addClass("txtrojo");
		}
		else if(!ValidarCorreo($("#"+n+"-email").val())){
			error+="El email del amigo número "+n+" no es correcto<br />";
			$("#tr"+n).addClass("txtrojo");
		}
		else{
			$("#tr"+n).removeClass("txtrojo");
		}
	}
	if(error!=""){
		$("#tdResult").html(error);
	}
	else{
		$("#frmAI").submit();
	}
}

function ValidarCorreo(email)
{ 
	var foundError = false; 
	var contador = 0; 
	var posicion = 1;
	var encontrada = false;
	var posicionpunto = 0;
	var posicionarroba = 0;
	var uno = "";
	var ultimo = 0;  
	var longitud = 0;
	var arrobaux = 0;
	var uno;
	uno = " ";
         
	sinblancos = Trim(email);   
	for (x=0 ; x < sinblancos.length ; x++) {
		uno = sinblancos.substring(x, x +1); 
		if (uno.charAt() == " ")
			foundError = true;
	}
  
	if (foundError == false && sinblancos.charAt(0) == "@" ) 
		foundError = true;              

	if (foundError == false && sinblancos.charAt(0) == "." ) 
		foundError = true;              
	
	if (foundError == false) {     
		longitud = sinblancos.length;
		if (sinblancos.charAt(longitud - 1) == ".")
			foundError = true;      
	} 
	
	if (foundError == false) {     
		longitud = sinblancos.length;
		if (sinblancos.charAt(longitud - 1) == "@")
			foundError = true;      
	} 

	if (foundError == false) {
		for (x=0 ; x < sinblancos.length ; x++) {
			uno = sinblancos.substring(x, x +1); 
			if (uno == "@")
				contador++;
		}
    
		if (contador < 1 || contador > 1 )      
			foundError = true;
	} 

	if (foundError == false) { 
		var contador=0;
		for (x=0 ; x < sinblancos.length ; x++) {
			uno = sinblancos.substring(x, x +1); 
			if (uno.charAt() == ".")
				contador = contador + 1;
   	}
		if (contador == 0)
			foundError = true;
	} 

	if (foundError == false) {
		for (x=0 ; x < sinblancos.length ; x++) {
			uno = sinblancos.substring(x, x +1); 
			if (uno.charAt() == "@"){
				encontrada = true; 
				posicionarroba = posicion;
				break; 
			}
   
			if (encontrada == false)
				posicion = posicion + 1; 
		} 
	} 
	var HayPuntoDespArroba='N';    

	if (foundError == false) {
		posicion = 1;
		uno = "";
		for (x=0 ; x < sinblancos.length ; x++) {
			uno = sinblancos.substring(x, x +1); 
			if (uno.charAt() == "."){
				posicionpunto = posicion; 
				if ((posicionpunto - 1) == posicionarroba)
					foundError = true; 
				if (posicion - 1 == ultimo)
					foundError = true; 
			} 
			posicion = posicion +1 ;
			ultimo = posicionpunto;
		}
		var buscaPunto=sinblancos.indexOf('.',posicionarroba);
		if(buscaPunto!='-1')
			HayPuntoDespArroba='S';
		if ( HayPuntoDespArroba=='N')
			foundError = true; 
	}
	if (foundError)
		return false;
	else
		return true; 
}

function Trim(str){
	return LTrim(RTrim(str));
}

function LTrim(str){
	var whitespace = new String("\t\n\r");
	var s = new String(str);
	
	if(whitespace.indexOf(s.charAt(0))!= -1){
		var j = 0,i=s.length;
		while(j<i&&whitespace.indexOf(s.charAt(j))!= -1) j++
			s = s.substring(j,i);
	}
	return s;
}

function RTrim(str){
	var whitespace = new String("\t\n\r");
	var s = new String(str);
	
	if(whitespace.indexOf(s.charAt(s.length-1))!= -1)	{	
		var i = s.length-1;
		while(i>0&&whitespace.indexOf(s.charAt(i))!=-1) i--
			 s = s.substring(0,i+1);
	}
	return s;
}
