var GLOBALS = this; (function ($) {

// prevent empty alerts
function _alert(msg) {
    if (typeof msg === 'string' && msg !== '') {
        alert(msg);
    }    
}

/*
 * this script is loaded on every page of the site
 */

var logwindow;
DEBUG = false;
if ($.browser.msie && $.browser.version < 8.0) {
    if (DEBUG === true) {
        logwindow = window.open('/ie7/', 'logwindow', 
			'top=309,left=437,height=150,width=150,' +
			'menubar=0,titlebar=0,status=0,toolbar=0,' +
			'location=0,scrollbars=0,resizable=0');
    }    
    GLOBALS.log = function (message) {
        if (DEBUG === true) {
            logwindow.document.write(message + '<br>');
        }
    };
} else {
    GLOBALS.log = function (message) {
        try {
            if (DEBUG === true && typeof console !== 'undefined' && 'log' in console) {
                console.log(message);
            }
        } catch (e) {/*IE trap not defined*/}
    };    
}

(function () {
    var hasRun = [], handlers = [];

    function checkEvents() {
        _(handlers).each(function (handler) {
            var allEventsHaveRun = _(handler.events).all(function (eventThatNeedsToHaveRun) {
                return _(hasRun).include(eventThatNeedsToHaveRun);
            });
            if (allEventsHaveRun) {
                handler.callback();
            }
        });
    }

    GLOBALS.complete = function (event) {
        hasRun.push(event);
        checkEvents();
    };

    GLOBALS.when = function () {
        if (typeof arguments[arguments.length - 1] !== 'function') {
            throw new Error('last argument of when() must be a callback function');
        }

        handlers.push({
            events: _(arguments).toArray().slice(0, -1),
            callback: arguments[arguments.length - 1]
        });

        checkEvents();
    };    
})();

var alHandlers = [];
GLOBALS.afterLoad = function afterLoad(desc, fn) {
    if (typeof fn === 'function') {
        log("afterLoader added, " + desc);
        alHandlers.push({ description: desc, handler: fn });
    }
};

var preloadHandlers = [];
var numPreLoaders = 0;
var finishedPreLoaders = 0;
GLOBALS.preLoad = function preLoad(desc, fn) {
    if (typeof fn === 'function') {
        numPreLoaders++;
        log("preloader added, " + desc + " (" + numPreLoaders + ")");
        preloadHandlers.push({ description: desc, handler: fn });
    }
};

$(document).ready(function () {
    _(preloadHandlers).each(function (preloader) {
        preloader.handler(function () {
            finishedPreLoaders++;
            log("preloader complete " + preloader.description + " (" + finishedPreLoaders + ")");
            if (finishedPreLoaders === numPreLoaders && alHandlers.length >= 1) {
                complete("preloadFinished");
                _(alHandlers).each(function (afterLoader) {
                    afterLoader.handler();
                    log("afterLoad complete " + afterLoader.description);
                });
                complete("afterloadFinished");
                execHashRoute();
                if (typeof logwindow !== 'undefined') {
                    logwindow.close();
                }
            }
        });
    });
    selectCurrentMenu();
});

function execHashRoute() {
    if (window.location.hash) {
        routeHash();
    }
}

function selectCurrentMenu() {
    var menuName = "menu_" + currentAppName.replace("-","_");
    // ie7 cannot use the css content entry so we use js
    $('li#' + menuName).children(".menu-dot-left").css('visibility', 'visible');
    $('li#' + menuName).children(".menu-dot-right").css('visibility', 'visible');
    $('li#' + menuName).children().css('color', 'rgb(227, 181, 83)');
}


// common jquery.eSelect settings for quick links
GLOBALS.eSelectOptions = {
    popUpContainerClass: 'quicklinks-popup',
    popUpItemClass: 'quicklinks-popup-item',
    rootTemplate: "quicklinks-header"
};

// allows munging of css rgb function
GLOBALS.rgb = function rgb(r,g,b) { return 'rgb('+r+','+g+','+b+')'; };

window.fbAsyncInit = function () {
    FB.init({
        apiKey: '120779134655435',
        status: true, cookie: true, oauth: true,
        channelURL: 'http://www.sargento.com/channel.html'
    });
    
    complete('facebookInitialized');
};

preLoad("initializing facebook", function (callback) {
    (function (d) {
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

    GLOBALS.doFacebookLogin = function (fns) {
        FB.login(function (response) {
            if (response.authResponse) {
                FB.api('/me', function (response) {
                    $.post('/facebook-connect/login/', {
                        uid: response.id, email: response.email,
                        first_name: response.first_name,
                        last_name: response.last_name
                    }, function (data) {
                        switch (data.message) {
                            case "login":
                                if (typeof fns.success === 'function') fns.success();
                            break;
                            case "registered":
                                window.location.href = window.location.protocol + '//' + window.location.host + ':' + window.location.port + '/users/welcome/';
                            break;
                            case "error":
                                if (typeof fns.error === 'function') fns.error();
                                _alert("An unknown error has occurred during login.");
                            break;
                        }
                    }, 'json');
                });
            } else {
                // failed
                if (typeof fns.error === 'function') fns.error();
                _alert("Facebook Authentication Failed. \nPlease register with your email address.");
            }
        }, { scope: 'email' });
    };
    callback();
});

preLoad("initializing shadow plugin", function (callback) {
    // jQuery plugin to add an offset, solid colored div behind an existing element
    $.fn.shadow = function (options) {
        options = $.extend({
            'color': rgb(159, 94, 25),
            'xOffset': 4, 'yOffset': 4
        }, options);
    
        return this.each(function () {
            var $this = $(this);
            
            $this.wrap($("<div />").css({
                'position': 'relative',
                'background': options.color,
                'height': $this.height() + 'px',
                'width': $this.width() + 'px',
                'margin-top': $this.css('margin-top'),
                'margin-right': $this.css('margin-right'),
                'margin-bottom': $this.css('margin-bottom'),
                'margin-left': $this.css('margin-left'),
                'top': options.yOffset + 'px',
                'left': options.xOffset + 'px'
            }));
            
            $this.css({
                'position': 'relative',
                'margin': '0',
                'top': '-' + options.yOffset + 'px',
                'left': '-' + options.xOffset + 'px'
            });
        });
    };

    callback();
});

preLoad("preload quick-links template", function (callback) {
    $.ajax('/jqt/quicklinks-header', {
        dataType: 'text',
        success: function (data) {
            $.template('quicklinks-header', data);
            callback();
        },
        error: function (jqxhr, textStatus, errorThrown) {
            log(errorThrown);
        }
    });
});


preLoad("prevent webkit autocomplete styling", function (callback) {
    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
        $(window).load(function () {
            $('input:-webkit-autofill').each(function () {
                var $this = $(this);
                $this.after(this.outerHTML).remove();
                $('input[name=' + $this.attr('name') + ']').val($this.val());
            });
        });
    }
    callback();
});


preLoad("bind drop box events", function (callback) {
    $("#search-term-input").click(function () {
        $(this).val(''); 
    });

    $("#search-term-input").blur(function () {
        if ($(this).val() === '') {
            $(this).val('Search');
        }
    });

    callback();
});

preLoad("hide scrollbars when necessary", function (callback) {
    $(window).resize(function fn() {
        if ( $(window).width() > 980 ) {
            $('html').css('overflow-x','hidden');
        } else {
            $('html').css('overflow-x','auto');
        }
        return fn;
    }());
    callback();
});

preLoad("use 'rel' attribute to identify external links", function (callback) {
    $("a[rel=external]").click(function () {
        window.open( $(this).attr('href') );
        return false;
    });
    callback();
});

preLoad("use 'rel' attribute to require login for a link", function (callback) {
    $("a[rel=login-required]").click(function () {
        var $this = $(this);
        if (typeof loggedInUsername === 'string') {
            return true;
        } else {
            userControlPanel.login(function () {
                window.location = $this.attr('href');
            });
            window.location.hash = "#register-indirect";
            return false;
        }
    });
    callback();
});

preLoad("display disabled ratings as stars", function (callback) {
    $(".rating-disabled").stars({
       'disabled': true
    });
    callback();
});

preLoad("initializing main menu", function (callback) {
    $("ul#menu-main").children(".menu-heading").each(function () {
        var $heading = $(this);
        $heading.css({ 'cursor': 'pointer' })
            .hover(function () {
                $heading.addClass('hover');
                $heading.children("ul").addClass('hover');
            }, function () {
                $heading.removeClass('hover');
                $heading.children("ul").removeClass('hover');
            });
    });

    $("li.menu-item").hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });

    callback();
});

preLoad("configuring drop shadows", function (callback) {
    $(".brown-shadow-large").shadow();
    $(".brown-shadow-small").shadow({
        xOffset: 2, yOffset: 2
    });
    callback();
});

GLOBALS.dialogBorder = {
    thickness: 13, offset: 3,
    'top-left corner': '/media/images/dialog-border-top-left.png',
    'top-right corner': '/media/images/dialog-border-top-right.png',
    'bottom-left corner': '/media/images/dialog-border-bottom-left.png',
    'bottom-right corner': '/media/images/dialog-border-bottom-right.png',
    'top edge': '/media/images/dialog-border-top.png',
    'right edge': '/media/images/dialog-border-right.png',
    'bottom edge': '/media/images/dialog-border-bottom.png',
    'left edge': '/media/images/dialog-border-left.png'
};


preLoad("loading register dialog", function (callback) {
    GLOBALS.registerDialog = {
        headings: {
            direct: "Sign Up for a Free Account",
            indirect: "Please Register to Continue"
        },
        bodyText: {
            direct: "By registering, you'll be able to rate and review recipes, save recipes to your recipe box and sign up for our e-newsletter. Fill out the fields below to become a registered member of Sargento.com <span class=\"italic\">or</span>",
            indirect: "Once you register, you can save recipes to your recipe box, rate and review recipes and sign up for our newsletter. To sign up for a free account, all you have to do is fill out the fields below <span class=\"italic\">or</span>"
        },
        template: null,
        init: _.once(function () {
            var self = this;

            $.ajax('/jqt/dialog-register', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('dialog-register', data);
                    self.templateLoaded();
                    callback();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                }
            });
        }),
        templateLoaded: _.once(function () {
            var self = this;
            
            $("body").prepend($.tmpl(this.template, {
                id: 'register-dialog',
                heading: this.directHeading,
                bodyText: this.directBodyText
            }));

            when('facebookInitialized', 'afterloadFinished', function () {
                FB.XFBML.parse(document.getElementById("log-in-dialog"));
            });

            $("#register-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 560, height: 494,
                closeText: '', position: 'center'
            }).wrapBorder($.extend({
                height: 480, width: 560
            }, dialogBorder));
            
            $("#register-dialog .register-dialog-mid .register-facebook-container").click(function () {
                doFacebookLogin({
                    success: function () {
                        window.location.hash = "#";
                    }
                });
            });
            
            $("button#registration-form-submit").click(function () {
                $.ajax('/users/', {
                    type: 'post',
                    data: $("#registration-form").serialize(),
                    success: function (data, status, jqXHR) {
                        userControlPanel.show();
                        window.location.hash = "#thank-you";
                    },
                    error: function (jqXHR, statusText, errorThrown) {
                        if (jqXHR.status === 400) {
                            var errorlist = $.parseJSON(jqXHR.responseText);
                            
                            function resolveFieldName(fieldName) {
                                return {
                                    first_name: "First Name",
                                    postal_code: "Zip Code",
                                    email: "Email",
                                    password1: "Password",
                                    password2: "Confirm Password",
                                    __all__: "all"
                                }[fieldName];
                            }
                            
                            function makeMessageIntelligible(field, messages) {
                                var fieldName = resolveFieldName(field);
                                var message = "";
                                for (var i in messages) {
                                    switch (messages[i]) {
                                        case "This field is required.":
                                            message += fieldName + " is required.";
                                            break;
                                        case "You must type in the same password each time":
                                            message += "Password and Confirm Password must match.";
                                            break;
                                        case "This email address is already in use.":
                                            message += messages[i];
                                            break;
                                        default:
                                            message += fieldName + " is invalid.";
                                    }
                                    message += "\n";
                                }
                                message = message.slice(0, -1);
                                return message;
                            }
                            
                            var message = "";
                            for (var fieldName in errorlist) {
                                message += makeMessageIntelligible(fieldName, errorlist[fieldName]) + "\n";
                            }
                            _alert(message);
                        } else {
                            _alert("Login failed. (Unknown error)");
                        }
                    }
                });
                return false;
            });
            
            beforeRoute(function () {
                registerDialog.hide();
            });
            
            addHashRoute("register-direct", function () {
                if (typeof loggedInUsername === 'string') {
                    window.location.hash = "#";
                } else {
                    self.show("direct");
                }
            });
            
            addHashRoute("register-indirect", function () {
                if (typeof loggedInUsername === 'string') {
                    window.location.hash = "#";
                } else {
                    self.show("indirect");
                }
            });
        }),
        show: function (which) {
            if (which === 'direct') {
                $("#register-dialog div.register-dialog-mid h4").text(registerDialog.headings.direct);
                $("#register-dialog div.register-dialog-mid p").html(registerDialog.bodyText.direct);
                $("#register-dialog").dialog("open");
            } else if (which === 'indirect') {
                $("#register-dialog div.register-dialog-mid h4").text(registerDialog.headings.indirect);
                $("#register-dialog div.register-dialog-mid p").html(registerDialog.bodyText.indirect);
                $("#register-dialog").dialog("open");
            } else {
                throw new Error('Dialog type, ' + which + ', does not exist. Try "direct" or "indirect".');
            }
        },
        hide: function () {
            $("#register-dialog").dialog("close");
        }
    };
    registerDialog.init();
});

