﻿// Check user cookie to see if user is logged in
// TO DO: Actually check cookie instead of the visibility of a dom object
function isLoggedIn() {
    if ($('#logout').is(":visible")) { return true }
    else { return false }
}

function showRegError(title, msg) {
    if (title == '') { title = 'Validation Error' };
    $('#reg-message').hide();    
    $('#reg-error-title').html(title);
    $('#reg-error-message').html(msg);
    $('#reg-error-wrap').show();
    $("#reg-error-wrap").fadeOut().fadeIn().animate({ opacity: 1.0 }, 1000);
}

function valid(val, txt) {
    if (val == '' || val  == txt) {
        return(false);
    } else {
        return(true);
    }
}

//Perform post-logout actions
function logout(success) {
    if (success == true) {
        $.fn.colorbox({ inline: true, opacity: 0.3, href: "/mymetro/logout/true", transition: "none", open: true, scrolling: false });
    }
    else {
        $.fn.colorbox({ inline: true, opacity: 0.3, href: "/mymetro/logout/false", transition: "none", open: true, scrolling: false });
    }
}

//Register a user
function register() {
    var f = $('#reg-first'),
        l = $('#reg-last'),
        e = $('#reg-email'),
        er = $('#reg-emailrt'),
        p = $('#reg-pword'),
        pr = $('#reg-pwordrt'),
        t = $('#reg-phone'),
        url = '/my-metro/visitor/reg/true';
    if ($('#reg-terms:checked').val() == null) {
        showRegError('', 'You must agree to the terms to continue');
        return;
    }
    if (!valid(f.val(), 'First Name')) {
        showRegError('', 'First name is required');
        return;
    }
    if (!valid(l.val(), 'Last Name')) {
        showRegError('', 'Last name is required');
        return;
    }
    if (!valid(e.val(), 'Email Address')) {
        showRegError('', 'Email address is required');
        return;
    }
    if (e.val() != er.val()) {
        showRegError('', 'The email addresses do not match');
        return;
    }
    if (!valid(p.val(), 'Password')) {
        showRegError('', 'A password is required');
        return;
    }
    if (p.val() != pr.val()) {
        showRegError('', 'The passwords do not match');
        return;
    }
    url += '/first/' + $.URLEncode(f.val())
        + '/last/' + $.URLEncode(l.val())
        + '/pass/' + $.URLEncode(p.val())
        + '/email/' + $.URLEncode(e.val());
    if (t.val() != '') {
        url += '/phone/' + $.URLEncode(t.val());
    }
    if ($('#reg-contact:checked').val() == null) {
        url += '/contact/false';
    } else {
        url += '/contact/true';
    }
    if ($('#reg-keep:checked').val() == null) {
        url += '/keep/false';
    } else {
        url += '/keep/true';
    }
    $.get(url, function(data) {
        switch (data) {
            case 'SUCCESS':
                ////$.fn.colorbox.close();
                //window.location = '/my-metro';
                //alert($('#redirect-after-login').val());
                $.cookie("MyMetroLoginLastEmail", e.val(), { expires: 30 });
                if ($('#redirect-after-login').val() != '') {
                    window.location = $('#redirect-after-login').val(); //default is to mymetro page
                }
                else {
                    $.fn.colorbox.close();
                    $('#logout').show();
                }

                break;
            default:
                showRegError('Submit Error', data);
        }
    });
}

