/**
 * NAME: newsletter.js
 * PURPOSE: Controls the newsletter popup, handles error checking for the form
 * inside the popup, and sends validated data to the customers contactology account
 */

var Newsletter = {

    /* PROPERTIES */

    // Config settings from the HTML page the script is called from. Must be set
    // before calling init()
    config : {
        client_id : '',
        list_id : ''
    },

    overlay: Object,
    popup: Object,

    /* METHODS */

    // Constructor method. Call to enable the popup
    init : function () {
        jQuery(document).ready(function() {

            // Find out overlay and popup
            Newsletter.overlay = jQuery('#newsletter_popup_overlay');
            Newsletter.popup = jQuery('#newsletter_popup');

            Newsletter.adjust_overlay();
            Newsletter.center_popup();

            // We recenter the popup on window resize so its always center
            jQuery(window).resize(function () {
                Newsletter.center_popup();
            });
        });
    },

    // Strech the overlay to match the height and width of the document
    adjust_overlay: function() {
        Newsletter.overlay.css('width', jQuery(document).width());
        Newsletter.overlay.css('height', jQuery(document).height());
    },

    // Center the popup based on the current height and width of the browser
    // window
    center_popup : function() {

        window_height = jQuery(window).height();
        window_width = jQuery(window).width();

        popup_top_margin = (window_height/2-Newsletter.popup.height()/2 >= 0) ?
            window_height/2-Newsletter.popup.height()/2 :
            0;
        popup_left_margin = (window_width/2-Newsletter.popup.width()/2 >= 0) ?
            window_width/2-Newsletter.popup.width()/2 :
            0;

        Newsletter.popup.css('top', popup_top_margin);
        Newsletter.popup.css('left', popup_left_margin);
    },

    // Open the popup with groovy fade in animation
    open_popup : function() {

        // Capture whatever is in the newsletter sign up field in the header
        // and inject it into our email field
        jQuery('#newsletter_popup_email').val(jQuery('#newsletter_sign_up').val());

        Newsletter.popup.fadeIn('2000');
        Newsletter.overlay.fadeIn('2000');
    },

    // Open the popup with groovy fade in animation
    close_popup : function() {
        Newsletter.popup.fadeOut('2000');
        Newsletter.overlay.fadeOut('2000');
    },

    // Validates email address and sends the form data to contactology
    submit_popup_form : function () {

        // Find the email address field from our popup
        email_address = jQuery('#newsletter_popup_email').val();

        // Only continue if email address from contactology is valid
        if (!Newsletter.is_email_address_valid(email_address)) {
            jQuery('#newsletter_popup_error').html('Oops! We need a valid email address!');
            jQuery('#newsletter_popup_error').css('color', 'red');
            jQuery('#newsletter_popup_email').css('background-color', 'red')
        }
        else {
            // Find all the form fields
            form_fields = jQuery('#newsletter_popup input');

            var query_string = '';
            var checkbox_values = new Array();

            // Loop through each form field
            jQuery.each(form_fields, function() {

                // Only interested in form fields that aren't buttons
                if (jQuery(this).attr('type') != 'button') {

                    // If its a checkbox that has been checked, we push it's
                    // name into checkbox_values to be used later
                    if (jQuery(this).attr('type') == 'checkbox') {
                        if (jQuery(this).is(':checked'))
                            checkbox_values.push(jQuery(this).attr('name'));
                    }
                    // Otherwise, it's a text field and we escape and append the
                    // value onto the end of the query_string
                    else {
                            value = jQuery(this).val();
                            escaped_value = escape(value);
                            query_string += '&' + jQuery(this).attr('name') + '=' + escaped_value;
                    }
                }
            });

            // Append on the checkbox values onto query string
            query_string += '&' + 'requested_information' + '=' + escape(checkbox_values.join(', '));

            // Insert the client id and list id at the front of the query string
            id_string = '?c=' + Newsletter.config.client_id + '&lid=' + Newsletter.config.list_id;
            query_string = id_string + query_string;

            // Insert the query string into the url for contactology
            url = 'http://server1.emailcampaigns.net/autoadd/' + query_string;

            // Inject a hidden image into the popup so the query string can be
            // sent to contactology
            jQuery('#newsletter_popup').append('<img style="display: none;" src="'+url+'" />');

            // Display a success message
            jQuery('#newsletter_popup_error').html('Thank you for joining our newsletter! You should receive emails from us shortly!');
            jQuery('#newsletter_popup_error').css('color', 'red');
            jQuery('#newsletter_popup_email').css('background-color', 'white')
        }
    },

    // Validate email address using contactology standards
    is_email_address_valid : function (email) {
        var pattern = /^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._\+-])*([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/;
        return pattern.test(email);
    }
}