preLoad("loading 'forgot password' dialog", function (callback) {
	GLOBALS.forgotPasswordDialog = {
		template: null,
		init: _.once(function () {
			var self = this;
			$.ajax('/jqt/dialog-forgot-password', {
				dataType: 'text',
				success: function (data) {
					self.template = $.template('dialog-forgot-password', data);
					callback();
					self.templateLoaded();
				},
				error: function (jqXHR, textStatus, errorThrown) {
					_alert(errorThrown);
				}
			});
		}),
		templateLoaded: _.once(function () {
			$('body').prepend($.tmpl(this.template, {
				id: 'forgot-password-dialog'
			}));
			
            $("#forgot-password-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 560, height: 294,
                closeText: '', position: 'center'
            }).wrapBorder($.extend({
                height: 280, width: 560
            }, dialogBorder));
			
            beforeRoute(function () {
                forgotPasswordDialog.hide();
            });
            
            addHashRoute("forgot-password", function () {
                if (typeof loggedInUsername === 'string') {
                    window.location.hash = "#";
                } else {
                    forgotPasswordDialog.show();
                }
            });
		}),
		show: function () {
			$('#forgot-password-dialog').dialog('open');
		},
		hide: function () {
			$('#forgot-password-dialog').dialog('close');
		}
	};
	forgotPasswordDialog.init();
});