function wireUpMyMetroEvents() {
    //Hook up events to the Login, Forgot Password, and Register forms.

    $("#login-button").click(function() {
        var uname = $.URLEncode($('#userName').val()),
            pass = $.URLEncode($('#password').val());
        if (pass == '' || uname == '') {
            $('#login-message').hide();
            $('#login-error-title').html('Validation Error');
            $('#login-error-message').html('Username and Password are required');
            $('#login-error-wrap').show();
            $("#login-error-wrap").fadeOut().fadeIn().animate({ opacity: 1.0 }, 1000);
            return false;
        }
        var url = '/my-metro/visitor/login/' + uname + '/pass/' + pass;
        $.get(url, function(data) {
            switch (data) {
                case 'SUCCESS':
                    $.cookie("MyMetroLoginLastEmail", $('#userName').val(), { expires: 30 });
                    if ($('#redirect-after-login').val() != '') {
                        window.location = $('#redirect-after-login').val(); //default is to mymetro page
                    }
                    else {
                        $.fn.colorbox.close();
                        $('#logout').show();
                    }
                    break;
                case 'FAILURE':
                    $('#login-message').hide();
                    $('#login-error-title').html('Please try again.');
                    $('#login-error-message').html('Invalid Username or Password');
                    $('#login-error-wrap').show();
                    $("#login-error-wrap").fadeOut().fadeIn().animate({ opacity: 1.0 }, 1000);
                    break;
            }
        });
    });

    $("#forgot-button").click(function() {
        //alert('forgot clicked');
        var uname = $.URLEncode($('#myMetroEmail').val());
        //alert(uname);
        if (uname == '' || uname == 'Email+Address') {
            //alert('no email entered');
            $('#lost-message').hide();
            $('#lost-error-wrap').show();
            $('#lost-error-title').html('Validation Error');
            $('#lost-error-message').html('Email Address is required');
            return false;
        }
        var url = '/my-metro/visitor/recover/' + uname;
        $.get(url, function(data) {
            switch (data) {
                case 'SUCCESS':
                    //alert('success password recovered');
                    $.fn.colorbox({ inline: true, opacity: 0.3, href: "#lost-div-success", open: true, scrolling: false });
                    $('#myMetroEmail').val($('#userName').val())
                    break;
                case 'FAILURE':
                    $('#lost-message').hide();
                    $('#lost-error-wrap').hide();
                    $('#lost-error-title').html('Please try again.');
                    $('#lost-error-message').html('Unable to locate the account for this email.');
                    $('#lost-error-wrap').show();
                    $("#lost-error-wrap").fadeOut().fadeIn().animate({ opacity: 1.0 }, 1000);
                    break;
            }
        });
    });
     
    $('#register-button').click(function() {
        register();
    });
    $('.passwordph').focus(function () {
        $(this).hide();
        $(this).next('.password').show().focus();
    });
    $('.password').blur(function() {
        if ($(this).val() == '') {
            $(this).hide();
            $(this).prev('.passwordph').show().css('color', '#FF3300');
        }
    });
    $("#logout").click(function(e) {
        e.preventDefault();
        var url = '/my-metro/visitor/logout/true';
        $.get(url, function(data) {
            if (data = 'SUCCESS') {
                $('#logout').hide();
                $.fn.colorbox({ inline: true, opacity: 0.3, href: "#logout-div", transition: "none", open: true, scrolling: false });
            }
        });
    });
    if (isLoggedIn()) {
        $('#loginAndRegister').hide();
    } else {
        $('#login').click(function(e) {
            e.preventDefault();
            $().bind('cbox_closed', function() {
                $().unbind('cbox_closed');
                window.location.reload();
            });
            $.fn.colorbox({ inline: true, opacity: 0.3, href: "#login-div", transition: "none", open: true, scrolling: false });
        });
        $('#register').click(function(e) {
            e.preventDefault();
            $().bind('cbox_closed', function() {
                $().unbind('cbox_closed');
                window.location.reload();
            });
            $.fn.colorbox({ inline: true, opacity: 0.3, href: "#register-div", transition: "none", open: true, scrolling: false });
        });
    };
    $('#login-form-switch').click(function(e) {
            e.preventDefault();
            $.fn.colorbox({ inline: true, opacity:0.3, href: "#register-div", open: true, scrolling: false});
        });
    $('#lost-form-switch-register').click(function(e) {
        e.preventDefault();
        $.fn.colorbox({ inline: true, opacity: 0.3, href: "#register-div", open: true, scrolling: false });
    }); 
    $('#register-form-switch').click(function(e) {
            e.preventDefault();
            $.fn.colorbox({ inline: true, opacity:0.3, href: "#login-div", open: true, scrolling: false});
    });
    $('#lost-form-switch').click(function(e) {
            e.preventDefault();
            $.fn.colorbox({ inline: true, opacity: 0.3, href: "#login-div", open: true, scrolling: false });
        });
    $('#lost-form-switch-recovered').click(function(e) {
        e.preventDefault();
        $.fn.colorbox({ inline: true, opacity: 0.3, href: "#login-div", open: true, scrolling: false });
    });     
    $('#lost-password').click(function(e) {
            e.preventDefault();
            $.fn.colorbox({ inline: true, opacity: 0.3, href: "#lost-div", open: true, scrolling: false });
            $('#myMetroEmail').val($('#userName').val())
            $('#lost-message').show();
            $('#lost-error-wrap').hide();
    });
    $('#login-div').keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('#login-button').click();
            return false;
        }
        else {
            return true;
        }
    });
    $('#register-div').keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('#register-button').click();
            return false;
        }
        else {
            return true;
        }
    });
    $('#lost-div').keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('#forgot-button').click();
            return false;
        }
        else {
            return true;
        }
    });
    $("a.okay-button").click(function(e) {
        e.preventDefault();
        $.fn.colorbox.close();
    });
    $('#save-search-button').click(function(e) {
        e.preventDefault();
        var updateFreq = $('#updateFreq');
        var id = updateFreq.prev('input').val();
        var freq = updateFreq.val();
        if (freq == '') {
            freq = -1;
        };
        var url = '/my-metro/saved-search/add/' + id + '/freq/' + freq;
        $.get(url, function(data) {
            if (data == 'SUCCESS') {
                $.fn.colorbox({ inline: true, opacity: 0.3, href: "#save-search-confirm", open: true, scrolling: false });
                $('#myMetro-Save').hide();
                $('#myMetro-Saved').show();
            }
        });
    });
}
