﻿/**
 * @author dgarcia
 */

var animando=false;

$(document).ready(function()
{
    ventanaPopup();
});

function ventanaPopup()
{
	$('[rel=pop]').click(function() {
		var cual= $(this).attr('id');
		muestraVentanaPop(cual,$(this));
		animando=true;
	});
}

function muestraVentanaPop(cual,donde)
{
	if (animando) { return; }
	
	link = $('[rel='+cual+'] a')[0];
	cual = $('[rel='+cual+']')[0];
	btnEnvio = $('#btnEnviarPopup');
	
	var containerPosition;
	containerPosition = $(donde).position();
	$(cual).css({
		opacity:0,
        top: containerPosition.top,
        left: containerPosition.left-100,
        display: 'block'
	});
	$(cual).animate({
	    opacity: 1,
	    top: '+=17'
	  }, 360, function() {
		  animando=false;
		  $(link).click(function() {
				ocultaVentanaPop(cual);
				animando=true;
		  });	
		  $(btnEnvio).click(function() {
		    if (isValidEmail($('#direccionPopup').val()))
		    {
		      if ($('#condicionesPopup').attr('checked'))
		      {
		        
		        var tipo = 'GET';
		        var url = '../correo.aspx';
		        var enlace = encodeURI(document.URL);
		        var direccionCorreo = $('#direccionPopup').val();
		        var tituloPagina = document.title;
		        //alert(tituloPagina);
		        var datos = "direccionPopup="+direccionCorreo+"&titulo="+tituloPagina+"&enlace="+enlace;
		        enviaDatosAjax(tipo,url,datos,cual);
		      } else {
		        alert('Debe aceptar las condiciones para poder enviar la página por correo');
		      }
		    } else {
		        alert('El E-Mail introducido no es válido');
		    }
		  });
	  });	
}

function ocultaVentanaPop(cual)
{
	if (animando) { return; }
	$(cual).animate({
		opacity: 0,
		top: '-=17'
	  }, 360, function() {
		  animando=false;
		  $(cual).css({
			  display: 'none'
		  });
	  });
}

function isValidEmail(emailAddress)
{
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}



function enviaDatosAjax(tipo,url,datos,cual)
{
    //alert(datos);
    $.ajax({
       type: tipo,
       url: url,
       data: datos,
       dataType: 'text',
       error: function() { 
        alert('Se ha producido un error y no se ha podido enviar el correo.\nDisculpe las molestias');
        ocultaVentanaPop(cual);
       },
       success: function(data) {
        alert(data);
        ocultaVentanaPop(cual);
       }
     });
}
