﻿// Check user cookie to see if user is logged in
// TO DO: Actually check cookie instead of an interface item
function isLoggedIn() {
    if ($('#myMetroBtn').is(":visible")) { return true }
    else { return false }
}

//Save a listing
function saveListing(listingGroupID, clientid) {
    if (isLoggedIn()) {
        var url = '/my-metro/saved-property/add/' + listingGroupID;
        $.get(url, function(data) {
            if (data == 'SUCCESS') {
                $('#' + clientid).addClass('btn-saved-listing').removeClass('btn-save-listing');
            }
        });
    } else {
        $('.must-log-in').show()
        $('#redirect-after-login').val('') //do not redirect after login

        $().bind('cbox_closed', function(){
            $().unbind('cbox_closed');
            //alert('cbox_closed');
            var url = '/my-metro/saved-property/add/' + listingGroupID;
            $.get(url, function(data) {
            //alert('return from ss');
            if (data == 'SUCCESS') {
                //alert('ss sucess');
                    $('#' + clientid).addClass('btn-saved-listing').removeClass('btn-save-listing');
                    $('.must-log-in').hide()
                }
            });
        })
        $.fn.colorbox( { 
            inline: true, 
            opacity:0.3, 
            href: "#login-div", 
            transition: "none", 
            open: true, 
            scrolling: false
        });
        //alert('end ss');
    }
}

//Save a search
function saveSearch(listingSearchID, clientid) {
    if (isLoggedIn()) {
        var url = '/my-metro/saved-search/add/' + listingSearchID;
        $.get(url, function(data) {
            if (data == 'SUCCESS') {
                $('#' + clientid).addClass('btn-savedSearch').removeClass('btn-saveSearch');
            }
        });
    } else {
        $('.must-log-in').show()
        $('#redirect-after-login').val('') //do not redirect after login
        $().bind('cbox_closed', function(){
            $().unbind('cbox_closed');
            var url = '/my-metro/saved-search/add/' + listingSearchID;
            $.get(url, function(data) {
                if (data == 'SUCCESS') {
                    $('#' + clientid).addClass('btn-savedSearch').removeClass('btn-saveSearch');
                    $('.must-log-in').hide()
                }
            });
        })
        $.fn.colorbox( { 
            inline: true, 
            opacity:0.3, 
            href: "#login-div", 
            transition: "none", 
            open: true, 
            scrolling: 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);
    }
}

//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();
                    $('#accountBtn').hide();
                    $('#myMetroBtn').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':
                    //alert($('#redirect-after-login').val());
                    $.cookie("MyMetroLoginLastEmail", $('#reg-email').val(), { expires: 30 });
                    if ($('#redirect-after-login').val() != '') {
                        window.location = $('#redirect-after-login').val(); //default is to mymetro page
                    }
                    else {
                        $.fn.colorbox.close();
                        $('#accountBtn').hide();
                        $('#myMetroBtn').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') {
                $('#accountBtn').show();
                $('#myMetroBtn').hide();
            }
        });
    });
    $('#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;
        }
    });
}