preLoad("loading registration thank-you dialog", function (callback) {
    GLOBALS.thankYouDialog = {
        template: null,
        init: _.once(function () {
            var self = this;

            $.ajax('/jqt/dialog-register-thank-you', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('dialog-register-thank-you', data);
                    callback();
                    self.templateLoaded();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                }
            });
        }),
        templateLoaded: _.once(function () {
            $('body').prepend($.tmpl(this.template, {
                id: 'thank-you-dialog'
            }));

            // fix for weird bug in FF6
            if ($.browser.mozilla && parseInt($.browser.version) >= 6.0) {
                $("#thank-you-dialog").dialog({
                    autoOpen: false, draggable: false,
                    modal: true, resizable: false,
                    width: 560, height: 904, // WHY DOES THIS HAPPEN?
                    closeText: '', position: 'center'
                }).wrapBorder($.extend({
                    height: 480, width: 560
                }, dialogBorder));
            } else {
                $("#thank-you-dialog").dialog({
                    autoOpen: false, draggable: false,
                    modal: true, resizable: false,
                    width: 560, height: 494,
                    closeText: '', position: 'center'
                }).wrapBorder($.extend({
                    height: 480, width: 560
                }, dialogBorder));
            }

            $("a#thank-you-close-link").click(function () {
                window.location.hash = "#";
                return false;
            });
            
            beforeRoute(function () {
                thankYouDialog.hide();
            });
            
            addHashRoute("thank-you", function () {
                if (typeof loggedInUsername === 'string') {
                    window.location.hash = "#";
                } else {
                    thankYouDialog.show();
                }
            });
        }),
        show: function () {
            $("#thank-you-dialog").dialog("open");
        },
        hide: function () {
            $("#thank-you-dialog").dialog("close");
        }
    };
    thankYouDialog.init();
});


