/*
 * SimpleModal Contact Form
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2009 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: referfriend.js 204 2009-06-09 22:43:28Z emartin24 $
 *
 */

$(document).ready(function () {
    $('#referfriendForm input.referfriend, #referfriendForm a.referfriend').click(function (e) {
        e.preventDefault();
        // load the referfriend form using ajax
        $.get("/refer/", function(data){
            // create a modal dialog with the data
            $(data).modal({
                closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
                position: ["15%",],
                overlayId: 'referfriend-overlay',
                containerId: 'referfriend-container',
                onOpen: referfriend.open,
                onShow: referfriend.show,
                onClose: referfriend.close
            });
        });
    });

    // preload images
    var img = ['cancel.png', 'form_bottom.gif', 'form_top.gif', 'loading.gif', 'send.png'];
    $(img).each(function () {
        var i = new Image();
        i.src = '/media/dash/img/referfriend/' + this;
    });
});

var referfriend = {
    message: null,
    open: function (dialog) {
        // add padding to the buttons in firefox/mozilla
        if ($.browser.mozilla) {
            $('#referfriend-container .referfriend-button').css({
                'padding-bottom': '2px'
            });
        }
        // input field font size
        if ($.browser.safari) {
            $('#referfriend-container .referfriend-input').css({
                'font-size': '.9em'
            });
        }

        // dynamically determine height
        var h = 390;
        if ($('#referfriend-subject').length) {
            h += 26;
        }
        if ($('#referfriend-cc').length) {
            h += 22;
        }

        var title = $('#referfriend-container .referfriend-title').html();
        $('#referfriend-container .referfriend-title').html('Loading...');
        dialog.overlay.fadeIn(200, function () {
            dialog.container.fadeIn(200, function () {
                dialog.data.fadeIn(200, function () {
                    $('#referfriend-container .referfriend-content').animate({
                        height: h
                    }, function () {
                        $('#referfriend-container .referfriend-title').html(title);
                        $('#referfriend-container form').fadeIn(200, function () {
                            $('#referfriend-container #referfriend-name').focus();

                            $('#referfriend-container .referfriend-cc').click(function () {
                                var cc = $('#referfriend-container #referfriend-cc');
                                cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
                            });

                            // fix png's for IE 6
                            if ($.browser.msie && $.browser.version < 7) {
                                $('#referfriend-container .referfriend-button').each(function () {
                                    if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
                                        var src = RegExp.$1;
                                        $(this).css({
                                            backgroundImage: 'none',
                                            filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
                                        });
                                    }
                                });
                            }
                        });
                    });
                });
            });
        });
    },
    show: function (dialog) {
        $('#referfriend-container .referfriend-send').click(function (e) {
            e.preventDefault();
            // validate form
            if (referfriend.validate()) {
                $('#referfriend-container .referfriend-message').fadeOut(function () {
                    $('#referfriend-container .referfriend-message').removeClass('referfriend-error').empty();
                });
                $('#referfriend-container .referfriend-title').html('Sending...');
                $('#referfriend-container form').fadeOut(200);
                $('#referfriend-container .referfriend-content').animate({
                    height: '80px'
                }, function () {
                    $('#referfriend-container .referfriend-loading').fadeIn(200, function () {
                        $.ajax({
                            url: '/refer/',
                            data: $('#referfriend-container form').serialize() + '&action=send',
                            type: 'post',
                            cache: false,
                            dataType: 'html',
                            complete: function (xhr) {
                                $('#referfriend-container .referfriend-loading').fadeOut(200, function () {
                                    $('#referfriend-container .referfriend-title').html('Thank you!');
                                    $('#referfriend-container .referfriend-message').html(xhr.responseText).fadeIn(200);
                                });
                            },
                            error: referfriend.error
                        });
                    });
                });
            }
            else {
                if ($('#referfriend-container .referfriend-message:visible').length > 0) {
                    var msg = $('#referfriend-container .referfriend-message div');
                    msg.fadeOut(200, function () {
                        msg.empty();
                        referfriend.showError();
                        msg.fadeIn(200);
                    });
                }
                else {
                    $('#referfriend-container .referfriend-message').animate({
                        height: '30px'
                    }, referfriend.showError);
                }
                
            }
        });
    },
    close: function (dialog) {
        $('#referfriend-container .referfriend-message').fadeOut();
        $('#referfriend-container form').fadeOut(200);
        $('#referfriend-container .referfriend-content').animate({
            height: 40
        }, function () {
            dialog.data.fadeOut(200, function () {
                dialog.container.fadeOut(200, function () {
                    dialog.overlay.fadeOut(200, function () {
                        $.modal.close();
                    });
                });
            });
        });
    },
    error: function (xhr) {
        alert(xhr.statusText);
    },
    validate: function () {
        referfriend.message = '';
        if (!$('#referfriend-container #id_users_name').val()) {
            referfriend.message += 'Name is required. ';
        }

        var email = $('#referfriend-container #id_users_email').val();
        if (!email) {
            referfriend.message += 'Your email is required. ';
        }
        else {
            if (!referfriend.validateEmail(email)) {
                referfriend.message += 'Your email is invalid. ';
            }
        }

        var email = $('#referfriend-container #id_friends_email').val();
        if (!email) {
            referfriend.message += 'Your friend\'s email is required. ';
        }
        else {
            if (!referfriend.validateEmail(email)) {
                referfriend.message += 'Your friend\'s email is invalid. ';
            }
        }

        if (!$('#referfriend-container #id_security_code').val()) {
            referfriend.message += 'Security code is required.';
        }

        if (referfriend.message.length > 0) {
            return false;
        } else {
            return true;
        }
    },
    validateEmail: function (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;
    },
    showError: function () {
        $('#referfriend-container .referfriend-message')
            .html($('<div class="referfriend-error">').append(referfriend.message))
            .fadeIn(200);
    }
};

