// retrieve the sessions status from the frontio app and change the header accordlingly
$(document).ready(function(){
    var $loginCart = $("#login_cart")
    var $loginStatus = $loginCart.find(".login a");
    if (! $loginStatus.size()) {
        return;
    }

    var hostname = $loginStatus.attr("href").split("/accounts")[0];

    $.ajax({
        url: hostname + "/accounts/status",
        dataType: 'jsonp',
        success: function(json) {
            var is_in = json["logged_in"];
            if (is_in) {
                var meta = json.meta;
                //  update the login area of the header
                $loginStatus.attr({
                    "href":hostname + "/accounts/logout"
                }).text("Sign Out");

                // cycle over the session status meta data and populate/show
                // based on the keys provided in the hash
                $.each(meta, function(cls, value){
                    // if we've been sent it, show it
                    var $elem = $loginCart.find("."+cls).show(0);

                    // null value means just show, don't populate, in this case
                    if (value === null) return true;

                    // in the case of 'my account' and 'my store' we get a json
                    // with path and label keys used for updating the link
                    if (cls === "my_thing"){
                        $elem.attr("href", value.path).html(value.menu || value.label);
                        return true;
                    }

                    // we fell through so just populate as html
                    $elem.html(value);
                });
            }
        }
    });
});