preLoad("loading contact thank-you dialog", function (callback) {
    GLOBALS.contactThankYouDialog = {
        template: null,
        init: _.once(function () {
            var self = this;

            $.ajax('/jqt/dialog-contact-thank-you', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('dialog-contact-thank-you', data);
                    callback();
                    self.templateLoaded();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                }
            });
        }),
        templateLoaded: _.once(function () {
            $('body').prepend($.tmpl(this.template, {
                id: 'contact-thank-you-dialog'
            }));

            $("#contact-thank-you-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 500, height: 250,
                closeText: '', position: 'center'
            }).wrapBorder($.extend({
                height: 236, width: 500
            }, dialogBorder));

            $("a#contact-thank-you-close-link").click(function () {
                window.location.href = "/";
                return false;
            });
            
            beforeRoute(function () {
                contactThankYouDialog.hide();
            });
            
            addHashRoute("contact-thank-you", function () {
                contactThankYouDialog.show();
            });
        }),
        show: function () {
            $("#contact-thank-you-dialog").dialog("open");
        },
        hide: function () {
            $("#contact-thank-you-dialog").dialog("close");
        }
    };
    contactThankYouDialog.init();
});

preLoad("initializing user control panel", function (callback) {
    GLOBALS.userControlPanel = {
        loginListeners: [],
        login: function (fn) {
            if (typeof fn === 'function') {
                this.loginListeners.push(fn);
                return this;
            } else {
                for (var i in this.loginListeners) {
                    this.loginListeners[i]();
                }
                return this;
            }
        },
        logoutListeners: [],
        logout: function (fn) {
            if (typeof fn === 'function') {
                this.logoutListeners.push(fn);
                return this;
            } else {
                for (var i in this.logoutListeners) {
                    this.logoutListeners[i]();
                }
                return this;
            }
        },
        show: function () {
            var self = this;
            $.ajax({
                url: '/users/username/',
                dataType: 'text',
                success: function (data) {
                    loggedInUsername = data;
                    $("#logged-in-links").removeClass('hidden');
                    $("#not-logged-in-links").addClass('hidden');
                    if (self.loginListeners.length > 0) {
                        self.login();
                    }
                }
            });
            return this;
        },
        hide: function () {
            $("#not-logged-in-links").removeClass('hidden');
            $("#logged-in-links").addClass('hidden');
            if (this.loginListeners.length > 0) {
                this.logout();
            }
            return this;
        }
    };
    callback();
});


