﻿/* Fix for any extra console.logs so they dont break IE and Safari and Chrome */
if (typeof console == "undefined") { console = {}; }
if (typeof console.dir == "undefined") { console.dir = function() { }; }
if (typeof console.log == "undefined") { console.log = function() { }; }

/* *******************************************************
    Set up 'staga' javascript object
****************************************************** */
window.staga = function() {
    var init = true;
    return {
        debug: false || (location.hash.indexOf('debugOn') > -1),
        log: function() { if (staga.debug) { console.log.apply(this, arguments); } },
        dir: function(o) { if (staga.debug) { console.dir(o); } },
        canary: function() { return $('#canary').val(); },
        info: {
            page: { location: "" }
        },
        cookies: {
            create: function(name, value, days) {
                if (days) {
                    var date = new Date(),
                        expires = "; expires=" + date.toGMTString();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                }
                else var expires = "";
                document.cookie = name + "=" + value + expires + "; path=/";
            },

            read: function(name) {
                var nameEQ = name + "=",
                    ca = document.cookie.split(';'),
                    i, len;
                for (i = 0, len = ca.length; i < len; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                }
                return null;
            },

            erase: function(name) {
                this.create(name, "", -1);
            }
        },
        utility: {
            processSecureData: function(insecureData) {
                return eval('(' + insecureData.split('while(1);')[1] + ')');
            },
            requireLogin: function(signInCallback) {
                if (!staga.info.visitor.loggedIn) {
                    $('#loginPopup').openStagaBox({
                        css: "sbMessage",
                        title: "Sign in to The Staga Network",
                        onLoad: function() {
                            $('#cmdSignInPopup').click(function() {
                                var params = {
                                    email: $('#loginPopupEmail').val(),
                                    password: $('#loginPopupPassword').val(),
                                    rememberMe: $('#loginPopupRememberMe').val()
                                };

                                staga.UI.displayMessage({
                                    message: "Please wait while we sign you in...",
                                    title: "Signing In..."
                                });

                                $.postJSONsecure("/Ajax/Members/SignIn", params, function(data) {
                                    if (data.result == "success") {
                                        staga.utility.reloadPage();
                                    } else {
                                        staga.UI.displayError(data.message, { title: "We could not sign you in." });
                                    }
                                });
                                return false;
                            });
                            setTimeout(function() { $('#loginPopupEmail').get(0).focus(); }, 250);
                        }
                    });
                } else {
                    if (signInCallback) { signInCallback(); }
                }
            },
            reloadPage: function() {
                if (/(.*)\#+/.test(location.href)) { location.href = /(.*)\#+/.exec(location.href)[1]; }
                location.href = location.href;
            },

            lazyLoad: function(src, delay) {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = src;
                if (delay) {
                    setTimeout(function() { document.getElementsByTagName("head")[0].appendChild(script); }, delay);
                } else {
                    document.getElementsByTagName("head")[0].appendChild(script);
                }
            }
        },
        exAuth: {
            doLogin: function(provider) {
                window.location = "/exAuth/handleLoginRequest.ashx?provider=" + provider;
            },
            connectAccounts: function(provider) {
                var sbSettings = {
                    title: "Connect your accounts",
                     formatData: [provider],
                };
                staga.UI.loadTemplate('connectAccounts', { provider: provider }, sbSettings, false);
            }
        },
        URL: {
            getSiteURL: function() {
                return [window.location.protocol, "", window.location.host].join("/");
            },
            getPostURL: function() {
                return [this.getCommunityURL(), "Post", staga.info.post.PostURL].join("/");
            },
            getProfileURL: function(member) {
                return [this.getSiteURL(), "Members", member || staga.info.visitor.userName].join("/");
            },
            getCommunityURL: function() {
                return [this.getSiteURL(), "Communities", staga.info.post.CommunityURL].join("/");
            }
        },
        UI: {
            /* Temporary array for holding dynamicly loaded content*/
            ajaxControls: [],
            getViewportSize: function() {
                var w = window, d = document;
                if (typeof w.innerWidth != 'undefined') {
                    return { width: w.innerWidth, height: w.innerHeight };
                }
                else if (typeof d.documentElement != 'undefined' && typeof d.documentElement.clientWidth != 'undefined' && d.documentElement.clientWidth != 0) {
                    return { width: d.documentElement.clientWidth, height: d.documentElement.clientHeight };
                }
                return { width: d.getElementsByTagName('body')[0].clientWidth, height: d.getElementsByTagName('body')[0].clientHeight };
            },
            addAjaxBox: function(div, callback) {
                if ($('#ajaxDivs').length === 0) { $('<div id="ajaxDivs" />').appendTo('#body'); }
                $(div).appendTo('#ajaxDivs');
                if (typeof callback == 'function') { callback(); }
            },
            dimScreen: function(speed, opacity, callback) {
                $('.flash').addClass('flashHidden hidden'); $.dimScreen(speed, opacity, callback);
            },
            dimScreenStop: function() {
                $('.flashHidden').removeClass('flashHidden hidden'); $.dimScreenStop();
            },

            /* displayLoadingBox - displays a stagaBox that just says loading while an ajax request is loaded*/
            displayLoadingBox: function(cbAfterDisplayed) {
                this.displayMessage({
                    message: '<div class="loading"><img src="' + $.stagaBox.settings.loading_image + '"/></div>',
                    closeButton: false,
                    title: "<span style='text-align:center; display:block'>Loading...</span>",
                    onLoad: cbAfterDisplayed
                });
            },

            /* loadTemplate - Displays a stagaBox popup that will be loaded dynamically via Ajax */
            loadTemplate: function(control, queryParams, popupParams, skipCache) {
                this._loadTemplate(control, queryParams, function(data) {
                    popupParams.message = data;
                    staga.UI.displayMessage(popupParams);
                }, skipCache);
            },

            /* _loadTemplate- Loads the ajax control and stores it in an array for future use on this page */
            _loadTemplate: function(control, queryParams, callback, skipCache) {
                queryParams = queryParams || {};
                skipCache = skipCache || false;
                if (typeof this.ajaxControls[control] == 'undefined' || skipCache) {
                    this.displayLoadingBox(function() {
                        $.get("/Ajax/LoadTemplate/" + control, queryParams, function(data) {
                            if (!skipCache) { staga.UI.ajaxControls[control] = data; }
                            callback(data);
                        });
                    });
                } else {
                    callback(staga.UI.ajaxControls[control]);
                }
            },
            displayMessage: function(params) {
                params = params || {};
                this.dimScreen(
                    300,
                    null,
                    function() {
                        if (typeof params.message == 'string') {
                            $.stagaBox(params);
                        } else if (typeof params.message == 'function') {
                            $.stagaBox(function($) { $.stagaBox(params); });
                        }
                    }
                );
            },
            /* staga.UI.displayConfirmation("are you sure?", function(){ alert('tes')}) */
            displayConfirmation: function(message, cbYes, cbNo, params) {
                params = params || {
                    closeButton: false,
                    confirmYes: cbYes,
                    title: "Are you sure?"
                };
                message += '<div class="buttons clearfix"><button id="sb-confirm-yes" title="Yes">Yes</button></a><button id="sb-confirm-no" title="No">No</button></a></div>';

                params.onLoad = function() {
                    $('#sb-confirm-yes').click(function() {
                        if (typeof cbYes == 'function') { cbYes(); } else {
                            jQuery().closeStagaBox();
                        }
                        return false;
                    });
                    $('#sb-confirm-no').click(function() {
                        if (typeof cbNo == 'function') { cbNo(); } else {
                            jQuery().closeStagaBox();
                        }
                        return false;
                    })[0].focus();
                };

                params.message = message;
                staga.UI.displayMessage(params);
            },
            displayError: function(message, params) {
                params = params ? params : {};
                params.message = message;
                params.title = params.title || "We have encountered an error";
                params.css = params.css ? params.css : 'sbError';
                staga.UI.displayMessage(params);

            },
            /* displayAjaxStatus - Handles the display of Ajax status for any stagaBox popup messages*/
            displayAjaxStatus: function(message, e, cssClass) {
                var x = $(e).removeAttr('class').addClass('ajaxResponse').addClass(cssClass).html(message);

            },
            /* displayAjaxBusy - Displays Ajax Status controls for StagaBox popups */
            displayAjaxBusy: function(message) {
                message = message || "Please wait...";
                var workingMsg = "<div class='ajax-working'><h4>{0}</h4><span class='barber'></span></div>";
                workingMsg = workingMsg.format(message);
                staga.UI.displayMessage({
                    message: workingMsg,
                    title: 'Please Wait...',
                    closeButton: false
                });
            },
            /* displayAjaxError - Displays Ajax Error Message for StagaBox popups */
            displayAjaxError: function(stagaBox, message) {
                $(".memberInput", stagaBox).slideUp();
                staga.UI.displayAjaxStatus(message, $(".ajaxResponse", stagaBox), "error");
            },
            hideAjaxStatus: function(e) {
                $(e).slideUp().removeAttr('class').html('');
            },
            setupHovering: function(el) {
                /* setup item hovering and action items */
                var hover = "list-item-hover";
                $el = $(el) || $('body');

                $el.find(".list-item").hover(function() {
                    $(this).addClass(hover);
                }, function() {
                    $(this).removeClass(hover);
                }).click(function() {
                    var action = $(this).find('a.item-action:eq(0)');
                    if (action.length !== 0) {
                        location.href = action[0].href;
                    }
                });
            },
            stagaBoxDefaults: {
                message: "(No message)",
                cssClass: "stagaBox",
                css: "sbMessage",
                title: "Staga Network Message",
                onLoad: null,
                onClose: null,
                closeButton: true,
                height: 'auto',
                width: 'auto',
                imageBox: false,
                imageIndex: null,
                keepCentered: true
            }
        }
    };
} ();

/* *******************************************************
    jQuery Plugins - Public
 ****************************************************** */
 
// postJson
$.postJSON = function(url, params, callback) {
    $.post(url, params, callback, "json");
};

$.postJSONsecure = function(url, params, callback) {
    params.canary = staga.canary();
    params.tzOffset = new Date().getTimezoneOffset() / 60;
    $.post(url, params, function(data) {
        if (typeof callback == 'function') {
            callback(staga.utility.processSecureData(data));
        }
    });
};

$.getJSONsecure = function(url, params, callback) {
    params.canary = staga.canary();
    if ((typeof params == 'function') && (typeof callback == 'undefined')) {
        callback = params;
        params = null;
    }
    $.get(url, params, function(data) {
        if (typeof callback == 'function') {
            callback(staga.utility.processSecureData(data));
        }
    });
};


jQuery.fn.extend({
    // enable and disable elements
    enable: function() {
        return this.each(function() {
            $(this).removeAttr('disabled').removeClass('disabled');
        });
    },
    disable: function() {
        return this.each(function() {
            $(this).attr('disabled', 'disabled').addClass('disabled');
        });
    },
    getElementPath: function() {
        var $this = $(this),
            el = $this,
            classes = '';
        try {
            while (el.parent()[0].id == "") {
                el = el.parent();
                if (el.attr('class') != '') {
                    classes += ' ' + el[0].tagName.toLowerCase() + '.' + el.attr('class').split(' ').join('.');
                }
            }

            return "#" + el.parent()[0].id + classes + ' ' + el[0].tagName.toLowerCase() + '.' + $this.attr('class').split(' ').join('.');
        } catch (ex) { }
    },
    // Ajax hash \ containers loader thingy
    ajaxContainer: function(triggerClass, callback) {
        // check location first
        var loc = location.href.split("#"),
            path = $(this).getElementPath();

        if (loc.length > 1) {
            var ajaxLoc = loc[1]
            $(this).empty().load(ajaxLoc + " " + path, callback)
        }

        $(this).live("click", function(e) {
            var $link = $(e.target);
            if ($link.hasClass(triggerClass)) {
                var linkHref = $link.attr('href'),
                    loc = location.href.split("#")[0],
                    windowLocation = loc + "#" + linkHref;

                location.href = windowLocation;
                $(this).empty().scrollTo().load(linkHref + " " + path, callback)
                return false;
            }
        });
    },
    // Get item guid from element ID
    getItemGUID: function(itemType) {
        var re = new RegExp(itemType + "-item-(.*)", "ig");
        return re.exec(this[0].id)[1];
    },
    // ScrollTo
    scrollTo: function(speed, easing) {
        return this.each(function() {
            var targetOffset = $(this).offset().top;
            $('html,body').animate({
                scrollTop: targetOffset - 20
            },
            speed, easing);
        });
    }
});


// dimScreen - http://docs.jquery.com/Plugins/dimScreen - **modified a bit**
jQuery.extend({
    //dims the screen
    dimScreen: function(speed, opacity, callback) {
        if (typeof speed == 'function') {
            callback = speed;
            speed = null;
        }

        if (typeof opacity == 'function') {
            callback = opacity;
            opacity = null;
        }

        if (speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder;
        }

        if (opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder;
        }

        if (jQuery('#__dimScreen').size() > 0) {
            if (typeof callback == 'function') {callback();}
            return;
        }
        speed = (speed > 0) ? speed : 500;
        opacity = (opacity > 0) ? opacity : 0.5;
        return jQuery('<div></div>').attr({
            id: '__dimScreen',
            fade_opacity: opacity,
            speed: speed
        }).css({
            background: '#000',
            height: $(document).height(),
            left: '0px',
            opacity: 0,
            position: 'absolute',
            top: '0px',
            width: '100%',
            zIndex: 999
        }).appendTo(document.body).fadeTo(speed, opacity, callback);
    },

    //stops current dimming of the screen
    dimScreenStop: function(callback) {
        var x = jQuery('#__dimScreen'),
            opacity = x.attr('fade_opacity'),
            speed = x.attr('speed');
            
        x.fadeOut(speed, function() {
            x.remove();
            if (typeof callback == 'function') {callback();}
        });
    }
});

/* *******************************************************
    jQuery Plugins - Bryan Migliorisi
 ****************************************************** */
// Star Ratings
jQuery.fn.ratingSetup = function(Stars) {
    return this.each(function() {
        for (i = 0; i < Stars; i++) {$('<span class="starOff"></span>').appendTo(this);}
        $('span', this).hover(
            function() {
                $(this).removeClass('starOff').addClass('starOn').prevAll().removeClass('starOff').addClass('starOn');
                $('.starSelected').removeClass('starSelected').addClass('starSelectedOff');
            },
            function() {
                $(this).removeClass('starOn').addClass('starOff').prevAll().removeClass('starOn').addClass('starOff');
                $('.starSelectedOff').removeClass('starSelectedOff').addClass('starSelected');
            }
        ).click(function() {
            $('.starSelectedOff').removeClass('starSelectedOff');
            $(this).siblings().removeClass('starSelected').end().addClass('starSelected').prevAll().addClass('starSelected');
        });
        $(this).addClass('ratingStar');
    });
};

jQuery.fn.ratingGet = function() {
    return ($('.starSelected', this).length);
};
jQuery.fn.ratingSet = function(rating) {
    return this.each(function() {
        $('span:lt(' + rating + ')', this).addClass('starSelected').removeClass('starOff');
    });
};

// This plugin is designed to translate the data attribute into JSON data
jQuery.fn.parseData = function(rating) {
    return this.each(function() {
        try {
            eval("this.dataJson = {" + $(this).attr('data') + "}");
        } catch (ex) {
            // do nothing
        }
    });
};


jQuery.fn.setupForm = function() {
    return this.each(function() {
        /* setup active LIs */
        $(this).find('input, textarea, select').focus(function() {
            $(this).parents('li').addClass('active').siblings('li').removeClass('active');
        })[0].focus();
    });
};

// String prototype to do formatting similar to C#
String.prototype.format = function() {
    var str = this, i, j, arg = arguments, re;
    if (arg.length === 0) { return str; }
    for (i = 0, j = arg.length; i < j; i++) {
        re = new RegExp("\\{" + i + "\\}", "ig");
        str = str.replace(re, arg[i]);
    }
    return str;
};

/* *******************************************************
    Staga AJAX Common Functions
 ****************************************************** */
function processAjaxResult(ajax) {
    if (typeof ajax.redirectURL !== 'undefined') {
        if (ajax.redirectURL === "this") { location.href = location.href; return; }
        if (ajax.redirectURL !== "") { location.href = ajax.redirectURL; return; }
    }
    if ((ajax.innerhtml !== "") && (ajax.targetelement !== "")) { $(ajax.targetelement).html(ajax.innerhtml);}
}


function displayAjaxError(message, $e) {
    // this function expects to find a span.ajaxError sibling to $e
    $e.siblings("span.ajaxError").html(message);
    // lets add a few lines to detect if this span exists and if not, show a modal box instead
}

/* *******************************************************
    Set up signin & register actions
 ****************************************************** */
function setupHomepage() {
    $("#what-staga-can-do ul a").click(function() {
        var my = $(this);
        $('#popup-' + my.parent().parent().attr('id')).openStagaBox(
            {
                title: my.attr('title'),
                height: 350,
                width: 600,
                css: "home-popup"
            }
        );
        return false;
    });

    $("#catch-phrase").hover(
        function() { $(this).addClass('hover'); },
        function() { $(this).removeClass('hover'); }
    ).click(
        function() { location.href = "/Register"; }
    );
}
function setupHomepage2() {
    var selected = "selected"
    $("#header-titles li a").mouseover(function() {
        $(this).animate({ opacity: 0 }, 500)
    }).mouseout(function() {
    if ($(this).hasClass(selected)) return;
        $(this).animate({ opacity: 1 }, 500)
    })

    function slidePane(newLeft) {
        $("#info-panes-container").animate({
            left: newLeft
        }, 500);
    }
    function animateThis(e) {
        $(e).animate({ opacity: 0 }, 500).addClass(selected)[0].blur();
    }
    
    function restoreLinks() {
        $("#header-titles .selected").removeClass(selected).animate({ opacity: 1 }, 350)
    }
    $("#learn-what a").click(function() {
        restoreLinks();
        slidePane("0px");
        animateThis(this);
        return false;
    })
    $("#learn-why a").click(function() {
        restoreLinks();
        slidePane("-610px");
        animateThis(this);
        return false;
    })
    $("#learn-how a").click(function() {
        restoreLinks();
        slidePane("-1220px");
        animateThis(this);
        return false;
    });
}



/* *******************************************************
    Set up My Staga Profile
 ****************************************************** */
function setupMyNotifications() {
    
}
function setupMyContact() {
    $("#sb-save-changes").click(function() {
        $.postJSONsecure(
            "/Ajax/MyStaga/SaveContact",
            {
                firstName: $("#txt-first-name").val(),
                lastName: $("#txt-last-name").val(),
                email: $("#txt-email").val(),
                zipcode: $("#txt-zipcode").val()
            },
            function(data) {
                if (data.result == "success") {
                    staga.UI.displayMessage({ message: data.message });
                } else {
                    staga.UI.displayError(data.message);
                }
            }
        );
        return false;
    });
}


function setupMyPassword() {
    $("#sb-save-changes").click(function() {
        $.postJSONsecure(
            "/Ajax/MyStaga/SavePassword",
            {
                oldPassword: $("#txt-current-password").val(),
                password1: $("#txt-new-password1").val(),
                password2: $("#txt-new-password2").val()
            },
            function(data) {
                if (data.result == "success") {
                    staga.UI.displayMessage({ message: data.message });
                } else {
                    staga.UI.displayError(data.message);
                }
            }
        );
        return false;
    });
}

function setupMyStagaProfile() {
    $("#sb-save-changes").click(function() {
        $.postJSONsecure(
            "/Ajax/MyStaga/SaveProfile",
            { aboutMe: $("#txt-profile-about-me").val() },
            function(data) {
                staga.UI.displayMessage({ message: "Your profile has been updated." });
            }
        );
        return false;
    });
}

function setupMyStagaCommunities() {

    /* leave community */
    $('a.remove').click(function() {
        var communityURL = this.id.split("leaveCommunity_")[1],
            message = "Are you sure you want to leave this Community?";

        staga.UI.displayConfirmation(
            message,
            function() {
                staga.UI.displayAjaxBusy("Leaving Group.  Please wait.");
                var params = {
                    communityURL: communityURL
                };

                $.postJSONsecure("/Ajax/Communities/Leave", params, function(data) {
                    if (data.result == "success") {
                        setTimeout(function() { $(this).closeStagaBox(); staga.utility.reloadPage(); }, 3000);
                    } else {
                        staga.UI.displayMessage("Failed!");
                    }
                });
            }
        );
        return false;
    });
}

function setupMyStagaPosts() {

}

function setupMyStagaMessages() {
    
    $("a.remove").click(function() {
        var $this = $(this).parents('.message-item'),
            guid = $this.getItemGUID("message");
            
        staga.UI.displayConfirmation(
            "Are you sure you want to delete this message?",
            function() {
                $.postJSONsecure("/Ajax/Messages/Delete", { guid: guid }, function(data) {
                    if (data.result == "success") {
                        $().closeStagaBox();
                        $this.fadeOut();
                    } else {
                        staga.UI.displayError(data.message);
                    }
                });
            }
        );
        return false;
    });
}

function setupMyStagaViewMessage() {
    $("#sb-delete-message").click(function() {
        staga.UI.displayConfirmation(
            "Are you sure you want to delete this message?",
            function() {
                $.postJSONsecure("/Ajax/Messages/Delete", { guid: staga.info.message.messageGUID }, function(data) {
                    if (data.result == "success") {
                        location.href = "/MyStaga/Messages";
                    } else {
                        staga.UI.displayError(data.message);
                    }
                });
            }
        );
        return false;
    });

    $("#sb-reply-message").click(function() {
        $("#message-reply").find('textarea').val('').end().slideDown();
        return false;
    });

    $("#sb-send-reply").click(function() {
        var subject = staga.info.message.subject,
            body = $("#message-reply-body").val(),
            replyParams;

        if (body === "") {
            staga.UI.displayError("Your message appears to be empty!");
            return false;
        }

        replyParams = {
            body: body,
            guid: staga.info.message.messageGUID
        };

        $.postJSONsecure("/Ajax/Messages/Reply", replyParams, function(data) {
            if (data.result == "success") {
                location.href = "/MyStaga/Messages";
            } else {
                staga.UI.displayError(data.message);
            }
        });

        return false;
    });

    $("#sb-cancel-reply").click(function() {
        $("#message-reply").slideUp();
        return false;
    });
}

/* *******************************************************
    Set up registration & registration actions
 ****************************************************** */
function setupRegister() {

    /* setup active LIs */
    $('#register').setupForm();
        
    /* auto update of the member url */
    var updateMember = function(s) {
        $("#member-url").html(staga.URL.getProfileURL(s));
    };
    var $userName = $("#txtUserName");
    $userName.keyup(function() {
        updateMember($(this).val());
    }).change(function() {
        updateMember($(this).val());
    });
    updateMember($userName.val());
}

/* *******************************************************
    Set up browse & browse actions
 ****************************************************** */
function setupCommunityBrowse() {
    $('#cmd-join-community').click(function() {
        staga.UI.displayConfirmation(
            "Would you like to join this Community?",
            function() {
                var url = '/Ajax/Communities/Join',
                    params = { community: staga.info.community.URL };
                    
                $.postJSONsecure(url, params, function(data) {
                    if (data.result == "success") {
                        staga.UI.displayMessage({
                            message: data.message,
                            title: "Thanks!",
                            onLoad: function() {
                                $('#join-community').slideUp(500);
                            }
                        });
                    } else {
                        staga.UI.displayError(data.message);
                    }
                });
            }, null, { title: "Join Community?" }
        );
        return false;
    });

    $('a.hide').click(function() {
        $('#join-community').slideUp(500);
        return false;
    });
}

/* *******************************************************
    Community Locator
 ****************************************************** */
function setupCommunityLocator() {
    $('#txtZipcode').keypress(function(e) {
        if (e.which == 13) { $('#sb-locate-community').click(); return false; }
    });


    $('#sb-locate-community').click(function() {
        var re = /\d{5}/,
            $zipcode = $('#txtZipcode'),
            $distance = $('#selDistance');
            
        if ((re.test($zipcode.val()) && $zipcode.val().length == 5)) {
            location.href = "/Communities/Locate/" + $zipcode.val() + "/" + $distance.val();
        } else {
            displayAjaxError("Please enter a valid ZipCode", $(this));
        }
        return false;
    });

    var selector = "#community-list .right";
    $(selector).ajaxContainer("ajax-load", function() { staga.UI.setupHovering(this); });

}

/* *******************************************************
    Setup New Post
 ****************************************************** */
function setupNewPost() {
    $(".post-gallery").click(function(e) {
        if ($(e.target).hasClass('post-image-remove')) {
            var $parent = $(e.target).parents('.post-gallery-item'),
                guid = $parent.getItemGUID('post-gallery');
                
            $.postJSONsecure("/Ajax/Media/Delete", { guid: guid }, function(data) {
            if (data.result == "success") {
                    $parent.animate({ opacity: 0 }, 500, function() { $(this).remove() ;});
                }
            });
            $('a.post-image-enlarge').loadImageBox(true);
            return false;
        }
    });
}


/* *******************************************************
Setup View Post Interests
****************************************************** */
function setupViewPostInterests() {
    findInterestedMember = function(guid) {
        var i, len, items = staga.info.postInterests;
        for (i = 0, len = items.length; i < len; i++) {
            if (items[i].interestedGUID === guid) {
                return items[i];
            }
        }
    };

    $('.interested-member-item li.flag a').click(function() {
        var guid = $(this).parents('.interested-member-item').getItemGUID("interested-member");
        staga.UI.displayMessage({ message: 'Flagging ' + guid });
        return false;
    });

    $('.interested-member-item li.give a').click(function() {
        var guid = $(this).parents('.interested-member-item').getItemGUID("interested-member"),
            message = findInterestedMember(guid);

        staga.UI.loadTemplate(
            "giveItemAway",
            {},
            {
                formatData: [message.authorFirstName, guid],
                title: "Give Item Away"
            }
        );
        return false;
    });
}


/* *******************************************************
    Setup Post View
 ****************************************************** */
function setupViewPost() {
    var UI = staga.UI,
        info = staga.info;
        
    $("#txt-comment-body").click(function() {
        staga.utility.requireLogin();
    });
    $("#sb-post-comment").click(function() {

        var $this = $(this),
            params = {
                body: $("#txt-comment-body").val(),
                guid: staga.info.post.PostGUID
            };
            
        staga.utility.requireLogin(function() {
            $this.disable();
            $.postJSONsecure('/Ajax/Comments/SavePostComment', params, function(data) {
                if (data.result == "success") {
                    $(data.innerHTML).hide().prependTo("#post-comments .inner").slideDown();
                    $("#txt-comment-body").val('');

                    staga.facebookConnect.events.addPostComment(
                        $('#fbPostComment'),
                        staga.URL.getPostURL(),
                        params.body
                    );
                    $this.enable();
                } else {
                    UI.displayError(data.message);
                    $this.enable();
                }
            });
        });
        return false;
    });

    $('#txtPostReply').focus(function() {
        if (!staga.info.visitor.loggedIn) {
            staga.utility.requireLogin();
        }
    });
    $('#members-interested').click(function() {
        location.href = [staga.URL.getPostURL(), "Interested-Members"].join("/");
    });

    //check for do_facebook_connect cookie
    
    if (info.post.AuthorUserName == info.visitor.userName) {
        var fbc = "do_fbc_new_post",
        cookie = staga.cookies.read(fbc);
        if (cookie != null & cookie == "true") {
            staga.facebookConnect.events.createNewPost(info.post.Title, staga.URL.getPostURL());
            staga.cookies.erase(fbc);
        }
    }
    
    
    setupSideButtons();
}

/* *******************************************************
    Setup Member Profile View
 ****************************************************** */
function setupMemberProfile() {
    $("#txt-comment-body").click(function() {
        staga.utility.requireLogin();
    });

    $("#sb-post-comment").click(function() {
        var $this = $(this),
            params = {
                body: $("#txt-comment-body").val(),
                member: staga.info.member.userName
            };

        staga.utility.requireLogin(function() {
            $this.disable();
            $.postJSONsecure('/Ajax/Comments/SaveMemberComment', params, function(data) {
                if (data.result == "success") {
                    $(data.innerHTML).hide().prependTo("#member-comments .inner").slideDown();
                    $("#txt-comment-body").val('');

                    staga.facebookConnect.events.addProfileComment(
                        $('#fbProfileComment'),
                        staga.info.member.firstName,
                        staga.URL.getProfileURL(staga.info.member.userName),
                        params.body
                    );
                    $this.enable();
                } else {
                    staga.UI.displayError(data.message);
                    $this.enable();
                }
            });
        });
        return false;
    });

    setupSideButtons();
}

/* *******************************************************
    Setup Sidebuttons
 ****************************************************** */
function setupSideButtons() {
    var UI = staga.UI;
    $("#btn-invite-facebook-friends").click(function() {
        staga.utility.requireLogin(function() {
            var params = {
                title: "Invite your friends from Facebook to join The Staga Network!"
            };
            switch (staga.info.page.location) {
                case "posts.view":
                    params.url = staga.URL.getPostURL(),
                    params.message = staga.info.visitor.name + " thinks you might be interested in a post on The Staga Network: <br /><br />" + staga.info.post.Title;
                    break;
                case "":
                    break;
                case "":
                    break;
            }
            staga.facebookConnect.events.inviteFriends(params);
        });
        return false;
    });
    
    $("#i-want-this").click(function() {
        staga.utility.requireLogin(function() {
            UI.loadTemplate(
                "interested",
                {},
                {
                    title: "I Want This Item",
                    formatData: [staga.info.post.AuthorFirstName],
                    onLoad: function() {
                        $('#cmd-request-item').click(function() {
                            var params = {
                                guid: staga.info.post.PostGUID,
                                message: $("#txt-interested-message").val()
                            };

                            $.postJSONsecure("/Ajax/Post/Interested", params, function(data) {
                                if (data.result == "success") {
                                    UI.displayMessage({
                                        message: "We've sent your message to " + staga.info.post.AuthorFirstName,
                                        title: "Message Sent!",
                                        onLoad: function() {
                                            setTimeout(function() { $().closeStagaBox(); }, 4000);
                                        }
                                    });
                                } else {
                                    staga.UI.displayError(data.message);
                                }
                            });
                            return false;
                        });
                    }
                }
            );
        });
        return false;
    });

    $("#addFriend").click(function() {
        staga.utility.requireLogin(function() {
            staga.UI.loadTemplate(
                "AddToFriends",
                {},
                {
                    title: "Add " + staga.info.member.firstName + " to My Friends",
                    formatData: [
                        staga.info.member.firstName,
                        staga.info.member.zipCode,
                        staga.info.member.postCount,
                        staga.info.member.imagePath
                    ],
                    onLoad: function() {
                        var $sb = $("#sb-add-to-friends");
                        $('#cmd-add-to-friends', $sb).click(function() {
                            var params = {
                                userName: staga.info.member.userName,
                                message: $("#txt-add-friend-message").val()
                            };

                            UI.displayAjaxBusy("Please Wait...");

                            $.postJSONsecure("/Ajax/Friends/Add", params, function(data) {
                                if (data.result == "success") {
                                    UI.displayMessage({
                                        message: "Your friend request has been sent to " + staga.info.member.firstName + " successfully.",
                                        title: "Friend Request Sent",
                                        onLoad: function() {
                                            setTimeout(function() { $().closeStagaBox(); }, 4000);
                                        }
                                    });
                                } else {
                                    staga.UI.displayError(data.message);
                                }
                            });
                            return false;
                        });
                    }
                });
        });
        return false;
    });

    $("#rateMember").click(function() {
        staga.utility.requireLogin(function() {
            staga.UI.loadTemplate(
                "RateMember",
                {},
                {
                    title: "Rate " + staga.info.member.firstName,
                    formatData: [
                        staga.info.member.firstName
                    ],
                    onLoad: function() {
                        $('#member-stars').ratingSetup(5).click(function() {
                            $(this).parents('.memberInput').find('.my-rating').html('You have rated ' + staga.info.member.firstName + ' ' + $('#member-stars').ratingGet() + ' stars out of 5!');
                        });
                        $('#cmd-save-rating').click(function() {
                            var params = {
                                userName: staga.info.member.userName,
                                rating: $('#member-stars').ratingGet()
                            };
                            
                            $.postJSONsecure("/Ajax/Members/Rate", params, function(data) {
                                if (data.result == "success") {
                                    UI.displayMessage({
                                        message: "Thanks for rating " + staga.info.member.firstName,
                                        title: "Rate " + staga.info.member.firstName,
                                        onLoad: function() {
                                            setTimeout(function() { $().closeStagaBox(); }, 4000);
                                        }
                                    });
                                } else {
                                    staga.UI.displayError(data.message);
                                }
                            });
                            return false;
                        });

                    }
                });
        });
        return false;
    });

    $("#sendMessage").click(function() {
        staga.utility.requireLogin(function() {
            staga.UI.loadTemplate(
                "sendMessage",
                {},
                {
                    title: "Send a Message to " + staga.info.member.firstName,
                    formatData: [
                        staga.info.member.firstName
                    ],
                    onLoad: function() {
                        $("#cmd-send-message").click(function() {
                            var params = {
                                recipient: staga.info.member.userName,
                                subject: $("#txt-send-message-subject").val(),
                                body: $("#txt-send-message-body").val()
                            };
                            
                            $.postJSONsecure("/Ajax/Messages/Send", params, function(data) {
                                if (data.result == "success") {
                                    UI.displayMessage({
                                        message: "Your message has been sent to " + staga.info.member.firstName + " successfully.",
                                        title: "Message Sent Successfully",
                                        onLoad: function() {
                                            setTimeout(function() { $(this).closeStagaBox(); }, 4000);
                                        }
                                    });
                                    processAjaxResult(data);
                                } else {
                                    staga.UI.displayError(data.message);
                                }
                            });
                            return false;
                        });
                    }
                });
        });
        return false;
    });

    $("#report-post").click(function() {
        staga.utility.requireLogin(function() {
            staga.UI.loadTemplate(
                "ReportPost",
                {},
                {
                    title: "Report " + staga.info.member.firstName + "'s Post",
                    /*formatData: [ ],*/
                    onLoad: function() {
                        $('#sb-report-post #customReason').click(function() {
                            $(this).prev()[0].checked = "checked";
                        });
                        $("#cmd-send-report").click(function() {
                            var params = {
                                guid: staga.info.post.PostGUID,
                                reason: $("#sb-report-post input:checked")[0].value,
                                custom: $("#sb-report-post #customReason").val()
                            };
                            
                            $.postJSONsecure("/Ajax/Post/Report", params, function(data) {
                                if (data.result == "success") {
                                    UI.displayMessage({
                                        message: "We have received your report successfully.  Thanks for reporting this post, it helps keep the community clean and free of spam or other innapropriate posts.",
                                        title: "Report " + staga.info.member.firstName + "'s Post",
                                        onLoad: function() {
                                            setTimeout(function() { $(this).closeStagaBox(); }, 4000);
                                        }
                                    });
                                } else {
                                    staga.UI.displayError(data.message);
                                }
                            });
                            return false;
                        });
                    }
                });
        });
        return false;
    });

    $("#emailFriend").click(function() {
        staga.utility.requireLogin(function() {
            staga.UI.loadTemplate(
                "emailToFriend",
                {},
                {
                    title: "Email this Post for a Friend",
                    //formatData: [ ],
                    onLoad: function() {
                        $("#cmd-send-email").click(function() {
                            var params = {
                                guid: staga.info.post.PostGUID,
                                friendName: $("#emailToFriendName").val(),
                                friendEmail: $("#emailToFriendRecipient").val(),
                                subject: $("#emailToFriendSubject").val(),
                                body: $("#emailToFriendBody").val()
                            };
                            
                            $.postJSONsecure("/Ajax/Post/SendToFriend", params, function(data) {
                                if (data.result == "success") {
                                    UI.displayMessage({
                                        message: "We have sent an email to "+params.friendName +" successfully.",
                                        title: "Email this Post for a Friend",
                                        onLoad: function() {
                                            setTimeout(function() { $(this).closeStagaBox(); }, 4000);
                                        }
                                    });
                                } else {
                                    staga.UI.displayError(data.message);
                                }
                            });
                            return false;
                        });
                    }
                });
        });
        return false;
    });
}

/* *******************************************************
    Setup Feedback
 ****************************************************** */
function setupFeedback() {

    $("#sendFeedback a").click(function() {
        staga.UI.loadTemplate(
            "Feedback",
            {},
            {
                title: "Send Feedback",
                //formatData: [ ],
                onLoad: function() {
                    $("#cmd-send-feedback").click(function() {
                        var params = {
                            feedbackName: $("#sb-send-feedback #feedbackName").val(),
                            feedbackEmail: $("#sb-send-feedback #feedbackEmail").val(),
                            feedbackBody: $("#sb-send-feedback #feedbackBody").val()
                        };
                        $.postJSONsecure("/Ajax/Feedback/Send", params, function(data) {
                            if (data.result == "success") {
                                staga.UI.displayMessage({
                                    message: data.message,
                                    title: "Send Us Feedback!",
                                    css: 'sbMessage'
                                });
                            } else {
                                staga.UI.displayError(data.message);
                            }
                        }
                        );
                        return false;
                    });
                }
            });
        return false;
    });
}

/* *******************************************************
    Setup Join Community
 ****************************************************** */
function setupJoinCommunity() {
    $('#cmdJoinCommunity').click(function() {
        $.getJSONsecure("/Ajax/Communities/Join?community=" + $('#communityID').val(), function(data) {
            if (data.result == "success") {
                staga.UI.displayMessage({ message: data.message, title: "Join Community", css: 'sbMessage', onClose: function() { location.href = "/Communities/" + $('#communityURL').val(); } });
            } else {
                processAjaxResult(data);
                staga.UI.displayMessage({ message: data.message, title: "Join Community", css: 'sbMessage', onClose: function() { location.href = "/Communities/" + $('#communityURL').val(); } });
            }
        });
        return false;
    });
}

/* *******************************************************
    Setup Create Community
 ****************************************************** */
function setupCommunityCreate() {
    function createCommunity(zipCode, force) {
        var $status = $("#ajaxStatus").addClass("ajaxWait").html("Please Wait");
        $.postJSONsecure("/Ajax/Communities/Create", { zipcode: zipCode, force: force }, function(data) {
            $status.html("").removeClass("ajaxWait").hide();
            if (data.count > 0) {
                $("#sb-create-community, #sb-force-create-community").toggle();
                $("#foundExisting").show();
                $("#community-list").hide().html(data.innerHTML).slideDown();
                setupAllPages();
            } else {
                if (data.result == "success") {
                    processAjaxResult(data);
                } else {
                    staga.UI.displayError(data.message);
                }
            }
        });
    }

    $("#sb-create-community").click(function() {
        createCommunity($('#newCommunityZipcode').val(), false);
        return false;
    });

    $("#sb-force-create-community").click(function() {
        createCommunity($('#newCommunityZipcode').val(), true);
        return false;
    });

    $("#create-community").setupForm();
}

/* *******************************************************
    Setup Edit Post
 ****************************************************** */
function setupEditPost() {
    $("#cmdChangeExpiration").click(function() {
        $("#changeExpiration").slideDown();
        $(this).fadeOut();
        $("#isExpirationChanged").val('1');
        return false;
    });
    $("#cmdCancelChangeExpiration").click(function() {
        $("#changeExpiration").slideUp();
        $("#cmdChangeExpiration").fadeIn();
        $("#isExpirationChanged").val('0');
        return false;
    });

    $(".post-gallery").click(function(e) {
        if ($(e.target).hasClass('post-image-remove')) {
            var $parent = $(e.target).parents('.post-gallery-item'),
                guid = $parent.getItemGUID('post-gallery');

            $.postJSONsecure("/Ajax/Media/Delete", { guid: guid }, function(data) {
                if (data.result == "success") {
                    $parent.animate({ opacity: 0 }, 500, function() { $(this).remove(); });
                }
            });
            $('a.post-image-enlarge').loadImageBox(true);
            return false;
        }
    });
}

/* *******************************************************
    Setup Remove Posts Page
 ****************************************************** */
function setupRemovePost() {
    $("#cmdRemovePost").click(function() {
        staga.UI.displayAjaxStatus("Removing Post...", "#ajaxStatus", "ajaxWait");
        var postId = /[Pp]ost\/([0-9]+)\/[Rr]emove/.exec(location.href)[1];
        $.getJSONsecure("/Ajax/Post/Remove?id=" + postId, function(data) {
            if (data.result != "success") {
                staga.UI.displayAjaxStatus(data.message, "#ajaxStatus", "ajaxError");
            }
            processAjaxResult(data);
        });
        return false;
    });

    $("#cmdMarkTaken").click(function() {
        staga.UI.displayAjaxStatus("Marking Post as Taken...", "#ajaxStatus", "ajaxWait");
        var postId = /[Pp]ost\/([0-9]+)\/[Rr]emove/.exec(location.href)[1];
        $.getJSONsecure("/Ajax/Post/Taken?id=" + postId, function(data) {
            if (data.result != "success") {
                staga.UI.displayAjaxStatus(data.message, "#ajaxStatus", "ajaxError");
            }
            processAjaxResult(data);
        });
        return false;
    });

    $("#cmdCancel").click(function() {
        history.back();
        return false;
    });
}


/* *******************************************************
    Setup Plaxo Invite Friends Page
 ****************************************************** */
function setupInviteFriends() {
    $('a#cmdAddManually').click(function() {
        $('#ajaxDivs #manualPopup').openStagaBox({
            css: "sbMessage",
            title: "Invite Family & Friends",
            onLoad: function() {
                $('#stagaBox #cmdAddMore').click(function() {
                    for (var i = 0; i < 3; i++){
                        $('<tr><td><input type="text" value="" /></td><td><input type="text" value="" /></td></tr>').appendTo('#stagaBox .manualPopup tbody');
                        }
                    return false;
                });
                $('#stagaBox #cmdAddToList').click(function() {
                    var emailAddresses = [];
                    $('#stagaBox .manualPopup tr').each(function(idx, e) {
                        var i = $('input', this);
                        if ($(i[1]).val() !== "") {
                            if ($(i[0]).val() === ""){ $(i[0]).val($(i[1]).val());}
                            emailAddresses.push('"' + $(i[0]).val() + '" <' + $(i[1]).val() + '>');
                        }
                    });
                    if ($('#emailAddresses').val() === "") {
                        $('#emailAddresses').val(emailAddresses.join(","));
                    } else {
                        $('#emailAddresses').val($('#emailAddresses').val() + "," + emailAddresses.join(","));
                    }

                    onABCommComplete();
                    $(this).closeStagaBox();
                    return false;
                });

            }
        });
    });
    $('#cmdImportFriends').click(function() {
        showPlaxoABChooser('emailAddresses', '/Invite/popup.htm');
        return false;
    });
}

function removeFromList(email) {
    var updatedFriends = [],
        selectedFriends = $('#emailAddresses').val().split(',');
        
    for (i in selectedFriends) {
        if (selectedFriends[i].indexOf(email) == -1) {updatedFriends.push(selectedFriends[i]);}
    }
    $('#emailAddresses').val(updatedFriends.join(","));
}

function onABCommComplete() {
    $('#imported table tbody').empty();
    if ($('textarea#emailAddresses').val() !== "") {
        $('#noneSelected').hide();
        $('table').show();
    } else {
        $('#noneSelected').show();
        $('table').hide();
    }
    var selectedFriends = $('#emailAddresses').val().split(',');
    //var arySelectedFriends = new Array();
    for (i in selectedFriends) {
        try {
            var fi = /\"(.*)\"\s<(.*)\>/.exec(selectedFriends[i]);
            //arySelectedFriends[arySelectedFriends.length] = {name: fi[1], email: fi[2]}
            var $tr = $("<tr><td><input type='checkbox' name='select" + i + "'></td><td>" + fi[1] + "</td><td>" + fi[2] + "</td><td><a href='#' title='Remove'>Remove</a></td></tr>");
            $tr.appendTo('#imported table tbody');
        }
        catch (x) { }
    }

    $('#imported table tbody').find('tr:odd').addClass('odd').end().find('tr').hover(
        function() { $(this).addClass('hover'); },
        function() { $(this).removeClass('hover'); }
    ).click(function() {
        var x = $(this).find('input');
        x[0].checked = !x[0].checked;
    }).end().find('a').click(function() {
        removeFromList($(this).parents('tr').find('td:eq(2)').text());
        $(this).parents('tr').remove();
        if ($('#imported table tbody tr').removeClass('odd').length === 0) {
            $('#noneSelected').show();
            $('#imported table').hide();
        } else {
            $('#imported table tbody tr:odd').addClass('odd');
        }
        return false;
    });
}

/* *******************************************************
   Setup My Staga Friends Lists
 ****************************************************** */
function setupMyStagaFriends() {

    /* confirm friend request */
    $('a.confirm').click(function() {
        var guid = $(this).parents('.friend-item').getItemGUID("friend");

        $.postJSONsecure("/Ajax/Friends/Accept", { id: guid }, function(data) {
            if (data.result == "success") {
                staga.utility.reloadPage();
            }
        });

        return false;
    });
    
    /* ignore friend request */
    $('a.ignore').click(function() {
    var $this = $(this).parents('.friend-item'),
        guid = $this.getItemGUID("friend");

        $.postJSONsecure("/Ajax/Friends/Ignore", { id: guid }, function(data) {
            if (data.result == "success") {
                $this.fadeOut(500, function() {
                    $(this).remove();
                    var $friendRequestList = $("#my-friends-list-requests");
                    if ($friendRequestList.find(".friend-item").length === 0) {
                        // no requests left, remove the header
                        $friendRequestList.remove();
                    }
                });
            }
        });

        return false;
    });
    

    /* remove from friends list  */
    $('a.remove').click(function() {
        var $this = $(this).parents('.friend-item'),
            guid = $this.getItemGUID("friend"),
            message = "Are you sure you want to remove this friend?";
            
        staga.UI.displayConfirmation(
            message,
            function() {
                $.postJSONsecure("/Ajax/Friends/Remove", { id: guid }, function(data) {
                    if (data.result == "success") {
                        $().closeStagaBox();
                        $this.fadeOut();

                    } else {
                        staga.UI.displayError(data.message);
                    }
                });
            }
        );
        return false;
    });
}

/* *******************************************************
    Setup All Pages
 ****************************************************** */
function setupMyHome() {

    $(".activity-story").hover(
        function() { $(this).addClass('activity-hover'); },
        function() { $(this).removeClass('activity-hover'); }
    );

    $("#my-home .activity-story").click(function() {
        var actionItem = $(this).find(".action-item");
        if (actionItem.length > 0) {
            location.href = actionItem[0].href;
        }
    });

    $("#choose-username").click(function() {
        staga.UI.loadTemplate(
            "ChooseUsername",
            {},
            { title: "Choose a Username" }
        );
        return false;
    });

    //check for do_facebook_connect cookie
    var fbc = "do_fbc_register",
        cookie = staga.cookies.read(fbc);
        
    if (cookie != null & cookie == "true") {
        staga.facebookConnect.events.joinStagaNetwork(staga.info.visitor.name, staga.URL.getProfileURL());
        staga.cookies.erase(fbc);
    }
}

/* *******************************************************
    Setup All Pages
 ****************************************************** */
function setupAllPages() {
    /* reset ie styles */
    if ($.browser.msie) {
        $('input:radio,input:checkbox').addClass('removeInputStyle');
    }

    /* setup item hovering and action items */
    staga.UI.setupHovering();
    
    // Create action event handlers
    $("button.action").click(function() {
    var action = $(this).attr("rel");
    if (action != '') {
        $('input#formAction').attr("value", action);
        $('#aspnetForm').submit();
    }
    });
    
    // Trigger action button when enter key is pressed
    $("input.stb[onReturn]").keypress(function(e) {
        if (e && e.which) {
            characterCode = e.which;
        } else {
            characterCode = e.keyCode;
        }
        if (characterCode == 13) {
            $("#" + $(this).attr('onReturn')).trigger('click');
        }
    });

    // Setup tooltips
    $('.tooltip').click(function() {
        var $this = $(this);
        staga.UI.displayMessage({
            title: $this.text(),
            message: $this.attr('rel')
        });
        return false;
    });
    
    // show old browser message
    if ($.browser.version == '6.0' && $.browser.msie) {
        var div = "<div class='info' id='ie6' style='cursor:pointer; z-index:9999; position:fixed; left:0; margin:0; top:-10px; width:100%;'>Your browser is out of date.  Please update to a new version today.  Click here for details.</div>";
        $(div).prependTo('#wrapper').click(function() { 
            location.href = '/Resources/Upgrade_Browser';
        }).animate({ height: '20px'});
    }
    
    $('a.externalAdLink').each(function(i, e) { this.href = "/Redirect/" + this.href; }); // Add internal redirect to external ad links

    // Lazy load scripts we dont need immediately
        
}

/* *******************************************************
    Main Document actions here
 ****************************************************** */

$(function() {
    // debug only! $("*").click(function() {alert(this + "\n" + this.id + "\n" + "Class: " + $(this).attr("class")); });
    if (staga.debug) {
        $('a').click(function() { location.href = this.href + "#debugOn"; return false; });
        console.time("Staga");
        console.dir(staga);
    }

    switch (staga.info.page.location) {
        case "homepages.home_2":
            setupHomepage2();
            break;
        case "homepages.home_1":
            setupHomepage();
            break;
        case "communities.list":
            setupCommunityLocator();
            break;
        case "communities.browse":
            setupCommunityBrowse();
            setupSideButtons();
            break;
        case "communities.locate":
            setupCommunityLocator();
            break;
        case "communities.create":
            setupCommunityCreate();
            break;
        case "register.default":
            setupRegister();
            break;
        case "register.withopenid":
            $("#txtUserName").focus();
            setupRegister();
            break;
        case "register.withfacebook":
            $("#txtUserName").focus();
            setupRegister();
            break;
        case "posts.new":
            setupNewPost();
            break;
        case "posts.view":
            setupViewPost();
            break;
        case "posts.whosinterested":
            setupViewPostInterests();
            break;
        case "mystaga.notifications":
            setupMyNotifications();
            $("#my-notifications").setupForm();
            break;
        case "mystaga.contact":
            setupMyContact();
            break;
        case "mystaga.password":
            setupMyPassword();
            break;
        case "mystaga.profile":
            setupMyStagaProfile();
            break;
        case "mystaga.communities":
            setupMyStagaCommunities();
            break;
        case "mystaga.posts":
            setupMyStagaPosts();
            break;
        case "mystaga.messages.received":
            setupMyStagaMessages();
            break;
        case "mystaga.messages.sent":
            setupMyStagaMessages();
            break;
        case "mystaga.messages.view":
            setupMyStagaViewMessage();
            break;
        case "mystaga.friends":
            setupMyStagaFriends();
            break;
        case "members.profile":
            setupMemberProfile();
            break;
        case "posts.edit":
            setupEditPost();
            break;
        case "posts.remove":
            setupRemovePost();
            break;
        case "communities.join":
            setupJoinCommunity();
            break;
        case "invite.default":
            setupInviteFriends();
            break;
        case "mystaga.home":
            setupMyHome();
            setupSideButtons();
            break;
        case "contact":
            $("#contact-message").setupForm();
            break;
        case "recoverpassword":
            $("#reset-password").setupForm();
            break;
        default:
            staga.log("Unhandled page: " + staga.info.page.location);
    }

    setupAllPages();
    setupFeedback();

    $('a.post-image-enlarge').loadImageBox();
    staga.facebookConnect.core.init();
    if (staga.debug) { console.timeEnd("Staga"); }
});