﻿var revealTimer = null;
var revealDelay = 200;

function sendAsyncRequest(handlerUrl, jsonData, returnFunction) {
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        url: handlerUrl,
        data: jsonData,
        dataType: "text",
        success: function(msg) {
            if (msg != null) {
                returnFunction(msg);
            }
        },
        error: function(xhr, status, error) {
            $(".fb-loader-small").hide();
            //if (xhr.responseText != "") {
                $.notifyBar({ html: xhr.responseText, delay: 4000 });
            //}
        }
    });
}

function returnCheckCountry(msg) {
    var jsonResult = jQuery.parseJSON(msg.toString());
    if (jsonResult.retcode == 100) 
    {
        $("#def-country").empty().append(jsonResult.countrycode);
        if (jsonResult.alreadylaunched == 1) {
            $(".container-middle").empty().append($("#betaInviteTemplate").tmpl(null));
            $("#container-middle-content").show("slow");
            $("#countrySelectionMenu").initCountrySelection();
            $("#inputFirstName").focus();

            if ($("#def-country").text() == "ca") {
                $("#selectedCountry").text("Canada");
                $("#pziplbl").text("Postal Code");
                $("#selected-flag").attr('src', "/images/flag_canada.png");
            }
            else if ($("#def-country").text() == "us") {
                $("#selectedCountry").text("United States");
                $("#pziplbl").text("Zip Code");
                $("#selected-flag").attr('src', "/images/flag_usa.png");
            }            
        }
        else 
        {
            if (jsonResult.acceptbeta == 1) {
                $(".container-middle").empty().append($("#betaCountrySignUp").tmpl(null));
            }
            else {
                $(".container-middle").empty().append($("#betaCountryComingSoon").tmpl(null));
            }
            $("#inputEmail").focus();
        }
        $("#country").val($("#def-country").text());
    }
    $(".container-middle").removeClass("home");
    $(".container-middle").addClass("dialog");
    $(".share-box.home").hide();
    $("#logo-img").show();
    return false;
}

function returnRegisterComing(msg) {
    var jsonResult = jQuery.parseJSON(msg.toString());
    if (jsonResult.retcode == 100) {
        $(".container-middle").empty().append($("#betaRegisterComingSuccess").tmpl(null));        
    }
    return false;
}

function returnResetReqest(msg) {
    var jsonResult = jQuery.parseJSON(msg.toString());
    if (jsonResult.retcode == 100) {
        $(".container-middle").empty().append($("#betaResetRequestSent").tmpl(jsonResult));
    }
    return false;
}

function returnResetPassword(msg) {
    var jsonResult = jQuery.parseJSON(msg.toString());
    if (jsonResult.retcode == 100) {
        $.notifyBar({ html: "Your password has been reset. Please sign in with your new password.", delay: 4000 });
        $(".container-middle").empty().append($("#betaLoginTemplate").tmpl(jsonResult));
    }
    return false;
}

function returnSingup(msg) {
    var jsonResult = jQuery.parseJSON(msg.toString());
    if (jsonResult.retcode == 100) {
        $(".container-middle").empty().append($("#betaSignupSuccess").tmpl(null));        
    }
    return false;
}

function loginClicked() {
    $(".fb-loader-small").show();
    sendAsyncRequest("services/login?req=login", $("form").serialize(), function(msg) { window.location.href = msg });    
}

function activateClicked() {
    sendAsyncRequest("services/login?req=activate", $("form").serialize(), function(msg) { window.location.href = msg });
}

function registerComingClicked() {
    if (!isValidEmailAddress($("#inputEmail").val())) {
        $.notifyBar({ html: "Please enter a valid email address.", delay: 2000 });
    }
    else {
        sendAsyncRequest("services/login?req=registercoming", $("form").serialize(), returnRegisterComing);
    }
}

function checkCountry() {
    sendAsyncRequest("services/login?req=checkcountry", "{}", returnCheckCountry);
}

function resetClicked() {
    if (($("#inputNewPassword1").val() != "") || ($("#inputNewPassword2").val() != "")) {
        if ($("#inputNewPassword1").val() != $("#inputNewPassword2").val()) {
            $.notifyBar({ html: "Passwords do not match.", delay: 3000 });
        }
        else {
            sendAsyncRequest("services/login?req=resetpassword", $("form").serialize(), returnResetPassword);
        }
    }
}