preLoad("initializing login confirmation dialog", function (callback) {
    GLOBALS.confirmLoginDialog = {
        init: _.once(function () {
            var self = this;
            
            $.ajax('/jqt/dialog-confirm-login', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('dialog-confim-login', data);
                    self.templateLoaded();
                    callback();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                }
            });
        }),
        templateLoaded: _.once(function () {
            $('body').prepend($.tmpl(this.template, {
                id: 'confirm-login-dialog'
            }));

            $("#confirm-login-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 560, height: 300,
                closeText: '', position: 'center',
                closeOnEscape: false
            }).wrapBorder($.extend({
                width: 560, height: 284
            }, dialogBorder));

            userControlPanel.logout(confirmLoginDialog.logout);

            $("#confirm-login-dialog").parent().find("span.ui-icon-closethick").css({ visibility: 'hidden' });

            beforeRoute(function () {
                confirmLoginDialog.hide();
            });
            
            addHashRoute('confirm-login', function () {
                confirmLoginDialog.show();
            });
        }),
        logout: function () {
            $("#confirm-login-dialog").parent().find("span.ui-icon-closethick").css({ visibility: 'hidden' });
            $('div.confirm-login-dialog-loading').css({ display: 'block' });
            $('div.confirm-login-dialog-complete').css({ display: 'none' });
        },
        loginComplete: function () {
            $("#confirm-login-dialog").parent().find("span.ui-icon-closethick").css({ visibility: 'visible' });
            $('div.confirm-login-dialog-loading').css({ display: 'none' });
            $('div.confirm-login-dialog-complete').css({ display: 'block' });
        },
        show: function () {
            $('#confirm-login-dialog').dialog('open');
        },
        hide: function () {
            $('#confirm-login-dialog').dialog('close');
        }
    };
    confirmLoginDialog.init();
});

