/*
 *Copyright Last Rose Studios Inc.
 * Written on March 27th 2011
 * Version 2.0
 * Last Updated March 30th 2011
 */
(function($) {
    $.fn.ModalEmail = function(options) {
        var mask,modalform,stylesheet,tag;
        var body = $('body');
        var head = $('head');
        var rose = this;
        var settings = {
            cssstyle :   './assets/baseStyle.css',
            action:   './includes/contact.php',
            simple:   true
        }
        modalform = $('div#contact');
        mask = $('div#mask');
        var methods = {
            formOpen : function() {
                mask.show().fadeTo('', 0.7);
                modalform.fadeIn();
            },
            formClose : function() {
                modalform.add(mask).stop().fadeOut('slow');
            },
            formValidate    :   function(form){
                modalform.find('span').detach();
                var name = form.find('#name');
                var email = form.find('#email');
                var subject = form.find('#subject');
                var content = form.find('#message');
                var emailfilter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                var errors = [];
                var message = [];
                if (name.val().length < 1) {
                    errors[errors.length] = name;
                    message[message.length] = 'Nom obligatoire.';
                }
                if (!emailfilter.test(email.val())) {
                    errors[errors.length] = email;
                    message[message.length] = 'Merci de taper une adresse email valide.';
                }
                if (subject.val().length < 1) {
                    errors[errors.length] = subject;
                    message[message.length] = 'Entrez un sujet.'
                }
                if (content.val().length < 1) {
                    errors[errors.length] = content;
                    message[message.length] = 'Ecrivez votre message.'
                }
                if (errors.length > 0) {
                    modalform.find('.error').detach();
                    $.each(errors, function(index, value) {
                        alertval = message[Number(index)];
                        value.prev().prepend('<span class="error">' + alertval + '</span>');
                    });
                    return false;
                }
                return true;
            },
            formPost    : function(form){
                $.post(settings.action, form.serialize(), function(data) {
                        var lrs;
                        if (data == 'Email Sent') {
                            form.find('input[type=text],textarea').val('');
                            lrs = '<span class="success">Merci pour votre e-mail</span>';
                            modalform.add(mask).stop().delay(5000).fadeOut('slow');
                        } else {
                            lrs = '<span class="fail">Nous nous excusons mais le mail n\'a pas pu &ecirc;tre envoy&eacute;</span>';
                        }
                        form.parent().append(lrs).find('span').hide().delay(500).fadeIn('slow').delay(3000).fadeOut('slow');
                    });
                    form.find('input[type=submit]').fadeOut('fast').delay(5000).fadeIn('fast');
            },
            emailClick  : function(tag){
                email = tag.attr('title');
                person = tag.html();
                modalform.find('#to').attr('value', email);
                modalform.find('#formTitle').html('Email pour ' + person);
                methods.formOpen();
                return false;
            },
            simple      : function(){
                regex = /\b([\w\.-]+)\[at\]([\w\.-]+)\[dot\](\w{2,4})\b/g;
                replace = '<a href="mailto:$1@$2.$3" title="$1@$2.$3" class="simpleReplace">$1@$2.$3</a>'
                rose.html(rose.html().replace(regex, replace));
                tag = rose.find('.simpleReplace');
            },
            advanced    : function(tag){
                tag.each(function() {
                    text = $(this).attr('title');
                    address = $(this).html();
                    address = address.replace("[at]", "@").replace("[dot]", ".");
                    $(this).replaceWith('<a class="emailReplace" href="mailto:' + address + '" title="' + address + '">' + text + '</a>');
                });
            }
        }

        return rose.each(function() {
            if (options) {
                $.extend(settings, options);
            }
            if (settings.cssstyle) {
                if (!stylesheet && $('link[href="'+settings.cssstyle+'"]').length < 1) { //prevent adding resource twice
                    stylesheet = head.append('<link rel="stylesheet" href="' + settings.cssstyle + '">')
                }
            }
            if (!mask || mask.length < 1) { //prevent adding resource twice
                mask = $('<div id="mask"></div>').appendTo(body);
            }
            if (!modalform || modalform.length < 1) { //prevent adding resource twice
                modalform = $('\
                    <div id="contact">\
			        <p id="formTitle"></p>\
			        <div id="close">Fermer</div>\
			        <form id="contactForm" action="' + settings.action + '" method="post" name="contactForm" id="contactForm">\
                    <input name="to" id="to" type="hidden" value=""/>\
                    <label for="name">Votre Nom:</label><input id="name" name="name" type="text"/>\
                    <label for="email">Votre Email:</label><input id="email" name="email" type="text"/>\
                    <label for="subject">Sujet:</label><input id="subject" name="subject" type="text"/>\
                    <label for="message">Message:</label><textarea id="message" name="message"></textarea>\
                    <input type="submit" value="ENVOI" class="button"/>\
                    </form></div>').appendTo(body);
            }
            if (settings.simple) {
                methods.simple();
            } else {
                tag = rose.find('.emailReplace');
                //Search and replace email addresses
                methods.advanced(tag);
            }
            //On click
            tag.live('click', function() {
                return methods.emailClick($(this));
            });
            //Close Form
            modalform.find('div#close').add(mask).click(function() {
                methods.formClose();
            });

            //AJAX Validation and POST
            modalform.find('#contactForm').submit(function() {
                 if(methods.formValidate($(this))){
                     methods.formPost($(this));
                 }
                return false
            });
        });
    }
})(jQuery);
