//
// jQuery\defineAR.js
//

if (typeof (AR) == "undefined") {
    AR = {};
}

//
// lib\jQuery\jquery-1.4.4.js
//
/*!
* jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function (window, undefined) {

    // Use the correct document accordingly with window argument (sandbox)
    var document = window.document;
    var jQuery = (function () {

        // Define a local copy of jQuery
        var jQuery = function (selector, context) {
            // The jQuery object is actually just the init constructor 'enhanced'
            return new jQuery.fn.init(selector, context);
        },

        // Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

        // Map over the $ in case of overwrite
	_$ = window.$,

        // A central reference to the root jQuery(document)
	rootjQuery,

        // A simple way to check for HTML strings or ID strings
        // (both of which we optimize for)
	quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,

        // Is it a simple selector
	isSimple = /^.[^:#\[\.,]*$/,

        // Check if a string has a non-whitespace character in it
	rnotwhite = /\S/,
	rwhite = /\s/,

        // Used for trimming whitespace
	trimLeft = /^\s+/,
	trimRight = /\s+$/,

        // Check for non-word characters
	rnonword = /\W/,

        // Check for digits
	rdigit = /\d/,

        // Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,

        // JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,

        // Useragent RegExp
	rwebkit = /(webkit)[ \/]([\w.]+)/,
	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
	rmsie = /(msie) ([\w.]+)/,
	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,

        // Keep a UserAgent string for use with jQuery.browser
	userAgent = navigator.userAgent,

        // For matching the engine and version of the browser
	browserMatch,

        // Has the ready events already been bound?
	readyBound = false,

        // The functions to execute on DOM ready
	readyList = [],

        // The ready event handler
	DOMContentLoaded,

        // Save a reference to some core methods
	toString = Object.prototype.toString,
	hasOwn = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	trim = String.prototype.trim,
	indexOf = Array.prototype.indexOf,

        // [[Class]] -> type pairs
	class2type = {};

        jQuery.fn = jQuery.prototype = {
            init: function (selector, context) {
                var match, elem, ret, doc;

                // Handle $(""), $(null), or $(undefined)
                if (!selector) {
                    return this;
                }

                // Handle $(DOMElement)
                if (selector.nodeType) {
                    this.context = this[0] = selector;
                    this.length = 1;
                    return this;
                }

                // The body element only exists once, optimize finding it
                if (selector === "body" && !context && document.body) {
                    this.context = document;
                    this[0] = document.body;
                    this.selector = "body";
                    this.length = 1;
                    return this;
                }

                // Handle HTML strings
                if (typeof selector === "string") {
                    // Are we dealing with HTML string or an ID?
                    match = quickExpr.exec(selector);

                    // Verify a match, and that no context was specified for #id
                    if (match && (match[1] || !context)) {

                        // HANDLE: $(html) -> $(array)
                        if (match[1]) {
                            doc = (context ? context.ownerDocument || context : document);

                            // If a single string is passed in and it's a single tag
                            // just do a createElement and skip the rest
                            ret = rsingleTag.exec(selector);

                            if (ret) {
                                if (jQuery.isPlainObject(context)) {
                                    selector = [document.createElement(ret[1])];
                                    jQuery.fn.attr.call(selector, context, true);

                                } else {
                                    selector = [doc.createElement(ret[1])];
                                }

                            } else {
                                ret = jQuery.buildFragment([match[1]], [doc]);
                                selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
                            }

                            return jQuery.merge(this, selector);

                            // HANDLE: $("#id")
                        } else {
                            elem = document.getElementById(match[2]);

                            // Check parentNode to catch when Blackberry 4.6 returns
                            // nodes that are no longer in the document #6963
                            if (elem && elem.parentNode) {
                                // Handle the case where IE and Opera return items
                                // by name instead of ID
                                if (elem.id !== match[2]) {
                                    return rootjQuery.find(selector);
                                }

                                // Otherwise, we inject the element directly into the jQuery object
                                this.length = 1;
                                this[0] = elem;
                            }

                            this.context = document;
                            this.selector = selector;
                            return this;
                        }

                        // HANDLE: $("TAG")
                    } else if (!context && !rnonword.test(selector)) {
                        this.selector = selector;
                        this.context = document;
                        selector = document.getElementsByTagName(selector);
                        return jQuery.merge(this, selector);

                        // HANDLE: $(expr, $(...))
                    } else if (!context || context.jquery) {
                        return (context || rootjQuery).find(selector);

                        // HANDLE: $(expr, context)
                        // (which is just equivalent to: $(context).find(expr)
                    } else {
                        return jQuery(context).find(selector);
                    }

                    // HANDLE: $(function)
                    // Shortcut for document ready
                } else if (jQuery.isFunction(selector)) {
                    return rootjQuery.ready(selector);
                }

                if (selector.selector !== undefined) {
                    this.selector = selector.selector;
                    this.context = selector.context;
                }

                return jQuery.makeArray(selector, this);
            },

            // Start with an empty selector
            selector: "",

            // The current version of jQuery being used
            jquery: "1.4.4",

            // The default length of a jQuery object is 0
            length: 0,

            // The number of elements contained in the matched element set
            size: function () {
                return this.length;
            },

            toArray: function () {
                return slice.call(this, 0);
            },

            // Get the Nth element in the matched element set OR
            // Get the whole matched element set as a clean array
            get: function (num) {
                return num == null ?

                // Return a 'clean' array
			this.toArray() :

                // Return just the object
			(num < 0 ? this.slice(num)[0] : this[num]);
            },

            // Take an array of elements and push it onto the stack
            // (returning the new matched element set)
            pushStack: function (elems, name, selector) {
                // Build a new jQuery matched element set
                var ret = jQuery();

                if (jQuery.isArray(elems)) {
                    push.apply(ret, elems);

                } else {
                    jQuery.merge(ret, elems);
                }

                // Add the old object onto the stack (as a reference)
                ret.prevObject = this;

                ret.context = this.context;

                if (name === "find") {
                    ret.selector = this.selector + (this.selector ? " " : "") + selector;
                } else if (name) {
                    ret.selector = this.selector + "." + name + "(" + selector + ")";
                }

                // Return the newly-formed element set
                return ret;
            },

            // Execute a callback for every element in the matched set.
            // (You can seed the arguments with an array of args, but this is
            // only used internally.)
            each: function (callback, args) {
                return jQuery.each(this, callback, args);
            },

            ready: function (fn) {
                // Attach the listeners
                jQuery.bindReady();

                // If the DOM is already ready
                if (jQuery.isReady) {
                    // Execute the function immediately
                    fn.call(document, jQuery);

                    // Otherwise, remember the function for later
                } else if (readyList) {
                    // Add the function to the wait list
                    readyList.push(fn);
                }

                return this;
            },

            eq: function (i) {
                return i === -1 ?
			this.slice(i) :
			this.slice(i, +i + 1);
            },

            first: function () {
                return this.eq(0);
            },

            last: function () {
                return this.eq(-1);
            },

            slice: function () {
                return this.pushStack(slice.apply(this, arguments),
			"slice", slice.call(arguments).join(","));
            },

            map: function (callback) {
                return this.pushStack(jQuery.map(this, function (elem, i) {
                    return callback.call(elem, i, elem);
                }));
            },

            end: function () {
                return this.prevObject || jQuery(null);
            },

            // For internal use only.
            // Behaves like an Array's method, not like a jQuery method.
            push: push,
            sort: [].sort,
            splice: [].splice
        };

        // Give the init function the jQuery prototype for later instantiation
        jQuery.fn.init.prototype = jQuery.fn;

        jQuery.extend = jQuery.fn.extend = function () {
            var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

            // Handle a deep copy situation
            if (typeof target === "boolean") {
                deep = target;
                target = arguments[1] || {};
                // skip the boolean and the target
                i = 2;
            }

            // Handle case when target is a string or something (possible in deep copy)
            if (typeof target !== "object" && !jQuery.isFunction(target)) {
                target = {};
            }

            // extend jQuery itself if only one argument is passed
            if (length === i) {
                target = this;
                --i;
            }

            for (; i < length; i++) {
                // Only deal with non-null/undefined values
                if ((options = arguments[i]) != null) {
                    // Extend the base object
                    for (name in options) {
                        src = target[name];
                        copy = options[name];

                        // Prevent never-ending loop
                        if (target === copy) {
                            continue;
                        }

                        // Recurse if we're merging plain objects or arrays
                        if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
                            if (copyIsArray) {
                                copyIsArray = false;
                                clone = src && jQuery.isArray(src) ? src : [];

                            } else {
                                clone = src && jQuery.isPlainObject(src) ? src : {};
                            }

                            // Never move original objects, clone them
                            target[name] = jQuery.extend(deep, clone, copy);

                            // Don't bring in undefined values
                        } else if (copy !== undefined) {
                            target[name] = copy;
                        }
                    }
                }
            }

            // Return the modified object
            return target;
        };

        jQuery.extend({
            noConflict: function (deep) {
                window.$ = _$;

                if (deep) {
                    window.jQuery = _jQuery;
                }

                return jQuery;
            },

            // Is the DOM ready to be used? Set to true once it occurs.
            isReady: false,

            // A counter to track how many items to wait for before
            // the ready event fires. See #6781
            readyWait: 1,

            // Handle when the DOM is ready
            ready: function (wait) {
                // A third-party is pushing the ready event forwards
                if (wait === true) {
                    jQuery.readyWait--;
                }

                // Make sure that the DOM is not already loaded
                if (!jQuery.readyWait || (wait !== true && !jQuery.isReady)) {
                    // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                    if (!document.body) {
                        return setTimeout(jQuery.ready, 1);
                    }

                    // Remember that the DOM is ready
                    jQuery.isReady = true;

                    // If a normal DOM Ready event fired, decrement, and wait if need be
                    if (wait !== true && --jQuery.readyWait > 0) {
                        return;
                    }

                    // If there are functions bound, to execute
                    if (readyList) {
                        // Execute all of them
                        var fn,
					i = 0,
					ready = readyList;

                        // Reset the list of functions
                        readyList = null;

                        while ((fn = ready[i++])) {
                            fn.call(document, jQuery);
                        }

                        // Trigger any bound ready events
                        if (jQuery.fn.trigger) {
                            jQuery(document).trigger("ready").unbind("ready");
                        }
                    }
                }
            },

            bindReady: function () {
                if (readyBound) {
                    return;
                }

                readyBound = true;

                // Catch cases where $(document).ready() is called after the
                // browser event has already occurred.
                if (document.readyState === "complete") {
                    // Handle it asynchronously to allow scripts the opportunity to delay ready
                    return setTimeout(jQuery.ready, 1);
                }

                // Mozilla, Opera and webkit nightlies currently support this event
                if (document.addEventListener) {
                    // Use the handy event callback
                    document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);

                    // A fallback to window.onload, that will always work
                    window.addEventListener("load", jQuery.ready, false);

                    // If IE event model is used
                } else if (document.attachEvent) {
                    // ensure firing before onload,
                    // maybe late but safe also for iframes
                    document.attachEvent("onreadystatechange", DOMContentLoaded);

                    // A fallback to window.onload, that will always work
                    window.attachEvent("onload", jQuery.ready);

                    // If IE and not a frame
                    // continually check to see if the document is ready
                    var toplevel = false;

                    try {
                        toplevel = window.frameElement == null;
                    } catch (e) { }

                    if (document.documentElement.doScroll && toplevel) {
                        doScrollCheck();
                    }
                }
            },

            // See test/unit/core.js for details concerning isFunction.
            // Since version 1.3, DOM methods and functions like alert
            // aren't supported. They return false on IE (#2968).
            isFunction: function (obj) {
                return jQuery.type(obj) === "function";
            },

            isArray: Array.isArray || function (obj) {
                return jQuery.type(obj) === "array";
            },

            // A crude way of determining if an object is a window
            isWindow: function (obj) {
                return obj && typeof obj === "object" && "setInterval" in obj;
            },

            isNaN: function (obj) {
                return obj == null || !rdigit.test(obj) || isNaN(obj);
            },

            type: function (obj) {
                return obj == null ?
			String(obj) :
			class2type[toString.call(obj)] || "object";
            },

            isPlainObject: function (obj) {
                // Must be an Object.
                // Because of IE, we also have to check the presence of the constructor property.
                // Make sure that DOM nodes and window objects don't pass through, as well
                if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
                    return false;
                }

                // Not own constructor property must be Object
                if (obj.constructor &&
			!hasOwn.call(obj, "constructor") &&
			!hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
                    return false;
                }

                // Own properties are enumerated firstly, so to speed up,
                // if last one is own, then all properties are own.

                var key;
                for (key in obj) { }

                return key === undefined || hasOwn.call(obj, key);
            },

            isEmptyObject: function (obj) {
                for (var name in obj) {
                    return false;
                }
                return true;
            },

            error: function (msg) {
                throw msg;
            },

            parseJSON: function (data) {
                if (typeof data !== "string" || !data) {
                    return null;
                }

                // Make sure leading/trailing whitespace is removed (IE can't handle it)
                data = jQuery.trim(data);

                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if (rvalidchars.test(data.replace(rvalidescape, "@")
			.replace(rvalidtokens, "]")
			.replace(rvalidbraces, ""))) {

                    // Try to use the native JSON parser first
                    return window.JSON && window.JSON.parse ?
				window.JSON.parse(data) :
				(new Function("return " + data))();

                } else {
                    jQuery.error("Invalid JSON: " + data);
                }
            },

            noop: function () { },

            // Evalulates a script in a global context
            globalEval: function (data) {
                if (data && rnotwhite.test(data)) {
                    // Inspired by code by Andrea Giammarchi
                    // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
                    var head = document.getElementsByTagName("head")[0] || document.documentElement,
				script = document.createElement("script");

                    script.type = "text/javascript";

                    if (jQuery.support.scriptEval) {
                        script.appendChild(document.createTextNode(data));
                    } else {
                        script.text = data;
                    }

                    // Use insertBefore instead of appendChild to circumvent an IE6 bug.
                    // This arises when a base node is used (#2709).
                    head.insertBefore(script, head.firstChild);
                    head.removeChild(script);
                }
            },

            nodeName: function (elem, name) {
                return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
            },

            // args is for internal usage only
            each: function (object, callback, args) {
                var name, i = 0,
			length = object.length,
			isObj = length === undefined || jQuery.isFunction(object);

                if (args) {
                    if (isObj) {
                        for (name in object) {
                            if (callback.apply(object[name], args) === false) {
                                break;
                            }
                        }
                    } else {
                        for (; i < length; ) {
                            if (callback.apply(object[i++], args) === false) {
                                break;
                            }
                        }
                    }

                    // A special, fast, case for the most common use of each
                } else {
                    if (isObj) {
                        for (name in object) {
                            if (callback.call(object[name], name, object[name]) === false) {
                                break;
                            }
                        }
                    } else {
                        for (var value = object[0];
					i < length && callback.call(value, i, value) !== false; value = object[++i]) { }
                    }
                }

                return object;
            },

            // Use native String.trim function wherever possible
            trim: trim ?
		function (text) {
		    return text == null ?
				"" :
				trim.call(text);
		} :

            // Otherwise use our own trimming functionality
		function (text) {
		    return text == null ?
				"" :
				text.toString().replace(trimLeft, "").replace(trimRight, "");
		},

            // results is for internal usage only
            makeArray: function (array, results) {
                var ret = results || [];

                if (array != null) {
                    // The window, strings (and functions) also have 'length'
                    // The extra typeof function check is to prevent crashes
                    // in Safari 2 (See: #3039)
                    // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
                    var type = jQuery.type(array);

                    if (array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow(array)) {
                        push.call(ret, array);
                    } else {
                        jQuery.merge(ret, array);
                    }
                }

                return ret;
            },

            inArray: function (elem, array) {
                if (array.indexOf) {
                    return array.indexOf(elem);
                }

                for (var i = 0, length = array.length; i < length; i++) {
                    if (array[i] === elem) {
                        return i;
                    }
                }

                return -1;
            },

            merge: function (first, second) {
                var i = first.length,
			j = 0;

                if (typeof second.length === "number") {
                    for (var l = second.length; j < l; j++) {
                        first[i++] = second[j];
                    }

                } else {
                    while (second[j] !== undefined) {
                        first[i++] = second[j++];
                    }
                }

                first.length = i;

                return first;
            },

            grep: function (elems, callback, inv) {
                var ret = [], retVal;
                inv = !!inv;

                // Go through the array, only saving the items
                // that pass the validator function
                for (var i = 0, length = elems.length; i < length; i++) {
                    retVal = !!callback(elems[i], i);
                    if (inv !== retVal) {
                        ret.push(elems[i]);
                    }
                }

                return ret;
            },

            // arg is for internal usage only
            map: function (elems, callback, arg) {
                var ret = [], value;

                // Go through the array, translating each of the items to their
                // new value (or values).
                for (var i = 0, length = elems.length; i < length; i++) {
                    value = callback(elems[i], i, arg);

                    if (value != null) {
                        ret[ret.length] = value;
                    }
                }

                return ret.concat.apply([], ret);
            },

            // A global GUID counter for objects
            guid: 1,

            proxy: function (fn, proxy, thisObject) {
                if (arguments.length === 2) {
                    if (typeof proxy === "string") {
                        thisObject = fn;
                        fn = thisObject[proxy];
                        proxy = undefined;

                    } else if (proxy && !jQuery.isFunction(proxy)) {
                        thisObject = proxy;
                        proxy = undefined;
                    }
                }

                if (!proxy && fn) {
                    proxy = function () {
                        return fn.apply(thisObject || this, arguments);
                    };
                }

                // Set the guid of unique handler to the same of original handler, so it can be removed
                if (fn) {
                    proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
                }

                // So proxy can be declared as an argument
                return proxy;
            },

            // Mutifunctional method to get and set values to a collection
            // The value/s can be optionally by executed if its a function
            access: function (elems, key, value, exec, fn, pass) {
                var length = elems.length;

                // Setting many attributes
                if (typeof key === "object") {
                    for (var k in key) {
                        jQuery.access(elems, k, key[k], exec, fn, value);
                    }
                    return elems;
                }

                // Setting one attribute
                if (value !== undefined) {
                    // Optionally, function values get executed if exec is true
                    exec = !pass && exec && jQuery.isFunction(value);

                    for (var i = 0; i < length; i++) {
                        fn(elems[i], key, exec ? value.call(elems[i], i, fn(elems[i], key)) : value, pass);
                    }

                    return elems;
                }

                // Getting an attribute
                return length ? fn(elems[0], key) : undefined;
            },

            now: function () {
                return (new Date()).getTime();
            },

            // Use of jQuery.browser is frowned upon.
            // More details: http://docs.jquery.com/Utilities/jQuery.browser
            uaMatch: function (ua) {
                ua = ua.toLowerCase();

                var match = rwebkit.exec(ua) ||
			ropera.exec(ua) ||
			rmsie.exec(ua) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec(ua) ||
			[];

                return { browser: match[1] || "", version: match[2] || "0" };
            },

            browser: {}
        });

        // Populate the class2type map
        jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (i, name) {
            class2type["[object " + name + "]"] = name.toLowerCase();
        });

        browserMatch = jQuery.uaMatch(userAgent);
        if (browserMatch.browser) {
            jQuery.browser[browserMatch.browser] = true;
            jQuery.browser.version = browserMatch.version;
        }

        // Deprecated, use jQuery.browser.webkit instead
        if (jQuery.browser.webkit) {
            jQuery.browser.safari = true;
        }

        if (indexOf) {
            jQuery.inArray = function (elem, array) {
                return indexOf.call(array, elem);
            };
        }

        // Verify that \s matches non-breaking spaces
        // (IE fails on this test)
        if (!rwhite.test("\xA0")) {
            trimLeft = /^[\s\xA0]+/;
            trimRight = /[\s\xA0]+$/;
        }

        // All jQuery objects should point back to these
        rootjQuery = jQuery(document);

        // Cleanup functions for the document ready method
        if (document.addEventListener) {
            DOMContentLoaded = function () {
                document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
                jQuery.ready();
            };

        } else if (document.attachEvent) {
            DOMContentLoaded = function () {
                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                if (document.readyState === "complete") {
                    document.detachEvent("onreadystatechange", DOMContentLoaded);
                    jQuery.ready();
                }
            };
        }

        // The DOM ready check for Internet Explorer
        function doScrollCheck() {
            if (jQuery.isReady) {
                return;
            }

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch (e) {
                setTimeout(doScrollCheck, 1);
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        }

        // Expose jQuery to the global object
        return (window.jQuery = window.$ = jQuery);

    })();


    (function () {

        jQuery.support = {};

        var root = document.documentElement,
		script = document.createElement("script"),
		div = document.createElement("div"),
		id = "script" + jQuery.now();

        div.style.display = "none";
        div.innerHTML = "   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";

        var all = div.getElementsByTagName("*"),
		a = div.getElementsByTagName("a")[0],
		select = document.createElement("select"),
		opt = select.appendChild(document.createElement("option"));

        // Can't get basic test support
        if (!all || !all.length || !a) {
            return;
        }

        jQuery.support = {
            // IE strips leading whitespace when .innerHTML is used
            leadingWhitespace: div.firstChild.nodeType === 3,

            // Make sure that tbody elements aren't automatically inserted
            // IE will insert them into empty tables
            tbody: !div.getElementsByTagName("tbody").length,

            // Make sure that link elements get serialized correctly by innerHTML
            // This requires a wrapper element in IE
            htmlSerialize: !!div.getElementsByTagName("link").length,

            // Get the style information from getAttribute
            // (IE uses .cssText insted)
            style: /red/.test(a.getAttribute("style")),

            // Make sure that URLs aren't manipulated
            // (IE normalizes it by default)
            hrefNormalized: a.getAttribute("href") === "/a",

            // Make sure that element opacity exists
            // (IE uses filter instead)
            // Use a regex to work around a WebKit issue. See #5145
            opacity: /^0.55$/.test(a.style.opacity),

            // Verify style float existence
            // (IE uses styleFloat instead of cssFloat)
            cssFloat: !!a.style.cssFloat,

            // Make sure that if no value is specified for a checkbox
            // that it defaults to "on".
            // (WebKit defaults to "" instead)
            checkOn: div.getElementsByTagName("input")[0].value === "on",

            // Make sure that a selected-by-default option has a working selected property.
            // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
            optSelected: opt.selected,

            // Will be defined later
            deleteExpando: true,
            optDisabled: false,
            checkClone: false,
            scriptEval: false,
            noCloneEvent: true,
            boxModel: null,
            inlineBlockNeedsLayout: false,
            shrinkWrapBlocks: false,
            reliableHiddenOffsets: true
        };

        // Make sure that the options inside disabled selects aren't marked as disabled
        // (WebKit marks them as diabled)
        select.disabled = true;
        jQuery.support.optDisabled = !opt.disabled;

        script.type = "text/javascript";
        try {
            script.appendChild(document.createTextNode("window." + id + "=1;"));
        } catch (e) { }

        root.insertBefore(script, root.firstChild);

        // Make sure that the execution of code works by injecting a script
        // tag with appendChild/createTextNode
        // (IE doesn't support this, fails, and uses .text instead)
        if (window[id]) {
            jQuery.support.scriptEval = true;
            delete window[id];
        }

        // Test to see if it's possible to delete an expando from an element
        // Fails in Internet Explorer
        try {
            delete script.test;

        } catch (e) {
            jQuery.support.deleteExpando = false;
        }

        root.removeChild(script);

        if (div.attachEvent && div.fireEvent) {
            div.attachEvent("onclick", function click() {
                // Cloning a node shouldn't copy over any
                // bound event handlers (IE does this)
                jQuery.support.noCloneEvent = false;
                div.detachEvent("onclick", click);
            });
            div.cloneNode(true).fireEvent("onclick");
        }

        div = document.createElement("div");
        div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";

        var fragment = document.createDocumentFragment();
        fragment.appendChild(div.firstChild);

        // WebKit doesn't clone checked state correctly in fragments
        jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;

        // Figure out if the W3C box model works as expected
        // document.body must exist before we can do this
        jQuery(function () {
            var div = document.createElement("div");
            div.style.width = div.style.paddingLeft = "1px";

            document.body.appendChild(div);
            jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;

            if ("zoom" in div.style) {
                // Check if natively block-level elements act like inline-block
                // elements when setting their display to 'inline' and giving
                // them layout
                // (IE < 8 does this)
                div.style.display = "inline";
                div.style.zoom = 1;
                jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;

                // Check if elements with layout shrink-wrap their children
                // (IE 6 does this)
                div.style.display = "";
                div.innerHTML = "<div style='width:4px;'></div>";
                jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
            }

            div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";
            var tds = div.getElementsByTagName("td");

            // Check if table cells still have offsetWidth/Height when they are set
            // to display:none and there are still other visible table cells in a
            // table row; if so, offsetWidth/Height are not reliable for use when
            // determining if an element has been hidden directly using
            // display:none (it is still safe to use offsets if a parent element is
            // hidden; don safety goggles and see bug #4512 for more information).
            // (only IE 8 fails this test)
            jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;

            tds[0].style.display = "";
            tds[1].style.display = "none";

            // Check if empty table cells still have offsetWidth/Height
            // (IE < 8 fail this test)
            jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
            div.innerHTML = "";

            document.body.removeChild(div).style.display = "none";
            div = tds = null;
        });

        // Technique from Juriy Zaytsev
        // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
        var eventSupported = function (eventName) {
            var el = document.createElement("div");
            eventName = "on" + eventName;

            var isSupported = (eventName in el);
            if (!isSupported) {
                el.setAttribute(eventName, "return;");
                isSupported = typeof el[eventName] === "function";
            }
            el = null;

            return isSupported;
        };

        jQuery.support.submitBubbles = eventSupported("submit");
        jQuery.support.changeBubbles = eventSupported("change");

        // release memory in IE
        root = script = div = all = a = null;
    })();



    var windowData = {},
	rbrace = /^(?:\{.*\}|\[.*\])$/;

    jQuery.extend({
        cache: {},

        // Please use with caution
        uuid: 0,

        // Unique for each copy of jQuery on the page	
        expando: "jQuery" + jQuery.now(),

        // The following elements throw uncatchable exceptions if you
        // attempt to add expando properties to them.
        noData: {
            "embed": true,
            // Ban all objects except for Flash (which handle expandos)
            "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
            "applet": true
        },

        data: function (elem, name, data) {
            if (!jQuery.acceptData(elem)) {
                return;
            }

            elem = elem == window ?
			windowData :
			elem;

            var isNode = elem.nodeType,
			id = isNode ? elem[jQuery.expando] : null,
			cache = jQuery.cache, thisCache;

            if (isNode && !id && typeof name === "string" && data === undefined) {
                return;
            }

            // Get the data from the object directly
            if (!isNode) {
                cache = elem;

                // Compute a unique ID for the element
            } else if (!id) {
                elem[jQuery.expando] = id = ++jQuery.uuid;
            }

            // Avoid generating a new cache unless none exists and we
            // want to manipulate it.
            if (typeof name === "object") {
                if (isNode) {
                    cache[id] = jQuery.extend(cache[id], name);

                } else {
                    jQuery.extend(cache, name);
                }

            } else if (isNode && !cache[id]) {
                cache[id] = {};
            }

            thisCache = isNode ? cache[id] : cache;

            // Prevent overriding the named cache with undefined values
            if (data !== undefined) {
                thisCache[name] = data;
            }

            return typeof name === "string" ? thisCache[name] : thisCache;
        },

        removeData: function (elem, name) {
            if (!jQuery.acceptData(elem)) {
                return;
            }

            elem = elem == window ?
			windowData :
			elem;

            var isNode = elem.nodeType,
			id = isNode ? elem[jQuery.expando] : elem,
			cache = jQuery.cache,
			thisCache = isNode ? cache[id] : id;

            // If we want to remove a specific section of the element's data
            if (name) {
                if (thisCache) {
                    // Remove the section of cache data
                    delete thisCache[name];

                    // If we've removed all the data, remove the element's cache
                    if (isNode && jQuery.isEmptyObject(thisCache)) {
                        jQuery.removeData(elem);
                    }
                }

                // Otherwise, we want to remove all of the element's data
            } else {
                if (isNode && jQuery.support.deleteExpando) {
                    delete elem[jQuery.expando];

                } else if (elem.removeAttribute) {
                    elem.removeAttribute(jQuery.expando);

                    // Completely remove the data cache
                } else if (isNode) {
                    delete cache[id];

                    // Remove all fields from the object
                } else {
                    for (var n in elem) {
                        delete elem[n];
                    }
                }
            }
        },

        // A method for determining if a DOM node can handle the data expando
        acceptData: function (elem) {
            if (elem.nodeName) {
                var match = jQuery.noData[elem.nodeName.toLowerCase()];

                if (match) {
                    return !(match === true || elem.getAttribute("classid") !== match);
                }
            }

            return true;
        }
    });

    jQuery.fn.extend({
        data: function (key, value) {
            var data = null;

            if (typeof key === "undefined") {
                if (this.length) {
                    var attr = this[0].attributes, name;
                    data = jQuery.data(this[0]);

                    for (var i = 0, l = attr.length; i < l; i++) {
                        name = attr[i].name;

                        if (name.indexOf("data-") === 0) {
                            name = name.substr(5);
                            dataAttr(this[0], name, data[name]);
                        }
                    }
                }

                return data;

            } else if (typeof key === "object") {
                return this.each(function () {
                    jQuery.data(this, key);
                });
            }

            var parts = key.split(".");
            parts[1] = parts[1] ? "." + parts[1] : "";

            if (value === undefined) {
                data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

                // Try to fetch any internally stored data first
                if (data === undefined && this.length) {
                    data = jQuery.data(this[0], key);
                    data = dataAttr(this[0], key, data);
                }

                return data === undefined && parts[1] ?
				this.data(parts[0]) :
				data;

            } else {
                return this.each(function () {
                    var $this = jQuery(this),
					args = [parts[0], value];

                    $this.triggerHandler("setData" + parts[1] + "!", args);
                    jQuery.data(this, key, value);
                    $this.triggerHandler("changeData" + parts[1] + "!", args);
                });
            }
        },

        removeData: function (key) {
            return this.each(function () {
                jQuery.removeData(this, key);
            });
        }
    });

    function dataAttr(elem, key, data) {
        // If nothing was found internally, try to fetch any
        // data from the HTML5 data-* attribute
        if (data === undefined && elem.nodeType === 1) {
            data = elem.getAttribute("data-" + key);

            if (typeof data === "string") {
                try {
                    data = data === "true" ? true :
				data === "false" ? false :
				data === "null" ? null :
				!jQuery.isNaN(data) ? parseFloat(data) :
					rbrace.test(data) ? jQuery.parseJSON(data) :
					data;
                } catch (e) { }

                // Make sure we set the data so it isn't changed later
                jQuery.data(elem, key, data);

            } else {
                data = undefined;
            }
        }

        return data;
    }




    jQuery.extend({
        queue: function (elem, type, data) {
            if (!elem) {
                return;
            }

            type = (type || "fx") + "queue";
            var q = jQuery.data(elem, type);

            // Speed up dequeue by getting out quickly if this is just a lookup
            if (!data) {
                return q || [];
            }

            if (!q || jQuery.isArray(data)) {
                q = jQuery.data(elem, type, jQuery.makeArray(data));

            } else {
                q.push(data);
            }

            return q;
        },

        dequeue: function (elem, type) {
            type = type || "fx";

            var queue = jQuery.queue(elem, type),
			fn = queue.shift();

            // If the fx queue is dequeued, always remove the progress sentinel
            if (fn === "inprogress") {
                fn = queue.shift();
            }

            if (fn) {
                // Add a progress sentinel to prevent the fx queue from being
                // automatically dequeued
                if (type === "fx") {
                    queue.unshift("inprogress");
                }

                fn.call(elem, function () {
                    jQuery.dequeue(elem, type);
                });
            }
        }
    });

    jQuery.fn.extend({
        queue: function (type, data) {
            if (typeof type !== "string") {
                data = type;
                type = "fx";
            }

            if (data === undefined) {
                return jQuery.queue(this[0], type);
            }
            return this.each(function (i) {
                var queue = jQuery.queue(this, type, data);

                if (type === "fx" && queue[0] !== "inprogress") {
                    jQuery.dequeue(this, type);
                }
            });
        },
        dequeue: function (type) {
            return this.each(function () {
                jQuery.dequeue(this, type);
            });
        },

        // Based off of the plugin by Clint Helfers, with permission.
        // http://blindsignals.com/index.php/2009/07/jquery-delay/
        delay: function (time, type) {
            time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
            type = type || "fx";

            return this.queue(type, function () {
                var elem = this;
                setTimeout(function () {
                    jQuery.dequeue(elem, type);
                }, time);
            });
        },

        clearQueue: function (type) {
            return this.queue(type || "fx", []);
        }
    });




    var rclass = /[\n\t]/g,
	rspaces = /\s+/,
	rreturn = /\r/g,
	rspecialurl = /^(?:href|src|style)$/,
	rtype = /^(?:button|input)$/i,
	rfocusable = /^(?:button|input|object|select|textarea)$/i,
	rclickable = /^a(?:rea)?$/i,
	rradiocheck = /^(?:radio|checkbox)$/i;

    jQuery.props = {
        "for": "htmlFor",
        "class": "className",
        readonly: "readOnly",
        maxlength: "maxLength",
        cellspacing: "cellSpacing",
        rowspan: "rowSpan",
        colspan: "colSpan",
        tabindex: "tabIndex",
        usemap: "useMap",
        frameborder: "frameBorder"
    };

    jQuery.fn.extend({
        attr: function (name, value) {
            return jQuery.access(this, name, value, true, jQuery.attr);
        },

        removeAttr: function (name, fn) {
            return this.each(function () {
                jQuery.attr(this, name, "");
                if (this.nodeType === 1) {
                    this.removeAttribute(name);
                }
            });
        },

        addClass: function (value) {
            if (jQuery.isFunction(value)) {
                return this.each(function (i) {
                    var self = jQuery(this);
                    self.addClass(value.call(this, i, self.attr("class")));
                });
            }

            if (value && typeof value === "string") {
                var classNames = (value || "").split(rspaces);

                for (var i = 0, l = this.length; i < l; i++) {
                    var elem = this[i];

                    if (elem.nodeType === 1) {
                        if (!elem.className) {
                            elem.className = value;

                        } else {
                            var className = " " + elem.className + " ",
							setClass = elem.className;

                            for (var c = 0, cl = classNames.length; c < cl; c++) {
                                if (className.indexOf(" " + classNames[c] + " ") < 0) {
                                    setClass += " " + classNames[c];
                                }
                            }
                            elem.className = jQuery.trim(setClass);
                        }
                    }
                }
            }

            return this;
        },

        removeClass: function (value) {
            if (jQuery.isFunction(value)) {
                return this.each(function (i) {
                    var self = jQuery(this);
                    self.removeClass(value.call(this, i, self.attr("class")));
                });
            }

            if ((value && typeof value === "string") || value === undefined) {
                var classNames = (value || "").split(rspaces);

                for (var i = 0, l = this.length; i < l; i++) {
                    var elem = this[i];

                    if (elem.nodeType === 1 && elem.className) {
                        if (value) {
                            var className = (" " + elem.className + " ").replace(rclass, " ");
                            for (var c = 0, cl = classNames.length; c < cl; c++) {
                                className = className.replace(" " + classNames[c] + " ", " ");
                            }
                            elem.className = jQuery.trim(className);

                        } else {
                            elem.className = "";
                        }
                    }
                }
            }

            return this;
        },

        toggleClass: function (value, stateVal) {
            var type = typeof value,
			isBool = typeof stateVal === "boolean";

            if (jQuery.isFunction(value)) {
                return this.each(function (i) {
                    var self = jQuery(this);
                    self.toggleClass(value.call(this, i, self.attr("class"), stateVal), stateVal);
                });
            }

            return this.each(function () {
                if (type === "string") {
                    // toggle individual class names
                    var className,
					i = 0,
					self = jQuery(this),
					state = stateVal,
					classNames = value.split(rspaces);

                    while ((className = classNames[i++])) {
                        // check each className given, space seperated list
                        state = isBool ? state : !self.hasClass(className);
                        self[state ? "addClass" : "removeClass"](className);
                    }

                } else if (type === "undefined" || type === "boolean") {
                    if (this.className) {
                        // store className if set
                        jQuery.data(this, "__className__", this.className);
                    }

                    // toggle whole className
                    this.className = this.className || value === false ? "" : jQuery.data(this, "__className__") || "";
                }
            });
        },

        hasClass: function (selector) {
            var className = " " + selector + " ";
            for (var i = 0, l = this.length; i < l; i++) {
                if ((" " + this[i].className + " ").replace(rclass, " ").indexOf(className) > -1) {
                    return true;
                }
            }

            return false;
        },

        val: function (value) {
            if (!arguments.length) {
                var elem = this[0];

                if (elem) {
                    if (jQuery.nodeName(elem, "option")) {
                        // attributes.value is undefined in Blackberry 4.7 but
                        // uses .value. See #6932
                        var val = elem.attributes.value;
                        return !val || val.specified ? elem.value : elem.text;
                    }

                    // We need to handle select boxes special
                    if (jQuery.nodeName(elem, "select")) {
                        var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type === "select-one";

                        // Nothing was selected
                        if (index < 0) {
                            return null;
                        }

                        // Loop through all the selected options
                        for (var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++) {
                            var option = options[i];

                            // Don't return options that are disabled or in a disabled optgroup
                            if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
								(!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) {

                                // Get the specific value for the option
                                value = jQuery(option).val();

                                // We don't need an array for one selects
                                if (one) {
                                    return value;
                                }

                                // Multi-Selects return an array
                                values.push(value);
                            }
                        }

                        return values;
                    }

                    // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
                    if (rradiocheck.test(elem.type) && !jQuery.support.checkOn) {
                        return elem.getAttribute("value") === null ? "on" : elem.value;
                    }


                    // Everything else, we just grab the value
                    return (elem.value || "").replace(rreturn, "");

                }

                return undefined;
            }

            var isFunction = jQuery.isFunction(value);

            return this.each(function (i) {
                var self = jQuery(this), val = value;

                if (this.nodeType !== 1) {
                    return;
                }

                if (isFunction) {
                    val = value.call(this, i, self.val());
                }

                // Treat null/undefined as ""; convert numbers to string
                if (val == null) {
                    val = "";
                } else if (typeof val === "number") {
                    val += "";
                } else if (jQuery.isArray(val)) {
                    val = jQuery.map(val, function (value) {
                        return value == null ? "" : value + "";
                    });
                }

                if (jQuery.isArray(val) && rradiocheck.test(this.type)) {
                    this.checked = jQuery.inArray(self.val(), val) >= 0;

                } else if (jQuery.nodeName(this, "select")) {
                    var values = jQuery.makeArray(val);

                    jQuery("option", this).each(function () {
                        this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0;
                    });

                    if (!values.length) {
                        this.selectedIndex = -1;
                    }

                } else {
                    this.value = val;
                }
            });
        }
    });

    jQuery.extend({
        attrFn: {
            val: true,
            css: true,
            html: true,
            text: true,
            data: true,
            width: true,
            height: true,
            offset: true
        },

        attr: function (elem, name, value, pass) {
            // don't set attributes on text and comment nodes
            if (!elem || elem.nodeType === 3 || elem.nodeType === 8) {
                return undefined;
            }

            if (pass && name in jQuery.attrFn) {
                return jQuery(elem)[name](value);
            }

            var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc(elem),
            // Whether we are setting (or getting)
			set = value !== undefined;

            // Try to normalize/fix the name
            name = notxml && jQuery.props[name] || name;

            // These attributes require special treatment
            var special = rspecialurl.test(name);

            // Safari mis-reports the default selected property of an option
            // Accessing the parent's selectedIndex property fixes it
            if (name === "selected" && !jQuery.support.optSelected) {
                var parent = elem.parentNode;
                if (parent) {
                    parent.selectedIndex;

                    // Make sure that it also works with optgroups, see #5701
                    if (parent.parentNode) {
                        parent.parentNode.selectedIndex;
                    }
                }
            }

            // If applicable, access the attribute via the DOM 0 way
            // 'in' checks fail in Blackberry 4.7 #6931
            if ((name in elem || elem[name] !== undefined) && notxml && !special) {
                if (set) {
                    // We can't allow the type property to be changed (since it causes problems in IE)
                    if (name === "type" && rtype.test(elem.nodeName) && elem.parentNode) {
                        jQuery.error("type property can't be changed");
                    }

                    if (value === null) {
                        if (elem.nodeType === 1) {
                            elem.removeAttribute(name);
                        }

                    } else {
                        elem[name] = value;
                    }
                }

                // browsers index elements by id/name on forms, give priority to attributes.
                if (jQuery.nodeName(elem, "form") && elem.getAttributeNode(name)) {
                    return elem.getAttributeNode(name).nodeValue;
                }

                // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
                // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
                if (name === "tabIndex") {
                    var attributeNode = elem.getAttributeNode("tabIndex");

                    return attributeNode && attributeNode.specified ?
					attributeNode.value :
					rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ?
						0 :
						undefined;
                }

                return elem[name];
            }

            if (!jQuery.support.style && notxml && name === "style") {
                if (set) {
                    elem.style.cssText = "" + value;
                }

                return elem.style.cssText;
            }

            if (set) {
                // convert the value to a string (all browsers do this but IE) see #1070
                elem.setAttribute(name, "" + value);
            }

            // Ensure that missing attributes return undefined
            // Blackberry 4.7 returns "" from getAttribute #6938
            if (!elem.attributes[name] && (elem.hasAttribute && !elem.hasAttribute(name))) {
                return undefined;
            }

            var attr = !jQuery.support.hrefNormalized && notxml && special ?
            // Some attributes require a special call on IE
				elem.getAttribute(name, 2) :
				elem.getAttribute(name);

            // Non-existent attributes return null, we normalize to undefined
            return attr === null ? undefined : attr;
        }
    });




    var rnamespaces = /\.(.*)$/,
	rformElems = /^(?:textarea|input|select)$/i,
	rperiod = /\./g,
	rspace = / /g,
	rescape = /[^\w\s.|`]/g,
	fcleanup = function (nm) {
	    return nm.replace(rescape, "\\$&");
	},
	focusCounts = { focusin: 0, focusout: 0 };

    /*
    * A number of helper functions used for managing events.
    * Many of the ideas behind this code originated from
    * Dean Edwards' addEvent library.
    */
    jQuery.event = {

        // Bind an event to an element
        // Original by Dean Edwards
        add: function (elem, types, handler, data) {
            if (elem.nodeType === 3 || elem.nodeType === 8) {
                return;
            }

            // For whatever reason, IE has trouble passing the window object
            // around, causing it to be cloned in the process
            if (jQuery.isWindow(elem) && (elem !== window && !elem.frameElement)) {
                elem = window;
            }

            if (handler === false) {
                handler = returnFalse;
            } else if (!handler) {
                // Fixes bug #7229. Fix recommended by jdalton
                return;
            }

            var handleObjIn, handleObj;

            if (handler.handler) {
                handleObjIn = handler;
                handler = handleObjIn.handler;
            }

            // Make sure that the function being executed has a unique ID
            if (!handler.guid) {
                handler.guid = jQuery.guid++;
            }

            // Init the element's event structure
            var elemData = jQuery.data(elem);

            // If no elemData is found then we must be trying to bind to one of the
            // banned noData elements
            if (!elemData) {
                return;
            }

            // Use a key less likely to result in collisions for plain JS objects.
            // Fixes bug #7150.
            var eventKey = elem.nodeType ? "events" : "__events__",
			events = elemData[eventKey],
			eventHandle = elemData.handle;

            if (typeof events === "function") {
                // On plain objects events is a fn that holds the the data
                // which prevents this data from being JSON serialized
                // the function does not need to be called, it just contains the data
                eventHandle = events.handle;
                events = events.events;

            } else if (!events) {
                if (!elem.nodeType) {
                    // On plain objects, create a fn that acts as the holder
                    // of the values to avoid JSON serialization of event data
                    elemData[eventKey] = elemData = function () { };
                }

                elemData.events = events = {};
            }

            if (!eventHandle) {
                elemData.handle = eventHandle = function () {
                    // Handle the second event of a trigger and when
                    // an event is called after a page has unloaded
                    return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
					jQuery.event.handle.apply(eventHandle.elem, arguments) :
					undefined;
                };
            }

            // Add elem as a property of the handle function
            // This is to prevent a memory leak with non-native events in IE.
            eventHandle.elem = elem;

            // Handle multiple events separated by a space
            // jQuery(...).bind("mouseover mouseout", fn);
            types = types.split(" ");

            var type, i = 0, namespaces;

            while ((type = types[i++])) {
                handleObj = handleObjIn ?
				jQuery.extend({}, handleObjIn) :
				{ handler: handler, data: data };

                // Namespaced event handlers
                if (type.indexOf(".") > -1) {
                    namespaces = type.split(".");
                    type = namespaces.shift();
                    handleObj.namespace = namespaces.slice(0).sort().join(".");

                } else {
                    namespaces = [];
                    handleObj.namespace = "";
                }

                handleObj.type = type;
                if (!handleObj.guid) {
                    handleObj.guid = handler.guid;
                }

                // Get the current list of functions bound to this event
                var handlers = events[type],
				special = jQuery.event.special[type] || {};

                // Init the event handler queue
                if (!handlers) {
                    handlers = events[type] = [];

                    // Check for a special event handler
                    // Only use addEventListener/attachEvent if the special
                    // events handler returns false
                    if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
                        // Bind the global event handler to the element
                        if (elem.addEventListener) {
                            elem.addEventListener(type, eventHandle, false);

                        } else if (elem.attachEvent) {
                            elem.attachEvent("on" + type, eventHandle);
                        }
                    }
                }

                if (special.add) {
                    special.add.call(elem, handleObj);

                    if (!handleObj.handler.guid) {
                        handleObj.handler.guid = handler.guid;
                    }
                }

                // Add the function to the element's handler list
                handlers.push(handleObj);

                // Keep track of which events have been used, for global triggering
                jQuery.event.global[type] = true;
            }

            // Nullify elem to prevent memory leaks in IE
            elem = null;
        },

        global: {},

        // Detach an event or set of events from an element
        remove: function (elem, types, handler, pos) {
            // don't do events on text and comment nodes
            if (elem.nodeType === 3 || elem.nodeType === 8) {
                return;
            }

            if (handler === false) {
                handler = returnFalse;
            }

            var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
			eventKey = elem.nodeType ? "events" : "__events__",
			elemData = jQuery.data(elem),
			events = elemData && elemData[eventKey];

            if (!elemData || !events) {
                return;
            }

            if (typeof events === "function") {
                elemData = events;
                events = events.events;
            }

            // types is actually an event object here
            if (types && types.type) {
                handler = types.handler;
                types = types.type;
            }

            // Unbind all events for the element
            if (!types || typeof types === "string" && types.charAt(0) === ".") {
                types = types || "";

                for (type in events) {
                    jQuery.event.remove(elem, type + types);
                }

                return;
            }

            // Handle multiple events separated by a space
            // jQuery(...).unbind("mouseover mouseout", fn);
            types = types.split(" ");

            while ((type = types[i++])) {
                origType = type;
                handleObj = null;
                all = type.indexOf(".") < 0;
                namespaces = [];

                if (!all) {
                    // Namespaced event handlers
                    namespaces = type.split(".");
                    type = namespaces.shift();

                    namespace = new RegExp("(^|\\.)" +
					jQuery.map(namespaces.slice(0).sort(), fcleanup).join("\\.(?:.*\\.)?") + "(\\.|$)");
                }

                eventType = events[type];

                if (!eventType) {
                    continue;
                }

                if (!handler) {
                    for (j = 0; j < eventType.length; j++) {
                        handleObj = eventType[j];

                        if (all || namespace.test(handleObj.namespace)) {
                            jQuery.event.remove(elem, origType, handleObj.handler, j);
                            eventType.splice(j--, 1);
                        }
                    }

                    continue;
                }

                special = jQuery.event.special[type] || {};

                for (j = pos || 0; j < eventType.length; j++) {
                    handleObj = eventType[j];

                    if (handler.guid === handleObj.guid) {
                        // remove the given handler for the given type
                        if (all || namespace.test(handleObj.namespace)) {
                            if (pos == null) {
                                eventType.splice(j--, 1);
                            }

                            if (special.remove) {
                                special.remove.call(elem, handleObj);
                            }
                        }

                        if (pos != null) {
                            break;
                        }
                    }
                }

                // remove generic event handler if no more handlers exist
                if (eventType.length === 0 || pos != null && eventType.length === 1) {
                    if (!special.teardown || special.teardown.call(elem, namespaces) === false) {
                        jQuery.removeEvent(elem, type, elemData.handle);
                    }

                    ret = null;
                    delete events[type];
                }
            }

            // Remove the expando if it's no longer used
            if (jQuery.isEmptyObject(events)) {
                var handle = elemData.handle;
                if (handle) {
                    handle.elem = null;
                }

                delete elemData.events;
                delete elemData.handle;

                if (typeof elemData === "function") {
                    jQuery.removeData(elem, eventKey);

                } else if (jQuery.isEmptyObject(elemData)) {
                    jQuery.removeData(elem);
                }
            }
        },

        // bubbling is internal
        trigger: function (event, data, elem /*, bubbling */) {
            // Event object or event type
            var type = event.type || event,
			bubbling = arguments[3];

            if (!bubbling) {
                event = typeof event === "object" ?
                // jQuery.Event object
				event[jQuery.expando] ? event :
                // Object literal
				jQuery.extend(jQuery.Event(type), event) :
                // Just the event type (string)
				jQuery.Event(type);

                if (type.indexOf("!") >= 0) {
                    event.type = type = type.slice(0, -1);
                    event.exclusive = true;
                }

                // Handle a global trigger
                if (!elem) {
                    // Don't bubble custom events when global (to avoid too much overhead)
                    event.stopPropagation();

                    // Only trigger if we've ever bound an event for it
                    if (jQuery.event.global[type]) {
                        jQuery.each(jQuery.cache, function () {
                            if (this.events && this.events[type]) {
                                jQuery.event.trigger(event, data, this.handle.elem);
                            }
                        });
                    }
                }

                // Handle triggering a single element

                // don't do events on text and comment nodes
                if (!elem || elem.nodeType === 3 || elem.nodeType === 8) {
                    return undefined;
                }

                // Clean up in case it is reused
                event.result = undefined;
                event.target = elem;

                // Clone the incoming data, if any
                data = jQuery.makeArray(data);
                data.unshift(event);
            }

            event.currentTarget = elem;

            // Trigger the event, it is assumed that "handle" is a function
            var handle = elem.nodeType ?
			jQuery.data(elem, "handle") :
			(jQuery.data(elem, "__events__") || {}).handle;

            if (handle) {
                handle.apply(elem, data);
            }

            var parent = elem.parentNode || elem.ownerDocument;

            // Trigger an inline bound script
            try {
                if (!(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()])) {
                    if (elem["on" + type] && elem["on" + type].apply(elem, data) === false) {
                        event.result = false;
                        event.preventDefault();
                    }
                }

                // prevent IE from throwing an error for some elements with some event types, see #3533
            } catch (inlineError) { }

            if (!event.isPropagationStopped() && parent) {
                jQuery.event.trigger(event, data, parent, true);

            } else if (!event.isDefaultPrevented()) {
                var old,
				target = event.target,
				targetType = type.replace(rnamespaces, ""),
				isClick = jQuery.nodeName(target, "a") && targetType === "click",
				special = jQuery.event.special[targetType] || {};

                if ((!special._default || special._default.call(elem, event) === false) &&
				!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()])) {

                    try {
                        if (target[targetType]) {
                            // Make sure that we don't accidentally re-trigger the onFOO events
                            old = target["on" + targetType];

                            if (old) {
                                target["on" + targetType] = null;
                            }

                            jQuery.event.triggered = true;
                            target[targetType]();
                        }

                        // prevent IE from throwing an error for some elements with some event types, see #3533
                    } catch (triggerError) { }

                    if (old) {
                        target["on" + targetType] = old;
                    }

                    jQuery.event.triggered = false;
                }
            }
        },

        handle: function (event) {
            var all, handlers, namespaces, namespace_re, events,
			namespace_sort = [],
			args = jQuery.makeArray(arguments);

            event = args[0] = jQuery.event.fix(event || window.event);
            event.currentTarget = this;

            // Namespaced event handlers
            all = event.type.indexOf(".") < 0 && !event.exclusive;

            if (!all) {
                namespaces = event.type.split(".");
                event.type = namespaces.shift();
                namespace_sort = namespaces.slice(0).sort();
                namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
            }

            event.namespace = event.namespace || namespace_sort.join(".");

            events = jQuery.data(this, this.nodeType ? "events" : "__events__");

            if (typeof events === "function") {
                events = events.events;
            }

            handlers = (events || {})[event.type];

            if (events && handlers) {
                // Clone the handlers to prevent manipulation
                handlers = handlers.slice(0);

                for (var j = 0, l = handlers.length; j < l; j++) {
                    var handleObj = handlers[j];

                    // Filter the functions by class
                    if (all || namespace_re.test(handleObj.namespace)) {
                        // Pass in a reference to the handler function itself
                        // So that we can later remove it
                        event.handler = handleObj.handler;
                        event.data = handleObj.data;
                        event.handleObj = handleObj;

                        var ret = handleObj.handler.apply(this, args);

                        if (ret !== undefined) {
                            event.result = ret;
                            if (ret === false) {
                                event.preventDefault();
                                event.stopPropagation();
                            }
                        }

                        if (event.isImmediatePropagationStopped()) {
                            break;
                        }
                    }
                }
            }

            return event.result;
        },

        props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

        fix: function (event) {
            if (event[jQuery.expando]) {
                return event;
            }

            // store a copy of the original event object
            // and "clone" to set read-only properties
            var originalEvent = event;
            event = jQuery.Event(originalEvent);

            for (var i = this.props.length, prop; i; ) {
                prop = this.props[--i];
                event[prop] = originalEvent[prop];
            }

            // Fix target property, if necessary
            if (!event.target) {
                // Fixes #1925 where srcElement might not be defined either
                event.target = event.srcElement || document;
            }

            // check if target is a textnode (safari)
            if (event.target.nodeType === 3) {
                event.target = event.target.parentNode;
            }

            // Add relatedTarget, if necessary
            if (!event.relatedTarget && event.fromElement) {
                event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
            }

            // Calculate pageX/Y if missing and clientX/Y available
            if (event.pageX == null && event.clientX != null) {
                var doc = document.documentElement,
				body = document.body;

                event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
            }

            // Add which for key events
            if (event.which == null && (event.charCode != null || event.keyCode != null)) {
                event.which = event.charCode != null ? event.charCode : event.keyCode;
            }

            // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
            if (!event.metaKey && event.ctrlKey) {
                event.metaKey = event.ctrlKey;
            }

            // Add which for click: 1 === left; 2 === middle; 3 === right
            // Note: button is not normalized, so don't use it
            if (!event.which && event.button !== undefined) {
                event.which = (event.button & 1 ? 1 : (event.button & 2 ? 3 : (event.button & 4 ? 2 : 0)));
            }

            return event;
        },

        // Deprecated, use jQuery.guid instead
        guid: 1E8,

        // Deprecated, use jQuery.proxy instead
        proxy: jQuery.proxy,

        special: {
            ready: {
                // Make sure the ready event is setup
                setup: jQuery.bindReady,
                teardown: jQuery.noop
            },

            live: {
                add: function (handleObj) {
                    jQuery.event.add(this,
					liveConvert(handleObj.origType, handleObj.selector),
					jQuery.extend({}, handleObj, { handler: liveHandler, guid: handleObj.handler.guid }));
                },

                remove: function (handleObj) {
                    jQuery.event.remove(this, liveConvert(handleObj.origType, handleObj.selector), handleObj);
                }
            },

            beforeunload: {
                setup: function (data, namespaces, eventHandle) {
                    // We only want to do this special case on windows
                    if (jQuery.isWindow(this)) {
                        this.onbeforeunload = eventHandle;
                    }
                },

                teardown: function (namespaces, eventHandle) {
                    if (this.onbeforeunload === eventHandle) {
                        this.onbeforeunload = null;
                    }
                }
            }
        }
    };

    jQuery.removeEvent = document.removeEventListener ?
	function (elem, type, handle) {
	    if (elem.removeEventListener) {
	        elem.removeEventListener(type, handle, false);
	    }
	} :
	function (elem, type, handle) {
	    if (elem.detachEvent) {
	        elem.detachEvent("on" + type, handle);
	    }
	};

    jQuery.Event = function (src) {
        // Allow instantiation without the 'new' keyword
        if (!this.preventDefault) {
            return new jQuery.Event(src);
        }

        // Event object
        if (src && src.type) {
            this.originalEvent = src;
            this.type = src.type;
            // Event type
        } else {
            this.type = src;
        }

        // timeStamp is buggy for some events on Firefox(#3843)
        // So we won't rely on the native value
        this.timeStamp = jQuery.now();

        // Mark it as fixed
        this[jQuery.expando] = true;
    };

    function returnFalse() {
        return false;
    }
    function returnTrue() {
        return true;
    }

    // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
    // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
    jQuery.Event.prototype = {
        preventDefault: function () {
            this.isDefaultPrevented = returnTrue;

            var e = this.originalEvent;
            if (!e) {
                return;
            }

            // if preventDefault exists run it on the original event
            if (e.preventDefault) {
                e.preventDefault();

                // otherwise set the returnValue property of the original event to false (IE)
            } else {
                e.returnValue = false;
            }
        },
        stopPropagation: function () {
            this.isPropagationStopped = returnTrue;

            var e = this.originalEvent;
            if (!e) {
                return;
            }
            // if stopPropagation exists run it on the original event
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            // otherwise set the cancelBubble property of the original event to true (IE)
            e.cancelBubble = true;
        },
        stopImmediatePropagation: function () {
            this.isImmediatePropagationStopped = returnTrue;
            this.stopPropagation();
        },
        isDefaultPrevented: returnFalse,
        isPropagationStopped: returnFalse,
        isImmediatePropagationStopped: returnFalse
    };

    // Checks if an event happened on an element within another element
    // Used in jQuery.event.special.mouseenter and mouseleave handlers
    var withinElement = function (event) {
        // Check if mouse(over|out) are still within the same parent element
        var parent = event.relatedTarget;

        // Firefox sometimes assigns relatedTarget a XUL element
        // which we cannot access the parentNode property of
        try {
            // Traverse up the tree
            while (parent && parent !== this) {
                parent = parent.parentNode;
            }

            if (parent !== this) {
                // set the correct event type
                event.type = event.data;

                // handle event if we actually just moused on to a non sub-element
                jQuery.event.handle.apply(this, arguments);
            }

            // assuming we've left the element since we most likely mousedover a xul element
        } catch (e) { }
    },

    // In case of event delegation, we only need to rename the event.type,
    // liveHandler will take care of the rest.
delegate = function (event) {
    event.type = event.data;
    jQuery.event.handle.apply(this, arguments);
};

    // Create mouseenter and mouseleave events
    jQuery.each({
        mouseenter: "mouseover",
        mouseleave: "mouseout"
    }, function (orig, fix) {
        jQuery.event.special[orig] = {
            setup: function (data) {
                jQuery.event.add(this, fix, data && data.selector ? delegate : withinElement, orig);
            },
            teardown: function (data) {
                jQuery.event.remove(this, fix, data && data.selector ? delegate : withinElement);
            }
        };
    });

    // submit delegation
    if (!jQuery.support.submitBubbles) {

        jQuery.event.special.submit = {
            setup: function (data, namespaces) {
                if (this.nodeName.toLowerCase() !== "form") {
                    jQuery.event.add(this, "click.specialSubmit", function (e) {
                        var elem = e.target,
						type = elem.type;

                        if ((type === "submit" || type === "image") && jQuery(elem).closest("form").length) {
                            e.liveFired = undefined;
                            return trigger("submit", this, arguments);
                        }
                    });

                    jQuery.event.add(this, "keypress.specialSubmit", function (e) {
                        var elem = e.target,
						type = elem.type;

                        if ((type === "text" || type === "password") && jQuery(elem).closest("form").length && e.keyCode === 13) {
                            e.liveFired = undefined;
                            return trigger("submit", this, arguments);
                        }
                    });

                } else {
                    return false;
                }
            },

            teardown: function (namespaces) {
                jQuery.event.remove(this, ".specialSubmit");
            }
        };

    }

    // change delegation, happens here so we have bind.
    if (!jQuery.support.changeBubbles) {

        var changeFilters,

	getVal = function (elem) {
	    var type = elem.type, val = elem.value;

	    if (type === "radio" || type === "checkbox") {
	        val = elem.checked;

	    } else if (type === "select-multiple") {
	        val = elem.selectedIndex > -1 ?
				jQuery.map(elem.options, function (elem) {
				    return elem.selected;
				}).join("-") :
				"";

	    } else if (elem.nodeName.toLowerCase() === "select") {
	        val = elem.selectedIndex;
	    }

	    return val;
	},

	testChange = function testChange(e) {
	    var elem = e.target, data, val;

	    if (!rformElems.test(elem.nodeName) || elem.readOnly) {
	        return;
	    }

	    data = jQuery.data(elem, "_change_data");
	    val = getVal(elem);

	    // the current data will be also retrieved by beforeactivate
	    if (e.type !== "focusout" || elem.type !== "radio") {
	        jQuery.data(elem, "_change_data", val);
	    }

	    if (data === undefined || val === data) {
	        return;
	    }

	    if (data != null || val) {
	        e.type = "change";
	        e.liveFired = undefined;
	        return jQuery.event.trigger(e, arguments[1], elem);
	    }
	};

        jQuery.event.special.change = {
            filters: {
                focusout: testChange,

                beforedeactivate: testChange,

                click: function (e) {
                    var elem = e.target, type = elem.type;

                    if (type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select") {
                        return testChange.call(this, e);
                    }
                },

                // Change has to be called before submit
                // Keydown will be called before keypress, which is used in submit-event delegation
                keydown: function (e) {
                    var elem = e.target, type = elem.type;

                    if ((e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
					(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
					type === "select-multiple") {
                        return testChange.call(this, e);
                    }
                },

                // Beforeactivate happens also before the previous element is blurred
                // with this event you can't trigger a change event, but you can store
                // information
                beforeactivate: function (e) {
                    var elem = e.target;
                    jQuery.data(elem, "_change_data", getVal(elem));
                }
            },

            setup: function (data, namespaces) {
                if (this.type === "file") {
                    return false;
                }

                for (var type in changeFilters) {
                    jQuery.event.add(this, type + ".specialChange", changeFilters[type]);
                }

                return rformElems.test(this.nodeName);
            },

            teardown: function (namespaces) {
                jQuery.event.remove(this, ".specialChange");

                return rformElems.test(this.nodeName);
            }
        };

        changeFilters = jQuery.event.special.change.filters;

        // Handle when the input is .focus()'d
        changeFilters.focus = changeFilters.beforeactivate;
    }

    function trigger(type, elem, args) {
        args[0].type = type;
        return jQuery.event.handle.apply(elem, args);
    }

    // Create "bubbling" focus and blur events
    if (document.addEventListener) {
        jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
            jQuery.event.special[fix] = {
                setup: function () {
                    if (focusCounts[fix]++ === 0) {
                        document.addEventListener(orig, handler, true);
                    }
                },
                teardown: function () {
                    if (--focusCounts[fix] === 0) {
                        document.removeEventListener(orig, handler, true);
                    }
                }
            };

            function handler(e) {
                e = jQuery.event.fix(e);
                e.type = fix;
                return jQuery.event.trigger(e, null, e.target);
            }
        });
    }

    jQuery.each(["bind", "one"], function (i, name) {
        jQuery.fn[name] = function (type, data, fn) {
            // Handle object literals
            if (typeof type === "object") {
                for (var key in type) {
                    this[name](key, data, type[key], fn);
                }
                return this;
            }

            if (jQuery.isFunction(data) || data === false) {
                fn = data;
                data = undefined;
            }

            var handler = name === "one" ? jQuery.proxy(fn, function (event) {
                jQuery(this).unbind(event, handler);
                return fn.apply(this, arguments);
            }) : fn;

            if (type === "unload" && name !== "one") {
                this.one(type, data, fn);

            } else {
                for (var i = 0, l = this.length; i < l; i++) {
                    jQuery.event.add(this[i], type, handler, data);
                }
            }

            return this;
        };
    });

    jQuery.fn.extend({
        unbind: function (type, fn) {
            // Handle object literals
            if (typeof type === "object" && !type.preventDefault) {
                for (var key in type) {
                    this.unbind(key, type[key]);
                }

            } else {
                for (var i = 0, l = this.length; i < l; i++) {
                    jQuery.event.remove(this[i], type, fn);
                }
            }

            return this;
        },

        delegate: function (selector, types, data, fn) {
            return this.live(types, data, fn, selector);
        },

        undelegate: function (selector, types, fn) {
            if (arguments.length === 0) {
                return this.unbind("live");

            } else {
                return this.die(types, null, fn, selector);
            }
        },

        trigger: function (type, data) {
            return this.each(function () {
                jQuery.event.trigger(type, data, this);
            });
        },

        triggerHandler: function (type, data) {
            if (this[0]) {
                var event = jQuery.Event(type);
                event.preventDefault();
                event.stopPropagation();
                jQuery.event.trigger(event, data, this[0]);
                return event.result;
            }
        },

        toggle: function (fn) {
            // Save reference to arguments for access in closure
            var args = arguments,
			i = 1;

            // link all the functions, so any of them can unbind this click handler
            while (i < args.length) {
                jQuery.proxy(fn, args[i++]);
            }

            return this.click(jQuery.proxy(fn, function (event) {
                // Figure out which function to execute
                var lastToggle = (jQuery.data(this, "lastToggle" + fn.guid) || 0) % i;
                jQuery.data(this, "lastToggle" + fn.guid, lastToggle + 1);

                // Make sure that clicks stop
                event.preventDefault();

                // and execute the function
                return args[lastToggle].apply(this, arguments) || false;
            }));
        },

        hover: function (fnOver, fnOut) {
            return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
        }
    });

    var liveMap = {
        focus: "focusin",
        blur: "focusout",
        mouseenter: "mouseover",
        mouseleave: "mouseout"
    };

    jQuery.each(["live", "die"], function (i, name) {
        jQuery.fn[name] = function (types, data, fn, origSelector /* Internal Use Only */) {
            var type, i = 0, match, namespaces, preType,
			selector = origSelector || this.selector,
			context = origSelector ? this : jQuery(this.context);

            if (typeof types === "object" && !types.preventDefault) {
                for (var key in types) {
                    context[name](key, data, types[key], selector);
                }

                return this;
            }

            if (jQuery.isFunction(data)) {
                fn = data;
                data = undefined;
            }

            types = (types || "").split(" ");

            while ((type = types[i++]) != null) {
                match = rnamespaces.exec(type);
                namespaces = "";

                if (match) {
                    namespaces = match[0];
                    type = type.replace(rnamespaces, "");
                }

                if (type === "hover") {
                    types.push("mouseenter" + namespaces, "mouseleave" + namespaces);
                    continue;
                }

                preType = type;

                if (type === "focus" || type === "blur") {
                    types.push(liveMap[type] + namespaces);
                    type = type + namespaces;

                } else {
                    type = (liveMap[type] || type) + namespaces;
                }

                if (name === "live") {
                    // bind live handler
                    for (var j = 0, l = context.length; j < l; j++) {
                        jQuery.event.add(context[j], "live." + liveConvert(type, selector),
						{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType });
                    }

                } else {
                    // unbind live handler
                    context.unbind("live." + liveConvert(type, selector), fn);
                }
            }

            return this;
        };
    });

    function liveHandler(event) {
        var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
		elems = [],
		selectors = [],
		events = jQuery.data(this, this.nodeType ? "events" : "__events__");

        if (typeof events === "function") {
            events = events.events;
        }

        // Make sure we avoid non-left-click bubbling in Firefox (#3861)
        if (event.liveFired === this || !events || !events.live || event.button && event.type === "click") {
            return;
        }

        if (event.namespace) {
            namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
        }

        event.liveFired = this;

        var live = events.live.slice(0);

        for (j = 0; j < live.length; j++) {
            handleObj = live[j];

            if (handleObj.origType.replace(rnamespaces, "") === event.type) {
                selectors.push(handleObj.selector);

            } else {
                live.splice(j--, 1);
            }
        }

        match = jQuery(event.target).closest(selectors, event.currentTarget);

        for (i = 0, l = match.length; i < l; i++) {
            close = match[i];

            for (j = 0; j < live.length; j++) {
                handleObj = live[j];

                if (close.selector === handleObj.selector && (!namespace || namespace.test(handleObj.namespace))) {
                    elem = close.elem;
                    related = null;

                    // Those two events require additional checking
                    if (handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave") {
                        event.type = handleObj.preType;
                        related = jQuery(event.relatedTarget).closest(handleObj.selector)[0];
                    }

                    if (!related || related !== elem) {
                        elems.push({ elem: elem, handleObj: handleObj, level: close.level });
                    }
                }
            }
        }

        for (i = 0, l = elems.length; i < l; i++) {
            match = elems[i];

            if (maxLevel && match.level > maxLevel) {
                break;
            }

            event.currentTarget = match.elem;
            event.data = match.handleObj.data;
            event.handleObj = match.handleObj;

            ret = match.handleObj.origHandler.apply(match.elem, arguments);

            if (ret === false || event.isPropagationStopped()) {
                maxLevel = match.level;

                if (ret === false) {
                    stop = false;
                }
                if (event.isImmediatePropagationStopped()) {
                    break;
                }
            }
        }

        return stop;
    }

    function liveConvert(type, selector) {
        return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
    }

    jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error").split(" "), function (i, name) {

	    // Handle event binding
	    jQuery.fn[name] = function (data, fn) {
	        if (fn == null) {
	            fn = data;
	            data = null;
	        }

	        return arguments.length > 0 ?
			this.bind(name, data, fn) :
			this.trigger(name);
	    };

	    if (jQuery.attrFn) {
	        jQuery.attrFn[name] = true;
	    }
	});

    // Prevent memory leaks in IE
    // Window isn't included so as not to unbind existing unload events
    // More info:
    //  - http://isaacschlueter.com/2006/10/msie-memory-leaks/
    if (window.attachEvent && !window.addEventListener) {
        jQuery(window).bind("unload", function () {
            for (var id in jQuery.cache) {
                if (jQuery.cache[id].handle) {
                    // Try/Catch is to handle iframes being unloaded, see #4280
                    try {
                        jQuery.event.remove(jQuery.cache[id].handle.elem);
                    } catch (e) { }
                }
            }
        });
    }


    /*!
    * Sizzle CSS Selector Engine - v1.0
    *  Copyright 2009, The Dojo Foundation
    *  Released under the MIT, BSD, and GPL Licenses.
    *  More information: http://sizzlejs.com/
    */
    (function () {

        var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
	done = 0,
	toString = Object.prototype.toString,
	hasDuplicate = false,
	baseHasDuplicate = true;

        // Here we check if the JavaScript engine is using some sort of
        // optimization where it does not always call our comparision
        // function. If that is the case, discard the hasDuplicate value.
        //   Thus far that includes Google Chrome.
        [0, 0].sort(function () {
            baseHasDuplicate = false;
            return 0;
        });

        var Sizzle = function (selector, context, results, seed) {
            results = results || [];
            context = context || document;

            var origContext = context;

            if (context.nodeType !== 1 && context.nodeType !== 9) {
                return [];
            }

            if (!selector || typeof selector !== "string") {
                return results;
            }

            var m, set, checkSet, extra, ret, cur, pop, i,
		prune = true,
		contextXML = Sizzle.isXML(context),
		parts = [],
		soFar = selector;

            // Reset the position of the chunker regexp (start from head)
            do {
                chunker.exec("");
                m = chunker.exec(soFar);

                if (m) {
                    soFar = m[3];

                    parts.push(m[1]);

                    if (m[2]) {
                        extra = m[3];
                        break;
                    }
                }
            } while (m);

            if (parts.length > 1 && origPOS.exec(selector)) {

                if (parts.length === 2 && Expr.relative[parts[0]]) {
                    set = posProcess(parts[0] + parts[1], context);

                } else {
                    set = Expr.relative[parts[0]] ?
				[context] :
				Sizzle(parts.shift(), context);

                    while (parts.length) {
                        selector = parts.shift();

                        if (Expr.relative[selector]) {
                            selector += parts.shift();
                        }

                        set = posProcess(selector, set);
                    }
                }

            } else {
                // Take a shortcut and set the context if the root selector is an ID
                // (but not if it'll be faster if the inner selector is an ID)
                if (!seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1])) {

                    ret = Sizzle.find(parts.shift(), context, contextXML);
                    context = ret.expr ?
				Sizzle.filter(ret.expr, ret.set)[0] :
				ret.set[0];
                }

                if (context) {
                    ret = seed ?
				{ expr: parts.pop(), set: makeArray(seed)} :
				Sizzle.find(parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML);

                    set = ret.expr ?
				Sizzle.filter(ret.expr, ret.set) :
				ret.set;

                    if (parts.length > 0) {
                        checkSet = makeArray(set);

                    } else {
                        prune = false;
                    }

                    while (parts.length) {
                        cur = parts.pop();
                        pop = cur;

                        if (!Expr.relative[cur]) {
                            cur = "";
                        } else {
                            pop = parts.pop();
                        }

                        if (pop == null) {
                            pop = context;
                        }

                        Expr.relative[cur](checkSet, pop, contextXML);
                    }

                } else {
                    checkSet = parts = [];
                }
            }

            if (!checkSet) {
                checkSet = set;
            }

            if (!checkSet) {
                Sizzle.error(cur || selector);
            }

            if (toString.call(checkSet) === "[object Array]") {
                if (!prune) {
                    results.push.apply(results, checkSet);

                } else if (context && context.nodeType === 1) {
                    for (i = 0; checkSet[i] != null; i++) {
                        if (checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i]))) {
                            results.push(set[i]);
                        }
                    }

                } else {
                    for (i = 0; checkSet[i] != null; i++) {
                        if (checkSet[i] && checkSet[i].nodeType === 1) {
                            results.push(set[i]);
                        }
                    }
                }

            } else {
                makeArray(checkSet, results);
            }

            if (extra) {
                Sizzle(extra, origContext, results, seed);
                Sizzle.uniqueSort(results);
            }

            return results;
        };

        Sizzle.uniqueSort = function (results) {
            if (sortOrder) {
                hasDuplicate = baseHasDuplicate;
                results.sort(sortOrder);

                if (hasDuplicate) {
                    for (var i = 1; i < results.length; i++) {
                        if (results[i] === results[i - 1]) {
                            results.splice(i--, 1);
                        }
                    }
                }
            }

            return results;
        };

        Sizzle.matches = function (expr, set) {
            return Sizzle(expr, null, null, set);
        };

        Sizzle.matchesSelector = function (node, expr) {
            return Sizzle(expr, null, null, [node]).length > 0;
        };

        Sizzle.find = function (expr, context, isXML) {
            var set;

            if (!expr) {
                return [];
            }

            for (var i = 0, l = Expr.order.length; i < l; i++) {
                var match,
			type = Expr.order[i];

                if ((match = Expr.leftMatch[type].exec(expr))) {
                    var left = match[1];
                    match.splice(1, 1);

                    if (left.substr(left.length - 1) !== "\\") {
                        match[1] = (match[1] || "").replace(/\\/g, "");
                        set = Expr.find[type](match, context, isXML);

                        if (set != null) {
                            expr = expr.replace(Expr.match[type], "");
                            break;
                        }
                    }
                }
            }

            if (!set) {
                set = context.getElementsByTagName("*");
            }

            return { set: set, expr: expr };
        };

        Sizzle.filter = function (expr, set, inplace, not) {
            var match, anyFound,
		old = expr,
		result = [],
		curLoop = set,
		isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);

            while (expr && set.length) {
                for (var type in Expr.filter) {
                    if ((match = Expr.leftMatch[type].exec(expr)) != null && match[2]) {
                        var found, item,
					filter = Expr.filter[type],
					left = match[1];

                        anyFound = false;

                        match.splice(1, 1);

                        if (left.substr(left.length - 1) === "\\") {
                            continue;
                        }

                        if (curLoop === result) {
                            result = [];
                        }

                        if (Expr.preFilter[type]) {
                            match = Expr.preFilter[type](match, curLoop, inplace, result, not, isXMLFilter);

                            if (!match) {
                                anyFound = found = true;

                            } else if (match === true) {
                                continue;
                            }
                        }

                        if (match) {
                            for (var i = 0; (item = curLoop[i]) != null; i++) {
                                if (item) {
                                    found = filter(item, match, i, curLoop);
                                    var pass = not ^ !!found;

                                    if (inplace && found != null) {
                                        if (pass) {
                                            anyFound = true;

                                        } else {
                                            curLoop[i] = false;
                                        }

                                    } else if (pass) {
                                        result.push(item);
                                        anyFound = true;
                                    }
                                }
                            }
                        }

                        if (found !== undefined) {
                            if (!inplace) {
                                curLoop = result;
                            }

                            expr = expr.replace(Expr.match[type], "");

                            if (!anyFound) {
                                return [];
                            }

                            break;
                        }
                    }
                }

                // Improper expression
                if (expr === old) {
                    if (anyFound == null) {
                        Sizzle.error(expr);

                    } else {
                        break;
                    }
                }

                old = expr;
            }

            return curLoop;
        };

        Sizzle.error = function (msg) {
            throw "Syntax error, unrecognized expression: " + msg;
        };

        var Expr = Sizzle.selectors = {
            order: ["ID", "NAME", "TAG"],

            match: {
                ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
                CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
                NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
                ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
                TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
                CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
                POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
                PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
            },

            leftMatch: {},

            attrMap: {
                "class": "className",
                "for": "htmlFor"
            },

            attrHandle: {
                href: function (elem) {
                    return elem.getAttribute("href");
                }
            },

            relative: {
                "+": function (checkSet, part) {
                    var isPartStr = typeof part === "string",
				isTag = isPartStr && !/\W/.test(part),
				isPartStrNotTag = isPartStr && !isTag;

                    if (isTag) {
                        part = part.toLowerCase();
                    }

                    for (var i = 0, l = checkSet.length, elem; i < l; i++) {
                        if ((elem = checkSet[i])) {
                            while ((elem = elem.previousSibling) && elem.nodeType !== 1) { }

                            checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
						elem || false :
						elem === part;
                        }
                    }

                    if (isPartStrNotTag) {
                        Sizzle.filter(part, checkSet, true);
                    }
                },

                ">": function (checkSet, part) {
                    var elem,
				isPartStr = typeof part === "string",
				i = 0,
				l = checkSet.length;

                    if (isPartStr && !/\W/.test(part)) {
                        part = part.toLowerCase();

                        for (; i < l; i++) {
                            elem = checkSet[i];

                            if (elem) {
                                var parent = elem.parentNode;
                                checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
                            }
                        }

                    } else {
                        for (; i < l; i++) {
                            elem = checkSet[i];

                            if (elem) {
                                checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
                            }
                        }

                        if (isPartStr) {
                            Sizzle.filter(part, checkSet, true);
                        }
                    }
                },

                "": function (checkSet, part, isXML) {
                    var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;

                    if (typeof part === "string" && !/\W/.test(part)) {
                        part = part.toLowerCase();
                        nodeCheck = part;
                        checkFn = dirNodeCheck;
                    }

                    checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
                },

                "~": function (checkSet, part, isXML) {
                    var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;

                    if (typeof part === "string" && !/\W/.test(part)) {
                        part = part.toLowerCase();
                        nodeCheck = part;
                        checkFn = dirNodeCheck;
                    }

                    checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
                }
            },

            find: {
                ID: function (match, context, isXML) {
                    if (typeof context.getElementById !== "undefined" && !isXML) {
                        var m = context.getElementById(match[1]);
                        // Check parentNode to catch when Blackberry 4.6 returns
                        // nodes that are no longer in the document #6963
                        return m && m.parentNode ? [m] : [];
                    }
                },

                NAME: function (match, context) {
                    if (typeof context.getElementsByName !== "undefined") {
                        var ret = [],
					results = context.getElementsByName(match[1]);

                        for (var i = 0, l = results.length; i < l; i++) {
                            if (results[i].getAttribute("name") === match[1]) {
                                ret.push(results[i]);
                            }
                        }

                        return ret.length === 0 ? null : ret;
                    }
                },

                TAG: function (match, context) {
                    return context.getElementsByTagName(match[1]);
                }
            },
            preFilter: {
                CLASS: function (match, curLoop, inplace, result, not, isXML) {
                    match = " " + match[1].replace(/\\/g, "") + " ";

                    if (isXML) {
                        return match;
                    }

                    for (var i = 0, elem; (elem = curLoop[i]) != null; i++) {
                        if (elem) {
                            if (not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0)) {
                                if (!inplace) {
                                    result.push(elem);
                                }

                            } else if (inplace) {
                                curLoop[i] = false;
                            }
                        }
                    }

                    return false;
                },

                ID: function (match) {
                    return match[1].replace(/\\/g, "");
                },

                TAG: function (match, curLoop) {
                    return match[1].toLowerCase();
                },

                CHILD: function (match) {
                    if (match[1] === "nth") {
                        // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
                        var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
					!/\D/.test(match[2]) && "0n+" + match[2] || match[2]);

                        // calculate the numbers (first)n+(last) including if they are negative
                        match[2] = (test[1] + (test[2] || 1)) - 0;
                        match[3] = test[3] - 0;
                    }

                    // TODO: Move to normal caching system
                    match[0] = done++;

                    return match;
                },

                ATTR: function (match, curLoop, inplace, result, not, isXML) {
                    var name = match[1].replace(/\\/g, "");

                    if (!isXML && Expr.attrMap[name]) {
                        match[1] = Expr.attrMap[name];
                    }

                    if (match[2] === "~=") {
                        match[4] = " " + match[4] + " ";
                    }

                    return match;
                },

                PSEUDO: function (match, curLoop, inplace, result, not) {
                    if (match[1] === "not") {
                        // If we're dealing with a complex expression, or a simple one
                        if ((chunker.exec(match[3]) || "").length > 1 || /^\w/.test(match[3])) {
                            match[3] = Sizzle(match[3], null, null, curLoop);

                        } else {
                            var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);

                            if (!inplace) {
                                result.push.apply(result, ret);
                            }

                            return false;
                        }

                    } else if (Expr.match.POS.test(match[0]) || Expr.match.CHILD.test(match[0])) {
                        return true;
                    }

                    return match;
                },

                POS: function (match) {
                    match.unshift(true);

                    return match;
                }
            },

            filters: {
                enabled: function (elem) {
                    return elem.disabled === false && elem.type !== "hidden";
                },

                disabled: function (elem) {
                    return elem.disabled === true;
                },

                checked: function (elem) {
                    return elem.checked === true;
                },

                selected: function (elem) {
                    // Accessing this property makes selected-by-default
                    // options in Safari work properly
                    elem.parentNode.selectedIndex;

                    return elem.selected === true;
                },

                parent: function (elem) {
                    return !!elem.firstChild;
                },

                empty: function (elem) {
                    return !elem.firstChild;
                },

                has: function (elem, i, match) {
                    return !!Sizzle(match[3], elem).length;
                },

                header: function (elem) {
                    return (/h\d/i).test(elem.nodeName);
                },

                text: function (elem) {
                    return "text" === elem.type;
                },
                radio: function (elem) {
                    return "radio" === elem.type;
                },

                checkbox: function (elem) {
                    return "checkbox" === elem.type;
                },

                file: function (elem) {
                    return "file" === elem.type;
                },
                password: function (elem) {
                    return "password" === elem.type;
                },

                submit: function (elem) {
                    return "submit" === elem.type;
                },

                image: function (elem) {
                    return "image" === elem.type;
                },

                reset: function (elem) {
                    return "reset" === elem.type;
                },

                button: function (elem) {
                    return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
                },

                input: function (elem) {
                    return (/input|select|textarea|button/i).test(elem.nodeName);
                }
            },
            setFilters: {
                first: function (elem, i) {
                    return i === 0;
                },

                last: function (elem, i, match, array) {
                    return i === array.length - 1;
                },

                even: function (elem, i) {
                    return i % 2 === 0;
                },

                odd: function (elem, i) {
                    return i % 2 === 1;
                },

                lt: function (elem, i, match) {
                    return i < match[3] - 0;
                },

                gt: function (elem, i, match) {
                    return i > match[3] - 0;
                },

                nth: function (elem, i, match) {
                    return match[3] - 0 === i;
                },

                eq: function (elem, i, match) {
                    return match[3] - 0 === i;
                }
            },
            filter: {
                PSEUDO: function (elem, match, i, array) {
                    var name = match[1],
				filter = Expr.filters[name];

                    if (filter) {
                        return filter(elem, i, match, array);

                    } else if (name === "contains") {
                        return (elem.textContent || elem.innerText || Sizzle.getText([elem]) || "").indexOf(match[3]) >= 0;

                    } else if (name === "not") {
                        var not = match[3];

                        for (var j = 0, l = not.length; j < l; j++) {
                            if (not[j] === elem) {
                                return false;
                            }
                        }

                        return true;

                    } else {
                        Sizzle.error("Syntax error, unrecognized expression: " + name);
                    }
                },

                CHILD: function (elem, match) {
                    var type = match[1],
				node = elem;

                    switch (type) {
                        case "only":
                        case "first":
                            while ((node = node.previousSibling)) {
                                if (node.nodeType === 1) {
                                    return false;
                                }
                            }

                            if (type === "first") {
                                return true;
                            }

                            node = elem;

                        case "last":
                            while ((node = node.nextSibling)) {
                                if (node.nodeType === 1) {
                                    return false;
                                }
                            }

                            return true;

                        case "nth":
                            var first = match[2],
						last = match[3];

                            if (first === 1 && last === 0) {
                                return true;
                            }

                            var doneName = match[0],
						parent = elem.parentNode;

                            if (parent && (parent.sizcache !== doneName || !elem.nodeIndex)) {
                                var count = 0;

                                for (node = parent.firstChild; node; node = node.nextSibling) {
                                    if (node.nodeType === 1) {
                                        node.nodeIndex = ++count;
                                    }
                                }

                                parent.sizcache = doneName;
                            }

                            var diff = elem.nodeIndex - last;

                            if (first === 0) {
                                return diff === 0;

                            } else {
                                return (diff % first === 0 && diff / first >= 0);
                            }
                    }
                },

                ID: function (elem, match) {
                    return elem.nodeType === 1 && elem.getAttribute("id") === match;
                },

                TAG: function (elem, match) {
                    return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
                },

                CLASS: function (elem, match) {
                    return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf(match) > -1;
                },

                ATTR: function (elem, match) {
                    var name = match[1],
				result = Expr.attrHandle[name] ?
					Expr.attrHandle[name](elem) :
					elem[name] != null ?
						elem[name] :
						elem.getAttribute(name),
				value = result + "",
				type = match[2],
				check = match[4];

                    return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value !== check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
                },

                POS: function (elem, match, i, array) {
                    var name = match[2],
				filter = Expr.setFilters[name];

                    if (filter) {
                        return filter(elem, i, match, array);
                    }
                }
            }
        };

        var origPOS = Expr.match.POS,
	fescape = function (all, num) {
	    return "\\" + (num - 0 + 1);
	};

        for (var type in Expr.match) {
            Expr.match[type] = new RegExp(Expr.match[type].source + (/(?![^\[]*\])(?![^\(]*\))/.source));
            Expr.leftMatch[type] = new RegExp(/(^(?:.|\r|\n)*?)/.source + Expr.match[type].source.replace(/\\(\d+)/g, fescape));
        }

        var makeArray = function (array, results) {
            array = Array.prototype.slice.call(array, 0);

            if (results) {
                results.push.apply(results, array);
                return results;
            }

            return array;
        };

        // Perform a simple check to determine if the browser is capable of
        // converting a NodeList to an array using builtin methods.
        // Also verifies that the returned array holds DOM nodes
        // (which is not the case in the Blackberry browser)
        try {
            Array.prototype.slice.call(document.documentElement.childNodes, 0)[0].nodeType;

            // Provide a fallback method if it does not work
        } catch (e) {
            makeArray = function (array, results) {
                var i = 0,
			ret = results || [];

                if (toString.call(array) === "[object Array]") {
                    Array.prototype.push.apply(ret, array);

                } else {
                    if (typeof array.length === "number") {
                        for (var l = array.length; i < l; i++) {
                            ret.push(array[i]);
                        }

                    } else {
                        for (; array[i]; i++) {
                            ret.push(array[i]);
                        }
                    }
                }

                return ret;
            };
        }

        var sortOrder, siblingCheck;

        if (document.documentElement.compareDocumentPosition) {
            sortOrder = function (a, b) {
                if (a === b) {
                    hasDuplicate = true;
                    return 0;
                }

                if (!a.compareDocumentPosition || !b.compareDocumentPosition) {
                    return a.compareDocumentPosition ? -1 : 1;
                }

                return a.compareDocumentPosition(b) & 4 ? -1 : 1;
            };

        } else {
            sortOrder = function (a, b) {
                var al, bl,
			ap = [],
			bp = [],
			aup = a.parentNode,
			bup = b.parentNode,
			cur = aup;

                // The nodes are identical, we can exit early
                if (a === b) {
                    hasDuplicate = true;
                    return 0;

                    // If the nodes are siblings (or identical) we can do a quick check
                } else if (aup === bup) {
                    return siblingCheck(a, b);

                    // If no parents were found then the nodes are disconnected
                } else if (!aup) {
                    return -1;

                } else if (!bup) {
                    return 1;
                }

                // Otherwise they're somewhere else in the tree so we need
                // to build up a full list of the parentNodes for comparison
                while (cur) {
                    ap.unshift(cur);
                    cur = cur.parentNode;
                }

                cur = bup;

                while (cur) {
                    bp.unshift(cur);
                    cur = cur.parentNode;
                }

                al = ap.length;
                bl = bp.length;

                // Start walking down the tree looking for a discrepancy
                for (var i = 0; i < al && i < bl; i++) {
                    if (ap[i] !== bp[i]) {
                        return siblingCheck(ap[i], bp[i]);
                    }
                }

                // We ended someplace up the tree so do a sibling check
                return i === al ?
			siblingCheck(a, bp[i], -1) :
			siblingCheck(ap[i], b, 1);
            };

            siblingCheck = function (a, b, ret) {
                if (a === b) {
                    return ret;
                }

                var cur = a.nextSibling;

                while (cur) {
                    if (cur === b) {
                        return -1;
                    }

                    cur = cur.nextSibling;
                }

                return 1;
            };
        }

        // Utility function for retreiving the text value of an array of DOM nodes
        Sizzle.getText = function (elems) {
            var ret = "", elem;

            for (var i = 0; elems[i]; i++) {
                elem = elems[i];

                // Get the text from text nodes and CDATA nodes
                if (elem.nodeType === 3 || elem.nodeType === 4) {
                    ret += elem.nodeValue;

                    // Traverse everything else, except comment nodes
                } else if (elem.nodeType !== 8) {
                    ret += Sizzle.getText(elem.childNodes);
                }
            }

            return ret;
        };

        // Check to see if the browser returns elements by name when
        // querying by getElementById (and provide a workaround)
        (function () {
            // We're going to inject a fake input element with a specified name
            var form = document.createElement("div"),
		id = "script" + (new Date()).getTime(),
		root = document.documentElement;

            form.innerHTML = "<a name='" + id + "'/>";

            // Inject it into the root element, check its status, and remove it quickly
            root.insertBefore(form, root.firstChild);

            // The workaround has to do additional checks after a getElementById
            // Which slows things down for other browsers (hence the branching)
            if (document.getElementById(id)) {
                Expr.find.ID = function (match, context, isXML) {
                    if (typeof context.getElementById !== "undefined" && !isXML) {
                        var m = context.getElementById(match[1]);

                        return m ?
					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
						[m] :
						undefined :
					[];
                    }
                };

                Expr.filter.ID = function (elem, match) {
                    var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");

                    return elem.nodeType === 1 && node && node.nodeValue === match;
                };
            }

            root.removeChild(form);

            // release memory in IE
            root = form = null;
        })();

        (function () {
            // Check to see if the browser returns only elements
            // when doing getElementsByTagName("*")

            // Create a fake element
            var div = document.createElement("div");
            div.appendChild(document.createComment(""));

            // Make sure no comments are found
            if (div.getElementsByTagName("*").length > 0) {
                Expr.find.TAG = function (match, context) {
                    var results = context.getElementsByTagName(match[1]);

                    // Filter out possible comments
                    if (match[1] === "*") {
                        var tmp = [];

                        for (var i = 0; results[i]; i++) {
                            if (results[i].nodeType === 1) {
                                tmp.push(results[i]);
                            }
                        }

                        results = tmp;
                    }

                    return results;
                };
            }

            // Check to see if an attribute returns normalized href attributes
            div.innerHTML = "<a href='#'></a>";

            if (div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#") {

                Expr.attrHandle.href = function (elem) {
                    return elem.getAttribute("href", 2);
                };
            }

            // release memory in IE
            div = null;
        })();

        if (document.querySelectorAll) {
            (function () {
                var oldSizzle = Sizzle,
			div = document.createElement("div"),
			id = "__sizzle__";

                div.innerHTML = "<p class='TEST'></p>";

                // Safari can't handle uppercase or unicode characters when
                // in quirks mode.
                if (div.querySelectorAll && div.querySelectorAll(".TEST").length === 0) {
                    return;
                }

                Sizzle = function (query, context, extra, seed) {
                    context = context || document;

                    // Make sure that attribute selectors are quoted
                    query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");

                    // Only use querySelectorAll on non-XML documents
                    // (ID selectors don't work in non-HTML documents)
                    if (!seed && !Sizzle.isXML(context)) {
                        if (context.nodeType === 9) {
                            try {
                                return makeArray(context.querySelectorAll(query), extra);
                            } catch (qsaError) { }

                            // qSA works strangely on Element-rooted queries
                            // We can work around this by specifying an extra ID on the root
                            // and working up from there (Thanks to Andrew Dupont for the technique)
                            // IE 8 doesn't work on object elements
                        } else if (context.nodeType === 1 && context.nodeName.toLowerCase() !== "object") {
                            var old = context.getAttribute("id"),
						nid = old || id;

                            if (!old) {
                                context.setAttribute("id", nid);
                            }

                            try {
                                return makeArray(context.querySelectorAll("#" + nid + " " + query), extra);

                            } catch (pseudoError) {
                            } finally {
                                if (!old) {
                                    context.removeAttribute("id");
                                }
                            }
                        }
                    }

                    return oldSizzle(query, context, extra, seed);
                };

                for (var prop in oldSizzle) {
                    Sizzle[prop] = oldSizzle[prop];
                }

                // release memory in IE
                div = null;
            })();
        }

        (function () {
            var html = document.documentElement,
		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector,
		pseudoWorks = false;

            try {
                // This should fail with an exception
                // Gecko does not error, returns false instead
                matches.call(document.documentElement, "[test!='']:sizzle");

            } catch (pseudoError) {
                pseudoWorks = true;
            }

            if (matches) {
                Sizzle.matchesSelector = function (node, expr) {
                    // Make sure that attribute selectors are quoted
                    expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");

                    if (!Sizzle.isXML(node)) {
                        try {
                            if (pseudoWorks || !Expr.match.PSEUDO.test(expr) && !/!=/.test(expr)) {
                                return matches.call(node, expr);
                            }
                        } catch (e) { }
                    }

                    return Sizzle(expr, null, null, [node]).length > 0;
                };
            }
        })();

        (function () {
            var div = document.createElement("div");

            div.innerHTML = "<div class='test e'></div><div class='test'></div>";

            // Opera can't find a second classname (in 9.6)
            // Also, make sure that getElementsByClassName actually exists
            if (!div.getElementsByClassName || div.getElementsByClassName("e").length === 0) {
                return;
            }

            // Safari caches class attributes, doesn't catch changes (in 3.2)
            div.lastChild.className = "e";

            if (div.getElementsByClassName("e").length === 1) {
                return;
            }

            Expr.order.splice(1, 0, "CLASS");
            Expr.find.CLASS = function (match, context, isXML) {
                if (typeof context.getElementsByClassName !== "undefined" && !isXML) {
                    return context.getElementsByClassName(match[1]);
                }
            };

            // release memory in IE
            div = null;
        })();

        function dirNodeCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
            for (var i = 0, l = checkSet.length; i < l; i++) {
                var elem = checkSet[i];

                if (elem) {
                    var match = false;

                    elem = elem[dir];

                    while (elem) {
                        if (elem.sizcache === doneName) {
                            match = checkSet[elem.sizset];
                            break;
                        }

                        if (elem.nodeType === 1 && !isXML) {
                            elem.sizcache = doneName;
                            elem.sizset = i;
                        }

                        if (elem.nodeName.toLowerCase() === cur) {
                            match = elem;
                            break;
                        }

                        elem = elem[dir];
                    }

                    checkSet[i] = match;
                }
            }
        }

        function dirCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
            for (var i = 0, l = checkSet.length; i < l; i++) {
                var elem = checkSet[i];

                if (elem) {
                    var match = false;

                    elem = elem[dir];

                    while (elem) {
                        if (elem.sizcache === doneName) {
                            match = checkSet[elem.sizset];
                            break;
                        }

                        if (elem.nodeType === 1) {
                            if (!isXML) {
                                elem.sizcache = doneName;
                                elem.sizset = i;
                            }

                            if (typeof cur !== "string") {
                                if (elem === cur) {
                                    match = true;
                                    break;
                                }

                            } else if (Sizzle.filter(cur, [elem]).length > 0) {
                                match = elem;
                                break;
                            }
                        }

                        elem = elem[dir];
                    }

                    checkSet[i] = match;
                }
            }
        }

        if (document.documentElement.contains) {
            Sizzle.contains = function (a, b) {
                return a !== b && (a.contains ? a.contains(b) : true);
            };

        } else if (document.documentElement.compareDocumentPosition) {
            Sizzle.contains = function (a, b) {
                return !!(a.compareDocumentPosition(b) & 16);
            };

        } else {
            Sizzle.contains = function () {
                return false;
            };
        }

        Sizzle.isXML = function (elem) {
            // documentElement is verified for cases where it doesn't yet exist
            // (such as loading iframes in IE - #4833) 
            var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;

            return documentElement ? documentElement.nodeName !== "HTML" : false;
        };

        var posProcess = function (selector, context) {
            var match,
		tmpSet = [],
		later = "",
		root = context.nodeType ? [context] : context;

            // Position selectors must be done after the filter
            // And so must :not(positional) so we move all PSEUDOs to the end
            while ((match = Expr.match.PSEUDO.exec(selector))) {
                later += match[0];
                selector = selector.replace(Expr.match.PSEUDO, "");
            }

            selector = Expr.relative[selector] ? selector + "*" : selector;

            for (var i = 0, l = root.length; i < l; i++) {
                Sizzle(selector, root[i], tmpSet);
            }

            return Sizzle.filter(later, tmpSet);
        };

        // EXPOSE
        jQuery.find = Sizzle;
        jQuery.expr = Sizzle.selectors;
        jQuery.expr[":"] = jQuery.expr.filters;
        jQuery.unique = Sizzle.uniqueSort;
        jQuery.text = Sizzle.getText;
        jQuery.isXMLDoc = Sizzle.isXML;
        jQuery.contains = Sizzle.contains;


    })();


    var runtil = /Until$/,
	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
    // Note: This RegExp should be improved, or likely pulled from Sizzle
	rmultiselector = /,/,
	isSimple = /^.[^:#\[\.,]*$/,
	slice = Array.prototype.slice,
	POS = jQuery.expr.match.POS;

    jQuery.fn.extend({
        find: function (selector) {
            var ret = this.pushStack("", "find", selector),
			length = 0;

            for (var i = 0, l = this.length; i < l; i++) {
                length = ret.length;
                jQuery.find(selector, this[i], ret);

                if (i > 0) {
                    // Make sure that the results are unique
                    for (var n = length; n < ret.length; n++) {
                        for (var r = 0; r < length; r++) {
                            if (ret[r] === ret[n]) {
                                ret.splice(n--, 1);
                                break;
                            }
                        }
                    }
                }
            }

            return ret;
        },

        has: function (target) {
            var targets = jQuery(target);
            return this.filter(function () {
                for (var i = 0, l = targets.length; i < l; i++) {
                    if (jQuery.contains(this, targets[i])) {
                        return true;
                    }
                }
            });
        },

        not: function (selector) {
            return this.pushStack(winnow(this, selector, false), "not", selector);
        },

        filter: function (selector) {
            return this.pushStack(winnow(this, selector, true), "filter", selector);
        },

        is: function (selector) {
            return !!selector && jQuery.filter(selector, this).length > 0;
        },

        closest: function (selectors, context) {
            var ret = [], i, l, cur = this[0];

            if (jQuery.isArray(selectors)) {
                var match, selector,
				matches = {},
				level = 1;

                if (cur && selectors.length) {
                    for (i = 0, l = selectors.length; i < l; i++) {
                        selector = selectors[i];

                        if (!matches[selector]) {
                            matches[selector] = jQuery.expr.match.POS.test(selector) ?
							jQuery(selector, context || this.context) :
							selector;
                        }
                    }

                    while (cur && cur.ownerDocument && cur !== context) {
                        for (selector in matches) {
                            match = matches[selector];

                            if (match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match)) {
                                ret.push({ selector: selector, elem: cur, level: level });
                            }
                        }

                        cur = cur.parentNode;
                        level++;
                    }
                }

                return ret;
            }

            var pos = POS.test(selectors) ?
			jQuery(selectors, context || this.context) : null;

            for (i = 0, l = this.length; i < l; i++) {
                cur = this[i];

                while (cur) {
                    if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) {
                        ret.push(cur);
                        break;

                    } else {
                        cur = cur.parentNode;
                        if (!cur || !cur.ownerDocument || cur === context) {
                            break;
                        }
                    }
                }
            }

            ret = ret.length > 1 ? jQuery.unique(ret) : ret;

            return this.pushStack(ret, "closest", selectors);
        },

        // Determine the position of an element within
        // the matched set of elements
        index: function (elem) {
            if (!elem || typeof elem === "string") {
                return jQuery.inArray(this[0],
                // If it receives a string, the selector is used
                // If it receives nothing, the siblings are used
				elem ? jQuery(elem) : this.parent().children());
            }
            // Locate the position of the desired element
            return jQuery.inArray(
            // If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this);
        },

        add: function (selector, context) {
            var set = typeof selector === "string" ?
				jQuery(selector, context || this.context) :
				jQuery.makeArray(selector),
			all = jQuery.merge(this.get(), set);

            return this.pushStack(isDisconnected(set[0]) || isDisconnected(all[0]) ?
			all :
			jQuery.unique(all));
        },

        andSelf: function () {
            return this.add(this.prevObject);
        }
    });

    // A painfully simple check to see if an element is disconnected
    // from a document (should be improved, where feasible).
    function isDisconnected(node) {
        return !node || !node.parentNode || node.parentNode.nodeType === 11;
    }

    jQuery.each({
        parent: function (elem) {
            var parent = elem.parentNode;
            return parent && parent.nodeType !== 11 ? parent : null;
        },
        parents: function (elem) {
            return jQuery.dir(elem, "parentNode");
        },
        parentsUntil: function (elem, i, until) {
            return jQuery.dir(elem, "parentNode", until);
        },
        next: function (elem) {
            return jQuery.nth(elem, 2, "nextSibling");
        },
        prev: function (elem) {
            return jQuery.nth(elem, 2, "previousSibling");
        },
        nextAll: function (elem) {
            return jQuery.dir(elem, "nextSibling");
        },
        prevAll: function (elem) {
            return jQuery.dir(elem, "previousSibling");
        },
        nextUntil: function (elem, i, until) {
            return jQuery.dir(elem, "nextSibling", until);
        },
        prevUntil: function (elem, i, until) {
            return jQuery.dir(elem, "previousSibling", until);
        },
        siblings: function (elem) {
            return jQuery.sibling(elem.parentNode.firstChild, elem);
        },
        children: function (elem) {
            return jQuery.sibling(elem.firstChild);
        },
        contents: function (elem) {
            return jQuery.nodeName(elem, "iframe") ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.makeArray(elem.childNodes);
        }
    }, function (name, fn) {
        jQuery.fn[name] = function (until, selector) {
            var ret = jQuery.map(this, fn, until);

            if (!runtil.test(name)) {
                selector = until;
            }

            if (selector && typeof selector === "string") {
                ret = jQuery.filter(selector, ret);
            }

            ret = this.length > 1 ? jQuery.unique(ret) : ret;

            if ((this.length > 1 || rmultiselector.test(selector)) && rparentsprev.test(name)) {
                ret = ret.reverse();
            }

            return this.pushStack(ret, name, slice.call(arguments).join(","));
        };
    });

    jQuery.extend({
        filter: function (expr, elems, not) {
            if (not) {
                expr = ":not(" + expr + ")";
            }

            return elems.length === 1 ?
			jQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [] :
			jQuery.find.matches(expr, elems);
        },

        dir: function (elem, dir, until) {
            var matched = [],
			cur = elem[dir];

            while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) {
                if (cur.nodeType === 1) {
                    matched.push(cur);
                }
                cur = cur[dir];
            }
            return matched;
        },

        nth: function (cur, result, dir, elem) {
            result = result || 1;
            var num = 0;

            for (; cur; cur = cur[dir]) {
                if (cur.nodeType === 1 && ++num === result) {
                    break;
                }
            }

            return cur;
        },

        sibling: function (n, elem) {
            var r = [];

            for (; n; n = n.nextSibling) {
                if (n.nodeType === 1 && n !== elem) {
                    r.push(n);
                }
            }

            return r;
        }
    });

    // Implement the identical functionality for filter and not
    function winnow(elements, qualifier, keep) {
        if (jQuery.isFunction(qualifier)) {
            return jQuery.grep(elements, function (elem, i) {
                var retVal = !!qualifier.call(elem, i, elem);
                return retVal === keep;
            });

        } else if (qualifier.nodeType) {
            return jQuery.grep(elements, function (elem, i) {
                return (elem === qualifier) === keep;
            });

        } else if (typeof qualifier === "string") {
            var filtered = jQuery.grep(elements, function (elem) {
                return elem.nodeType === 1;
            });

            if (isSimple.test(qualifier)) {
                return jQuery.filter(qualifier, filtered, !keep);
            } else {
                qualifier = jQuery.filter(qualifier, filtered);
            }
        }

        return jQuery.grep(elements, function (elem, i) {
            return (jQuery.inArray(elem, qualifier) >= 0) === keep;
        });
    }




    var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnocache = /<(?:script|object|embed|option|style)/i,
    // checked="checked" or checked (html5)
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	raction = /\=([^="'>\s]+\/)>/g,
	wrapMap = {
	    option: [1, "<select multiple='multiple'>", "</select>"],
	    legend: [1, "<fieldset>", "</fieldset>"],
	    thead: [1, "<table>", "</table>"],
	    tr: [2, "<table><tbody>", "</tbody></table>"],
	    td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
	    col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
	    area: [1, "<map>", "</map>"],
	    _default: [0, "", ""]
	};

    wrapMap.optgroup = wrapMap.option;
    wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
    wrapMap.th = wrapMap.td;

    // IE can't serialize <link> and <script> tags normally
    if (!jQuery.support.htmlSerialize) {
        wrapMap._default = [1, "div<div>", "</div>"];
    }

    jQuery.fn.extend({
        text: function (text) {
            if (jQuery.isFunction(text)) {
                return this.each(function (i) {
                    var self = jQuery(this);

                    self.text(text.call(this, i, self.text()));
                });
            }

            if (typeof text !== "object" && text !== undefined) {
                return this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(text));
            }

            return jQuery.text(this);
        },

        wrapAll: function (html) {
            if (jQuery.isFunction(html)) {
                return this.each(function (i) {
                    jQuery(this).wrapAll(html.call(this, i));
                });
            }

            if (this[0]) {
                // The elements to wrap the target around
                var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);

                if (this[0].parentNode) {
                    wrap.insertBefore(this[0]);
                }

                wrap.map(function () {
                    var elem = this;

                    while (elem.firstChild && elem.firstChild.nodeType === 1) {
                        elem = elem.firstChild;
                    }

                    return elem;
                }).append(this);
            }

            return this;
        },

        wrapInner: function (html) {
            if (jQuery.isFunction(html)) {
                return this.each(function (i) {
                    jQuery(this).wrapInner(html.call(this, i));
                });
            }

            return this.each(function () {
                var self = jQuery(this),
				contents = self.contents();

                if (contents.length) {
                    contents.wrapAll(html);

                } else {
                    self.append(html);
                }
            });
        },

        wrap: function (html) {
            return this.each(function () {
                jQuery(this).wrapAll(html);
            });
        },

        unwrap: function () {
            return this.parent().each(function () {
                if (!jQuery.nodeName(this, "body")) {
                    jQuery(this).replaceWith(this.childNodes);
                }
            }).end();
        },

        append: function () {
            return this.domManip(arguments, true, function (elem) {
                if (this.nodeType === 1) {
                    this.appendChild(elem);
                }
            });
        },

        prepend: function () {
            return this.domManip(arguments, true, function (elem) {
                if (this.nodeType === 1) {
                    this.insertBefore(elem, this.firstChild);
                }
            });
        },

        before: function () {
            if (this[0] && this[0].parentNode) {
                return this.domManip(arguments, false, function (elem) {
                    this.parentNode.insertBefore(elem, this);
                });
            } else if (arguments.length) {
                var set = jQuery(arguments[0]);
                set.push.apply(set, this.toArray());
                return this.pushStack(set, "before", arguments);
            }
        },

        after: function () {
            if (this[0] && this[0].parentNode) {
                return this.domManip(arguments, false, function (elem) {
                    this.parentNode.insertBefore(elem, this.nextSibling);
                });
            } else if (arguments.length) {
                var set = this.pushStack(this, "after", arguments);
                set.push.apply(set, jQuery(arguments[0]).toArray());
                return set;
            }
        },

        // keepData is for internal use only--do not document
        remove: function (selector, keepData) {
            for (var i = 0, elem; (elem = this[i]) != null; i++) {
                if (!selector || jQuery.filter(selector, [elem]).length) {
                    if (!keepData && elem.nodeType === 1) {
                        jQuery.cleanData(elem.getElementsByTagName("*"));
                        jQuery.cleanData([elem]);
                    }

                    if (elem.parentNode) {
                        elem.parentNode.removeChild(elem);
                    }
                }
            }

            return this;
        },

        empty: function () {
            for (var i = 0, elem; (elem = this[i]) != null; i++) {
                // Remove element nodes and prevent memory leaks
                if (elem.nodeType === 1) {
                    jQuery.cleanData(elem.getElementsByTagName("*"));
                }

                // Remove any remaining nodes
                while (elem.firstChild) {
                    elem.removeChild(elem.firstChild);
                }
            }

            return this;
        },

        clone: function (events) {
            // Do the clone
            var ret = this.map(function () {
                if (!jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this)) {
                    // IE copies events bound via attachEvent when
                    // using cloneNode. Calling detachEvent on the
                    // clone will also remove the events from the orignal
                    // In order to get around this, we use innerHTML.
                    // Unfortunately, this means some modifications to
                    // attributes in IE that are actually only stored
                    // as properties will not be copied (such as the
                    // the name attribute on an input).
                    var html = this.outerHTML,
					ownerDocument = this.ownerDocument;

                    if (!html) {
                        var div = ownerDocument.createElement("div");
                        div.appendChild(this.cloneNode(true));
                        html = div.innerHTML;
                    }

                    return jQuery.clean([html.replace(rinlinejQuery, "")
                    // Handle the case in IE 8 where action=/test/> self-closes a tag
					.replace(raction, '="$1">')
					.replace(rleadingWhitespace, "")], ownerDocument)[0];
                } else {
                    return this.cloneNode(true);
                }
            });

            // Copy the events from the original to the clone
            if (events === true) {
                cloneCopyEvent(this, ret);
                cloneCopyEvent(this.find("*"), ret.find("*"));
            }

            // Return the cloned set
            return ret;
        },

        html: function (value) {
            if (value === undefined) {
                return this[0] && this[0].nodeType === 1 ?
				this[0].innerHTML.replace(rinlinejQuery, "") :
				null;

                // See if we can take a shortcut and just use innerHTML
            } else if (typeof value === "string" && !rnocache.test(value) &&
			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) &&
			!wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {

                value = value.replace(rxhtmlTag, "<$1></$2>");

                try {
                    for (var i = 0, l = this.length; i < l; i++) {
                        // Remove element nodes and prevent memory leaks
                        if (this[i].nodeType === 1) {
                            jQuery.cleanData(this[i].getElementsByTagName("*"));
                            this[i].innerHTML = value;
                        }
                    }

                    // If using innerHTML throws an exception, use the fallback method
                } catch (e) {
                    this.empty().append(value);
                }

            } else if (jQuery.isFunction(value)) {
                this.each(function (i) {
                    var self = jQuery(this);

                    self.html(value.call(this, i, self.html()));
                });

            } else {
                this.empty().append(value);
            }

            return this;
        },

        replaceWith: function (value) {
            if (this[0] && this[0].parentNode) {
                // Make sure that the elements are removed from the DOM before they are inserted
                // this can help fix replacing a parent with child elements
                if (jQuery.isFunction(value)) {
                    return this.each(function (i) {
                        var self = jQuery(this), old = self.html();
                        self.replaceWith(value.call(this, i, old));
                    });
                }

                if (typeof value !== "string") {
                    value = jQuery(value).detach();
                }

                return this.each(function () {
                    var next = this.nextSibling,
					parent = this.parentNode;

                    jQuery(this).remove();

                    if (next) {
                        jQuery(next).before(value);
                    } else {
                        jQuery(parent).append(value);
                    }
                });
            } else {
                return this.pushStack(jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value);
            }
        },

        detach: function (selector) {
            return this.remove(selector, true);
        },

        domManip: function (args, table, callback) {
            var results, first, fragment, parent,
			value = args[0],
			scripts = [];

            // We can't cloneNode fragments that contain checked, in WebKit
            if (!jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test(value)) {
                return this.each(function () {
                    jQuery(this).domManip(args, table, callback, true);
                });
            }

            if (jQuery.isFunction(value)) {
                return this.each(function (i) {
                    var self = jQuery(this);
                    args[0] = value.call(this, i, table ? self.html() : undefined);
                    self.domManip(args, table, callback);
                });
            }

            if (this[0]) {
                parent = value && value.parentNode;

                // If we're in a fragment, just use that instead of building a new one
                if (jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length) {
                    results = { fragment: parent };

                } else {
                    results = jQuery.buildFragment(args, this, scripts);
                }

                fragment = results.fragment;

                if (fragment.childNodes.length === 1) {
                    first = fragment = fragment.firstChild;
                } else {
                    first = fragment.firstChild;
                }

                if (first) {
                    table = table && jQuery.nodeName(first, "tr");

                    for (var i = 0, l = this.length; i < l; i++) {
                        callback.call(
						table ?
							root(this[i], first) :
							this[i],
						i > 0 || results.cacheable || this.length > 1 ?
							fragment.cloneNode(true) :
							fragment
					);
                    }
                }

                if (scripts.length) {
                    jQuery.each(scripts, evalScript);
                }
            }

            return this;
        }
    });

    function root(elem, cur) {
        return jQuery.nodeName(elem, "table") ?
		(elem.getElementsByTagName("tbody")[0] ||
		elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
		elem;
    }

    function cloneCopyEvent(orig, ret) {
        var i = 0;

        ret.each(function () {
            if (this.nodeName !== (orig[i] && orig[i].nodeName)) {
                return;
            }

            var oldData = jQuery.data(orig[i++]),
			curData = jQuery.data(this, oldData),
			events = oldData && oldData.events;

            if (events) {
                delete curData.handle;
                curData.events = {};

                for (var type in events) {
                    for (var handler in events[type]) {
                        jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
                    }
                }
            }
        });
    }

    jQuery.buildFragment = function (args, nodes, scripts) {
        var fragment, cacheable, cacheresults,
		doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);

        // Only cache "small" (1/2 KB) strings that are associated with the main document
        // Cloning options loses the selected state, so don't cache them
        // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
        // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
        if (args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
		!rnocache.test(args[0]) && (jQuery.support.checkClone || !rchecked.test(args[0]))) {

            cacheable = true;
            cacheresults = jQuery.fragments[args[0]];
            if (cacheresults) {
                if (cacheresults !== 1) {
                    fragment = cacheresults;
                }
            }
        }

        if (!fragment) {
            fragment = doc.createDocumentFragment();
            jQuery.clean(args, doc, fragment, scripts);
        }

        if (cacheable) {
            jQuery.fragments[args[0]] = cacheresults ? fragment : 1;
        }

        return { fragment: fragment, cacheable: cacheable };
    };

    jQuery.fragments = {};

    jQuery.each({
        appendTo: "append",
        prependTo: "prepend",
        insertBefore: "before",
        insertAfter: "after",
        replaceAll: "replaceWith"
    }, function (name, original) {
        jQuery.fn[name] = function (selector) {
            var ret = [],
			insert = jQuery(selector),
			parent = this.length === 1 && this[0].parentNode;

            if (parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1) {
                insert[original](this[0]);
                return this;

            } else {
                for (var i = 0, l = insert.length; i < l; i++) {
                    var elems = (i > 0 ? this.clone(true) : this).get();
                    jQuery(insert[i])[original](elems);
                    ret = ret.concat(elems);
                }

                return this.pushStack(ret, name, insert.selector);
            }
        };
    });

    jQuery.extend({
        clean: function (elems, context, fragment, scripts) {
            context = context || document;

            // !context.createElement fails in IE with an error but returns typeof 'object'
            if (typeof context.createElement === "undefined") {
                context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
            }

            var ret = [];

            for (var i = 0, elem; (elem = elems[i]) != null; i++) {
                if (typeof elem === "number") {
                    elem += "";
                }

                if (!elem) {
                    continue;
                }

                // Convert html string into DOM nodes
                if (typeof elem === "string" && !rhtml.test(elem)) {
                    elem = context.createTextNode(elem);

                } else if (typeof elem === "string") {
                    // Fix "XHTML"-style tags in all browsers
                    elem = elem.replace(rxhtmlTag, "<$1></$2>");

                    // Trim whitespace, otherwise indexOf won't work as expected
                    var tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase(),
					wrap = wrapMap[tag] || wrapMap._default,
					depth = wrap[0],
					div = context.createElement("div");

                    // Go to html and back, then peel off extra wrappers
                    div.innerHTML = wrap[1] + elem + wrap[2];

                    // Move to the right depth
                    while (depth--) {
                        div = div.lastChild;
                    }

                    // Remove IE's autoinserted <tbody> from table fragments
                    if (!jQuery.support.tbody) {

                        // String was a <table>, *may* have spurious <tbody>
                        var hasBody = rtbody.test(elem),
						tbody = tag === "table" && !hasBody ?
							div.firstChild && div.firstChild.childNodes :

                        // String was a bare <thead> or <tfoot>
							wrap[1] === "<table>" && !hasBody ?
								div.childNodes :
								[];

                        for (var j = tbody.length - 1; j >= 0; --j) {
                            if (jQuery.nodeName(tbody[j], "tbody") && !tbody[j].childNodes.length) {
                                tbody[j].parentNode.removeChild(tbody[j]);
                            }
                        }

                    }

                    // IE completely kills leading whitespace when innerHTML is used
                    if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) {
                        div.insertBefore(context.createTextNode(rleadingWhitespace.exec(elem)[0]), div.firstChild);
                    }

                    elem = div.childNodes;
                }

                if (elem.nodeType) {
                    ret.push(elem);
                } else {
                    ret = jQuery.merge(ret, elem);
                }
            }

            if (fragment) {
                for (i = 0; ret[i]; i++) {
                    if (scripts && jQuery.nodeName(ret[i], "script") && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript")) {
                        scripts.push(ret[i].parentNode ? ret[i].parentNode.removeChild(ret[i]) : ret[i]);

                    } else {
                        if (ret[i].nodeType === 1) {
                            ret.splice.apply(ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))));
                        }
                        fragment.appendChild(ret[i]);
                    }
                }
            }

            return ret;
        },

        cleanData: function (elems) {
            var data, id, cache = jQuery.cache,
			special = jQuery.event.special,
			deleteExpando = jQuery.support.deleteExpando;

            for (var i = 0, elem; (elem = elems[i]) != null; i++) {
                if (elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) {
                    continue;
                }

                id = elem[jQuery.expando];

                if (id) {
                    data = cache[id];

                    if (data && data.events) {
                        for (var type in data.events) {
                            if (special[type]) {
                                jQuery.event.remove(elem, type);

                            } else {
                                jQuery.removeEvent(elem, type, data.handle);
                            }
                        }
                    }

                    if (deleteExpando) {
                        delete elem[jQuery.expando];

                    } else if (elem.removeAttribute) {
                        elem.removeAttribute(jQuery.expando);
                    }

                    delete cache[id];
                }
            }
        }
    });

    function evalScript(i, elem) {
        if (elem.src) {
            jQuery.ajax({
                url: elem.src,
                async: false,
                dataType: "script"
            });
        } else {
            jQuery.globalEval(elem.text || elem.textContent || elem.innerHTML || "");
        }

        if (elem.parentNode) {
            elem.parentNode.removeChild(elem);
        }
    }




    var ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	rdashAlpha = /-([a-z])/ig,
	rupper = /([A-Z])/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssWidth = ["Left", "Right"],
	cssHeight = ["Top", "Bottom"],
	curCSS,

	getComputedStyle,
	currentStyle,

	fcamelCase = function (all, letter) {
	    return letter.toUpperCase();
	};

    jQuery.fn.css = function (name, value) {
        // Setting 'undefined' is a no-op
        if (arguments.length === 2 && value === undefined) {
            return this;
        }

        return jQuery.access(this, name, value, true, function (elem, name, value) {
            return value !== undefined ?
			jQuery.style(elem, name, value) :
			jQuery.css(elem, name);
        });
    };

    jQuery.extend({
        // Add in style property hooks for overriding the default
        // behavior of getting and setting a style property
        cssHooks: {
            opacity: {
                get: function (elem, computed) {
                    if (computed) {
                        // We should always get a number back from opacity
                        var ret = curCSS(elem, "opacity", "opacity");
                        return ret === "" ? "1" : ret;

                    } else {
                        return elem.style.opacity;
                    }
                }
            }
        },

        // Exclude the following css properties to add px
        cssNumber: {
            "zIndex": true,
            "fontWeight": true,
            "opacity": true,
            "zoom": true,
            "lineHeight": true
        },

        // Add in properties whose names you wish to fix before
        // setting or getting the value
        cssProps: {
            // normalize float css property
            "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
        },

        // Get and set the style property on a DOM Node
        style: function (elem, name, value, extra) {
            // Don't set styles on text and comment nodes
            if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
                return;
            }

            // Make sure that we're working with the right name
            var ret, origName = jQuery.camelCase(name),
			style = elem.style, hooks = jQuery.cssHooks[origName];

            name = jQuery.cssProps[origName] || origName;

            // Check if we're setting a value
            if (value !== undefined) {
                // Make sure that NaN and null values aren't set. See: #7116
                if (typeof value === "number" && isNaN(value) || value == null) {
                    return;
                }

                // If a number was passed in, add 'px' to the (except for certain CSS properties)
                if (typeof value === "number" && !jQuery.cssNumber[origName]) {
                    value += "px";
                }

                // If a hook was provided, use that value, otherwise just set the specified value
                if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value)) !== undefined) {
                    // Wrapped to prevent IE from throwing errors when 'invalid' values are provided
                    // Fixes bug #5509
                    try {
                        style[name] = value;
                    } catch (e) { }
                }

            } else {
                // If a hook was provided get the non-computed value from there
                if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
                    return ret;
                }

                // Otherwise just get the value from the style object
                return style[name];
            }
        },

        css: function (elem, name, extra) {
            // Make sure that we're working with the right name
            var ret, origName = jQuery.camelCase(name),
			hooks = jQuery.cssHooks[origName];

            name = jQuery.cssProps[origName] || origName;

            // If a hook was provided get the computed value from there
            if (hooks && "get" in hooks && (ret = hooks.get(elem, true, extra)) !== undefined) {
                return ret;

                // Otherwise, if a way to get the computed value exists, use that
            } else if (curCSS) {
                return curCSS(elem, name, origName);
            }
        },

        // A method for quickly swapping in/out CSS properties to get correct calculations
        swap: function (elem, options, callback) {
            var old = {};

            // Remember the old values, and insert the new ones
            for (var name in options) {
                old[name] = elem.style[name];
                elem.style[name] = options[name];
            }

            callback.call(elem);

            // Revert the old values
            for (name in options) {
                elem.style[name] = old[name];
            }
        },

        camelCase: function (string) {
            return string.replace(rdashAlpha, fcamelCase);
        }
    });

    // DEPRECATED, Use jQuery.css() instead
    jQuery.curCSS = jQuery.css;

    jQuery.each(["height", "width"], function (i, name) {
        jQuery.cssHooks[name] = {
            get: function (elem, computed, extra) {
                var val;

                if (computed) {
                    if (elem.offsetWidth !== 0) {
                        val = getWH(elem, name, extra);

                    } else {
                        jQuery.swap(elem, cssShow, function () {
                            val = getWH(elem, name, extra);
                        });
                    }

                    if (val <= 0) {
                        val = curCSS(elem, name, name);

                        if (val === "0px" && currentStyle) {
                            val = currentStyle(elem, name, name);
                        }

                        if (val != null) {
                            // Should return "auto" instead of 0, use 0 for
                            // temporary backwards-compat
                            return val === "" || val === "auto" ? "0px" : val;
                        }
                    }

                    if (val < 0 || val == null) {
                        val = elem.style[name];

                        // Should return "auto" instead of 0, use 0 for
                        // temporary backwards-compat
                        return val === "" || val === "auto" ? "0px" : val;
                    }

                    return typeof val === "string" ? val : val + "px";
                }
            },

            set: function (elem, value) {
                if (rnumpx.test(value)) {
                    // ignore negative width and height values #1599
                    value = parseFloat(value);

                    if (value >= 0) {
                        return value + "px";
                    }

                } else {
                    return value;
                }
            }
        };
    });

    if (!jQuery.support.opacity) {
        jQuery.cssHooks.opacity = {
            get: function (elem, computed) {
                // IE uses filters for opacity
                return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
				(parseFloat(RegExp.$1) / 100) + "" :
				computed ? "1" : "";
            },

            set: function (elem, value) {
                var style = elem.style;

                // IE has trouble with opacity if it does not have layout
                // Force it by setting the zoom level
                style.zoom = 1;

                // Set the alpha filter to set the opacity
                var opacity = jQuery.isNaN(value) ?
				"" :
				"alpha(opacity=" + value * 100 + ")",
				filter = style.filter || "";

                style.filter = ralpha.test(filter) ?
				filter.replace(ralpha, opacity) :
				style.filter + ' ' + opacity;
            }
        };
    }

    if (document.defaultView && document.defaultView.getComputedStyle) {
        getComputedStyle = function (elem, newName, name) {
            var ret, defaultView, computedStyle;

            name = name.replace(rupper, "-$1").toLowerCase();

            if (!(defaultView = elem.ownerDocument.defaultView)) {
                return undefined;
            }

            if ((computedStyle = defaultView.getComputedStyle(elem, null))) {
                ret = computedStyle.getPropertyValue(name);
                if (ret === "" && !jQuery.contains(elem.ownerDocument.documentElement, elem)) {
                    ret = jQuery.style(elem, name);
                }
            }

            return ret;
        };
    }

    if (document.documentElement.currentStyle) {
        currentStyle = function (elem, name) {
            var left, rsLeft,
			ret = elem.currentStyle && elem.currentStyle[name],
			style = elem.style;

            // From the awesome hack by Dean Edwards
            // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

            // If we're not dealing with a regular pixel number
            // but a number that has a weird ending, we need to convert it to pixels
            if (!rnumpx.test(ret) && rnum.test(ret)) {
                // Remember the original values
                left = style.left;
                rsLeft = elem.runtimeStyle.left;

                // Put in the new values to get a computed value out
                elem.runtimeStyle.left = elem.currentStyle.left;
                style.left = name === "fontSize" ? "1em" : (ret || 0);
                ret = style.pixelLeft + "px";

                // Revert the changed values
                style.left = left;
                elem.runtimeStyle.left = rsLeft;
            }

            return ret === "" ? "auto" : ret;
        };
    }

    curCSS = getComputedStyle || currentStyle;

    function getWH(elem, name, extra) {
        var which = name === "width" ? cssWidth : cssHeight,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight;

        if (extra === "border") {
            return val;
        }

        jQuery.each(which, function () {
            if (!extra) {
                val -= parseFloat(jQuery.css(elem, "padding" + this)) || 0;
            }

            if (extra === "margin") {
                val += parseFloat(jQuery.css(elem, "margin" + this)) || 0;

            } else {
                val -= parseFloat(jQuery.css(elem, "border" + this + "Width")) || 0;
            }
        });

        return val;
    }

    if (jQuery.expr && jQuery.expr.filters) {
        jQuery.expr.filters.hidden = function (elem) {
            var width = elem.offsetWidth,
			height = elem.offsetHeight;

            return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css(elem, "display")) === "none");
        };

        jQuery.expr.filters.visible = function (elem) {
            return !jQuery.expr.filters.hidden(elem);
        };
    }




    var jsc = jQuery.now(),
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
	rselectTextarea = /^(?:select|textarea)/i,
	rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
	rnoContent = /^(?:GET|HEAD)$/,
	rbracket = /\[\]$/,
	jsre = /\=\?(&|$)/,
	rquery = /\?/,
	rts = /([?&])_=[^&]*/,
	rurl = /^(\w+:)?\/\/([^\/?#]+)/,
	r20 = /%20/g,
	rhash = /#.*$/,

    // Keep a copy of the old load method
	_load = jQuery.fn.load;

    jQuery.fn.extend({
        load: function (url, params, callback) {
            if (typeof url !== "string" && _load) {
                return _load.apply(this, arguments);

                // Don't do a request if no elements are being requested
            } else if (!this.length) {
                return this;
            }

            var off = url.indexOf(" ");
            if (off >= 0) {
                var selector = url.slice(off, url.length);
                url = url.slice(0, off);
            }

            // Default to a GET request
            var type = "GET";

            // If the second parameter was provided
            if (params) {
                // If it's a function
                if (jQuery.isFunction(params)) {
                    // We assume that it's the callback
                    callback = params;
                    params = null;

                    // Otherwise, build a param string
                } else if (typeof params === "object") {
                    params = jQuery.param(params, jQuery.ajaxSettings.traditional);
                    type = "POST";
                }
            }

            var self = this;

            // Request the remote document
            jQuery.ajax({
                url: url,
                type: type,
                dataType: "html",
                data: params,
                complete: function (res, status) {
                    // If successful, inject the HTML into all the matched elements
                    if (status === "success" || status === "notmodified") {
                        // See if a selector was specified
                        self.html(selector ?
                        // Create a dummy div to hold the results
						jQuery("<div>")
                        // inject the contents of the document in, removing the scripts
                        // to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(rscript, ""))

                        // Locate the specified elements
							.find(selector) :

                        // If not, just inject the full result
						res.responseText);
                    }

                    if (callback) {
                        self.each(callback, [res.responseText, status, res]);
                    }
                }
            });

            return this;
        },

        serialize: function () {
            return jQuery.param(this.serializeArray());
        },

        serializeArray: function () {
            return this.map(function () {
                return this.elements ? jQuery.makeArray(this.elements) : this;
            })
		.filter(function () {
		    return this.name && !this.disabled &&
				(this.checked || rselectTextarea.test(this.nodeName) ||
					rinput.test(this.type));
		})
		.map(function (i, elem) {
		    var val = jQuery(this).val();

		    return val == null ?
				null :
				jQuery.isArray(val) ?
					jQuery.map(val, function (val, i) {
					    return { name: elem.name, value: val };
					}) :
					{ name: elem.name, value: val };
		}).get();
        }
    });

    // Attach a bunch of functions for handling common AJAX events
    jQuery.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function (i, o) {
        jQuery.fn[o] = function (f) {
            return this.bind(o, f);
        };
    });

    jQuery.extend({
        get: function (url, data, callback, type) {
            // shift arguments if data argument was omited
            if (jQuery.isFunction(data)) {
                type = type || callback;
                callback = data;
                data = null;
            }

            return jQuery.ajax({
                type: "GET",
                url: url,
                data: data,
                success: callback,
                dataType: type
            });
        },

        getScript: function (url, callback) {
            return jQuery.get(url, null, callback, "script");
        },

        getJSON: function (url, data, callback) {
            return jQuery.get(url, data, callback, "json");
        },

        post: function (url, data, callback, type) {
            // shift arguments if data argument was omited
            if (jQuery.isFunction(data)) {
                type = type || callback;
                callback = data;
                data = {};
            }

            return jQuery.ajax({
                type: "POST",
                url: url,
                data: data,
                success: callback,
                dataType: type
            });
        },

        ajaxSetup: function (settings) {
            jQuery.extend(jQuery.ajaxSettings, settings);
        },

        ajaxSettings: {
            url: location.href,
            global: true,
            type: "GET",
            contentType: "application/x-www-form-urlencoded",
            processData: true,
            async: true,
            /*
            timeout: 0,
            data: null,
            username: null,
            password: null,
            traditional: false,
            */
            // This function can be overriden by calling jQuery.ajaxSetup
            xhr: function () {
                return new window.XMLHttpRequest();
            },
            accepts: {
                xml: "application/xml, text/xml",
                html: "text/html",
                script: "text/javascript, application/javascript",
                json: "application/json, text/javascript",
                text: "text/plain",
                _default: "*/*"
            }
        },

        ajax: function (origSettings) {
            var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
			jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);

            s.url = s.url.replace(rhash, "");

            // Use original (not extended) context object if it was provided
            s.context = origSettings && origSettings.context != null ? origSettings.context : s;

            // convert data if not already a string
            if (s.data && s.processData && typeof s.data !== "string") {
                s.data = jQuery.param(s.data, s.traditional);
            }

            // Handle JSONP Parameter Callbacks
            if (s.dataType === "jsonp") {
                if (type === "GET") {
                    if (!jsre.test(s.url)) {
                        s.url += (rquery.test(s.url) ? "&" : "?") + (s.jsonp || "callback") + "=?";
                    }
                } else if (!s.data || !jsre.test(s.data)) {
                    s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
                }
                s.dataType = "json";
            }

            // Build temporary JSONP function
            if (s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url))) {
                jsonp = s.jsonpCallback || ("jsonp" + jsc++);

                // Replace the =? sequence both in the query string and the data
                if (s.data) {
                    s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
                }

                s.url = s.url.replace(jsre, "=" + jsonp + "$1");

                // We need to make sure
                // that a JSONP style response is executed properly
                s.dataType = "script";

                // Handle JSONP-style loading
                var customJsonp = window[jsonp];

                window[jsonp] = function (tmp) {
                    if (jQuery.isFunction(customJsonp)) {
                        customJsonp(tmp);

                    } else {
                        // Garbage collect
                        window[jsonp] = undefined;

                        try {
                            delete window[jsonp];
                        } catch (jsonpError) { }
                    }

                    data = tmp;
                    jQuery.handleSuccess(s, xhr, status, data);
                    jQuery.handleComplete(s, xhr, status, data);

                    if (head) {
                        head.removeChild(script);
                    }
                };
            }

            if (s.dataType === "script" && s.cache === null) {
                s.cache = false;
            }

            if (s.cache === false && noContent) {
                var ts = jQuery.now();

                // try replacing _= if it is there
                var ret = s.url.replace(rts, "$1_=" + ts);

                // if nothing was replaced, add timestamp to the end
                s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
            }

            // If data is available, append data to url for GET/HEAD requests
            if (s.data && noContent) {
                s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
            }

            // Watch for a new set of requests
            if (s.global && jQuery.active++ === 0) {
                jQuery.event.trigger("ajaxStart");
            }

            // Matches an absolute URL, and saves the domain
            var parts = rurl.exec(s.url),
			remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);

            // If we're requesting a remote document
            // and trying to load JSON or Script with a GET
            if (s.dataType === "script" && type === "GET" && remote) {
                var head = document.getElementsByTagName("head")[0] || document.documentElement;
                var script = document.createElement("script");
                if (s.scriptCharset) {
                    script.charset = s.scriptCharset;
                }
                script.src = s.url;

                // Handle Script loading
                if (!jsonp) {
                    var done = false;

                    // Attach handlers for all browsers
                    script.onload = script.onreadystatechange = function () {
                        if (!done && (!this.readyState ||
							this.readyState === "loaded" || this.readyState === "complete")) {
                            done = true;
                            jQuery.handleSuccess(s, xhr, status, data);
                            jQuery.handleComplete(s, xhr, status, data);

                            // Handle memory leak in IE
                            script.onload = script.onreadystatechange = null;
                            if (head && script.parentNode) {
                                head.removeChild(script);
                            }
                        }
                    };
                }

                // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
                // This arises when a base node is used (#2709 and #4378).
                head.insertBefore(script, head.firstChild);

                // We handle everything using the script element injection
                return undefined;
            }

            var requestDone = false;

            // Create the request object
            var xhr = s.xhr();

            if (!xhr) {
                return;
            }

            // Open the socket
            // Passing null username, generates a login popup on Opera (#2865)
            if (s.username) {
                xhr.open(type, s.url, s.async, s.username, s.password);
            } else {
                xhr.open(type, s.url, s.async);
            }

            // Need an extra try/catch for cross domain requests in Firefox 3
            try {
                // Set content-type if data specified and content-body is valid for this type
                if ((s.data != null && !noContent) || (origSettings && origSettings.contentType)) {
                    xhr.setRequestHeader("Content-Type", s.contentType);
                }

                // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
                if (s.ifModified) {
                    if (jQuery.lastModified[s.url]) {
                        xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
                    }

                    if (jQuery.etag[s.url]) {
                        xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
                    }
                }

                // Set header so the called script knows that it's an XMLHttpRequest
                // Only send the header if it's not a remote XHR
                if (!remote) {
                    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                }

                // Set the Accepts header for the server, depending on the dataType
                xhr.setRequestHeader("Accept", s.dataType && s.accepts[s.dataType] ?
				s.accepts[s.dataType] + ", */*; q=0.01" :
				s.accepts._default);
            } catch (headerError) { }

            // Allow custom headers/mimetypes and early abort
            if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
                // Handle the global AJAX counter
                if (s.global && jQuery.active-- === 1) {
                    jQuery.event.trigger("ajaxStop");
                }

                // close opended socket
                xhr.abort();
                return false;
            }

            if (s.global) {
                jQuery.triggerGlobal(s, "ajaxSend", [xhr, s]);
            }

            // Wait for a response to come back
            var onreadystatechange = xhr.onreadystatechange = function (isTimeout) {
                // The request was aborted
                if (!xhr || xhr.readyState === 0 || isTimeout === "abort") {
                    // Opera doesn't call onreadystatechange before this point
                    // so we simulate the call
                    if (!requestDone) {
                        jQuery.handleComplete(s, xhr, status, data);
                    }

                    requestDone = true;
                    if (xhr) {
                        xhr.onreadystatechange = jQuery.noop;
                    }

                    // The transfer is complete and the data is available, or the request timed out
                } else if (!requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout")) {
                    requestDone = true;
                    xhr.onreadystatechange = jQuery.noop;

                    status = isTimeout === "timeout" ?
					"timeout" :
					!jQuery.httpSuccess(xhr) ?
						"error" :
						s.ifModified && jQuery.httpNotModified(xhr, s.url) ?
							"notmodified" :
							"success";

                    var errMsg;

                    if (status === "success") {
                        // Watch for, and catch, XML document parse errors
                        try {
                            // process the data (runs the xml through httpData regardless of callback)
                            data = jQuery.httpData(xhr, s.dataType, s);
                        } catch (parserError) {
                            status = "parsererror";
                            errMsg = parserError;
                        }
                    }

                    // Make sure that the request was successful or notmodified
                    if (status === "success" || status === "notmodified") {
                        // JSONP handles its own success callback
                        if (!jsonp) {
                            jQuery.handleSuccess(s, xhr, status, data);
                        }
                    } else {
                        jQuery.handleError(s, xhr, status, errMsg);
                    }

                    // Fire the complete handlers
                    if (!jsonp) {
                        jQuery.handleComplete(s, xhr, status, data);
                    }

                    if (isTimeout === "timeout") {
                        xhr.abort();
                    }

                    // Stop memory leaks
                    if (s.async) {
                        xhr = null;
                    }
                }
            };

            // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
            // Opera doesn't fire onreadystatechange at all on abort
            try {
                var oldAbort = xhr.abort;
                xhr.abort = function () {
                    if (xhr) {
                        // oldAbort has no call property in IE7 so
                        // just do it this way, which works in all
                        // browsers
                        Function.prototype.call.call(oldAbort, xhr);
                    }

                    onreadystatechange("abort");
                };
            } catch (abortError) { }

            // Timeout checker
            if (s.async && s.timeout > 0) {
                setTimeout(function () {
                    // Check to see if the request is still happening
                    if (xhr && !requestDone) {
                        onreadystatechange("timeout");
                    }
                }, s.timeout);
            }

            // Send the data
            try {
                xhr.send(noContent || s.data == null ? null : s.data);

            } catch (sendError) {
                jQuery.handleError(s, xhr, null, sendError);

                // Fire the complete handlers
                jQuery.handleComplete(s, xhr, status, data);
            }

            // firefox 1.5 doesn't fire statechange for sync requests
            if (!s.async) {
                onreadystatechange();
            }

            // return XMLHttpRequest to allow aborting the request etc.
            return xhr;
        },

        // Serialize an array of form elements or a set of
        // key/values into a query string
        param: function (a, traditional) {
            var s = [],
			add = function (key, value) {
			    // If value is a function, invoke it and return its value
			    value = jQuery.isFunction(value) ? value() : value;
			    s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
			};

            // Set traditional to true for jQuery <= 1.3.2 behavior.
            if (traditional === undefined) {
                traditional = jQuery.ajaxSettings.traditional;
            }

            // If an array was passed in, assume that it is an array of form elements.
            if (jQuery.isArray(a) || a.jquery) {
                // Serialize the form elements
                jQuery.each(a, function () {
                    add(this.name, this.value);
                });

            } else {
                // If traditional, encode the "old" way (the way 1.3.2 or older
                // did it), otherwise encode params recursively.
                for (var prefix in a) {
                    buildParams(prefix, a[prefix], traditional, add);
                }
            }

            // Return the resulting serialization
            return s.join("&").replace(r20, "+");
        }
    });

    function buildParams(prefix, obj, traditional, add) {
        if (jQuery.isArray(obj) && obj.length) {
            // Serialize array item.
            jQuery.each(obj, function (i, v) {
                if (traditional || rbracket.test(prefix)) {
                    // Treat each array item as a scalar.
                    add(prefix, v);

                } else {
                    // If array item is non-scalar (array or object), encode its
                    // numeric index to resolve deserialization ambiguity issues.
                    // Note that rack (as of 1.0.0) can't currently deserialize
                    // nested arrays properly, and attempting to do so may cause
                    // a server error. Possible fixes are to modify rack's
                    // deserialization algorithm or to provide an option or flag
                    // to force array serialization to be shallow.
                    buildParams(prefix + "[" + (typeof v === "object" || jQuery.isArray(v) ? i : "") + "]", v, traditional, add);
                }
            });

        } else if (!traditional && obj != null && typeof obj === "object") {
            if (jQuery.isEmptyObject(obj)) {
                add(prefix, "");

                // Serialize object item.
            } else {
                jQuery.each(obj, function (k, v) {
                    buildParams(prefix + "[" + k + "]", v, traditional, add);
                });
            }

        } else {
            // Serialize scalar item.
            add(prefix, obj);
        }
    }

    // This is still on the jQuery object... for now
    // Want to move this to jQuery.ajax some day
    jQuery.extend({

        // Counter for holding the number of active queries
        active: 0,

        // Last-Modified header cache for next request
        lastModified: {},
        etag: {},

        handleError: function (s, xhr, status, e) {
            // If a local callback was specified, fire it
            if (s.error) {
                s.error.call(s.context, xhr, status, e);
            }

            // Fire the global callback
            if (s.global) {
                jQuery.triggerGlobal(s, "ajaxError", [xhr, s, e]);
            }
        },

        handleSuccess: function (s, xhr, status, data) {
            // If a local callback was specified, fire it and pass it the data
            if (s.success) {
                s.success.call(s.context, data, status, xhr);
            }

            // Fire the global callback
            if (s.global) {
                jQuery.triggerGlobal(s, "ajaxSuccess", [xhr, s]);
            }
        },

        handleComplete: function (s, xhr, status) {
            // Process result
            if (s.complete) {
                s.complete.call(s.context, xhr, status);
            }

            // The request was completed
            if (s.global) {
                jQuery.triggerGlobal(s, "ajaxComplete", [xhr, s]);
            }

            // Handle the global AJAX counter
            if (s.global && jQuery.active-- === 1) {
                jQuery.event.trigger("ajaxStop");
            }
        },

        triggerGlobal: function (s, type, args) {
            (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
        },

        // Determines if an XMLHttpRequest was successful or not
        httpSuccess: function (xhr) {
            try {
                // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
                return !xhr.status && location.protocol === "file:" ||
				xhr.status >= 200 && xhr.status < 300 ||
				xhr.status === 304 || xhr.status === 1223;
            } catch (e) { }

            return false;
        },

        // Determines if an XMLHttpRequest returns NotModified
        httpNotModified: function (xhr, url) {
            var lastModified = xhr.getResponseHeader("Last-Modified"),
			etag = xhr.getResponseHeader("Etag");

            if (lastModified) {
                jQuery.lastModified[url] = lastModified;
            }

            if (etag) {
                jQuery.etag[url] = etag;
            }

            return xhr.status === 304;
        },

        httpData: function (xhr, type, s) {
            var ct = xhr.getResponseHeader("content-type") || "",
			xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

            if (xml && data.documentElement.nodeName === "parsererror") {
                jQuery.error("parsererror");
            }

            // Allow a pre-filtering function to sanitize the response
            // s is checked to keep backwards compatibility
            if (s && s.dataFilter) {
                data = s.dataFilter(data, type);
            }

            // The filter can actually parse the response
            if (typeof data === "string") {
                // Get the JavaScript object, if JSON is used.
                if (type === "json" || !type && ct.indexOf("json") >= 0) {
                    data = jQuery.parseJSON(data);

                    // If the type is "script", eval it in global context
                } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
                    jQuery.globalEval(data);
                }
            }

            return data;
        }

    });

    /*
    * Create the request object; Microsoft failed to properly
    * implement the XMLHttpRequest in IE7 (can't request local files),
    * so we use the ActiveXObject when it is available
    * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
    * we need a fallback.
    */
    if (window.ActiveXObject) {
        jQuery.ajaxSettings.xhr = function () {
            if (window.location.protocol !== "file:") {
                try {
                    return new window.XMLHttpRequest();
                } catch (xhrError) { }
            }

            try {
                return new window.ActiveXObject("Microsoft.XMLHTTP");
            } catch (activeError) { }
        };
    }

    // Does this browser support XHR requests?
    jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();




    var elemdisplay = {},
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/,
	timerId,
	fxAttrs = [
    // height animations
		["height", "marginTop", "marginBottom", "paddingTop", "paddingBottom"],
    // width animations
		["width", "marginLeft", "marginRight", "paddingLeft", "paddingRight"],
    // opacity animations
		["opacity"]
	];

    jQuery.fn.extend({
        show: function (speed, easing, callback) {
            var elem, display;

            if (speed || speed === 0) {
                return this.animate(genFx("show", 3), speed, easing, callback);

            } else {
                for (var i = 0, j = this.length; i < j; i++) {
                    elem = this[i];
                    display = elem.style.display;

                    // Reset the inline display of this element to learn if it is
                    // being hidden by cascaded rules or not
                    if (!jQuery.data(elem, "olddisplay") && display === "none") {
                        display = elem.style.display = "";
                    }

                    // Set elements which have been overridden with display: none
                    // in a stylesheet to whatever the default browser style is
                    // for such an element
                    if (display === "" && jQuery.css(elem, "display") === "none") {
                        jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
                    }
                }

                // Set the display of most of the elements in a second loop
                // to avoid the constant reflow
                for (i = 0; i < j; i++) {
                    elem = this[i];
                    display = elem.style.display;

                    if (display === "" || display === "none") {
                        elem.style.display = jQuery.data(elem, "olddisplay") || "";
                    }
                }

                return this;
            }
        },

        hide: function (speed, easing, callback) {
            if (speed || speed === 0) {
                return this.animate(genFx("hide", 3), speed, easing, callback);

            } else {
                for (var i = 0, j = this.length; i < j; i++) {
                    var display = jQuery.css(this[i], "display");

                    if (display !== "none") {
                        jQuery.data(this[i], "olddisplay", display);
                    }
                }

                // Set the display of the elements in a second loop
                // to avoid the constant reflow
                for (i = 0; i < j; i++) {
                    this[i].style.display = "none";
                }

                return this;
            }
        },

        // Save the old toggle function
        _toggle: jQuery.fn.toggle,

        toggle: function (fn, fn2, callback) {
            var bool = typeof fn === "boolean";

            if (jQuery.isFunction(fn) && jQuery.isFunction(fn2)) {
                this._toggle.apply(this, arguments);

            } else if (fn == null || bool) {
                this.each(function () {
                    var state = bool ? fn : jQuery(this).is(":hidden");
                    jQuery(this)[state ? "show" : "hide"]();
                });

            } else {
                this.animate(genFx("toggle", 3), fn, fn2, callback);
            }

            return this;
        },

        fadeTo: function (speed, to, easing, callback) {
            return this.filter(":hidden").css("opacity", 0).show().end()
					.animate({ opacity: to }, speed, easing, callback);
        },

        animate: function (prop, speed, easing, callback) {
            var optall = jQuery.speed(speed, easing, callback);

            if (jQuery.isEmptyObject(prop)) {
                return this.each(optall.complete);
            }

            return this[optall.queue === false ? "each" : "queue"](function () {
                // XXX 'this' does not always have a nodeName when running the
                // test suite

                var opt = jQuery.extend({}, optall), p,
				isElement = this.nodeType === 1,
				hidden = isElement && jQuery(this).is(":hidden"),
				self = this;

                for (p in prop) {
                    var name = jQuery.camelCase(p);

                    if (p !== name) {
                        prop[name] = prop[p];
                        delete prop[p];
                        p = name;
                    }

                    if (prop[p] === "hide" && hidden || prop[p] === "show" && !hidden) {
                        return opt.complete.call(this);
                    }

                    if (isElement && (p === "height" || p === "width")) {
                        // Make sure that nothing sneaks out
                        // Record all 3 overflow attributes because IE does not
                        // change the overflow attribute when overflowX and
                        // overflowY are set to the same value
                        opt.overflow = [this.style.overflow, this.style.overflowX, this.style.overflowY];

                        // Set display property to inline-block for height/width
                        // animations on inline elements that are having width/height
                        // animated
                        if (jQuery.css(this, "display") === "inline" &&
							jQuery.css(this, "float") === "none") {
                            if (!jQuery.support.inlineBlockNeedsLayout) {
                                this.style.display = "inline-block";

                            } else {
                                var display = defaultDisplay(this.nodeName);

                                // inline-level elements accept inline-block;
                                // block-level elements need to be inline with layout
                                if (display === "inline") {
                                    this.style.display = "inline-block";

                                } else {
                                    this.style.display = "inline";
                                    this.style.zoom = 1;
                                }
                            }
                        }
                    }

                    if (jQuery.isArray(prop[p])) {
                        // Create (if needed) and add to specialEasing
                        (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
                        prop[p] = prop[p][0];
                    }
                }

                if (opt.overflow != null) {
                    this.style.overflow = "hidden";
                }

                opt.curAnim = jQuery.extend({}, prop);

                jQuery.each(prop, function (name, val) {
                    var e = new jQuery.fx(self, opt, name);

                    if (rfxtypes.test(val)) {
                        e[val === "toggle" ? hidden ? "show" : "hide" : val](prop);

                    } else {
                        var parts = rfxnum.exec(val),
						start = e.cur() || 0;

                        if (parts) {
                            var end = parseFloat(parts[2]),
							unit = parts[3] || "px";

                            // We need to compute starting value
                            if (unit !== "px") {
                                jQuery.style(self, name, (end || 1) + unit);
                                start = ((end || 1) / e.cur()) * start;
                                jQuery.style(self, name, start + unit);
                            }

                            // If a +=/-= token was provided, we're doing a relative animation
                            if (parts[1]) {
                                end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
                            }

                            e.custom(start, end, unit);

                        } else {
                            e.custom(start, val, "");
                        }
                    }
                });

                // For JS strict compliance
                return true;
            });
        },

        stop: function (clearQueue, gotoEnd) {
            var timers = jQuery.timers;

            if (clearQueue) {
                this.queue([]);
            }

            this.each(function () {
                // go in reverse order so anything added to the queue during the loop is ignored
                for (var i = timers.length - 1; i >= 0; i--) {
                    if (timers[i].elem === this) {
                        if (gotoEnd) {
                            // force the next step to be the last
                            timers[i](true);
                        }

                        timers.splice(i, 1);
                    }
                }
            });

            // start the next in the queue if the last step wasn't forced
            if (!gotoEnd) {
                this.dequeue();
            }

            return this;
        }

    });

    function genFx(type, num) {
        var obj = {};

        jQuery.each(fxAttrs.concat.apply([], fxAttrs.slice(0, num)), function () {
            obj[this] = type;
        });

        return obj;
    }

    // Generate shortcuts for custom animations
    jQuery.each({
        slideDown: genFx("show", 1),
        slideUp: genFx("hide", 1),
        slideToggle: genFx("toggle", 1),
        fadeIn: { opacity: "show" },
        fadeOut: { opacity: "hide" },
        fadeToggle: { opacity: "toggle" }
    }, function (name, props) {
        jQuery.fn[name] = function (speed, easing, callback) {
            return this.animate(props, speed, easing, callback);
        };
    });

    jQuery.extend({
        speed: function (speed, easing, fn) {
            var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
                complete: fn || !fn && easing ||
				jQuery.isFunction(speed) && speed,
                duration: speed,
                easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
            };

            opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
			opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;

            // Queueing
            opt.old = opt.complete;
            opt.complete = function () {
                if (opt.queue !== false) {
                    jQuery(this).dequeue();
                }
                if (jQuery.isFunction(opt.old)) {
                    opt.old.call(this);
                }
            };

            return opt;
        },

        easing: {
            linear: function (p, n, firstNum, diff) {
                return firstNum + diff * p;
            },
            swing: function (p, n, firstNum, diff) {
                return ((-Math.cos(p * Math.PI) / 2) + 0.5) * diff + firstNum;
            }
        },

        timers: [],

        fx: function (elem, options, prop) {
            this.options = options;
            this.elem = elem;
            this.prop = prop;

            if (!options.orig) {
                options.orig = {};
            }
        }

    });

    jQuery.fx.prototype = {
        // Simple function for setting a style value
        update: function () {
            if (this.options.step) {
                this.options.step.call(this.elem, this.now, this);
            }

            (jQuery.fx.step[this.prop] || jQuery.fx.step._default)(this);
        },

        // Get the current size
        cur: function () {
            if (this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null)) {
                return this.elem[this.prop];
            }

            var r = parseFloat(jQuery.css(this.elem, this.prop));
            return r && r > -10000 ? r : 0;
        },

        // Start an animation from one number to another
        custom: function (from, to, unit) {
            var self = this,
			fx = jQuery.fx;

            this.startTime = jQuery.now();
            this.start = from;
            this.end = to;
            this.unit = unit || this.unit || "px";
            this.now = this.start;
            this.pos = this.state = 0;

            function t(gotoEnd) {
                return self.step(gotoEnd);
            }

            t.elem = this.elem;

            if (t() && jQuery.timers.push(t) && !timerId) {
                timerId = setInterval(fx.tick, fx.interval);
            }
        },

        // Simple 'show' function
        show: function () {
            // Remember where we started, so that we can go back to it later
            this.options.orig[this.prop] = jQuery.style(this.elem, this.prop);
            this.options.show = true;

            // Begin the animation
            // Make sure that we start at a small width/height to avoid any
            // flash of content
            this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());

            // Start by showing the element
            jQuery(this.elem).show();
        },

        // Simple 'hide' function
        hide: function () {
            // Remember where we started, so that we can go back to it later
            this.options.orig[this.prop] = jQuery.style(this.elem, this.prop);
            this.options.hide = true;

            // Begin the animation
            this.custom(this.cur(), 0);
        },

        // Each step of an animation
        step: function (gotoEnd) {
            var t = jQuery.now(), done = true;

            if (gotoEnd || t >= this.options.duration + this.startTime) {
                this.now = this.end;
                this.pos = this.state = 1;
                this.update();

                this.options.curAnim[this.prop] = true;

                for (var i in this.options.curAnim) {
                    if (this.options.curAnim[i] !== true) {
                        done = false;
                    }
                }

                if (done) {
                    // Reset the overflow
                    if (this.options.overflow != null && !jQuery.support.shrinkWrapBlocks) {
                        var elem = this.elem,
						options = this.options;

                        jQuery.each(["", "X", "Y"], function (index, value) {
                            elem.style["overflow" + value] = options.overflow[index];
                        });
                    }

                    // Hide the element if the "hide" operation was done
                    if (this.options.hide) {
                        jQuery(this.elem).hide();
                    }

                    // Reset the properties, if the item has been hidden or shown
                    if (this.options.hide || this.options.show) {
                        for (var p in this.options.curAnim) {
                            jQuery.style(this.elem, p, this.options.orig[p]);
                        }
                    }

                    // Execute the complete function
                    this.options.complete.call(this.elem);
                }

                return false;

            } else {
                var n = t - this.startTime;
                this.state = n / this.options.duration;

                // Perform the easing function, defaults to swing
                var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
                var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
                this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
                this.now = this.start + ((this.end - this.start) * this.pos);

                // Perform the next step of the animation
                this.update();
            }

            return true;
        }
    };

    jQuery.extend(jQuery.fx, {
        tick: function () {
            var timers = jQuery.timers;

            for (var i = 0; i < timers.length; i++) {
                if (!timers[i]()) {
                    timers.splice(i--, 1);
                }
            }

            if (!timers.length) {
                jQuery.fx.stop();
            }
        },

        interval: 13,

        stop: function () {
            clearInterval(timerId);
            timerId = null;
        },

        speeds: {
            slow: 600,
            fast: 200,
            // Default speed
            _default: 400
        },

        step: {
            opacity: function (fx) {
                jQuery.style(fx.elem, "opacity", fx.now);
            },

            _default: function (fx) {
                if (fx.elem.style && fx.elem.style[fx.prop] != null) {
                    fx.elem.style[fx.prop] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
                } else {
                    fx.elem[fx.prop] = fx.now;
                }
            }
        }
    });

    if (jQuery.expr && jQuery.expr.filters) {
        jQuery.expr.filters.animated = function (elem) {
            return jQuery.grep(jQuery.timers, function (fn) {
                return elem === fn.elem;
            }).length;
        };
    }

    function defaultDisplay(nodeName) {
        if (!elemdisplay[nodeName]) {
            var elem = jQuery("<" + nodeName + ">").appendTo("body"),
			display = elem.css("display");

            elem.remove();

            if (display === "none" || display === "") {
                display = "block";
            }

            elemdisplay[nodeName] = display;
        }

        return elemdisplay[nodeName];
    }




    var rtable = /^t(?:able|d|h)$/i,
	rroot = /^(?:body|html)$/i;

    if ("getBoundingClientRect" in document.documentElement) {
        jQuery.fn.offset = function (options) {
            var elem = this[0], box;

            if (options) {
                return this.each(function (i) {
                    jQuery.offset.setOffset(this, options, i);
                });
            }

            if (!elem || !elem.ownerDocument) {
                return null;
            }

            if (elem === elem.ownerDocument.body) {
                return jQuery.offset.bodyOffset(elem);
            }

            try {
                box = elem.getBoundingClientRect();
            } catch (e) { }

            var doc = elem.ownerDocument,
			docElem = doc.documentElement;

            // Make sure we're not dealing with a disconnected DOM node
            if (!box || !jQuery.contains(docElem, elem)) {
                return box || { top: 0, left: 0 };
            }

            var body = doc.body,
			win = getWindow(doc),
			clientTop = docElem.clientTop || body.clientTop || 0,
			clientLeft = docElem.clientLeft || body.clientLeft || 0,
			scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop),
			scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
			top = box.top + scrollTop - clientTop,
			left = box.left + scrollLeft - clientLeft;

            return { top: top, left: left };
        };

    } else {
        jQuery.fn.offset = function (options) {
            var elem = this[0];

            if (options) {
                return this.each(function (i) {
                    jQuery.offset.setOffset(this, options, i);
                });
            }

            if (!elem || !elem.ownerDocument) {
                return null;
            }

            if (elem === elem.ownerDocument.body) {
                return jQuery.offset.bodyOffset(elem);
            }

            jQuery.offset.initialize();

            var computedStyle,
			offsetParent = elem.offsetParent,
			prevOffsetParent = elem,
			doc = elem.ownerDocument,
			docElem = doc.documentElement,
			body = doc.body,
			defaultView = doc.defaultView,
			prevComputedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle,
			top = elem.offsetTop,
			left = elem.offsetLeft;

            while ((elem = elem.parentNode) && elem !== body && elem !== docElem) {
                if (jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed") {
                    break;
                }

                computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
                top -= elem.scrollTop;
                left -= elem.scrollLeft;

                if (elem === offsetParent) {
                    top += elem.offsetTop;
                    left += elem.offsetLeft;

                    if (jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName))) {
                        top += parseFloat(computedStyle.borderTopWidth) || 0;
                        left += parseFloat(computedStyle.borderLeftWidth) || 0;
                    }

                    prevOffsetParent = offsetParent;
                    offsetParent = elem.offsetParent;
                }

                if (jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible") {
                    top += parseFloat(computedStyle.borderTopWidth) || 0;
                    left += parseFloat(computedStyle.borderLeftWidth) || 0;
                }

                prevComputedStyle = computedStyle;
            }

            if (prevComputedStyle.position === "relative" || prevComputedStyle.position === "static") {
                top += body.offsetTop;
                left += body.offsetLeft;
            }

            if (jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed") {
                top += Math.max(docElem.scrollTop, body.scrollTop);
                left += Math.max(docElem.scrollLeft, body.scrollLeft);
            }

            return { top: top, left: left };
        };
    }

    jQuery.offset = {
        initialize: function () {
            var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat(jQuery.css(body, "marginTop")) || 0,
			html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";

            jQuery.extend(container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" });

            container.innerHTML = html;
            body.insertBefore(container, body.firstChild);
            innerDiv = container.firstChild;
            checkDiv = innerDiv.firstChild;
            td = innerDiv.nextSibling.firstChild.firstChild;

            this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
            this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

            checkDiv.style.position = "fixed";
            checkDiv.style.top = "20px";

            // safari subtracts parent border width here which is 5px
            this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
            checkDiv.style.position = checkDiv.style.top = "";

            innerDiv.style.overflow = "hidden";
            innerDiv.style.position = "relative";

            this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

            this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);

            body.removeChild(container);
            body = container = innerDiv = checkDiv = table = td = null;
            jQuery.offset.initialize = jQuery.noop;
        },

        bodyOffset: function (body) {
            var top = body.offsetTop,
			left = body.offsetLeft;

            jQuery.offset.initialize();

            if (jQuery.offset.doesNotIncludeMarginInBodyOffset) {
                top += parseFloat(jQuery.css(body, "marginTop")) || 0;
                left += parseFloat(jQuery.css(body, "marginLeft")) || 0;
            }

            return { top: top, left: left };
        },

        setOffset: function (elem, options, i) {
            var position = jQuery.css(elem, "position");

            // set position first, in-case top/left are set even on static elem
            if (position === "static") {
                elem.style.position = "relative";
            }

            var curElem = jQuery(elem),
			curOffset = curElem.offset(),
			curCSSTop = jQuery.css(elem, "top"),
			curCSSLeft = jQuery.css(elem, "left"),
			calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1),
			props = {}, curPosition = {}, curTop, curLeft;

            // need to be able to calculate position if either top or left is auto and position is absolute
            if (calculatePosition) {
                curPosition = curElem.position();
            }

            curTop = calculatePosition ? curPosition.top : parseInt(curCSSTop, 10) || 0;
            curLeft = calculatePosition ? curPosition.left : parseInt(curCSSLeft, 10) || 0;

            if (jQuery.isFunction(options)) {
                options = options.call(elem, i, curOffset);
            }

            if (options.top != null) {
                props.top = (options.top - curOffset.top) + curTop;
            }
            if (options.left != null) {
                props.left = (options.left - curOffset.left) + curLeft;
            }

            if ("using" in options) {
                options.using.call(elem, props);
            } else {
                curElem.css(props);
            }
        }
    };


    jQuery.fn.extend({
        position: function () {
            if (!this[0]) {
                return null;
            }

            var elem = this[0],

            // Get *real* offsetParent
		offsetParent = this.offsetParent(),

            // Get correct offsets
		offset = this.offset(),
		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0} : offsetParent.offset();

            // Subtract element margins
            // note: when an element has margin: auto the offsetLeft and marginLeft
            // are the same in Safari causing offset.left to incorrectly be 0
            offset.top -= parseFloat(jQuery.css(elem, "marginTop")) || 0;
            offset.left -= parseFloat(jQuery.css(elem, "marginLeft")) || 0;

            // Add offsetParent borders
            parentOffset.top += parseFloat(jQuery.css(offsetParent[0], "borderTopWidth")) || 0;
            parentOffset.left += parseFloat(jQuery.css(offsetParent[0], "borderLeftWidth")) || 0;

            // Subtract the two offsets
            return {
                top: offset.top - parentOffset.top,
                left: offset.left - parentOffset.left
            };
        },

        offsetParent: function () {
            return this.map(function () {
                var offsetParent = this.offsetParent || document.body;
                while (offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static")) {
                    offsetParent = offsetParent.offsetParent;
                }
                return offsetParent;
            });
        }
    });


    // Create scrollLeft and scrollTop methods
    jQuery.each(["Left", "Top"], function (i, name) {
        var method = "scroll" + name;

        jQuery.fn[method] = function (val) {
            var elem = this[0], win;

            if (!elem) {
                return null;
            }

            if (val !== undefined) {
                // Set the scroll offset
                return this.each(function () {
                    win = getWindow(this);

                    if (win) {
                        win.scrollTo(
						!i ? val : jQuery(win).scrollLeft(),
						 i ? val : jQuery(win).scrollTop()
					);

                    } else {
                        this[method] = val;
                    }
                });
            } else {
                win = getWindow(elem);

                // Return the scroll offset
                return win ? ("pageXOffset" in win) ? win[i ? "pageYOffset" : "pageXOffset"] :
				jQuery.support.boxModel && win.document.documentElement[method] ||
					win.document.body[method] :
				elem[method];
            }
        };
    });

    function getWindow(elem) {
        return jQuery.isWindow(elem) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
    }




    // Create innerHeight, innerWidth, outerHeight and outerWidth methods
    jQuery.each(["Height", "Width"], function (i, name) {

        var type = name.toLowerCase();

        // innerHeight and innerWidth
        jQuery.fn["inner" + name] = function () {
            return this[0] ?
			parseFloat(jQuery.css(this[0], type, "padding")) :
			null;
        };

        // outerHeight and outerWidth
        jQuery.fn["outer" + name] = function (margin) {
            return this[0] ?
			parseFloat(jQuery.css(this[0], type, margin ? "margin" : "border")) :
			null;
        };

        jQuery.fn[type] = function (size) {
            // Get window width or height
            var elem = this[0];
            if (!elem) {
                return size == null ? null : this;
            }

            if (jQuery.isFunction(size)) {
                return this.each(function (i) {
                    var self = jQuery(this);
                    self[type](size.call(this, i, self[type]()));
                });
            }

            if (jQuery.isWindow(elem)) {
                // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
                return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement["client" + name] ||
				elem.document.body["client" + name];

                // Get document width or height
            } else if (elem.nodeType === 9) {
                // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
                return Math.max(
				elem.documentElement["client" + name],
				elem.body["scroll" + name], elem.documentElement["scroll" + name],
				elem.body["offset" + name], elem.documentElement["offset" + name]
			);

                // Get or set width or height on the element
            } else if (size === undefined) {
                var orig = jQuery.css(elem, type),
				ret = parseFloat(orig);

                return jQuery.isNaN(ret) ? orig : ret;

                // Set the width or height on the element (default to pixels if value is unitless)
            } else {
                return this.css(type, typeof size === "string" ? size : size + "px");
            }
        };

    });


})(window);

//
// lib\json2\json2.js
//
/*
    http://www.JSON.org/json2.js
    2010-08-25

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());

//
// lib\JsfIoc\JsfIoc.js
//
// license.txt
/*********************************************************************

(this is the MIT license)

Copyright (c) 2010 Frank Schwieterman

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

**********************************************************************/
// Binding.js



function BindingStart(ioc, name) {
    this._container = ioc;
    this._name = name;

    ExtendAsFluent.PrototypeOf(BindingStart);
}


BindingStart.prototype = {
    constructor: BindingStart,

    withConstructor: function (value) {
	///	<summary>
	///		Registers a component by constructor, returning a configuration builder with more options.
	///	</summary>
	///	<param name="value" type="function">
    ///     The constructor for the component
	///	</param>
	///	<returns type="Binding" />

        var binding = new Binding(this._name);
        binding.service = value;

        this._container.RegBinding(binding);

        return binding;
    },

    withInstance: function (value) {
	///	<summary>
	///		Registers a component with a single instance.
	///	</summary>
	///	<param name="value" type="Object">
    ///     An instance of the component
	///	</param>

        this._container.RegisterInstance(this._name, value);
    }
}


function Binding(name) {
    this._name = name;
    this._requires = [];
    this._parameters = [];
    this._singleton = false;
    this._eventSource = [];
    this._eventListener = [];

    ExtendAsFluent.PrototypeOf(Binding);
}

Binding.prototype = {
    constructor: Binding,

    withDependencies: function() {
    	///	<returns type="Binding" />
        Binding.AppendArgsToMember(arguments, this, "_requires");
    },

    withParameters: function() {
	    ///	<returns type="Binding" />
        Binding.AppendArgsToMember(arguments, this, "_parameters");

        for (var i = 0; i < this._parameters.length; i++) {
            if (typeof this._parameters[i] == "string") {
                this._parameters[i] = JsfIoc.prototype.Parameter(this._parameters[i]);
            }
        }
    },

    asSingleton: function() {
	    ///	<returns type="Binding" />
        this._singleton = true;
    },

    sendingEvents: function() {
	    ///	<returns type="Binding" />
        Binding.AppendArgsToMember(arguments, this, "_eventSource");
    },

    receivingEvents: function() {
	    ///	<returns type="Binding" />
        Binding.AppendArgsToMember(arguments, this, "_eventListener");
    },

    GetFriendlyName: function () {
        var result = this.service.toString();

        if (result.indexOf("(") > -1)
            result = result.slice(0, result.indexOf("("));
        if (result.indexOf("function ") == 0)
            result = result.slice("function ".length);

        if (Binding.WhitespaceRegex.test(result))
            return this._name;

        return result;
    }
}

Binding.WhitespaceRegex = /^\s*$/;

Binding.AppendArgsToMember = function(args, target, member) {
    for(var i = 0; i < args.length; i++) {
        target[member].push(args[i]);
    }
}

// ExtendAsFluent.js


ExtendAsFluent = {};

ExtendAsFluent.PrototypeOf = function (obj) {

    var prototype = obj.prototype;

    if (prototype.isFluent)
        return;

    prototype.isFluent = true;
    
    for (var key in prototype) {

        if (!prototype.hasOwnProperty(key))
            continue;

        if (typeof (prototype[key]) == "function") {

            prototype[key] = (function (original) {
                return function () {
                    var rv = original.apply(this, arguments);

                    if (typeof (rv) === "undefined")
                        return this;
                    else
                        return rv;
                }
            })(prototype[key]);
        }
    }
};
// JsfIoc.js

function JsfIoc() {
    this._bindings = [];
    this._singletons = [];
}

JsfIoc.prototype = {

    Register: function (name) {
        ///	<returns type="BindingStart" />

        return new BindingStart(this, name);
    },

    RegBinding: function (binding) {
        this._bindings[binding._name] = binding;
    },

    RegisterInstance: function (name, instance) {

        this._singletons[name] = instance;
    },

    Load: function (name) {

        var result = this._singletons[name];

        if (result)
            return result;

        var binding = this.GetBinding(name, "Load");

        result = new binding.service;

        for (var i = 0; i < binding._requires.length; i++) {
            var dependency = binding._requires[i];
            result[dependency] = this.Load(dependency);
        }

        if (binding.boundParameters) {
            for (var i = 0; i < binding._parameters.length; i++) {
                var parameter = binding._parameters[i];
                result[parameter._name] = binding.boundParameters[parameter._name];
            }
        }
        else {
            var values = Array.prototype.slice.call(arguments, 1); // all arguments after the first

            this._SetParametersToObject(binding, result, values)
        }

        for (var i = 0; i < binding._eventSource.length; i++) {

            (function (event, that) {

                result["_notify" + event] = function () {
                    that.NotifyEvent(event, arguments);
                };
            })(binding._eventSource[i], this);
        }

        if (binding._singleton) {
            this._singletons[name] = result;
        }

        return result;
    },
    Configure: function (name) {

        var binding = this.GetBinding(name, "Configure");

        var boundParameters = {};

        for (var i = 0; i < binding._parameters.length; i++) {
            this._SetParameterToObject(binding, binding._parameters[i], boundParameters, arguments[1 + i], i);
        }

        binding.boundParameters = boundParameters;
    },
    GetBinding: function (name, caller) {

        var binding = this._bindings[name];

        if (typeof (binding) == "undefined") {
            throw caller + " was called for undefined service '" + name + "'.";
        }

        return binding;
    },
    NotifyEvent: function (name, eventParameters) {

        for (var bindingName in this._bindings) {

            if (!this._bindings.hasOwnProperty(bindingName))
                continue;

            var events = this._bindings[bindingName]._eventListener;

            if (events) {

                for (var i = 0; i < events.length; i++) {

                    if (events[i] == name) {

                        var listener = this.Load(bindingName);

                        listener["On" + name].apply(listener, eventParameters || []);
                    }
                }
            }
        }
    },
    _SetParametersToObject: function(binding, target, values) {
        for (var i = 0; i < binding._parameters.length; i++) {
            this._SetParameterToObject(binding, binding._parameters[i], target, values[i], i);
        }
    },
    _SetParameterToObject: function (binding, parameter, target, value, index) {

        if (typeof(value) !== "undefined" && !parameter.validator(value)) {
            throw new Error("Invalid parameter #" + (index + 1) + " passed to " + binding._name + ".");
        }

        if (typeof(value) === "undefined") {
            if (typeof(parameter.defaultValue) !== "undefined") {
                target[parameter._name] = parameter.defaultValue;
            }
        } else {
            target[parameter._name] = value;
        }
    }
};

function JsfParameter(name) {
    this._name = name;
    this.validator = function () { return true; };

    ExtendAsFluent.PrototypeOf(JsfParameter);
}

JsfParameter.prototype = {
    constructor: JsfParameter,
    withValidator: function (value) {
        ///	<returns type="JsfParameter" />
        this.validator = value;
    },
    withDefault: function (value) {
        ///	<returns type="JsfParameter" />
        this.defaultValue = value;
    },
    asSingleJQueryElement: function () {
        ///	<returns type="JsfParameter" />

        this.validator = function (value) {

            return typeof (jQuery) != "undefined" &&
                    (value instanceof jQuery) &&
                    (value.length == 1);
        }
    }
}

JsfIoc.prototype.Parameter = function (name) {
    ///	<returns type="JsfParameter" />
    return new JsfParameter(name);
}



var ioc = new JsfIoc();





//
// client.js
//
// JScript File

//getCookie & setCookie pulled over from modalDialog.js
function getCookie(sName) {
    var aCookie = document.cookie.split('; ');
    for (var i = 0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split('=');
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    return null;
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    expiredays = (expiredays == null) ? 0 : expiredays;
    exdate.setDate(exdate.getDate() + expiredays);
    exdate = exdate.toGMTString();
    var domain = document.domain;
    if (typeof domain == 'string' && domain.indexOf(".") == -1) {
        domain = "";
    }
    var cookiestring = c_name + '=' + escape(value) +
        '; expires=' + exdate +
        '; path=/' +
        ((domain == '') ? ';' : ('; domain=' + domain + ';'));
    document.cookie = cookiestring;
}

//(url,key,value) Simliar to UrlUtils.UpdateQueryStringItem
function UpdateQueryStringItem(a, k, v) {
    var re = new RegExp("([?|&])" + k + "=.*?(&|$)", "i");
    if (a.match(re))
        return a.replace(re, RegExp.$1 + k + "=" + v + RegExp.$2);
    else
        return (a.indexOf('?') != -1) ? (a + '&' + k + "=" + v) : (a + '?' + k + "=" + v);
}

function ClickButton(e, formID, buttonID)
{
    e = e ? e : window.event ? event : null
    if (e)
    {
        var keyCode = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which ? e.which : void 0;
        if (keyCode == 13)
        {
            try
            {
		        var button = document.getElementById(buttonID);
                if (button && button.click)
                {
                    button.click();
                }
            }
            catch (e)
            {
            }
            return false;
        }
    }
}

var __eventListeners = [];
function addAREventListener(instance, eventName, listener) 
{
    var listenerFn = listener;
    if (instance.addEventListener) {
        instance.addEventListener(eventName, listenerFn, false);
    } else if (instance.attachEvent) {
        listenerFn = function() {
            listener(window.event);
        }
        instance.attachEvent("on" + eventName, listenerFn);
    } else {
        alert("Registration not supported! instance:" + instance + " eventname: " + eventName);
    }
    var event = {
        instance: instance,
        name: eventName,
        listener: listenerFn
    };
    __eventListeners.push(event);
    return event;
}

function removeEventListener(event) 
{
    var instance = event.instance;
    if(instance)
    {
	if (instance.removeEventListener) {
	    instance.removeEventListener(event.name, event.listener, false);
	} else if (instance.detachEvent) {
            instance.detachEvent("on" + event.name, event.listener);
	}
	for (var i = 0; i < __eventListeners.length; i++) {
	    if (__eventListeners[i] == event) {
		__eventListeners.splice(i, 1);
		break;
	    }
	}
    }
}

function unregisterAllEvents() 
{
    while (__eventListeners.length > 0) {
        removeEventListener(__eventListeners[0]);
    }
}

function getEventTarget(e) 
{
    var target;
    if (e)
    {
        if (e.target) 
        {
            target = e.target;
        }
	    else if (e.srcElement) 
	    {
	        target = e.srcElement;
	    }
	
	    if (target && target.nodeType == 3) 
	    {
	        target = target.parentNode;
		}
	}
	
	return target;
}

function findX(element)
{
    var x = 0;
    if(element.offsetParent)
        while(true) 
        {
          x += element.offsetLeft;
          if(!element.offsetParent)
            break;
          element = element.offsetParent;
        }
    else if(element.x)
        x += element.x;
    return x;
}

function findY(element)
{
    var y = 0;
    if(element.offsetParent)
        while(true)
        {
          y += element.offsetTop;
          if(!element.offsetParent)
            break;
          element = element.offsetParent;
        }
    else if(element.y)
        y += element.y;
    return y;
}

function getClientWidth() 
{
	return filterClientInfo (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function getClientHeight() 
{
	return filterClientInfo (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

function getScrollLeft() 
{
	return filterClientInfo (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function getScrollTop() 
{
	return filterClientInfo (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function filterClientInfo(win, doc, body) 
{
	var retVal = win ? win : 0;
	if (doc && (!retVal || (retVal > doc)))
		retVal = doc;
	return body && (!retVal || (retVal > body)) ? body : retVal;
}

function togglePanelView(id) {
    if (document.getElementById(id).className == 'expanded') {
        document.getElementById(id).className = 'collapsed';
    }
    else {
        document.getElementById(id).className = 'expanded';
    }
}

function togglePanelArrow(id) {
    if (document.getElementById(id).className == 'expanded') {
        document.getElementById(id).className = 'collapsed';
    }
    else {
        document.getElementById(id).className = 'expanded';
    }
}

/*********************************************************************
* Get an object, this function is cross browser
* *** Please do not remove this header. ***
* This code is working on my IE7, IE6, FireFox, Opera and Safari
* 
* Usage: 
* var object = getObject(element_id);
*
* @Author Hamid Alipour Codehead @ webmaster-forums.code-head.com  
**/
function get_Object(id) {
    var object = null;
    if (document.layers) {
        object = document.layers[id];
    } else if (document.all) {
        object = document.all[id];
    } else if (document.getElementById) {
        object = document.getElementById(id);
    }
    return object;
}

//
// clientPopup.js
//
/// <reference path="Intellisense.js" />

// JScript source code
var popupArray = [];

document.onclick=check;

function check(e){
  var target = (e && e.target) || (event && event.srcElement);
  
  var divs = $('.PopUp').toArray();
  var i = 0;
  var obj; 
  var countHiddenFloats = 0;

   if (popupArray.length > 0)
   {
      for (i=0; i<popupArray.length; i++)
      {
        if (!target.floater)
        {
           obj=document.getElementById(popupArray[i]);
           obj.style.visibility='hidden';
           removeArrItem(popupArray, popupArray[i]);
           countHiddenFloats++;
        }
      }
   }
   
   if (countHiddenFloats > 0)
       RestoreObjectTags();   
}

function initializeFloater(triggerID, floaterID, click, mouseout, Xoffset, Yoffset) 
{
    if (!offset) var offset = 0;
    if (mouseout == 'undefined') var mouseout = true;
	var trigger = document.getElementById(triggerID);
	var floater = document.getElementById(floaterID);
		
	if (trigger && floater)
	{   
		trigger.floater = floater;
		floater.isFocused = false;
		floater.isFloater = true;
		floater.Xoffset = Xoffset;
		floater.Yoffset = Yoffset;
		
		if (click)
		{
		    trigger.onclick = function() {
		     var i = 0;
             for (i =0; i < popupArray.length; i++)
             {
                 if (popupArray[i] !=floater.id)
                 {
                     hideFloater(popupArray[i], true);
                     removeArrItem(popupArray, popupArray[i]);
                 }
             }
		        return false;
		    }
		}
		
		var divs = floater.getElementsByTagName('div');

		for (var i=0; i < divs.length; i++)
		{
		    if (divs[i].className == "button")
		    {
		        addAREventListener(divs[i],
		            'click',
		            function() { hideFloater(floater.id, true);
		                         removeArrItem(popupArray, popupArray[i]);});
		    }
		}
		
		addAREventListener(trigger, 
		    click ? 'click' : 'mouseover',
		    trigger_onfire);
		addAREventListener(floater,
		    'mouseover',
		    floater_onmouseover);
		    
//		if(mouseout)
//		{
//		    addAREventListener(trigger,
//			    'mouseout',
//			    trigger_onmouseout);

//		    addAREventListener(floater,
//                'mouseout',
//                floater_onmouseout);
//		}
	}
}

function floater_onmouseover(e)
{
	if (!e) var e = window.event;
	
    var element = getEventTarget(e);
    if (element)
    {
        if (element.isFloater)
        {
            element.isFocused = true;
        }
        else
        {
            while (element)
            {
                element = element.parentNode;
                
                if (element.isFloater)
                {
                    element.isFocused = true;
                    break;
                }
            }
        }
    }    
}


//function floater_onmouseout(e)
//{
//    if (!e) var e = window.event;

//    var element = getEventTarget(e);
//  
//	if (element.isFloater)
//        {
//            element.isFocused = false;
//	    setTimeout("hideFloater('" + element.id+ "')",100);
//        }
//        else
//        {
//            while (element)
//            {
//                element = element.parentNode;
//                
//                if (element.isFloater)
//                {
//                    element.isFocused = false;
//		             setTimeout("hideFloater('" + element.id+ "')",100);
//                    break;
//                }
//            }
//        }
//     
//    e.cancelBubble = true;
//}

function hideFloater(elementID, forceClose)
{
    var element = document.getElementById(elementID);
    if (element) 
    {
        if (forceClose)
        {
            element.isFocused = false;
        }
        if (!element.isFocused)
        {
            element.style.visibility = "hidden";
        }
    }
    
    RestoreObjectTags();    
}

function trigger_onfire(e) 
{
    if (!e) var e = window.event;
    
    //close popup if the popup is not target and open.
    var element = getEventTarget(e);
    var divs = $('.PopUp').toArray();
    var i = 0;

     if (popupArray.length > 0)
     {
        for (i=0; i <popupArray.length; i++)
        {
            hideFloater(popupArray[i], true);
            removeArrItem(popupArray, popupArray[i]);
        }
     }

    
    if (element && element.floater)
    {
        var floater = element.floater;
        var floaterWidth = floater.offsetWidth;
        var floaterHeight = floater.offsetHeight;
        var Xoffset = floater.Xoffset ? floater.Xoffset : 0;
        var Yoffset = floater.Yoffset ? floater.Yoffset : 0;
        
        //standard position
        var x = findX(element) + Xoffset;
        var y = findY(element) + element.offsetHeight + Yoffset;
                
        var browserWidth = getClientWidth();
        var browserHeight = getClientHeight();
        var scrollLeft = getScrollLeft();
        var scrollTop = getScrollTop();   
                
        if (browserWidth > floaterWidth)
        {
            if (x < scrollLeft)
            {
                x = scrollLeft;
            }
            else if (x + floaterWidth > browserWidth + scrollLeft)
            {
                x = browserWidth - floaterWidth + scrollLeft;                    
            }
        }
        
        if (browserHeight > floaterHeight)
        {
            if (y + floaterHeight > browserHeight + scrollTop)
            {
                y = y - floaterHeight - element.offsetHeight - (2*Yoffset);
                y = y > scrollTop ? y : scrollTop;
            }
        }
             
        floater.style.left = x + "px";
        floater.style.top = y + "px";
        floater.style.visibility = "visible";
        
        popupArray[popupArray.length] = floater.id;
        
        HideObjectTags($(floater), true);
    }
}

//function trigger_onmouseout(e)
//{
//	if (!e) var e = window.event;
//	
//    var element = getEventTarget(e);
//    
//    if (element && element.floater)
//    {
//       setTimeout("hideFloater('" + element.floater.id + "')",100);
//    }
//}

function removeArrItem(arr, id)
{
   if (id)
   {
       for (var i = arr.length - 1; i >= 0; i -= 1)
       {
            if (arr[i]==id)
            {
                arr.splice(i, 1);
            }
       }
   }
}


var HiddenObjects = [];

function HideObjectTags(overlapTarget, onlyHideOverlapping) {
    // hides all <object> tags (ActionX, Flash content) that overlap with 'overlapTarget'.
    // if overlapTarget is not specified, all <object>s are hidden.
    // We now hide <select> tags, as IE6 has z-index issues with those.

    var hiddenObjects = HiddenObjects;

    var elementsNotToHide = [];

    if (overlapTarget != null) {
        elementsNotToHide = overlapTarget.find("*");
    }

    $("object:visible, embed:visible, select:visible").each(function () {

        if (onlyHideOverlapping && overlapTarget != null && !AR.IntersectionDetection.DoElementsOverlap(overlapTarget, $(this))) {
            return;
        }

        if ($.inArray(this, elementsNotToHide) >= 0) {
            return;
        }

        $(this).css("visibility", "hidden");
        hiddenObjects.push(this);
    });
}

function RestoreObjectTags() {
    var objectsToRestore = HiddenObjects;
    HiddenObjects = [];

    jQuery.each(objectsToRestore, function () {
        $(this).css("visibility", "visible");
    });
}

//
// modalDialog.js
//
function showModalDialog(dialogID, underlayID, wrapperID)
{
    var success = false;
    setCookie('test','none',1);
    if(getCookie('test'))
    {
        if(getCookie('ARUKModal') != 'noshow')
        {
            try
            {
                var u = document.getElementById(underlayID);
                var p = document.getElementById(dialogID);
                var w = document.getElementById(wrapperID);
                if(p.style.visibility)
                {
                    p.style.visibility='visible';
                    u.style.visibility='visible';
                    w.style.visibility='visible';
                }
                if(p.style.display)
                {
                    p.style.display='block';
                    u.style.display='block';
                    w.style.display='block';
                }
                //success = true;
            }
            catch(ex)
            {
            }
            /*if(success)
            {
                setCookie('ARUKModal','noshow',1);
            }*/
        }
    }
}

function hideModalDialog(dialogID, underlayID, wrapperID)
{
    var u = document.getElementById(underlayID);
    var p = document.getElementById(dialogID);
    var w = document.getElementById(wrapperID);
    if(p.style.visibility)
    {
        p.style.visibility='hidden';
        u.style.visibility='hidden';
        w.style.visibility='hidden';
    }
    else if(p.style.display)
    {
        p.style.display='none';
        u.style.display='none';
        w.style.display='none';
    }
    setCookie('ARUKModal','noshow',1);
}

function hideModalDialogForever(underlayID, dialogID, wrapperID)
{
    var u = document.getElementById(underlayID);
    var p = document.getElementById(dialogID);
    var w = document.getElementById(wrapperID);
    if(p.style.visibility)
    {
        p.style.visibility='hidden';
        u.style.visibility='hidden';
        w.style.visibility='hidden';
    }
    else if(p.style.display)
    {
        p.style.display='none';
        u.style.display='none';
        w.style.display='none';
    }
    setCookie('ARUKModal','noshow',365);
}
//
// jQuery\main.js
//
/// <reference path="../Intellisense.js" />

//reverse a collection of jquery objects.
$.fn.reverse = [].reverse;

//trim whitespace from a string
$.fn.trim = function(str) {
	if (str === undefined) {
		str = $(this)[0];
	}
	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
};

//determine if a value is an int
$.fn.isInt = function(x) {
	if (x === undefined) {
		x = $(this).val();
	}
	var objRegExp = /(^-?\d\d*$)/;

	//check for integer characters
	return objRegExp.test(x);
};

// Array Remove
Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

String.prototype.startsWith = function (prefix) {
    return (this.substr(0, prefix.length) === prefix);
}

String.prototype.endsWith = function(str){
    return (this.match(str+"$")==str)
};

$.extend(AR, {
    _isMobileDevice: false,
    Config: {
        ClientServiceUrl: "/Services/Client.svc/",
        ApplicationPath: "",
        ErrorLoggingHandler: "~/Handlers/LogClientError.ashx"
    },
    AnimationSpeed: function () {
        if (AR.IsIE6() == true) {
            return 10;
        }
        else {
            return 500;
        }
    },
    ServerSideData: {
        Data: {},
        Set: function (data, key) {
            if (key) {
                this.Data[key] = data;
            }
        },
        Initialize: function (data) {
            this.Data = data;
        },
        Get: function (key) {
            var obj = this.Data[key];
            if (obj != null) {
                return obj;
            }
            else {
                this.Data[key] = {};
                return this.Data[key];
            }
        },
        GetByDom: function (item) {
            return this.Get($(item).attr("id"));
        }

    },
    IsIE6: function () { return (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6"); },
    ImageServer: {},
    ResponseCode: {
        "DidNotReachServer": -1,  // indicates user aborted the request, or the clients connection was lost before receiving a server response
        "Success": 0,
        "Failure": 1,
        "UserError": 2,
        "NotFound": 3,
        "PartialFailure": 4
    },
    ShouldLogResponseCode: function (responseCode) {
        return responseCode == AR.ResponseCode.Failure;
    },
    ItemType: // should match Allrecipes.CoreClasses.RecipeBox.ItemType
		{Recipe: 1, Article: 2, WebLink: 3, Reference: 4, PersonalRecipe: 5, CustomRecipe: 6, Menu: 7, NotSet: -1 },
    MenuType: { MenuAR: 1, MenuPersonal: 2, MenuSample: 3, NotSet: -1 },
    TypeSpecificID: 0,
    DebugVars: function (vars) { //Expects an array of format: { "var1", var1, "var2", var2, "var3", var3 }
        var debug = "<table cellspacing=3>";
        for (x = 0; x < vars.length; x++) {
            debug += "<tr><td align='right' style='font-weight:bold'>" + vars[x] + ":</td><td>" + vars[x + 1] + "</td></tr>";
            x++;
        }
        debug += "</table>";
        return debug;
    },
    LogError: function (description, source, title) {
        description = (description == null) ? "No Description" : description;

        AR.LogErrorEx({ description: description }, source, title);
    },
    LogAlert: function (description, source, title) {
        description = (description == null) ? "No Description" : description;

        AR.LogAlertEx({ description: description }, source, title);
    },
    SetCursor: function (cursorStyle) { document.body.style.cursor = cursorStyle; },
    Cursor: {
        "SetWait": function () { document.body.style.cursor = 'wait'; },
        "SetDefault": function () { document.body.style.cursor = 'default'; }
    },
    HostName: function () {
        var hostName = location.host;
        if (AR.Config.ApplicationPath.indexOf("/") != 0) {
            hostName += "/";
        }
        return hostName + AR.Config.ApplicationPath;
    },
    SetIsMobileDevice: function (value) {
        this._isMobileDevice = value;
    },
    IsMobileDevice: function () {
        return this._isMobileDevice;
    }
});


// CLIENT SIDE MESSAGEBOX
AR.MessageBox = {
    MessageType: { "Information": 0, "Warning": 1, "Failure": 2, "Success": 3 },
    MessageClass: ['message-box', 'message-box message-warning', 'message-box message-failure', 'message-box message-success'],
    PrintMessage: function (targetID, messageType, messageText, persist) {
        var target = $(targetID);
        target.removeClass(AR.MessageBox.MessageClass[1])
			.removeClass(AR.MessageBox.MessageClass[2])
			.removeClass(AR.MessageBox.MessageClass[3])
			.addClass(AR.MessageBox.MessageClass[messageType]);
        var speed = 500;
        target.hide().html(messageText).fadeIn(speed, function () {
            $(this).css('zoom', '');  // fadeIn leaves a CSS zoom value on the attribute, which may cause IE to mark the node with hasLayout
            if (persist == null || persist == false) {
                // after 5 seconds close message box
                setTimeout(function () { target.fadeOut(speed); }, 5000);
            }
        });
    },
    TryGetSelector: function (id) {
        if (id == null || id == '') {
            id = "#msgClientPage";
        }
        return id;
    },
    ShowSuccess: function (msg, selector, persist) { AR.MessageBox.PrintMessage(AR.MessageBox.TryGetSelector(selector), AR.MessageBox.MessageType.Success, msg, persist); },
    ShowFailure: function (msg, selector, persist) { AR.MessageBox.PrintMessage(AR.MessageBox.TryGetSelector(selector), AR.MessageBox.MessageType.Failure, msg, persist); },
    ShowWarning: function (msg, selector, persist) { AR.MessageBox.PrintMessage(AR.MessageBox.TryGetSelector(selector), AR.MessageBox.MessageType.Warning, msg, persist); },
    ShowInfo: function (msg, selector, persist) { AR.MessageBox.PrintMessage(AR.MessageBox.TryGetSelector(selector), AR.MessageBox.MessageType.Information, msg, persist); }
};


// TOOLBOXES

AR.Toolbox = {
    Close: function () {
        $(".toolbox-actions-trigger-active").click();
    }
}

//END TOOLBOXES


// THIS BINDS THE ROW HOVER OVER ACTIONS TO rowOver FUNCTION
var rowOver = function () {
    var thisRow = $(this);
    thisRow.addClass("recipe-list-row-active");
    var recipeName = thisRow.find(".title").text();
    $(".recipe-name").text(recipeName);
    $(this).find(".toolbox-header h1").show();
};
$(".row").live("mouseover.row-over", rowOver);

// THIS BINDS THE ROW HOVER OUT ACTIONS TO rowOut FUNCTION
var rowOut = function () {
    $(this).removeClass("recipe-list-row-active");
    if ($(this).find(".toolbox-header").data("active") != "active") {
        $(this).find(".toolbox-header h1").hide();
    }
};
$(".row").live("mouseout.row-out", rowOut);

$(".toolbox-header").live("click", function () {
    var toolboxLink = $(this).find("a");
    if ($(this).data("active") == "active") {
        $(this).next("ul").slideUp(300, function callback() {
            toolboxLink.removeClass("toolbox-actions-trigger-active");
        });
        $(this).data("active", "");
    } else {
        toolboxLink.addClass("toolbox-actions-trigger-active");
        $(this).next("ul").slideDown(300);
        $(this).data("active", "active");
    }
});


// Dialogs
AR.Dialog = {
    Overlay: {},
    ShowLayer: function (id, speed) {

        if (AR.SlideUpAllOptionsDropdowns) {
            AR.SlideUpAllOptionsDropdowns();
        }

        var mb = $(id);
        speed = speed | 200;

        AR.TabBlocker.singletonInstance.BlockTabindexes($(document), mb);

        mb.fadeIn(speed);
        $(this.Overlay).css({ "opacity": "0.20" }).fadeIn(speed);
        this.SizeModalToContent(mb);
        this.CenterModal(mb);
        this.ApplyFocusToModal(mb);
    },
    SizeModalToContent: function (modalBox) {
        modalBox = modalBox || $(".modal:visible");

        var resizeableContent = modalBox.find(".rsz-content").children();

        if (resizeableContent.length > 0) {
            var contentWidth = resizeableContent.outerWidth();
            var contentHeight = resizeableContent.outerHeight();

            modalBox.width(contentWidth + 18).height(contentHeight + 36);
            modalBox.find(".rsz-footer .rsz-footer-content, .rsz-header .rsz-header-content").width(contentWidth - 6);
            modalBox.find(".rsz-right-border, .rsz-left-border").height(contentHeight);
        }
    },
    CenterModal: function (modalBox) {
        var mHeight = modalBox.outerHeight(true);
        var mWidth = modalBox.outerWidth(true);
        var winHeight = $(document).height();
        var visibleHeight = document.documentElement.clientHeight;
        var winWidth = $(document).width();
        var scrollTop = $(document).scrollTop();
        var posTop = (visibleHeight / 2 - mHeight / 2) + scrollTop;
        if (posTop < 0)
            posTop = 0;
        var posLeft = winWidth / 2 - mWidth / 2;
        if (posLeft < 0)
            posLeft = 0;
        modalBox.css({ "position": "absolute", "top": posTop, "left": posLeft });
        AR.AdSuppress(modalBox);
        $(this.Overlay).css({ "height": winHeight, "width": winWidth });
    },
    CloseModalBox: function (onFinishCallback, speed) {
        speed = speed | 200;

        var targetElements = $(this.Overlay).add(".modal");

        var callbacksToIgnore = targetElements.length - 1;

        this.RunOnClosingHandlers();

        var that = this;

        var restoreElementsIfAppropriate = function() {
            if (callbacksToIgnore <= 0) {

                AR.TabBlocker.singletonInstance.RestoreTabindexes();
                that.RunOnClosedHandlers();

                if (onFinishCallback != null) {
                    onFinishCallback();
                }
            }
        };

        restoreElementsIfAppropriate();

        targetElements.fadeOut(speed, function () {
            restoreElementsIfAppropriate();
            callbacksToIgnore = callbacksToIgnore - 1;
        });
    },
    CloseModalBoxAndShowAnother: function (id) {
        AR.Dialog.CloseModalBox(function () {
            AR.Dialog.ShowLayer(id);
        });
    },
    EnableGlobalEscapeHandler:function() {
    
        AR.Dialog.DisableGlobalEscapeHandler();

        $(document).bind("keyup.DialogEscapeHandler", function (e) {
            if (e.keyCode == 27) {
                AR.Dialog.CloseModalBox();
            }
        });
    },
    DisableGlobalEscapeHandler:function() {
        $(document).unbind("keyup.DialogEscapeHandler");
    },
    _onClosingHandlers: [],
    _onClosedHandlers: [],
    AddOnClosingHandler: function (callback) {
        this._onClosingHandlers.push(callback);
    },
    RunOnClosingHandlers: function () {
        var currentHandlers = this._onClosingHandlers;
        this._onClosingHandlers = [];
        $.each(currentHandlers, function (index, value) { value(); });
    },
    AddOnClosedHandler: function (callback) {
        this._onClosedHandlers.push(callback);
    },
    RunOnClosedHandlers: function () {
        var currentHandlers = this._onClosedHandlers;
        this._onClosedHandlers = [];
        $.each(currentHandlers, function (index, value) { value(); });
    },
    ApplyFocusToModal: function (mb) {

        var allInputs = mb.find("input:visible, textarea:visible");

        if (allInputs.length > 0 && !allInputs[0].disabled) {
            allInputs[0].focus();
        }
    }
};

AR.VisitorInfo = {
    IsLoggedIn: function () { return this._data._isLoggedIn; },
    IsRecognized: function () { return this._data._isRecognized; },
    IsSupportingMember: function () { return this._data._isSupportingMember; },
    IsLoggedInAsASupportingMember: function () { return this._data._isLoggedIn && this._data._isSupportingMember; },
    VisitorID: function () { return this._data._ID; },
    _data: {
        _isLoggedIn: false,
        _isRecognized: false,
        _isSupportingMember: false,
        _ID: 0
    }
};

ioc.Register("_visitorInfo").withInstance(AR.VisitorInfo);

AR.Loader = {
    Show: function () {
        //AR.Dialog.ShowLayer('.loader', 10);
        AR.Cursor.SetWait();
    },
    Hide: function (callback) {
        //if (callback != null) {
        //    callback();
        //}
        AR.Dialog.CloseModalBox(callback, 10);
        AR.Cursor.SetDefault();
    }
}

AR.Photos = {
    ShowUserPhotoUploadDialog: function (data) {

        AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.RecipeAddPhoto, AR.Analytics.Action.GetItem(data.ItemType));

        var modalBox = $('.modal-upload-a-photo');
        var iframe = modalBox.find('iframe')[0];
        var continueButton = modalBox.find('.modal-upload-a-photo-continue-button');
        continueButton.unbind('click');
        continueButton.bind('click', function (e) {
            e.preventDefault();
            var iframeDocument = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.document;
            iframeDocument.IframeSubmit();
        });
        // iframe callbacks are set on the window / globally so they are accessible from
        // the iframe
        IframeCallback_RecenterIframeDialog = function (iframeDimensionsFunc, buttonText) {
            modalBox.find('.modal-upload-a-photo-continue-button-text').html(buttonText);

            var iframeDimensions = iframeDimensionsFunc();

            $(iframe).css('height', iframeDimensions.Height);
            AR.Dialog.CenterModal(modalBox);
        };

        IframeCallback_FinishIframeDialog = function (photoID, previewImage50x50, previewImage140x140) {
            $('#' + data.ResultField).val(photoID);
            AR.Dialog.CloseModalBox();
            var callback = eval(data.ClientCallback);
            callback(photoID, previewImage50x50, previewImage140x140);
        };
        $(iframe).attr('src', data.IframeSrc);
        AR.Dialog.ShowLayer(modalBox);
    }
};

AR.ContactUs = {
    PopulateRecipeContactUs: function (listItem) {
        if (listItem) {
            var layer = $(".modal-recipe-contact-us");
            $(".contact-us-recipe-name", layer).html(listItem.title);
            $(".contact-us-recipe-reply-address", layer).val(listItem.email);
            $(".recipe-approval-status", layer).val(listItem.status);
            $(".recipe-item-owner-id", layer).val(listItem.visitor);
            $(".recipe-shared-item-id", layer).val(listItem.ID);
            $(".recipe-approval-status-updated", layer).val(listItem.dateUpdated);
            $(".recipe-total", layer).val(listItem.recipeTotal);
            $("#commit", layer).unbind("click").click(listItem.commit);
            if (listItem.email.length > 0) {
                $(".contact-us-recipe-message").focus();
            }
            else {
                $(".contact-us-recipe-reply-address").focus();
            }
        }
    }
};

AR.TypesDlg = {
    // The type names must match the values of enum ItemType (case sensitive)
    RecipeTypes: ["PersonalRecipe", "WebLink", "Reference", "CustomRecipe", "Recipe"],
    MenuTypes: ["PersonalMenu", "Menu"],
    SwitchTypes: function (shift, typeGroupID, type) {
        if (typeGroupID == 1) {
            AR.TypesDlg.SwitchRecipeTypes(shift, type);
        }
        else if (typeGroupID == 2) {
            AR.TypesDlg.SwitchMenuTypes(shift, type);
        }
    },
    SwitchRecipeTypes: function (shift, type) {
        type = type || $(".recipe-type-content:visible").attr('class').split(' ')[1];

        $(".recipe-type-content").each(function () {
            $(this).hide();
        });

        var index = $.inArray(type, this.RecipeTypes);
        index = index + shift;
        if (index < 0) {
            index = this.RecipeTypes.length - 1;
        }
        else if (index >= this.RecipeTypes.length) {
            index = 0;
        }
        $("." + this.RecipeTypes[index]).show();
    },
    SwitchMenuTypes: function (shift, type) {
        type = type || $(".menu-type-content:visible").attr('class').split(' ')[1];

        $(".menu-type-content").each(function () {
            $(this).hide();
        });

        var index = $.inArray(type, this.MenuTypes);
        index = index + shift;
        if (index < 0) {
            index = this.MenuTypes.length - 1;
        }
        else if (index >= this.MenuTypes.length) {
            index = 0;
        }
        $("." + this.MenuTypes[index]).show();
    }
};

// Submitted Recipe Approval Status Types
AR.RecipeApprovalStatus = {
    Types: ["AwaitingReview", "Accepted", "NotAccepted", "NotSubmittedForReview"],
    SwitchTypes: function (listItem) {
        listItem = listItem || $(".recipe-approval-status-type-content:visible").attr('class').split(' ')[1];
        var layer = $(".recipe-approval-status-type-content " + listItem.status);
        var index = $.inArray(listItem.status, this.Types);
        var titleID = '#recipe-name-' + listItem.status;
        $(".recipe-approval-status-type-content").each(function () {
            $(this).hide();
        });
        $("." + this.Types[index]).show();
        $(titleID).html(listItem.title);
    }
};


AR.StarRating = {
    SetStarRatingImages: function (ratingList, value) {
        var selectedClass = 'star-selected';
        ratingList.find('.' + selectedClass).removeClass(selectedClass);

        switch (value) {
            // these case statements intentionally fall through to the next                                                        
            case 5:
                $('.five-stars', ratingList).addClass(selectedClass);
            case 4:
                $('.four-stars', ratingList).addClass(selectedClass);
            case 3:
                $('.three-stars', ratingList).addClass(selectedClass);
            case 2:
                $('.two-stars', ratingList).addClass(selectedClass);
            case 1:
                $('.one-star', ratingList).addClass(selectedClass);
        }
    },

    CreateStarRatingController: function (ratingInputId) {
        var inputElement = $('#' + ratingInputId);
        var ratingList = inputElement.prev('ul');

        function onRatingChanged(newValue) {
            inputElement.val(newValue);
            AR.StarRating.SetStarRatingImages(ratingList, newValue);
        }

        function getRating() {
            var rating = inputElement.val();

            if (1 <= rating && rating <= 5) {
                return rating;
            }

            return 0;
        }

        onRatingChanged(parseInt(inputElement.val()));  // set stars to display current input value
        $('a.five-stars', ratingList).click(function () { onRatingChanged(5); return false; });
        $('a.four-stars', ratingList).click(function () { onRatingChanged(4); return false; });
        $('a.three-stars', ratingList).click(function () { onRatingChanged(3); return false; });
        $('a.two-stars', ratingList).click(function () { onRatingChanged(2); return false; });
        $('a.one-star', ratingList).click(function () { onRatingChanged(1); return false; });

        return {
            SetRating: onRatingChanged,
            GetRating: getRating
        };
    }
};

AR.Search = {
    Load: function () {
        $("#ctl00_btnSearch").click(function () {
            return DoSearch('checkcarat');
        });
        $('.search-link-recipes').click(function () {
            return moveSelectedSearch($(this));
        });
        $('.search-link-ingredients').click(function () {
            return moveSelectedSearch($(this));
        });
        $(".search-link-articles").click(function () {
            return moveSelectedSearch($(this));
        });
        $('.search-link-advanced').click(function () {
            return DoSearch('advanced');
        });
        $('.search-link-glossary').click(function () {
            return DoSearch('glossary');
        });
        $('.search-link-collection').click(function () {
            return DoSearch('collection');
        });
    }
};

$(document).ready(function () {

    //failsafe in case primary nav init failed during UserControl load, try to load it again once the document has finished loading
    if (AR.PrimaryNav != null && AR.PrimaryNav._initFinished == 0) {
        AR.PrimaryNav.OnInit();
    }

    // do post document load processing
    if (AR.PrimaryNav != null && AR.PrimaryNav._loadFinished == 0) {
        AR.PrimaryNav.OnLoad();
    }


    if (AR.DialogLinker != null) {
        AR.DialogLinker.LinkMembershipDialogs($(document));
    }

    AR.Dialog.Overlay = $('.modal-overlay:not(.loader)');
    $('a.modal-link').each(function () {
        $(this).click(function (event) {
            event.preventDefault();
        });
    });
    $(".close-modal").click(function (e) {
        AR.Dialog.CloseModalBox();
        e.preventDefault();
    });
    $(".add-photo").click(function () {
        AR.Dialog.ShowLayer(".modal-add-a-photo", null);
    });
    $(".open-recipe-approvalstatus-type-modal").click(function () {
        AR.Dialog.ShowLayer(".modal-recipe-approval-status-types", AR.RecipeApprovalStatus.SwitchTypes(AR.ServerSideData.GetByDom(this)));
    });
    $('.open-photo-upload-link').click(function () {
        var data = AR.ServerSideData.GetByDom(this);
        AR.Photos.ShowUserPhotoUploadDialog(data);
    });
    $(".open-recipe-contact-us-modal").click(function () {
        AR.Dialog.ShowLayer(".modal-recipe-contact-us", AR.ContactUs.PopulateRecipeContactUs(AR.ServerSideData.GetByDom(this)));
    });
    $(".open-add-folder-modal").click(function () {
        AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.FolderAdd);
        $("#msgAddFolderDialog").hide();
        $(".foldername-add").val('');
        AR.Dialog.ShowLayer(".modal-folder-add", null);

        var funcExclude = function (folderID) {
            if (isNaN(folderID) || folderID <= 0) {
                return true;
            }
            return false;
        };

        AR.Folders.Dom.LoadDropDownList($(".folder-add-ddl"), funcExclude, true);
        AR.Folders.Dom.SetDropdownSelected(".folder-add-ddl", AR.ServerSideData.GetByDom(this).selectedFolderID);
    });

    $('.modal-folder-add .folder-add-close-button').click(function () {
        $(".foldername-add").val('');
        $('#msgAddFolderDialog').hide;
        AR.Dialog.CloseModalBox();
    });

    //wire up top nav search functionality
    AR.Search.Load();

    AR.Share.LoadDialogs();

    AR.Dialog.EnableGlobalEscapeHandler();

    $('.add-to-brands-i-like').click(function () {
        var brandID = AR.ServerSideData.Get("BrandID");
        AR.BrandedProfile.AddToBrandsILike(brandID);
    });
});

// add to folder action - TEST ONLY
function addToFolder(successMessage) {
    AR.Dialog.CloseModalBox();
    AR.MessageBox.PrintMessage("#msgClientPage", AR.MessageBox.MessageType.Failure, successMessage);
}

AR.ClientService = {
    DoGet: function (url, callback) {

        AR.SetModuleLogContent("AR.ClientService request", {
            verb: "GET",
            url: url,
            clientServiceUrl: AR.LogEval("AR.Config.ClientServiceUrl")
        });

        var ajaxSuccessCallback = this.CreateSuccessHandler(callback);
        var ajaxErrorCallback = this.CreateErrorHandler(callback);

        if (!this.__suppressLoaderChangeOnNextServiceCall) {
            AR.Loader.Show();
        }

        try {
            $.ajax({
                type: "GET",
                url: AR.Config.ClientServiceUrl + url,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: ajaxSuccessCallback,
                error: ajaxErrorCallback
            });
        }
        catch (e) {
            AR.SetModuleLogContent("AR.ClientService response", {
                message: "An exception was thrown calling $.ajax() for a GET request",
                exception: e
            });
            ajaxErrorCallback(null, null, null);
        }

        this.__suppressLoaderChangeOnNextServiceCall = false;
    },
    DoInvoke: function (verb, url, postBody, callback) {

        AR.SetModuleLogContent("AR.ClientService request", {
            verb: verb,
            url: url,
            postBody: postBody,
            clientServiceUrl: AR.LogEval("AR.Config.ClientServiceUrl")
        });

        var ajaxSuccessCallback = this.CreateSuccessHandler(callback);
        var ajaxErrorCallback = this.CreateErrorHandler(callback);

        if (!this.__suppressLoaderChangeOnNextServiceCall) {
            AR.Loader.Show();
        }

        try {
            $.ajax({
                type: verb,
                url: AR.Config.ClientServiceUrl + url,
                data: JSON.stringify(postBody),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: ajaxSuccessCallback,
                error: ajaxErrorCallback
            });
        }
        catch (e) {
            AR.SetModuleLogContent("AR.ClientService response", {
                message: "An exception was thrown calling $.ajax() for a non-get request",
                verb: verb,
                exception: e
            });
            ajaxErrorCallback(null, null, null);
        }

        this.__suppressLoaderChangeOnNextServiceCall = false;
    },
    __suppressLoaderChangeOnNextServiceCall: false,
    SuppressNextLoaderChange: function () {
        this.__suppressLoaderChangeOnNextServiceCall = true;
    },
    CreateSuccessHandler: function (callback) {
        if (this.__suppressLoaderChangeOnNextServiceCall) {
            return function (data) {
                AR.SetModuleLogContent("AR.ClientService response", {
                    message: "A client service call succeeded",
                    response: data
                });

                callback(data);
            };
        } else {
            return function (data) {
                AR.SetModuleLogContent("AR.ClientService response", {
                    message: "A client service call succeeded",
                    response: data
                });

                AR.Loader.Hide(function () {
                    callback(data);
                });
            };
        }
    },
    CreateErrorHandler: function (callback) {
        if (this.__suppressLoaderChangeOnNextServiceCall) {
            return function (XMLHttpRequest, ignored1, ignored2) {

                var responseCode = AR.ResponseCode.Failure;

                if (XMLHttpRequest != null) {

                    responseCode = AR.ResponseCode.DidNotReachServer;

                    AR.SetModuleLogContent("AR.ClientService response", {
                        message: "A client service call failed",
                        status: XMLHttpRequest.status,
                        statusText: XMLHttpRequest.statusText
                    });
                }

                callback({
                    Message: "There was an unexpected error.",
                    ResponseCode: responseCode,
                    Data: null
                });
            }
        } else {
            return function (XMLHttpRequest, ignored1, ignored2) {

                var responseCode = AR.ResponseCode.Failure;

                if (XMLHttpRequest != null) /* null indicates the network was not hit */{

                    responseCode = AR.ResponseCode.DidNotReachServer;

                    AR.SetModuleLogContent("AR.ClientService response", {
                        message: "A client service call failed",
                        status: XMLHttpRequest.status,
                        statusText: XMLHttpRequest.statusText
                    });
                }

                AR.Loader.Hide(function () {
                    callback({
                        Message: "There was an unexpected error.",
                        ResponseCode: responseCode,
                        Data: null
                    });
                });
            }
        }
    },
    BoolToString: function (value) {
        return (value == true || value.toString().toLowerCase() == "true") ? 'true' : 'false';
    },

    ContactUs: function (address, subject, message, category, callback) {
        this.DoInvoke('POST', 'Contact/Us/' + category, { address: address, subject: subject, message: message }, callback);
    },

    CreateFolder: function (name, parentFolderID, callback) {
        this.DoInvoke('POST', 'Folder', { name: name, parentFolderID: parentFolderID }, callback);
    },

    DeleteFolder: function (folderID, name, callback) {
        this.DoInvoke('POST', 'Folder/Delete/' + folderID, { name: name }, callback);
    },

    DeleteFromRecipeBox: function (savedItemID, folderID, callback) {
        this.DoInvoke('POST', 'Recipebox/Item/Delete/' + savedItemID, { folderID: folderID }, callback);
    },

    GetNote: function (savedItemID, callback) {
        this.DoGet('Note/' + savedItemID, callback);
    },

    GetPhotos: function (itemID, isRecipe, callback) {
        this.DoGet('Photos/' + itemID + '/' + this.BoolToString(isRecipe), callback);
    },

    GetPhotosPaged: function (itemID, isRecipe, pageNumber, pageSize, callback) {
        this.DoGet('Photos/' + itemID + '/' + this.BoolToString(isRecipe) + '?pageNumber=' + pageNumber + '&pageSize=' + pageSize,
		 callback);
    },

    GetReview: function (itemID, itemType, callback) {
        this.DoGet('Review/' + itemID + '/' + itemType, callback);
    },

    GetReviewsPaged: function (itemID, itemType, pageNumber, pageSize, callback) {
        //leave in place for future use - 404 right now
        this.DoGet('Reviews/' + itemID + '/' + itemType + '?pageNumber=' + pageNumber + '&pageSize=' + pageSize, callback);
    },

    IncrementReviewWasHelpful: function (reviewID, callback) {
        this.DoInvoke('POST', 'Review/' + reviewID + '/Helpful', { action: 'Add', value: 1 }, callback);
    },

    MoveFolder: function (folderID, parentFolderID, name, callback) {
        this.DoInvoke('POST', 'Folder/Move/' + folderID, { parentFolderID: parentFolderID, name: name }, callback);
    },

    RenameFolder: function (folderID, nameNew, nameOld, callback) {
        this.DoInvoke('POST', 'Folder/Rename/' + folderID, { nameNew: nameNew, nameOld: nameOld }, callback);
    },

    SaveItemShareState: function (savedItemID, isShared, submitForApproval, callback) {
        this.DoInvoke('POST', 'Share/' + savedItemID, { isShared: isShared, submitForApproval: submitForApproval }, callback);
    },

    SaveNote: function (savedItemID, note, callback) {
        this.DoInvoke('POST', 'Note/' + savedItemID, { note: note }, callback);
    },

    SaveReview: function (itemID, itemType, rating, review, callback) {
        this.DoInvoke('POST', 'Review/' + itemID + '/' + itemType, { rating: rating, review: review }, callback);
    },

    SaveToRecipeBox: function (itemID, isRecipe, isMenu, folderID, callback) {
        this.DoInvoke('POST', 'RecipeBox/Item/' + itemID + '/' + this.BoolToString(isRecipe), { folderID: folderID, isMenu: this.BoolToString(isMenu) }, callback);
    },

    AddToShoppingList: function (listID, isKitchenApprovedRecipe, isMenu, itemID, servings, callback) {
        this.DoInvoke('POST', 'ShoppingList/Item/' + itemID + '/' + this.BoolToString(isKitchenApprovedRecipe), { isMenu: this.BoolToString(isMenu), servings: servings, listID: listID }, callback);
    },

    AddGroceryItemsToShoppingList: function (listID, items, callback) {
        this.DoInvoke('POST', 'ShoppingList/Items/' + listID, { items: items }, callback);
    },

    AddCustomGroceryItemsToShoppingList: function (listID, groceryItemTexts, callback) {
        this.DoInvoke('POST', 'ShoppingList/Item/Custom/Many/' + listID, { groceryItemTexts: groceryItemTexts }, callback);
    },

    AddCustomGroceryItemsToShoppingListAisle: function (listID, aisleID, groceryItemTexts, callback) {
        this.DoInvoke('POST', 'ShoppingList/Item/Custom/Many/' + listID + "/" + aisleID, { groceryItemTexts: groceryItemTexts }, callback);
    },

    AddCustomGroceryItemToShoppingList: function (listID, groceryItemText, callback) {
        this.DoInvoke('POST', 'ShoppingList/Item/Custom/' + listID, { groceryItemText: groceryItemText }, callback);
    },

    GetGroceryItems: function (aisleID, callback) {
        this.DoGet('ShoppingList/Grocery/' + aisleID, callback);
    },

    CreateShoppingList: function (name, isDefault, callback) {
        this.DoInvoke('POST', 'ShoppingList', { name: name, isDefault: isDefault }, callback);
    },

    RenameShoppingList: function (listID, name, callback) {
        this.DoInvoke('POST', 'ShoppingList/Rename/' + listID, { name: name }, callback);
    },

    DeleteRecipesAndUpdateServings: function (listID, kitchenApprovedRecipeIDsToDelete, personalRecipeIDsToDelete, servingsToUpdate, callback) {
        this.DoInvoke('POST', 'ShoppingList/Update/' + listID, { kitchenApprovedRecipeIDsToDelete: kitchenApprovedRecipeIDsToDelete, personalRecipeIDsToDelete: personalRecipeIDsToDelete, servingsToUpdate: servingsToUpdate }, callback);
    },

    DeleteAndUpdateGroceryItems: function (listID, groceryItemsToDelete, kitchenApprovedRecipeItemsToDelete, personalItemsToDelete, groceryItemsToUpdate, kitchenApprovedRecipeItemsToUpdate, personalItemsToUpdate, callback) {
        this.DoInvoke('POST', 'ShoppingList/UpdateItems/' + listID, { groceryItemsToDelete: groceryItemsToDelete, kitchenApprovedRecipeItemsToDelete: kitchenApprovedRecipeItemsToDelete, personalItemsToDelete: personalItemsToDelete, groceryItemsToUpdate: groceryItemsToUpdate, kitchenApprovedRecipeItemsToUpdate: kitchenApprovedRecipeItemsToUpdate, personalItemsToUpdate: personalItemsToUpdate }, callback);
    },

    AddPhotoToSharedItem: function (sharedItemID, userPhotoID, callback) {
        this.DoInvoke('POST', 'Photos/AddToSharedItem/' + sharedItemID + '/' + userPhotoID, {}, callback);
    },

    IsCustomUrlAvailable: function (customUrl, callback) {
        this.DoInvoke('POST', 'IsCustomUrlAvailable', { customUrl: customUrl }, callback);
    },

    AddToBrandsILike: function (brandUserID, callback) {
        this.DoInvoke('POST', 'BrandedProfile/AddToBrandsILike/' + brandUserID, {}, callback);
    },

    AddItemToMenu: function (userID, sharedItemID, typeSpecificID, itemType, servings, callback) {
        this.DoInvoke('POST', 'Menu/Item/' + sharedItemID, { userID: userID, typeSpecificID: typeSpecificID, itemType: itemType, servings: servings }, callback);
    }
};


AR.Extenders = {
    BindEnterToButton: function (targetID, buttonID) {
        $('#' + targetID + ',#' + targetID + ' input,#' + targetID + ' select,#' + targetID + ' textarea').bind('keypress',
		function (e) {
		    if (e.keyCode == 13) {
		        if (e.preventDefault) e.preventDefault();
		        var btn = $('#' + buttonID);
		        var href = btn.attr("href");

		        //unfortunately, linkbuttons store the javascript in their href attribute
		        if (typeof (href) != "undefined" && href.substr(0, 11) == "javascript:") {
		            new Function(href.substr(11)).call(btn.eq(0));
		        }
		        else {
		            $('#' + buttonID).trigger('click');
		        }
		    }
		});
    },
    ShowCharCount: function (counterID, txtboxID, show) {
        var wrapper = $('#' + counterID + '_StyleWrapper');
        var txtBox = $('#' + txtboxID);
        if (show == 'true') {
            //if (txtBox.is(':visible'))
            wrapper.show();
            //else
            //    wrapper.hide();
        }
        else
            wrapper.hide();
    },
    CheckMaxLength: function (e, textBox, maxLength) {
        switch (e.keyCode) {
            case 9:  //tab
            case 16: // shift
            case 17: // ctrl
            case 35: // home
            case 36: // end
            case 37: // left
            case 38: // up
            case 39: // right
            case 40: // down
            case 8:  // backspace
            case 46: // delete
                return true;
            case 27: // escape
                textBox.value = '';
                return true;
        }
        return (textBox.value.length < maxLength);
    },
    SetCharCount: function (e, extenderID, showMaxLength, maxLength, textBoxID, warningColor, defaultColor, stopInput) {
        var txt = $('#' + textBoxID);
        var charCount = $('#' + extenderID + '_CharCount');
        var allText = $('#' + extenderID + '_StyleWrapper');
        if (txt.length > 0 && charCount.length > 0 && allText.length > 0) {
            charCount.html(maxLength - txt.val().length);
            if (showMaxLength == 'true') charCount.html(charCount.html() + '/' + maxLength);
            var color = (txt.val().length > maxLength) ? warningColor : defaultColor;
            allText.css('color', color);

            if (e) {
                var item = txt[0];
                if ((item.selectionStart !== undefined || item.selectionStart == 0) &&
					(item.selectionEnd !== undefined || item.selectionEnd == 0)) {
                    if (txt.val().substring(item.selectionStart, item.selectionEnd) == '') {
                        if (!this.CheckMaxLength(e, item, maxLength) && stopInput == 'true') { e.preventDefault(); return false; }
                    }
                }
                else if (document.selection != undefined) { // must come last
                    var us = document.selection.createRange();
                    if (us.text.length == 0) {
                        if (!this.CheckMaxLength(e, item, maxLength) && stopInput == 'true') { e.preventDefault(); return false; }
                    }
                }
            }
        }
        else {
            if (txt.length > 0) txt.hide();
            if (charCount.length > 0) charCount.hide();
            if (allText.length > 0) allText.hide();
        }
        return true;
    },
    BindKeysToCharCount: function (counterID, showMax, maxLength, targetID, warningColor, defaultColor, stopInput) {

        var that = this;
        var target = $('#' + targetID);

        target.bind('keydown keyup input',
			function (e) {
			    if (!that.SetCharCount(e, counterID, showMax, maxLength, targetID, warningColor, defaultColor, stopInput)) {
			        e.preventDefault();
			        return false;
			    }
			}
		);

        // each text field with a character count extender has a RefreshCharacterCount
        // method added to for the count to refresh manually
        target.each(function () {
            this.RefreshCharacterCount = function () {
                that.SetCharCount(null, counterID, showMax, maxLength, targetID, warningColor, defaultColor, stopInput);
            };
        });

        target.bind('paste',
			function (e) {

			    var originalValue = target.val();

			    setTimeout(function () {

			        var newValue = target.val();

			        if (newValue.length > maxLength && originalValue.length <= maxLength) {
			            target.val(originalValue);
			            that.SetCharCount(null, counterID, showMax, maxLength, targetID, warningColor, defaultColor, stopInput)
			        }
			    }, 0);
			}
		);
    }
}

// This jQuery extension method runs RefreshCharacterCount on all elements
// in a jQuery collections
$.fn.RefreshCharacterCount = function () {
    this.each(function () {
        if (this.RefreshCharacterCount != null) {
            this.RefreshCharacterCount();
        }
    });
};

AR.CreateTagsController = function (_rootElement, maxSelectable) {
    var rootElement = $(_rootElement);
    var hiddenElement = $("input[type='hidden']", rootElement);
    var checkboxes = $("input[type='checkbox']", rootElement);

    var controller = {};

    controller.UpdateHiddenField = function (lastClickedCheckbox) {
        var checkedCheckboxes = checkboxes.filter(':checked');

        if (checkedCheckboxes.size() > maxSelectable) {
            $(lastClickedCheckbox).attr('checked', false);
        }
        else {
            var hiddenTextValue = '';
            checkedCheckboxes.each(function () {
                var checkbox = $(this);
                hiddenTextValue = hiddenTextValue + '|' + checkbox.val();
            });

            hiddenElement.val(hiddenTextValue);
        }
    }

    return controller;
}

AR.CreateCustomRecipeTagsController = function (_rootElement, maxSelectable) {
    var rootElement = $(_rootElement);
    var hiddenElement = $("input[type='hidden']", rootElement);
    var checkboxes = $("input[type='checkbox']", rootElement);

    var controller = {};

    controller.UpdateHiddenField = function (lastClickedCheckbox) {
        var checkedCheckboxes = checkboxes.filter(':checked');

        if (checkedCheckboxes.size() > maxSelectable) {
            $(lastClickedCheckbox).attr('checked', false);
        }
        else {
            var hiddenTextValue = '';
            checkedCheckboxes.each(function () {
                var checkbox = $(this);
                hiddenTextValue = hiddenTextValue + '|' + checkbox.val();
            });

            hiddenElement.val(hiddenTextValue);
        }
    }

    return controller;
}



AR.ShowRateAndReview2 = function (
	_$,
	itemID,
	itemType,
	itemName,
	msgLabelSelector,
	ratingImageSelector,
	noRatingSpanSelector,
	reviewTextSelector,
    menuType,
    actionSource) {
    _$ = _$ || $; // default to $.  taken as a parameter for testability only

    if (parseInt(itemType) == 7) {
        AR.Analytics.RecordCustomLinkClick(AR.Analytics.Action.CustomLinkClick.MenuReview);
    }
    else {
        AR.Analytics.RecordCustomLinkClick(AR.Analytics.Action.CustomLinkClick.RecipeReview);
    }

    var result = new AR.RateAndReviewContext(
		itemID,
		itemType,
		itemName,
		_$(msgLabelSelector),
		_$(ratingImageSelector),
		_$(noRatingSpanSelector),
		_$(reviewTextSelector),
        menuType,
        actionSource);

    AR.RateAndReviewContext.instance = result;  // tracking instance so the injected AspxDialog can find it

    return result;
};


AR.RateAndReviewContext = function (
	itemID,
	itemType,
	itemName,
	msgLabel,
	ratingImage,
	noRatingSpan,
	reviewText,
    menuType,
    actionSource
    ) {

    this._itemID = itemID;
    this._itemType = itemType;
    this._itemName = itemName;
    this._msgLabel = msgLabel;
    this._ratingImage = ratingImage;
    this._noRatingSpan = noRatingSpan;
    this._reviewText = reviewText;
    this._menuType = menuType;
    this._actionSource = actionSource;
}


AR.RateAndReviewContext.prototype.Start = function () {
    var that = this;
    var url = AR.ClientUrlProvider.GetRateAndReviewLogonDialog(this._itemID, this._itemType, this._itemName, this._menuType);
    AR.CreateAspxDialog(url, function () { that.OnFailure() });
    AR.Analytics.DoStartReview(this._itemType, this._menuType, this._actionSource);
};

AR.RateAndReviewContext.prototype.OnSuccess = function (rating, review) {
    AR.Analytics.DoSavedReview(this._itemType, this._menuType, this._actionSource);
    this._reviewText.text(review);

    if (rating > 0) {

        var imageUrl = AR.ClientUrlProvider.GetRecipeBoxListViewRatingImage(rating);

        this._ratingImage.attr("src", imageUrl);
        this._ratingImage.css("display", "block");
        this._noRatingSpan.css("display", "none");
    } else {
        this._ratingImage.css("display", "none");
        this._noRatingSpan.css("display", "inline");
    }
}

AR.RateAndReviewContext.prototype.OnFailure = function (errorText) {

    errorText = errorText || "Sorry, there was an error viewing or saving your review.";

    AR.MessageBox.ShowFailure(errorText, this._msgLabel);
};


AR.StartTooltipController = function (
	anchorContainerSelector,
	anchorSelector,
	sliderContainerSelector,
	sliderSelector,
	sliderHideableRegionSelector) {
    var anchorContainer = $(anchorContainerSelector);
    var anchors = $(anchorSelector, anchorContainer);
    var sliderContainer = $(sliderContainerSelector);
    var sliders = $(sliderSelector, sliderContainer);

    var getOffsets = function (container, children, skew) {
        var containerOffset = container.offset().top;
        var childrenOffsets = [];

        children.each(function () {
            var child = $(this);
            childrenOffsets[childrenOffsets.length] = child.offset().top - containerOffset + skew;
        });

        return childrenOffsets;
    };

    var getRelativeOffsetToNextChild = function (container, children) {
        var offsets = getOffsets(container, children, 0);
        var relativeOffsets = [];

        for (var i = 0; i < offsets.length - 1; i++) {
            relativeOffsets[i] = offsets[i + 1] - offsets[i];
        }

        return relativeOffsets;
    };

    // fitToOffsets adjusts the positioning of the tooltip to try and match a set
    // of offsets.  It won't allow tooltips to overlap, pushing some tooltips down
    // when necessary.
    var fitToOffsets = function (minimumRelativeOffsets, animationSpeed) {
        sliders.css('position', 'absolute');
        sliders.css('margin', '0px');

        var minimumNextOffset = 0;

        //recalculate targetOffsets everytime this is called in case the left column has changed
        targetOffsets = getOffsets(anchorContainer, anchors, deltaFromAnchorToSliderContainer);

        for (var i = 0; i < anchors.length; i++) {
            var nextOffset = targetOffsets[i];

            if (nextOffset < minimumNextOffset)
                nextOffset = minimumNextOffset;

            $(sliders[i]).animate({ top: nextOffset }, animationSpeed);
            minimumNextOffset = nextOffset + minimumRelativeOffsets[i];
        }
    };

    var setOpen = function (index, animationSpeed) {
        var minimumRelativeOffsets = $.extend({}, closedRelativeOffsets);
        minimumRelativeOffsets[index] = openRelativeOffsets[index];

        fitToOffsets(minimumRelativeOffsets, animationSpeed);
    };

    if (anchorContainer && anchorContainer.length > 0 && sliderContainer && sliderContainer.length > 0) {
        var deltaFromAnchorToSliderContainer = anchorContainer.offset().top - sliderContainer.offset().top;

        // record the offsets of the anchors, those are the offset's we'll try to fit the tips to.
        var targetOffsets = getOffsets(anchorContainer, anchors, deltaFromAnchorToSliderContainer);

        // On page load the tips are all open, allowing us to measure how much they need in
        // that state.
        var openRelativeOffsets = getRelativeOffsetToNextChild(sliderContainer, sliders);

        // We'll immediately close them all, as thats what we want the user to initially see.
        // We also measure how much space each needs when closed.
        $(sliderHideableRegionSelector, sliders).css('display', 'none');
        var closedRelativeOffsets = getRelativeOffsetToNextChild(sliderContainer, sliders);

        sliders.each(function (sliderIndex) {
            var currentSlider = $(this);

            $('a', currentSlider).click(function () {
                var anchorLink = $(this);
                var allAnchors = $('a', sliders);
                var otherAnchors = allAnchors.not(anchorLink);

                var expandingSelectedNode = anchorLink.hasClass("expand");

                allAnchors.removeClass("collapse").removeClass("expand");

                if (expandingSelectedNode) {
                    anchorLink.addClass("collapse");
                    otherAnchors.addClass("expand");

                    var regionToShow = $(sliderHideableRegionSelector, currentSlider);
                    $(sliderHideableRegionSelector, sliders).not(regionToShow).slideUp(300);
                    regionToShow.slideDown(300);
                    setOpen(sliderIndex, 300);
                }
                else {
                    allAnchors.addClass("expand");
                    $(sliderHideableRegionSelector, sliders).slideUp(300);
                    fitToOffsets(closedRelativeOffsets, 300);
                }
            });
        });

        // wire up events such that when the user enters a textarea, the associated tip automagically opens.
        anchors.each(function (i) {
            var func = function () {
                var associatedTip = $('a', sliders[i]);
                if (!associatedTip.hasClass("expand"))
                    associatedTip.addClass("expand"); // always open (vs. toggle)
                associatedTip.click();
            };

            if (($(this).attr('tagName') == "TEXTAREA") ||
			($(this).attr('tagName') == "INPUT" && $(this).attr("type") == "text")) {
                $(this).focus(func); // use focus event for text-type inputs
            } else {
                $(this).click(func); // use click for all other controls
            }
        });

        fitToOffsets(closedRelativeOffsets, 0);
    }
};

AR.Share = {
    LoadDialogs: function () {
        $('.modal-link-sharing').click(function () {

            var serverItem = AR.ServerSideData.GetByDom(this);
            var radioButton, litIsShared;

            if (serverItem.isShared === false) {
                radioButton = $('#isSharedFalse');
                litIsShared = 'Not Shared';
            }
            else if (serverItem.approvalStatusType > 1 && serverItem.canBeSubmitted === true) {
                radioButton = $('#isSharedTrueAndSubmitted');
                litIsShared = 'Shared';
            }
            else if (serverItem.canBeShared === false) {
                radioButton = $('#isSharedFalse');
                litIsShared = 'Not Shared';
            }
            else {
                radioButton = $('#isSharedTrue');
                litIsShared = 'Shared';
            }


            if (serverItem.canBeSubmitted === true) {
                $('#canSubmit').show();
            }
            else {
                $('#canSubmit').hide();
            }

            if (serverItem.canBeShared === true) {
                $('#canShare').show();
            }
            else {
                $('#canShare').hide();
            }

            radioButton.attr("checked", "checked");
            $('.isShared').text(litIsShared);
            $('.recipe-name').text(serverItem.title);

            $('.share-commit').unbind('click').click(function () {
                AR.Cursor.SetWait();
                var isShared;
                if ($('#isSharedTrue').attr("checked") || $('#isSharedTrueAndSubmitted').attr("checked")) {
                    isShared = true;
                }
                else {
                    isShared = false;
                }

                var submitForApproval = $('#isSharedTrueAndSubmitted').attr("checked");
                AR.ClientService.SaveItemShareState(serverItem.savedItemID, isShared, submitForApproval,

                //success callback
					function (data) {
					    var link = $('#savedItemID_' + serverItem.savedItemID);
					    var notificationArea = link.parents('.myrecipeboxrow').find("#notificationArea");

					    if (data.ResponseCode != AR.ResponseCode.Success) {
					        AR.MessageBox.ShowFailure(data.Message, notificationArea);

					        if (AR.ShouldLogResponseCode(data.ResponseCode)) {
					            AR.LogErrorEx({}, "AR.Share", "Error saving change to sharing selection.");
					        }

					        AR.Dialog.CloseModalBox();
					        AR.Cursor.SetDefault();
					        return;
					    }

					    AR.MessageBox.PrintMessage(notificationArea,
							AR.MessageBox.MessageType.Success, data.Message, false);

					    if (isShared === true) {
					        link.text("Shared");
					    }
					    else {
					        link.text("Not Shared");
					    }

					    serverItem.isShared = isShared;

					    // only update the approval status if its a value that can actually be updated
					    // in the store proc.
					    if (serverItem.approvalStatusType == 1 || serverItem.approvalStatusType == 2) {
					        serverItem.approvalStatusType = submitForApproval ? 2 : 1;
					    }

					    AR.Dialog.CloseModalBox();
					    AR.Cursor.SetDefault();
					});
            });

            AR.Dialog.ShowLayer('.modal-sharing');
        });
    }
};

//
// A client side cache of the user note associated with each saved item.
//
AR.SavedItemNoteCache = {
    CachedNotes: {},
    GetCachedNote: function (savedItemID) {
        return this.CachedNotes[savedItemID];
    },
    SetCachedNote: function (savedItemID, note) {
        this.CachedNotes[savedItemID] = note;
    }
};

AR.AddEditNoteLayer = null;  // collection of jQuery selectors set on startup

AR.InitAddEditNoteLayer = function () {
    var layer = $(".modal-add-notes");

    AR.AddEditNoteLayer = {
        Layer: layer,
        NameField: $('.recipe-name', layer),
        TextInput: $('textarea', layer),
        SaveButton: $('.add-button', layer)
    };
};

//
// AR.ShowAddEditNote - initiates the Add/Edit note dialog.
//
//   sharedItemID, sharedItemName originalNoteValue: describe original note value
//   resultMsgSelector: jQuery selector for msg field where status result will be displayed
//   linkTextSelector: jQuery selector for the text field of the link
//
// The caller should ignore the return value, it is for test purposes only.
//
AR.ShowAddEditNote = function (savedItemID, sharedItemName, noteValue, resultMsgSelector, linkTextSelector) {
    AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.Note);
    // If client-side script has cached a new value, use that instead.
    noteValue = AR.SavedItemNoteCache.GetCachedNote(savedItemID) || noteValue;

    if (typeof (linkTextSelector) == 'string')
        linkTextSelector = $(linkTextSelector);

    var addEditLayer = AR.AddEditNoteLayer;

    addEditLayer.NameField.text(sharedItemName);
    addEditLayer.TextInput.val(noteValue || "");
    addEditLayer.TextInput.RefreshCharacterCount();

    var context = {};

    context.NewNoteValue = null;

    context.OnSave = function () {
        context.NewNoteValue = addEditLayer.TextInput.val();
        AR.Dialog.CloseModalBox();
        AR.ClientService.SaveNote(savedItemID, context.NewNoteValue, context.OnClientServiceSuccess);
    };

    context.OnClientServiceSuccess = function (ajaxResponse) {
        if (ajaxResponse.ResponseCode == AR.ResponseCode.Success) {
            context.OnSuccess(context.NewNoteValue);
            AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.Note);
        }
        else {
            context.OnError();
        }
    };

    context.OnError = function () {
        AR.MessageBox.ShowFailure("Unable to save note.", resultMsgSelector);
    }

    context.OnSuccess = function () {
        AR.MessageBox.ShowSuccess("Your note was saved.", resultMsgSelector);
        AR.SavedItemNoteCache.SetCachedNote(savedItemID, context.NewNoteValue);
        linkTextSelector.text("View Notes");
    }

    AR.Dialog.ShowLayer(addEditLayer.Layer);

    addEditLayer.SaveButton.unbind('click');
    addEditLayer.SaveButton.bind('click', function () {
        context.OnSave();
    });

    return context;
};


//
// A client side cache of the folders each saved item is in 
//
AR.SavedItemFolderCache = {
    CachedFolderLists: {},
    GetCachedFolders: function (savedItemID) {
        return this.CachedFolderLists[savedItemID];
    },
    SetCachedFolders: function (savedItemID, folders) {
        this.CachedFolderLists[savedItemID] = folders;
    },
    AddToFolder: function (savedItemID, folderID, folderName) {
        if (this.CachedFolderLists[savedItemID] == null)
            this.CachedFolderLists[savedItemID] = [];

        this.CachedFolderLists[savedItemID].push({ ID: folderID, Name: folderName });
    },
    RemoveFromFolder: function (savedItemID, folderID) {
        error("not implemented");
    }
}


//
//  Example:
//    AR.JoinFirst10FolderNamesWithSemicolons([{ID:1, Name:"folder1"}, {ID:2, Name:"folder2"}])
//  returns
//    "folder1; folder2"
//
AR.JoinFirst10FolderNamesWithSemicolons = function (folders) {

    // reverse the list so the user sees the most recently added folders first, and the 
    // most recently added aren't trimmed.
    folders = jQuery.extend([], folders);
    folders.reverse();

    var result = "";
    var separator = "";
    $.each(folders, function (index) {
        if (index < 10) {
            result = result + separator + this.Name;
            separator = "; ";
        }
    });
    return result;
};

AR.AddSavedItemToFolderLayer = null;

AR.InitAddSavedItemToFolderLayer = function () {
    var layer = $(".modal-add-to-folder");

    AR.AddSavedItemToFolderLayer = {
        Layer: layer,
        NameField: $('.recipe-name', layer),
        CurrentFoldersField: $('.current-folders', layer),
        FolderDropdown: $('select', layer),
        AddButton: $('.add-button', layer)
    };
};

//
//  specialItemID is either a recipe ID or a sharedItemID, depending on isRecipe
//
AR.ShowAddToFolder = function (savedItemID, isRecipe, specialItemID, itemType, itemName, currentFoldersItemIsAlreadyIn, resultMsgSelector) {

    AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.FolderAdd, AR.Analytics.Action.GetItem(itemType));

    var cachedFoldersItemIsAlreadyIn = AR.SavedItemFolderCache.GetCachedFolders(savedItemID);

    if (cachedFoldersItemIsAlreadyIn == null)
        AR.SavedItemFolderCache.SetCachedFolders(savedItemID, currentFoldersItemIsAlreadyIn);

    currentFoldersItemIsAlreadyIn = cachedFoldersItemIsAlreadyIn || currentFoldersItemIsAlreadyIn;

    var idsOfFoldersItemIsAlreadyIn = $.map(currentFoldersItemIsAlreadyIn, function (f) { return f.ID; });

    var layer = AR.AddSavedItemToFolderLayer;

    var funcExclude = function (folderID) {
        if (isNaN(folderID) || $.inArray(folderID, idsOfFoldersItemIsAlreadyIn) != -1) {
            return true;
        }
        return false;
    };

    AR.Folders.Dom.LoadDropDownList(layer.FolderDropdown, funcExclude, false);

    layer.NameField.text(itemName + ' ');

    var currentFoldersItemIsAlreadyInText = AR.JoinFirst10FolderNamesWithSemicolons(currentFoldersItemIsAlreadyIn);

    layer.CurrentFoldersField.text(currentFoldersItemIsAlreadyInText);

    AR.Dialog.ShowLayer(layer.Layer);

    var context = {};

    context.SelectedFolder = null;
    context.SelectedFolderName = null;
    context.OnAdd = function () {
        var selectedFolder = layer.FolderDropdown.val();

        if (selectedFolder == null || !isFinite(selectedFolder))
            return;

        context.SelectedFolder = parseInt(selectedFolder);
        context.SelectedFolderName = layer.FolderDropdown.find("option:selected").text();

        AR.Dialog.CloseModalBox();

        var isMenu = false; //can't add menus to folders, currently
        AR.ClientService.SaveToRecipeBox(
				specialItemID,
				isRecipe,
                isMenu,
				selectedFolder,
				context.Callback);
    };

    context.Callback = function (ajaxResponse) {
        if (ajaxResponse.ResponseCode == AR.ResponseCode.Success)
            context.OnSuccess();
        else
            context.OnFailure(ajaxResponse);
    };

    context.OnSuccess = function () {
        //close the toolbox
        AR.Toolbox.Close();

        AR.MessageBox.ShowSuccess("Successfully added to folder.", resultMsgSelector);

        var isUncategorized = (window.location.href.indexOf("folder=" + VirtualFolders.UnCategorized) > 0);
        var isMyRecipeList = (window.location.href.indexOf("folder=" + VirtualFolders.MyRecipeList) > 0);
        if (isUncategorized || (isMyRecipeList && currentFoldersItemIsAlreadyIn.length == 0)) {
            AR.Folders.Dom.UpdateSavedItemCount(VirtualFolders.UnCategorized, -1);
            AR.RecBoxSubNav.UpdateFolderCount(-1);

            if (isUncategorized) {
                $(resultMsgSelector).parent().next().hide(); //Remove the row that's no longer uncategorized.
            }
        }
        AR.SavedItemFolderCache.AddToFolder(savedItemID, context.SelectedFolder, context.SelectedFolderName);
        AR.Folders.Dom.UpdateSavedItemCount(context.SelectedFolder, 1);
        AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.FolderAdd, AR.Analytics.Action.GetItem(itemType));
    };

    context.OnFailure = function (ajaxResponse) {

        AR.MessageBox.ShowFailure("Unable to add to folder.", resultMsgSelector);

        if (AR.ShouldLogResponseCode(ajaxResponse.ResponseCode)) {

            AR.LogErrorEx({
                savedItemID: savedItemID,
                isRecipe: isRecipe,
                specialItemID: specialItemID,
                itemType: itemType,
                itemName: itemName,
                currentFoldersItemIsAlreadyIn: currentFoldersItemIsAlreadyIn,
                resultMsgSelector: resultMsgSelector
            }, 'main.js', 'AR.ShowAddToFolder.context.OnAdd');
        }
    };

    layer.AddButton.unbind("click");
    layer.AddButton.bind("click", context.OnAdd);

    return context;
};

AR.DeleteSavedItemFromFolderLayer = null;

AR.InitDeleteSavedItemFromFolderLayer = function () {
    var layer = $(".modal-delete");

    AR.DeleteSavedItemFromFolderLayer = {
        Layer: layer,
        NameField: $('.recipe-name', layer),
        FolderNameField: $('.folder-name', layer),
        SingleFolderDeletePlaceholder: $('.single-folder-delete', layer),
        MultipleFolderDeletePlaceholder: $('.multi-folder-delete', layer),
        ZeroFolderDeletePlaceholder: $('.zero-folder-delete', layer),
        DeleteButton: $('.delete-button', layer)
    };
};


AR.ShowDeleteFromFolderOrRecipeBox = function (savedItemID, savedItemName, folderID, folderName, currentFolders, resultMsgSelector, containingRow) {
    if (folderID <= 0) {
        AR.ShowDeleteFromRecipeBox(savedItemID, savedItemName, currentFolders, resultMsgSelector, containingRow);
    }
    else {
        AR.ShowDeleteFromFolder(savedItemID, savedItemName, folderID, folderName, currentFolders, resultMsgSelector, containingRow);
    }
}

AR.ShowDeleteFromFolder = function (savedItemID, savedItemName, folderID, folderName, currentFolders, resultMsgSelector, containingRow) {
    var layer = AR.DeleteSavedItemFromFolderLayer;

    layer.NameField.text(savedItemName + ' ');
    layer.FolderNameField.text(folderName);

    layer.SingleFolderDeletePlaceholder.show();
    layer.MultipleFolderDeletePlaceholder.hide();
    layer.ZeroFolderDeletePlaceholder.hide();

    AR.Dialog.ShowLayer(layer.Layer);

    var context = {};

    context.OnDelete = function () {
        AR.Dialog.CloseModalBox();

        AR.ClientService.DeleteFromRecipeBox(savedItemID, folderID,
			context.Callback);
    };

    layer.DeleteButton.unbind("click");
    layer.DeleteButton.bind("click", context.OnDelete);

    context.Callback = function (ajaxResponse) {
        if (ajaxResponse.ResponseCode == AR.ResponseCode.Success)
            context.OnSuccess();
        else
            context.OnFailure(ajaxResponse);
    };

    context.OnSuccess = function () {
        AR.MessageBox.ShowSuccess("Item has been deleted.", resultMsgSelector);
        AR.Folders.Dom.UpdateSavedItemCount(folderID, -1);
        containingRow.hide();
        AR.RecBoxSubNav.UpdateFolderCount(-1);

        if (currentFolders.length == 1) {
            AR.Folders.Dom.UpdateSavedItemCount(-1, 1);
        }
    };

    context.OnFailure = function (ajaxResponse) {
        AR.MessageBox.ShowFailure("Could not delete item.", resultMsgSelector);

        if (AR.ShouldLogResponseCode(ajaxResponse.ResponseCode)) {
            AR.LogErrorEx({
                savedItemID: savedItemID,
                folderID: folderID
            }, 'main.js', 'AR.ShowDeleteFromFolder.context.OnDelete');
        }
    };

    return context;
};


AR.ShowDeleteFromRecipeBox = function (savedItemID, savedItemName, currentFolders, resultMsgSelector, containingRow) {
    var cachedFolders = AR.SavedItemFolderCache.GetCachedFolders(savedItemID);

    if (cachedFolders == null) {
        AR.SavedItemFolderCache.SetCachedFolders(savedItemID, currentFolders);
    }

    currentFolders = cachedFolders || currentFolders;

    var layer = AR.DeleteSavedItemFromFolderLayer;

    var nameText = AR.JoinFirst10FolderNamesWithSemicolons(currentFolders);

    layer.NameField.text(savedItemName + ' ');
    layer.FolderNameField.text(nameText);

    layer.SingleFolderDeletePlaceholder.hide();
    layer.MultipleFolderDeletePlaceholder.hide();
    layer.ZeroFolderDeletePlaceholder.hide();

    if (currentFolders.length > 1)
        layer.MultipleFolderDeletePlaceholder.show();
    else if (currentFolders.length > 0)
        layer.SingleFolderDeletePlaceholder.show();
    else
        layer.ZeroFolderDeletePlaceholder.show();

    AR.Dialog.ShowLayer(layer.Layer);

    var context = {};

    context.OnDelete = function () {
        AR.Dialog.CloseModalBox();
        AR.ClientService.DeleteFromRecipeBox(savedItemID, 0, context.Callback);
    };

    layer.DeleteButton.unbind("click");
    layer.DeleteButton.bind("click", context.OnDelete);

    context.Callback = function (ajaxResponse) {
        if (ajaxResponse.ResponseCode == AR.ResponseCode.Success)
            context.OnSuccess();
        else
            context.OnFailure(ajaxResponse);
    };

    context.OnSuccess = function () {
        AR.MessageBox.ShowSuccess("Item has been deleted.", resultMsgSelector);

        $.each(currentFolders, function () {
            AR.Folders.Dom.UpdateSavedItemCount(this.ID, -1);
        });

        // decrement count of "My Recipes" list
        AR.Folders.Dom.UpdateSavedItemCount(0, -1);

        // decrement count of "uncategorized", if it was anywhere
        if (currentFolders.length == 0) {
            AR.Folders.Dom.UpdateSavedItemCount(-1, -1);
        }

        containingRow.hide();

        AR.RecBoxSubNav.UpdateFolderCount(-1);
    };

    context.OnFailure = function (ajaxResponse) {
        AR.MessageBox.ShowFailure("Could not delete item from your RecipeBox.", resultMsgSelector);

        if (AR.ShouldLogResponseCode(ajaxResponse.ResponseCode)) {
            AR.LogErrorEx({ savedItemID: savedItemID }, 'main.js', 'AR.ShowDeleteFromRecipeBox.context.OnDelete');
        }

        var updatedImage = ClientUrlProvider.GetRecipeBoxListViewRatingImage(context._review.Rating);
    };

    return context;
}


AR.Utils = {
    PruneAndHellip: function (originalString, totalLength, findLastSpace) {
        var result = "";
        var hellip = "…";

        if (originalString != null && originalString.length > 0) {
            if (originalString.length <= totalLength) {
                result = originalString;
            }
            else {
                var offset = ((hellip == "…") ? 1 : hellip.length);

                //Trim it down to the total length specified minus the offset
                result = originalString.substr(0, totalLength - offset);
                if (findLastSpace && result.indexOf(" ") >= 0) {
                    result = result.substr(0, result.lastIndexOf(" "));
                }

                //Tack on hellip
                result += hellip;
            }
        }
        return result;
    },
    HtmlEncode: function (value) {
        var test = $('<div/>').text(value).html();
        return test;
    },

    HtmlDecode: function (value) {
        return $('<div/>').html(value).text();
    },
    
    TruncateText: function () {
        $(".text-truncate").textTruncate();
        $(".text-truncate-multiline-height-30").textTruncate({ multiline: true, height: 30 });
        $(".text-truncate-multiline-height-40").textTruncate({ multiline: true, height: 40 });
        $(".text-truncate-multiline-height-45").textTruncate({ multiline: true, height: 45 });
        $(".text-truncate-multiline-height-55").textTruncate({ multiline: true, height: 55 });
    }

}

AR.RecBoxSubNav = {
    UpdateFolderCount: function (countChanged) {
        var spanToUpdate = $('.rec-box-sub-nav-folder-size');
        var currentValue = parseInt(spanToUpdate.text());

        if (currentValue != NaN) {

            if (currentValue < 0)
                currentValue = 0;

            currentValue = currentValue + countChanged;
            spanToUpdate.text(currentValue);
        }
    }
};

AR.ShoppingListUtils = {
    AddToList: function (link, listID, isKitchenApprovedRecipe, isMenu, itemID, itemType) {
        AR.Cursor.SetWait();
        AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.ShoppingListAddRecipe, AR.Analytics.Action.GetItem(itemType));
        AR.ClientService.AddToShoppingList(listID, isKitchenApprovedRecipe, isMenu, itemID, 0,
			function (response) {
			    if (response.ResponseCode == AR.ResponseCode.Success) {
			        AR.Toolbox.Close();
			        AR.MessageBox.PrintMessage($(link).parents('.row').prev().find('div'),
						AR.MessageBox.MessageType.Success, response.Message, false);
			        AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.ShoppingListAddRecipe, AR.Analytics.Action.GetItem(itemType));
			    }
			    else {
			        if (AR.ShouldLogResponseCode(response.ResponseCode)) {
			            AR.LogErrorEx({
			                ListID: listID,
			                isKitchenApprovedRecipe: isKitchenApprovedRecipe,
			                ItemID: itemID
			            }, 'main.js', 'AR.ShoppingListUtils.AddToList');
			        }

			        AR.MessageBox.PrintMessage($(link).parents('.row').prev().find('div'),
						AR.MessageBox.MessageType.Failure, response.Message, true);
			    }
			    AR.Cursor.SetDefault();
			});
    }
};

AR.Analytics = {
    GetOmnitureS: function () {
        try {
            return s_gi(omnitureAccount);
        }
        catch (exception) {
            return null;
        }
    },
    LogConsoleInfo: function (message) {
        var s_console = null;
        if (typeof (console) != "undefined") {
            console.info(message);
        }
    }, 
    ResetS: function (sObj) {
        if (sObj != null) {
            s.linkTrackVars = s.linkTrackEvents = "None";
            s.events = "";
            s.pe = s.pev1 = s.pev2 = "";
            s.eVar3 = s.eVar7 = s.eVar8 = s.eVar9 = s.eVar12 = s.eVar13 = "";
            s.prop24 = s.prop34 = s.prop36 = "";
        }
    },
    LogS: function (extraInfo, sObj) {
        if (sObj != null) {
            AR.Analytics.LogConsoleInfo(extraInfo);

            var msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
            AR.Analytics.LogConsoleInfo(msg);
            msg = "-- s.linkTrackEvents:'" + s.linkTrackEvents + "'";
            AR.Analytics.LogConsoleInfo(msg);
            msg = "s.events:'" + s.events + "'";
            AR.Analytics.LogConsoleInfo(msg);

            msg = (s.pe != null) ? "s.pe:'" + s.pe + "'\n" : '';
            msg += (s.pev1 != null) ? "s.pev1:'" + s.pev1 + "'\n" : '';
            msg += (s.pev2 != null) ? "s.pev2:'" + s.pev2 + "'\n" : '';

            msg += (s.eVar3 != null) ? "s.eVar3:'" + s.eVar3 + "'\n" : '';
            msg += (s.eVar7 != null) ? "s.eVar7:'" + s.eVar7 + "'\n" : '';
            msg += (s.eVar8 != null) ? "s.eVar8:'" + s.eVar8 + "'\n" : '';
            msg += (s.eVar9 != null) ? "s.eVar9:'" + s.eVar9 + "'\n" : '';
            msg += (s.eVar12 != null) ? "s.eVar12:'" + s.eVar12 + "'\n" : '';
            msg += (s.eVar13 != null) ? "s.eVar13:'" + s.eVar13 + "'\n" : '';

            msg += (s.prop24 != null) ? "s.prop24:'" + s.prop24 + "'\n" : '';
            msg += (s.prop34 != null) ? "s.prop34:'" + s.prop34 + "'\n" : '';
            msg += (s.prop36 != null) ? "s.prop36:'" + s.prop36 + "'\n" : '';
            AR.Analytics.LogConsoleInfo(msg);
        }
    },

    /*
    Supporting Member Start
    args:
    callToAction: value sent to omniture as trigger for start
		
    */
    DoSupportingMemberStart: function (callToAction, serializationID, visitVersion, linkName, internalSource) {
        var s = AR.Analytics.GetOmnitureS();
        var hasLinkName = (linkName.length > 0 && linkName != 'undefined');
        var hasInternalSource = (internalSource.length > 0 && internalSource != 'undefined');
        if (s != null) {
            s.linkTrackVars = 'eVar2,eVar3,eVar7,eVar13,events,products';
            s.linkTrackVars += (hasLinkName) ? ',prop34' : '';
            s.linkTrackVars += (hasInternalSource) ? ',prop24' : '';
            s.linkTrackEvents = 'event2';
            s.events = 'event2:' + serializationID;
            s.eVar2 = (AR.VisitorInfo.IsLoggedIn() && !AR.VisitorInfo.IsSupportingMember()) ? "Upsell" : 'Registration';
            //BI requirement: only set evar3 if we have a explicit call to action value
            if (callToAction != null && callToAction != 'undefined' &&
				callToAction.length > 0 && callToAction != 'Not Set' && callToAction != 'NotSet') {
                s.eVar3 = callToAction;
            }
            s.eVar7 = "";
            if (callToAction == "Kitchen View of Recipe") {
                try {
                    var referrer = document.referrer.toLowerCase();
                    if (referrer.lastIndexOf("my/recipebox") != -1)
                        s.eVar7 = "Recipe Box";
                    else if (referrer.lastIndexOf("detail.aspx") != -1)
                        s.eVar7 = "Recipe Page";
                }
                catch (e) {
                }
            }
            s.eVar13 = visitVersion;
            if (hasLinkName) {
                s.prop34 = linkName;
            }
            if (hasInternalSource) {
                s.prop24 = internalSource;
            }
            s.tl(true, 'o', 'SM Start');

            var msg = "BI: DoSupportingMemberStart('" + callToAction + "','" + serializationID + "','" + visitVersion + "','" + linkName + "','" + internalSource + "')";
            AR.Analytics.LogConsoleInfo(msg);
            msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
            AR.Analytics.LogConsoleInfo(msg);
            msg = "-- s.events:'" + s.events + "'|s.eVar2:'" + s.eVar2 + "'|s.eVar3:'" + s.eVar3 + "'|s.eVar7:'" + s.eVar7 + "'";
            AR.Analytics.LogConsoleInfo(msg);
            msg = "-- s.eVar13:'" + s.eVar13 + "'";
            msg += (hasLinkName) ? "|prop34:'" + s.prop34 + "'" : '';
            msg += (hasInternalSource) ? "|prop24:'" + s.prop24 + "'" : '';
            msg += " * s.tl(true, 'o', 'SM Start')";
            AR.Analytics.LogConsoleInfo(msg);
            s.prop24 = s.prop34 = s.eVar13 = s.eVar2 = s.eVar3 = s.eVar7 = s.events = s.linkTrackVars = "";
        }
    },
    /*
    Do Free Member Start
    args:
    callToAction: value sent to omniture as trigger for start
    linkName: value sent to omniture in prop34 link name
    internalSource: value sent to omniture in prop24
        
    */
    DoFreeMemberStart: function (sToExtend, callToAction, linkName, internalSource) {
        var s = sToExtend || AR.Analytics.GetOmnitureS();
        var hasLinkName = (linkName.length > 0 && linkName != 'undefined');
        var hasInternalSource = (internalSource.length > 0 && internalSource != 'undefined');

        if (s != null) {
            s.linkTrackVars = 'eVar3,events,products';
            s.linkTrackVars += (hasLinkName) ? ',prop34' : '';
            s.linkTrackVars += (hasInternalSource) ? ',prop24' : '';
            s.linkTrackEvents = 'event11';
            s.events = 'event11';
            //BI requirement: only set evar3 if we have a explicit call to action value
            if (callToAction != null && callToAction != 'undefined' &&
                callToAction.length > 0 && callToAction != 'Not Set' && callToAction != 'NotSet') {
                s.eVar3 = callToAction;
            }
            if (hasLinkName) {
                s.prop34 = linkName;
            }
            if (hasInternalSource) {
                s.prop24 = internalSource;
            }
            if (sToExtend == null) {
                s.tl(true, 'o', 'Registration');

                var msg = "BI: DoFreeMemberStart('" + sToExtend + "','" + callToAction + "','" + linkName + "','" + internalSource + "')";
                AR.Analytics.LogConsoleInfo(msg);
                msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
                AR.Analytics.LogConsoleInfo(msg);
                msg = "-- s.events:'" + s.events + "'|s.eVar3:'" + s.eVar3 + "'";
                msg += (hasLinkName) ? "|s.prop34:'" + s.prop34 + "'" : '';
                msg += (hasInternalSource) ? "|s.prop24:'" + s.prop24 + "'" : '';
                msg += " * s.tl(true, 'o', 'Registration')";
                AR.Analytics.LogConsoleInfo(msg);
                s.prop24 = s.prop34 = s.eVar3 = s.events = s.linkTrackVars = "";
            }
        }
    },
    DoFreeMemberComplete: function (sToExtend) {
        var s = sToExtend || AR.Analytics.GetOmnitureS();
        if (s != null) {
            s.linkTrackVars = 'events,products';
            s.linkTrackEvents = 'event12';
            s.events = 'event12';

            if (sToExtend == null) {
                s.tl(true, 'o', 'Order');

                var msg = "BI: DoFreeMemberComplete('" + sToExtend + "')";
                AR.Analytics.LogConsoleInfo(msg);
                msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
                AR.Analytics.LogConsoleInfo(msg);
                msg = "-- s.events:'" + s.events + "' * s.tl(true, 'o', 'Order')";
                AR.Analytics.LogConsoleInfo(msg);
                s.prop34 = s.events = s.linkTrackVars = "";
            }
        }
    },
    DoStartReview: function (itemType, menuType, actionSource) {

        if (menuType > 0) {
            AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.RateReview,
                                               AR.Analytics.Event.Start,
                                               actionSource,
                                               AR.Analytics.Action.Type.MenuReview,
                                               AR.Analytics.Action.GetMenuItem(menuType), '');
        }
        else {
            AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.RateReview,
                                               AR.Analytics.Event.Start,
                                               actionSource,
                                               AR.Analytics.Action.Type.RecipeReview,
                                               AR.Analytics.Action.GetItem(itemType), '');
        }
    },
    DoSavedReview: function (itemType, menuType, actionSource) {

        if (menuType > 0) {
            AR.Analytics.RecordAction(AR.Analytics.Event.Complete, actionSource, AR.Analytics.Action.Type.MenuReview, AR.Analytics.Action.GetMenuItem(menuType));
        }
        else {
            AR.Analytics.RecordAction(AR.Analytics.Event.Complete, actionSource, AR.Analytics.Action.Type.RecipeReview, AR.Analytics.Action.GetItem(itemType));
        }
    },
    SetFMOmniCallToAction: function (anchor) {
        var s = AR.Analytics.GetOmnitureS();
        if (s != null) {
            try {
                var hasOverRide = false;
                var callToAction = '';
                var qsLinkName = '';
                var qsInternalSource = '';
                var pageName = window.location.pathname;
                var cleanQs = anchor[0].search;
                var OverRideItems = AR.Analytics.OverRide.ParseItems(anchor[0].search.substr(1));

                for (i = 0; i < OverRideItems.length; i++) {
                    if (OverRideItems[i]) {
                        switch (OverRideItems[i].Key) {
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsCallToAction:
                                callToAction = OverRideItems[i].Value;
                                hasOverRide = true;
                                break;
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsLinkName:
                                qsLinkName = OverRideItems[i].Value;
                                hasOverRide = true;
                                break;
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsCustomLinkClick:
                                AR.Analytics.RecordCustomLinkClick(OverRideItems[i].Value);
                                hasOverRide = true;
                                break;
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsInternalSource:
                                qsInternalSource = OverRideItems[i].Value;
                                hasOverRide = true;
                                break;
                        }
                        if (hasOverRide) {
                            cleanQs = cleanQs.replace(OverRideItems[i].Key + '=' + OverRideItems[i].Original, '');
                        }
                    }
                }

                //check custom attribute for value and use if present
                if (!hasOverRide) {
                    if (anchor.attr('calltoaction')) {
                        callToAction = anchor.attr('calltoaction');
                    }
                }

                //default call to action - hack something from page name and linkid
                if (callToAction.length < 1) {
                    //strip path and file extension
                    var pos1 = pageName.lastIndexOf('/') + 1;
                    var pos2 = pageName.lastIndexOf('.');
                    if (pos2 > pos1)
                        pageName = pageName.substring(pos1, pos2);

                    callToAction = anchor[0].id + ' ' + pageName;
                }

                AR.Analytics.DoFreeMemberStart(null, callToAction, qsLinkName, qsInternalSource);

                //Scrub all analyitcs reporting params from the original qs to avoid double counting
                //on next page load.
                if (hasOverRide) {
                    var regEx = new RegExp("&*[&]", 'g'); //replace multiple occurances of & char's with single &                    
                    anchor[0].search =  cleanQs.replace(regEx, '&');
                    return anchor[0].href; 
                }
                else {
                    return '';
                }
            }
            catch (exception) {
                //AR.LogErrorEx({ pageName: pageName, callToAction: callToAction, exception: exception }, 'main.js', 'AR.Analytics.SetFMOmniCallToAction');
                return '';
            }
        }
    }
};

ioc.Register("_analytics").withInstance(AR.Analytics);


AR.IntersectionDetection = {
	IsPointInRange: function(value, rangeStart, rangeLength) {
		return rangeStart <= value && value <= (rangeStart + rangeLength);
	},
	DoRangesOverlap: function(aStart, aLength, bStart, bLength) {
		return this.IsPointInRange(aStart, bStart, bLength)
			|| this.IsPointInRange(aStart + aLength, bStart, bLength)
			|| this.IsPointInRange(bStart, aStart, aLength)
			|| this.IsPointInRange(bStart + bLength, aStart, aLength);
	},
	DoElementsOverlap: function(a, b) {
		var aOffset = a.offset();  // x,y position of a
		var bOffset = b.offset();  // x,y position of b
		
		return this.DoRangesOverlap(aOffset.left, a.outerWidth(), 
									bOffset.left, b.outerWidth())
			&& this.DoRangesOverlap(aOffset.top, a.outerHeight(), 
									bOffset.top, b.outerHeight());
	}
};


AR.BrandedProfile = {
	   
	AddToBrandsILike: function(brandID) {
		 AR.Cursor.SetWait();
		 AR.ClientService.AddToBrandsILike(brandID,
			function(response) {
				if (response.ResponseCode == AR.ResponseCode.Success) {
					 AR.MessageBox.ShowSuccess(response.Message, null, true);   
					  $('.add-to-brands-i-like').hide('normal', function() { } );             
				}
				else if(response.ResponseCode == AR.ResponseCode.UserError){
					AR.MessageBox.ShowWarning(response.Message, null, true);   
				}
				else {
					AR.MessageBox.ShowFailure(response.Message, null, true);                    
				}                
			 });
		AR.Cursor.SetDefault();
	}    
};


//console.time implementation for IE
if(window.console && typeof(window.console.time) == "undefined") {
    console.time = function(name, reset){
        if(!name) { return; }
        var time = new Date().getTime();
        if(!console.timeCounters) { console.timeCounters = {} };
        var key = "KEY" + name.toString();
        if(!reset && console.timeCounters[key]) { return; }
            console.timeCounters[key] = time;
        };

    console.timeEnd = function(name){
        var time = new Date().getTime();
        if(!console.timeCounters) { return; }
        var key = "KEY" + name.toString();
        var timeCounter = console.timeCounters[key];
        if(timeCounter) {
            var diff = time - timeCounter;
            var label = name + ": " + diff + "ms";
            console.info(label);
            delete console.timeCounters[key];
        }
        return diff;
    };
}

//used to fix IE7 bug where z-index is recalculated on relative blocks, hiding content regardless of z-index
AR.ZIndexOverride = {

    OverriddenElements: [],

    OriginalValues: [],

    RevertOverrides: function (key) {
        for (i = this.OverriddenElements.length-1; i >= 0; i--) {
            if (key == this.OverriddenElements[i].Key) {
                $(this.OverriddenElements[i].Element).css("z-index", this.OriginalValues[i].Value);
                this.OverriddenElements.remove(i);
                this.OriginalValues.remove(i);
            }
        }
    },

    ApplyOverride: function (element, key) {
        var overrideZIndex = $(element).css("z-index");
        var that = this;

        $(element).parents().each(function () {
            var parent = $(this);
            if (parent.css("position") == "relative") {
                that.OverriddenElements.push({ Element: parent, Key: key });
                that.OriginalValues.push({ Value: parent.css("z-index"), Key: key });
                parent.css("z-index", overrideZIndex);
            }
        });
    }
};

AR.AdData = {
    RootURL: "//ad.doubleclick.net",

    IFrameVerb: "adi",

    Site: "",

    Zone: "",

    KeyValues: "",

    KeyWords: "",

    Ord: "",

    VisitorID: "",

    VisitorStatus: "",

    VisitorStatusAbbr: "",

    ItemID: "",

    ItemAdKey: "",

    SessionGroup: "",

    GenerateIFrameURL: function (pos, size, product) {
        var root = [];
        root.push(this.RootURL);
        root.push(this.IFrameVerb);
        root.push(this.Site);
        root.push(this.Zone);

        var params = [];
        params.push(root.join("/"));
        params.push(AudienceScience.SegmentValues);
        params.push(this.KeyValues);
        params.push(this.KeyWords);
        params.push("ssngroup=" + this.SessionGroup);
        params.push("status=" + this.VisitorStatus);
        params.push(this.GenerateUParam(pos, product));
        params.push("product=" + product);
        params.push("tile=" + pos);
        params.push("pos=" + pos);
        params.push("sz=" + size);
        params.push("ord=" + Math.random() * 10000000000000000);

        return params.join(";");
    },

    GenerateUParam: function (pos, product) {
        var vals = [];
        vals.push(AudienceScience.EncodeRSI(AudienceScience.SegmentValues));
        vals.push(this.VisitorID);
        vals.push(this.ItemAdKey.toUpperCase() + this.ItemID);
        vals.push(pos);
        vals.push(product);
        vals.push(encodeURI(this.KeyWords));
        vals.push(this.SessionGroup);
        vals.push(this.VisitorStatusAbbr);
        vals.push('');
        return "u=" + vals.join("|");
    }
};

AudienceScience = {

    Segments: [],

    SegmentValues: "",

    Initialize: function () {
        this.Segments = [];
        var segs_beg = document.cookie.indexOf('rsi_segs=');
        if (segs_beg >= 0) {
            segs_beg = document.cookie.indexOf('=', segs_beg) + 1;
            if (segs_beg > 0) {
                var segs_end = document.cookie.indexOf(';', segs_beg);
                if (segs_end == -1) {
                    segs_end = document.cookie.length;
                }
                this.Segments = document.cookie.substring(segs_beg, segs_end).split('|');
            }
        }
        var segLen = 20;
        this.SegmentValues = "";
        if (this.Segments.length < segLen) {
            segLen = this.Segments.length;
        }
        for (var i = 0; i < segLen; i++) {
            this.SegmentValues += ("rsi" + "=" + this.Segments[i] + ";");
        }
    },

    TrimRSI: function (rsiValueString) {

        var output = "";
        var rsiArray = rsiValueString.split(";");
        for (x = 0; x < rsiArray.length; x++) {
            if (rsiArray[x].indexOf("_") != -1) {
                output += rsiArray[x].substring(rsiArray[x].indexOf("_") + 1);
                if (x == rsiArray.length + 1) output += "|";
            }
        }

        return output;
    },

    EncodeRSI: function (rsiValueString) {

        //TEST:
        //rsiValueString = "rsi=D11170_10027;rsi=D08734_72782;rsi=D11170_10012;rsi=D08734_70079;rsi=D08734_72731;rsi=D08734_70035;rsi=D08734_70056;rsi=D08734_70060;rsi=D08734_72011;rsi=D08734_72012;rsi=D08734_72020;rsi=D11170_10002;rsi=D11170_10016;rsi=D11170_10017;rsi=D11170_10019;rsi=D11170_10021;rsi=D11170_10022;rsi=D11170_10024;rsi=D11170_10025;rsi=D08734_72772";

        var output = AudienceScience.TrimRSI(rsiValueString);
        output = AR.BaseN.RecodeString(output, BASE_DECIMAL, BASE_64_DART_SAFE);
        return output;
    }
};

AudienceScience.Initialize();

//
// Controls\OptionsDropdown.js
//

/// <reference path="../Intellisense.js" />

$(document).ready(function () {
    $("*").live("mousedown", function(event) {
    
        if (event.target != event.currentTarget) {
            // don't handle the event if its been propagated
            return;
        }

        if (AR.ActiveOption && jQuery.contains(AR.ActiveOption.dropdown[0], this)) {
            return;
        }

        AR.SlideUpAllOptionsDropdowns();
    });
});

//Call to give Option Dropdown behavior to a given selector
//Example: AR.InitOptionsDropdown('.cardOptions')
AR.InitOptionsDropdown = function (selector) {

    $(selector).live('click', function () {

        AR.SlideUpAllOptionsDropdowns();

        //show the next Option Menu closest to me
        var nextOptionsDropdown = $(this).nextAll(".options-dropdown:first");
        if (nextOptionsDropdown.is(":hidden")) {

            AR.ActiveOption = {
                dropdown : nextOptionsDropdown,
                dropdownButton : $(this)
            };

            AR.ZIndexOverride.ApplyOverride(nextOptionsDropdown, "optiondropdown");
            nextOptionsDropdown.slideDown(250);
            $(this).css({ background: "url('" + AR.ImageServer + "/ar/myar/menuplanner/canvas/options-arrow-up.png') no-repeat scroll 2px 50% transparent" });
        }
    });
}

AR.ActiveOption = null;

AR.SlideUpAllOptionsDropdowns = function () {



    if (AR.ActiveOption) {

        var optionText = AR.ActiveOption.dropdownButton;
        var optionMenu = AR.ActiveOption.dropdown;

        AR.ActiveOption = null;

        optionMenu.slideUp(250);
        optionText.css({ background: "url('" + AR.ImageServer + "/ar/myar/menuplanner/canvas/options-arrow-down.png') no-repeat scroll 2px 50% transparent" });

        //hide all 'add to shoppinglist' and 'add to menu' dropdown and buttons inside of option menus
        optionMenu.find("#newshoppinglist").hide();
        optionMenu.find("#newmenu").hide();
    }

    AR.ZIndexOverride.RevertOverrides("optiondropdown");
}

AR.OptionDropdown = {

    Load: function () {
        $(".addtoshoppinglist").click(function (e) {
            e.preventDefault();
            if ($(this).next("#newshoppinglist").is(':hidden')) {
                var BI = AR.Analytics;
                var biLinkValue = (window.location.pathname.indexOf("RecipeBox") > -1) ? BI.Action.CustomLinkClick.ShoppingListRecipeAdd : (window.location.pathname.indexOf("Menus") > -1) ? BI.Action.CustomLinkClick.ShoppingListAddMenu : "Unknown";
                BI.RecordCustomLinkClick(biLinkValue);
            }
            $(this).next("#newshoppinglist").toggle();
        });

        $(".tool-addtomenu").click(function (e) {
            e.preventDefault();
            if (!AR.VisitorInfo.IsSupportingMember()) {
                var menuPlannerURL = $(this).attr("href");
                if (menuPlannerURL != null && menuPlannerURL != "javascript:void(0);") {
                    window.location = menuPlannerURL;
                }
            }
            else {
                // record Start Event
                if ($(this).next(".star").next("#newmenu").is(':hidden')) {
                    var BI = AR.Analytics;
                    var source = (window.location.pathname.indexOf("RecipeBox") > -1) ? BI.Action.Source.RecipeBox : (window.location.pathname.indexOf("Menus") > -1) ? BI.Action.Source.MyMenus : "Unknown";
                    var rowValue = $(this).parents(".recipe-box-list-row")[0]; //.find(".recipe-list-type").text();
                    var nlRegEx = new RegExp("\\n", 'g');
                    var wsRegEx = new RegExp("\\s", 'g');
                    var itemValue = $(rowValue).find(".recipe-list-type").text().replace(nlRegEx, "").replace(wsRegEx, "");
                    var itemType = '';
                    switch (itemValue) {
                        case "PersonalRecipe":
                            itemType = "Personal";
                            break;
                        case "KitchenApproved":
                            itemType = "Kitchen Approved";
                            break;
                        case "Weblink":
                            itemType = "Weblink";
                            break;
                        case "CustomRecipe":
                            itemType = "Custom";
                            break;
                        case "Reference":
                            itemType = "Reference";
                            break;
                    }
                    BI.RecordCustomLinkClick(BI.Action.CustomLinkClick.MenuRecipeAddExpanded);
                    BI.RecordAction(BI.Event.Start, source, BI.Action.Type.MenuAdd, itemType);
                }

                var hasMenus = ($(this).next(".star").next("#newmenu").find(".ddlSelectedMenuItem").children().length > 0);
                if (hasMenus) {
                    $(this).next(".star").next("#newmenu").toggle();
                }
                else {
                    var savedItemID = $(this).parents(".myrecipeboxrow")[0].id;
                    $(".action-addMenu-" + savedItemID).trigger("click");
                }
            }
           
        });

        $(".tool-addfolder").click(function (e) {
            e.preventDefault();

            ioc.Load("_dialogLauncher").AddFolder(
             function (result) {
                 AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.FolderAdd);
             },
             function () {
                 AR.MessageBox.ShowFailure("Sorry, but your new folder could not be created.", null, false);
             });
        });
    }
}


//
// Controls\FeaturedVideosInline.js
//


function FeaturedVideosHomepage() {
    this._wasReady = false;
    this._wasStarted = false;
    this._activePanel = null;
    this._needVolumeZero = false;
    this._channelCallToAction = null;
    this._callToActions = [];
}


FeaturedVideosHomepage.prototype = {
    constructor : FeaturedVideosHomepage,

    //  Initialization functions

    RequestAutoplay : function() {
        this._needVolumeZero = true;
    },
    SetCallToActions : function(channelCallToAction, callToActions) {
        this._channelCallToAction = channelCallToAction;
        this._callToActions = callToActions;
    },

    //  Query functions

    WasReady : function() {
        return this._wasReady;
    },
    WasStarted : function() {
        return this._wasStarted;
    },
    GetActivePanel: function() {
        return this._activePanel;
    },

    //  Internal functions

    OnVideoEvent : function(playerId, eventName, eventArgs) { 

        this.Player = document.getElementById(playerId)

        // We're not reliably received the "apiReady" event, so to work around this we'll
        // test if the api is ready by using it. 
        try
        {
            if (this._needVolumeZero) {
                this.Player.setVolume(0);
                this._needVolumeZero = false;
            }
        }
        catch(err)
        {
        }

        if (!this._wasReady) {
            try
            {
                this.Player.getVolume();
                this._wasReady = true;
            }
            catch(err)
            {
            }
        }

        switch(eventName) {
            case "stateChanged":
                if (eventArgs.state == "playing") {
                    this._wasStarted = true;
    
                    this.UpdateTitleDescription();
                    this.UpdateCallToAction();
                } else if (eventArgs.state == "buffering") {
                    this.UpdateTitleDescription();
                    this.UpdateCallToAction();
                }
                break;

            case "activePanelChanged":
                this._activePanel = eventArgs.activePanel;
                break;
        }
    },
    UpdateTitleDescription: function() {
        var item = this.Player.getCurrentItem();
        $(".homepage-video-container .titleText").text(item.title).removeAttr("title");
        $(".homepage-video-container .descriptionText").text(item.description).removeAttr("title");
        this.ApplyEllipsis();
    },
    UpdateCallToAction: function() {

        var item = this.Player.getCurrentItem();
        var callToActionLink = $(".homepage-video-container .calltoaction");

        var callToAction = null;

        for(var i = 0; i < this._callToActions.length; i++) {

            var current = this._callToActions[i];
            if (item.embedCode == current.embedCode) {
    
                callToAction = current;
                break;
            }
        }

        // default to channel's call to action, if available
        callToAction = callToAction || this._channelCallToAction;

        if (callToAction != null) {
            callToActionLink.attr("href", callToAction.link);
            callToActionLink.text(callToAction.linkText);
            callToActionLink.attr("title", callToAction.linkPopup);
            callToActionLink.css("visibility", "visible");
        } 
        else {
            callToActionLink.css("visibility", "hidden");
        }
    },
    ApplyEllipsis: function() {
        $(".homepage-video-container .titleText").textTruncate({ multiline: true, height: 50 });
        $(".homepage-video-container .descriptionText").textTruncate({ multiline: true, height: 100 });
    }
}

AR.FeaturedVideosHomepage = new FeaturedVideosHomepage();
AR.FeaturedVideosHomepageEventHandler = function() {
    return AR.FeaturedVideosHomepage.OnVideoEvent.apply(AR.FeaturedVideosHomepage, arguments);
};


//
// Controls\Video.js
//
/// <reference path="../Intellisense.js" />

if (typeof (AR) == "undefined") {
    AR = {};
}

// Define the command queue to be able to issue tagging commands before the actual JavaScript library loads.
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];

//Default function that Brightcove's player calls when its APIs are loaded... cannot change the function name, so redirecting it here to our own.
function onTemplateLoaded(pPlayer) {
    AR.Video.Brightcove.OnTemplateLoaded(pPlayer);
}

AR.Video = {
    HasBannerAd: false,
    IsBannerAdDivEmpty: function () {
        if (!AR.Video.HasBannerAd && $("div#videoCompanionAdDiv div").is(":empty")) {
            AR.Video.HasBannerAd = true;
            return true;
        }
        return false;
    },
    ConfigureAds: function () {
        // Load the library, asynchronously.
        (function () {
            var gads = document.createElement('script');
            gads.async = true;
            gads.type = 'text/javascript';
            var useSSL = 'https:' == document.location.protocol;
            gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
            var node = document.getElementsByTagName('script')[0];
            node.parentNode.insertBefore(gads, node);
        })();

        // Add a command to the command queue (defining unit and enabling)
        googletag.cmd.push(function () {
            googletag.defineUnit(videoNetworkSiteZone, [300, 250], 'ad-companion').addService(googletag.companionAds()).addService(googletag.pubads());
            googletag.pubads().disableInitialLoad();
            googletag.pubads().enableAsyncRendering();
            googletag.companionAds().setRefreshUnfilledSlots(true);
            googletag.enableServices();
        });
    }
}

AR.Video.Brightcove = {
    DebugRenditions: (RegExp('[?&]debug([^&]*)').exec(window.location.search)), //Append "debug" as a query string parameter to turn on console output. Assign 0-7 to "debug" to select a rendition.
    IsFullScreen: false,
    PlayerModule: null,
    VideoPlayerModule: null,
    ContentModule: null,
    ExperienceModule: null,
    MenuModule: null,
    AdsModule: null,
    SocialModule: null,
    OnTemplateLoaded: function (pPlayer) {

        //Get the player module
        AR.Video.Brightcove.PlayerModule = bcPlayer.getPlayer(pPlayer);

        //Use the player module to create references to the rest of the modules
        AR.Video.Brightcove.VideoPlayerModule = AR.Video.Brightcove.PlayerModule.getModule(APIModules.VIDEO_PLAYER);
        AR.Video.Brightcove.AdsModule = AR.Video.Brightcove.PlayerModule.getModule(APIModules.ADVERTISING);
        AR.Video.Brightcove.ExperienceModule = AR.Video.Brightcove.PlayerModule.getModule(APIModules.EXPERIENCE);
        AR.Video.Brightcove.MenuModule = AR.Video.Brightcove.PlayerModule.getModule(APIModules.MENU);
        AR.Video.Brightcove.ContentModule = AR.Video.Brightcove.PlayerModule.getModule(APIModules.CONTENT);
        AR.Video.Brightcove.SocialModule = AR.Video.Brightcove.PlayerModule.getModule(APIModules.SOCIAL);

        //Setup OnTemplateReady, where the event listeners get wired up
        if (AR.Video.Brightcove.ExperienceModule) {
            AR.Video.Brightcove.ExperienceModule.addEventListener(BCExperienceEvent.TEMPLATE_READY, AR.Video.Brightcove.OnTemplateReady);
        }

        //Setup callback function for rendition selection
        if (AR.Video.Brightcove.VideoPlayerModule) {
            AR.Video.Brightcove.VideoPlayerModule.setRenditionSelectionCallback(AR.Video.Brightcove.SelectRendition);
        }

        AR.Video.Brightcove.SetAdPolicy(videoAdTagUrl);
    },
    OnTemplateReady: function (e) {
        if (AR.Video.Brightcove.VideoPlayerModule) {
            AR.Video.Brightcove.VideoPlayerModule.setVolume(0.5);
            if ($("input#_HomepageAutoplay").val() === "true") {
                AR.Video.Brightcove.VideoPlayerModule.mute();
            }
        }

        //Set the info menu links for both "Email Video" and "Get Link". 
        if (AR.Video.Brightcove.SocialModule) {
            AR.Video.Brightcove.SocialModule.setLink(socialModuleGetLink);
        }

        //Setup callback function for loading the related videos collection
        if (AR.Video.Brightcove.ContentModule) {
            AR.Video.Brightcove.ContentModule.addEventListener(BCContentEvent.MEDIA_COLLECTION_LOAD, AR.Video.Brightcove.OnMediaCollectionLoad);
        }

        if (AR.Video.Brightcove.ExperienceModule) {
            //Setup callback functions for setting IsFullScreen boolean 
            AR.Video.Brightcove.ExperienceModule.addEventListener(BCExperienceEvent.ENTER_FULLSCREEN, AR.Video.Brightcove.OnEnterFullScreen);
            AR.Video.Brightcove.ExperienceModule.addEventListener(BCExperienceEvent.EXIT_FULLSCREEN, AR.Video.Brightcove.OnExitFullScreen);
        }

        //Setup callback function for info menu video request event
        if (AR.Video.Brightcove.MenuModule) {
            AR.Video.Brightcove.MenuModule.addEventListener(BCMenuEvent.VIDEO_REQUEST, AR.Video.Brightcove.OnVideoRequest);

            //Setup callback for setting related videos
            AR.Video.Brightcove.MenuModule.setAdditionalMediaCallback(AR.Video.Brightcove.LoadRelatedVideos)
        }

        //Hide the loading graphic when the player is ready... fixes a Chrome bug.
        $("div.video-loading").css("background", "none");
    },
    OnEnterFullScreen: function () {
        AR.Video.Brightcove.IsFullScreen = true;
    },
    OnExitFullScreen: function () {
        AR.Video.Brightcove.IsFullScreen = false;
    },
    OnMediaCollectionLoad: function (e) {
        if (e.mediaCollection !== null) {
            var media = [];
            for (var i = 0; i < e.mediaCollection.mediaCount; i++) {
                media[i] = AR.Video.Brightcove.ContentModule.getMedia(e.mediaCollection.mediaIds[i]);
            }
            AR.Video.Brightcove.MenuModule.setAdditionalMediaForType(media, BCMenuAdditionalMedia.RELATED_VIDEOS);
        }
    },
    OnVideoRequest: function (e) {
        if (e.args.id !== null) {
            window.location.href = AR.ClientUrlProvider.ResolveUrl("/handlers/videoredirect.ashx?p=2&id=" + e.args.id);
        }
    },
    LoadRelatedVideos: function (type, media) {
        if (type === BCMenuAdditionalMedia.RELATED_VIDEOS) {
            if (AR.Video.Brightcove.ContentModule && mediaIDsRelatedVideos) {
                //After this loads asynchronously, OnMediaCollectionLoad() will be called...
                AR.Video.Brightcove.ContentModule.getMediaInGroupAsynch(mediaIDsRelatedVideos);
            }
        }
        return true;
    },
    SelectRendition: function (context) {
        //There are two reasons we are selecting a rendition: 
        //  1) There is a rendition that perfectly fits each video player size. If the user can stream it (bandwidth), 
        //     then we should use it to achieve the best quality.
        //  2) Significant bandwidth savings by forcing the perfect rendition versus allowing the player to choose. 
        var renditions = context.renditions;
        var renditionIndex = -1;
        var playerHeight = context.screenHeight;

        if (AR.Video.Brightcove.DebugRenditions) {
            console.info("Current rendition is: " + context.currentRendition.size + " " + context.currentRendition.frameWidth + "x" + context.currentRendition.frameHeight);
            console.info("Player width and height: " + context.screenWidth + "x" + context.screenHeight);
        }

        if (!AR.Video.Brightcove.IsFullScreen) {
            //If current rendition height is greater or equal to the player height, then continue (means the 
            //user has the bandwidth to support larger streams, otherwise we let the player decide the rendition 
            //by passing back a -1 index)
            if (context.currentRendition.frameHeight >= playerHeight) {
                for (var i = 0; i < renditions.length; i++) {
                    //Choose the "perfect rendition" if it exists
                    if (playerHeight === renditions[i].frameHeight) {
                        renditionIndex = i;
                        break;
                    } else if (playerHeight > renditions[i].frameHeight) {
                        //Select the previous rendition (renditions are sorted from largest to smallest)
                        renditionIndex = i - 1;
                        break;
                    }
                }
            }
        }

        if (AR.Video.Brightcove.DebugRenditions) {
            //Append "debug" as a query string parameter to turn on console output. Assign 0-7 to "debug" (e.g. debug=2) to select a rendition.
            var match = RegExp('[?&]debug=([^&]*)').exec(window.location.search);
            var index = match && decodeURIComponent(match[1].replace(/\+/g, ' '));
            renditionIndex = index || renditionIndex;
            if (renditionIndex !== -1 && renditionIndex < renditions.length) {
                console.info("New rendition is: " + renditions[renditionIndex].size + " " + renditions[renditionIndex].frameWidth + "x" + renditions[renditionIndex].frameHeight);
            }
        }
        if (AR.Video.Brightcove.DebugRenditions) {
            console.info("------------------------------------------");
        }

        return renditionIndex;
    },
    SetAdPolicy: function (adTagUrl) {
        var adPolicy = new Object();
        adPolicy.adServerURL = adTagUrl;
        adPolicy.prerollAds = true;
        //adPolicy.prerollAdKeys = "pos=pre";
        adPolicy.midrollAds = false;
        //adPolicy.midrollAdKeys = "pos=mid";
        adPolicy.postrollAds = false;
        //adPolicy.postrollAdKeys = "pos=post";
        AR.Video.Brightcove.AdsModule.setAdPolicy(adPolicy);
    }
}

AR.Video.Ooyala = {
    ReceiveOoyalaEvent: function (playerId, eventName, eventArgs) {

        switch (eventName) {
            case "adStarted":
                if (AR.Video.IsBannerAdDivEmpty()) {
                    //googletag.content().setContent(adSlot1, "<iframe src='http://ad.doubleclick.net/adi/ar.videobanner;sz=300x250;ord=" + aradsord + "' width='300' height='250' marginwidth='0' marginheight='0' scrolling='no' frameborder='0'></iframe>");
                }
                break;
            case "playheadTimeChanged":
                if (AR.Video.IsBannerAdDivEmpty()) {
                    if (AR.VisitorInfo.IsLoggedInAsASupportingMember()) {
                        //googletag.content().setContent(adSlot1, "<iframe src='http://ad.doubleclick.net/adi/ar.supportingmember/videobanner;sz=300x250;ord=" + aradsord + "' width='300' height='250' marginwidth='0' marginheight='0' scrolling='no' frameborder='0'></iframe>");
                    } else {
                        //googletag.content().setContent(adSlot1, "<iframe src='http://ad.doubleclick.net/adi/ar.videobanner;sz=300x250;ord=" + aradsord + "' width='300' height='250' marginwidth='0' marginheight='0' scrolling='no' frameborder='0'></iframe>");
                    }
                }
                break;
        }
    }
}

//
// jQuery\AnalyticsProperties.js
//
/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="main.js" />
/// <reference path="../bundles/main-site.js" />


AR.Analytics.Event = {
    ChangeServingSize: "event6",
    Complete: "event10",
    PrintMenu: "event13",
    SearchResultClick: "event8",
    Start: "event9"
};
AR.Analytics.OverRide = {
    CreateItem: function (key, value, original) {
        this.Key = key;
        this.Value = value;
        this.Original = original;
    },
    ParseItems: function (qs) {
        var OverRideItems = new Array(3);
        var qsItems = qs.split("&");
        for (i = 0; i < qsItems.length; i++) {
            qsItem = qsItems[i].split("=");
            var overRide = new AR.Analytics.OverRide.CreateItem(qsItem[0], decodeURIComponent(qsItem[1]).replace(/\+/g, ' '), qsItem[1]);
            OverRideItems[i] = overRide;
        }
        return OverRideItems;
    }
};
AR.Analytics.Action = {
    Source: {
        BlogPost: "Blog Post",
        MenuDetail: "Menu Detail",
        MPFullMode: "MP Full Mode",
        MPDemoMode: "MP Demo Mode",
        MenuPreview: "Menu Preview",
        MyMenus: "My Menus",
        RecipeBox: "Recipe Box",
        RecipePage: "Recipe Page",
        RecipePreview: "Recipe Preview",
        RecipeSearch: "Recipe Search",
        ReferencePage: "Reference Page",
        ShoppingList: "Shopping List",
        WeblinkPage: "Weblink Page",
        Video: "Video Detail"
    },
    Type: {
        AdvancedPrintOption: "Adv Print Option",
        ChangeServings: "Adjust Servings",
        EmailBlog: "Email Blog Post",
        EmailRecipe: "Email Recipe",
        EmailRecipeBranded: "Email Recipe:Branded",
        EmailReference: "Email Reference",
        EmailWeblink: "Email Weblink",
        EmailShoppingList: "Email Shopping List",
        EmailVideo: "Email Video",
        FolderAdd: "Add to Folder",
        ItemAdd: "Add New Item",
        MealNoteAdd: "Add Meal Notes",
        MealRename: "Rename Meal",
        MealSaveAsMenu: "Save Meal as Menu",
        MenuAdd: "Add to Menu",
        MenuCreate: "Create Menu",
        MenuDelete: "Delete Menu",
        MenuDetailsAdd: "Add Menu Details",
        MenuOpen: "Open Menu",
        MenuPrint: "Print Menu",
        MenuRename: "Rename Menu",
        MenuReview: "Rate/Review Menu",
        MenuSaveAs: "Save Menu As",
        MenuShare: "Share Menu",
        MpMealDrop: "MP Drop in Meal",
        MpMealReorder: "MP Reorder Meal",
        MpMyMenusSearch: "MP My Menus Search",
        MpRecipeBoxSearch: "MP Recipe Box Search",
        MpRecipeMove: "MP Move Recipe",
        MpRecipeReorder: "MP Reorder Recipe",
        MpRecipeSearch: "MP Recipe Search",
        MyMenuAdd: "Add to My Menus",
        Note: "Personal Note",
        NutritionSearchCollapsed: "Nutrition Search Collapsed",
        NutritionSearchExpanded: "Nutrition Search Expanded",
        RecipeAddPhoto: "Add a Recipe Photo",
        RecipeBoxAdd: "Add to Recipe Box",
        RecipeCustomize: "Customize Recipe",
        RecipeEmail: "Email Recipe",
        RecipePhotoLayer: "Recipe Photo Layer",
        RecipePrint: "Print Recipe",
        RecipeReview: "Rate/Review Recipe",
        RecipeReviewLayer: "Recipe Review Layer",
        RecipeSearchMoreClicked: "Recipe Search - More Description",
        RecipeSearchNutritionClicked: "Recipe Search - Nutrition",
        RecipeSearchPhotoClicked: "Recipe Search - Recipe Photo",
        ServingsAdjust: "Adjust Servings",
        ShoppingListAddItem: "Add Grocery Item",
        ShoppingListAddMenu: "Add Menu to SL",
        ShoppingListAddRecipe: "Add Recipe to Shopping List",
        ShoppingListCreate: "Create Shopping List",
        ShoppingListEmail: "Email Shopping List",
        ShoppingListPrint: "Print Shopping List"
    },
    Item: {
        Custom: "Custom",
        MealItem: "Meal",
        Menu: "Menu",
        MenuAR: "Menu AR",
        MenuPersonal: "Menu Personal",
        MenuSample: "Menu Sample",
        NonPartnerVideo: "Non Partner Video",
        PartnerVideo: "Partner Video",
        Personal: "Personal",
        Recipe: "Kitchen Approved",
        Reference: "Reference",
        Weblink: "Weblink",
        WriteInMealItem: "Write In"
    },
    ActionOption: {
        AdvancedPrintCancelTheme: "Adv Print Cancel Theme",
        AdvancedPrintChooseColor: "Adv Print Pick Color",
        AdvancedPrintChooseFont: "Adv Print Pick Font",
        AdvancedPrintChoosePhoto: "Adv Print Pick Photo",
        AdvancedPrintChooseReview: "Adv Print Pick Reviews",
        AdvancedPrintChooseTheme: "Adv Print Pick Theme",
        AdvancedPrintCustomHeadline: "Adv Print Custom Headline",
        AdvancedPrintSaveTheme: "Adv Print Save Theme",
        MenuPrintCookingInstructions: "Print Opt:Instructions",
        MenuPrintMeal: "Print Opt:Meal",
        MenuPrintShoppingList: "Print Opt:SL",
        MenuSpecialCreate: "Create Menu:Custom",
        MenuWeeklyCreate: "Create Menu:Week"
    },
    CallToAction: {
        ArToolsMenuTab: "AR Tools Menus Tab",
        ArToolsRecipeBoxTab: "AR Tools Recipe Box Tab",
        ArToolsShoppingListTab: "AR Tools SL Tab",
        CookMenusThumb: "Cooks Menus:Thumb",
        CookMenusTitle: "Cooks Menus:Title",
        LatestARMenusThumb: "Latest AR Menus:Thumb",
        LatestARMenusMenuTitle: "Latest AR Menus:Title",
        LatestUserMenusMenuTitle: "Latest User Menus:Menu Title",
        LatestUserMenusThumb: "Latest User Menus:Thumb",
        MenuDetailMenuCustomize: "Menu Detail:Customize Menu",
        MenuDetailMpTry: "Menu Detail:Try MP",
        MenuDetailMyMenusAdd: "Menu Detail:Add to My Menus",
        MenuDetailReview: "Menu Detail:RateReview",
        MenuDetailShoppingListAdd: "Menu Detail:Add to SL",
        MenuListThumb: "Menu List:Thumb",
        MenusLikeThisMenuTitle: "Menus Like This:Menu Title",
        MenuListMenuTitle: "Menu List:Title",
        MenuListNotification: "Menu List:Notification",
        MenuListItem: "Menu List:Item",
        MenuTabFeaturedMenu: "Menu Tab Featured Menu",
        MenuToggleThumb: "Menus Toggle:Thumb",
        MenuToggleTitle: "Menus Toggle:Title",
        MpNotifications: "MP Notifications",
        RecipeDetailReview: "Recipe Detail:RateReview",
        RecipeBoxMenuAdd: "Recipe Box:Add to Menu",
        RecipeBoxReview: "RecipeBox:RateReview",
        RecipeMenuAdd: "Recipe:Add to Menu",
        RelatedMenu: "Related Menu",
        ShoppingListCustomizeMenu: "SL:Customize Menu",
        SupportingMemberIcon: "Blue Star",
        WeeklyMenuAlerts: "New Menu Sign Up",
        PrimaryNavMenuPlanAMenu: "PrimaryNav:Try MP",
        PrimaryNavMenuWeeklySignUp: "PrimaryNav: New Menu Sign Up",
        PrimaryNavBuzzNewsletters: "PrimaryNav: Newsletters",
        PrimaryNavMyARJoinForFreeTab: "PrimaryNav:Tab7",
        PrimaryNavMyARJoinForFreeBtn: "PrimaryNav:Tab7 Free",
        PrimaryNavMyARSupportingMemberBtn: "PrimaryNav:Tab7 Supporting"
    },
    LayerName: {
        ChangeServings: "Adjust Servings",
        EmailBlog: "Email Blog Post",
        EmailRecipe: "Email Recipe",
        EmailRecipeBranded: "Email Recipe:Branded",
        EmailShoppingList: "Email Shopping List",
        EmailVideo: "Email Video",
        NewItemAdd: "Add New Item",
        NotesAdd: "Add Notes",
        MealRename: "Rename Meal",
        MenuCreate: "Create Menu",
        MenuDelete: "Delete Menu",
        MenuDetailsAdd: "Add Menu Details",
        MenuOpen: "Open Menu",
        MenuPreview: "Menu Preview",
        MenuRename: "Rename Menu",
        MenuSaveAs: "Save Menu As",
        MenuShare: "Share Menu",
        MpInitialUX: "MP Initial UX",
        MpMenuCreate: "Create New Menu",
        PersonalRecipeAdd: "Add New Personal Recipe",
        RateReview: "Rate Review",
        RecipePhoto: "Recipe Photo Layer",
        RecipePreview: "Recipe Preview",
        RecipeReview: "Recipe Review Layer",
        ServingsAdjust: "Adjust Servings",
        ShoppingListCreate: "Create Shopping List",
        UnsavedWork: "Unsaved Work"
    },
    CustomLinkClick: {
        Back: "Back",
        CompletePurchaseButton: "Complete Purchase",
        MealAdd: "Add Meal to Menu",
        MealDelete: "Delete Meal",
        MealNotesAdd: "Add Meal Notes",
        MealRecipeDelete: "Delete Recipe from Meal",
        MealSaveAsMenu: "Save Meal as Menu",
        MealServingSizeChange: "Change Meal Serving Size",
        MenuAdd: "Add to Menu",
        MenuAddRecipe: "Add Recipe to Menu",
        MenuAddWeblink: "Add Weblink to Menu",
        MenuAddWebReference: "Add Reference to Menu",
        MenuAddtoMenu: "Add Menu to Menu",
        MenuCreate: "Create Menu",
        MenuDelete: "Delete Menu",
        MenuDetailActSLCollapse: "Menu Detail Act SL Collapsed",
        MenuDetailActSLExpand: "Menu Detail Act SL Expanded",
        MenuDetailsAdd: "Add Menu Details",
        MenuDetailSLCollapse: "Menu Detail:SL Collapsed",
        MenuDetailSLExpand: "Menu Detail:SL Expanded",
        MenuDetailMenuAdd: "Menu Detail:Add to My Menus",
        MenuMealAdd: "Add Meal to Menu",
        MenuNutritionCollapse: "Menu Nutrition Collapsed",
        MenuNutritionExpand: "Menu Nutrition Expanded",
        MenuPreview: "Menu Preview",
        MenuPrint: "Print Menu",
        MenuRecipeAddExpanded: "Add Recipe to Menu Expanded",
        MenuRename: "Rename Menu",
        MenuReview: "Rate/Review Menu",
        MenuSave: "Save Menu",
        MenuSaveAs: "Save Menu As",
        MenuServingSizeChange: "Change Menu Serving Size",
        MenuShare: "Share Menu",
        MenuShareStatus: "Menu Share Status",
        MpMealNutritionCollapse: "MP Meal Nutrition Collapsed",
        MpMealNutritionExpand: "MP Meal Nutrition Expanded",
        MpMenuOptionsCollapse: "MP Menu Opt Collapsed",
        MpMenuOptionsExpand: "MP Menu Opt Expanded",
        MpMyArToolsCollapse: "MP My ARTools Collapsed",
        MpMyArToolsExpand: "MP My ARTools Expanded",
        MpMyMenusCollapse: "MP MyMenus Collapsed",
        MpMyMenusExpand: "MP MyMenus Expanded",
        MpMyRecipesCollapse: "MP MyRecipes Collapsed",
        MpMyRecipesExpand: "MP MyRecipes Expanded",
        MpSearchCollapse: "MP Search Collapsed",
        MpSearchExpand: "MP Search Expanded",
        MyArItemOptionCollapse: "MyAR Menu Item Opt Collapsed",
        MyArItemOptionExpand: "MyAR Menu Item Opt Expanded",
        MyArMenusOptionsCollapse: "MyAR Menus Opt Collapsed",
        MyArMenusOptionsExpand: "MyAR Menus Opt Expanded",
        MyArRbItemOptionsCollapse: "MyAR RB Item Opt Collapsed",
        MyArRbItemOptionsExpand: "MyAR RB Item Opt Expanded",
        MyArRbMenuRecipeAddExpand: "Add Recipe to Menu Expanded",
        MyArRbOptionsCollapse: "MyAR RB Opt Expanded",
        MyArRbOptionsExpand: "MyAR RB Opt Expanded",
        MyArSlOptCollapse: "MyAR SL Opt Collapsed",
        MyArSlOptExpand: "MyAR SL Opt Expanded",
        MyMenusAdd: "Add to My Menus",
        PersonalRecipeCreate: "Create Personal Recipe",
        RecipeDetailSLCollapse: "Recipe Detail:SL Collapsed",
        RecipeDetailSLExpand: "Recipe Detail:SL Expanded",
        RecipeFolders: "Recipe Folders",
        RecipePreview: "Recipe Preview",
        RecipeReview: "Rate/Review Recipe",
        RecipeSearch: "Recipe Search",
        RecipeServingSizeChange: "Change Recipe Serving Size",
        ReferencePreview: "Reference Preview",
        ShoppingListAddMenu: "Add Menu to SL",
        ShoppingListCreate: "Create Shopping List",
        ShoppingListRecipeAdd: "Add Recipe to SL",
        WeblinkPreview: "Weblink Preview",
        WriteInMealItem: "Write In Meal Item",
        WriteInMenuItem: "Write In Menu Item"
    },
    LinkName: {
        ArToolsMenusCreateMenu: "AR Tools:Create Menu",
        ArToolsMenusView: "AR Tools:View Menus",
        ArToolsMenuThumb: "AR Tools:Menu Thumb",
        ArToolsMenuTitle: "AR Tools:Title",
        ArToolsSampleMenu: "AR Tools:Sample Menu",
        ContinueAwayFromPage: "Continue Away from Page",
        CreatePersonalRecipe: "Create Personal Recipe",
        FeaturedMenuMealTitle: "Featured Menu:Meal Title",
        FeaturedMenuMenuPlannerTry: "Featured Menu:Try MP",
        FeaturedMenuMenuTitle: "Featured Menu:Menu Title",
        FeaturedMenuViewMenu: "Featured Menu:View Menu",
        LatestARMenusThumb: "Latest AR Menus:Thumb",
        LatestARMenusMenuTitle: "Latest AR Menus:Title",
        LatestUserMenusThumb: "Latest User Menus:Thumb",
        LatestUserMenusMenuTitle: "Latest User Menus:Title",
        MenuCategory: "Menu Category:",
        MenuCustomize: "Customize Menu",
        MenuEdit: "Edit Menu",
        MenuPageView: "View Menu Page",
        MenuPlannerTry: "Try MP",
        MenuPrint: "Print Menu",
        MenusLikeThisMenuTitle: "Menus Like This:Title",
        MenuTag: "Menu Tag:",
        MenuThumb: "Menu Thumb",
        MenuTitle: "Menu Title",
        MenuToggleThumb: "Menus Toggle:Thumb",
        MenuToggleTitle: "Menus Toggle:Title",
        MyArSlNewMenu: "My AR SL:New Menu",
        MyArToolsMP: "MyAR Tools:MP",
        NoMenusNewMenu: "No Menus:New Menu",
        NoMenusSampleMenu: "No Menus:Sample Menu",
        OptionsNewMenu: "Opt:New Menu",
        RateReviewCustomizeMenu: "Rate/Review:Customize Menu",
        RecipePageView: "View Recipe Page",
        RecipePhotoLayerTurn: "Recipe Photo Layer Turn",
        RecipePhotoLayerViewAll: "Recipe Photo Layer View All",
        RecipeReviewLayerTurn: "Recipe Review Layer Turn",
        RecipeReviewLayerViewAll: "Recipe Review Layer View All",
        RecipeReviewLayerHeader: "Recipe Header",
        RecipeReviewLayerBlock: "Recipe Review Block",
        RecipeTitleSearch: "Search:Recipe Title",
        RelatedMenusMenuCreate: "Related Menus:Create Menu",
        RelatedMenusMenuTitle: "Related Menus:Title",
        RelatedMenusViewMenus: "Related Menus:View Menus",
        RelatedMenusViewRelated: "Related Menus:View Related",
        RelatedMenusViewSampleMenu: "Related Menus:Sample Menu",
        ReturnToPage: "Return to Page",
        ShoppingListMenuCustomize: "SL:Customize Menu",
        VideoHomeNewestTab: "VH_Newest",
        VideoHomePopularTab: "VH_Popular",
        VideoHomeAllVideosTab: "VH_AllVideos",
        VideoHomeBrandsTab: "VH_Brands",
        VideoCarouselThumbnailClick: "VH_VideoPromos",
        VideoCarouselPrevNextClick: "VH_CarouselTurn"
    },
    ContentType: {
        Recipe: "Recipe",
        CommunityList: "Community List",
        MenuList: "Menu List",
        MpDemoMode: "MP Demo Mode",
        MpFullMode: "MP Full Mode",
        MenuPrint: "Menu Print",
        RecipePhoto: "Recipe Photos",
        Review: "Reviews"
    },
    GetItem: function (itemType) {
        var retVal = "";
        itemType = parseInt(itemType);
        switch (itemType) {
            case AR.ItemType.Recipe:
                retVal = this.Item.Recipe;
                break;
            case AR.ItemType.WebLink:
                retVal = this.Item.Weblink;
                break;
            case AR.ItemType.Reference:
                retVal = this.Item.Reference;
                break;
            case AR.ItemType.PersonalRecipe:
                retVal = this.Item.Personal;
                break;
            case AR.ItemType.CustomRecipe:
                retVal = this.Item.Custom;
                break;
            case AR.ItemType.MealItem:
                retVal = this.Item.MealItem;
                break;
            case AR.ItemType.Menu:
                retVal = this.Item.Menu;
                break;
            case AR.ItemType.MenuAR:
                retVal = this.Item.MenuAR;
                break;
            case AR.ItemType.MenuPersonal:
                retVal = this.Item.MenuPersonal;
                break;
            case AR.ItemType.MenuSample:
                retVal = this.Item.MenuSample;
                break;
            case AR.ItemType.WriteInMealItem:
                retVal = this.Item.WriteInMealItem;
                break;
            default:
                retVal = null;
                break;
        }
        return retVal;
    },
    GetMenuItem: function (menuType) {
        var retVal = "";
        menuType = parseInt(menuType);
        switch (menuType) {
            case AR.MenuType.MenuAR:
                retVal = this.Item.MenuAR;
                break;
            case AR.MenuType.MenuPersonal:
                retVal = this.Item.MenuPersonal;
                break;
            case AR.MenuType.MenuSample:
                retVal = this.Item.MenuSample;
                break;           
            default:
                retVal = null;
                break;
        }
        return retVal;
    }

}
//
// jQuery\AnalyticsMethods.js
//
/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="main.js" />
/// <reference path="../bundles/main-site.js" />


AR.Analytics.RecordPageView = function (data) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null && data != null) {
        AR.Analytics.ResetS(s);

        $.extend(s, data);

        //        s.pageName = data.pageName;

        //        s.channel = data.channel;
        //        s.events = data.events;
        s.eVar1 = s.pageName;
        //        s.prop6 = data.prop6;
        //        s.prop24 = data.prop24;
        //        s.prop36 = data.prop36;

        AR.Analytics.LogS("-- BI: RecordPageView s.t()", s);

        s.t();

        AR.Analytics.ResetS(s);
    }
};

/*
******  All NON-Funnel Methods reside here for client side BI Beacons
******  Free Member Reg & Supporting Member Methods still reside in main.js
*/
AR.Analytics.SendBeacon = function (data, anchor) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null && data != null) {
        s.linkTrackVars = data.linkTrackVars || 'None';
        s.linkTrackEvents = data.linkTrackEvents || 'None';
        s.events = data.events;

        s.pe = data.pe || 'lnk_o';    //Link Type (lnk_d, lnk_e, lnk_o)
        s.pev1 = data.pev1;           //Link URL
        s.pev2 = data.pev2 || 'None'; //Link Name

        //qs v1 - v50
        s.eVar3 = data.eVar3;   //Call To Action
        s.eVar7 = (data.usePageContentTypeAsSource && s.prop6) ? s.prop6 : data.eVar7; //Action Source
        s.eVar8 = data.eVar8;   //Action Type
        s.eVar9 = data.eVar9;   //Action Item
        s.eVar12 = data.eVar12; //Action Detail
        s.eVar13 = data.eVar13; //AB Test Version

        //qs c1 - c50
        s.prop24 = data.prop24; //Link Name
        s.prop34 = data.prop34; //Link Name
        s.prop36 = data.prop36; //Layer Name

        var msg = "";
        if (!data.disableDelay && anchor != null) {
            s.tl(anchor[0], 'o', s.pev2);
            msg = "-- BI: SendBeacon  s.tl(this, 'o', '" + s.pev2 + "')";
        }
        else {
            s.tl(true, 'o', s.pev2);
            msg = "-- BI: SendBeacon  s.tl(true, 'o', '" + s.pev2 + "')";
        }       
        AR.Analytics.LogS(msg, s);
        AR.Analytics.ResetS(s);
    }
};

AR.Analytics.RecordAction = function (event, source, type, item, itemID) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.linkTrackVars = (source != '') ? "eVar7," : '';
        s.linkTrackVars += (type != '') ? "eVar8," : '';
        s.linkTrackVars += (item != '') ? "eVar9," : '';
        s.linkTrackVars += (itemID != '') ? "eVar12," : '';
        s.linkTrackVars += (s.linkTrackEvents != '') ? "events" : '';
        s.linkTrackVars = (s.linkTrackVars.endsWith(',')) ? s.linkTrackVars.substr(0, s.linkTrackVars.length - 1) : s.linkTrackVars;
        s.eVar7 = source;
        s.eVar8 = type;
        s.eVar9 = item;
        s.eVar12 = itemID;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        if (type != '') {
            s.tl(true, 'o', type);
        }
        else {
            s.tl(true, 'o', 'None');
        }
        var msg = "BI: RecordAction('" + event + "','" + source + "','" + type + "','" + item + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|";
        msg += (source != '') ? "s.eVar7:'" + s.eVar7 + "'|" : '';
        msg += (type != '') ? "s.eVar8:'" + s.eVar8 + "'|" : '';
        msg += (item != '') ? "s.eVar9:'" + s.eVar9 + "'|" : '';
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- * s.tl(true, 'o', '" + type + "')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar7 = s.eVar8 = s.eVar9 = s.linkTrackEvents = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordActionOption =  function (actionoption, actiontype) {
    var s = AR.Analytics.GetOmnitureS();
    var event = '';
    if (s != null) {
        s.linkTrackVars = "eVar12";
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.eVar12 = actionoption;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.tl(true, 'o', actiontype);

        var msg = "BI: RecordActionOption('" + actionoption + "','" + actiontype + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar12:'" + s.eVar12 + "' * s.tl(true, 'o', '" + actiontype + "')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar12 = s.linkTrackEvents = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordInternalSource = function (linkName) {
    var s = AR.Analytics.GetOmnitureS();
    var event = '';
    if (s != null) {
        s.linkTrackVars = "prop24";
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.prop24 = linkName;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordInternalSource('" + linkName + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.prop24:'" + s.prop24 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop24 = s.linkTrackEvents = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordCustomLinkClick = function (linkType) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.events = "None";
        s.linkTrackVars = "None";
        s.pe = 'lnk_o';
        s.pev2 = linkType;
        s.tl(true, 'o', linkType);
        var msg = "BI: RecordCustomLinkClick('" + linkType + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|linkType:'" + linkType + "' * s.tl(true, 'o', '" + linkType + "')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.pe = s.pev2 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordExternalShare = function (source, type, item, customLinkOverRide) {
    var s = AR.Analytics.GetOmnitureS();
    var customLinkClickValue = (customLinkOverRide != '') ? customLinkOverRide : type;
    if (s != null) {
        s.events = "None";
        s.pe = 'lnk_o';
        s.pev2 = customLinkClickValue;
        s.linkTrackVars = (source != '') ? "eVar7," : '';
        s.linkTrackVars += (type != '') ? "eVar8," : '';
        s.linkTrackVars += (item != '') ? "eVar9," : '';
        s.linkTrackVars = (s.linkTrackVars.endsWith(',')) ? s.linkTrackVars.substr(0, s.linkTrackVars.length - 1) : s.linkTrackVars;
        s.eVar7 = source;
        s.eVar8 = type;
        s.eVar9 = item;
        s.tl(true, 'o', customLinkClickValue);
        var msg = "BI: RecordExternalShare('" + source + "','" + type + "','" + item + "','" + customLinkOverRide + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|";
        msg += (source != '') ? "s.eVar7:'" + s.eVar7 + "'|" : '';
        msg += (type != '') ? "s.eVar8:'" + s.eVar8 + "'|" : '';
        msg += (item != '') ? "s.eVar9:'" + s.eVar9 + "'|" : '';
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- * s.tl(true, 'o', '" + customLinkClickValue + "')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar7 = s.eVar8 = s.eVar9 = s.linkTrackEvents = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordLinkName = function (linkName) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.events = "None";
        s.linkTrackVars = "prop34";
        s.prop34 = linkName;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordLinkName('" + linkName + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.prop34:'" + s.prop34 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordCallToAction = function (callToAction) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.events = "None";
        s.linkTrackVars = "eVar3";
        s.eVar3 = callToAction;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordCallToAction('" + callToAction + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar3:'" + s.eVar3 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar3 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordCallToActionAndLinkName = function (callToAction, linkName) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.events = "None";
        s.linkTrackVars = "eVar3,prop34";
        s.eVar3 = callToAction;
        s.prop34 = linkName;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordCallToActionAndLinkName('" + callToAction + "','" + linkName + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar3:'" + s.eVar3 + "'|s.prop34:'" + s.prop34 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.eVar3 = s.prop34 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordCallToActionAndCustomLink = function (callToAction, linkType) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.events = "None";
        s.linkTrackVars = "eVar3";
        s.pe = 'lnk_o';
        s.pev2 = linkType;
        s.eVar3 = callToAction;
        s.tl(true, 'o', linkType);

        var msg = "BI: RecordCallToActionAndCustomLink('" + callToAction + "','" + linkType + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar3:'" + s.eVar3 + "|linkType:'" + linkType + "' * s.tl(true, 'o', '" + linkType + "')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar3 = s.pe = s.pev2 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordSearchAction = function (event, source, type, searchTerm, resultCount) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackVars = "eVar7,eVar8,eVar11,prop14,events";
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.eVar7 = source;
        s.eVar8 = type;
        s.eVar11 = searchTerm;
        s.prop14 = resultCount;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordSearchAction('" + event + "','" + source + "','" + type + "','" + searchTerm + "','" + resultCount + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar7:'" + s.eVar7 + "'|s.eVar8:'" + s.eVar8 + "'|s.eVar11:'" + s.eVar11 + "'|s.prop14:'" + s.prop14 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar7 = s.eVar8 = s.eVar11 = s.prop14 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordSearchActionDetail = function (event, source, type, searchTerm, resultCount, actionDetail) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackVars = "eVar7,eVar8,eVar11,prop14,eVar12,events";
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.eVar7 = source;
        s.eVar8 = type;
        s.eVar11 = searchTerm;
        s.eVar12 = actionDetail;
        s.prop14 = resultCount;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordSearchActionDetail('" + event + "','" + source + "','" + type + "','" + searchTerm + "','" + resultCount + "','" + actionDetail + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar7:'" + s.eVar7 + "'|s.eVar8:'" + s.eVar8 + "'|s.eVar11:'" + s.eVar11 + "'|s.prop14:'" + s.prop14 + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- |s.evar12:'" + s.eVar12 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar7 = s.eVar8 = s.eVar11 = s.prop14 = s.eVar12 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordSearchResultClick = function (event, linkName) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackVars = "prop34,events";
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.prop34 = linkName;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordSearchResultClick('" + event + "','" + linkName + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.prop34:'" + s.prop34 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordCanvasDrop = function (type) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackVars = "eVar8";
        s.events = "None";
        s.eVar8 = type;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordCanvasDrop('" + type + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.eVar8:'" + s.eVar8 + "' * s.tl(true, 'o', 'None')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar8 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordLayerOpen = function (layerName, contentType) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackVars = "prop36";
        s.linkTrackVars += (contentType != '') ? ',prop6' : '';
        s.events = "None";
        s.prop36 = layerName;
        s.prop6 = contentType;
        s.tl(true, 'o', 'None');

        var msg = "BI: RecordLayerOpen('" + layerName + "','" + contentType + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|s.prop36:'" + s.prop36 + "'";
        msg += (contentType != '') ? "|s.prop6:'" + s.prop6 + "'" : '';
        msg += " * s.tl(true, 'o', 'None')"
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar8 = s.prop36 = s.prop6 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordLayerOpenAction = function (layerName, event, source, type, item, itemID) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.linkTrackVars = (layerName != '') ? "prop36," : '';
        s.linkTrackVars += (source != '') ? "eVar7," : '';
        s.linkTrackVars += (type != '') ? "eVar8," : '';
        s.linkTrackVars += (item != '') ? "eVar9," : '';
        s.linkTrackVars += (itemID != '') ? "eVar12," : '';
        s.linkTrackVars += (s.linkTrackEvents != '') ? "events" : '';
        s.linkTrackVars = (s.linkTrackVars.endsWith(',')) ? s.linkTrackVars.substr(0, s.linkTrackVars.length - 1) : s.linkTrackVars;
        s.prop36 = layerName;
        s.eVar7 = source;
        s.eVar8 = type;
        s.eVar9 = item;
        s.eVar12 = itemID;
        var param = (type != "") ? type : "None";
        s.tl(true, 'o', param);

        var msg = "BI: RecordLayerOpenAction('" + layerName + "','" + event + "','" + source + "','" + type + "','" + item + "')";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.linkTrackVars:'" + s.linkTrackVars + "'";
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- s.events:'" + s.events + "'|";
        msg += (layerName != '') ? "s.prop36:'" + s.prop36 + "'|" : '';
        msg += (source != '') ? "s.eVar7:'" + s.eVar7 + "'|" : '';
        msg += (type != '') ? "s.eVar8:'" + s.eVar8 + "'|" : '';
        msg += (item != '') ? "s.eVar9:'" + s.eVar9 + "'|" : '';
        AR.Analytics.LogConsoleInfo(msg);
        msg = "-- * s.tl(true, 'o', '" + param + "')";
        AR.Analytics.LogConsoleInfo(msg);
        s.prop34 = s.eVar7 = s.eVar8 = s.eVar9 = s.prop36 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordVideoClick = function (event, actionType, actionItem, actionDetail, internalSource) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null) {
        s.linkTrackVars = "eVar1,eVar7,eVar8,eVar9,eVar12,events";
        s.linkTrackVars += (internalSource != '') ? ",prop24" : '';
        s.linkTrackEvents = (event instanceof Array) ? event.join(",") : event;
        s.events = (s.linkTrackEvents != "") ? s.linkTrackEvents : "None";
        s.eVar1 = s.pageName;
        s.eVar7 = s.prop6 || s.pageName;
        s.eVar8 = actionType;
        s.eVar9 = actionItem;
        s.eVar12 = "Video: " + actionDetail;
        s.prop24 = internalSource;
        s.tl(true, "o", ((event === "event10") ? "Video Close" : actionType));

        s.eVar1 = s.eVar7 = s.eVar8 = s.eVar9 = s.eVar12 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.RecordCarouselAction = function (linkName) {
    var s = AR.Analytics.GetOmnitureS();
    if (s != null && linkName) {
        s.events = "None";
        s.linkTrackVars = "prop34";
        s.prop34 = linkName;
        s.tl(true, 'o', linkName);

        s.prop34 = "";
        s.linkTrackVars = s.events = "None";
    }
};
AR.Analytics.CollapsiblePanelScript = function () {
    var _value;

    function SetValue(value) {
        if (value == null || value.toString() == '') {
            AR.LogAlert('CollapsiblePanelScript.SetValue is null or empty', 'Print Page', 'Advanced Print Options');
        }
        _value = value;
    }
    function GetValue() {
        if (_value == null || _value.length < 1) {
            AR.LogAlert('CollapsiblePanelScript.GetValue is null or empty', 'Print Page', 'Advanced Print Options');
            return '';
        }
        else
            return _value;
    }
    return {
        SetValue: SetValue,
        GetValue: GetValue
    };
} ();
//
// Utilities\AdSuppress.js
//


AR.AdSuppress = function(elementNotToHide) {

    $("embed, object, select").each(function () {

        var elementToHide = $(this);

        if (elementToHide.css("visibility") == "hidden") {
            return;
        }

        if (elementNotToHide != null) {
            var shouldntHideElement = false;
            
            elementNotToHide.each(function() {
                shouldntHideElement = shouldntHideElement || jQuery.contains(this, elementToHide[0]);
            });

            if (shouldntHideElement) {
                return;
            }
        }

        elementToHide.css("visibility", "hidden");

        AR.Dialog.AddOnClosedHandler(function() {
            elementToHide.css("visibility", "visible");
        });

        elementToHide.parents().each(function() {
            var parentOfElementToHide = $(this);
            var originalZIndex = parentOfElementToHide.css("z-index");

            parentOfElementToHide.css("z-index", "0");

            AR.Dialog.AddOnClosedHandler(function() {
                parentOfElementToHide.css("z-index", originalZIndex);
            });
        });
    });
}

//
// Utilities\Logging.js
//


//
//  AR.LogEval - evaluates an expression for logging purposes.
//  (if an exception is thrown, a string describing the exception is thrown instead)
//  Input parameter 'expression' should be a string.  Only global values can be
//  referenced, local variables will not evaluate successfully.
//

AR.LogEval = function (expression) {
    var result = null;

    try {
        result = eval(expression);

        if (typeof (result) == "undefined") {
            result = {
                LogEvalMessage: "Value was undefined"
            };
        }
    }
    catch (exception) {

        result = {
            LogEvalMessage: "Exception thrown during eval",
            exception: exception
        };
    }

    return result;
};


//
// AR.LogErrorEx - Logs a client-side error:
//  data - arbitrary javascript data (can be nested, etc)
//  source - string indicating sourcefile that threw the error
//  title - string describing error
//

AR.LogErrorEx = function (data, source, title) {

    try {
        AR.SetModuleLogContent("PageInfo", {
            location: AR.LogEval("window.location.href"),
            visitor: AR.LogEval("AR.VisitorInfo._data"),
            TypeSpecificID: AR.LogEval("AR.TypeSpecificID")
        });

        data = $.extend({}, data, { modules: AR._moduleLogContent });

        data = AR.LogClean(data);

        data = JSON.stringify(data);
        source = (source == null) ? "Main.js" : source;
        title = (title == null) ? "Script Error" : title;

        var url = AR.ClientUrlProvider.ResolveUrl(AR.Config.ErrorLoggingHandler) + "?source=" + escape(source) + "&title=" + escape(title);
        var result = $.post(url, { description: data });
    } catch (e) { }
};

AR.LogAlertEx = function (data, source, title) {
    try {
        AR.SetModuleLogContent("PageInfo", {
            location: AR.LogEval("window.location.href"),
            visitor: AR.LogEval("AR.VisitorInfo._data"),
            TypeSpecificID: AR.LogEval("AR.TypeSpecificID")
        });

        data = $.extend({}, data, { modules: AR._moduleLogContent });

        data = AR.LogClean(data);

        data = JSON.stringify(data);
        source = (source == null) ? "Main.js" : source;
        title = (title == null) ? "Script Alert" : title;

        var url = AR.ClientUrlProvider.ResolveUrl(AR.Config.ErrorLoggingHandler) + "?source=" + escape(source) + "&title=" + escape(title) + "&type=Alert";
        var result = $.post(url, { description: data });
    } catch (e) { }
};

//
// AR.SetModuleLogContent
//   Stores some module-specific debug context to be sent with the next
// logged error.  Nothing more than a key-value store, where the module
// name is the key.  The data can be any type of data, all will be sent
// to the server.
//

AR.SetModuleLogContent = function (moduleName, data) {
    AR._moduleLogContent[moduleName] = AR.LogClean(data);
};

AR._moduleLogContent = {};


//
//  AR.LogClean(input) - does a deep clone of input.  Only objects
//  that can be handled safely by our logging code is included in the result.
//  (our logging code can handle anything that can be converted to JSON)
//  The cloning will discard member functions and type information (prototype).
//
//

AR.LogClean = function (expression, allowedDepth) {

    if (typeof (allowedDepth) != "number") {
        allowedDepth = 8;  // limit recursive depth
        AR.LogClean.CallLimit = 256;  // limit overall number of calls
    }

    if (allowedDepth <= 0
		|| AR.LogClean.CallLimit <= 0) {
        return "AR.LogClean stopped due to recursion limit";
    }

    AR.LogClean.CallLimit--;

    if (typeof (expression) == "undefined"
		|| expression == null
		|| typeof (expression) == "number"
		|| typeof (expression) == "string"
		|| typeof (expression) == "boolean") {

        return expression;
    }
    else if (typeof (expression) == "function") {
        return null;
    }
    else {

        var result = {}

        // Do a quick check to see accessing the objects iterator will throw an exception
        try {
            for (key in expression) {
                break;
            }
        }
        catch (e) {
            return AR.LogClean({
                message: "AR.LogClean stopped due to exception accessing iterator",
                exception: e
            });
        }

        // Now iterate for real, recording each object property.
        // The properties are evaluated in an exception handler, but the call
        // to AR.LogClean on the results are not.  In this way we don't recurse
        // through too many exception blocks

        for (key in expression) {

            var value = null;
            var haveValue = false;

            try {
                value = expression[key];

                if (typeof (value) != "function")
                    haveValue = true;
            }
            catch (error) {
            }

            if (haveValue)
                result[key] = AR.LogClean(value, allowedDepth - 1);
        }

        return result;
    }
}

//
// Utilities\BaseN.js
//
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @fileoverview Numeric base conversion library.  Works for arbitrary bases and
* arbitrary length numbers.
*
* For base-64 conversion use base64.js because it is optimized for the specific
* conversion to base-64 while this module is generic.  Base-64 is defined here
* mostly for demonstration purpose.
*
* TODO: Make base64 and baseN classes that have common interface.  (Perhaps...)
*
*/

    //goog.provide('goog.crypt.baseN');

/**
* Base-2, i.e. '01'.
* @type {string}
*/
//BASE_BINARY = '01';

    /**
    * Base-2, i.e. '01'.
    * @type {string}
    */
    //BASE_BINARY = '01';

/**
* Base-8, i.e. '01234567'.
* @type {string}
*/
//BASE_OCTAL = '01234567';

    /**
    * Base-8, i.e. '01234567'.
    * @type {string}
    */
    //BASE_OCTAL = '01234567';

/**
* Base-16 using lower case, i.e. '0123456789abcdef'.
* @type {string}
*/
//BASE_LOWERCASE_HEXADECIMAL = '0123456789abcdef';

    /**
    * Base-10, i.e. '0123456789'.
    * @type {string}
    */
    //BASE_DECIMAL = '0123456789';

/**
* Base-16 using upper case, i.e. '0123456789ABCDEF'.
* @type {string}
*/
//BASE_UPPERCASE_HEXADECIMAL = '0123456789ABCDEF';

    /**
    * Base-16 using lower case, i.e. '0123456789abcdef'.
    * @type {string}
    */
    //BASE_LOWERCASE_HEXADECIMAL = '0123456789abcdef';

/**
* The more-known version of the BASE-64 encoding.  Uses + and / characters.
* @type {string}
*/
//BASE_64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

    /**
    * Base-16 using upper case, i.e. '0123456789ABCDEF'.
    * @type {string}
    */
    //BASE_UPPERCASE_HEXADECIMAL = '0123456789ABCDEF';

/**
* URL-safe version of the BASE-64 encoding.
* @type {string}
*/
//BASE_64_URL_SAFE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';

    /**
    * The more-known version of the BASE-64 encoding.  Uses + and / characters.
    * @type {string}
    */
    //BASE_64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';


/**
* Base-10, i.e. '0123456789'.
* @type {string}
*/
BASE_DECIMAL = '0123456789';

/**
* DART-safe version of the BASE-64 encoding.
* @type {string}
*/
BASE_64_DART_SAFE = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$-_.!*(),';
//Removed: + '


AR.BaseN = {

    /**
    * Converts a number from one numeric base to another.
    *
    * The bases are represented as strings, which list allowed digits.  Each digit
    * should be unique.  The bases can either be user defined, or any of
    * BASE_xxx.
    *
    * The number is in human-readable format, most significant digit first, and is
    * a non-negative integer.  Base designators such as $, 0x, d, b or h (at end)
    * will be interpreted as digits, so avoid them.  Leading zeros will be trimmed.
    *
    * Note: for huge bases the result may be inaccurate because of overflowing
    * 64-bit doubles used by JavaScript for integer calculus.  This may happen
    * if the product of the number of digits in the input and output bases comes
    * close to 10^16, which is VERY unlikely (100M digits in each base), but
    * may be possible in the future unicode world.  (Unicode 3.2 has less than 100K
    * characters.  However, it reserves some more, close to 1M.)
    *
    * @param {string} number The number to convert.
    * @param {string} inputBase The numeric base the number is in (all digits).
    * @param {string} outputBase Requested numeric base.
    * @return {string} The converted number.
    */

    RecodeString: function (number, inputBase, outputBase) {

        if (outputBase == '') {
            throw Error('Empty output base');
        }

        // Check if number is 0 (special case when we don't want to return '').
        var isZero = true;
        for (var i = 0, n = number.length; i < n; i++) {
            if (number.charAt(i) != inputBase.charAt(0)) {
                isZero = false;
                break;
            }
        }
        if (isZero) {
            return outputBase.charAt(0);
        }

        var numberDigits = AR.BaseN.StringToArray(number, inputBase);
        var inputBaseSize = inputBase.length;
        var outputBaseSize = outputBase.length;

        var result = [];

        // For all digits of number, starting with the most significant ...
        for (var i = numberDigits.length - 1; i >= 0; i--) {

            // result *= number.base.
            var carry = 0;
            for (var j = 0, n = result.length; j < n; j++) {
                var digit = result[j];
                // This may overflow for huge bases.  See function comment.
                digit = digit * inputBaseSize + carry;
                if (digit >= outputBaseSize) {
                    var remainder = digit % outputBaseSize;
                    carry = (digit - remainder) / outputBaseSize;
                    digit = remainder;
                } else {
                    carry = 0;
                }
                result[j] = digit;
            }
            while (carry) {
                var remainder = carry % outputBaseSize;
                result.push(remainder);
                carry = (carry - remainder) / outputBaseSize;
            }
            if (isZero) {
                return outputBase.charAt(0);
            }

            carry = numberDigits[i];
            var j = 0;
            while (carry) {
                if (j >= result.length) {
                    // Extend result with a leading zero which will be overwritten below.
                    result.push(0);
                }
                var digit = result[j];
                digit += carry;
                if (digit >= outputBaseSize) {
                    var remainder = digit % outputBaseSize;
                    carry = (digit - remainder) / outputBaseSize;
                    digit = remainder;
                } else {
                    carry = 0;
                }
                result[j] = digit;
                j++;
            }
        }

        return AR.BaseN.ArrayToString(result, outputBase);
    },

    /**
    * Converts a string representation of a number to an array of digit values.
    *
    * More precisely, the digit values are indices into the number base, which
    * is represented as a string, which can either be user defined or one of the
    * BASE_xxx constants.
    *
    * Throws an Error if the number contains a digit not found in the base.
    *
    * @param {string} number The string to convert, most significant digit first.
    * @param {string} base Digits in the base.
    * @return {Array.<number>} Array of digit values, least significant digit
    *     first.
    * @private
    */
    StringToArray: function (number, base) {
        var index = {};
        for (var i = 0, n = base.length; i < n; i++) {
            index[base.charAt(i)] = i;
        }
        var result = [];
        for (var i = number.length - 1; i >= 0; i--) {
            var character = number.charAt(i);
            var digit = index[character];
            if (typeof digit == 'undefined') {
                throw Error('Number ' + number +
                      ' contains a character not found in base ' +
                      base + ', which is ' + character);
            }
            result.push(digit);
        }
        return result;
    },


    /**
    * Converts an array representation of a number to a string.
    *
    * More precisely, the elements of the input array are indices into the base,
    * which is represented as a string, which can either be user defined or one of
    * the BASE_xxx constants.
    *
    * Throws an Error if the number contains a digit which is outside the range
    * 0 ... base.length - 1.
    *
    * @param {Array.<number>} number Array of digit values, least significant
    *     first.
    * @param {string} base Digits in the base.
    * @return {string} Number as a string, most significant digit first.
    * @private
    */
    ArrayToString: function (number, base) {
        var n = number.length;
        var chars = [];
        var baseSize = base.length;
        for (var i = n - 1; i >= 0; i--) {
            var digit = number[i];
            if (digit >= baseSize || digit < 0) {
                throw Error('Number ' + number + ' contains an invalid digit: ' + digit);
            }
            chars.push(base.charAt(digit));
        }
        return chars.join('');
    }
};

//
// Utilities\ClientUrlProvider.js
//

AR.ClientUrlProvider = {
    ResolveUrl: function (url) {
        if (url != null) {
            if (url.length > 1 && url.charAt(0) == '~' && url.charAt(1) == '/') {
                url = url.substr(1, url.length - 1);
                url = AR.Config.ApplicationPath + url;
            } else if (url.length > 0 && url.charAt(0) == '/') {
                url = AR.Config.ApplicationPath + url;
            }
        }
        return url;
    },
    ResolveImageUrl: function (path) {
        if (path.charAt(0) != '/') {
            path = "/" + path;
        }

        var imageServer = AR.ImageServer;
        if (imageServer.charAt(imageServer.length - 1) == '/') {
            imageServer = imageServer.substr(0, imageServer.length - 1);
        }

        return imageServer + path;
    },
    GetItemFolder: function (itemType, useFriendly) {
        var folder = "";
        switch (itemType) {
            case AR.ItemType.CustomRecipe:
                folder = (useFriendly) ? "~/CustomRecipe" : "~/My/RecipeBox/CustomRecipes";
                break;
            case AR.ItemType.WebLink:
                folder = (useFriendly) ? "~/WebLink" : "~/My/RecipeBox/Links";
                break;
            case AR.ItemType.PersonalRecipe:
                folder = (useFriendly) ? "~/PersonalRecipe" : "~/My/RecipeBox/PersonalRecipes";
                break;
            case AR.ItemType.Reference:
                folder = (useFriendly) ? "~/Reference" : "~/My/RecipeBox/References";
                break;
        }
        return folder;
    },
    GetRecipeBoxFolder: function (folderID) {
        return this.ResolveUrl("~/My/RecipeBox/Default.aspx?folder=" + folderID);
    },
    GetMyReviewsDetailPage: function (sharedItemID, itemType) {
        sharedItemID = parseInt(sharedItemID);
        itemType = parseInt(itemType);
        return this.ResolveUrl("~/My/Shared/Reviews/Detail.aspx?id=" + sharedItemID + "&typeID=" + itemType);
    },
    GetCustomizeRecipeUrl: function (recipeID) {
        return this.ResolveUrl("~/My/RecipeBox/CustomRecipes/AddEdit.aspx?recipeID=" + recipeID + "&new=1");
    },
    GetRecipeBoxListViewRatingImage: function (rating) {

        // Multiply by 2 and round to give an int. 0=0, 2=1 star, 3=1 and half stars, etc.
        var relativeURL = "/ar/myar/stars/";
        var newRating = Math.round(rating * 2);

        switch (newRating) {
            case 0:
                relativeURL += "sm_0star.gif";
                break;
            case 1:
                relativeURL += "sm_0.5star.gif";
                break;
            case 2:
                relativeURL += "sm_1star.gif";
                break;
            case 3:
                relativeURL += "sm_1.5star.gif";
                break;
            case 4:
                relativeURL += "sm_2star.gif";
                break;
            case 5:
                relativeURL += "sm_2.5star.gif";
                break;
            case 6:
                relativeURL += "sm_3star.gif";
                break;
            case 7:
                relativeURL += "sm_3.5star.gif";
                break;
            case 8:
                relativeURL += "sm_4star.gif";
                break;
            case 9:
                relativeURL += "sm_4.5star.gif";
                break;
            case 10:
                relativeURL += "sm_5star.gif";
                break;
        };

        return this.ResolveImageUrl(relativeURL);
    },
    GetRatingImage: function (rating) {

        var relativeURL = "/images/";
        var newRating = Math.round(rating * 2);

        switch (newRating) {
            case 0:
                relativeURL += "15876.gif";
                break;
            case 1:
                relativeURL += "15877.gif";
                break;
            case 2:
                relativeURL += "15868.gif";
                break;
            case 3:
                relativeURL += "15867.gif";
                break;
            case 4:
                relativeURL += "15870.gif";
                break;
            case 5:
                relativeURL += "15869.gif";
                break;
            case 6:
                relativeURL += "15872.gif";
                break;
            case 7:
                relativeURL += "15871.gif";
                break;
            case 8:
                relativeURL += "15874.gif";
                break;
            case 9:
                relativeURL += "15873.gif";
                break;
            case 10:
                relativeURL += "15875.gif";
                break;
        };

        return this.ResolveImageUrl(relativeURL);
    },
    GetTypesUrl: function () {
        return this.ResolveUrl("~/Controls/Dialogs/TypesDlg.aspx");
    },
    GetSignUpAspxDialog: function () {
        return this.ResolveUrl("~/Membership/SignUpDialog.aspx");
    },
    GetLogonAspxDialog: function () {
        return this.ResolveUrl("~/Membership/LogonDialog.aspx");
    },
    GetProductSelectionDialog: function (featureType, linkName, internalSource, callToAction) {
        featureType = featureType || "NotSet";
        callToAction = callToAction || "";

        //ensure uri encoding and avoid double encoding
        featureType = encodeURIComponent(decodeURIComponent(featureType));
        linkName = encodeURIComponent(decodeURIComponent(linkName));
        internalSource = encodeURIComponent(decodeURIComponent(internalSource));

        var qs = "FeatureType=" + featureType + "&p34=" + linkName + "&prop24=" + internalSource;
        if (callToAction != "") {
            qs += "&e3=" + encodeURIComponent(decodeURIComponent(callToAction));
        }
        return this.ResolveUrl("~/Membership/Controls/SKU/ProductSelectionDialog.aspx?" + qs);
    },
    GetAdvancedPrintProductSelectionDialog: function (featureType, printFeature, linkName) {
        featureType = featureType || "NotSet";
        printFeature = printFeature || "NotSet";

        //ensure uri encoding and avoid double encoding
        featureType = encodeURIComponent(decodeURIComponent(featureType));
        printFeature = encodeURIComponent(decodeURIComponent(printFeature));
        linkName = encodeURIComponent(decodeURIComponent(linkName));
        return this.ResolveUrl("~/Membership/Controls/SKU/ProductSelectionDialog.aspx?FeatureType=" + featureType + "&AdvancedPrintFeature=" + printFeature + "&p34=" + linkName);
    },
    GetRateAndReviewLogonDialog: function (itemID, itemType, itemTitle, menuType) {
        return this.ResolveUrl("~/Controls/RateAndReviewDialog/Dialog.aspx"
            + "?id=" + itemID
            + "&itemtype=" + itemType
            + "&title=" + escape(itemTitle)
            + "&menuType=" + menuType);
    },
    GetPhotoByID: function (photoID, size, isUserPhoto) {

        var path = '/global/recipes/';
        if (isUserPhoto)
            path = '/site/allrecipes/area/community/userphoto/';

        return this.ResolveImageUrl(path + size + '/' + photoID + '.jpg');
    },
    GetMyMenusPage: function () {
        return this.ResolveUrl("~/My/Menus/Default.aspx");
    },
    GetMyRecipeBoxPage: function () {
        return this.ResolveUrl("~/My/RecipeBox/Default.aspx");
    },
    GetCanvasUrl: function (menuId) {
        if (menuId != null)
            return this.ResolveUrl("~/My/Menus/Planner.aspx?sharedItemID=" + menuId);
        else
            return this.ResolveUrl("~/My/Menus/Planner.aspx");
    },
    GetRecipeOfTheDayUrl: function () {
        var url = $("a.recipe-of-the-day-link").attr("href");
        return this.ResolveUrl(url);
    },
    GetVideoOfTheDayUrl: function () {
        var url = $("a.video-of-the-day-link").attr("href");
        return url;
    }
};

ioc.Register("_clientUrlProvider").withInstance(AR.ClientUrlProvider);

//
// Utilities\ClientUrlUtils.js
//

/// <reference path="../Intellisense.js" />

AR.ClientUrlUtils = {
    QueryStringParameters: {
        AnalyticsCallToAction: "e3",
        AnalyticsActionItem: "e9",
        AnalyticsInternalSource: "prop24",
        AnalyticsLinkName: "p34",
        AnalyticsCustomLinkClick: "custlnkclk"
    },
    GetQueryStringItemFromAnchor: function (key, anchor) {
        var retVal = null;
        if (anchor != null && anchor.is("a")) {
            retVal = AR.ClientUrlUtils.GetQueryStringItem(key, anchor.attr("href"));
        }
        return retVal;
    },
    GetQueryStringItem: function (key, url) {
        return AR.ClientUrlUtils.GetUrlEncodedKey(key, url);
    },
    RemoveQueryStringItems: function (queryString, paramKeys) { //no ? in return val, example: foo=bar, not ?foo=bar
        queryString = queryString || "";
        paramKeys = paramKeys || "";

        if (queryString.substr(0, 1) == "?") {
            queryString = queryString.substr(1);
        }

        var qsItems = queryString.split("&");
        var qsItem;

        var itemsToKeep = new Array();
        var j = 0;
        for (i = 0; i < qsItems.length; i++) {
            qsItem = qsItems[i].split("=");

            if ($.inArray(qsItem[0], paramKeys) == -1) {
                itemsToKeep[j++] = qsItems[i];
            }
        }

        return ((itemsToKeep.length > 0) ? itemsToKeep.join("&") : "");
    },
    // SetQueryString intially adapted from a Rick Strahl blog post:
    //http://west-wind.com/weblog/posts/884279.aspx
    SetQueryString: function (key, value, url) {
        if (!url) return ""
        if (!key) return url;


        var qryStrPos = url.indexOf("?");
        var baseUrl = (qryStrPos > -1) ? url.substring(0, qryStrPos) : url;
        var q = (qryStrPos > -1) ? url.substring(url.indexOf("?", 0)) : "";

        return baseUrl + AR.ClientUrlUtils.SetUrlEncodedKey(key, value, q);
    },
    GetUrlEncodedKey: function (key, url) {
        if (!url)
            url = window.location.search;

        var re = new RegExp("[?|&]" + key + "=(.*?)&");
        var matches = re.exec(url + "&");
        if (!matches || matches.length < 2)
            return "";
        return decodeURIComponent(matches[1].replace("+", " "));
    },
    SetUrlEncodedKey: function (key, value, qryStr) {
        qryStr = qryStr || "";
        value = value || ""

        var q = qryStr + "&";
        var re = new RegExp("[?|&]" + key + "=.*?&");
        if (!re.test(q))
            q += key + "=" + encodeURI(value);
        else
            q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");

        q = AR.ClientUrlUtils.TrimStart(q, "&");
        q = AR.ClientUrlUtils.TrimEnd(q, "&");


        return (q[0] == "?") ? q : q = "?" + q;
    },
    TrimEnd: function (qryStr, valToTrim) {
        if (valToTrim)
            return qryStr.replace(new RegExp(AR.ClientUrlUtils.EscapeRegExp(valToTrim) + "*$"), '');
        else
            return qryStr.replace(/\s+$/, '');
    },
    TrimStart: function (qryStr, valToTrim) {
        if (valToTrim)
            return qryStr.replace(new RegExp("^" + AR.ClientUrlUtils.EscapeRegExp(valToTrim) + "*"), '');
        else
            return qryStr.replace(/^\s+/, '');
    },
    EscapeRegExp: function (textToEscape) {
        if (textToEscape)
            return textToEscape.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
        else
            return "";
    }
};

//
// Utilities\DialogLauncher.js
//


function DialogLauncher() { 
    this._defaultErrorHandler = function() { };
}

ioc.Register("_dialogLauncher").withConstructor(DialogLauncher)
    .withDependencies("_aspxDialog", "_clientUrlProvider")
    .asSingleton();


// All DialogLauncher take first some parameters for the dialog followed by
// a success and error callback.

// The successcallback is called when the dialog has return values to return to the caller,
// those return values are passed as the first parameter to successCallback.

// errorCallback is called when a dialog fails to load.  If not specified, a default
// implementation is used that sends a generic server error message to NotificationBar.

// If the user cancels out of the dialog, neither successCallback nor errorCallback are
// called.

DialogLauncher.prototype = {

    SetErrorHandler: function (callback) {
        this._defaultErrorHandler = callback;
    },
    AddEditMenuDetails: function (title, descr, notes, attributes, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuAddEditDetails.aspx", {
            _title: title,
            _description: descr,
            _note: notes,
            _attributes: JSON.stringify(attributes)
        }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuDetailsAdd,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MenuDetailsAdd,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    AddEditMealNote: function (mealName, note, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MealAddEditNote.aspx", { _mealName: mealName, _note: note }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.NotesAdd,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MealNoteAdd,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    AddMenu: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuAdd.aspx", null, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MpMenuCreate,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MenuCreate,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    AddMenuItem: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuAddItem.aspx", null, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.NewItemAdd,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.ItemAdd,
                                               AR.Analytics.Action.Item.WriteInMealItem);
    },
    ChangeServings: function (currSrv, origYield, itemName, srvType, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuChangeServings.aspx", { _currSrv: currSrv, _origYield: origYield, _itemName: itemName, _srvType: srvType }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.ChangeServings,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.ChangeServings,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    ChooseShoppingList: function (menuID, defaultName, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/ChooseShoppingList.aspx", { _menuID: menuID, _defaultName: defaultName }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.ShoppingListCreate,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.ShoppingListCreate,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    OpenMenu: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuOpen.aspx", null, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuOpen,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MenuOpen,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    PreviewMenu: function (menu, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuPreview.aspx", { _menu: JSON.stringify(menu) }, successCallback, errorCallback);
        AR.Analytics.RecordLayerOpen(AR.Analytics.Action.LayerName.MenuPreview, AR.Analytics.Action.Item.MenuPersonal);
    },
    PreviewMenuByMenuID: function (menuID, canAddToMenu, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuPreview.aspx", { _menuID: menuID, _canAddToMenu: canAddToMenu }, successCallback, errorCallback);
        //BI call is made server side since we don't know the menu type
    },
    PreviewRecipe: function (itemType, typeSpecificID, canAddToMenu, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/RecipePreview.aspx", { _itemTypeID: itemType, _typeSpecificID: typeSpecificID, _canAddToMenu: canAddToMenu }, successCallback, errorCallback);
        AR.Analytics.RecordLayerOpen(AR.Analytics.Action.LayerName.RecipePreview, 'Recipe');
    },
    RecipeLimitExceeded: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuRecipeLimitExceeded.aspx", { _context: 0 }, successCallback, errorCallback);
    },
    MealLimitExceeded: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuRecipeLimitExceeded.aspx", { _context: 1 }, successCallback, errorCallback);
    },
    RenameMenu: function (currTitle, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuRename.aspx", { _currTitle: currTitle, _type: 1 }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuRename,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MenuRename,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    RenameMeal: function (currTitle, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuRename.aspx", { _currTitle: currTitle, _type: 2 }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MealRename,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MealRename,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    SaveAs: function (currTitle, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuSaveAs.aspx", { _currTitle: currTitle }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuSaveAs,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MenuSaveAs,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    ShareMenu: function (isShared, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuShare.aspx", { _isShared: isShared }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuShare,
                                               AR.Analytics.Event.Start,
                                               (AR.VisitorInfo.IsSupportingMember()) ? AR.Analytics.Action.Source.MPFullMode : AR.Analytics.Action.Source.MPDemoMode,
                                               AR.Analytics.Action.Type.MenuShare,
                                               AR.Analytics.Action.Item.MenuPersonal);
    },
    UnsavedWork: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuUnsavedWork.aspx", null, successCallback, errorCallback);
        AR.Analytics.RecordLayerOpen(AR.Analytics.Action.LayerName.UnsavedWork, '');
    },
    CreateNewMenu: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuCreate.aspx", null, successCallback, errorCallback);
    },
    CreateNewShoppingList: function (suggestedTitle, currentListNames, successCallback, errorCallback) {
        this.Launch("~/My/ShoppingList/Controls/Dialogs/CreateShoppingList.aspx", { _suggestedTitle: suggestedTitle, _currentListNames: currentListNames }, successCallback, errorCallback);
    },
    DeleteMenu: function (savedItemID, menuTitle, actionSource, successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuDelete.aspx", { _savedItemID: savedItemID, _menuTitle: menuTitle }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuDelete,
                                               AR.Analytics.Event.Start,
                                               actionSource,
                                               AR.Analytics.Action.Type.MenuDelete,
                                               AR.Analytics.Action.Item.MenuPersonal);

    },
    MembershipProductSelection: function (featureType, linkName) {
        this.Launch("~/Membership/Controls/SKU/ProductSelectionDialog.aspx?FeatureType=" + featureType + "&p34=" + linkName);
    },
    NewMenuAlertPitch: function (successCallback, errorCallback) {
        this.Launch("~/My/Menus/Controls/Dialogs/MenuAlertEmailPrompt.aspx", null, successCallback, errorCallback);
    },
    AddFolder: function (successCallback, errorCallback) {
        this.Launch("~/My/Controls/Dialogs/FolderAdd.aspx", null, successCallback, errorCallback);
        AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.FolderAdd);
    },
    MailRecipe: function (recipeID, userID, merchDate, sharedItemID, sharedItemType, sharedItemTypeEnumDescription, biSource, biType, isBranded, successCallback, errorCallback) {
        this.Launch("~/Recipe-Tools/Controls/Dialogs/EmailRecipe.aspx", { _recipeID: recipeID, _userID: userID, _merchDate: merchDate, _sharedItemID: sharedItemID, _sharedItemType: sharedItemType }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction((isBranded) ? AR.Analytics.Action.LayerName.EmailRecipeBranded : AR.Analytics.Action.LayerName.EmailRecipe,
                                               AR.Analytics.Event.Start,
                                               biSource,
                                               biType,
                                               sharedItemTypeEnumDescription,
                                               recipeID);
    },
    MailBlogPost: function (blogPostID, successCallback, errorCallback) {
        this.Launch("~/My/Shared/Blogs/Controls/Dialogs/EmailBlogPost.aspx", { _blogPostID: blogPostID }, successCallback, errorCallback);

        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.EmailBlog,
                                               AR.Analytics.Event.Start,
                                               AR.Analytics.Action.Source.BlogPost,
                                               AR.Analytics.Action.Type.EmailBlog,
                                               '');
    },
    MailShoppingList: function (shoppingListID, userID, merchDate, shouldPurgeMerch, successCallback, errorCallback) {
        this.Launch("~/Recipe-Tools/Controls/Dialogs/EmailShoppingList.aspx", { _shoppingListID: shoppingListID, _userID: userID, merchDate: merchDate, _shouldPurgeMerch: shouldPurgeMerch }, successCallback, errorCallback);
        AR.Analytics.RecordLayerOpenAction(AR.Analytics.Action.LayerName.EmailShoppingList,
                                               AR.Analytics.Event.Start,
                                               AR.Analytics.Action.Source.ShoppingList,
                                               AR.Analytics.Action.Type.EmailShoppingList,
                                               '');
    },
    SampleMenuPitch: function (successCallback, errorCallback, menuType) {
        this.Launch("~/Controls/Menus/Dialogs/SampleMenuPitchDlg.aspx", { _menuType: menuType }, successCallback, errorCallback);
    },
    MailVideo: function (videoID, isPartnerVideo, successCallback, errorCallback) {
        this.Launch("~/Recipe-Tools/Controls/Dialogs/EmailVideo.aspx", { _videoID: videoID, _isPartnerVideo: isPartnerVideo }, successCallback, errorCallback);

    },
    Launch: function (url, postData, successCallback, errorCallback) {

        var that = this;

        errorCallback = errorCallback || this._defaultErrorHandler;

        url = this._clientUrlProvider.ResolveUrl(url);
        this._aspxDialog.StartPost(url, postData, successCallback, errorCallback);
    }
};


//
// Utilities\SitePinning.js
//

AR.SitePinning = {
    CreateDynamicJumplists: function () {
        try {
            if (window.external.msIsSiteMode()) {
                window.external.msSiteModeClearJumpList();
                window.external.msSiteModeCreateJumplist("Featured");
                window.external.msSiteModeAddJumpListItem("Recipe of the Day", AR.ClientUrlProvider.GetRecipeOfTheDayUrl(), "favicon.ico");
                window.external.msSiteModeAddJumpListItem("Video of the Day", AR.ClientUrlProvider.GetVideoOfTheDayUrl(), "favicon.ico");
                window.external.msSiteModeShowJumplist();
            };
        } catch (ex) {
        };
    }
};
//
// jQuery\detail-page.js
//
/// <reference path="../Intellisense.js" />

AR.DetailPage = {
    SlideContent: function (hide, show, img, imgPath) {
        img.attr('src', imgPath);
        hide.attr('display', 'block');
        show.attr('display', 'block');
        show.slideDown(400);
        hide.slideUp(200);
    },
    CurrentList: ".review",
    SwitchLists: function (show) {
        if (this.CurrentList == show)
            return;

        var morereviews = $("a.link-more-reviews");
        var morecustom = $("a.link-custom-versions");
        if (show === '.review') {
            morereviews.show();
            morecustom.hide();
        } else if (show === '.custom') {
            morereviews.hide();
            morecustom.show();
        } else {
            morereviews.hide();
            morecustom.hide();
        }

        $(show + "-block").slideDown(400, 'swing');
        $(this.CurrentList + "-block").slideUp(400, 'swing');
        $(this.CurrentList + "-link").removeClass("on");
        this.CurrentList = show;
        $(this.CurrentList + "-link").addClass("on");
    },
    MinusImageURL: 'ar/myar/icons/icon-minus.gif',
    PlusImageURL: 'ar/myar/icons/icon-plus.gif',
    CustomLoaded: false,
    SavedLoaded: false,
    MenusLoaded: false,
    ScrollAndOpenUserSaved: function () {
        if ($(".detailpagemidpagetabs").offset()) {
            var offset = $('.detailpagemidpagetabs').offset().top;
            $('html, body').animate({ scrollTop: offset }, 'slow');
            if (!AR.DetailPage.SavedLoaded) {
                AR.DetailPage.LoadSaved();
            }
            AR.DetailPage.SwitchLists(".saved");
        }
    },
    ScrollAndOpenCustomVersions: function () {
        if ($(".detailpagemidpagetabs").offset()) {
            var offset = $('.detailpagemidpagetabs').offset().top;
            $('html, body').animate({ scrollTop: offset }, 'slow');
            AR.DetailPage.OpenCustomVersions();
        }
    },
    OpenCustomVersions: function() {
        if (!AR.DetailPage.CustomLoaded) {
            AR.DetailPage.LoadCustom();
            AR.DetailPage.SwitchLists(".custom");
            AR.DetailPage.TruncateCustom(300);
        } else {
            AR.DetailPage.SwitchLists(".custom");
        }
    },
    LoadCustomVersionsPage: function() {
        AR.DetailPage.LoadCustom();
        $(".custom-block").show();
        AR.DetailPage.TruncateCustom(450);
    },
    ScrollAndOpenMenus: function () {
        if ($(".detailpagemidpagetabs").offset()) {
            var offset = $('.detailpagemidpagetabs').offset().top;
            $('html, body').animate({ scrollTop: offset }, 'slow');
            if (!AR.DetailPage.MenusLoaded) {
                AR.DetailPage.LoadMenus();
            }
            AR.DetailPage.SwitchLists(".menus");
        }
    },
    LoadMenus: function () {
        var container = $(".menu");
        var menus = AR.ServerSideData.Get("menusData");
        var menuDiv = $(".menus-block");
        var linkClass;
        if (container && menus && menuDiv) {
            jQuery.each(menus, function () {
                var m = container.clone();
                $('#title', m).text(this.title);
                $('#title', m).attr('href', this.detailLink);
                linkClass = (this.isSample) ? "titleLink" : "titleLink linkPrefersSupportingMembershipPitchDialog pitchDialogHintMenuBarricade";
                $('#title', m).attr('class', linkClass);
                $('#description', m).text(this.desc);
                $('.image-link', m).attr('href', this.imageLink);
                linkClass = (this.isSample) ? "image-link" : "image-link linkPrefersSupportingMembershipPitchDialog pitchDialogHintMenuBarricade";
                $('.image-link', m).attr('class', linkClass);
                if (this.img != '') {
                    $('#previewImage', m).attr('src', this.img);
                }
                else {
                    $('#previewImage', m).hide();
                }
                $('#recipeCount', m).text(this.recipeCount);
                $('#mealCount', m).text(this.mealCount);
                if (this.tags != '') {
                    $('#tags', m).text(this.tags);
                }
                if (this.creatorLink != '') {
                    $('#creatorLink', m).text(this.creatorName);
                    $('#creatorLink', m).attr('href', this.creatorLink);
                    $('#creatorName', m).hide();
                }
                else {
                    $('#creatorName', m).text(this.creatorName);
                    $('#creatorLink', m).hide();
                }
                if (this.isSample == false) {
                    $('#isSample', m).hide();
                }
                else {
                    $('#isSample', m).show();
                }

                menuDiv.append(m.html());
            });
        }
        // Need to ensure MembershipDialog links are wired up:
        if (AR.DialogLinker != null) {
            AR.DialogLinker.LinkMembershipDialogs($(".menu"));
        }
        this.MenusLoaded = true;
    },
    LoadCustom: function () {
        var container = $(".customVersion");
        var customs = AR.ServerSideData.Get("customVersions");
        var customDiv = $(".custom-block");
        if (container && customs && customDiv) {
            jQuery.each(customs, function () {
                var c = container.clone();
                if (this.isBP == true) {
                    $('#container', c).removeClass('blinged').addClass('branded');
                    $('#iconSpan', c).hide();
                }
                if (this.img != '') {
                    $('#profileImage', c).attr('src', this.img);
                }
                else {
                    $('#profileImage', c).hide();
                }
                $('#title', c).attr('href', this.detailLink).text(this.title);
                if (this.userLink != '') {
                    $('#profileURL', c).attr('href', this.userLink).text(this.userName);
                    $('#submitterName', c).hide();
                }
                else {
                    $('#profileURL', c).hide();
                    $('#submitterName', c).text(this.userName);
                }

                var tagContainer = $('#customrec-tags', c);

                //show images for each TagID in the array
                if (this.CRTags.length > 0) {
                    var that = this;
                    $.each(this.CRTags, function (index, value) {
                        var toolTip = AR.DetailPage.GetCustomRecipeTagTooltip(value);
                        var cssClass = AR.DetailPage.GetCustomRecipeTagCssClass(value);
                        var image = $('<div>').attr('class', cssClass).attr('title', toolTip).html('&nbsp;');

                        //if it's not the first one, put a seperator div below it
                        if (index != 0) {
                            var div = $('<div>').attr('class', 'tagdivider').html('&nbsp;')
                            tagContainer.prepend(div);
                        }
                        tagContainer.prepend(image);
                    });
                } //if there were no CustomRecipeTags, just don't append the above HTML to the container. no work done.

                if (this.whatChanged != '') {
                    $('#whatChanged', c).text(this.whatChanged);
                } else {
                    $('.customchanges', c).hide();
                }

                $('#description', c).text(this.desc);

                customDiv.append(c.html());
            });
        };
        this.CustomLoaded = true;
    },
    TruncateCustom: function (width) {
        $('.customWhatChanged').textTruncate({ width: width });
    },
    GetCustomRecipeTagCssClass: function (tagID) {
        var ret = "";
        switch (tagID) {
            case 31:
                ret = "spicy";
                break;
            case 32:
                ret = "healthier";
                break;
            case 33:
                ret = "veg";
                break;
            case 34:
                ret = "quick";
                break;
            case 35:
                ret = "budget";
                break;
            case 36:
                ret = "restricted";
                break;
            case 37:
                ret = "kid";
                break;
            case 38:
                ret = "flair";
                break;
        }

        return ret;
    },
    GetCustomRecipeTagTooltip: function (tagID) {
        var ret = "";
        switch (tagID) {
            case 31:
                ret = "Spicier";
                break;
            case 32:
                ret = "Healthier";
                break;
            case 33:
                ret = "Vegetarian / Vegan";
                break;
            case 34:
                ret = "Quick & Easy";
                break;
            case 35:
                ret = "Budget Friendly";
                break;
            case 36:
                ret = "Restricted / Special Diet";
                break;
            case 37:
                ret = "Kid Friendly";
                break;
            case 38:
                ret = "Flair";
                break;
        }

        return ret;
    },
    LoadSaved: function () {
        var container = $(".userWhoSaved");
        var users = AR.ServerSideData.Get("userWhoSaved");
        var customDiv = $(".saved-block");
        if (container && users && customDiv) {
            jQuery.each(users, function () {
                var c = container.clone();

                $('#profileImage', c).attr('src', this.imgUrl);
                if (this.regionName && this.regionName != '') {
                    $('#region', c).attr('href', this.regionUrl).text(this.regionName);
                    $('#country', c).attr('href', this.countryUrl).text(this.countryName);
                }
                else {
                    $('#savedLocation', c).hide();
                }
                if (this.userUrl != '') {
                    $('#profileURL', c).attr('href', this.userUrl).text(this.userName);
                    $('#submitterName', c).hide();
                    $('#prof', c).attr('href', this.userUrl);
                    $('#profText', c).hide();
                    $('#rb', c).attr('href', this.userUrl.replace('Profile.aspx', 'Recipes.aspx'));
                    $('#rbText', c).hide();
                    if (this.reviews == 'true') {
                        $('#review', c).attr('href', this.userUrl.replace('Profile.aspx', 'Reviews.aspx'));
                        $('#revText', c).hide();
                    }
                    else {
                        $('#review', c).hide();
                        $('#revText', c).show();
                    }
                }
                else {
                    $('#profileURL', c).hide();
                    $('#submitterName', c).text(this.userName);
                    $('#rb', c).hide();
                    $('#prof', c).hide();
                    $('#review', c).hide();
                }
                if (this.isBP == true) {
                    $('#container', c).removeClass('blinged').addClass('branded');
                    $('#iconSpan', c).hide();
                    $('#spanReviewContainer', c).hide();
                }
                else if (this.isSupporting == 'false') {
                    $('.author-info', c).removeClass("blinged");
                    $('#iconSpan', c).hide();
                }
                $('#savedOn', c).text(this.saved);

                customDiv.append(c.html());
            });
        };
        this.SavedLoaded = true;
    },
    OnPhotoCountIncrease: function () {
        $('div.recipe-photos').css("display", "block");
        var countSpan = $('span.userphotocount');
        var currentCount = parseInt(countSpan.text());
        if (currentCount != NaN) {
            currentCount = currentCount + 1;
        }
        countSpan.text(currentCount);
        countSpan.next('span').text(currentCount > 1 ? " Photos" : " Photo");
    },
    GetPhotoUploadHandler: function (typeSpecificID, itemType, imageTargetSelector, messageBoxSelector) {

        return function (photoID, previewImage50x50, previewImage140x140) {
            var onSuccess = function () {
                $(imageTargetSelector).attr("src", previewImage140x140);
                AR.DetailPage.OnPhotoCountIncrease();
                AR.PhotoCarousel.ClearCachedData();
                AR.MessageBox.ShowSuccess("Your photo has been saved.", messageBoxSelector);
                AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.RecipeBox, AR.Analytics.Action.Type.RecipeAddPhoto, AR.Analytics.Action.GetItem(itemType));
            };

            var onFailure = function () {
                AR.MessageBox.ShowFailure("There was a problem uploading your photo.", messageBoxSelector);
            };

            if (itemType != AR.ItemType.Recipe) {
                AR.ClientService.AddPhotoToSharedItem(typeSpecificID, photoID,
                    function (response) {
                        if (response.ResponseCode == AR.ResponseCode.Success)
                            onSuccess();
                        else
                            onFailure();
                    });
            }
            else {
                onSuccess();
            }
        };
    }
};

AR.DetailPage.MenuDetails = {
    OnInit: function () {
        if (AR.IsMobileDevice()) {           
            this.WireUpMobileEvents();
        }
    },
    WireUpMobileEvents: function () {
        $('.recipe').removeClass("use_hover");
        $('.recipe').click(function (event) {
            if (!$(this).is(".has_hover")) {
                $('.recipe').removeClass("has_hover");
                $('.recipe').find('.MenusrecipeCTA').hide();

                $(this).addClass("has_hover");
                $(this).find('.MenusrecipeCTA').show();
            }
            else {
                $(this).removeClass("has_hover");
                $(this).find('.MenusrecipeCTA').hide();
            }
        });
    },
    ToggleContent: function (content, trigger) {
        if (content.is(':hidden')) {
            content.slideDown(400);
            trigger.html('Hide Details');
        }
        else {
            content.slideUp(200);
            trigger.html('See Details &#187;');
        }
    },
    ToggleNutritionContent: function (content, trigger, tagSpan) {
        if (content.is(':hidden')) {
            AR.Analytics.RecordCustomLinkClick(AR.Analytics.Action.CustomLinkClick.MenuNutritionExpand);
            AR.DetailPage.MenuDetails.ToggleContent(content, trigger);
        }
        else {
            AR.Analytics.RecordCustomLinkClick(AR.Analytics.Action.CustomLinkClick.MenuNutritionCollapse);
            AR.DetailPage.MenuDetails.ToggleContent(content, trigger);
        }
        if (tagSpan) {
            if (tagSpan.is(':hidden')) { tagSpan.show(); } else { tagSpan.hide(); }
        }
    },
    SetNutritionDetailsOnClick: function (mealID) {
        var triggerLink = $('.menudetail-nutrition-trigger' + mealID);
        var contentDiv = $('.menudetail-nutrition-content' + mealID);
        var tagSpan = $('.menudetail-nutrition-powered-by-tag' + mealID);
        triggerLink.click(function (e) {
            e.preventDefault();
            AR.DetailPage.MenuDetails.ToggleNutritionContent(contentDiv, triggerLink, tagSpan);
        });
    }

};

AR.DetailPage.RecipeTools = {
    IsRecipe: function () { return AR.ServerSideData.Data.IsRecipe },
    IsMenu: function () { return AR.ServerSideData.Data.IsMenu },
    IsWebLink: function () { return AR.ServerSideData.Data.IsWebLink },
    IsWebReference: function () { return AR.ServerSideData.Data.IsWebReference },
    Slide: function (li, link, parent, useBordbot) {
        if (li.is(':hidden')) {
            $('img', link).attr('src', AR.ImageServer + AR.DetailPage.MinusImageURL);
            var source = 'none';
            if (link.hasClass("menu")) {
                source = link.hasClass("RTSL") ? AR.Analytics.Action.CustomLinkClick.MenuDetailActSLExpand : 'none'; //RTMN???
            }
            if (link.hasClass("recipe")) {
                source = link.hasClass("RTSL") ? AR.Analytics.Action.CustomLinkClick.RecipeDetailSLExpand : 'none'; //RTSE??
            }
            if (source != 'none') {
                AR.Analytics.RecordCustomLinkClick(source);
            }
            if (useBordbot) { $(parent).removeClass('bordbot'); }
            li.slideDown(300);
        }
        else {
            $('img', link).attr('src', AR.ImageServer + AR.DetailPage.PlusImageURL);
            var source = 'none';
            if (link.hasClass("menu")) {
                source = link.hasClass("RTSL") ? AR.Analytics.Action.CustomLinkClick.MenuDetailActSLCollapse : 'none'; //RTMN???
            }
            if (link.hasClass("recipe")) {
                source = link.hasClass("RTSL") ? AR.Analytics.Action.CustomLinkClick.RecipeDetailSLCollapse : 'none'; //RTSE??
            }
            if (source != 'none') {
                AR.Analytics.RecordCustomLinkClick(source);
            }
            li.slideUp(300, function () {
                if (useBordbot) { $(parent).addClass('bordbot'); }
            });
        }
    },
    AddToRB: function (folder) {
        if (AR.VisitorInfo.IsLoggedIn()) {
            AR.Analytics.RecordAction(AR.Analytics.Event.Start, AR.Analytics.Action.Source.RecipePage, AR.Analytics.Action.Type.RecipeBoxAdd, AR.Analytics.Action.GetItem(AR.ServerSideData.Data.ItemType));
            var folderID = (folder) ? folder.toString() : '0';
            AR.ClientService.SaveToRecipeBox(AR.TypeSpecificID.toString(), this.IsRecipe(), this.IsMenu(), folderID,
                function (response) {
                    if (response.ResponseCode == AR.ResponseCode.Success) {
                        AR.MessageBox.ShowSuccess(response.Message, '#msgLabel');
                        AR.RBM.Add($('#itemTitle').text(), document.URL, AR.ServerSideData.Get('Item_RateAndReview_Rating'));
                        AR.Loader.Hide();
                        AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.RecipePage, AR.Analytics.Action.Type.RecipeBoxAdd, AR.Analytics.Action.GetItem(AR.ServerSideData.Data.ItemType));
                    }
                    else {
                        AR.MessageBox.ShowFailure(response.Message, '#msgLabel');

                        if (AR.ShouldLogResponseCode(response.ResponseCode)) {
                            AR.LogErrorEx({
                                IsRecipe: AR.LogEval("AR.DetailPage.RecipeTools.IsRecipe()"),
                                FolderID: folderID
                            }, 'detail-page.js', 'Error adding item to RecipeBox.');
                        }
                    }


                    // if it was the inner add button...
                    if (folder) {
                        //close the expanded toolbox
                        $('a.RTRB').trigger('click');
                    }
                });
        }
    },
    AddToMyMenus: function () {
        if (AR.VisitorInfo.IsLoggedIn()) {
            AR.Analytics.RecordCustomLinkClick(AR.Analytics.Action.CustomLinkClick.MenuDetailMenuAdd);
            AR.ClientService.SaveToRecipeBox(AR.TypeSpecificID.toString(), this.IsRecipe(), this.IsMenu(), 0,
                function (response) {
                    if (response.ResponseCode == AR.ResponseCode.Success) {
                        AR.MessageBox.ShowSuccess(response.Message, '#msgLabel');
                        AR.RBM.AddMenu($('.menuDetailTitle').text(), document.URL);
                        AR.Loader.Hide();
                        AR.Analytics.RecordAction(AR.Analytics.Event.Complete, AR.Analytics.Action.Source.MenuDetail, AR.Analytics.Action.Type.MyMenuAdd, AR.ServerSideData.Get('sharedItemType'));
                    }
                    else {
                        AR.MessageBox.ShowFailure(response.Message, '#msgLabel');

                        if (AR.ShouldLogResponseCode(response.ResponseCode)) {
                            AR.LogErrorEx({
                                IsMenu: AR.LogEval("AR.DetailPage.RecipeTools.IsMenu()"),
                                FolderID: 0
                            }, 'detail-page.js', 'Error adding menu to MY Menus from menu detail page.');
                        }
                    }
                });
        }
    },
    AddItemToMenu: function (sharedItemID, createNewMenu) {
        var an = AR.Analytics;
        if (AR.VisitorInfo.IsLoggedIn()) {
//            if (!createNewMenu) {
//                var link = (AR.DetailPage.RecipeTools.IsRecipe()) ? an.Action.CustomLinkClick.MenuAddRecipe : (AR.DetailPage.RecipeTools.IsWebLink()) ? an.Action.CustomLinkClick.MenuAddWebLink : an.Action.CustomLinkClick.MenuAddWebReference;
//                an.RecordCustomLinkClick(link);
//            }
            if (!AR.RBM.MenuExists(sharedItemID)) {
                AR.RBM.IncrementMenuCount();
            }
            var servingValue = ($('.servings-amount').val() && ($('.servings-amount').val() != $('.yield').text().toString().toLowerCase().replace(' servings', ''))) ? $('.servings-amount').val() : -1;
            AR.ClientService.AddItemToMenu(AR.VisitorInfo._data._ID.toString(), sharedItemID, AR.TypeSpecificID.toString(), AR.ServerSideData.Data.ItemType, servingValue,
                function (response) {
                    if (response.ResponseCode == AR.ResponseCode.Success) {
                        AR.MessageBox.ShowSuccess(response.Message, '#msgLabel');
                        AR.RBM.AddToMenu(response.Data);
                        AR.Loader.Hide();
                        var source = (AR.DetailPage.RecipeTools.IsMenu()) ? an.Action.Source.MenuDetail : (AR.DetailPage.RecipeTools.IsRecipe()) ? an.Action.Source.RecipePage : (AR.DetailPage.RecipeTools.IsWebLink()) ? an.Action.Source.WeblinkPage : an.Action.Source.ReferencePage;
                        an.RecordAction(AR.Analytics.Event.Complete, source, an.Action.Type.MenuAdd, AR.ServerSideData.Get('sharedItemType'));
                    }
                    else {
                        AR.MessageBox.ShowFailure(response.Message, '#msgLabel');

                        if (AR.ShouldLogResponseCode(response.ResponseCode)) {
                            AR.LogErrorEx({
                                IsMenu: AR.LogEval("AR.DetailPage.RecipeTools.IsMenu()"),
                                FolderID: 0
                            }, 'detail-page.js', 'Error adding item to menu from ' + window.location.pathname);
                        }
                    }
                });
            if (!($(".menu-box-form").is(':hidden'))) {
                //close the expanded toolbox
                $('a.RTMN').trigger('click');
            }
        }
    },
    AddToList: function (analyticsLoggingInProgress) {
        if (AR.VisitorInfo.IsLoggedIn()) {
            if (analyticsLoggingInProgress == 'false') {
                var source = (AR.DetailPage.RecipeTools.IsMenu()) ? AR.Analytics.Action.Source.MenuDetail : AR.Analytics.Action.Source.RecipePage;
                var type = (AR.DetailPage.RecipeTools.IsMenu()) ? AR.Analytics.Action.Type.ShoppingListAddMenu : AR.Analytics.Action.Type.ShoppingListAddRecipe;
                var actionItem = (AR.DetailPage.RecipeTools.IsMenu()) ? AR.ServerSideData.Get("sharedItemType") : AR.Analytics.Action.GetItem(AR.ServerSideData.Data.ItemType);
                if (AR.DetailPage.RecipeTools.IsMenu()) {
                    AR.Analytics.RecordCustomLinkClick(AR.Analytics.Action.CustomLinkClick.ShoppingListAddMenu);
                }
                //AR.Analytics.RecordAction(AR.Analytics.Event.Start, source, type, actionItem);
            }
            var list = $('.shopping-list option:selected');
            var servings = $('.servings-amount').val();

            AR.ClientService.AddToShoppingList(list.val(), AR.ServerSideData.Data.IsRecipe, AR.ServerSideData.Data.IsMenu, AR.TypeSpecificID.toString(), (servings) ? servings : 0, function (response) {
                if (response.ResponseCode == AR.ResponseCode.Success) {
                    AR.MessageBox.ShowSuccess(response.Message, '#msgLabel');
                    if (analyticsLoggingInProgress == 'false') {
                        AR.Analytics.RecordAction(AR.Analytics.Event.Complete, source, type, actionItem);
                    }
                    AR.RBM.AddToList(list.val(), list.text());
                    AR.Loader.Hide();
                }
                else {
                    AR.MessageBox.ShowFailure(response.Message, '#msgLabel');

                    if (AR.ShouldLogResponseCode(response.ResponseCode)) {
                        AR.LogErrorEx({
                            IsRecipe: AR.LogEval("AR.DetailPage.RecipeTools.IsRecipe()"),
                            Servings: servings,
                            ShoppingListID: AR.LogEval("$('.shopping-list').val()")
                        }, 'AddToList', 'Error adding item to Shopping List.');
                    }
                    AR.Loader.Hide();
                }
                // if it was the inner add button...
                if (list && !($(".shopping-list-form").is(':hidden'))) {
                    //close the expanded toolbox
                    AR.DetailPage.RecipeTools.Slide($('.shopping-list-form'), $('a.RTSL'), '#liAddToSL', true);
                }
            });
        }
    }
};


AR.DetailPage.Servings = {
    MinServings: 1,
    MaxServings: 300,
    ServingsWarningMsg: 'You must enter a number between 1 and 300.',
    ValidateServings: function() {
        var reg_isinteger = /^\d+$/; // matches strings with 1 or more digits only
        var servings = $('.servings-amount').val();
        if (!reg_isinteger.test(servings)) {
            return false;
        } else {
            return (servings >= this.MinServings && servings <= this.MaxServings);
        }      
    }
};

$(document).ready(function () {
    $("a.nutritional-information").click(function (e) {
        e.preventDefault();
        if ($("#nutri-info").is(":hidden")) {
            AR.DetailPage.SlideContent($("p.nutritional-information"), $("#nutri-info"), $('img.nutritional-information'), AR.ImageServer + AR.DetailPage.MinusImageURL);
        }
        else {
            AR.DetailPage.SlideContent($("#nutri-info"), $("p.nutritional-information"), $('img.nutritional-information'), AR.ImageServer + AR.DetailPage.PlusImageURL);
        }
    });
    $(".listItemReview").click(function (e) {

        e.preventDefault();

        if ($(".listItemReviewFull", $(this).parent().parent()).is(":hidden")) {
            AR.DetailPage.SlideContent($(".listItemReviewMini", $(this).parent().parent()), $(".listItemReviewFull", $(this).parent().parent()), $('.listItemReviewImage', $(this)), AR.ImageServer + AR.DetailPage.MinusImageURL);
            $('.listItemReviewImage', $(this)).attr("alt", "show less");
            $('.listItemReviewImage', $(this)).attr("title", "show less");
        }
        else {
            AR.DetailPage.SlideContent($(".listItemReviewFull", $(this).parent().parent()), $(".listItemReviewMini", $(this).parent().parent()), $('.listItemReviewImage', $(this)), AR.ImageServer + AR.DetailPage.PlusImageURL);
            $('.listItemReviewImage', $(this)).attr("alt", "view full review");
            $('.listItemReviewImage', $(this)).attr("title", "view full review");
        }
    });
    $(".review-link").click(function (e) {
        e.preventDefault();
        AR.DetailPage.SwitchLists(".review");
    });
    $(".custom-link").click(function (e) {
        e.preventDefault();
        AR.DetailPage.OpenCustomVersions();
    });
    $(".menus-link").click(function (e) {
        e.preventDefault();
        if (!AR.DetailPage.MenusLoaded) {
            AR.DetailPage.LoadMenus();
        }
        AR.DetailPage.SwitchLists(".menus");
    });
    $(".saved-link").click(function (e) {
        e.preventDefault();
        if (!AR.DetailPage.SavedLoaded) {
            AR.DetailPage.LoadSaved();
        }
        AR.DetailPage.SwitchLists(".saved");
    });

    var featureHintFromItemType = AR.DetailPage.RecipeTools.IsWebLink() ? 'featureHintWeblinkAddToMenu' : AR.DetailPage.RecipeTools.IsWebReference() ? 'featureHintReferenceAddToMenu' : 'featureHintRecipeAddToMenu';
    $("a.RTMN").addClass(featureHintFromItemType);
    $('.userSaved').click(function (e) { e.preventDefault(); AR.DetailPage.ScrollAndOpenUserSaved(); });
    //$('.customVersions').click(function (e) { e.preventDefault(); AR.DetailPage.ScrollAndOpenCustomVersions(); });
    $('.menu').click(function (e) { e.preventDefault(); AR.DetailPage.ScrollAndOpenMenus(); });
    $("a.RTRB").click(function (e) { e.preventDefault(); AR.DetailPage.RecipeTools.Slide($('.recipe-box-form'), $('a.RTRB'), '#liAddToRB', true); });
    $("a.RTSL").click(function (e) { e.preventDefault(); AR.DetailPage.RecipeTools.Slide($('.shopping-list-form'), $('a.RTSL'), '#liAddToSL', true); });
    $("a.RTSE").click(function (e) { e.preventDefault(); AR.DetailPage.RecipeTools.Slide($('.share-email-form'), $('a.RTSE'), '#liEmail', false); });
    $("a.RTMN").click(function (e) {
        e.preventDefault();
        if ($('.menu-box-form').is(':hidden')) {
            var BI = AR.Analytics;
            var itemType = AR.ServerSideData.Get("sharedItemType");
            var source = (AR.DetailPage.RecipeTools.IsMenu()) ? BI.Action.Source.MenuDetail : (AR.DetailPage.RecipeTools.IsWebLink()) ? BI.Action.Source.WeblinkPage : (AR.DetailPage.RecipeTools.IsWebReference()) ? BI.Action.Source.ReferencePage : BI.Action.Source.RecipePage;
            BI.RecordAction(BI.Event.Start, source, BI.Action.Type.MenuAdd, itemType);
        }
        AR.DetailPage.RecipeTools.Slide($('.menu-box-form'), $('a.RTMN'), '#liAddToMyMenu', true);
    });
    $("a.share-email").click(function (e) { e.preventDefault(); AR.DetailPage.RecipeTools.Slide($('.share-email-form'), $('a.RTSE'), '#liEmail', false); });
    $('#addToRB').click(function () { AR.DetailPage.RecipeTools.AddToRB(); });
    $('.add-item-to-default-shopping-list').click(function () { AR.DetailPage.RecipeTools.AddToList('false'); });
    $(".toolbox-add-to-my-menu").click(function (e) { e.preventDefault(); AR.DetailPage.RecipeTools.AddToMyMenus(); });
    $('.menu-add-item-button').click(function (e) { e.preventDefault(); AR.DetailPage.RecipeTools.AddItemToMenu($('.ddlSelectedMenuItem').val(), false); });
    $('.add-item-to-recipe-box').click(function () { AR.DetailPage.RecipeTools.AddToRB($('.fold-list').val()); });
    $('.add-item-to-shopping-list').click(function () { AR.DetailPage.RecipeTools.AddToList('false'); });

    $("a.RT-recipe-send-to-a-friend").click(function (e) {
        e.preventDefault();
        var BI = AR.Analytics;
        var data = $("a.RT-recipe-send-to-a-friend");
        var isBrandedEmail = data.attr("data-recipe-detail-brandedemail");
        var itemType = (data.attr("data-recipe-detail-shared-item-type")) ? data.attr("data-recipe-detail-shared-item-type") : '';
        var recipeID = (data.attr("data-recipe-detail-recipe-id")) ? data.attr("data-recipe-detail-recipe-id") : '0';
        var merchDate = (data.attr("data-recipe-detail-merchdate")) ? data.attr("data-recipe-detail-merchdate") : '';
        var biSource = (AR.DetailPage.RecipeTools.IsWebLink()) ? BI.Action.Source.WeblinkPage : (AR.DetailPage.RecipeTools.IsWebReference()) ? BI.Action.Source.ReferencePage : BI.Action.Source.RecipePage;
        var biType = (AR.DetailPage.RecipeTools.IsWebLink()) ? BI.Action.Type.EmailWeblink : (AR.DetailPage.RecipeTools.IsWebReference()) ? BI.Action.Type.EmailReference : (isBrandedEmail) ? BI.Action.Type.EmailRecipeBranded : BI.Action.Type.EmailRecipe;
        var resultMsgSelector = (itemType == "Recipe") ? null : "#msgLabel";
        if (isBrandedEmail) {
            // additional BI for partnertoolbox
            AR.Analytics.RecordActionOption(AR.TypeSpecificID, BI.Action.Type.EmailRecipeBranded);
        }
        ioc.Load("_dialogLauncher").MailRecipe(recipeID, AR.VisitorInfo.VisitorID(), merchDate, AR.TypeSpecificID, itemType, AR.ServerSideData.Get("sharedItemType"), biSource, biType, isBrandedEmail,
            function (result) {
                if (result) {
                    BI.RecordAction(BI.Event.Complete, biSource, biType, AR.ServerSideData.Get("sharedItemType"), recipeID);
                    if (result !== true) { // if result is a non-empty string, it is true in "if(result)" but "result !== true" will be false because of the differing types
                        window.location.href = result;
                    }
                    AR.MessageBox.ShowSuccess("Recipe successfully emailed.", resultMsgSelector, false);
                }
                else {
                    AR.MessageBox.ShowFailure("An unexpected error occured while attempting to email this recipe.", resultMsgSelector, false);
                }
            },
             function () {
                 AR.MessageBox.ShowFailure("An unexpected error occured while attempting to email this recipe.", resultMsgSelector, false);
             });
    });

    $("a.emailVid").click(function (e) {
        e.preventDefault();
        var videoResultMessage = $('#msgClientPage');
        var data = $("a.emailVid");
        var isPartnerVideo = (data.attr("data-video-detail-isPartnerVideo")) ? data.attr("data-video-detail-isPartnerVideo") : "false";
        ioc.Load("_dialogLauncher").MailVideo(AR.TypeSpecificID, isPartnerVideo,
            function (result) {
                if (result) {
                    AR.MessageBox.ShowSuccess("Video successfully emailed.", videoResultMessage, false);
                }
                else {
                    AR.MessageBox.ShowFailure("An unexpected error occured while attempting to email this video.", videoResultMessage, false);
                }
            },
            function () {
                AR.MessageBox.ShowFailure("An unexpected error occured while attempting to email this video.", videoResultMessage, false);
            });
    });

    $('.create-shopping-list-from-detail-page').click(function (e) {
        var BI = AR.Analytics;
        var itemType = AR.ServerSideData.Get("sharedItemType");
        var source = (AR.DetailPage.RecipeTools.IsMenu()) ? BI.Action.Source.MenuDetail : (AR.DetailPage.RecipeTools.IsRecipe()) ? BI.Action.Source.RecipePage : (AR.DetailPage.RecipeTools.IsWebLink()) ? BI.Action.Source.WeblinkPage : BI.Action.Source.ReferencePage;
        BI.RecordLayerOpenAction(BI.Action.LayerName.ShoppingListCreate, BI.Event.Start, source, BI.Action.Type.ShoppingListCreate, itemType);
        ioc.Load("_dialogLauncher").CreateNewShoppingList(
             AR.ServerSideData.Get("currentItemTitle"),
             AR.ServerSideData.Get("currentShoppingListTitles"),
             function (result) {
                 BI.RecordAction(AR.Analytics.Event.Complete, source, BI.Action.Type.ShoppingListCreate, itemType);
                 // insert return value into SL DDL
                 $('.ddlSelectedShoppingListItem').append(
                    $('<option></option>').val(result.substring(result.indexOf("|^|") + 3)).html(result.substring(0, result.indexOf("|^|"))).attr("selected", "selected")
                 );
                 AR.DetailPage.RecipeTools.AddToList(result.substring(result.indexOf("|^|") + 3), false);
                 // if it was the inner add button...
                 if (!($(".shopping-list-form").is(':hidden'))) {
                     //close the expanded toolbox
                     AR.DetailPage.RecipeTools.Slide($('.shopping-list-form'), $('a.RTSL'), '#liAddToSL', true);
                 }
                 //   AR.RBM.AddToList(list.val(), list.text(), $('#itemTitle').text(), document.URL); ; // RBM animation stuff
                 AR.Loader.Hide();
             },
             function () {
                 AR.MessageBox.ShowFailure("Sorry, your new shopping list could not be created.", null, false);
                 AR.Loader.Hide();
             });
    });
    $('.create-new-menu').click(function (e) {
        var an = AR.Analytics;
        var source = (AR.DetailPage.RecipeTools.IsMenu()) ? an.Action.Source.MenuDetail : (AR.DetailPage.RecipeTools.IsWebLink()) ? an.Action.Source.WeblinkPage : (AR.DetailPage.RecipeTools.IsWebReference()) ? an.Action.Source.ReferencePage : an.Action.Source.RecipePage;
        an.RecordLayerOpenAction(AR.Analytics.Action.LayerName.MenuCreate, AR.Analytics.Event.Start, source, an.Action.Type.MenuCreate, an.Action.Item.MenuPersonal);
        ioc.Load("_dialogLauncher").CreateNewMenu(
             function (result) {
                 an.RecordAction(AR.Analytics.Event.Complete, source, an.Action.Type.MenuCreate, an.Action.Item.MenuPersonal);
                 AR.DetailPage.RecipeTools.AddItemToMenu(result.substring(result.indexOf(",") + 1), true);
                 // insert return value into Menu DDL
                 $('.ddlSelectedMenuItem').append(
                    $('<option></option>').val(result.substring(result.indexOf(",") + 1)).html(result.substring(0, result.indexOf(",")))
                );
             },
             function () {
                 AR.MessageBox.ShowFailure("Sorry, but your new menu could not be created.", null, false);
             });
    });
    $('.calculate-servings').click(function (event) {
        if (!AR.DetailPage.Servings.ValidateServings()) {
            event.preventDefault();
            $(".servings-amount").focus();
            AR.MessageBox.ShowWarning(AR.DetailPage.Servings.ServingsWarningMsg, null, false);
        }
    });

    $(".servings-amount").keydown(function (e) {
        if (e.which == 13) {  // on enter          
            if (!AR.DetailPage.Servings.ValidateServings()) {
                e.preventDefault();
                e.stopPropagation();
                $(".servings-amount").focus();
                AR.MessageBox.ShowWarning(AR.DetailPage.Servings.ServingsWarningMsg, null, false);
            }
            else { //do submit
                var lnkbtn = $(".calculate-servings");
                var href = lnkbtn.attr("href");

                //unfortunately, linkbuttons store the javascript in their href attribute
                if (typeof (href) != "undefined" && href.substr(0, 11) == "javascript:") {
                    new Function(href.substr(11)).call(lnkbtn.eq(0));
                }
            }
        }
    }),
    $('.servings-amount').val($('.servings-hdnservings').val()); //back button fix - restore values from hdn fields

    $('.menudetail-sl-info').click(function (event) {
        event.preventDefault();
        var val = $('.menudetail-sl-content').is(':hidden') ? AR.Analytics.Action.CustomLinkClick.MenuDetailSLExpand : AR.Analytics.Action.CustomLinkClick.MenuDetailSLCollapse;
        AR.Analytics.RecordCustomLinkClick(val);
        AR.DetailPage.MenuDetails.ToggleContent($('.menudetail-sl-content'), $('.menudetail-sl-info'));
    });


});
//=========================================================================
AR.PhotoCarousel = {
    Config: {
        PageSize: 10,
        MessageBoxSelector: "#msgLabel",
        ErrorLoadingMessage: "Sorry, there was an error loading the current photo."
    },
    Data: {
        ItemID: 0,
        IsRecipe: false,
        CurrentPhotoIndex: 0,
        TotalRecords: 0,
        Photos: {}
    },
    GetCurrentPageNumber: function () {
        return this.GetPageNumber(AR.PhotoCarousel.Data.CurrentPhotoIndex);
    },
    GetIsCurrentPage: function (pageNumber) {
        return (pageNumber == this.GetCurrentPageNumber());
    },
    GetPreviousPhotoIndex: function () {
        return (AR.PhotoCarousel.Data.CurrentPhotoIndex == 0)
           ? (AR.PhotoCarousel.Data.TotalRecords - 1)
           : (AR.PhotoCarousel.Data.CurrentPhotoIndex - 1);
    },
    GetNextPhotoIndex: function () {
        return (AR.PhotoCarousel.Data.CurrentPhotoIndex == (AR.PhotoCarousel.Data.TotalRecords - 1))
            ? 0
            : (AR.PhotoCarousel.Data.CurrentPhotoIndex + 1);
    },
    GetPageNumber: function (photoIndex) {
        return Math.ceil((photoIndex + 1) / AR.PhotoCarousel.Config.PageSize);
    },
    LoadLayer: function () {
        var photoIndex = AR.PhotoCarousel.Data.CurrentPhotoIndex;

        if (AR.PhotoCarousel.Data.Photos[photoIndex]) {
            AR.PhotoCarousel.SetContent(AR.PhotoCarousel.Data.Photos[photoIndex]);
        }
        else {
            //Get page data, which will cause the layer to be loaded.
            AR.PhotoCarousel.GetDataFromService(this.GetCurrentPageNumber());
        }

        AR.PhotoCarousel.PreLoadIndexData(this.GetNextPhotoIndex());
        AR.PhotoCarousel.PreLoadIndexData(this.GetPreviousPhotoIndex());
    },
    SetLinkOrSpan: function (spanSelector, linkSelector, text, url) {
        if (url) {
            $(spanSelector).hide();
            $(linkSelector).show().attr("href", AR.ClientUrlProvider.ResolveUrl(url)).text(text);
        }
        else {
            $(spanSelector).show().text(text);
            $(linkSelector).hide();
        }
    },
    SetContent: function (photo) {
        if (photo) {
            //Paging
            if (AR.PhotoCarousel.Data.TotalRecords > 1) {
                $("#spnPageNumber").text(AR.PhotoCarousel.Data.CurrentPhotoIndex + 1);
                $("#spnPageCount").text(AR.PhotoCarousel.Data.TotalRecords);
                $(".photo-scroll-buttons").show();

                $("#jqViewAllDiv").show();
                $("#jqViewAllLink").attr("href", AR.PhotoCarousel.Data.PhotoGalleryUrl);
            } else {
                $(".photo-scroll-buttons").hide();
                $("#jqViewAllDiv").hide();
            }

            var cookBaseUrl = (photo.User.CustomUrlPiece)
                ? AR.ClientUrlProvider.ResolveUrl("~/Cook/" + photo.User.CustomUrlPiece)
                : AR.ClientUrlProvider.ResolveUrl("~/Cook/" + photo.User.ObfuscatedUserID);

            var thumbnailUrl = photo.User.ProfileImageUrl.replace("/userphoto/small/", "/userphoto/mini/");

            //Main Content
            $("#jqPhotoTitleSpan").text(photo.Title);

            if (photo.Caption.toLowerCase() == photo.Title.toLowerCase()) {
                $("#jqPhotoCaptionSpan").hide();
            } else {
                $("#jqPhotoCaptionSpan").show();
            }
            $("#jqPhotoCaptionSpan").text(photo.Caption);
            $("#jqPhotoDateSpan").text(photo.Date);
            $("#jqPhotographerDisplayName").text(photo.User.DisplayName);

            if (photo.User.HasHomePage) {
                $("#jqPhotographerProfileSpan").hide();
                $("#jqPhotographerProfileLink").show().attr("href", cookBaseUrl);
            } else {
                $("#jqPhotographerProfileSpan").show();
                $("#jqPhotographerProfileLink").hide();
            }

            if (photo.User.ProfileImageUrl == "") {
                $("#jqPhotographerThumbnailImage").hide();
            }
            else {
                $("#jqPhotographerThumbnailImage").show().attr("src", AR.ClientUrlProvider.ResolveImageUrl(thumbnailUrl));
            }
            $("#jqPhotographerBadgeDiv").removeClass("blinged");
            $("#jqPhotographerStarLink").hide();
            if (photo.User.IsSupporting) {
                $("#jqPhotographerBadgeDiv").addClass("blinged");
                $("#jqPhotographerStarLink").show().attr("href", AR.ClientUrlProvider.ResolveUrl("~/SupportingMembership/Info.aspx?ect=21"));
            }

            $("#jqPhotographerProfileLink").attr("href", cookBaseUrl + "/Profile.aspx");
            if (photo.User.RecipeCount > 0) {
                $("#jqPhotographerNoRecipesSpan").hide();
                $("#jqPhotographerRecipesLink").show().attr("href", cookBaseUrl + "/Recipes.aspx");
            }
            else {
                $("#jqPhotographerRecipesLink").hide();
                $("#jqPhotographerNoRecipesSpan").show();
            }
            $("#jqPhotographerPhotosLink").attr("href", cookBaseUrl + "/Photos.aspx");

            if (photo.User.HomeTown) {
                $(".home-town-modal").show();
                AR.PhotoCarousel.SetLinkOrSpan("#jqPhotographerHomeTownCitySpan", "#jqPhotographerHomeTownCityLink",
                        photo.User.HomeTown.City.Text, photo.User.HomeTown.City.URI);
                AR.PhotoCarousel.SetLinkOrSpan("#jqPhotographerHomeTownStateSpan", "#jqPhotographerHomeTownStateLink",
                    photo.User.HomeTown.State.Text, photo.User.HomeTown.State.URI);
                AR.PhotoCarousel.SetLinkOrSpan("#jqPhotographerHomeTownCountrySpan", "#jqPhotographerHomeTownCountryLink",
                    photo.User.HomeTown.Country.Text, photo.User.HomeTown.Country.URI);
            }
            else {
                $(".home-town-modal").hide();
            }

            if (photo.User.LivingIn) {
                $(".living-in-modal").show();
                AR.PhotoCarousel.SetLinkOrSpan("#jqPhotographerLivingInCitySpan", "#jqPhotographerLivingInCityLink",
                        photo.User.LivingIn.City.Text, photo.User.LivingIn.City.URI);
                AR.PhotoCarousel.SetLinkOrSpan("#jqPhotographerLivingInStateSpan", "#jqPhotographerLivingInStateLink",
                    photo.User.LivingIn.State.Text, photo.User.LivingIn.State.URI);
                AR.PhotoCarousel.SetLinkOrSpan("#jqPhotographerLivingInCountrySpan", "#jqPhotographerLivingInCountryLink",
                    photo.User.LivingIn.Country.Text, photo.User.LivingIn.Country.URI);
            }
            else {
                $(".living-in-modal").hide();
            }

            //robr: tweak view for Branded Profile
            if (photo.User.IsBrandedProfile) {
                $("#jqPhotoLinks").hide();
                $("#jqCookingLevel").hide();
                $("#jqLivingIn").hide();
                $("jqPhotographerStarLink").hide();
                $("#jqSupportingMemberIconSpan").hide();
                $("#jqHomeTownLabel").text("Headquarters:");
                $("#jqPhotographerLabel").text("Photo By:");
                if (photo.User.IsSupporting) $("#jqPhotographerBadgeDiv").removeClass("blinged");
                $("#jqPhotographerBadgeDiv").addClass("branded");
            }
            else {
                $("#jqPhotographerBadgeDiv").removeClass("branded");
            }

            AR.PhotoCarousel.PreLoadImage(photo);
            AR.PhotoCarousel.PreLoadImage(AR.PhotoCarousel.Data.Photos[AR.PhotoCarousel.GetNextPhotoIndex()]);
            AR.PhotoCarousel.PreLoadImage(AR.PhotoCarousel.Data.Photos[AR.PhotoCarousel.GetPreviousPhotoIndex()]);

            var pos = AR.PhotoCarousel.Data.CurrentPhotoIndex + 1;

            $("#jqAdIframe").attr("src", AR.AdData.GenerateIFrameURL(pos, "300x250", "photo")); // AR.ClientUrlProvider.ResolveUrl("~/Ad/iframe.aspx?adid=3&sequence=" + pos + "&site=" + AR.AdData.Site + "&zone=" + AR.AdData.Zone + "&kw=" + AR.AdData.KeyWords + "&kv=" + AR.AdData.KeyValues + ";product=photo;" + AudienceScience.SegmentValues + "&bust=" + Math.random()));

            $("#imgPhotoImage").attr("src", photo.Image.src);

            //Make sure Dialog Layer is visible.
            if (!$(".modal-recipe-photos").is(":visible")) {
                AR.Dialog.ShowLayer(".modal-recipe-photos");
                //Now that dialog is visible, show scroll border if necessary.
            }

            var descDiv = $("#jqDescription");
            var parentHeight = $(".modal-recipe-photos").find(".right-column").innerHeight();

            descDiv.height(parentHeight - $("#jqPhotographerBadgeDiv").outerHeight() - 7);

            if (descDiv.attr("scrollHeight") > descDiv.outerHeight()) {
                descDiv.css("border", '1px solid #cccccc');
            } else {
                descDiv.css("border", '');
            }

            descDiv.scrollTop(0);
        }
    },
    PreLoadIndexData: function (index) {
        var pageNumber = this.GetPageNumber(index);
        if (!AR.PhotoCarousel.GetIsCurrentPage(pageNumber) && !AR.PhotoCarousel.Data.Photos[index]) {
            AR.PhotoCarousel.GetDataFromService(pageNumber);
        }
    },
    PreLoadImage: function (photo) {
        if (photo && !photo.Image) {
            if ((new RegExp("https?://")).test(photo.PhotoUrl) != true) {
                photo.PhotoUrl = AR.ImageServer + photo.PhotoUrl;
            }
            photo.Image = new Image(250, 250);
            photo.Image.src = photo.PhotoUrl;
        }
    },
    GetDataFromService: function (pageNumber) {
        if (AR.PhotoCarousel.GetIsCurrentPage(pageNumber)) {
            AR.Cursor.SetWait();
        }

        AR.ClientService.SuppressNextLoaderChange();
        AR.ClientService.GetPhotosPaged(AR.PhotoCarousel.Data.ItemID,
                AR.PhotoCarousel.Data.IsRecipe,
                pageNumber,
                AR.PhotoCarousel.Config.PageSize,
                AR.PhotoCarousel.Events.GetPhotosPaged_callback);
    },
    StorePageData: function (photos, pageNumber) {
        if (photos) {
            var index = 0;
            for (i = 0; i < photos.length; i++) {
                index = ((pageNumber - 1) * AR.PhotoCarousel.Config.PageSize) + i;
                AR.PhotoCarousel.Data.Photos[index] = photos[i];
            }

            if (pageNumber != AR.PhotoCarousel.GetCurrentPageNumber()) {
                //load first image in page
                index = ((pageNumber - 1) * AR.PhotoCarousel.Config.PageSize);
                AR.PhotoCarousel.Data.Photos[index];

                //load last image in page
                index = ((pageNumber - 1) * AR.PhotoCarousel.Config.PageSize) + photos.length;
                AR.PhotoCarousel.Data.Photos[index];
            }
        }
    },
    ClearCachedData: function () {
        //Initialize data
        AR.PhotoCarousel.Data.ItemID = null;
        AR.PhotoCarousel.Data.IsRecipe = null;
        AR.PhotoCarousel.Data.TotalRecords = 0;
        AR.PhotoCarousel.Data.Photos = null;
    },
    OpenCarousel: function (itemID, isRecipe, photoGalleryUrl) {
        AR.PhotoCarousel.Data.CurrentPhotoIndex = 0;

        if (AR.PhotoCarousel.Data.ItemID != itemID
            || AR.PhotoCarousel.Data.IsRecipe != isRecipe
            || AR.PhotoCarousel.Data.Photos == null) {
            //Initialize data
            AR.PhotoCarousel.ClearCachedData();
            AR.PhotoCarousel.Data.ItemID = itemID;
            AR.PhotoCarousel.Data.IsRecipe = isRecipe;
            AR.PhotoCarousel.Data.PhotoGalleryUrl = photoGalleryUrl;
            AR.PhotoCarousel.GetDataFromService(1); //Load Page 1
        }
        else {
            AR.PhotoCarousel.LoadLayer();
        }
    },
    Events: {

        //----------------------------------------
        Open_onClick: function () {
            var serverItem = AR.ServerSideData.GetByDom(this);
            if (serverItem) {
                AR.PhotoCarousel.OpenCarousel(serverItem.itemID, serverItem.isRecipe, serverItem.photoGalleryUrl);
                AR.PhotoCarousel.RecordView(false);
            }
        },
        //----------------------------------------
        PreviousPhoto_onClick: function (e) {

            e.preventDefault();

            //Update Current Index
            AR.PhotoCarousel.Data.CurrentPhotoIndex = AR.PhotoCarousel.GetPreviousPhotoIndex();

            AR.PhotoCarousel.RecordView(true);

            //Call method to load current photo
            AR.PhotoCarousel.LoadLayer();
        },
        //----------------------------------------
        NextPhoto_onClick: function (e) {

            e.preventDefault();

            //Update Current Index
            AR.PhotoCarousel.Data.CurrentPhotoIndex = AR.PhotoCarousel.GetNextPhotoIndex();

            AR.PhotoCarousel.RecordView(true);

            //Call method to load current photo
            AR.PhotoCarousel.LoadLayer();
        },
        ViewAll_onClick: function (e) {
            //tell BI that the user clicked the link
            AR.Analytics.RecordInternalSource(AR.Analytics.Action.LinkName.RecipePhotoLayerViewAll);
        },
        GetPhotosPaged_callback: function (response) {
            var fatalError = false;
            var errorMessage = "";
            var shouldLogError = AR.ShouldLogResponseCode(response.ResponseCode);

            if (response.ResponseCode == AR.ResponseCode.Success) {

                var isCurrentPage = response.Data.PageNumber == AR.PhotoCarousel.GetCurrentPageNumber();

                AR.PhotoCarousel.Data.TotalRecords = response.Data.TotalRecords;
                if (AR.PhotoCarousel.Data.Photos == null) {
                    AR.PhotoCarousel.Data.Photos = new Array(response.Data.TotalRecords);
                }

                if (response.Data.PageNumber > 0 && response.Data.Items.length > 0) {

                    AR.PhotoCarousel.StorePageData(response.Data.Items, response.Data.PageNumber);

                    if (isCurrentPage) {
                        AR.PhotoCarousel.LoadLayer();
                    }
                }
                else {
                    fatalError = true;
                    shouldLogError = true;
                }
            }
            else {
                //Unknown response.
                fatalError = true;
            }

            if (fatalError) {
                //Unable to load current page. Close box and show error.
                AR.Dialog.CloseModalBox();
                AR.MessageBox.ShowFailure(AR.PhotoCarousel.Config.ErrorLoadingMessage, AR.PhotoCarousel.Config.MessageBoxSelector);

                if (shouldLogError) {
                    AR.LogErrorEx({
                        ItemID: AR.LogEval("AR.PhotoCarousel.Data.ItemID"),
                        IsRecipe: AR.LogEval("AR.PhotoCarousel.Data.IsRecipe")
                    }, "PhotoCarousel", "Error in GetPhotosPaged_onSuccess.");
                }
            }

            AR.Cursor.SetDefault();
        }
    },
    Initialize: function () {
        $(".open_modal-recipe-photos").click(this.Events.Open_onClick);
        $("#lnkNextPhoto").click(this.Events.NextPhoto_onClick);
        $("#lnkPreviousPhoto").click(this.Events.PreviousPhoto_onClick);
        $("#jqViewAllLink").click(this.Events.ViewAll_onClick);
    },
    RecordView: function (pageTurn) {
        AR.Analytics.RecordPageView(
        {
            pageName: "/recipe/" + AR.FriendlyName + "/photo-gallery-layer",
            channel: "Recipes",
            events: "event1",
            prop6: AR.Analytics.Action.ContentType.RecipePhoto,
            prop9: 1,
            prop24: (pageTurn ? AR.Analytics.Action.LinkName.RecipePhotoLayerTurn : ""),
            prop36: AR.Analytics.Action.LayerName.RecipePhoto
        });
    }
};


//=========================================================================
AR.ReviewCarousel = {
    Config: {
        PageSize: 10,
        MessageBoxSelector: "#msgLabel",
        ErrorLoadingMessage: "Sorry, there was an error loading the current review.",
        DynamicMode: true
    },
    Data: {
        ItemID: 0,
        ItemType: 0,
        CurrentReviewIndex: 0,
        TotalRecords: 0,
        Reviews: {}
    },
    RegisterData: function (itemID, itemType, count, reviews) {
        this.Data.ItemID = itemID;
        this.Data.ItemType = itemType;

        if (count) {
            this.Data.TotalRecords = count;
        }

        if (reviews) {
            this.Data.Reviews = reviews;
            this.Config.DynamicMode = false;
            this.Data.TotalRecords = Math.max(this.Data.TotalRecords, this.Data.Reviews.length);
        }
    },
    GetCurrentPageNumber: function () {
        return this.GetPageNumber(AR.ReviewCarousel.Data.CurrentReviewIndex);
    },
    GetIsCurrentPage: function (pageNumber) {
        return (pageNumber == this.GetCurrentPageNumber());
    },
    GetPreviousReviewIndex: function () {
        return (AR.ReviewCarousel.Data.CurrentReviewIndex == 0)
           ? (AR.ReviewCarousel.Data.TotalRecords - 1)
           : (AR.ReviewCarousel.Data.CurrentReviewIndex - 1);
    },
    GetNextReviewIndex: function () {
        return (AR.ReviewCarousel.Data.CurrentReviewIndex == (AR.ReviewCarousel.Data.TotalRecords - 1))
            ? 0
            : (AR.ReviewCarousel.Data.CurrentReviewIndex + 1);
    },
    GetPageNumber: function (reviewIndex) {
        return Math.ceil((reviewIndex + 1) / AR.ReviewCarousel.Config.PageSize);
    },
    LoadLayer: function () {
        var reviewIndex = AR.ReviewCarousel.Data.CurrentReviewIndex;

        if (!AR.ReviewCarousel.Config.DynamicMode) {
            if (reviewIndex == 0 && AR.ReviewCarousel.Data.TotalRecords > AR.ReviewCarousel.Data.Reviews.length) {
                $('#lnkPreviousReview').addClass('left-arrow-inactive');
            } else {
                $('#lnkPreviousReview').removeClass('left-arrow-inactive');
            }
        }

        if (AR.ReviewCarousel.Data.Reviews[reviewIndex]) {
            AR.ReviewCarousel.SetContent(AR.ReviewCarousel.Data.Reviews[reviewIndex]);
        }
        else if (AR.ReviewCarousel.Config.DynamicMode) {
            //Get page data, which will cause the layer to be loaded.
            AR.ReviewCarousel.GetDataFromService(this.GetCurrentPageNumber());
        }
        else {
            AR.ReviewCarousel.Navigate('reviews.aspx?SortBy=Helpfulness&Direction=Descending&Page=2');
        }

        if (AR.ReviewCarousel.Config.DynamicMode && AR.ReviewCarousel.Data.TotalRecords > 0) {
            AR.ReviewCarousel.PreLoadIndexData(this.GetNextReviewIndex());
            AR.ReviewCarousel.PreLoadIndexData(this.GetPreviousReviewIndex());
        }
    },
    SetLinkOrSpan: function (spanSelector, linkSelector, text, url) {
        if (url) {
            $(spanSelector).hide();
            $(linkSelector).show().attr("href", url).text(text);
        }
        else {
            $(spanSelector).show().text(text);
            $(linkSelector).hide();
        }
    },
    SetContent: function (review) {
        if (review) {
            //Paging
            if (AR.ReviewCarousel.Data.TotalRecords > 1) {
                $("#spnPageNumberReview").text(AR.ReviewCarousel.Data.CurrentReviewIndex + 1);
                $("#spnPageCountReview").text(AR.ReviewCarousel.Data.TotalRecords);
                $(".review-scroll-buttons").show();

                $("#jqViewAllDivReview").show();
                $("#jqViewAllLinkReview").attr("href", AR.ReviewCarousel.Data.ReviewGalleryUrl); //todo:check prop/url
            } else {
                $(".review-scroll-buttons").hide();
                $("#jqViewAllDivReview").hide();
            }

            var cookBaseUrl = (review.User.CustomUrlPiece)
                ? AR.ClientUrlProvider.ResolveUrl("~/Cook/" + review.User.CustomUrlPiece)
                : AR.ClientUrlProvider.ResolveUrl("~/Cook/" + review.User.ObfuscatedUserID);


            //Main Content
            $("#jqReviewTitleSpan").text(review.Title);
            $("#jqReviewRating").attr("src", AR.ClientUrlProvider.GetRatingImage(review.Rating));
            this.SetLinkOrSpan("#jqReviewerProfileSpan", "#jqReviewerProfileLink", review.User.DisplayName, review.User.HasHomePage ? cookBaseUrl : null);
            $("#jqReviewDate").text(review.Date);
            $("#jqReviewText").text(review.Text);
            $("#jqReviewHelpfulLink").data("reviewID", review.ID);
            $("#jqReviewHelpfulCount").text(review.HelpfulCount);

            $("#jqReviewHelpfulContainer").show();
            $("#jqReviewHelpfulMessage").hide();

            var pos = AR.ReviewCarousel.Data.CurrentReviewIndex + 1;

            $("#jqAdIframeReview").attr("src", AR.AdData.GenerateIFrameURL(pos, "300x250", "review"));

            //Make sure Dialog Layer is visible.
            if (!$(".modal-recipe-reviews").is(":visible")) {
                AR.Dialog.ShowLayer(".modal-recipe-reviews");
            }
        }
    },
    PreLoadIndexData: function (index) {
        var pageNumber = this.GetPageNumber(index);
        if (this.Config.DynamicMode && !AR.ReviewCarousel.GetIsCurrentPage(pageNumber) && !AR.ReviewCarousel.Data.Reviews[index]) {
            AR.ReviewCarousel.GetDataFromService(pageNumber);
        }
    },
    GetDataFromService: function (pageNumber) {
        if (!this.Config.DynamicMode) {
            AR.MessageBox.ShowFailure(AR.ReviewCarousel.Config.ErrorLoadingMessage, AR.ReviewCarousel.Config.MessageBoxSelector);
        } else {
            if (AR.ReviewCarousel.GetIsCurrentPage(pageNumber)) {
                AR.Cursor.SetWait();
            }

            AR.ClientService.SuppressNextLoaderChange();
            AR.ClientService.GetReviewsPaged(AR.ReviewCarousel.Data.ItemID,
                    AR.ReviewCarousel.Data.ItemType,
                    pageNumber,
                    AR.ReviewCarousel.Config.PageSize,
                    AR.ReviewCarousel.Events.GetReviewsPaged_callback);
        }
    },
    StorePageData: function (reviews, pageNumber) {
        if (reviews) {
            var index = 0;
            for (i = 0; i < reviews.length; i++) {
                index = ((pageNumber - 1) * AR.ReviewCarousel.Config.PageSize) + i;
                AR.ReviewCarousel.Data.Reviews[index] = reviews[i];
            }

            //what does this do?
            if (pageNumber != AR.ReviewCarousel.GetCurrentPageNumber()) {
                //load first image in page
                index = ((pageNumber - 1) * AR.ReviewCarousel.Config.PageSize);
                AR.ReviewCarousel.Data.Reviews[index];

                //load last image in page
                index = ((pageNumber - 1) * AR.ReviewCarousel.Config.PageSize) + reviews.length;
                AR.ReviewCarousel.Data.Reviews[index];
            }
        }
    },
    Navigate: function (url) {
        $('.review-body').hide();
        $('#review-loading').show();
        document.location = url;
    },
    OpenCarousel: function (index) {
        AR.ReviewCarousel.Data.CurrentReviewIndex = index;
        AR.ReviewCarousel.LoadLayer();
    },
    Events: {

        //----------------------------------------
        Open_onClick: function (e) {
            e.preventDefault();
            var serverdata = AR.ServerSideData.GetByDom(this)
            if (serverdata) {
                AR.ReviewCarousel.OpenCarousel(parseInt(serverdata.index));
                if (serverdata.source == "review") {
                    AR.ReviewCarousel.RecordView(AR.Analytics.Action.LinkName.RecipeReviewLayerBlock);
                } else {
                    AR.ReviewCarousel.RecordView(AR.Analytics.Action.LinkName.RecipeReviewLayerHeader);
                }
            }
        },
        //----------------------------------------
        PreviousReview_onClick: function (e) {

            e.preventDefault();

            if (!$(this).hasClass('left-arrow-inactive')) {
                //Update Current Index
                AR.ReviewCarousel.Data.CurrentReviewIndex = AR.ReviewCarousel.GetPreviousReviewIndex();

                AR.ReviewCarousel.RecordView(AR.Analytics.Action.LinkName.RecipeReviewLayerTurn);

                //Call method to load current review
                AR.ReviewCarousel.LoadLayer();
            }
        },
        //----------------------------------------
        NextReview_onClick: function (e) {

            e.preventDefault();

            //Update Current Index
            AR.ReviewCarousel.Data.CurrentReviewIndex = AR.ReviewCarousel.GetNextReviewIndex();

            AR.ReviewCarousel.RecordView(AR.Analytics.Action.LinkName.RecipeReviewLayerTurn);

            //Call method to load current review
            AR.ReviewCarousel.LoadLayer();
        },
        ViewAll_onClick: function (e) {
            //tell BI that the user clicked the link
            AR.Analytics.RecordInternalSource(AR.Analytics.Action.LinkName.RecipeReviewLayerViewAll);
        },
        Helpful_onClick: function (e) {
            var reviewID = $(this).data("reviewID");
            if (reviewID) {
                AR.ClientService.SuppressNextLoaderChange();
                AR.ClientService.IncrementReviewWasHelpful(reviewID, function () { });
            }
            $("#jqReviewHelpfulContainer").hide();
            $("#jqReviewHelpfulMessage").show();
        },
        GetReviewsPaged_callback: function (response) {
            var fatalError = false;
            var errorMessage = "";
            var shouldLogError = AR.ShouldLogResponseCode(response.ResponseCode);

            if (response.ResponseCode == AR.ResponseCode.Success) {

                var isCurrentPage = response.Data.PageNumber == AR.ReviewCarousel.GetCurrentPageNumber();

                AR.ReviewCarousel.Data.TotalRecords = response.Data.TotalRecords;
                if (AR.ReviewCarousel.Data.Reviews == null) {
                    AR.ReviewCarousel.Data.Reviews = new Array(response.Data.TotalRecords);
                }

                if (response.Data.PageNumber > 0 && response.Data.Items.length > 0) {

                    AR.ReviewCarousel.StorePageData(response.Data.Items, response.Data.PageNumber);

                    if (isCurrentPage) {
                        AR.ReviewCarousel.LoadLayer();
                    }
                }
                else {
                    fatalError = true;
                    shouldLogError = true;
                }
            }
            else {
                //Unknown response.
                fatalError = true;
            }

            if (fatalError) {
                //Unable to load current page. Close box and show error.
                AR.Dialog.CloseModalBox();
                AR.MessageBox.ShowFailure(AR.ReviewCarousel.Config.ErrorLoadingMessage, AR.ReviewCarousel.Config.MessageBoxSelector);

                if (shouldLogError) {
                    AR.LogErrorEx({
                        ItemID: AR.LogEval("AR.ReviewCarousel.Data.ItemID"),
                        ItemType: AR.LogEval("AR.ReviewCarousel.Data.ItemType")
                    }, "ReviewCarousel", "Error in GetReviewsPaged_callback.");
                }
            }

            AR.Cursor.SetDefault();
        }
    },
    Initialize: function () {

        $(".open_modal-recipe-reviews").click(this.Events.Open_onClick);
        $("#lnkNextReview").click(this.Events.NextReview_onClick);
        $("#lnkPreviousReview").click(this.Events.PreviousReview_onClick);
        $("#jqViewAllLinkReview").click(this.Events.ViewAll_onClick);
        $("#jqReviewHelpfulLink").click(this.Events.Helpful_onClick);
    },
    RecordView: function (action) {
        AR.Analytics.RecordPageView(
        {
            pageName: "/recipe/" + AR.FriendlyName + "/review-layer",
            channel: "Recipes",
            events: "event1",
            prop6: AR.Analytics.Action.ContentType.Review,
            prop9: 1,
            prop24: action,
            prop36: AR.Analytics.Action.LayerName.RecipeReview
        });
    }
}

//
// jQuery\Membership.js
//
/// IntelliSense support references:
/// <reference path="../JQuery/jquery-1.3.2-vsdoc.js" />
/// <reference path="../JQuery/main.js" />

var FeaturePrefix = "featureHint";
var Features1 = ["NotSet", "Blogs", "CustomPrint", "CustomRecipe", "NutritionSearch", "CustomUrl", "KitchenView", "Menus"];
var Features2 = ["UpgradeNowTopNav", "ARToolsRecipeBoxTab", "ARToolsMenusTab", "RelatedMenu", "MoreMenusLikeThis"];
var Features3 = ["MenusToggleThumbnail", "MenusToggleTitle", "MPNotifications", "MenuDetailAddMenu", "MenuListTitle", "MenuListThumb", "MenuListNotification", "MenuListItem", "MenuLatestUserTitle", "MenuLatestUserThumb", "MenuLatestARTitle", "MenuLatestARThumb", "MenuWeeklyAlert", "MPAddToShoppingList", "MPSaveMenu", "MPMyMenus"];
var Features4 = ["RecipeAddToMenu", "ReferenceAddToMenu", "WeblinkAddToMenu", "CooksMenuListThumb", "CooksMenuListTitle", "RecipeBoxMenuAdd"];
var Features5 = ["PrimaryNavNewMenuSignUp", "PrimaryNavMyARSupportingMemberBtn"];
var Features = Features1.concat(Features2.concat(Features3.concat(Features4.concat(Features5))));

var AdvancedPrintFeatures = ["NotSet", "CustomHeadline", "Reviews", "Photos", "Themes", "Colors", "Fonts"];
var PitchDialogType = ["NotSet", "NewestMenuAlerts", "MenuBarricade"];

AR.DialogLinker = {
    SetNextStepUrl: function (value) {
        setCookie("ARNextStep", value, 1);
    },
    GetNextStepForHyperlink: function (anchor) {

        var nextStep = anchor[0].href;

        if (anchor.hasClass("linkRequirementNextStepIsSamePage")) {
            nextStep = window.location.href;
        }

        return nextStep;
    },
    GetPitchDialogForHyperLink: function (anchor) {
        var pitchDialogType = "NotSet";

        if (anchor) {
            var classToPitchDialogMap = $.map(PitchDialogType, function (pitchTypeName) {
                return { hintClass: "pitchDialogHint" + pitchTypeName, pitchType: pitchTypeName };
            });

            $.each(classToPitchDialogMap, function () {
                if (anchor.hasClass(this.hintClass))
                    pitchDialogType = this.pitchType;
            });
        }

        return pitchDialogType;
    },
    GetFeatureHintFromHyperlink: function (anchor) {

        var featureHighlight = "NotSet";

        if (anchor) {
            var classToFeatureMap = $.map(Features, function (featureName) {
                return { hintClass: FeaturePrefix + featureName, feature: featureName };
            });

            $.each(classToFeatureMap, function () {
                if (anchor.hasClass(this.hintClass))
                    featureHighlight = this.feature;
            });
        }

        return featureHighlight;
    },
    GetAdvancedPrintFeatureHintFromHyperlink: function (anchor) {

        var featureHighlight = "NotSet";

        if (anchor) {
            var classToFeatureMap = $.map(AdvancedPrintFeatures, function (featureName) {
                return { hintClass: "advancedPrintFeatureHint" + featureName, feature: featureName };
            });

            $.each(classToFeatureMap, function () {
                if (anchor.hasClass(this.hintClass))
                    featureHighlight = this.feature;
            });
        }

        return featureHighlight;
    },
    LinkMembershipDialogs: function (domToLink) {

        var that = this;

        domToLink.find('.linkRequiresLogin').click(function (e) {
            that.OnLinkRequiringLogin(e, $(this));
        });

        domToLink.find('.linkPrefersLogin').click(function (e) {
            that.OnLinkPrefersLogin(e, $(this));
        });

        domToLink.find('.linkShowsRegister').click(function (e) {
            that.OnShowRegisterDialog(e, $(this));
        });

        domToLink.find('.linkShowsLogin').click(function (e) {
            that.OnShowsLoginDialog(e, $(this));
        });

        domToLink.find(".linkRequiresSupportingMembership").click(function (e) {
            that.OnLinkRequiringSupportingMembership(e, $(this));
        });

        domToLink.find(".linkPrefersSupportingMembership").click(function (e) {
            that.OnLinkPrefersSupportingMembership(e, $(this));
        });

        domToLink.find(".linkPrefersSupportingMembershipPitchDialog").click(function (e) {
            that.OnLinkPrefersSupportingMembershipPitchDialog(e, $(this));
        });
    },
    OnLinkRequiringLogin: function (event, anchor) {

        if (AR.VisitorInfo.IsLoggedIn()) {
            //do nothing - Allow Event to propagate            
        } else {
            event.preventDefault();
            event.stopImmediatePropagation();

            this.SetNextStepUrl(this.GetNextStepForHyperlink(anchor));

            if (AR.VisitorInfo.IsRecognized()) {
                AR.CreateAspxDialog(AR.ClientUrlProvider.GetLogonAspxDialog());
            }
            else {
                AR.CreateAspxSignUpDialog(anchor);
            }
        }
    },
    OnLinkPrefersLogin: function (event, anchor) {

        if (!AR.VisitorInfo.IsLoggedIn() && AR.VisitorInfo.IsRecognized()) {

            event.preventDefault();
            event.stopImmediatePropagation();

            AR.DialogLinker.SetNextStepUrl(AR.DialogLinker.GetNextStepForHyperlink(anchor));

            AR.CreateAspxDialog(AR.ClientUrlProvider.GetLogonAspxDialog());
        }
    },
    OnShowRegisterDialog: function (event, anchor) {
        if (AR.VisitorInfo.IsLoggedIn()) {
            //do nothing - Allow Event to propagate    
        } else {

            event.preventDefault();
            event.stopImmediatePropagation();

            AR.DialogLinker.SetNextStepUrl(AR.DialogLinker.GetNextStepForHyperlink(anchor));
            AR.CreateAspxSignUpDialog(anchor);
        }
    },
    OnShowsLoginDialog: function (event, anchor) {
        if (AR.VisitorInfo.IsLoggedIn()) {
            //do nothing - Allow Event to propagate    
        } else {

            event.preventDefault();
            event.stopImmediatePropagation();

            AR.DialogLinker.SetNextStepUrl(AR.DialogLinker.GetNextStepForHyperlink(anchor));
            AR.CreateAspxDialog(AR.ClientUrlProvider.GetLogonAspxDialog());
        }
    },
    OnLinkPrefersSupportingMembershipPitchDialog: function (event, anchor) {
        if (AR.VisitorInfo.IsLoggedIn() && AR.VisitorInfo.IsSupportingMember()) {
            //do nothing - Allow Event to propagate    
        } else {
            event.preventDefault();
            event.stopImmediatePropagation();

            AR.DialogLinker.SetNextStepUrl(AR.DialogLinker.GetNextStepForHyperlink(anchor));

            if (!AR.VisitorInfo.IsLoggedIn() && AR.VisitorInfo.IsSupportingMember()) {
                AR.CreateAspxDialog(AR.ClientUrlProvider.GetLogonAspxDialog());
            } else {
                var pitchDialog = AR.DialogLinker.GetPitchDialogForHyperLink(anchor);
                var featureHighlight = AR.DialogLinker.GetFeatureHintFromHyperlink(anchor);
                var linkName = (anchor[0].name) ? encodeURIComponent(anchor[0].name) : '';

                if (pitchDialog == 'MenuBarricade') { //applies to anon and recognized
                    // Pass in ActionItem from query string 
                    var qsKey = AR.ClientUrlUtils.QueryStringParameters.AnalyticsActionItem;
                    var menuType = AR.ClientUrlUtils.GetQueryStringItemFromAnchor(qsKey, anchor); 
                    AR.DialogLinker.ProcessPitchDialog(pitchDialog, featureHighlight, menuType);
                }
                else if (!AR.VisitorInfo.IsRecognized() && pitchDialog != 'NotSet') {
                    // process pitch dialog type
                    AR.DialogLinker.ProcessPitchDialog(pitchDialog, featureHighlight, linkName);
                }               
                else {
                    // Normal SM Funnel if no specific pitch dialog is returned
                    AR.DialogLinker.ShowProductSelectionDialog(featureHighlight, linkName);
                }
            }
        }
    },
    OnLinkRequiringSupportingMembership: function (event, anchor) {
        if (AR.VisitorInfo.IsLoggedIn() && AR.VisitorInfo.IsSupportingMember()) {
            //do nothing - Allow Event to propagate    
        } else {

            event.preventDefault();
            event.stopImmediatePropagation();

            AR.DialogLinker.SetNextStepUrl(AR.DialogLinker.GetNextStepForHyperlink(anchor));

            if (!AR.VisitorInfo.IsLoggedIn() && AR.VisitorInfo.IsSupportingMember()) {
                AR.CreateAspxDialog(AR.ClientUrlProvider.GetLogonAspxDialog());
            } else {
                var featureHighlight = AR.DialogLinker.GetFeatureHintFromHyperlink(anchor);
                var linkName = (anchor[0].name) ? encodeURIComponent(anchor[0].name) : '';
                var advPrintFeatureHighlight = AR.DialogLinker.GetAdvancedPrintFeatureHintFromHyperlink(anchor);
                var qsInternalSource = "";
                var qsCallToAction = "";

                // Check for Link Name or CustomLinkClick in anchor's QueryString
                var OverRideItems = AR.Analytics.OverRide.ParseItems(anchor[0].search.substr(1));
                for (i = 0; i < OverRideItems.length; i++) {
                    if (OverRideItems[i]) {
                        switch (OverRideItems[i].Key) {
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsLinkName:
                                linkName = OverRideItems[i].Value;
                                break;
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsCustomLinkClick:
                                AR.Analytics.RecordCustomLinkClick(OverRideItems[i].Value);
                                break;
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsInternalSource:
                                qsInternalSource = OverRideItems[i].Value;
                                break;
                            case AR.ClientUrlUtils.QueryStringParameters.AnalyticsCallToAction:
                                qsCallToAction = OverRideItems[i].Value;
                                break;
                        }
                    }
                }

                if (advPrintFeatureHighlight == 'NotSet') {
                    AR.DialogLinker.ShowProductSelectionDialog(featureHighlight, linkName, qsInternalSource, qsCallToAction);
                }
                else {
                    AR.DialogLinker.ShowAdvancedPrintProductSelectionDialog(featureHighlight, advPrintFeatureHighlight, linkName);
                }
            }
        }
    },
    OnLinkPrefersSupportingMembership: function (event, anchor) {

        if (!AR.VisitorInfo.IsLoggedIn() && AR.VisitorInfo.IsSupportingMember()) {

            event.preventDefault();
            event.stopImmediatePropagation();

            AR.DialogLinker.SetNextStepUrl(AR.DialogLinker.GetNextStepForHyperlink(anchor));

            AR.CreateAspxDialog(AR.ClientUrlProvider.GetLogonAspxDialog());
        }
    },
    ShowProductSelectionDialog: function (featureHighlight, linkName, internalSource, callToAction) {
        AR.CreateAspxDialog(AR.ClientUrlProvider.GetProductSelectionDialog(featureHighlight, linkName, internalSource, callToAction));
    },
    ShowAdvancedPrintProductSelectionDialog: function (featureHighlight, printFeature, linkName) {
        AR.CreateAspxDialog(AR.ClientUrlProvider.GetAdvancedPrintProductSelectionDialog(featureHighlight, printFeature, linkName));
    },
    ProcessPitchDialog: function (pitchItem, featureHighlight, postData) {
        switch (pitchItem) {
            case "NewestMenuAlerts":
                ioc.Load("_dialogLauncher").NewMenuAlertPitch(function (result) {
                    var t = setTimeout(function () { AR.DialogLinker.ShowProductSelectionDialog(featureHighlight, postData); }, 10);
                },
                function () {
                    // error handling?
                });
                break;
            case "MenuBarricade":
                ioc.Load("_dialogLauncher").SampleMenuPitch(
                function (result) {
                    // nothing more to do here
                },
                function () {
                    // error handling?
                },
                postData);
                break;
            default:
                break;
        }
    }
};


//Helper function for creating the Free Member Register Dialog
//args
// anchor: the dom link object that triggered the dialog, link id is used for omniture call to action
// if QueryString values are posted for use with FM signup, they need to be removed prior to redirect to nextStepUrl ('updatedUrl' value)
AR.CreateAspxSignUpDialog = function (anchor) {
    var updatedUrl = AR.Analytics.SetFMOmniCallToAction(anchor);
    if (updatedUrl.length > 0) {
        AR.DialogLinker.SetNextStepUrl(updatedUrl);
    }
    AR.CreateAspxDialog(AR.ClientUrlProvider.GetSignUpAspxDialog());
};


ioc.Register("_membershipDialogLinker").withInstance(AR.DialogLinker);

//
// jQuery\TabBlocker.js
//


AR.TabBlocker = function() {
    this._storedTabindexes = [];
};

AR.TabBlocker.prototype.GetTotalTabindexesBlocked = function() {
    return this._storedTabindexes.length;
};

AR.TabBlocker.prototype.BlockTabindexes = function (targetDom, excludedDom) {

    targetDom = targetDom || $(document);  // default to the entire document
    
    var elementsToBlock = targetDom.find("*");

    var that = this;
    var elementsAndTabindexes = [];

    jQuery.each(elementsToBlock, function () {

        var elementToBlock = this;
        var jQueryelementToBlock = $(elementToBlock);

        if (jQueryelementToBlock.css("display") == "none" || jQueryelementToBlock.css("visibility") == "hidden") {
            return;
        }

        var originalTabIndex = jQueryelementToBlock.attr("tabindex");

        if (originalTabIndex == '-1') {
            return;
        }

        if (typeof (originalTabIndex) == "undefined" && jQueryelementToBlock[0].nodeName != "UL") {
            // For some reason Firefox is allowing <UL> elements to be part of the tab order, even
            // though they have no tabindex.
            return;
        }

        if (excludedDom) {
            var excluded = false;

            jQuery.each(excludedDom, function() {
                var domToExclude = this;

                if (elementToBlock == domToExclude || jQuery.contains(domToExclude, elementToBlock)) {
                    excluded = true;
                }
            });

            if (excluded) {
                return;
            }
        }

        elementsAndTabindexes[elementsAndTabindexes.length] = [elementToBlock, originalTabIndex];

        $(this).attr("tabindex", -1);
    });

    this._storedTabindexes = this._storedTabindexes.concat(elementsAndTabindexes);
};

AR.TabBlocker.prototype.RestoreTabindexes = function() {

    var toRestore = this._storedTabindexes.reverse();
    this._storedTabindexes = [];
    
    var that = this;
    
    $.each(toRestore, function() {
        var targetNode = this[0];
        var tabindex = this[1];
        
        $(targetNode).attr("tabindex", tabindex);
    });
};

AR.TabBlocker.singletonInstance = new AR.TabBlocker();


//
// jQuery\AspxDialog.js
//


AR.AspnetJavascriptContext = function() {
    this._valuesToPreserve = ["__doPostBack", "theForm", "WebForm_OnSubmit", "Page_Validators", "ValidatorOnSubmit", "Page_ValidationActive", "ValidatorOnChange"];
    this._context = null;
};

AR.AspnetJavascriptContext.prototype.Preserve = function() {
    if (this._context != null)
        return;

    var result = {};
    
    $.each(this._valuesToPreserve, function() {
        if (typeof (window[this]) !== "undefined") {
            result[this] = window[this];
        }
    });

    this._context = result;
}

AR.AspnetJavascriptContext.prototype.GetContext = function() {
    return this._context;
}

AR.AspnetJavascriptContext.prototype.Restore = function() {
    
    if (this._context != null) {
        var context = this._context;
    
        $.each(this._valuesToPreserve, function() {
            window[this] = context[this];
        });    
    };
}

AR.AspnetJavascriptContext.singletonInstance = new AR.AspnetJavascriptContext();

//  Invoked as:
//     var widget = new  AR.AspxDialogTemplateWidget($(dialogTemplate));

AR.AspxDialogTemplateWidget = function(dialogTemplate) {
    this._dialog = dialogTemplate.clone(false);
    this._dialog.addClass("aspx-dialog-instance");
};

AR.AspxDialogTemplateWidget.prototype.Close = function() {
    this._dialog.remove();
};

AR.AspxDialogTemplateWidget.prototype.GetDialog = function() {
    return this._dialog;
};

AR.AspxDialogTemplateWidget.prototype.GetTitleArea = function() {
    return this._dialog.find(".aspxdialog-title");
};

AR.AspxDialogTemplateWidget.prototype.GetContentArea = function() {
    return this._dialog.find(".rsz-content");
};

AR.AspxDialogTemplateWidget.prototype.GetCloseButtons = function() {
    return this._dialog.find("a.close-modal, a.close-modal-and-handle-click");
}

AR.AspxDialogTemplateWidget.prototype.GetForm = function() {
    return this.GetContentArea().find("form");
}

AR.AspxDialogTemplateWidget.prototype.GetUpperRightCloseButton = function() {
    return this._dialog.find("div.modal-close-button");
}

AR.AspxDialogTemplateWidget.prototype.GetHiddenTitleInfo = function() {
    return this.GetContentArea().find(".hiddeninfo-title");
};

AR.AspxDialogTemplateWidget.prototype.GetHiddenShouldShowButtonInfo = function () {
    return typeof (aspxDialogParameters) !== "undefined"
      && typeof (aspxDialogParameters.ShowCloseButton) !== "undefined"
      && aspxDialogParameters.ShowCloseButton;
};

AR.AspxDialogTemplateWidget.prototype.GetUrl = function() {
    
    if (typeof(aspxDialogParameters) !== "undefined" 
        && typeof(aspxDialogParameters.Url) !== "undefined") {
        
        return aspxDialogParameters.Url;
    } else {
        return window.location;
    }
};

AR.AspxDialogTemplateWidget.prototype.GetReturnValue = function() {

    if (typeof(aspxDialogParameters) !== "undefined" 
        && typeof(aspxDialogParameters.ReturnValue) !== "undefined") {
        
        return aspxDialogParameters.ReturnValue;
    } else {
        return null;
    }
};

AR.AspxDialogTemplateWidget.prototype.IsValidDownloadResult = function() {
    return this.GetTitleArea().length > 0;
};

// This code relies on there being a modal dialog with class name "modal-dialog-template".
// The content from 'url' will be downloaded and injected into the "div.modal-dialog-template .modal-content".
// Any buttons that are intended to close the dialog should match ".close-modal".
// See the testdoc in AR_AspxDialog.htm for an example of the expected document structure

AR.CreateAspxDialog = function(url, errorCallback) {
    
    AR.SetModuleLogContent("AR.AspxDialog", {
        url : url
    });
    
    var result = new AR.AspxDialog(AR.AspnetJavascriptContext.singletonInstance, $);
    result.Start(url, null, errorCallback);
};

// jQuery($) is taken as input parameter $ so that unit tests can substitute a test double.

AR.AspxDialog = function(aspnetJavascriptContext) {
    this._aspnetJavascriptContext = aspnetJavascriptContext;
    this._clickFormParameters = [];
    this._aspnetFormParameters = [];

    // some methods provided by the class are made per-instance members that
    // can be passed to event handler functions.
    
    var that = this;
    
    $.each([
        "Close", 
        "OnLoadFinished", 
        "OnFormSubmit", 
        "OnFormClick", 
        "OnSubmit", 
        "OnClosing",
        "OnClosed",
        "Aspnet__doPostBack"], function() {
        var functionToOverride = this;
        that[functionToOverride] = function() {
            return AR.AspxDialog.prototype[functionToOverride].apply(that, arguments);
        };
    });
}

AR.AspxDialog.prototype.Close = function(event) {
    AR.Dialog.CloseModalBox();
    
    if (event != null && event.preventDefault != null) {
        event.preventDefault();
    }    
}

AR.AspxDialog.prototype.Start = function(url, successCallback, errorCallback) {

    this._url = url;
    this._successCallback = successCallback;
    this._errorCallback = errorCallback;

    this.ClearExistingAspxDialog();
    this.RegisterDialogCloseHandlers();
    this.PreserveAspnetJavascriptContent();
    this.PrepareTemplate();
    this.LoadDialogContent();
};

AR.AspxDialog.prototype.StartPost = function (url, data, successCallback, errorCallback) {

    this._url = url;
    this._data = data;
    this._successCallback = successCallback;
    this._errorCallback = errorCallback;

    this.ClearExistingAspxDialog();
    this.RegisterDialogCloseHandlers();
    this.PreserveAspnetJavascriptContent();
    this.PrepareTemplate();
    this.LoadDialogContentPost();
};

AR.AspxDialog.prototype.ClearExistingAspxDialog = function() {
    AR.Dialog.RunOnClosingHandlers();
    AR.Dialog.RunOnClosedHandlers();
};

AR.AspxDialog.prototype.RegisterDialogCloseHandlers = function() {  
    AR.Dialog.AddOnClosingHandler(this.OnClosing);
    AR.Dialog.AddOnClosedHandler(this.OnClosed);
};

AR.AspxDialog.prototype.PreserveAspnetJavascriptContent = function() {
    this._aspnetJavascriptContext.Preserve();
};

AR.AspxDialog.prototype.PrepareTemplate = function() {
    this._widget = new AR.AspxDialogTemplateWidget($(".modal-dialog-template"));
    $("form").before(this._widget.GetDialog());
};

AR.AspxDialog.prototype.LoadDialogContent = function() {
    var modalContent = this._widget.GetContentArea();
    this._pendingRequest = modalContent.load(this._url, this.OnLoadFinished);
};

AR.AspxDialog.prototype.LoadDialogContentPost = function () {
    var modalContent = this._widget.GetContentArea();
    this._pendingRequest = modalContent.load(this._url, this._data, this.OnLoadFinished);
};

AR.AspxDialog.prototype.OnLoadFinished = function(responseText, textStatus) {

    this._pendingRequest = null;

    if (textStatus != "error") {

        var returnValue = this._widget.GetReturnValue();

        if (returnValue != null) {
            this.HandleReturnValue(returnValue);
            return;
        }

        if (this._widget.IsValidDownloadResult()) {
            this.HandleNextDialog();
            return;
        }
    }

    this.OnError();
};

AR.AspxDialog.prototype.OnError = function() {
    this.Close();

    if (this._errorCallback) {
        this._errorCallback();
    }
};

AR.AspxDialog.prototype.HandleReturnValue = function (value) {

    var that = this;

    AR.Dialog.CloseModalBox(function() { 
        if (that._successCallback) {
            that._successCallback(value);
        }
    });
};

AR.AspxDialog.prototype.HandleNextDialog = function() {

    this.RedefineAspnet__doPostBack();
    this.ShowDialog();
    this.SetTitle();
    this.SetUpperRightCancelButtonVisibility();
    this.WireCloseButtons();
    this.WireFormSubmit();
};

AR.AspxDialog.prototype.RedefineAspnet__doPostBack = function() {
    __doPostBack = this.Aspnet__doPostBack;
};

AR.AspxDialog.prototype.ShowDialog = function() {
    AR.Dialog.ShowLayer(this._widget.GetDialog());
};

AR.AspxDialog.prototype.Aspnet__doPostBack = function(eventTarget, eventArgument) {
    var aspnetFormParameters = []
    aspnetFormParameters[0] = { name: "__EVENTTARGET", value : eventTarget};
    aspnetFormParameters[1] = { name: "__EVENTARGUMENT", value : eventArgument};
    this._aspnetFormParameters = aspnetFormParameters;
    
    var that = this;
    
    setTimeout(function() {
        that._aspnetFormParameters = [];
    }, 100);
    
    this._widget.GetForm().submit();
};

AR.AspxDialog.prototype.SetTitle = function() {
    var titleContent = this._widget.GetHiddenTitleInfo();
    var titleTarget = this._widget.GetTitleArea();
    titleTarget.empty();
    titleTarget.append(titleContent.contents());
};

AR.AspxDialog.prototype.SetUpperRightCancelButtonVisibility = function() {

    var shouldShowButton = this._widget.GetHiddenShouldShowButtonInfo();
    
    this._widget.GetUpperRightCloseButton().css("visibility", shouldShowButton ? "visible" : "hidden");
};

AR.AspxDialog.prototype.WireCloseButtons = function() {
    var that = this;
    this._widget.GetCloseButtons().one("click", function(e) { 

        if (!$(this).hasClass("close-modal-and-handle-click")) {
            e.preventDefault();
        }

        that.Close(); 
    });
};

AR.AspxDialog.prototype.WireFormSubmit = function() {
    var form = this._widget.GetForm();
    form.click(this.OnFormClick);
    form.submit(this.OnFormSubmit);
};

AR.AspxDialog.prototype.OnFormSubmit = function() {
    this.OnSubmit();
    return false;
};

AR.AspxDialog.prototype.OnFormClick = function(e) {

    // the implementation of this function came from the jQuery forms plugin
    // it sets certain form parameters that would normally be generated when the
    // user clicks on a button or image input field.

    // Unlike the forms plugin, which associates the form fields with the form DOM
    // element, this code tracks them  _clickFormParameters 

    var target = e.target;
    var $el = $(target);
    if (!($el.is(":submit,input:image"))) {
        // is this a child element of the submit el?  (ex: a span within a button)
        var t = $el.closest(':submit');
        if (t.length == 0)
            return;
        target = t[0];
    }

    if (target.name) {
        var additionalFormParameters = [];
        additionalFormParameters.push({ name: target.name, value: target.value });

        if (target.type == 'image') {

            var x;
            var y;

            if (e.offsetX != undefined) {
                x = e.offsetX;
                y = e.offsetY;
            } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                var offset = $el.offset();
                x = e.pageX - offset.left;
                y = e.pageY - offset.top;
            } else {
                x = e.pageX - target.offsetLeft;
                y = e.pageY - target.offsetTop;
            }
            x = parseInt(x);  // convert decimal to integer
            y = parseInt(y);  // convert decimal to integer

            additionalFormParameters.push({ name: target.name + '.x', value: x });
            additionalFormParameters.push({ name: target.name + '.y', value: y });
        }

        this._clickFormParameters = additionalFormParameters;

        var that = this;

        setTimeout(function() { that._clickFormParameters = []; }, 100);
    }
};

AR.AspxDialog.prototype.GetFormParameters = function() {
    var form = this._widget.GetForm();
    var aspnetFormParameterNames = $.map(this._aspnetFormParameters, function(element) { return element.name; });
    
    var includedFormParameters = $.grep(form.serializeArray(),
        function(parameter, index) {
            var parameterName = parameter.name;
            return $.inArray(parameterName, aspnetFormParameterNames) == -1;
        });
    
    return $.merge($.merge($.merge([], includedFormParameters), this._clickFormParameters), this._aspnetFormParameters);
};

AR.AspxDialog.prototype.OnSubmit = function() {
    var formData = this.GetFormParameters();
    var targetUrl = this._widget.GetUrl();
    var modalContent = this._widget.GetContentArea();
    this._pendingRequest = modalContent.load(targetUrl, formData, this.OnLoadFinished);
};


AR.AspxDialog.prototype.OnClosing = function(e) {

    var pendingRequest = this._pendingRequest;
    this._pendingRequest = null;

    if (pendingRequest != null) {

        //  // jQuery.load() used to return an XMLHttpRequest object we could abort...
        //  // apparently it hasn't for some time, and the aborts haven't been happening.

        //pendingRequest.abort();
    }
};


AR.AspxDialog.prototype.OnClosed = function(e) {
    this._widget.Close();
    this._aspnetJavascriptContext.Restore();
};


ioc.Register("_aspnetJavascriptContext").withInstance(AR.AspnetJavascriptContext.singletonInstance);
ioc.Register("_aspxDialog").withConstructor(AR.AspxDialog).withDependencies("_aspnetJavascriptContext");


//
// lib\jQuery-textTruncate\jquery.textTruncate.js
//
/// <reference path="../../Intellisense.js" />

(function ($) {

    $.fn.textTruncate = function () {

        var userOptions = {};
        var args = arguments; // for better minification
        var func = args.callee // dito; and much shorter than $.fn.textTruncate

        if (args.length) {

            if (args[0].constructor == Object) {
                userOptions = args[0];
            } else if (args[0] == "options") {
                return $(this).eq(0).data("options-truncate");
            } else {
                userOptions = {
                    width: parseInt(args[0]),
                    height: parseInt(args[1]),
                    tail: args[2]
                }
            }
        }

        // Hide the element(s) while manipulating them
        this.css("visibility", "hidden");

        // apply options vs. defaults
        var options = $.extend({}, func.defaults, userOptions);

        return this.each(function () {

            var $this = $(this);
            $this.data("options-truncate", options);

            //If browser implements text-overflow:ellipsis in CSS and tail is "...", use it!
            if (options.tail == "..." && func._native) {

                this.style[func._native] = "ellipsis";
                $this.css("visibility", "visible");

                return true;
            }

            var width = options.width || $this.parent().width();
            var height = options.height || $this.parent().height();

            var text = $this.text();
            var maxCounter = text.length;
            var css = "padding:0; margin:0; border:none; font:inherit;";
            var $table;

            if (options.multiline) {
                $table = $('<table style="' + css + 'width:' + width + 'px;zoom:1;position:absolute;"><tr style="' + css + '"><td style="' + css + 'white-space:normal;">' + options.tail + '</td></tr></table>');
            } else {
                $table = $('<table style="' + css + 'width:auto;zoom:1;position:absolute;"><tr style="' + css + '"><td style="' + css + 'white-space:nowrap;">' + options.tail + '</td></tr></table>');
            }

            var $td = $("td", $table);
            $this.html($table);

            var tailwidth = $td.width();
            var targetWidth = (options.multiline) ? width : width - tailwidth;
            var targetHeight = height;
            var counter = 0;

            $td.text(text);

            if (options.multiline && ($td.height() > targetHeight || $td.width() > targetWidth)) {
                if (options.tooltip) {
                    $this.attr("title", $.trim(text));
                }
                while ($td.height() > targetHeight || $td.width() > targetWidth) {
                    counter++;
                    if (options.wrap == "word" && $td.text().lastIndexOf(" ") != -1) {
                        $td.text($td.text().substring(0, $td.text().lastIndexOf(" "))).append(options.tail);
                    } else {
                        $td.text($td.text().substring(0, $td.text().length - 2)).append(options.tail);
                    }

                    if (counter >= maxCounter) {
                        console.warn("Max loop count (" + maxCounter + ") encountered in textTruncate plug-in.");
                        return;
                    }
                }

                text = $.trim($td.text());
                $this.text(text);
            } else if ($td.width() > width) {
                if (options.tooltip) {
                    $this.attr("title", text);
                }

                while ($td.width() > targetWidth) {
                    counter++;
                    if (options.wrap == "word" && $td.text().lastIndexOf(" ") != -1) {
                        $td.text($td.text().substring(0, $td.text().lastIndexOf(" ")));
                    } else {
                        $td.text($td.text().substring(0, $td.text().length - 1));
                    }

                    if (counter >= maxCounter) {
                        console.warn("Max loop count (" + maxCounter + ") encountered in textTruncate plug-in.");
                        return;
                    }
                }

                text = $.trim($td.text());
                $this.text(text).append(options.tail);
            } else {
                $this.text(text);
            }

            this.style.visibility = "visible";

            return true;
        });

        return true;
    };


    var css = document.documentElement.style;
    var _native = false;

    if ("textOverflow" in css) {
        _native = "textOverflow";
    } else if ("OTextOverflow" in css) {
        _native = "OTextOverflow";
    }

    $.fn.textTruncate._native = _native;

    $.fn.textTruncate.defaults = {
        multiline: false,
        tail: "&hellip;",
        tooltip: true,
        wrap: "word"
    };

})(jQuery);

//
// RecipeBoxModule\AR.RBM.js
//
/// <reference path="../Intellisense.js" />
// Recipe box module stuff //

AR.RBM = {

    SetInitial: function () {
        var tabName = getCookie('rbm');

        switch (tabName) {
            case 'tabRecipe':
                AR.RBM.ShowTab('myarRecipe', $('#' + tabName).parent());
                AR.RBM.Truncate('recipe');
                break;
            case 'tabMenu':
                AR.RBM.ShowTab('myarMenu', $('#' + tabName).parent());
                AR.RBM.Truncate('menu');
                break;
            case 'tabShoppingList':
                AR.RBM.ShowTab('myarShoppingList', $('#' + tabName).parent());
                AR.RBM.TruncateSL();
                break;
            default: //MP1.2 - make Menus the default tab for anon users
                if (AR.VisitorInfo.IsRecognized() == false) {
                    AR.RBM.ShowTab('myarMenu', $('#tabMenu').parent());
                    AR.RBM.Truncate('menu');
                }
                break;
        }
    },

    Truncate: function (div) {
        $('div.recent-' + div + ' p.plaincharacterwrap a').textTruncate({ multiline: true, height: 35 });
    },

    TruncateSL: function () {
        $("p.shopListTitleP a").textTruncate({ width: 140 });
    },

    ShowTab: function (tabName, tab) {
        if (AR.RBM.IsVisible(tabName)) {
            return;
        }
        AR.RBM.HideAllTabs();
        $('#' + tabName).show();
        $('#activeTab').text(tabName);
        $(tab).addClass('on');
    },

    ToggleARTabs: function (e) {
        var tabName = $(e.target).attr('id');
        switch (tabName) {
            case 'tabRecipe':
                AR.RBM.ShowTab('myarRecipe', $(e.target).parent());
                AR.RBM.Truncate('recipe');
                break;
            case 'tabMenu':
                AR.RBM.ShowTab('myarMenu', $(e.target).parent());
                AR.RBM.Truncate('menu');
                break;
            case 'tabShoppingList':
                AR.RBM.ShowTab('myarShoppingList', $(e.target).parent());
                AR.RBM.TruncateSL();
                break;
        }
        setCookie('rbm', tabName, 1);

    },

    HideAllTabs: function () {
        $('.myar-wrap').hide();
        $('.myar-tab').parent().removeClass('on');
    },

    IsVisible: function (tab) {
        return $('#' + tab).is(':visible');
    },

    PerformHover: function (container, open, recent, func) {
        open.stop(true, true);
        if (container.innerWidth() == 58) {
            recent.die('mouseover', func);
            open.animate({ width: '58px' }, 300).removeClass('open');
            container.addClass('open').animate({ width: '174px' }, 300, function callback() {
                recent.live('mouseover', func);
            });
        }
    },

    Hover: function () {
        AR.RBM.PerformHover($(this), $('.recent-recipe.open'), $('.recent-recipe'), AR.RBM.Hover);
    },

    HoverMenu: function () {
        AR.RBM.PerformHover($(this), $('.recent-menu.open'), $('.recent-menu'), AR.RBM.HoverMenu);
    },

    HideNoItems: function (rb, context) {
        if (rb.is(':hidden')) {
            rb.slideDown(300);
            $('.noItems', context).slideUp(300);
        }
    },

    CloneTarget: function (baseClass) {
        $(baseClass + ':nth-child(1)').clone(true).insertAfter(baseClass + ':nth-child(1)').show();
        var clone = $(baseClass + ':nth-child(2)').removeClass('hidden');
        $(baseClass + ':nth-child(5)').remove();
        $(baseClass + '.open').animate({ width: '58px' }, 300).removeClass('open');
        clone.animate({ width: '174px' }, 300).addClass('open');
        return clone;
    },

    Add: function (title, url, rating) {
        $('#tabRecipe').click();
        var rb = $('.hasItem', $('#myarRecipe'));
        if (rb) {
            AR.RBM.HideNoItems(rb, '#myarRecipe');

            var clone = AR.RBM.CloneTarget('.recent-recipe');
            $('#imgStars', clone).hide();
            var img = AR.RBM.GetRecipeImage();
            var newImage = img.clone(true).insertAfter(img);
            var imgPos = img.offset();
            var newPos = clone.offset();

            AR.RBM.Animate(newImage, imgPos.top, imgPos.left, newPos.top, newPos.left);

            AR.RBM.LoadRecipe(img, clone, url, title, rating);

            var count = parseInt($('#rbmRecipeCount').text());
            $('#rbmRecipeCount').text(count + 1);
        }
    },

    LoadRecipe: function (img, clone, url, title, rating) {
        var t = $.trim(title);
        $('.cloneImage', clone).attr('src', img.attr('src'));
        $('.cloneImage', clone).attr('alt', AR.Utils.HtmlEncode(t)).attr("title", AR.Utils.HtmlEncode(t));
        $('#imgLink', clone).attr('href', url);
        $('p > #lnkRecipeTitle', clone).attr('href', url).text(t).textTruncate({ multiline: true, height: 35 });
        var imgStarUrl = AR.ClientUrlProvider.GetRecipeBoxListViewRatingImage(rating);
        $('#imgStars', clone).attr('src', imgStarUrl).attr('alt', rating + ' stars').attr('title', rating + ' stars').show();
    },

    AddMenu: function (menuTitle, menuUrl) {
        $('#tabMenu').click();
        var rb = $('.hasItem', $('#myarMenu'));
        if (rb) {
            AR.RBM.HideNoItems(rb, '#myarMenu');

            var count = parseInt($('#rbmMenuCount').text());
            $('#rbmMenuCount').text(count + 1);
            var mealCount = parseInt($('#mealCount').text());
            var recipeCount = parseInt($('#recipeCount').text());

            var imageUrl;

            var img = AR.RBM.GetMealImage();
            if (img.length > 0) {
                imageUrl = img.attr('src');
            } else {
                imageUrl = AR.ClientUrlProvider.ResolveImageUrl("/ar/myar/menuplanner/detail/no_image_menu_icon.png");
            }

            AR.RBM.PerformMenuAdd(img, menuTitle, menuUrl, imageUrl, mealCount, recipeCount);
        }
    },

    PerformMenuAdd: function (img, menuTitle, menuUrl, imageUrl, mealCount, mealItemCount) {
        var clone = AR.RBM.CloneTarget('.recent-menu');
        $('.rb-menu-added', clone).hide();

        if (img.length > 0) {
            var newImage = img.clone(true).insertAfter(img);
            var imgPos = img.position();
            var newPos = clone.offset();
            var animateTop, animateLeft, newPos;

            if (AR.ServerSideData.Data.IsRecipe) {
                animateTop = newPos.top;
                animateLeft = newPos.left;
            }
            else {
                animateTop = newPos.top - img.offset().top;
                animateLeft = newPos.left - img.offset().left;
            }
            var diff = AR.RBM.MessageLabelActive();
            if (diff > 0) {
                imgPos.top = imgPos.top - diff;
            }

            AR.RBM.Animate(newImage, imgPos.top, imgPos.left, animateTop, animateLeft);
        }

        AR.RBM.LoadMenu(clone, imageUrl, menuTitle, menuUrl, mealCount, mealItemCount, newImage);
    },

    MessageLabelActive: function () {
        return $('#msgLabel').height();
    },

    LoadMenu: function (clone, imageUrl, menuTitle, menuUrl, mealCount, mealItemCount, newImage) {
        var t = $.trim(menuTitle);
        $('p > #lnkMenuTitle', clone).attr('href', menuUrl).text(t).textTruncate({ multiline: true, height: 35 });
        $('.cloneImage', clone).attr('src', imageUrl).attr('alt', t);
        $('#imgMenuLink', clone).attr('href', menuUrl);
        $('#spanMealCount', clone).text(mealCount + " meals ");
        $('#spanRecipeCount', clone).text(mealItemCount + " recipes ");
        $('.rb-menu-added', clone).show();
    },

    Animate: function (newImage, startTop, startLeft, endTop, endLeft) {
        newImage.css({ position: 'absolute', top: startTop, left: startLeft, zIndex: '5000' });

        newImage.animate({ top: endTop, left: endLeft, width: '50px', height: '50px', opacity: '.2' }, 800, function callback() {
            newImage.remove();
        });
    },

    IncrementMenuCount: function () {
        var menuCountElement = $.find("#rbmMenuCount");
        var menuCount = parseInt($(menuCountElement).text());
        menuCount += 1;
        $(menuCountElement).text(menuCount);
    },

    MenuExists: function (sharedItemID) {
        var exists = $('.recent-menu a[href*="' + sharedItemID + '"]').length;
    },

    AddToMenu: function (menu) {
        $('#tabMenu').click();
        if (menu) {
            var rb = $('.hasItem');
            if (rb) {
                var img = AR.RBM.GetRecipeImage();
                AR.RBM.HideNoItems(rb);
                var existingMenu = $('.recent-menu a[href*="' + menu.SharedItemID + '"]'); // find the menu we are adding to by menu ID
                if (existingMenu.length) {
                    existingMenu.parent().addClass('open');
                    var img = $('.rec-image');
                    $('.rb-menu-added', existingMenu).hide();
                    var newImage = img.clone(true).insertAfter(img);
                    var imgPos = img.offset();
                    var newPos = existingMenu.offset();
                    var diff = AR.RBM.MessageLabelActive();
                    if (diff > 0) {
                        imgPos.top = imgPos.top - diff;
                    }
                    AR.RBM.Animate(newImage, imgPos.top, imgPos.left, newPos.top, newPos.left);

                    $(existingMenu.parent()).find('#spanMealCount').text(menu.MealCount + " meals ");
                    $(existingMenu.parent()).find('#spanRecipeCount').text(menu.MealItemCount + " recipes ");

                }
                else {
                    AR.RBM.PerformMenuAdd(img, menu.Title, menu.Description, menu.ListItemRecipePhotoURL, menu.MealCount, menu.MealItemCount);
                }
            }
        }
    },

    AddToList: function (shoppingListID, shoppingListTitle) {
        $('#tabShoppingList').click();

        if (shoppingListID) {
            var rb = $('.hasItem', $('#myarShoppingList'));
            if (rb) {
                AR.RBM.HideNoItems(rb, '#myarShoppingList');
                var SLID = $('.hidSLID').val();
                if (SLID != shoppingListID) {
                    // swap out the data
                    $('.shoppingListRBM li').remove();
                    $('.shopListTitleP > a').attr('href', AR.ClientUrlProvider.ResolveUrl('~/My/ShoppingList/Default.aspx?SID=' + shoppingListID)).text(shoppingListTitle);
                }

                var img;
                var titles = new Array();

                var newImageTopPos;
                var newImageLeftPos;
                var imgTopPos;
                var imgLeftPos;
                var newPos = $('#divRecentShoppingListItems').offset();

                if (AR.ServerSideData.Data.IsMenu) {
                    img = AR.RBM.GetMealImage();

                    $('.titleurl[disabled!="disabled"]').each(function () {
                        titles.push($(this).text());
                    });

                    imgTopPos = img.position().top;
                    imgLeftPos = img.position().left;
                    newImageTopPos = newPos.top - img.offset().top;
                    newImageLeftPos = newPos.left - img.offset().left;
                }
                else {
                    img = AR.RBM.GetRecipeImage();
                    titles.push($('#itemTitle').text());

                    imgTopPos = img.offset().top;
                    imgLeftPos = img.offset().left;
                    newImageTopPos = newPos.top;
                    newImageLeftPos = newPos.left;
                }

                if (img.length > 0) {

                    var newImage = img.clone(true).insertAfter(img);

                    var diff = AR.RBM.MessageLabelActive();
                    if (diff > 0) {
                        imgTopPos = imgTopPos - diff;
                    }

                    AR.RBM.Animate(newImage, imgTopPos, imgLeftPos, newImageTopPos, newImageLeftPos);
                }

                titles.reverse();

                jQuery.each(titles, function () {
                    AR.RBM.AddItemToShoppingList($.trim(this));
                });
            }
        }
    },

    AddItemToShoppingList: function (title) {
        var ul = $('.shoppingListRBM');
        var canAdd = true;
        $('li', ul).each(function (i, item) {
            if ($('span', item).text() == title) {
                canAdd = false;
            }
        });
        if (canAdd == true) {
            var count = ul.children("li").length;
            if (count > 2) {
                $("li:last-child", ul).remove();
            }
            ul.prepend('<li class="ellipsis">' + title + '</li>');
        }
    },

    GetRecipeImage: function () {
        return $('.rec-image');
    },

    GetMealImage: function () {
        return $('.isMainMenuPhoto img');
    }
};

$(document).ready(function () {

    $('.recent-recipe').live('mouseover', AR.RBM.Hover);
    $('.recent-menu').live('mouseover', AR.RBM.HoverMenu);
    $('.myar-tab').click(function (e) { AR.RBM.ToggleARTabs(e); });
});

//
// lib\jqote2\jquery.jqote2.js
//
/*
* jQote2 - client-side Javascript templating engine
* Copyright (C) 2010, aefxx
* http://aefxx.com/
*
* Dual licensed under the WTFPL v2 or MIT (X11) licenses
* WTFPL v2 Copyright (C) 2004, Sam Hocevar
*
* Date: Thu, Oct 21st, 2010
* Version: 0.9.7
*/
(function ($) {
    var JQOTE2_TMPL_UNDEF_ERROR = 'UndefinedTemplateError',
        JQOTE2_TMPL_COMP_ERROR = 'TemplateCompilationError',
        JQOTE2_TMPL_EXEC_ERROR = 'TemplateExecutionError';

    var ARR = '[object Array]',
        STR = '[object String]',
        FUNC = '[object Function]';

    var n = 1, tag = '%',
        qreg = /^[^<]*(<[\w\W]+>)[^>]*$/,
        type_of = Object.prototype.toString;

    function raise(error, ext) {
        throw ($.extend(error, ext), error);
    }

    function dotted_ns(fn) {
        var ns = [];

        if (type_of.call(fn) !== ARR) return false;

        for (var i = 0, l = fn.length; i < l; i++)
            ns[i] = fn[i].jqote_id;

        return ns.length ?
            ns.sort().join('.').replace(/(\b\d+\b)\.(?:\1(\.|$))+/g, '$1$2') : false;
    }

    function lambda(tmpl, t) {
        var f, fn = [], t = t || tag,
            type = type_of.call(tmpl);

        if (type === FUNC)
            return tmpl.jqote_id ? [tmpl] : false;

        if (type !== ARR)
            return [$.jqotec(tmpl, t)];

        if (type === ARR)
            for (var i = 0, l = tmpl.length; i < l; i++)
                if (f = lambda(tmpl[i], t)) fn.push(f[0]);

        return fn.length ? fn : false;
    }

    $.fn.extend({
        jqote: function (data, t) {
            var data = type_of.call(data) === ARR ? data : [data],
                dom = '';

            this.each(function (i) {
                var fn = $.jqotec(this, t);

                for (var j = 0; j < data.length; j++)
                    dom += fn.call(data[j], i, j, data, fn);
            });

            return dom;
        }
    });

    $.each({ app: 'append', pre: 'prepend', sub: 'html' }, function (name, method) {
        $.fn['jqote' + name] = function (elem, data, t) {
            var ns, regexp, str = $.jqote(elem, data, t),
                $$ = !qreg.test(str) ?
                    function (str) { return $(document.createTextNode(str)); } : $;

            if (!!(ns = dotted_ns(lambda(elem))))
                regexp = new RegExp('(^|\\.)' + ns.split('.').join('\\.(.*)?') + '(\\.|$)');

            return this.each(function () {
                var dom = $$(str);

                $(this)[method](dom);

                (dom[0].nodeType === 3 ?
                    $(this) : dom).trigger('jqote.' + name, [dom, regexp]);
            });
        };
    });

    $.extend({
        jqote: function (elem, data, t) {
            var str = '', t = t || tag,
                fn = lambda(elem);

            if (fn === false)
                raise(new Error('Empty or undefined template passed to $.jqote'), { type: JQOTE2_TMPL_UNDEF_ERROR });

            data = type_of.call(data) !== ARR ?
                [data] : data;

            for (var i = 0, l = fn.length; i < l; i++)
                for (var j = 0; j < data.length; j++)
                    str += fn[i].call(data[j], i, j, data, fn[i]);

            return str;
        },

        jqotec: function (template, t) {
            var cache, elem, tmpl, t = t || tag,
                type = type_of.call(template);

            if (type === STR && qreg.test(template)) {
                elem = tmpl = template;

                if (cache = $.jqotecache[template]) return cache;
            } else {
                elem = type === STR || template.nodeType ?
                    $(template) : template instanceof jQuery ?
                        template : null;

                if (!elem[0] || !(tmpl = elem[0].innerHTML) && !(tmpl = elem.text()))
                    raise(new Error('Empty or undefined template passed to $.jqotec'), { type: JQOTE2_TMPL_UNDEF_ERROR });

                if (cache = $.jqotecache[$.data(elem[0], 'jqote_id')]) return cache;
            }

            var str = '', index,
                arr = tmpl.replace(/\s*<!\[CDATA\[\s*|\s*\]\]>\s*|[\r\n\t]/g, '')
                    .split('<' + t).join(t + '>\x1b')
                        .split(t + '>');

            for (var m = 0, l = arr.length; m < l; m++)
                str += arr[m].charAt(0) !== '\x1b' ?
                    "out+='" + arr[m].replace(/(\\|["'])/g, '\\$1') + "'" : (arr[m].charAt(1) === '=' ?
                        ';out+=(' + arr[m].substr(2) + ');' : (arr[m].charAt(1) === '!' ?
                            ';out+=$.jqotenc((' + arr[m].substr(2) + '));' : ';' + arr[m].substr(1)));

            str = 'try{' +
                ('var out="";' + str + ';return out;')
                    .split("out+='';").join('')
                        .split('var out="";out+=').join('var out=') +
                '}catch(e){e.type="' + JQOTE2_TMPL_EXEC_ERROR + '";e.args=arguments;e.template=arguments.callee.toString();throw e;}';

            try {
                var fn = new Function('i, j, data, fn', str);
            } catch (e) { raise(e, { type: JQOTE2_TMPL_COMP_ERROR }); }

            index = elem instanceof jQuery ?
                $.data(elem[0], 'jqote_id', n) : elem;

            return $.jqotecache[index] = (fn.jqote_id = n++, fn);
        },

        jqotefn: function (elem) {
            var type = type_of.call(elem),
                index = type === STR && qreg.test(elem) ?
                    elem : $.data($(elem)[0], 'jqote_id');

            return $.jqotecache[index] || false;
        },

        jqotetag: function (str) {
            if (type_of.call(str) === STR) tag = str;
        },

        jqotenc: function (str) {
            return str.toString()
                    .replace(/&(?!\w+;)/g, '&#38;')
                        .split('<').join('&#60;').split('>').join('&#62;')
                            .split('"').join('&#34;').split("'").join('&#39;');
        },

        jqotecache: {}
    });

    $.event.special.jqote = {
        add: function (obj) {
            var ns, handler = obj.handler,
                data = !obj.data ?
                    [] : type_of.call(obj.data) !== ARR ?
                        [obj.data] : obj.data;

            if (!obj.namespace) obj.namespace = 'app.pre.sub';
            if (!data.length || !(ns = dotted_ns(lambda(data)))) return;

            obj.handler = function (event, dom, regexp) {
                return !regexp || regexp.test(ns) ?
                    handler.apply(this, [event, dom]) : null;
            };
        }
    };
})(jQuery);
//
// Navigation\PrimaryNav.js
//

/// <reference path="../Intellisense.js" />


//Primary Navigation
AR.PrimaryNav = {
    _hoverTimer: 0, //stores an ID (int) that is returned from a call to setTimeout, used to call clearTimeout
    _hasHover: false, //indicates one of the tabs is open, used to enable/disable time delay when opeing subnavs
    _initFinished: 0,
    _loadFinished: 0,
    OnInit: function () {
        this.Reset();
        this.WireTabEvents();
        this._initFinished = 1;
    },
    OnLoad: function () {
        this.WireMerchBlocks();
        this.WireLinkEvents();
        this._loadFinished = 1;
    },
    DelayEnabled: function () {
        return !this._hasHover;
    },
    Reset: function () {
        $(".sub_nav_menu").hide(); //hide all subnavs
        $("a.trigger").removeClass("has_hover"); //clear all tabs of hover state
        this._hasHover = false;
    },
    WireLinkEvents: function () {
        $('#lnkMyAR_Login_Anon').click(function (e) {
            AR.Analytics.RecordInternalSource("PN_7.2.1_SN.Login");
            AR.PrimaryNav.HideSubNavListItem($(".tabSeven"));
        });

        $('.linkShowsRegister').click(function (e) {
            AR.PrimaryNav.HideSubNavListItem($(".tabSeven"));
        });

        $('.linkRequiresLogin').click(function (e) {
            AR.PrimaryNav.HideSubNavListItem($(this).parents(".tabContainer"));
        });

        $('.linkRequiresSupportingMembership').click(function (e) {
            AR.PrimaryNav.HideSubNavListItem($(this).parents(".tabContainer"));
        });

        $('.linkLaunchesVideoLayer').click(function (e) {
            AR.PrimaryNav.HideSubNavListItem($(this).parents(".tabContainer"));
        });

        $('.lnkOffSite').click(function (e) {
            var lnk = $(this);
           
            if (lnk.attr("data-ar-prop24") != null) {
                e.preventDefault();
                e.stopImmediatePropagation();

                AR.Analytics.RecordInternalSource(lnk.attr("data-ar-prop24"));
                                
                (lnk.attr("target") == "_self") ?
                    window.location = lnk.attr("href") : window.open(lnk.attr("href"));
            }
        });
    },
    WireMerchBlocks: function () {
        //make entire merch block hot
        $(".topnavmerch").click(function (e) {
            AR.PrimaryNav.HideSubNavListItem($(this).parents(".tabContainer"));
            var anchor = $(this).find("a");
            if (anchor) {
                if (anchor.is(".linkRequiresLogin")) {
                    AR.DialogLinker.OnLinkRequiringLogin(e, anchor);
                }
                else if (anchor.is(".linkRequiresSupportingMembership")) {
                    AR.DialogLinker.OnLinkRequiringSupportingMembership(e, anchor);
                }
                else {
                    window.location = anchor.attr("href"); return false;
                }
            }
        });
    },
    WireTabEvents: function () {
        var that = this;
        if (!AR.IsMobileDevice()) {
            //on tab hover
            $("a.trigger").mouseenter(function () {
                that.TabOnHover($(this));
            });
            //on tab hover off
            $("a.trigger").mouseleave(function () {
                //kill timer so browser doesn't become unresponsive.
                clearTimeout(AR.PrimaryNav._hoverTimer);
            });
            //on sub nav hover off
            $(".tabContainer").mouseleave(function () {
                that.HideSubNavListItem($(this));
            });

            //clear global hover state to renable time delay
            $("ul#topNavUL").mouseleave(function () {
                AR.PrimaryNav._hasHover = false;
            });
        }
        else {
            // for mobile devices toggle subnav's on tab click and
            // disable tab link
            $("a.trigger").click(function (e) {
                e.preventDefault();
                e.stopImmediatePropagation();
                if ($(this).is(".has_hover") == false) {
                    AR.PrimaryNav.Reset(); //close any open subnavs
                    AR.PrimaryNav.SubNavLoadImages($(this)); //lazy load
                    AR.PrimaryNav.ShowSubNav($(this));
                }
                else {
                    AR.PrimaryNav.HideSubNavAnchor($(this));
                }
            });
        }
    },
    TabOnHover: function (anchor) {
        //open sub nav menu after .5 seconds delay, unless any tab
        //already is in the hover state, then we don't delay.  
        if (anchor.is(".has_hover") == false) { //prevent unecessary timer starts
            AR.PrimaryNav.SubNavLoadImages(anchor); //lazy load images

            AR.PrimaryNav._hoverTimer =
                    setTimeout(function () { AR.PrimaryNav.ShowSubNav(anchor); },
                    (AR.PrimaryNav.DelayEnabled()) ? 250 : 0);
        }
    },
    HideSubNavListItem: function (listItem) { //hide sub nav using the li.tabContainer
        listItem.find("a.trigger").removeClass("has_hover");
        listItem.children(".sub_nav_menu").hide();
        AR.ZIndexOverride.RevertOverrides("primarynav");
    },
    HideSubNavAnchor: function (anchor) { //hid the sub nav using the a.trigger
        anchor.removeClass("has_hover");
        var tabListItem = anchor.parents(".tabContainer");
        tabListItem.children(".sub_nav_menu").hide();
        AR.ZIndexOverride.RevertOverrides("primarynav");
    },
    ShowSubNav: function (anchor) {
        anchor.addClass("has_hover");
        var tabListItem = anchor.parents(".tabContainer");
        tabListItem.children(".sub_nav_menu").show();
        AR.PrimaryNav._hasHover = true; //disable time delay
        AR.ZIndexOverride.ApplyOverride(anchor.next(".sub_nav_menu"), "primarynav");
    },
    SubNavLoadImages: function (anchor) {
        //lazy load primary nav images
        anchor.parent().find(".imgTopNavFeat").each(function () {
            //if the image is still pointing to the spacer, set the src property
            var img = $(this);
            if (img.attr("src").indexOf("spacer.gif") != -1) {
                img.attr("src", img.attr("data-ar-src"));
            }
        });
    }

};


String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }

function DoSearch(linkClicked) {
    var canSearch = (typeof (linkClicked) != undefined) || !($('.dirtyform')) || !($('.dirtyform').isChanged());
    if (canSearch === true) {
        var searchID = '';
        var url = '';

        if (linkClicked == 'advanced') {
            url = '/Search/Recipes-Advanced.aspx';
        }
        else if (linkClicked == 'glossary') {
            url = '/Search/Glossary.aspx';
        }
        else if (linkClicked == 'collection') {
            url = '/Search/Collection.aspx';
        }
        else if ($(".search-link-recipes", ".searchtxt").hasClass("chosen")) {
            url = '/Search/Recipes.aspx';
            searchID = 'Recipe';
        }
        else if ($(".search-link-ingredients", ".searchtxt").hasClass("chosen")) {
            url = '/Search/Ingredients.aspx';
            searchID = 'Ingredient';
        }
        else if ($(".search-link-articles", ".searchtxt").hasClass("chosen")) {
            url = '/Search/Articles.aspx';
            searchID = 'Article';
        }
        url = AR.ClientUrlProvider.ResolveUrl(url);

        var searchTxt = $(".searchBox");
        if (searchTxt.length > 0) {
            var sVal = searchTxt.val().trim();
            var defaultText = searchTxt.data("stored").defaultText;
            if (sVal != '' && sVal != defaultText) {
                if (searchID == 'Ingredient') {
                    var iWanted = 1;
                    var iUnwanted = 1;
                    url += '?WithTerm=&SearchIn=All';
                    termArray = sVal.split(',');
                    for (i = 1; i < termArray.length + 1; i++) {
                        var qVal = termArray[i - 1].trim();
                        if (qVal.charAt(0) == '-') {
                            qVal = qVal.substring(1, qVal.length);
                            url += '&Unwanted' + iUnwanted + '=' + encodeMyHtml(qVal);
                            iUnwanted++;
                        }
                        else {
                            url += '&Wanted' + iWanted + '=' + encodeMyHtml(qVal);
                            iWanted++;
                        }
                    }
                }
                else {
                    sVal = sVal.replace(/:/g, ' ');
                    url += '?WithTerm=' + encodeMyHtml(sVal);
                }
                location.href = url;
                return false;
            }
            else {
                if (searchID == "Recipe" || searchID == "Article") {
                    //don't follow the link if Recipes or Articles was clicked
                    return false;
                }
                else {
                    return true;
                }
            }
        }
        return true;
    }
    else {
        return false;
    }
}
function moveSelectedSearch(link) {
    //set all to blue
    $(".search_link").css("color", "#0066CC").removeClass("chosen");

    //set selected one to gray
    link.css("color", "#333333").addClass("chosen");

    var ret = DoSearch();
    if (ret == false) {
        document.aspnetForm.ctl00_txtSearch.focus();
    }
    return ret;
}
function encodeMyHtml(htmlToEncode) {
    encodedHtml = escape(htmlToEncode);
    encodedHtml = encodedHtml.replace(/\//g, "%2F");
    encodedHtml = encodedHtml.replace(/\?/g, "%3F");
    encodedHtml = encodedHtml.replace(/=/g, "%3D");
    encodedHtml = encodedHtml.replace(/&/g, "%26");
    encodedHtml = encodedHtml.replace(/@/g, "%40");
    encodedHtml = encodedHtml.replace(/[<]/g, "");
    encodedHtml = encodedHtml.replace(/[>]/g, "");
    return encodedHtml;
}