preLoad("loading log-in dialog", function (callback) {
    GLOBALS.logInDialog = {
        template: null,
        init: _.once(function () {
            var self = this;
            
            $.ajax('/jqt/dialog-log-in', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('dialog-log-in', data);
                    self.templateLoaded();
                    callback();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                }
            });
        }),
        templateLoaded: _.once(function () {
            $('body').prepend($.tmpl(this.template, {
                id: 'log-in-dialog'
            }));

            when('facebookInitialized', 'afterloadFinished', function () {
                FB.XFBML.parse(document.getElementById("register-dialog"));
            });
            
            $("#log-in-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 560, height: 300,
                closeText: '', position: 'center'
            }).wrapBorder($.extend({
                width: 560, height: 284
            }, dialogBorder));

            $("button#log-in-form-submit").click(function () {
                logInDialog.hide();
                confirmLoginDialog.show();
                $.ajax('/users/log-in/', {
                    type: 'post',
                    data: $("#log-in-form").serialize(),
                    success: function (data, status, jqXHR) {
                        confirmLoginDialog.loginComplete();
                        userControlPanel.show();
                    },
                    error: function (jqXHR, statusText, errorThrown) {
                        confirmLoginDialog.hide();
                        logInDialog.show();
                        if (jqXHR.status === 400) {
                            _alert("Incorrect email or password, please try again.");
                        } else {
                            _alert("Login failed. (Unknown error)");
                        }
                    }
                });
                return false;
            });

            $('#register-facebook-container').click(function () {
                logInDialog.hide();
                confirmLoginDialog.show();
                doFacebookLogin({
                    success: function () {
                        confirmLoginDialog.loginComplete();
                        userControlPanel.show();
                    },
                    error: function () {
                        confirmLoginDialog.hide();
                        logInDialog.show();
                    }
                });
            });
            
            beforeRoute(function () {
                logInDialog.hide();
            });
            
            addHashRoute("log-in", function () {
                if (typeof loggedInUsername === 'string') {
                    window.location.hash = "#";
                } else {
                    logInDialog.show();
                }
            });
        }),
        show: function () {
            $("#log-in-dialog").dialog("open");
        },
        hide: function () {
            $("#log-in-dialog").dialog("close");
        }
    };
    
    logInDialog.init();
});


