/*
 * Contains functionality required on landing pages (i.e. pages displayed before a user
 * has logged in).
 */

$(document).ready( function() {

    /* Attach a mix panel event on each landing page display */
    if ($("div.landing-page").length) {
        mpmetrics.track("landing_page_displayed");
    }
    if ($("div.register-user-page").length) {
        mpmetrics.track("register_user_page_displayed");
    }
    if ($("div.login-user-page").length) {
        mpmetrics.track("login_user_page_displayed");
    }
    if ($("div.about-page").length) {
        mpmetrics.track("about_page_displayed");
    }
    if ($("div.contact-page").length) {
        mpmetrics.track("contact_page_displayed");
    }
    if ($("div.privacy-policy-page").length) {
        mpmetrics.track("privacy_policy_page_displayed");
    }
    if ($("div.tos-page").length) {
        mpmetrics.track("tos_page_displayed");
    }
    if ($("div.register-success-page").length) {
        mpmetrics.track("register_success_page_displayed");
    }

    if ($("a#peek_inside_link").length) {
        $("a#peek_inside_link").click( function(e) {
            mpmetrics.track("peek_inside_clicked");
            return true;
        });
    }
    if ($("a#see_more_action_link").length) {
        $("a#see_more_action_link").click( function(e) {
            mpmetrics.track("see_more_action_clicked");
            return true;
        });
    }



    /* Fancybox for 'peek inside' image */
    if ($("a.fancybox").length != 0) {
        $("a.fancybox").fancybox();
    }

    /* Effects on hover for buttons to indicate that they are buttons */
    if ($('a.button').length != 0) {
        $('a.button').each( function() {
            $(this).hover(function() {
                $(this).css({opacity : 0.7});
            }, function() {
                $(this).css({opacity : 1});
            });
        });
    }
    
    
    /* Implement the DatePicker jQuery UI widget for the DOB field on the user
     * registration form.
     */
    if ($("input#dob").length != 0) {
        $("input#dob").datepicker({
            changeYear: true,
            changeMonth: true,
            yearRange: '1930:2000',
            dateFormat: 'dd/mm/yy',
            defaultDate: "01/01/80",
            /* Validate this control on user selection and on closing the
             * selection box */
            onSelect : function() {
            	$(this).valid();
            },
            onClose: function() {
            	$(this).valid();
            }
        });
    }


    /* Implement JS-powered login so that we can send the user's timezone to the server
     * upon login (to determine their local time).
     */
    if ($("form#login").length) {
        $("form#login").submit( function(e) {
            e.preventDefault();

            /* Clear any errors that might have been displayed */
            $("span#error-holder").html('');

            var submitAction = $("form#login").attr("action");

            /* Notify the user of the operation in progress by changing the text on the button
             * and disabling it */
            var old_text = $('form#login input[type="submit"]').attr('value');
            $('form#login input[type="submit"]').attr('value', 'Logging in...');
            $('form#login input[type="submit"]').css({
                    opacity : 0.7
            });
            $('form#login input[type="submit"]').attr('disabled', 'disabled');

            /* Get the timezone offset in hours - this is the amount of hours we need to adjust
             * user local time to get back to GMT. */
            var userTimezoneOffset = new Date().getTimezoneOffset() / 60;

            mpmetrics.track("regular_login_attempt_made", {'email_address' : $("#email_address").val()});

            var login_data = {
                email_address : $("#email_address").val(),
                password: $("#password").val(),
                time_offset : userTimezoneOffset
            };

            /* Post to the login controller */
            $.post(submitAction, login_data,
              function (data) {

                if (data.result == 'failure') {

                    /* We don't want to send the user's password to mixpanel */
                    var input_to_track = { email_address : login_data.email_address, time_offset : login_data.time_offset };
                    mpmetrics.track("regular_login_verification_failed", { 'input' : JSON.stringify(input_to_track), 'errors' : JSON.stringify(data.errors)});

                    $('form#login input[type="submit"]').attr('value', old_text);
                    $('form#login input[type="submit"]').removeAttr('disabled');
                    $('form#login input[type="submit"]').css({
                        opacity : 1
                    });

                    /* Display the errors */
                    if (data.errors != undefined && data.errors.length != 0) {
                        /* Build the HTML to insert */
                        var html = '<div class="row"><div class="error-block"><ul>';
                        for (var key in data.errors) {
                            html = html + '<li>' + data.errors[key] + '</li>';
                        }
                        html = html + '</ul></div></div>';
                        $("span#error-holder").html(html);
                    }

                    /* Scroll to the top of the page so the user is aware
                    * of the validation errors.
                    */
                    $('body').scrollTop(0);
                } else if (data.result == 'success') {
                    /* Make the call to MixPanel to log this successful login. Note the timeout-limited override below it.
                     * This is so that if for some reason the mpmetrics.track() call fails to call our callback (MixPanel is down, for example),
                     * our users are not stuck unable to log in. You'll see this mechanism used elsewhere in the JS code when we need to encapsulate
                     * a redirect inside a call to mpmetrics.track().
                     */
                    mpmetrics.track("regular_login_successful", {'email_address' : $("#email_address").val()}, function() {
                        window.location.replace(data.redirect);
                    });
                    setTimeout(function() {
                        window.location.replace(data.redirect);
                    }, 1000);
                }
            }, 'json');

        });
        
    }
    
});