function signupClicked() {
    if (!isValidEmailAddress($("#inputEmail").val())) {
        $.notifyBar({ html: "Please enter a valid email address.", delay: 3000 });
    }
    else if (!isValidPostalCode($("#inputZipPostal").val(), $("#country").val())) {
        var strErrorMsg = "";
        if ($("#country").val() == "ca") {
            strErrorMsg = "Oops! Looks like we can't recognize the Postal code. Please enter a valid Postal code and try again.";
        }
        else if ($("#country").val() == "us") {
            strErrorMsg = "Oops! Looks like we can't recognize the Zip code. Please enter a valid Zip code (5-digit format) and try again.";
        }
        $.notifyBar({ html: strErrorMsg, delay: 5000 });
    }
    else {
        sendAsyncRequest("services/login?req=signup", $("form").serialize(), returnSingup);
    }
    return false;
}
/* Quick sanity check for email addresses */
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

/* Quick sanity check zip/postal code */
function isValidPostalCode(postalCode, countryCode) {
    switch (countryCode) {
        case "us":
            postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
            break;
        case "ca":
            postalCodeRegex = /^[a-zA-Z][0-9][a-zA-Z](-| )?[0-9][a-zA-Z][0-9]$/;
            break;
        default:
            postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;
    }
    return postalCodeRegex.test(postalCode);
}
/* Setup header/footer divs for verical liquid scale */
function setHeaderFooterSpacer() {
    var overflowH = ($(window).height() - $("#middle").height()) / 2;
    if (overflowH < 0) { overflowH = 0; }
    $("#header").height(overflowH);
    $("#footer").height(overflowH);
}

function hasFlash() {
    var bHasFlash = false;
    try {
        var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
        if (fo) bHasFlash = true;
    } catch (e) {
    if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) bHasFlash = true;
}
return bHasFlash;
}

function returnCheckUsername(msg) {
    var jsonResult = jQuery.parseJSON(msg.toString());
    if (jsonResult.taken == 1) {
        $(".username-status.taken").text(jsonResult.msg);
        $(".username-status.taken").fadeIn();
    }
    else {
        $(".username-status").hide();
    }
    return false;
}