preLoad("initializing profile dialog", function (callback) {
    GLOBALS.editProfileDialog = {
        init: _.once(function () {
            var self = this;

            $.ajax('/jqt/dialog-profile', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('profile-dialog', data);
                    self.templateLoaded();
                    callback();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                    callback();
                }
            });
        }),

        templateLoaded: _.once(function () {
            var self = this;

            $('body').prepend($.tmpl(this.template, {
                id: 'profile-dialog'
            }));

            $("#profile-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 560, height: 300,
                closeText: '', position: 'center'
            }).wrapBorder($.extend({
                width: 560, height: 284
            }, dialogBorder));

            $("button#profile-form-submit").click(function () {
                $.ajax('/users/profile/', {
                    type: 'post',
                    data: $("#profile-form").serialize(),
                    success: function (data, status, jqXHR) {
                        if (jqXHR.status === 200) {
                            _alert("Profile updated successfully.");
                            window.location.hash = "#";
                        }
                    },
                    error: function (jqXHR, statusText, errorThrown) {
                        if (jqXHR.status === 400) {
                            _alert("TODO");
                        } else {
                            _alert("Save profile failed. (Unknown error)");
                        }
                    }
                });
                return false;
            });
            
            beforeRoute(function () {
                editProfileDialog.hide();
            });
            
            addHashRoute("profile", function () {
                editProfileDialog.show();
            }, true);
        }),
        reloadData: function (callback) {
            $.ajax({
                url: '/users/profile/',
                dataType: 'html',
                success: function (data, textStatus, jqXHR) {
                    var $data = $(data);
                    $(".profile-form-first-name input").val($data.find("#id_first_name").val());
                    $(".profile-form-email input").val($data.find("#id_email").val());
                    $(".profile-form-zip-code input").val($data.find("#id_postal_code").val());
                    $(".profile-form-newsletter input").val($data.find("#id_newsletter").val());
                    callback();
                },
                error: function (jqXHR, status, errorThrown) {
                    _alert("Error occurred while loading profile data.");
                }
            });
        },
        show: function () {
            this.reloadData(function () {
                $("#profile-dialog").dialog("open");
            });
        },
        hide: function () {
            $("#profile-dialog").dialog("close");
        }
    };
    
    editProfileDialog.init();
});

preLoad("initializing password change dialog", function (callback) {
    GLOBALS.changePasswordDialog = {
        init: _.once(function () {
            var self = this;

            $.ajax('/jqt/dialog-password', {
                dataType: 'text',
                success: function (data) {
                    self.template = $.template('password-dialog', data);
                    self.templateLoaded();
                    callback();
                },
                error: function (jqxhr, textStatus, errorThrown) {
                    _alert(errorThrown);
                    callback();
                }
            });
        }),
        templateLoaded: _.once(function () {
            var self = this;

            $('body').prepend($.tmpl(this.template, {
                id: 'password-dialog'
            }));

            $("#password-dialog").dialog({
                autoOpen: false, draggable: false,
                modal: true, resizable: false,
                width: 560, height: 395,
                closeText: '', position: 'center'
            }).wrapBorder($.extend({
                width: 560, height: 380
            }, dialogBorder));

            $("button#password-form-submit").click(function () {
                $.ajax('/users/password/', {
                    type: 'post',
                    data: $("#password-form").serialize(),
                    success: function (data, status, jqXHR) {
                        if (jqXHR.status === 200) {
                            _alert("Password changed successfully.");
                            window.location.hash = "#";
                        }
                    },
                    error: function (jqXHR, statusText, errorThrown) {
                        if (jqXHR.status === 400) {
                            _alert("An error occurred while updating your password. Please try again.");
                        } else {
                            _alert("Save profile failed. (Unknown error)");
                        }
                    }
                });
                return false;
            });
            
            beforeRoute(function () {
                changePasswordDialog.hide();
            });
            
            addHashRoute("change-password", function () {
                changePasswordDialog.show();
            }, true);
        }),
        show: function () {
            $("#password-dialog").dialog('open');
        },
        hide: function () {
            $("#password-dialog").dialog('close');
        }
    };

    changePasswordDialog.init();
});


