jQuery(function()
{

    // Validate Email
    function validaEmail(email)
    {
        var at = email.lastIndexOf("@");

        // Make sure the at (@) sybmol exists and
        // it is not the first or last character
        if (at < 1 || (at + 1) === email.length)
                return false;

        // Make sure there aren't multiple periods together
        if (/(\.{2,})/.test(email))
                return false;

        // Break up the local and domain portions
        var local = email.substring(0, at);
        var domain = email.substring(at + 1);

        // Check lengths
        if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
                return false;

        // Make sure local and domain don't start with or end with a period
        if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
                return false;

        // Check for quoted-string addresses
        // Since almost anything is allowed in a quoted-string address,
        // we're just going to let them go through
        if (!/^"(.+)"$/.test(local)) {
                // It's a dot-string address...check for valid characters
                if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
                        return false;
        }

        // Make sure domain contains only valid characters and at least one period
        if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
            return false;

        return true;
    }

    function getForm(type, e)
    {
        //

        switch(type)
        {
            case 0:
                var x = 'newsletter'
            break;
            case 1:
                var x = "newsletter-1"
            break;
        }

        console.log(x);

        jQuery.get("/web/wp-content/themes/nitro/library/js/"+x+".php", function(data)
        {
            // create a modal dialog with the data
            jQuery(data).modal({
                // opacity: 80,
                // autoPosition:true,
                // close:true,
                closeHTML: "<a href='#' title='Close' class='modal-close'><img style='background:transparent;border:0px none;' src='/web/wp-content/themes/nitro/library/img/x.png' /></a>",
                position: ["10%",],
                overlayId: 'contact-overlay',
                containerId: 'contact-container',
                onOpen: function (dialog)
                {
                    dialog.overlay.slideDown('fast', function()
                    {
                        dialog.container.fadeIn(10, function()
                        {
                            dialog.data.fadeIn(250);
                        })
                    })
                },
                onShow: function (d)
                {
                    jQuery('#contact-container .sendButton').click(function (e)
                    {
                        e.preventDefault();

                        // Remove todas as class's ERROR
                        jQuery('form#myForm .error').remove();

                        // Existem nas duas forms
                        var hasError = false,
                            ccmail = jQuery('#contact-container #contact-email').val();

                        // Para valida, tem que diferenciar a form NEWSLETTER da form SUGERE
                        switch(type)
                        {
                            case 0:
                                if(!ccmail || !validaEmail(ccmail))
                                {
                                    console.log('No email');
                                    jQuery('#contact-container #contact-email-label').html('*Email:   <span class="error"><b>Existe um erro no email.</span>');
                                    hasError = true;
                                }
                            break;
                            case 1:
                                var myEmail = jQuery('#contact-container #my-email').val(),
                                    friendsEmail = jQuery('#contact-container #friend-email').val();

                                if(!friendsEmail || !validaEmail(friendsEmail))
                                {
                                    console.log('No email');
                                    jQuery('#contact-container #contact-friend-email-label').html('*Email do amigo:   <span class="error"><b>Existe um erro no email do amigo.</span>');
                                    hasError = true;
                                }

                                if(!myEmail || !validaEmail(myEmail))
                                {
                                    console.log('No email');
                                    jQuery('#contact-container #contact-myemail-label').html('*O seu email:  <span class="error"><b>Existe um erro no email.</span>');
                                    hasError = true;
                                }

                                if(jQuery('#contact-container #contact-observations').val() == "" )
                                {
                                    console.log('No text');
                                    jQuery('#contact-container #contact-textarea-label').html('Observações::  <span class="error"><b>Não pode enviar observações vazias.</span>');
                                    hasError = true;
                                }
                            break;
                        }

                        if(!hasError)
                        {
                            console.log('hello');
                            // jQuery('#contact-container .contact-content').css('border','3px solid #fffeee');
                            jQuery('#contact-container .modal-close simplemodal-close').attr('href', ';');
                            jQuery('#contact-container ').fadeOut('slow');

                            jQuery(document.createElement('div'))
                                .addClass('adiv')
                                .html('<h2 style="color:#fff">Por favor, espere</h2>')
                                .appendTo(jQuery('body'))
                                .fadeIn('slow');

                            setTimeout(function() {
                                    $.ajax({
                                            url: '/web/wp-content/themes/nitro/library/js/'+x+'.php',
                                            data: $('#contact-container form').serialize() + '&action=send',
                                            type: 'post',
                                            cache: false,
                                            success: function(data) {
                                                if(data == 'sucess')
                                                {
                                                    jQuery('.adiv').html('<h3 style="color:#fff">Obrigado!</h3><br/><p>Obrigado pelo seu contacto!</p>');
                                                }
                                                else
                                                {
                                                    jQuery('.adiv').html('<h3 style="color:#fff">Error!</h3><br/><p>Infelizmente, ocurreu um erro!<br/>Por favor, volte a tentar</p>');
                                                }
                                            },
                                            error: function(x) { console.log("sucesso") }
                                    });
                            }, 1500);

                            clearTimeout();

                            setTimeout(function(){
                                jQuery('.adiv').fadeOut('fast').remove();
                                jQuery.modal.close();
                                // location.reload(true);
                            }, 3500);
                        }
                    });
                },
                onClose: function (dialog)
                {
                    dialog.data.fadeOut(250, function ()
                    {
                        dialog.container.fadeOut(10, function ()
                        {
                            dialog.overlay.slideUp('fast', function ()
                            {
				jQuery.modal.close();
                            });
                        });
                    });
                }
            });
        });
    }

    jQuery("a.newsletter").click(function(e)
    {
        e.preventDefault();
        getForm(0);
    });

    jQuery("a.sugere").click(function(e)
    {
        e.preventDefault();
        getForm(1);
    });
});