$(document).ready(function() {
    setHeaderFooterSpacer();
    $.get('/templates/_beta.tmpl.htm', function(templates) { $('body').append(templates); });

    $("#password-reset-request-btn").live("click", (function() {
        sendAsyncRequest("services/login?req=resetreq", $("form").serialize(), returnResetReqest);
        return false;
    }));
    $("#login-to-flyerbug").live("click", (function() {
        if (($("#inputUserNameEmail").val() != "") &&
            ($("#inputPassword").val() != "")) {
            loginClicked();
        }
        return false;
    }));
    $("#activate-account").live("click", (function() {
        if (($("#inputUserName").val() != "") &&
            ($("#userPassword").val() != "")) {
            activateClicked();
        }
        return false;
    }));
    $("#register-coming-button").live("click", (function() {
        registerComingClicked();
        return false;
    }));
    $("#reset-password").live("click", (function() {
        if (($("#inputNewPassword1").val() != "") &&
            ($("#inputNewPassword2").val() != "")) {
            resetClicked();
        }
        return false;
    }));
    $("#signup-button").live("click", signupClicked);

    $("#forgot-password").live("click", (function() {
        $(".container-middle").empty().append($("#betaRequestPasswordResetTemplate").tmpl(null));
        $("#inputUserEmail").focus();
        return false;
    }));
    $("#logo-img").live("click", (function() {
        $(".link-button-no-outline").removeClass("active");
        $("#logo-img").hide();
        $(".share-box.home").show();
        $(".container-middle").empty().append($("#betaHomeTemplate").tmpl(null));
        $(".container-middle").removeClass("dialog");
        $(".container-middle").addClass("home");
        return false;
    }));

    $("#beta-login-btn, #login-again").live("click", (function() {
        window.location.href = $(this).attr("href");
        return false;
    }));
    $("#already-joined").live("click", (function() {
        $(".container-middle").empty().append($("#betaLoginTemplate").tmpl(null));
        $("#inputUserNameEmail").focus();
        return false;
    }));
    $(".privacy-btn.signup").live("click", (function() {
        $(".container-middle").empty().append($("#betaPrivacyTemplate").tmpl(null));
        $(".closeprivacy").addClass("signup");
        return false;
    }));
    $(".privacy-btn.activate").live("click", (function() {
        $(".container-middle .activate").hide();
        $(".container-middle .legal-notice").empty().append($("#betaPrivacyTemplate").tmpl(null));
        $(".container-middle .legal-notice").show();
        $(".closeprivacy").addClass("activate");
        return false;
    }));
    $(".terms-btn.activate").live("click", (function() {
        $(".container-middle .activate").hide();
        $(".container-middle .legal-notice").empty().append($("#betaTermsTemplate").tmpl(null));
        $(".container-middle .legal-notice").show();
        $(".closeprivacy").addClass("activate");
        return false;
    }));
    
    $("#signup, .closeprivacy.signup, #signuplink").live("click", (function() {
        checkCountry();
        return false;
    }));

    $(".closeprivacy.activate").live("click", (function() {
        $(".container-middle .legal-notice").empty().hide();
        $(".container-middle .activate").show();
        $("#inputUserName").focus();
        return false;
    }));

    $(".link-button-no-outline, #signuplink, .home-cmd-btn.invite").live("click", (function() {
        //$(".share-box.home").hide();
        //$("#logo-img").show();
        return false;
    }));
    $(".link-button-no-outline").live("click", (function() {
        $(".link-button-no-outline").removeClass("active");
        $(this).addClass("active");
        return false;
    }));
    $("#signuplink").live("click", (function() {
        $("#signup").addClass("active");
        return false;
    }));

    $(".watch-video").live("click", (function() {
        var bHasFlash = hasFlash();
        if (bHasFlash) {
            jQuery.facebox('', 'flyerbugvideo');
            var divHtml = $("#videoTemplate").tmpl(null);
            $(".content").empty().append(divHtml);
            return false;
        }
        else {
            window.open('http://vimeo.com/33083944');
            return false;
        }
    }));

    $(document).bind('afterClose.facebox', function() {
        $(".video-container").remove();
    });

    $("#inputPassword").live("keypress", (function(e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            e.preventDefault();
            loginClicked();
        }
    }));
    $(".retrieve-email").live("keypress", (function(e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            e.preventDefault();
            $("#password-reset-request-btn").click();
        }
    }));
    $(".register-email").live("keypress", (function(e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            e.preventDefault();
            $("#register-coming-button").click();
        }
    }));
    $("#inputZipPostal").live("keypress", (function(e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            e.preventDefault();
            $("#signup-button").click();
        }
    }));
    $("#inputNewPassword2").live("keypress", (function(e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            e.preventDefault();
            $("#reset-password").click();
        }
    }));
    $("#userPassword").live("keypress", (function(e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            e.preventDefault();
            $("#activate-account").click();
        }
    }));

    $("#inputUserName").live("keyup", (function() {
        sendAsyncRequest("/services/settings/checkusername", $("form").serialize(), returnCheckUsername);
        return false;
    }));        
    
    $(".hotspot").live({
        mouseenter: function() {
            $(this).addClass("hotspot-outline");
            $(".callout-container").hide();
            var $calloutDiv = null;
            if ($(this).hasClass("mobile")) {
                var iWindowWidth = $(window).width();
                var iFixedContainerWidth = $(this).parent().outerWidth({ 'margin': true });
                if (iWindowWidth > iFixedContainerWidth + 115) {
                    $calloutDiv = $(this).find(".callout-container.mobile-1");
                }
                else {
                    $calloutDiv = $(this).find(".callout-container.mobile-2");
                }
            }
            else {
                $calloutDiv = $(this).find(".callout-container");
            }
            if (revealTimer) {
                clearTimeout(revealTimer);
            }
            revealTimer = setTimeout(function() {
                $calloutDiv.fadeIn("fast");
            }, revealDelay);
        },
        mouseleave: function() {
            $(this).removeClass("hotspot-outline");
            $(this).find(".callout-container").fadeOut("fast");
            if (revealTimer) {
                clearTimeout(revealTimer);
            }
        }
    });
})

$.fn.initCountrySelection = function() {
    return this.each(function() {
        var C = $(this);
        var B = $("#cSelect");
        B.click(function(D) {
            var Padding = $("#middle").offset();
            var E = B.offset();            
            C.css({ top: E.top-Padding.top + 15, left: 155 })
            C.toggle();
            return false;
        });
        $(document).click(function() { C.hide(); });
        C.find("li").click(function() {
            if ($(this).attr("id") == "ca") {
                $("#selectedCountry").text("Canada");
                $("#pziplbl").text("Postal Code");
                $("#selected-flag").attr('src', "/images/flag_canada.png");
            }
            else {
                $("#selectedCountry").text("United States");
                $("#pziplbl").text("Zip Code");
                $("#selected-flag").attr('src', "/images/flag_usa.png");
            }
            $("#country").val($(this).attr("id"));
        })
    })
}

/* Setup header/footer heights */
$(window).resize(setHeaderFooterSpacer);