(function () {
    var routes = {};
    var beforeFns = [];
    
    GLOBALS.beforeRoute = function (fn) {
        beforeFns.push(fn);
    };
    
    GLOBALS.addHashRoute = function (hashTag, fn, requiresLogin) {
        if (typeof requiresLogin !== 'undefined') {
            routes[hashTag] = function () {
                if (typeof loggedInUsername === 'string') {
                    fn();
                } else {
                    window.location.hash = "#register-indirect";
                }
            };
        } else {
            routes[hashTag] = fn;
        }
    };
    
    addHashRoute('', function () {});
    
    GLOBALS.routeHash = function () {
        _(beforeFns).each(function (fn) { fn(); });
        var hashTag = window.location.hash.substr(1);
        var fn = routes[hashTag];
        if (typeof fn === 'function') {
            fn();
        }
    };

    if ($.browser.msie && $.browser.version < 8.0) {
        var lastHash = window.location.hash;
        afterLoad("setting hash poll", function () {
            setInterval(function () {
                if (window.location.hash !== lastHash) {
                    lastHash = window.location.hash;
                    routeHash();
                }
            }, 100);
        }); 
    }

    if ("onhashchange" in window) {
        window.onhashchange = function () {
            routeHash();
        }
    }

})();

afterLoad("initializing logout", function () {
    GLOBALS.logout = function () {
        $.ajax({
            url: '/users/log-out/',
            success: function () {
                userControlPanel.hide();
                loggedInUsername = undefined;
                window.location.hash = "#";
                _alert("You have been logged out successfully.");
            },
            error: function () {
                window.location.hash = "#";
                _alert("An error occurred during logout.");
            }
        });
    };
    
    addHashRoute("log-out", function () {
        logout();
    });
});


afterLoad("re-routing dialog close buttons", function () {
    $("a.ui-dialog-titlebar-close").click(function () {
        window.location.hash = "#";
        return false;
    });
});

afterLoad("initializing search form", function () {
    $("#search-type-select").change(function () {
        var newAction = $(this).val(),
            searchForm = $("#search-form");
        if (newAction === 'products') {
            searchForm.attr('action', '/search/product/');
        } else if (newAction === 'recipes') {
            searchForm.attr('action', '/search/recipe/');
        } else {
            searchForm.attr('action', '/search/site/');
        }
    });
});

afterLoad("initializing back-to-top button", function () {
    // Function to update button positioning mode
    function updateBttPos() {
        var scrollPos = document.body.scrollTop || document.documentElement.scrollTop;
        if (scrollPos < 1042 && $('#back-to-top').css('position') !== 'absolute') {
            $('#back-to-top').removeClass('bttfixed');
        } else if (scrollPos >= 1042 && $('#back-to-top').css('position') !== 'fixed') {
            $('#back-to-top').addClass('bttfixed');
        }
    }

    // Initialize 
    updateBttPos();

    // Update on scroll
    $(window).scroll(function () {
        updateBttPos();
    });
});

afterLoad("initializing internal anchor animation", function () {
    $('a[href^="#"]').click(function (e) {
        var name = $(this).attr('href');
        name = name.replace('#', '');
        var targetOffset = $('a[name="' + name + '"]').offset();
        if (targetOffset) {
            var target = targetOffset.top - 30;
            $('html,body').animate({ scrollTop: target }, 1500);
            return false;
        }
    });
});

afterLoad("styling search drop down", function () {
    $("#search-type-select").eSelect({
        popUpContainerClass: 'search-select-popup',
        popUpItemClass: 'search-select-popup-item',
        popUpItemTemplate: $.template('<div id="${id}" class="${htmlClass}"><img src="/media/images/search-select-dropdown-item-hover.png">${text}</div>')
    });
});

/* Removing Hover dots on main menu per Grey's request
   Incidentally, this feature actually wound about costing about $400
   That's a really good bottle of cognac man... :(
afterLoad("adding hover dots to menu headings", function() {
    var menuName = "menu_" + currentAppName.replace("-","_");
    $("li.menu-heading > a").each(function () {
        log($(this));
        if($(this).parent().attr('id') !== menuName) {
            $(this).hover(function () {    
                $(this).parent().children(".menu-dot-left").css('visibility', 'visible');
                $(this).parent().children(".menu-dot-right").css('visibility', 'visible');
            }, function() {
                $(this).parent().children(".menu-dot-left").css('visibility', 'hidden');
                $(this).parent().children(".menu-dot-right").css('visibility', 'hidden');
            });
       }   
    });        
});
*/


})(jQuery);

