/*!
* jQuery JavaScript Library v1.3.2
* http://jquery.com/
*
* Copyright (c) 2009 John Resig
* Dual licensed under the MIT and GPL licenses.
* http://docs.jquery.com/License
*
* Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
* Revision: 6246
*/
(function() {

    var 
    // Will speed up references to window, and allows munging its name.
	window = this,
    // Will speed up references to undefined, and allows munging its name.
	undefined,
    // Map over jQuery in case of overwrite
	_jQuery = window.jQuery,
    // Map over the $ in case of overwrite
	_$ = window.$,

	jQuery = window.jQuery = window.$ = function(selector, context) {
	    // The jQuery object is actually just the init constructor 'enhanced'
	    return new jQuery.fn.init(selector, context);
	},

    // A simple way to check for HTML strings or ID strings
    // (both of which we optimize for)
	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
    // Is it a simple selector
	isSimple = /^.[^:#\[\.,]*$/;

    jQuery.fn = jQuery.prototype = {
        init: function(selector, context) {
            // Make sure that a selection was provided
            selector = selector || document;

            // Handle $(DOMElement)
            if (selector.nodeType) {
                this[0] = selector;
                this.length = 1;
                this.context = selector;
                return this;
            }
            // Handle HTML strings
            if (typeof selector === "string") {
                // Are we dealing with HTML string or an ID?
                var 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])
                        selector = jQuery.clean([match[1]], context);

                    // HANDLE: $("#id")
                    else {
                        var elem = document.getElementById(match[3]);

                        // Handle the case where IE and Opera return items
                        // by name instead of ID
                        if (elem && elem.id != match[3])
                            return jQuery().find(selector);

                        // Otherwise, we inject the element directly into the jQuery object
                        var ret = jQuery(elem || []);
                        ret.context = document;
                        ret.selector = selector;
                        return ret;
                    }

                    // HANDLE: $(expr, [context])
                    // (which is just equivalent to: $(content).find(expr)
                } else
                    return jQuery(context).find(selector);

                // HANDLE: $(function)
                // Shortcut for document ready
            } else if (jQuery.isFunction(selector))
                return jQuery(document).ready(selector);

            // Make sure that old selector state is passed along
            if (selector.selector && selector.context) {
                this.selector = selector.selector;
                this.context = selector.context;
            }

            return this.setArray(jQuery.isArray(selector) ?
			selector :
			jQuery.makeArray(selector));
        },

        // Start with an empty selector
        selector: "",

        // The current version of jQuery being used
        jquery: "1.3.2",

        // The number of elements contained in the matched element set
        size: function() {
            return this.length;
        },

        // 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 === undefined ?

            // Return a 'clean' array
			Array.prototype.slice.call(this) :

            // Return just the object
			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(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;
        },

        // Force the current matched set of elements to become
        // the specified array of elements (destroying the stack in the process)
        // You should use pushStack() in order to do this, but maintain the stack
        setArray: function(elems) {
            // Resetting the length to 0, then using the native Array push
            // is a super-fast way to populate an object with array-like properties
            this.length = 0;
            Array.prototype.push.apply(this, elems);

            return this;
        },

        // 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);
        },

        // Determine the position of an element within
        // the matched set of elements
        index: function(elem) {
            // Locate the position of the desired element
            return jQuery.inArray(
            // If it receives a jQuery object, the first element is used
			elem && elem.jquery ? elem[0] : elem
		, this);
        },

        attr: function(name, value, type) {
            var options = name;

            // Look for the case where we're accessing a style value
            if (typeof name === "string")
                if (value === undefined)
                return this[0] && jQuery[type || "attr"](this[0], name);

            else {
                options = {};
                options[name] = value;
            }

            // Check to see if we're setting style values
            return this.each(function(i) {
                // Set all the styles
                for (name in options)
                    jQuery.attr(
					type ?
						this.style :
						this,
					name, jQuery.prop(this, options[name], type, i, name)
				);
            });
        },

        css: function(key, value) {
            // ignore negative width and height values
            if ((key == 'width' || key == 'height') && parseFloat(value) < 0)
                value = undefined;
            return this.attr(key, value, "curCSS");
        },

        text: function(text) {
            if (typeof text !== "object" && text != null)
                return this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(text));

            var ret = "";

            jQuery.each(text || this, function() {
                jQuery.each(this.childNodes, function() {
                    if (this.nodeType != 8)
                        ret += this.nodeType != 1 ?
						this.nodeValue :
						jQuery.fn.text([this]);
                });
            });

            return ret;
        },

        wrapAll: function(html) {
            if (this[0]) {
                // The elements to wrap the target around
                var wrap = jQuery(html, this[0].ownerDocument).clone();

                if (this[0].parentNode)
                    wrap.insertBefore(this[0]);

                wrap.map(function() {
                    var elem = this;

                    while (elem.firstChild)
                        elem = elem.firstChild;

                    return elem;
                }).append(this);
            }

            return this;
        },

        wrapInner: function(html) {
            return this.each(function() {
                jQuery(this).contents().wrapAll(html);
            });
        },

        wrap: function(html) {
            return this.each(function() {
                jQuery(this).wrapAll(html);
            });
        },

        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() {
            return this.domManip(arguments, false, function(elem) {
                this.parentNode.insertBefore(elem, this);
            });
        },

        after: function() {
            return this.domManip(arguments, false, function(elem) {
                this.parentNode.insertBefore(elem, this.nextSibling);
            });
        },

        end: function() {
            return this.prevObject || jQuery([]);
        },

        // For internal use only.
        // Behaves like an Array's method, not like a jQuery method.
        push: [].push,
        sort: [].sort,
        splice: [].splice,

        find: function(selector) {
            if (this.length === 1) {
                var ret = this.pushStack([], "find", selector);
                ret.length = 0;
                jQuery.find(selector, this[0], ret);
                return ret;
            } else {
                return this.pushStack(jQuery.unique(jQuery.map(this, function(elem) {
                    return jQuery.find(selector, elem);
                })), "find", selector);
            }
        },

        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;
                    if (!html) {
                        var div = this.ownerDocument.createElement("div");
                        div.appendChild(this.cloneNode(true));
                        html = div.innerHTML;
                    }

                    return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
                } else
                    return this.cloneNode(true);
            });

            // Copy the events from the original to the clone
            if (events === true) {
                var orig = this.find("*").andSelf(), i = 0;

                ret.find("*").andSelf().each(function() {
                    if (this.nodeName !== orig[i].nodeName)
                        return;

                    var events = jQuery.data(orig[i], "events");

                    for (var type in events) {
                        for (var handler in events[type]) {
                            jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
                        }
                    }

                    i++;
                });
            }

            // Return the cloned set
            return ret;
        },

        filter: function(selector) {
            return this.pushStack(
			jQuery.isFunction(selector) &&
			jQuery.grep(this, function(elem, i) {
			    return selector.call(elem, i);
			}) ||

			jQuery.multiFilter(selector, jQuery.grep(this, function(elem) {
			    return elem.nodeType === 1;
			})), "filter", selector);
        },

        closest: function(selector) {
            var pos = jQuery.expr.match.POS.test(selector) ? jQuery(selector) : null,
			closer = 0;

            return this.map(function() {
                var cur = this;
                while (cur && cur.ownerDocument) {
                    if (pos ? pos.index(cur) > -1 : jQuery(cur).is(selector)) {
                        jQuery.data(cur, "closest", closer);
                        return cur;
                    }
                    cur = cur.parentNode;
                    closer++;
                }
            });
        },

        not: function(selector) {
            if (typeof selector === "string")
            // test special case where just one selector is passed in
                if (isSimple.test(selector))
                return this.pushStack(jQuery.multiFilter(selector, this, true), "not", selector);
            else
                selector = jQuery.multiFilter(selector, this);

            var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
            return this.filter(function() {
                return isArrayLike ? jQuery.inArray(this, selector) < 0 : this != selector;
            });
        },

        add: function(selector) {
            return this.pushStack(jQuery.unique(jQuery.merge(
			this.get(),
			typeof selector === "string" ?
				jQuery(selector) :
				jQuery.makeArray(selector)
		)));
        },

        is: function(selector) {
            return !!selector && jQuery.multiFilter(selector, this).length > 0;
        },

        hasClass: function(selector) {
            return !!selector && this.is("." + selector);
        },

        val: function(value) {
            if (value === undefined) {
                var elem = this[0];

                if (elem) {
                    if (jQuery.nodeName(elem, 'option'))
                        return (elem.attributes.value || {}).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];

                            if (option.selected) {
                                // Get the specifc 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;
                    }

                    // Everything else, we just grab the value
                    return (elem.value || "").replace(/\r/g, "");

                }

                return undefined;
            }

            if (typeof value === "number")
                value += '';

            return this.each(function() {
                if (this.nodeType != 1)
                    return;

                if (jQuery.isArray(value) && /radio|checkbox/.test(this.type))
                    this.checked = (jQuery.inArray(this.value, value) >= 0 ||
					jQuery.inArray(this.name, value) >= 0);

                else if (jQuery.nodeName(this, "select")) {
                    var values = jQuery.makeArray(value);

                    jQuery("option", this).each(function() {
                        this.selected = (jQuery.inArray(this.value, values) >= 0 ||
						jQuery.inArray(this.text, values) >= 0);
                    });

                    if (!values.length)
                        this.selectedIndex = -1;

                } else
                    this.value = value;
            });
        },

        html: function(value) {
            return value === undefined ?
			(this[0] ?
				this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
				null) :
			this.empty().append(value);
        },

        replaceWith: function(value) {
            return this.after(value).remove();
        },

        eq: function(i) {
            return this.slice(i, +i + 1);
        },

        slice: function() {
            return this.pushStack(Array.prototype.slice.apply(this, arguments),
			"slice", Array.prototype.slice.call(arguments).join(","));
        },

        map: function(callback) {
            return this.pushStack(jQuery.map(this, function(elem, i) {
                return callback.call(elem, i, elem);
            }));
        },

        andSelf: function() {
            return this.add(this.prevObject);
        },

        domManip: function(args, table, callback) {
            if (this[0]) {
                var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
				scripts = jQuery.clean(args, (this[0].ownerDocument || this[0]), fragment),
				first = fragment.firstChild;

                if (first)
                    for (var i = 0, l = this.length; i < l; i++)
                    callback.call(root(this[i], first), this.length > 1 || i > 0 ?
							fragment.cloneNode(true) : fragment);

                if (scripts)
                    jQuery.each(scripts, evalScript);
            }

            return this;

            function root(elem, cur) {
                return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
				(elem.getElementsByTagName("tbody")[0] ||
				elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
				elem;
            }
        }
    };

    // Give the init function the jQuery prototype for later instantiation
    jQuery.fn.init.prototype = jQuery.fn;

    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);
    }

    function now() {
        return +new Date;
    }

    jQuery.extend = jQuery.fn.extend = function() {
        // copy reference to target object
        var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

        // 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 (var name in options) {
            var src = target[name], copy = options[name];

            // Prevent never-ending loop
            if (target === copy)
                continue;

            // Recurse if we're merging object values
            if (deep && copy && typeof copy === "object" && !copy.nodeType)
                target[name] = jQuery.extend(deep,
            // Never move original objects, clone them
						src || (copy.length != null ? [] : {})
					, copy);

            // Don't bring in undefined values
            else if (copy !== undefined)
                target[name] = copy;

        }

        // Return the modified object
        return target;
    };

    // exclude the following css properties to add px
    var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
    // cache defaultView
	defaultView = document.defaultView || {},
	toString = Object.prototype.toString;

    jQuery.extend({
        noConflict: function(deep) {
            window.$ = _$;

            if (deep)
                window.jQuery = _jQuery;

            return jQuery;
        },

        // 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 toString.call(obj) === "[object Function]";
        },

        isArray: function(obj) {
            return toString.call(obj) === "[object Array]";
        },

        // check if an element is in a (or is an) XML document
        isXMLDoc: function(elem) {
            return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
			!!elem.ownerDocument && jQuery.isXMLDoc(elem.ownerDocument);
        },

        // Evalulates a script in a global context
        globalEval: function(data) {
            if (data && /\S/.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;

            if (args) {
                if (length === undefined) {
                    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 (length === undefined) {
                    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;
        },

        prop: function(elem, value, type, i, name) {
            // Handle executable functions
            if (jQuery.isFunction(value))
                value = value.call(elem, i);

            // Handle passing in a number to a CSS property
            return typeof value === "number" && type == "curCSS" && !exclude.test(name) ?
			value + "px" :
			value;
        },

        className: {
            // internal only, use addClass("class")
            add: function(elem, classNames) {
                jQuery.each((classNames || "").split(/\s+/), function(i, className) {
                    if (elem.nodeType == 1 && !jQuery.className.has(elem.className, className))
                        elem.className += (elem.className ? " " : "") + className;
                });
            },

            // internal only, use removeClass("class")
            remove: function(elem, classNames) {
                if (elem.nodeType == 1)
                    elem.className = classNames !== undefined ?
					jQuery.grep(elem.className.split(/\s+/), function(className) {
					    return !jQuery.className.has(classNames, className);
					}).join(" ") :
					"";
            },

            // internal only, use hasClass("class")
            has: function(elem, className) {
                return elem && jQuery.inArray(className, (elem.className || elem).toString().split(/\s+/)) > -1;
            }
        },

        // 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 (var name in options)
                elem.style[name] = old[name];
        },

        css: function(elem, name, force, extra) {
            if (name == "width" || name == "height") {
                var val, props = { position: "absolute", visibility: "hidden", display: "block" }, which = name == "width" ? ["Left", "Right"] : ["Top", "Bottom"];

                function getWH() {
                    val = name == "width" ? elem.offsetWidth : elem.offsetHeight;

                    if (extra === "border")
                        return;

                    jQuery.each(which, function() {
                        if (!extra)
                            val -= parseFloat(jQuery.curCSS(elem, "padding" + this, true)) || 0;
                        if (extra === "margin")
                            val += parseFloat(jQuery.curCSS(elem, "margin" + this, true)) || 0;
                        else
                            val -= parseFloat(jQuery.curCSS(elem, "border" + this + "Width", true)) || 0;
                    });
                }

                if (elem.offsetWidth !== 0)
                    getWH();
                else
                    jQuery.swap(elem, props, getWH);

                return Math.max(0, Math.round(val));
            }

            return jQuery.curCSS(elem, name, force);
        },

        curCSS: function(elem, name, force) {
            var ret, style = elem.style;

            // We need to handle opacity special in IE
            if (name == "opacity" && !jQuery.support.opacity) {
                ret = jQuery.attr(style, "opacity");

                return ret == "" ?
				"1" :
				ret;
            }

            // Make sure we're using the right name for getting the float value
            if (name.match(/float/i))
                name = styleFloat;

            if (!force && style && style[name])
                ret = style[name];

            else if (defaultView.getComputedStyle) {

                // Only "float" is needed here
                if (name.match(/float/i))
                    name = "float";

                name = name.replace(/([A-Z])/g, "-$1").toLowerCase();

                var computedStyle = defaultView.getComputedStyle(elem, null);

                if (computedStyle)
                    ret = computedStyle.getPropertyValue(name);

                // We should always get a number back from opacity
                if (name == "opacity" && ret == "")
                    ret = "1";

            } else if (elem.currentStyle) {
                var camelCase = name.replace(/\-(\w)/g, function(all, letter) {
                    return letter.toUpperCase();
                });

                ret = elem.currentStyle[name] || elem.currentStyle[camelCase];

                // 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 (!/^\d+(px)?$/i.test(ret) && /^\d/.test(ret)) {
                    // Remember the original values
                    var 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 = ret || 0;
                    ret = style.pixelLeft + "px";

                    // Revert the changed values
                    style.left = left;
                    elem.runtimeStyle.left = rsLeft;
                }
            }

            return ret;
        },

        clean: function(elems, context, fragment) {
            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;

            // If a single string is passed in and it's a single tag
            // just do a createElement and skip the rest
            if (!fragment && elems.length === 1 && typeof elems[0] === "string") {
                var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
                if (match)
                    return [context.createElement(match[1])];
            }

            var ret = [], scripts = [], div = context.createElement("div");

            jQuery.each(elems, function(i, elem) {
                if (typeof elem === "number")
                    elem += '';

                if (!elem)
                    return;

                // Convert html string into DOM nodes
                if (typeof elem === "string") {
                    // Fix "XHTML"-style tags in all browsers
                    elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag) {
                        return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
						all :
						front + "></" + tag + ">";
                    });

                    // Trim whitespace, otherwise indexOf won't work as expected
                    var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();

                    var wrap =
                    // option or optgroup
					!tags.indexOf("<opt") &&
					[1, "<select multiple='multiple'>", "</select>"] ||

					!tags.indexOf("<leg") &&
					[1, "<fieldset>", "</fieldset>"] ||

					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
					[1, "<table>", "</table>"] ||

					!tags.indexOf("<tr") &&
					[2, "<table><tbody>", "</tbody></table>"] ||

                    // <thead> matched above
					(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
					[3, "<table><tbody><tr>", "</tr></tbody></table>"] ||

					!tags.indexOf("<col") &&
					[2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"] ||

                    // IE can't serialize <link> and <script> tags normally
					!jQuery.support.htmlSerialize &&
					[1, "div<div>", "</div>"] ||

					[0, "", ""];

                    // Go to html and back, then peel off extra wrappers
                    div.innerHTML = wrap[1] + elem + wrap[2];

                    // Move to the right depth
                    while (wrap[0]--)
                        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 = /<tbody/i.test(elem),
						tbody = !tags.indexOf("<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 && /^\s/.test(elem))
                        div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]), div.firstChild);

                    elem = jQuery.makeArray(div.childNodes);
                }

                if (elem.nodeType)
                    ret.push(elem);
                else
                    ret = jQuery.merge(ret, elem);

            });

            if (fragment) {
                for (var i = 0; ret[i]; i++) {
                    if (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 scripts;
            }

            return ret;
        },

        attr: function(elem, name, value) {
            // don't set attributes on text and comment nodes
            if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
                return undefined;

            var notxml = !jQuery.isXMLDoc(elem),
            // Whether we are setting (or getting)
			set = value !== undefined;

            // Try to normalize/fix the name
            name = notxml && jQuery.props[name] || name;

            // Only do all the following if this is a node (faster for style)
            // IE elem.getAttribute passes even for style
            if (elem.tagName) {

                // These attributes require special treatment
                var special = /href|src|style/.test(name);

                // Safari mis-reports the default selected property of a hidden option
                // Accessing the parent's selectedIndex property fixes it
                if (name == "selected" && elem.parentNode)
                    elem.parentNode.selectedIndex;

                // If applicable, access the attribute via the DOM 0 way
                if (name in elem && notxml && !special) {
                    if (set) {
                        // We can't allow the type property to be changed (since it causes problems in IE)
                        if (name == "type" && jQuery.nodeName(elem, "input") && elem.parentNode)
                            throw "type property can't be changed";

                        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
						: elem.nodeName.match(/(button|input|object|select|textarea)/i)
							? 0
							: elem.nodeName.match(/^(a|area)$/i) && elem.href
								? 0
								: undefined;
                    }

                    return elem[name];
                }

                if (!jQuery.support.style && notxml && name == "style")
                    return jQuery.attr(elem.style, "cssText", value);

                if (set)
                // convert the value to a string (all browsers do this but IE) see #1070
                    elem.setAttribute(name, "" + value);

                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;
            }

            // elem is actually elem.style ... set the style

            // IE uses filters for opacity
            if (!jQuery.support.opacity && name == "opacity") {
                if (set) {
                    // IE has trouble with opacity if it does not have layout
                    // Force it by setting the zoom level
                    elem.zoom = 1;

                    // Set the alpha filter to set the opacity
                    elem.filter = (elem.filter || "").replace(/alpha\([^)]*\)/, "") +
					(parseInt(value) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
                }

                return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
				(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1]) / 100) + '' :
				"";
            }

            name = name.replace(/-([a-z])/ig, function(all, letter) {
                return letter.toUpperCase();
            });

            if (set)
                elem[name] = value;

            return elem[name];
        },

        trim: function(text) {
            return (text || "").replace(/^\s+|\s+$/g, "");
        },

        makeArray: function(array) {
            var ret = [];

            if (array != null) {
                var i = array.length;
                // The window, strings (and functions) also have 'length'
                if (i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval)
                    ret[0] = array;
                else
                    while (i)
                    ret[--i] = array[i];
            }

            return ret;
        },

        inArray: function(elem, array) {
            for (var i = 0, length = array.length; i < length; i++)
            // Use === because on IE, window == document
                if (array[i] === elem)
                return i;

            return -1;
        },

        merge: function(first, second) {
            // We have to loop this way because IE & Opera overwrite the length
            // expando of getElementsByTagName
            var i = 0, elem, pos = first.length;
            // Also, we need to make sure that the correct elements are being returned
            // (IE returns comment nodes in a '*' query)
            if (!jQuery.support.getAll) {
                while ((elem = second[i++]) != null)
                    if (elem.nodeType != 8)
                    first[pos++] = elem;

            } else
                while ((elem = second[i++]) != null)
                first[pos++] = elem;

            return first;
        },

        unique: function(array) {
            var ret = [], done = {};

            try {

                for (var i = 0, length = array.length; i < length; i++) {
                    var id = jQuery.data(array[i]);

                    if (!done[id]) {
                        done[id] = true;
                        ret.push(array[i]);
                    }
                }

            } catch (e) {
                ret = array;
            }

            return ret;
        },

        grep: function(elems, callback, inv) {
            var ret = [];

            // Go through the array, only saving the items
            // that pass the validator function
            for (var i = 0, length = elems.length; i < length; i++)
                if (!inv != !callback(elems[i], i))
                ret.push(elems[i]);

            return ret;
        },

        map: function(elems, callback) {
            var ret = [];

            // 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++) {
                var value = callback(elems[i], i);

                if (value != null)
                    ret[ret.length] = value;
            }

            return ret.concat.apply([], ret);
        }
    });

    // Use of jQuery.browser is deprecated.
    // It's included for backwards compatibility and plugins,
    // although they should work to migrate away.

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    jQuery.browser = {
        version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1],
        safari: /webkit/.test(userAgent),
        opera: /opera/.test(userAgent),
        msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
        mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
    };

    jQuery.each({
        parent: function(elem) { return elem.parentNode; },
        parents: function(elem) { return jQuery.dir(elem, "parentNode"); },
        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"); },
        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(selector) {
            var ret = jQuery.map(this, fn);

            if (selector && typeof selector == "string")
                ret = jQuery.multiFilter(selector, ret);

            return this.pushStack(jQuery.unique(ret), name, selector);
        };
    });

    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);

            for (var i = 0, l = insert.length; i < l; i++) {
                var elems = (i > 0 ? this.clone(true) : this).get();
                jQuery.fn[original].apply(jQuery(insert[i]), elems);
                ret = ret.concat(elems);
            }

            return this.pushStack(ret, name, selector);
        };
    });

    jQuery.each({
        removeAttr: function(name) {
            jQuery.attr(this, name, "");
            if (this.nodeType == 1)
                this.removeAttribute(name);
        },

        addClass: function(classNames) {
            jQuery.className.add(this, classNames);
        },

        removeClass: function(classNames) {
            jQuery.className.remove(this, classNames);
        },

        toggleClass: function(classNames, state) {
            if (typeof state !== "boolean")
                state = !jQuery.className.has(this, classNames);
            jQuery.className[state ? "add" : "remove"](this, classNames);
        },

        remove: function(selector) {
            if (!selector || jQuery.filter(selector, [this]).length) {
                // Prevent memory leaks
                jQuery("*", this).add([this]).each(function() {
                    jQuery.event.remove(this);
                    jQuery.removeData(this);
                });
                if (this.parentNode)
                    this.parentNode.removeChild(this);
            }
        },

        empty: function() {
            // Remove element nodes and prevent memory leaks
            jQuery(this).children().remove();

            // Remove any remaining nodes
            while (this.firstChild)
                this.removeChild(this.firstChild);
        }
    }, function(name, fn) {
        jQuery.fn[name] = function() {
            return this.each(fn, arguments);
        };
    });

    // Helper function used by the dimensions and offset modules
    function num(elem, prop) {
        return elem[0] && parseInt(jQuery.curCSS(elem[0], prop, true), 10) || 0;
    }
    var expando = "jQuery" + now(), uuid = 0, windowData = {};

    jQuery.extend({
        cache: {},

        data: function(elem, name, data) {
            elem = elem == window ?
			windowData :
			elem;

            var id = elem[expando];

            // Compute a unique ID for the element
            if (!id)
                id = elem[expando] = ++uuid;

            // Only generate the data cache if we're
            // trying to access or manipulate it
            if (name && !jQuery.cache[id])
                jQuery.cache[id] = {};

            // Prevent overriding the named cache with undefined values
            if (data !== undefined)
                jQuery.cache[id][name] = data;

            // Return the named cache data, or the ID for the element
            return name ?
			jQuery.cache[id][name] :
			id;
        },

        removeData: function(elem, name) {
            elem = elem == window ?
			windowData :
			elem;

            var id = elem[expando];

            // If we want to remove a specific section of the element's data
            if (name) {
                if (jQuery.cache[id]) {
                    // Remove the section of cache data
                    delete jQuery.cache[id][name];

                    // If we've removed all the data, remove the element's cache
                    name = "";

                    for (name in jQuery.cache[id])
                        break;

                    if (!name)
                        jQuery.removeData(elem);
                }

                // Otherwise, we want to remove all of the element's data
            } else {
                // Clean up the element expando
                try {
                    delete elem[expando];
                } catch (e) {
                    // IE has trouble directly removing the expando
                    // but it's ok with using removeAttribute
                    if (elem.removeAttribute)
                        elem.removeAttribute(expando);
                }

                // Completely remove the data cache
                delete jQuery.cache[id];
            }
        },
        queue: function(elem, type, data) {
            if (elem) {

                type = (type || "fx") + "queue";

                var q = jQuery.data(elem, type);

                if (!q || jQuery.isArray(data))
                    q = jQuery.data(elem, type, jQuery.makeArray(data));
                else if (data)
                    q.push(data);

            }
            return q;
        },

        dequeue: function(elem, type) {
            var queue = jQuery.queue(elem, type),
			fn = queue.shift();

            if (!type || type === "fx")
                fn = queue[0];

            if (fn !== undefined)
                fn.call(elem);
        }
    });

    jQuery.fn.extend({
        data: function(key, value) {
            var parts = key.split(".");
            parts[1] = parts[1] ? "." + parts[1] : "";

            if (value === undefined) {
                var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

                if (data === undefined && this.length)
                    data = jQuery.data(this[0], key);

                return data === undefined && parts[1] ?
				this.data(parts[0]) :
				data;
            } else
                return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() {
                    jQuery.data(this, key, value);
                });
        },

        removeData: function(key) {
            return this.each(function() {
                jQuery.removeData(this, key);
            });
        },
        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() {
                var queue = jQuery.queue(this, type, data);

                if (type == "fx" && queue.length == 1)
                    queue[0].call(this);
            });
        },
        dequeue: function(type) {
            return this.each(function() {
                jQuery.dequeue(this, type);
            });
        }
    }); /*!
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
    (function() {

        var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
	done = 0,
	toString = Object.prototype.toString;

        var Sizzle = function(selector, context, results, seed) {
            results = results || [];
            context = context || document;

            if (context.nodeType !== 1 && context.nodeType !== 9)
                return [];

            if (!selector || typeof selector !== "string") {
                return results;
            }

            var parts = [], m, set, checkSet, check, mode, extra, prune = true;

            // Reset the position of the chunker regexp (start from head)
            chunker.lastIndex = 0;

            while ((m = chunker.exec(selector)) !== null) {
                parts.push(m[1]);

                if (m[2]) {
                    extra = RegExp.rightContext;
                    break;
                }
            }

            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 {
                var ret = seed ?
			{ expr: parts.pop(), set: makeArray(seed)} :
			Sizzle.find(parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context));
                set = Sizzle.filter(ret.expr, ret.set);

                if (parts.length > 0) {
                    checkSet = makeArray(set);
                } else {
                    prune = false;
                }

                while (parts.length) {
                    var cur = parts.pop(), pop = cur;

                    if (!Expr.relative[cur]) {
                        cur = "";
                    } else {
                        pop = parts.pop();
                    }

                    if (pop == null) {
                        pop = context;
                    }

                    Expr.relative[cur](checkSet, pop, isXML(context));
                }
            }

            if (!checkSet) {
                checkSet = set;
            }

            if (!checkSet) {
                throw "Syntax error, unrecognized expression: " + (cur || selector);
            }

            if (toString.call(checkSet) === "[object Array]") {
                if (!prune) {
                    results.push.apply(results, checkSet);
                } else if (context.nodeType === 1) {
                    for (var i = 0; checkSet[i] != null; i++) {
                        if (checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i]))) {
                            results.push(set[i]);
                        }
                    }
                } else {
                    for (var 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, context, results, seed);

                if (sortOrder) {
                    hasDuplicate = false;
                    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.find = function(expr, context, isXML) {
            var set, match;

            if (!expr) {
                return [];
            }

            for (var i = 0, l = Expr.order.length; i < l; i++) {
                var type = Expr.order[i], match;

                if ((match = Expr.match[type].exec(expr))) {
                    var left = RegExp.leftContext;

                    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 old = expr, result = [], curLoop = set, match, anyFound,
		isXMLFilter = set && set[0] && isXML(set[0]);

            while (expr && set.length) {
                for (var type in Expr.filter) {
                    if ((match = Expr.match[type].exec(expr)) != null) {
                        var filter = Expr.filter[type], found, item;
                        anyFound = false;

                        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) {
                        throw "Syntax error, unrecognized expression: " + expr;
                    } else {
                        break;
                    }
                }

                old = expr;
            }

            return curLoop;
        };

        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\(\)]*)+)\2\))?/
            },
            attrMap: {
                "class": "className",
                "for": "htmlFor"
            },
            attrHandle: {
                href: function(elem) {
                    return elem.getAttribute("href");
                }
            },
            relative: {
                "+": function(checkSet, part, isXML) {
                    var isPartStr = typeof part === "string",
				isTag = isPartStr && !/\W/.test(part),
				isPartStrNotTag = isPartStr && !isTag;

                    if (isTag && !isXML) {
                        part = part.toUpperCase();
                    }

                    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 === part ?
						elem || false :
						elem === part;
                        }
                    }

                    if (isPartStrNotTag) {
                        Sizzle.filter(part, checkSet, true);
                    }
                },
                ">": function(checkSet, part, isXML) {
                    var isPartStr = typeof part === "string";

                    if (isPartStr && !/\W/.test(part)) {
                        part = isXML ? part : part.toUpperCase();

                        for (var i = 0, l = checkSet.length; i < l; i++) {
                            var elem = checkSet[i];
                            if (elem) {
                                var parent = elem.parentNode;
                                checkSet[i] = parent.nodeName === part ? parent : false;
                            }
                        }
                    } else {
                        for (var i = 0, l = checkSet.length; i < l; i++) {
                            var 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 doneName = done++, checkFn = dirCheck;

                    if (!part.match(/\W/)) {
                        var nodeCheck = part = isXML ? part : part.toUpperCase();
                        checkFn = dirNodeCheck;
                    }

                    checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
                },
                "~": function(checkSet, part, isXML) {
                    var doneName = done++, checkFn = dirCheck;

                    if (typeof part === "string" && !part.match(/\W/)) {
                        var nodeCheck = part = isXML ? part : part.toUpperCase();
                        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]);
                        return m ? [m] : [];
                    }
                },
                NAME: function(match, context, isXML) {
                    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 + " ").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) {
                    for (var i = 0; curLoop[i] === false; i++) { }
                    return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
                },
                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 (match[3].match(chunker).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.toUpperCase() === "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 || "").indexOf(match[3]) >= 0;
                    } else if (name === "not") {
                        var not = match[3];

                        for (var i = 0, l = not.length; i < l; i++) {
                            if (not[i] === elem) {
                                return false;
                            }
                        }

                        return true;
                    }
                },
                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 === 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;

        for (var type in Expr.match) {
            Expr.match[type] = RegExp(Expr.match[type].source + /(?![^\[]*\])(?![^\(]*\))/.source);
        }

        var makeArray = function(array, results) {
            array = Array.prototype.slice.call(array);

            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.
        try {
            Array.prototype.slice.call(document.documentElement.childNodes);

            // Provide a fallback method if it does not work
        } catch (e) {
            makeArray = function(array, results) {
                var ret = results || [];

                if (toString.call(array) === "[object Array]") {
                    Array.prototype.push.apply(ret, array);
                } else {
                    if (typeof array.length === "number") {
                        for (var i = 0, l = array.length; i < l; i++) {
                            ret.push(array[i]);
                        }
                    } else {
                        for (var i = 0; array[i]; i++) {
                            ret.push(array[i]);
                        }
                    }
                }

                return ret;
            };
        }

        var sortOrder;

        if (document.documentElement.compareDocumentPosition) {
            sortOrder = function(a, b) {
                var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
                if (ret === 0) {
                    hasDuplicate = true;
                }
                return ret;
            };
        } else if ("sourceIndex" in document.documentElement) {
            sortOrder = function(a, b) {
                var ret = a.sourceIndex - b.sourceIndex;
                if (ret === 0) {
                    hasDuplicate = true;
                }
                return ret;
            };
        } else if (document.createRange) {
            sortOrder = function(a, b) {
                var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
                aRange.selectNode(a);
                aRange.collapse(true);
                bRange.selectNode(b);
                bRange.collapse(true);
                var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
                if (ret === 0) {
                    hasDuplicate = true;
                }
                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("form"),
		id = "script" + (new Date).getTime();
            form.innerHTML = "<input name='" + id + "'/>";

            // Inject it into the root element, check its status, and remove it quickly
            var root = document.documentElement;
            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);
        })();

        (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);
                };
            }
        })();

        if (document.querySelectorAll) (function() {
            var oldSizzle = Sizzle, div = document.createElement("div");
            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;

                // Only use querySelectorAll on non-XML documents
                // (ID selectors don't work in non-HTML documents)
                if (!seed && context.nodeType === 9 && !isXML(context)) {
                    try {
                        return makeArray(context.querySelectorAll(query), extra);
                    } catch (e) { }
                }

                return oldSizzle(query, context, extra, seed);
            };

            Sizzle.find = oldSizzle.find;
            Sizzle.filter = oldSizzle.filter;
            Sizzle.selectors = oldSizzle.selectors;
            Sizzle.matches = oldSizzle.matches;
        })();

        if (document.getElementsByClassName && document.documentElement.getElementsByClassName) (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)
            if (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]);
                }
            };
        })();

        function dirNodeCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
            var sibDir = dir == "previousSibling" && !isXML;
            for (var i = 0, l = checkSet.length; i < l; i++) {
                var elem = checkSet[i];
                if (elem) {
                    if (sibDir && elem.nodeType === 1) {
                        elem.sizcache = doneName;
                        elem.sizset = i;
                    }
                    elem = elem[dir];
                    var match = false;

                    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 === cur) {
                            match = elem;
                            break;
                        }

                        elem = elem[dir];
                    }

                    checkSet[i] = match;
                }
            }
        }

        function dirCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
            var sibDir = dir == "previousSibling" && !isXML;
            for (var i = 0, l = checkSet.length; i < l; i++) {
                var elem = checkSet[i];
                if (elem) {
                    if (sibDir && elem.nodeType === 1) {
                        elem.sizcache = doneName;
                        elem.sizset = i;
                    }
                    elem = elem[dir];
                    var match = false;

                    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;
                }
            }
        }

        var contains = document.compareDocumentPosition ? function(a, b) {
            return a.compareDocumentPosition(b) & 16;
        } : function(a, b) {
            return a !== b && (a.contains ? a.contains(b) : true);
        };

        var isXML = function(elem) {
            return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
		!!elem.ownerDocument && isXML(elem.ownerDocument);
        };

        var posProcess = function(selector, context) {
            var tmpSet = [], later = "", match,
		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.filter = Sizzle.filter;
        jQuery.expr = Sizzle.selectors;
        jQuery.expr[":"] = jQuery.expr.filters;

        Sizzle.selectors.filters.hidden = function(elem) {
            return elem.offsetWidth === 0 || elem.offsetHeight === 0;
        };

        Sizzle.selectors.filters.visible = function(elem) {
            return elem.offsetWidth > 0 || elem.offsetHeight > 0;
        };

        Sizzle.selectors.filters.animated = function(elem) {
            return jQuery.grep(jQuery.timers, function(fn) {
                return elem === fn.elem;
            }).length;
        };

        jQuery.multiFilter = function(expr, elems, not) {
            if (not) {
                expr = ":not(" + expr + ")";
            }

            return Sizzle.matches(expr, elems);
        };

        jQuery.dir = function(elem, dir) {
            var matched = [], cur = elem[dir];
            while (cur && cur != document) {
                if (cur.nodeType == 1)
                    matched.push(cur);
                cur = cur[dir];
            }
            return matched;
        };

        jQuery.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;
        };

        jQuery.sibling = function(n, elem) {
            var r = [];

            for (; n; n = n.nextSibling) {
                if (n.nodeType == 1 && n != elem)
                    r.push(n);
            }

            return r;
        };

        return;

        window.Sizzle = Sizzle;

    })();
    /*
    * 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 (elem.setInterval && elem != window)
                elem = window;

            // Make sure that the function being executed has a unique ID
            if (!handler.guid)
                handler.guid = this.guid++;

            // if data is passed, bind to handler
            if (data !== undefined) {
                // Create temporary function pointer to original handler
                var fn = handler;

                // Create unique handler function, wrapped around original handler
                handler = this.proxy(fn);

                // Store data in unique handler
                handler.data = data;
            }

            // Init the element's event structure
            var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", 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(arguments.callee.elem, arguments) :
					undefined;
			});
            // Add elem as a property of the handle function
            // This is to prevent a memory leak with non-native
            // event in IE.
            handle.elem = elem;

            // Handle multiple events separated by a space
            // jQuery(...).bind("mouseover mouseout", fn);
            jQuery.each(types.split(/\s+/), function(index, type) {
                // Namespaced event handlers
                var namespaces = type.split(".");
                type = namespaces.shift();
                handler.type = namespaces.slice().sort().join(".");

                // Get the current list of functions bound to this event
                var handlers = events[type];

                if (jQuery.event.specialAll[type])
                    jQuery.event.specialAll[type].setup.call(elem, data, namespaces);

                // 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 (!jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false) {
                        // Bind the global event handler to the element
                        if (elem.addEventListener)
                            elem.addEventListener(type, handle, false);
                        else if (elem.attachEvent)
                            elem.attachEvent("on" + type, handle);
                    }
                }

                // Add the function to the element's handler list
                handlers[handler.guid] = handler;

                // 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;
        },

        guid: 1,
        global: {},

        // Detach an event or set of events from an element
        remove: function(elem, types, handler) {
            // don't do events on text and comment nodes
            if (elem.nodeType == 3 || elem.nodeType == 8)
                return;

            var events = jQuery.data(elem, "events"), ret, index;

            if (events) {
                // Unbind all events for the element
                if (types === undefined || (typeof types === "string" && types.charAt(0) == "."))
                    for (var type in events)
                    this.remove(elem, type + (types || ""));
                else {
                    // types is actually an event object here
                    if (types.type) {
                        handler = types.handler;
                        types = types.type;
                    }

                    // Handle multiple events seperated by a space
                    // jQuery(...).unbind("mouseover mouseout", fn);
                    jQuery.each(types.split(/\s+/), function(index, type) {
                        // Namespaced event handlers
                        var namespaces = type.split(".");
                        type = namespaces.shift();
                        var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

                        if (events[type]) {
                            // remove the given handler for the given type
                            if (handler)
                                delete events[type][handler.guid];

                            // remove all handlers for the given type
                            else
                                for (var handle in events[type])
                            // Handle the removal of namespaced events
                                if (namespace.test(events[type][handle].type))
                                delete events[type][handle];

                            if (jQuery.event.specialAll[type])
                                jQuery.event.specialAll[type].teardown.call(elem, namespaces);

                            // remove generic event handler if no more handlers exist
                            for (ret in events[type]) break;
                            if (!ret) {
                                if (!jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false) {
                                    if (elem.removeEventListener)
                                        elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
                                    else if (elem.detachEvent)
                                        elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
                                }
                                ret = null;
                                delete events[type];
                            }
                        }
                    });
                }

                // Remove the expando if it's no longer used
                for (ret in events) break;
                if (!ret) {
                    var handle = jQuery.data(elem, "handle");
                    if (handle) handle.elem = null;
                    jQuery.removeData(elem, "events");
                    jQuery.removeData(elem, "handle");
                }
            }
        },

        // bubbling is internal
        trigger: function(event, data, elem, bubbling) {
            // Event object or event type
            var type = event.type || event;

            if (!bubbling) {
                event = typeof event === "object" ?
                // jQuery.Event object
				event[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 (this.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 = jQuery.data(elem, "handle");
            if (handle)
                handle.apply(elem, data);

            // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
            if ((!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on" + type] && elem["on" + type].apply(elem, data) === false)
                event.result = false;

            // Trigger the native events (except for clicks on links)
            if (!bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click")) {
                this.triggered = true;
                try {
                    elem[type]();
                    // prevent IE from throwing an error for some hidden elements
                } catch (e) { }
            }

            this.triggered = false;

            if (!event.isPropagationStopped()) {
                var parent = elem.parentNode || elem.ownerDocument;
                if (parent)
                    jQuery.event.trigger(event, data, parent, true);
            }
        },

        handle: function(event) {
            // returned undefined or false
            var all, handlers;

            event = arguments[0] = jQuery.event.fix(event || window.event);
            event.currentTarget = this;

            // Namespaced event handlers
            var namespaces = event.type.split(".");
            event.type = namespaces.shift();

            // Cache this now, all = true means, any handler
            all = !namespaces.length && !event.exclusive;

            var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

            handlers = (jQuery.data(this, "events") || {})[event.type];

            for (var j in handlers) {
                var handler = handlers[j];

                // Filter the functions by class
                if (all || namespace.test(handler.type)) {
                    // Pass in a reference to the handler function itself
                    // So that we can later remove it
                    event.handler = handler;
                    event.data = handler.data;

                    var ret = handler.apply(this, arguments);

                    if (ret !== undefined) {
                        event.result = ret;
                        if (ret === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    }

                    if (event.isImmediatePropagationStopped())
                        break;

                }
            }
        },

        props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

        fix: function(event) {
            if (event[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)
                event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either

            // 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.clientLeft || 0);
                event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
            }

            // Add which for key events
            if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode))
                event.which = 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)
                event.which = (event.button & 1 ? 1 : (event.button & 2 ? 3 : (event.button & 4 ? 2 : 0)));

            return event;
        },

        proxy: function(fn, proxy) {
            proxy = proxy || function() { return fn.apply(this, arguments); };
            // Set the guid of unique handler to the same of original handler, so it can be removed
            proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
            // So proxy can be declared as an argument
            return proxy;
        },

        special: {
            ready: {
                // Make sure the ready event is setup
                setup: bindReady,
                teardown: function() { }
            }
        },

        specialAll: {
            live: {
                setup: function(selector, namespaces) {
                    jQuery.event.add(this, namespaces[0], liveHandler);
                },
                teardown: function(namespaces) {
                    if (namespaces.length) {
                        var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");

                        jQuery.each((jQuery.data(this, "events").live || {}), function() {
                            if (name.test(this.type))
                                remove++;
                        });

                        if (remove < 1)
                            jQuery.event.remove(this, namespaces[0], liveHandler);
                    }
                }
            }
        }
    };

    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 = now();

        // Mark it as fixed
        this[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)
            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;
        // Traverse up the tree
        while (parent && parent != this)
            try { parent = parent.parentNode; }
        catch (e) { parent = this; }

        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);
        }
    };

    jQuery.each({
        mouseover: 'mouseenter',
        mouseout: 'mouseleave'
    }, function(orig, fix) {
        jQuery.event.special[fix] = {
            setup: function() {
                jQuery.event.add(this, orig, withinElement, fix);
            },
            teardown: function() {
                jQuery.event.remove(this, orig, withinElement);
            }
        };
    });

    jQuery.fn.extend({
        bind: function(type, data, fn) {
            return type == "unload" ? this.one(type, data, fn) : this.each(function() {
                jQuery.event.add(this, type, fn || data, fn && data);
            });
        },

        one: function(type, data, fn) {
            var one = jQuery.event.proxy(fn || data, function(event) {
                jQuery(this).unbind(event, one);
                return (fn || data).apply(this, arguments);
            });
            return this.each(function() {
                jQuery.event.add(this, type, one, fn && data);
            });
        },

        unbind: function(type, fn) {
            return this.each(function() {
                jQuery.event.remove(this, type, fn);
            });
        },

        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.event.proxy(fn, args[i++]);

            return this.click(jQuery.event.proxy(fn, function(event) {
                // Figure out which function to execute
                this.lastToggle = (this.lastToggle || 0) % i;

                // Make sure that clicks stop
                event.preventDefault();

                // and execute the function
                return args[this.lastToggle++].apply(this, arguments) || false;
            }));
        },

        hover: function(fnOver, fnOut) {
            return this.mouseenter(fnOver).mouseleave(fnOut);
        },

        ready: function(fn) {
            // Attach the listeners
            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
            // Add the function to the wait list
                jQuery.readyList.push(fn);

            return this;
        },

        live: function(type, fn) {
            var proxy = jQuery.event.proxy(fn);
            proxy.guid += this.selector + type;

            jQuery(document).bind(liveConvert(type, this.selector), this.selector, proxy);

            return this;
        },

        die: function(type, fn) {
            jQuery(document).unbind(liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type} : null);
            return this;
        }
    });

    function liveHandler(event) {
        var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
		stop = true,
		elems = [];

        jQuery.each(jQuery.data(this, "events").live || [], function(i, fn) {
            if (check.test(fn.type)) {
                var elem = jQuery(event.target).closest(fn.data)[0];
                if (elem)
                    elems.push({ elem: elem, fn: fn });
            }
        });

        elems.sort(function(a, b) {
            return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
        });

        jQuery.each(elems, function() {
            if (this.fn.call(this.elem, event, this.fn.data) === false)
                return (stop = false);
        });

        return stop;
    }

    function liveConvert(type, selector) {
        return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
    }

    jQuery.extend({
        isReady: false,
        readyList: [],
        // Handle when the DOM is ready
        ready: function() {
            // Make sure that the DOM is not already loaded
            if (!jQuery.isReady) {
                // Remember that the DOM is ready
                jQuery.isReady = true;

                // If there are functions bound, to execute
                if (jQuery.readyList) {
                    // Execute all of them
                    jQuery.each(jQuery.readyList, function() {
                        this.call(document, jQuery);
                    });

                    // Reset the list of functions
                    jQuery.readyList = null;
                }

                // Trigger any bound ready events
                jQuery(document).triggerHandler("ready");
            }
        }
    });

    var readyBound = false;

    function bindReady() {
        if (readyBound) return;
        readyBound = true;

        // Mozilla, Opera and webkit nightlies currently support this event
        if (document.addEventListener) {
            // Use the handy event callback
            document.addEventListener("DOMContentLoaded", function() {
                document.removeEventListener("DOMContentLoaded", arguments.callee, false);
                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", function() {
                if (document.readyState === "complete") {
                    document.detachEvent("onreadystatechange", arguments.callee);
                    jQuery.ready();
                }
            });

            // If IE and not an iframe
            // continually check to see if the document is ready
            if (document.documentElement.doScroll && window == window.top) (function() {
                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 (error) {
                    setTimeout(arguments.callee, 0);
                    return;
                }

                // and execute any waiting functions
                jQuery.ready();
            })();
        }

        // A fallback to window.onload, that will always work
        jQuery.event.add(window, "load", jQuery.ready);
    }

    jQuery.each(("blur,focus,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(fn) {
	        return fn ? this.bind(name, fn) : this.trigger(name);
	    };
	});

    // Prevent memory leaks in IE
    // And prevent errors on refresh with events like mouseover in other browsers
    // Window isn't included so as not to unbind existing unload events
    jQuery(window).bind('unload', function() {
        for (var id in jQuery.cache)
        // Skip the window
            if (id != 1 && jQuery.cache[id].handle)
            jQuery.event.remove(jQuery.cache[id].handle.elem);
    });
    (function() {

        jQuery.support = {};

        var root = document.documentElement,
		script = document.createElement("script"),
		div = document.createElement("div"),
		id = "script" + (new Date).getTime();

        div.style.display = "none";
        div.innerHTML = '   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';

        var all = div.getElementsByTagName("*"),
		a = div.getElementsByTagName("a")[0];

        // 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 you can get all elements in an <object> element
            // IE 7 always returns no results
            objectAll: !!div.getElementsByTagName("object")[0]
			.getElementsByTagName("*").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)
            opacity: a.style.opacity === "0.5",

            // Verify style float existence
            // (IE uses styleFloat instead of cssFloat)
            cssFloat: !!a.style.cssFloat,

            // Will be defined later
            scriptEval: false,
            noCloneEvent: true,
            boxModel: null
        };

        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];
        }

        root.removeChild(script);

        if (div.attachEvent && div.fireEvent) {
            div.attachEvent("onclick", function() {
                // Cloning a node shouldn't copy over any
                // bound event handlers (IE does this)
                jQuery.support.noCloneEvent = false;
                div.detachEvent("onclick", arguments.callee);
            });
            div.cloneNode(true).fireEvent("onclick");
        }

        // 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;
            document.body.removeChild(div).style.display = 'none';
        });
    })();

    var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";

    jQuery.props = {
        "for": "htmlFor",
        "class": "className",
        "float": styleFloat,
        cssFloat: styleFloat,
        styleFloat: styleFloat,
        readonly: "readOnly",
        maxlength: "maxLength",
        cellspacing: "cellSpacing",
        rowspan: "rowSpan",
        tabindex: "tabIndex"
    };
    jQuery.fn.extend({
        // Keep a copy of the old load
        _load: jQuery.fn.load,

        load: function(url, params, callback) {
            if (typeof url !== "string")
                return this._load(url);

            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);
                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(/<script(.|\s)*?\/script>/g, ""))

                    // 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 || /select|textarea/i.test(this.nodeName) ||
					/text|hidden|password|search/i.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);
        };
    });

    var jsc = now();

    jQuery.extend({

        get: function(url, data, callback, type) {
            // shift arguments if data argument was ommited
            if (jQuery.isFunction(data)) {
                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) {
            if (jQuery.isFunction(data)) {
                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,
            */
            // Create the request object; Microsoft failed to properly
            // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
            // This function can be overriden by calling jQuery.ajaxSetup
            xhr: function() {
                return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
            },
            accepts: {
                xml: "application/xml, text/xml",
                html: "text/html",
                script: "text/javascript, application/javascript",
                json: "application/json, text/javascript",
                text: "text/plain",
                _default: "*/*"
            }
        },

        // Last-Modified header cache for next request
        lastModified: {},

        ajax: function(s) {
            // Extend the settings, but re-extend 's' so that it can be
            // checked again later (in the test suite, specifically)
            s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

            var jsonp, jsre = /=\?(&|$)/g, status, data,
			type = s.type.toUpperCase();

            // convert data if not already a string
            if (s.data && s.processData && typeof s.data !== "string")
                s.data = jQuery.param(s.data);

            // Handle JSONP Parameter Callbacks
            if (s.dataType == "jsonp") {
                if (type == "GET") {
                    if (!s.url.match(jsre))
                        s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
                } else if (!s.data || !s.data.match(jsre))
                    s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
                s.dataType = "json";
            }

            // Build temporary JSONP function
            if (s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre))) {
                jsonp = "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
                window[jsonp] = function(tmp) {
                    data = tmp;
                    success();
                    complete();
                    // Garbage collect
                    window[jsonp] = undefined;
                    try { delete window[jsonp]; } catch (e) { }
                    if (head)
                        head.removeChild(script);
                };
            }

            if (s.dataType == "script" && s.cache == null)
                s.cache = false;

            if (s.cache === false && type == "GET") {
                var ts = now();
                // try replacing _= if it is there
                var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
                // if nothing was replaced, add timestamp to the end
                s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
            }

            // If data is available, append data to url for get requests
            if (s.data && type == "GET") {
                s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

                // IE likes to send both get and post data, prevent this
                s.data = null;
            }

            // Watch for a new set of requests
            if (s.global && !jQuery.active++)
                jQuery.event.trigger("ajaxStart");

            // Matches an absolute URL, and saves the domain
            var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec(s.url);

            // If we're requesting a remote document
            // and trying to load JSON or Script with a GET
            if (s.dataType == "script" && type == "GET" && parts
			&& (parts[1] && parts[1] != location.protocol || parts[2] != location.host)) {

                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                script.src = s.url;
                if (s.scriptCharset)
                    script.charset = s.scriptCharset;

                // 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;
                            success();
                            complete();

                            // Handle memory leak in IE
                            script.onload = script.onreadystatechange = null;
                            head.removeChild(script);
                        }
                    };
                }

                head.appendChild(script);

                // We handle everything using the script element injection
                return undefined;
            }

            var requestDone = false;

            // Create the request object
            var xhr = s.xhr();

            // 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 the correct header, if data is being sent
                if (s.data)
                    xhr.setRequestHeader("Content-Type", s.contentType);

                // Set the If-Modified-Since header, if ifModified mode.
                if (s.ifModified)
                    xhr.setRequestHeader("If-Modified-Since",
					jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT");

                // Set header so the called script knows that it's an XMLHttpRequest
                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] + ", */*" :
				s.accepts._default);
            } catch (e) { }

            // Allow custom headers/mimetypes and early abort
            if (s.beforeSend && s.beforeSend(xhr, s) === false) {
                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");
                // close opended socket
                xhr.abort();
                return false;
            }

            if (s.global)
                jQuery.event.trigger("ajaxSend", [xhr, s]);

            // Wait for a response to come back
            var onreadystatechange = function(isTimeout) {
                // The request was aborted, clear the interval and decrement jQuery.active
                if (xhr.readyState == 0) {
                    if (ival) {
                        // clear poll interval
                        clearInterval(ival);
                        ival = null;
                        // Handle the global AJAX counter
                        if (s.global && ! --jQuery.active)
                            jQuery.event.trigger("ajaxStop");
                    }
                    // 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;

                    // clear poll interval
                    if (ival) {
                        clearInterval(ival);
                        ival = null;
                    }

                    status = isTimeout == "timeout" ? "timeout" :
					!jQuery.httpSuccess(xhr) ? "error" :
					s.ifModified && jQuery.httpNotModified(xhr, s.url) ? "notmodified" :
					"success";

                    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 (e) {
                            status = "parsererror";
                        }
                    }

                    // Make sure that the request was successful or notmodified
                    if (status == "success") {
                        // Cache Last-Modified header, if ifModified mode.
                        var modRes;
                        try {
                            modRes = xhr.getResponseHeader("Last-Modified");
                        } catch (e) { } // swallow exception thrown by FF if header is not available

                        if (s.ifModified && modRes)
                            jQuery.lastModified[s.url] = modRes;

                        // JSONP handles its own success callback
                        if (!jsonp)
                            success();
                    } else
                        jQuery.handleError(s, xhr, status);

                    // Fire the complete handlers
                    complete();

                    if (isTimeout)
                        xhr.abort();

                    // Stop memory leaks
                    if (s.async)
                        xhr = null;
                }
            };

            if (s.async) {
                // don't attach the handler to the request, just poll it instead
                var ival = setInterval(onreadystatechange, 13);

                // Timeout checker
                if (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(s.data);
            } catch (e) {
                jQuery.handleError(s, xhr, null, e);
            }

            // firefox 1.5 doesn't fire statechange for sync requests
            if (!s.async)
                onreadystatechange();

            function success() {
                // If a local callback was specified, fire it and pass it the data
                if (s.success)
                    s.success(data, status);

                // Fire the global callback
                if (s.global)
                    jQuery.event.trigger("ajaxSuccess", [xhr, s]);
            }

            function complete() {
                // Process result
                if (s.complete)
                    s.complete(xhr, status);

                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xhr, s]);

                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");
            }

            // return XMLHttpRequest to allow aborting the request etc.
            return xhr;
        },

        handleError: function(s, xhr, status, e) {
            // If a local callback was specified, fire it
            if (s.error) s.error(xhr, status, e);

            // Fire the global callback
            if (s.global)
                jQuery.event.trigger("ajaxError", [xhr, s, e]);
        },

        // Counter for holding the number of active queries
        active: 0,

        // 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) {
            try {
                var xhrRes = xhr.getResponseHeader("Last-Modified");

                // Firefox always returns 200. check Last-Modified date
                return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
            } catch (e) { }
            return false;
        },

        httpData: function(xhr, type, s) {
            var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

            if (xml && data.documentElement.tagName == "parsererror")
                throw "parsererror";

            // Allow a pre-filtering function to sanitize the response
            // s != null 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") {

                // If the type is "script", eval it in global context
                if (type == "script")
                    jQuery.globalEval(data);

                // Get the JavaScript object, if JSON is used.
                if (type == "json")
                    data = window["eval"]("(" + data + ")");
            }

            return data;
        },

        // Serialize an array of form elements or a set of
        // key/values into a query string
        param: function(a) {
            var s = [];

            function add(key, value) {
                s[s.length] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
            };

            // 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);
                });

            // Otherwise, assume that it's an object of key/value pairs
            else
            // Serialize the key/values
                for (var j in a)
            // If the value is an array then the key names need to be repeated
                if (jQuery.isArray(a[j]))
                jQuery.each(a[j], function() {
                    add(j, this);
                });
            else
                add(j, jQuery.isFunction(a[j]) ? a[j]() : a[j]);

            // Return the resulting serialization
            return s.join("&").replace(/%20/g, "+");
        }

    });
    var elemdisplay = {},
	timerId,
	fxAttrs = [
    // height animations
		["height", "marginTop", "marginBottom", "paddingTop", "paddingBottom"],
    // width animations
		["width", "marginLeft", "marginRight", "paddingLeft", "paddingRight"],
    // opacity animations
		["opacity"]
	];

    function genFx(type, num) {
        var obj = {};
        jQuery.each(fxAttrs.concat.apply([], fxAttrs.slice(0, num)), function() {
            obj[this] = type;
        });
        return obj;
    }

    jQuery.fn.extend({
        show: function(speed, callback) {
            if (speed) {
                return this.animate(genFx("show", 3), speed, callback);
            } else {
                for (var i = 0, l = this.length; i < l; i++) {
                    var old = jQuery.data(this[i], "olddisplay");

                    this[i].style.display = old || "";

                    if (jQuery.css(this[i], "display") === "none") {
                        var tagName = this[i].tagName, display;

                        if (elemdisplay[tagName]) {
                            display = elemdisplay[tagName];
                        } else {
                            var elem = jQuery("<" + tagName + " />").appendTo("body");

                            display = elem.css("display");
                            if (display === "none")
                                display = "block";

                            elem.remove();

                            elemdisplay[tagName] = display;
                        }

                        jQuery.data(this[i], "olddisplay", display);
                    }
                }

                // Set the display of the elements in a second loop
                // to avoid the constant reflow
                for (var i = 0, l = this.length; i < l; i++) {
                    this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
                }

                return this;
            }
        },

        hide: function(speed, callback) {
            if (speed) {
                return this.animate(genFx("hide", 3), speed, callback);
            } else {
                for (var i = 0, l = this.length; i < l; i++) {
                    var old = jQuery.data(this[i], "olddisplay");
                    if (!old && old !== "none")
                        jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
                }

                // Set the display of the elements in a second loop
                // to avoid the constant reflow
                for (var i = 0, l = this.length; i < l; i++) {
                    this[i].style.display = "none";
                }

                return this;
            }
        },

        // Save the old toggle function
        _toggle: jQuery.fn.toggle,

        toggle: function(fn, fn2) {
            var bool = typeof fn === "boolean";

            return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle.apply(this, arguments) :
			fn == null || bool ?
				this.each(function() {
				    var state = bool ? fn : jQuery(this).is(":hidden");
				    jQuery(this)[state ? "show" : "hide"]();
				}) :
				this.animate(genFx("toggle", 3), fn, fn2);
        },

        fadeTo: function(speed, to, callback) {
            return this.animate({ opacity: to }, speed, callback);
        },

        animate: function(prop, speed, easing, callback) {
            var optall = jQuery.speed(speed, easing, callback);

            return this[optall.queue === false ? "each" : "queue"](function() {

                var opt = jQuery.extend({}, optall), p,
				hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
				self = this;

                for (p in prop) {
                    if (prop[p] == "hide" && hidden || prop[p] == "show" && !hidden)
                        return opt.complete.call(this);

                    if ((p == "height" || p == "width") && this.style) {
                        // Store display property
                        opt.display = jQuery.css(this, "display");

                        // Make sure that nothing sneaks out
                        opt.overflow = this.style.overflow;
                    }
                }

                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 (/toggle|show|hide/.test(val))
                        e[val == "toggle" ? hidden ? "show" : "hide" : val](prop);
                    else {
                        var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
						start = e.cur(true) || 0;

                        if (parts) {
                            var end = parseFloat(parts[2]),
							unit = parts[3] || "px";

                            // We need to compute starting value
                            if (unit != "px") {
                                self.style[name] = (end || 1) + unit;
                                start = ((end || 1) / e.cur(true)) * start;
                                self.style[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;
        }

    });

    // 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" }
    }, function(name, props) {
        jQuery.fn[name] = function(speed, callback) {
            return this.animate(props, speed, callback);
        };
    });

    jQuery.extend({

        speed: function(speed, easing, fn) {
            var opt = typeof speed === "object" ? 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 :
			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);

            // Set display property to block for height/width animations
            if ((this.prop == "height" || this.prop == "width") && this.elem.style)
                this.elem.style.display = "block";
        },

        // Get the current size
        cur: function(force) {
            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, force));
            return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
        },

        // Start an animation from one number to another
        custom: function(from, to, unit) {
            this.startTime = now();
            this.start = from;
            this.end = to;
            this.unit = unit || this.unit || "px";
            this.now = this.start;
            this.pos = this.state = 0;

            var self = this;
            function t(gotoEnd) {
                return self.step(gotoEnd);
            }

            t.elem = this.elem;

            if (t() && jQuery.timers.push(t) && !timerId) {
                timerId = setInterval(function() {
                    var timers = jQuery.timers;

                    for (var i = 0; i < timers.length; i++)
                        if (!timers[i]())
                        timers.splice(i--, 1);

                    if (!timers.length) {
                        clearInterval(timerId);
                        timerId = undefined;
                    }
                }, 13);
            }
        },

        // Simple 'show' function
        show: function() {
            // Remember where we started, so that we can go back to it later
            this.options.orig[this.prop] = jQuery.attr(this.elem.style, 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.attr(this.elem.style, this.prop);
            this.options.hide = true;

            // Begin the animation
            this.custom(this.cur(), 0);
        },

        // Each step of an animation
        step: function(gotoEnd) {
            var t = now();

            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;

                var done = true;
                for (var i in this.options.curAnim)
                    if (this.options.curAnim[i] !== true)
                    done = false;

                if (done) {
                    if (this.options.display != null) {
                        // Reset the overflow
                        this.elem.style.overflow = this.options.overflow;

                        // Reset the display
                        this.elem.style.display = this.options.display;
                        if (jQuery.css(this.elem, "display") == "none")
                            this.elem.style.display = "block";
                    }

                    // 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.attr(this.elem.style, 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
                this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](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, {
        speeds: {
            slow: 600,
            fast: 200,
            // Default speed
            _default: 400
        },
        step: {

            opacity: function(fx) {
                jQuery.attr(fx.elem.style, "opacity", fx.now);
            },

            _default: function(fx) {
                if (fx.elem.style && fx.elem.style[fx.prop] != null)
                    fx.elem.style[fx.prop] = fx.now + fx.unit;
                else
                    fx.elem[fx.prop] = fx.now;
            }
        }
    });
    if (document.documentElement["getBoundingClientRect"])
        jQuery.fn.offset = function() {
            if (!this[0]) return { top: 0, left: 0 };
            if (this[0] === this[0].ownerDocument.body) return jQuery.offset.bodyOffset(this[0]);
            var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
			clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
			top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop) - clientTop,
			left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
            return { top: top, left: left };
        };
    else
        jQuery.fn.offset = function() {
            if (!this[0]) return { top: 0, left: 0 };
            if (this[0] === this[0].ownerDocument.body) return jQuery.offset.bodyOffset(this[0]);
            jQuery.offset.initialized || jQuery.offset.initialize();

            var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
			doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
			body = doc.body, defaultView = doc.defaultView,
			prevComputedStyle = defaultView.getComputedStyle(elem, null),
			top = elem.offsetTop, left = elem.offsetLeft;

            while ((elem = elem.parentNode) && elem !== body && elem !== docElem) {
                computedStyle = defaultView.getComputedStyle(elem, null);
                top -= elem.scrollTop, left -= elem.scrollLeft;
                if (elem === offsetParent) {
                    top += elem.offsetTop, left += elem.offsetLeft;
                    if (jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)))
                        top += parseInt(computedStyle.borderTopWidth, 10) || 0,
					left += parseInt(computedStyle.borderLeftWidth, 10) || 0;
                    prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
                }
                if (jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible")
                    top += parseInt(computedStyle.borderTopWidth, 10) || 0,
				left += parseInt(computedStyle.borderLeftWidth, 10) || 0;
                prevComputedStyle = computedStyle;
            }

            if (prevComputedStyle.position === "relative" || prevComputedStyle.position === "static")
                top += body.offsetTop,
			left += body.offsetLeft;

            if (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() {
            if (this.initialized) return;
            var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
			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>';

            rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
            for (prop in rules) container.style[prop] = rules[prop];

            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);

            innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
            this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

            body.style.marginTop = '1px';
            this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
            body.style.marginTop = bodyMarginTop;

            body.removeChild(container);
            this.initialized = true;
        },

        bodyOffset: function(body) {
            jQuery.offset.initialized || jQuery.offset.initialize();
            var top = body.offsetTop, left = body.offsetLeft;
            if (jQuery.offset.doesNotIncludeMarginInBodyOffset)
                top += parseInt(jQuery.curCSS(body, 'marginTop', true), 10) || 0,
			left += parseInt(jQuery.curCSS(body, 'marginLeft', true), 10) || 0;
            return { top: top, left: left };
        }
    };


    jQuery.fn.extend({
        position: function() {
            var left = 0, top = 0, results;

            if (this[0]) {
                // Get *real* offsetParent
                var offsetParent = this.offsetParent(),

                // Get correct offsets
			offset = this.offset(),
			parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { 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 -= num(this, 'marginTop');
                offset.left -= num(this, 'marginLeft');

                // Add offsetParent borders
                parentOffset.top += num(offsetParent, 'borderTopWidth');
                parentOffset.left += num(offsetParent, 'borderLeftWidth');

                // Subtract the two offsets
                results = {
                    top: offset.top - parentOffset.top,
                    left: offset.left - parentOffset.left
                };
            }

            return results;
        },

        offsetParent: function() {
            var offsetParent = this[0].offsetParent || document.body;
            while (offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static'))
                offsetParent = offsetParent.offsetParent;
            return jQuery(offsetParent);
        }
    });


    // Create scrollLeft and scrollTop methods
    jQuery.each(['Left', 'Top'], function(i, name) {
        var method = 'scroll' + name;

        jQuery.fn[method] = function(val) {
            if (!this[0]) return null;

            return val !== undefined ?

            // Set the scroll offset
			this.each(function() {
			    this == window || this == document ?
					window.scrollTo(
						!i ? val : jQuery(window).scrollLeft(),
						 i ? val : jQuery(window).scrollTop()
					) :
					this[method] = val;
			}) :

            // Return the scroll offset
			this[0] == window || this[0] == document ?
				self[i ? 'pageYOffset' : 'pageXOffset'] ||
					jQuery.boxModel && document.documentElement[method] ||
					document.body[method] :
				this[0][method];
        };
    });
    // Create innerHeight, innerWidth, outerHeight and outerWidth methods
    jQuery.each(["Height", "Width"], function(i, name) {

        var tl = i ? "Left" : "Top",  // top or left
		br = i ? "Right" : "Bottom", // bottom or right
		lower = name.toLowerCase();

        // innerHeight and innerWidth
        jQuery.fn["inner" + name] = function() {
            return this[0] ?
			jQuery.css(this[0], lower, false, "padding") :
			null;
        };

        // outerHeight and outerWidth
        jQuery.fn["outer" + name] = function(margin) {
            return this[0] ?
			jQuery.css(this[0], lower, false, margin ? "margin" : "border") :
			null;
        };

        var type = name.toLowerCase();

        jQuery.fn[type] = function(size) {
            // Get window width or height
            return this[0] == window ?
            // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			document.compatMode == "CSS1Compat" && document.documentElement["client" + name] ||
			document.body["client" + name] :

            // Get document width or height
			this[0] == document ?
            // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
				Math.max(
					document.documentElement["client" + name],
					document.body["scroll" + name], document.documentElement["scroll" + name],
					document.body["offset" + name], document.documentElement["offset" + name]
				) :

            // Get or set width or height on the element
				size === undefined ?
            // Get width or height on the element
					(this.length ? jQuery.css(this[0], type) : null) :

            // Set the width or height on the element (default to pixels if value is unitless)
					this.css(type, typeof size === "string" ? size : size + "px");
        };

    });
})();
var NewsPopup = {
    id: '',
    pageIndex: '',
    pageSize: 1,
    isMax: false,

    init: function() {
        $("#closeNews").click(function() { NewsPopup.closePopup(); });
        $("#btnBack").click(function() { NewsPopup.backImage(); });
        $("#btnNext").click(function() { NewsPopup.nextImage(); });
        
        document.getElementById('newsImage').onerror = 
            function() {
                 document.getElementById('newsImage').src = "App_Themes/Images/PageNotFound-Man.jpg";
            };
    },

    successPopup: function(image, max) {
        document.getElementById('newsImage').src = image;
        NewsPopup.hideLoader();
        if (max == true)
            document.getElementById('nextIcon').style.visibility = 'hidden';
    },

    showPopup: function(pageIndex, pageSize) {
        document.getElementById('popUpNews').style.display = 'block';
        document.getElementById('backIcon').style.visibility = 'hidden';
        NewsPopup.pageSize = pageSize;
        NewsPopup.pageIndex = pageIndex;
        var images = new Images();
        images.GetNews(pageIndex, pageSize);
    },

    closePopup: function() {
        document.getElementById('popUpNews').style.display = 'none';
        document.getElementById('newsImage').src = "";
        NewsPopup.id = "";
    },

    nextImage: function() {
        document.getElementById('newsImage').src="App_Themes/Images/noImage.gif";

        if (!NewsPopup.isMax) {
            NewsPopup.pageIndex++;
            NewsPopup.getNews(NewsPopup.pageIndex, 1);
            document.getElementById('nextIcon').style.visibility = 'visible';
            document.getElementById('backIcon').style.visibility = 'visible';
        }
        else {
            document.getElementById('nextIcon').style.visibility = 'hidden';
        }
 
    },
    backImage: function() {
        document.getElementById('newsImage').src="App_Themes/Images/noImage.gif";
        
        if (NewsPopup.pageIndex > 0) {
            NewsPopup.pageIndex--;
            NewsPopup.getNews(NewsPopup.pageIndex, 1);
            document.getElementById('nextIcon').style.visibility = 'visible';
            document.getElementById('backIcon').style.visibility = 'visible';
            if (NewsPopup.pageIndex <= 0)
                document.getElementById('backIcon').style.visibility = 'hidden';
        }
        else
            document.getElementById('backIcon').style.visibility = 'hidden';
            

    },

    getNews: function(pageIndex, pageSize) {
        var images = new Images();
        images.GetNews(pageIndex, pageSize);
    },
    
    showLoader : function(){
        document.getElementById("loadNews").style.display = "block";
        document.getElementById("newsImage").style.visibility = "hidden";
    },
    
    hideLoader  : function(){
        document.getElementById("newsImage").style.visibility = "visible";
        document.getElementById("loadNews").style.display = "none";
    }
};

$(document).ready(function(){
    NewsPopup.init();
});
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 07/06/2008 +r13
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmBackground',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);
var ForgotPasswordController = {
    init: function() {
        $("#closeForgot").click(function() { ForgotPasswordController.closePopupForgot(); });
        $("#closeForgotConfirm").click(function() { ForgotPasswordController.closePopupForgotConfirm(); });
        $("#ConfirmForgotPassword").click(function() { ForgotPasswordController.closePopupForgotConfirm(); });
        $("#sendForgotPassword").click(function() { ForgotPasswordController.sendForgotPassword(); });
    },

    closePopupForgotConfirm: function() {
    document.getElementById('popUpForgotConfirm').style.display = 'none';
    },

    closePopupForgot: function() {
        document.getElementById('popUpForgot').style.display = 'none';
    },

    showPopupForgot: function() {
        document.getElementById('popUpForgot').style.display = 'block';
    },

    sendForgotPassword: function() {
        var email = $("#forgotEmail").val();
        if (email != "") {
            var users = new Users();
            users.forgotPassword(email);
        }
    },

    changePopup: function() {
        document.getElementById('popUpForgotConfirm').style.display = 'block';
        document.getElementById('popUpForgot').style.display = 'none';
    }

}   
$(document).ready(function() {
    ForgotPasswordController.init();
});
/***********************************************************
                    AJAX Helper
***********************************************************/

/*global $*/

var AjaxHelper = {
    Call:
    function(service, method, postData, isAsync, successFunction) {
        $.ajax({
            type: "POST",
            url: JavaScriptConstants.ApplicationUrl +  "Controllers/Service/" + service + ".asmx/" + method,
            data: postData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: successFunction,
            async: isAsync
        });
    },

    JSONSerialize:
    function(array) {
        var jsonString = "{", i;

        for (i = 0; i < array.length; i = i + 2) {
            jsonString = jsonString.concat("'");
            jsonString = jsonString.concat(array[i]);

            if (array[i + 1] === null) {
                jsonString = jsonString.concat("' : null, ");
            }
            else {
                jsonString = jsonString.concat("' : '");
                jsonString = jsonString.concat(array[i + 1]);
                jsonString = jsonString.concat("', ");
            }
        }

        jsonString = jsonString.substr(0, jsonString.length - 2);
        jsonString = jsonString.concat("} ");
        return jsonString;
    }
};
var KeyBoardHelper = {
    //get key code
    getKeyCode: function(e) {
        var code;

        if (!e) var e = window.event;

        if (!e) e = window.event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;

        return code;
    },

    isMaxLength: function(fieldId) {
        var field = $(fieldId);
        var length = field.getAttribute("maxlength");
        if (length != null && length != "" && field.getAttribute("length") > length)
            field.value = field.value.substring(0, length);
    },
    
    cssBrowserLabeler : function() {
        var ua = navigator.userAgent.toLowerCase(),
            is = function(t){ return ua.indexOf(t) != -1; },
            h = document.getElementsByTagName('html')[0],
            b = (!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua)) ? ('ie ie' + RegExp.$1)   : 
                is('firefox/2')                                    ? 'gecko ff2'             :
                is('firefox/3')                                    ? 'gecko ff3'             :
                is('gecko/')                                       ? 'gecko'                 :
                is('opera/9')                                      ? 'opera opera9'          :
                /opera (\d)/.test(ua)                              ? 'opera opera'+RegExp.$1 :
                is('konqueror')                                    ? 'konqueror'             :
                is('chrome')                                       ? 'chrome webkit safari'  :
                is('applewebkit/')                                 ? 'webkit safari'         :
                is('mozilla/')                                     ? 'gecko'                 :'',
                
            os = (is('x11')||is('linux')) ? ' linux' :
                  is('mac')               ? ' mac'   :
                  is('win')               ? ' win'   :'';
                  
            var c = b + os + ' js';
            
            h.className += h.className ? ' ' + c : c;
    }
};

KeyBoardHelper.cssBrowserLabeler();

var Helper = {

    FunctionUnavailable: function() {
        alert('This function is currently unavailable');
    }

};
var UrlHelper = {


    /***********************************
    ************* Default **************
    ***********************************/
    GetUrl: function(val1, val2, val3) {
        var url = JavaScriptConstants.ApplicationUrl + val1;

        if (val2) {
            url += '/' + val2;

            if (val3)
                url += '/' + val3;
        }

        return url;
    },

    /***********************************
    ************* Fashion **************
    ***********************************/
    GetFashionUrl: function(category1, category2) {
        return UrlHelper.GetUrl('moda', category1, category2);
    },

    GotoFashionPage: function(category1, category2) {
        document.location.href = UrlHelper.GetUrl('moda', category1, category2);
    },

    /***********************************
    ************ Corporate *************
    ***********************************/
    GetCorporateUrl: function(category1, category2) {
        return UrlHelper.GetUrl('corporativo', category1, category2);
    },

    GotoCorporatePage: function(category1, category2) {
        document.location.href = UrlHelper.GetUrl('corporativo', category1, category2);
    },

    /***********************************
    *************** Team ***************
    ***********************************/
    GetTeamUrl: function(category1, category2) {
        return UrlHelper.GetUrl('times', category1, category2);
    },

    GotoTeamPage: function(category1, category2) {
        document.location.href = UrlHelper.GetUrl('times', category1, category2);
    },
    
    /***********************************
    **************** Pets **************
    ***********************************/
    GetPetsUrl: function(category1, category2) {
        return UrlHelper.GetUrl('pet', category1, category2);
    },

    GotoPetsPage: function(category1, category2) {
        document.location.href = UrlHelper.GetUrl('pet', category1, category2);
    },

    /***********************************
    ************** Training ************
    ***********************************/
    GetTrainingUrl: function(category1, category2) {
        return UrlHelper.GetUrl('malhacao');
    },

    GotoTrainingPage: function(category1, category2) {
        document.location.href = UrlHelper.GetUrl('malhacao');
    },

    /***********************************
    ************** MountYour ***********
    ***********************************/
    GetMountYourUrl: function() {
        return UrlHelper.GetUrl('monte-o-seu');
    },

    GotoMountYourPage: function() {
        document.location.href = UrlHelper.GetUrl('monte-o-seu');
    },

    /***********************************
    *********** Shopping Cart **********
    ***********************************/
    GetShoppingCartUrl: function() {
        return UrlHelper.GetUrl('carrinho-de-compras');
    },

    GotoShoppingCartPage: function() {
        document.location.href = UrlHelper.GetUrl('carrinho-de-compras');
    },

    /***********************************
    ************** Orders **************
    ***********************************/
    GetOrdersUrl: function() {
        return UrlHelper.GetUrl('pedido');
    },

    GotoOrdersPage: function() {
        document.location.href = UrlHelper.GetUrl('pedido');
    },

    /***********************************
    ************** Orders Confirmation**
    ***********************************/
    GetOrdersConfirmationUrl: function() {
        return UrlHelper.GetUrl('pedido', 'confirmacao');
    },

    GotoOrdersConfirmationPage: function() {
    document.location.href = UrlHelper.GetUrl('pedido', 'confirmacao');
    },

    /***********************************
    *********** Order History **********
    ***********************************/
    GetOrderHistoryUrl: function() {
        return UrlHelper.GetUrl('historico-de-compras');
    },

    GotoOrderHistoryPage: function() {
        document.location.href = UrlHelper.GetUrl('historico-de-compras');
    },

    /***********************************
    ********** Products Type ***********
    ***********************************/
    ProductsType: { Category: [], Menu: [], Id: [] },

    InsertProductTypes: function(category, menu, id) {
        UrlHelper.ProductsType.Category.push(category);
        UrlHelper.ProductsType.Menu.push(menu);
        UrlHelper.ProductsType.Id.push(id);
    },

    BindProductTypes: function() {
        UrlHelper.InsertProductTypes('moda/relogio-de-pulso/tradicional', 'Fashion/clockPulse/traditional', 1);
        UrlHelper.InsertProductTypes('moda/relogio-de-pulso/bracelete', 'Fashion/clockPulse/bracelet', 2);
        UrlHelper.InsertProductTypes('moda/relogio-de-pulso/silicone', 'Fashion/clockPulse/silicone', 3);
        UrlHelper.InsertProductTypes('moda/relogio-de-pulso/metal', 'Fashion/clockPulse/brass', 4);
        UrlHelper.InsertProductTypes('moda/relogio-de-parede', 'Fashion/wallClock', 5);
        UrlHelper.InsertProductTypes('moda/oculos-de-sol', 'Fashion/sunglasses', 6);
        UrlHelper.InsertProductTypes('moda/projetos-especiais', 'Fashion/specialProjects', 7);
        UrlHelper.InsertProductTypes('moda/strass-bracelete', 'Fashion/strassBracelet', 8);
        UrlHelper.InsertProductTypes('moda/photo-watch', 'Fashion/photoWatch', 9);

        UrlHelper.InsertProductTypes('corporativo/relogio-de-parede', 'Corporate/wallClock', 10);
        UrlHelper.InsertProductTypes('corporativo/relogio-de-mesa', 'Corporate/tableClock', 11);
        UrlHelper.InsertProductTypes('corporativo/custom-watch', 'Corporate/customWatch', 12);
        UrlHelper.InsertProductTypes('corporativo/free-watch', 'Corporate/freeWatch', 13);
        UrlHelper.InsertProductTypes('corporativo/relogio-de-pulso/tradicional', 'Corporate/clockPulse/traditional', 14);
        UrlHelper.InsertProductTypes('corporativo/relogio-de-pulso/esportivo', 'Corporate/clockPulse/sports', 15);
        UrlHelper.InsertProductTypes('corporativo/relogio-de-pulso/metal', 'Corporate/clockPulse/brass', 16);

        UrlHelper.InsertProductTypes('times/relogio-de-pulso', 'Team/clockPulse', 17);
        UrlHelper.InsertProductTypes('times/relogio-de-parede', 'Team/wallClock', 18);
        UrlHelper.InsertProductTypes('times/relogio-de-mesa', 'Team/tableClock', 19);

        UrlHelper.InsertProductTypes('pet/relogio-de-parede', 'Pets/wallClock', 20);
        UrlHelper.InsertProductTypes('pet/relogio-de-pulso/relogio-de-couro', 'Pets/clockPulse/leather', 21);
        UrlHelper.InsertProductTypes('pet/relogio-de-pulso/silicone', 'Pets/clockPulse/silicone', 22);

        UrlHelper.InsertProductTypes('malhacao', 'Training', 23);
        UrlHelper.InsertProductTypes('monte-o-seu', 'MountYour', 24);

        UrlHelper.InsertProductTypes('times/relogio-de-pulso/corinthians', 'Team/clockPulse/corinthians', 25);
        UrlHelper.InsertProductTypes('times/relogio-de-pulso/palmeiras', 'Team/clockPulse/palmeiras', 26);
        UrlHelper.InsertProductTypes('times/relogio-de-pulso/sao-paulo', 'Team/clockPulse/sao-paulo', 27);
        UrlHelper.InsertProductTypes('times/relogio-de-pulso/santos', 'Team/clockPulse/santos', 28);

        UrlHelper.InsertProductTypes('times/relogio-de-parede/corinthians', 'Team/wallClock/corinthians', 29);
        UrlHelper.InsertProductTypes('times/relogio-de-parede/palmeiras', 'Team/wallClock/palmeiras', 30);
        UrlHelper.InsertProductTypes('times/relogio-de-parede/sao-paulo', 'Team/wallClock/sao-paulo', 31);
        UrlHelper.InsertProductTypes('times/relogio-de-parede/santos', 'Team/wallClock/santos', 32);

        UrlHelper.InsertProductTypes('times/relogio-de-mesa/corinthians', 'Team/tableClock/corinthians', 33);
        UrlHelper.InsertProductTypes('times/relogio-de-mesa/palmeiras', 'Team/tableClock/palmeiras', 34);
        UrlHelper.InsertProductTypes('times/relogio-de-mesa/sao-paulo', 'Team/tableClock/sao-paulo', 35);
        UrlHelper.InsertProductTypes('times/relogio-de-mesa/santos', 'Team/tableClock/santos', 36);

    },
    GetProductTypeIdAndSetMenu: function(category) {
        category = category.replace(/[\/]$/, '').replace(/^[\/]/, '');

        var id = 0;
        for (var i = 0; i < UrlHelper.ProductsType.Category.length; i++) {
            if (UrlHelper.ProductsType.Category[i] == category.replace(JavaScriptConstants.VirtualPath, "")) {
                id = UrlHelper.ProductsType.Id[i];
                var menu = UrlHelper.ProductsType.Menu[i].split('/');
                HearderMenu.defaultPage = menu[0].toLowerCase() == 'mountyour' ? 'mountYour' : menu[0].toLowerCase();
                HearderMenu.defaultMenu = menu.length > 1 ? 'mainSubMenu' + menu[0] : '0';
                if (menu[2] == "corinthians" || menu[2] == "palmeiras" || menu[2] == "sao-paulo" || menu[2] == "santos")
                    HearderMenu.defaultSubMenu = '0';
                else
                    HearderMenu.defaultSubMenu = menu.length > 2 ? 'subMenu' + menu[0] : '0';
                HearderMenu.defaultSubId = menu.length > 1 ? menu[1] + menu[0] : '0';
                if (menu[2] == "corinthians" || menu[2] == "palmeiras" || menu[2] == "sao-paulo" || menu[2] == "santos")
                    HearderMenu.defaultSubItemId = '0';
                else
                    HearderMenu.defaultSubItemId = menu.length > 2 ? menu[2] + menu[0] : '0';
                HearderMenu.activeId = HearderMenu.defaultPage;
                HearderMenu.activeMenuId = HearderMenu.defaultMenu;
                HearderMenu.activeSubMenu = HearderMenu.defaultSubMenu;
                HearderMenu.subId = HearderMenu.defaultSubId;
            }
        }

        return id;
    }

};

UrlHelper.BindProductTypes();
var HearderMenu = {
    activeId: '0',
    activeMenuId: '0',
    activeSubMenu: '0',
    subId: '0',
    isTrue: '0',
    defaultPage: 'mountYour', //FIRST LINE   
    defaultMenu: '0', //SECOND LINE
    defaultSubMenu: '0', //THIRD LINE
    defaultSubId: '0', //SECOND LINE ITE
    defaultSubItemId: '0',
    teamActive: '0',
    location: '',
    userId: null,
    userName: null,
    password: null,
    quantityItens:0,

    init: function() {
        HearderMenu.setDefault();
        $("#home").attr("href", JavaScriptConstants.ApplicationUrl + "home");
        $("#logoHome").attr("href", JavaScriptConstants.ApplicationUrl + "home");
        $("#company").attr("href", JavaScriptConstants.ApplicationUrl + "empresa");
        $("#contact").attr("href", JavaScriptConstants.ApplicationUrl + "contato");
        $("#wholesale").attr("href", JavaScriptConstants.ApplicationUrl + "cadastro-atacado");
        $("#editDetails").attr("href", JavaScriptConstants.ApplicationUrl + "alterar-dados");
        $("#retail").attr("href", JavaScriptConstants.ApplicationUrl + "cadastro-varejo");
        $("#register").click(function() { HearderMenu.showRegister(); });
        $("#registerItems").mouseout(function() { setTimeout(function() { HearderMenu.hideRegister(); }, 3000); });
        $("#news").attr("href", "javascript:NewsPopup.showPopup(0,1);");

        //LOGON
        HearderMenu.userId = document.getElementById('userId').innerHTML;
        HearderMenu.userName = $('#userName').val();
        HearderMenu.password = $('#password').val();
        HearderMenu.location = window.location;
        $("#OkButton").attr("href", "javascript:HearderMenu.authenticate();");
        $("#LogOff").attr("href", "javascript:HearderMenu.LogOffUser();");
        $("#forgotPassword").attr("href", "javascript:ForgotPasswordController.showPopupForgot();");
        $("#OrderHistory").attr("href", JavaScriptConstants.ApplicationUrl + "historico-de-compras");

        //MENU
        $("#fashion").click(function() { HearderMenu.subMenuShow("fashion", "mainSubMenuFashion"); });
        $("#corporate").click(function() { HearderMenu.subMenuShow("corporate", "mainSubMenuCorporate"); });
        $("#team").click(function() { HearderMenu.subMenuShow("team", "mainSubMenuTeam"); });
        $("#pets").click(function() { HearderMenu.subMenuShow("pets", "mainSubMenuPets"); });
        $("#training").click(function() { HearderMenu.subMenuShow("training", "0"); UrlHelper.GotoTrainingPage(); });
        $("#mountYour").click(function() { HearderMenu.subMenuShow("mountYour", "0"); UrlHelper.GotoMountYourPage(); });

        //SUBMENU
        $("#clockPulseFashion").click(function() { HearderMenu.subMenuShowItems("clockPulseFashion", "subMenuFashion"); });
        $("#clockPulseCorporate").click(function() { HearderMenu.subMenuShowItems("clockPulseCorporate", "subMenuCorporate"); });
        $("#clockPulsePets").click(function() { HearderMenu.subMenuShowItems("clockPulsePets", "subMenuPets"); });

        //MENU FASHION LINKS
        $("#wallClockFashion").click(function() { UrlHelper.GotoFashionPage("relogio-de-parede"); });
        $("#sunglassesFashion").click(function() { UrlHelper.GotoFashionPage("oculos-de-sol"); });
        $("#specialProjectsFashion").click(function() { UrlHelper.GotoFashionPage("projetos-especiais"); });
        $("#strassBraceletFashion").click(function() { UrlHelper.GotoFashionPage("strass-bracelete"); });
        $("#photoWatchFashion").click(function() { UrlHelper.GotoFashionPage("photo-watch"); });
        $("#traditionalFashion").click(function() { UrlHelper.GotoFashionPage("relogio-de-pulso", "tradicional"); });
        $("#braceletFashion").click(function() { UrlHelper.GotoFashionPage("relogio-de-pulso", "bracelete"); });
        $("#siliconeFashion").click(function() { UrlHelper.GotoFashionPage("relogio-de-pulso", "silicone"); });
        $("#brassFashion").click(function() { UrlHelper.GotoFashionPage("relogio-de-pulso", "metal"); });
        //MENU CORPORATE LINKS
        $("#wallClockCorporate").click(function() { UrlHelper.GotoCorporatePage("relogio-de-parede"); });
        $("#tableClockCorporate").click(function() { UrlHelper.GotoCorporatePage("relogio-de-mesa"); });
        $("#customWatchCorporate").click(function() { UrlHelper.GotoCorporatePage("custom-watch"); /*location.href = JavaScriptConstants.ApplicationUrl + "CustomWatch.aspx" */});
        $("#freeWatchCorporate").click(function() { UrlHelper.GotoCorporatePage("free-watch"); /*location.href = JavaScriptConstants.ApplicationUrl + "FreeWatch.aspx"*/ });
        $("#traditionalCorporate").click(function() { UrlHelper.GotoCorporatePage("relogio-de-pulso", "tradicional"); });
        $("#sportsCorporate").click(function() { UrlHelper.GotoCorporatePage("relogio-de-pulso", "esportivo"); });
        $("#brassCorporate").click(function() { UrlHelper.GotoCorporatePage("relogio-de-pulso", "metal"); });
        //MENU TEAM LINKS
        $("#clockPulseTeam").click(function() { UrlHelper.GotoTeamPage("relogio-de-pulso", "corinthians"); });
        $("#wallClockTeam").click(function() { UrlHelper.GotoTeamPage("relogio-de-parede", "corinthians"); });
        $("#tableClockTeam").click(function() { UrlHelper.GotoTeamPage("relogio-de-mesa", "corinthians"); });
        //MENU PETS LINKS
        $("#wallClockPets").click(function() { UrlHelper.GotoPetsPage("relogio-de-parede"); });
        $("#leatherPets").click(function() { UrlHelper.GotoPetsPage("relogio-de-pulso", "relogio-de-couro"); });
        $("#siliconePets").click(function() { UrlHelper.GotoPetsPage("relogio-de-pulso", "silicone"); });

        $("div[class*='enuItems']").each(function() {

            $(this).mousemove(function() {
                HearderMenu.setIsTrue();
            });
            $(this).mouseout(function() {
                HearderMenu.setDefault();
            });
        });

        
        HearderMenu.getShoppingCartsQuantity();
    },
    
    getShoppingCartsQuantity : function(){
        var shoppingCartsProxy = new ShoppingCarts();
        shoppingCartsProxy.GetShoppingCartsQuantity(HearderMenu.setQuantity);
    },
    
    setQuantity : function(data)
    {
        HearderMenu.quantityItens = data;
        document.getElementById("cartsQuantity").innerHTML = " " +HearderMenu.quantityItens+ " ";
    },

    showRegister: function() {
        $("#registerItems").attr("style", "diasplay:block;");
    },

    hideRegister: function() {
        $("#registerItems").attr("style", "diasplay:none;");
    },

    subMenuShow: function(id, menu) {
        if (HearderMenu.activeId != '0')
            document.getElementById(HearderMenu.activeId).className = "menuItemsWhite";
        if (HearderMenu.activeMenuId != '0') {
            document.getElementById(HearderMenu.activeMenuId).style.display = "none";
            document.getElementById(HearderMenu.subId).className = "menuItemsWhite";
        }
        if (HearderMenu.activeSubMenu != '0') {
            document.getElementById(HearderMenu.activeSubMenu).style.display = "none";
            document.getElementById(HearderMenu.subId).className = "menuItemsWhite";
        }
        if (id != '0')
            document.getElementById(id).className = "menuItems";
        if (menu != '0') {
            document.getElementById(menu).style.display = "block";
            HearderMenu.activeId = id;
            HearderMenu.activeMenuId = menu;
        }
        HearderMenu.subId = id;
        HearderMenu.activeSubMenu = menu;
    },

    subMenuShowItems: function(id, menu) {
        if (menu != '0') {
            document.getElementById(menu).style.display = "block";
            document.getElementById(id).className = "menuItems";
            HearderMenu.activeSubMenu = menu;
            HearderMenu.subId = id;
        }
    },

    setDefault: function() {
        setTimeout(function() {
            if (HearderMenu.isTrue == 'false') {
                if (HearderMenu.activeId != '0') document.getElementById(HearderMenu.activeId).className = "menuItemsWhite";
                if (HearderMenu.activeMenuId != '0') document.getElementById(HearderMenu.activeMenuId).style.display = "none";
                if (HearderMenu.activeSubMenu != '0') document.getElementById(HearderMenu.activeSubMenu).style.display = "none";
                if (HearderMenu.subId != '0') document.getElementById(HearderMenu.subId).className = "menuItemsWhite";

                if (HearderMenu.defaultPage != '0') document.getElementById(HearderMenu.defaultPage).className = "menuItems";
                if (HearderMenu.defaultMenu != '0') document.getElementById(HearderMenu.defaultMenu).style.display = "block";
                if (HearderMenu.defaultSubMenu != '0') document.getElementById(HearderMenu.defaultSubMenu).style.display = "block";
                if (HearderMenu.defaultSubId != '0') document.getElementById(HearderMenu.defaultSubId).className = "menuItems";
                if (HearderMenu.defaultSubItemId != '0') document.getElementById(HearderMenu.defaultSubItemId).className = "menuItems";

                HearderMenu.activeId = HearderMenu.defaultPage;
                HearderMenu.activeMenuId = HearderMenu.defaultMenu;
                HearderMenu.activeSubMenu = HearderMenu.defaultSubMenu;
                HearderMenu.subId = HearderMenu.defaultSubId;

                HearderMenu.isTrue = 'true';
                return;
            }
        }, 1000);
        HearderMenu.isTrue = 'false';
    },

    setIsTrue: function() {
        HearderMenu.isTrue = 'true';
    },

    goToUrl: function(url) {
        location.href = url;
    },

    showRegister: function() {
        $('#registerItems').attr("style", "display:block");
    },

    hideRegister: function() {
        $('#registerItems').attr("style", "display:none");
    },

    /// <summary>
    /// validate username and password
    /// </summary>
    validateFields: function() {
        var ret = false;

        HearderMenu.init();

        if (HearderMenu.userName === '' || HearderMenu.userName.lenght < 2) {
            ret = false;
        }
        else {
            ret = true;
        }
        if (HearderMenu.password === '' || HearderMenu.password.lenght < 4) {
            ret = ret && false;
        }
        else {
            ret = ret = true;
        }

        return ret;
    },
    /// <summary>
    /// authenticate and log user into the system
    /// </summary>
    authenticate: function() {
        if (!HearderMenu.validateFields()) { return; }
        var usersProxy = new Users();
        usersProxy.Authenticate(
            HearderMenu.userName,
            HearderMenu.password,
            false,
            HearderMenu.location);
    },

    successCallBack: function(data) {
        if (data.Result == true)  
        {
            var usersProxy = new Users();
            usersProxy.IsRetail();
        }
        else {
            if(!data.IsApproved) {
                alert('Seus dados foram enviados para consulta, por favor aguarde nosso contato!');
                window.location = JavaScriptConstants.ApplicationUrl + "moda/relogio-de-pulso/tradicional"; 
            }
            else {
                alert("Usuário ou senha inválidos!"); 
            }
        }
    },
    
    isEnabled : function(data){
         if (data.Result) { 
            if(window.location == (JavaScriptConstants.ApplicationUrl + "cadastro-varejo#"))
                window.location = JavaScriptConstants.ApplicationUrl + "moda/relogio-de-pulso/tradicional"; 
            else
                window.location = window.location;
        } 
        else { 
            alert("Cadastro em análise.");
            
            return false; 
            
            window.location = JavaScriptConstants.ApplicationUrl + "moda/relogio-de-pulso/tradicional"; 
       }
               
    },

    LogOffUser: function() {
        var usersProxy = new Users();
        usersProxy.logOffUser(HearderMenu.location);
    },

    headerNoDefault: function() {
        HearderMenu.defaultPage = '0';
        HearderMenu.defaultMenu = '0';
        HearderMenu.defaultSubMenu = '0';
        HearderMenu.defaultSubId = '0';
        HearderMenu.defaultSubItemId = '0';
    }
};

$(document).ready(function(){
    HearderMenu.init();
});


var QuotePopupController = {
    productId: '',
    Name: '',
    Email: '',
    Phone: '',
    Description: '',

    init: function() {
        $("#closeQuote").click(function() { QuotePopupController.closeQuotePopup(); });
        $("#QuoteSendButton").click(function() { QuotePopupController.sendQuoteProduct(); });
        $("#closeQuoteConfirm").click(function() { QuotePopupController.closeQuoteConfirmPopup(); });
        $("#QuoteConfirmButton").click(function() { QuotePopupController.closeQuoteConfirmPopup(); });
    },

    getProductInfo: function(id) {
        var products = new Products();
        products.GetProductById(id);
    },

    showPopup: function(data) {
        
        document.getElementById("limit").insertBefore(
            document.getElementById("popUpQuote"), document.getElementById("popUpNews"));
            
        document.getElementById("popUpQuote").style.display = "block";

        document.getElementById("productImagePath").src = data.ImagePath;
        document.getElementById("productId").innerHTML = data.Id;
        document.getElementById("UserNameQuote").value = data.Name;
        document.getElementById("userEmail").value = data.Email;
        document.getElementById("userPhone").value = data.Phone;
    },

    sendQuoteProduct: function() {
        if (QuotePopupController.setVariables()) {
            var quotes = new Quotes();
            quotes.sendQuoteProduct(
                QuotePopupController.productId,
                QuotePopupController.Name,
                QuotePopupController.Email,
                QuotePopupController.Phone,
                QuotePopupController.Description);
        }
    },

    setVariables: function() {
        if (document.getElementById("productId").innerHTML == "") return false;
        QuotePopupController.productId = document.getElementById("productId").innerHTML;
        if ($("#UserNameQuote").val() == "") return false;
        QuotePopupController.Name = $("#UserNameQuote").val();
        if ($("#userEmail").val() == "") return false;
        QuotePopupController.Email = $("#userEmail").val();
        if ($("#userPhone").val() == "") return false;
        QuotePopupController.Phone = $("#userPhone").val();
        if ($("#quoteDescription").val() == "") return false;
        QuotePopupController.Description = $("#quoteDescription").val();

        return true;
    },

    closeQuotePopup: function() {
        document.getElementById("popUpQuote").style.display = "none";
    },

    showConfimationPopup: function(data) {
        QuotePopupController.closeQuotePopup();
        document.getElementById("popUpQuoteConfirm").style.display = "block";

        document.getElementById("limit").insertBefore(
        document.getElementById("popUpQuoteConfirm"), document.getElementById("popUpNews"));
        document.getElementById("quoteId").innerHTML = data.QuoteId;
        document.getElementById("quoteCreated").innerHTML = data.QuoteCreated;
    },

    closeQuoteConfirmPopup: function() {
        document.getElementById("popUpQuoteConfirm").style.display = "none";
    }


}
$(document).ready(function() {
    QuotePopupController.init();
});
var BannerController = {
    categoryId: '',
    init: function() {

    }
}
$(document).ready(function() {
    BannerController.init();
});
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
        	this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
            	i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                   // alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);

/**
 * @fileoverview This file contains miscellaneous basic functionality.
 *
 */

/**
 * Creates a DOM element with the given tag name in the document of the
 * owner element.
 *
 * @param {String} tagName  The name of the tag to create.
 * @param {Element} owner The intended owner (i.e., parent element) of
 * the created element.
 * @param {Point} opt_position  The top-left corner of the created element.
 * @param {Size} opt_size  The size of the created element.
 * @param {Boolean} opt_noAppend Do not append the new element to the owner.
 * @return {Element}  The newly created element node.
 */
function createElement(tagName, owner, opt_position, opt_size, opt_noAppend) {
  var element = ownerDocument(owner).createElement(tagName);
  if (opt_position) {
    setPosition(element, opt_position);
  }
  if (opt_size) {
    setSize(element, opt_size);
  }
  if (owner && !opt_noAppend) {
    appendChild(owner, element);
  }

  return element;
}

/**
 * Creates a text node with the given value.
 *
 * @param {String} value  The text to place in the new node.
 * @param {Element} owner The owner (i.e., parent element) of the new
 * text node.
 * @return {Text}  The newly created text node.
 */
function createTextNode(value, owner) {
  var element = ownerDocument(owner).createTextNode(value);
  if (owner) {
    appendChild(owner, element);
  }
  return element;
}

/**
 * Returns the document owner of the given element. In particular,
 * returns window.document if node is null or the browser does not
 * support ownerDocument.
 *
 * @param {Node} node  The node whose ownerDocument is required.
 * @returns {Document|Null}  The owner document or null if unsupported.
 */
function ownerDocument(node) {
  return (node ? node.ownerDocument : null) || document;
}

/**
 * Wrapper function to create CSS units (pixels) string
 *
 * @param {Number} numPixels  Number of pixels, may be floating point.
 * @returns {String}  Corresponding CSS units string.
 */
function px(numPixels) {
  return round(numPixels) + "px";
}

/**
 * Sets the left and top of the given element to the given point.
 *
 * @param {Element} element  The dom element to manipulate.
 * @param {Point} point  The desired position.
 */
function setPosition(element, point) {
  var style = element.style;
  style.position = "absolute";
  style.left = px(point.x);
  style.top = px(point.y);
}

/**
 * Sets the width and height style attributes to the given size.
 *
 * @param {Element} element  The dom element to manipulate.
 * @param {Size} size  The desired size.
 */
function setSize(element, size) {
  var style = element.style;
  style.width = px(size.width);
  style.height = px(size.height);
}

/**
 * Sets display to none. Doing this as a function saves a few bytes for
 * the 'style.display' property and the 'none' literal.
 *
 * @param {Element} node  The dom element to manipulate.
 */
function displayNone(node) {
  node.style.display = 'none';
}

/**
 * Sets display to default.
 *
 * @param {Element} node  The dom element to manipulate.
 */
function displayDefault(node) {
  node.style.display = '';
}

function visibilityHidden(node) {
    node.style.visibility = 'hidden';
}

function visibilityDefault(node) {
    node.style.visibility = '';
}

/**
 * Appends the given child to the given parent in the DOM
 *
 * @param {Element} parent  The parent dom element.
 * @param {Node} child  The new child dom node.
 */
function appendChild(parent, child) {
  parent.appendChild(child);
}


/**
 * Wrapper for the eval() builtin function to evaluate expressions and
 * obtain their value. It wraps the expression in parentheses such
 * that object literals are really evaluated to objects. Without the
 * wrapping, they are evaluated as block, and create syntax
 * errors. Also protects against other syntax errors in the eval()ed
 * code and returns null if the eval throws an exception.
 *
 * @param {String} expr
 * @return {Object|Null}
 */
function jsEval(expr) {
  try {
    if(typeof expr != 'object')
        return eval('[' + expr + '][0]');
    return expr;
  } catch (e) {
    return null;
  }
}


/**
 * Wrapper for the eval() builtin function to execute statements. This
 * guards against exceptions thrown, but doesn't return a
 * value. Still, mostly for testability, it returns a boolean to
 * indicate whether execution was successful. NOTE:
 * javascript's eval semantics is murky in that it confounds
 * expression evaluation and statement execution into a single
 * construct. Cf. jsEval().
 *
 * @param {String} stmt
 * @return {Boolean}
 */
function jsExec(stmt) {
  try {
    eval(stmt);
    return true;
  } catch (e) {
    return false;
  }
}


/**
 * Wrapper for eval with a context. NOTE: The style guide
 * deprecates eval, so this is the exception that proves the
 * rule. Notice also that since the value of the expression is
 * returned rather than assigned to a local variable, one major
 * objection aganist the use of the with() statement, namely that
 * properties of the with() target override local variables of the
 * same name, is void here.
 *
 * @param {String} expr
 * @param {Object} context
 * @return {Object|Null}
 */
function jsEvalWith(expr, context) {
  try {
    with (context) {
      return eval('[' + expr + '][0]');
    }
  } catch (e) {
    return null;
  }
}


var DOM_ELEMENT_NODE = 1;
var DOM_ATTRIBUTE_NODE = 2;
var DOM_TEXT_NODE = 3;
var DOM_CDATA_SECTION_NODE = 4;
var DOM_ENTITY_REFERENCE_NODE = 5;
var DOM_ENTITY_NODE = 6;
var DOM_PROCESSING_INSTRUCTION_NODE = 7;
var DOM_COMMENT_NODE = 8;
var DOM_DOCUMENT_NODE = 9;
var DOM_DOCUMENT_TYPE_NODE = 10;
var DOM_DOCUMENT_FRAGMENT_NODE = 11;
var DOM_NOTATION_NODE = 12;

/**
 * Traverses the element nodes in the DOM tree underneath the given
 * node and finds the first node with elemId, or null if there is no such
 * element.  Traversal is in depth-first order.
 *
 * NOTE: The reason this is not combined with the elem() function is
 * that the implementations are different.
 * elem() is a wrapper for the built-in document.getElementById() function,
 * whereas this function performs the traversal itself.
 * Modifying elem() to take an optional root node is a possibility,
 * but the in-built function would perform better than using our own traversal.
 *
 * @param {Element} node Root element of subtree to traverse.
 * @param {String} elemId The id of the element to search for.
 * @return {Element|Null} The corresponding element, or null if not found.
 */
function nodeGetElementById(node, elemId) {
  for (var c = node.firstChild; c; c = c.nextSibling) {
    if (c.id == elemId) {
      return c;
    }
    if (c.nodeType == DOM_ELEMENT_NODE) {
      var n = arguments.callee.call(this, c, elemId);
      if (n) {
        return n;
      }
    }
  }
  return null;
}


/**
 * Get an attribute from the DOM.  Simple redirect, exists to compress code.
 *
 * @param {Element} node  Element to interrogate.
 * @param {String} name  Name of parameter to extract.
 * @return {String}  Resulting attribute.
 */
function domGetAttribute(node, name) {
  return node.attributes[name];
}

/**
 * Set an attribute in the DOM.  Simple redirect to compress code.
 *
 * @param {Element} node  Element to interrogate.
 * @param {String} name  Name of parameter to set.
 * @param {String} value  Set attribute to this value.
 */
function domSetAttribute(node, name, value) {
  node.setAttribute(name, value);
}

/**
 * Remove an attribute from the DOM.  Simple redirect to compress code.
 *
 * @param {Element} node  Element to interrogate.
 * @param {String} name  Name of parameter to remove.
 */
function domRemoveAttribute(node, name) {
  node.removeAttribute(name);
}

/**
 * Clone a node in the DOM.
 *
 * @param {Node} node  Node to clone.
 * @return {Node}  Cloned node.
 */
function domCloneNode(node) {
  return node.cloneNode(true);
}


/**
 * Return a safe string for the className of a node.
 * If className is not a string, returns "".
 *
 * @param {Element} node  DOM element to query.
 * @return {String}
 */
function domClassName(node) {
  return node.className ? "" + node.className : "";
}

/**
 * Adds a class name to the class attribute of the given node.
 *
 * @param {Element} node  DOM element to modify.
 * @param {String} className  Class name to add.
 */
function domAddClass(node, className) {
  var name = domClassName(node);
  if (name) {
    var cn = name.split(/\s+/);
    var found = false;
    for (var i = 0; i < jsLength(cn); ++i) {
      if (cn[i] == className) {
        found = true;
        break;
      }
    }

    if (!found) {
      cn.push(className);
    }

    node.className = cn.join(' ');
  } else {
    node.className = className;
  }
}

/**
 * Removes a class name from the class attribute of the given node.
 *
 * @param {Element} node  DOM element to modify.
 * @param {String} className  Class name to remove.
 */
function domRemoveClass(node, className) {
  var c = domClassName(node);
  if (!c || c.indexOf(className) == -1) {
    return;
  }
  var cn = c.split(/\s+/);
  for (var i = 0; i < jsLength(cn); ++i) {
    if (cn[i] == className) {
      cn.splice(i--, 1);
    }
  }
  node.className = cn.join(' ');
}

/**
 * Checks if a node belongs to a style class.
 *
 * @param {Element} node  DOM element to test.
 * @param {String} className  Class name to check for.
 * @return {Boolean}  Node belongs to style class.
 */
function domTestClass(node, className) {
  var cn = domClassName(node).split(/\s+/);
  for (var i = 0; i < jsLength(cn); ++i) {
    if (cn[i] == className) {
      return true;
    }
  }
  return false;
}

/**
 * Inserts a new child before a given sibling.
 *
 * @param {Node} newChild  Node to insert.
 * @param {Node} oldChild  Sibling node.
 * @return {Node}  Reference to new child.
 */
function domInsertBefore(newChild, oldChild) {
  return oldChild.parentNode.insertBefore(newChild, oldChild);
}

/**
 * Appends a new child to the specified (parent) node.
 *
 * @param {Element} node  Parent element.
 * @param {Node} child  Child node to append.
 * @return {Node}  Newly appended node.
 */
function domAppendChild(node, child) {
  return node.appendChild(child);
}

/**
 * Remove a new child from the specified (parent) node.
 *
 * @param {Element} node  Parent element.
 * @param {Node} child  Child node to remove.
 * @return {Node}  Removed node.
 */
function domRemoveChild(node, child) {
  return node.removeChild(child);
}

/**
 * Replaces an old child node with a new child node.
 *
 * @param {Node} newChild  New child to append.
 * @param {Node} oldChild  Old child to remove.
 * @return {Node}  Replaced node.
 */
function domReplaceChild(newChild, oldChild) {
  return oldChild.parentNode.replaceChild(newChild, oldChild);
}

/**
 * Removes a node from the DOM.
 *
 * @param {Node} node  The node to remove.
 * @return {Node}  The removed node.
 */
function domRemoveNode(node) {
  return domRemoveChild(node.parentNode, node);
}

/**
 * Creates a new text node in the given document.
 *
 * @param {Document} doc  Target document.
 * @param {String} text  Text composing new text node.
 * @return {Text}  Newly constructed text node.
 */
function domCreateTextNode(doc, text) {
  return doc.createTextNode(text);
}

/**
 * Creates a new node in the given document
 *
 * @param {Document} doc  Target document.
 * @param {String} name  Name of new element (i.e. the tag name)..
 * @return {Element}  Newly constructed element.
 */
function domCreateElement(doc, name) {
  return doc.createElement(name);
}

/**
 * Creates a new attribute in the given document.
 *
 * @param {Document} doc  Target document.
 * @param {String} name  Name of new attribute.
 * @return {Attr}  Newly constructed attribute.
 */
function domCreateAttribute(doc, name) {
  return doc.createAttribute(name);
}

/**
 * Creates a new comment in the given document.
 *
 * @param {Document} doc  Target document.
 * @param {String} text  Comment text.
 * @return {Comment}  Newly constructed comment.
 */
function domCreateComment(doc, text) {
  return doc.createComment(text);
}

/**
 * Creates a document fragment.
 *
 * @param {Document} doc  Target document.
 * @return {DocumentFragment}  Resulting document fragment node.
 */
function domCreateDocumentFragment(doc) {
  return doc.createDocumentFragment();
}

/**
 * Redirect to document.getElementById
 *
 * @param {Document} doc  Target document.
 * @param {String} id  Id of requested node.
 * @return {Element|Null}  Resulting element.
 */
function domGetElementById(doc, id) {
  return doc.getElementById(id);
}

/**
 * Redirect to window.setInterval
 *
 * @param {Window} win  Target window.
 * @param {Function} fun  Callback function.
 * @param {Number} time  Time in milliseconds.
 * @return {Object}  Contract id.
 */
function windowSetInterval(win, fun, time) {
  return win.setInterval(fun, time);
}

/**
 * Redirect to window.clearInterval
 *
 * @param {Window} win  Target window.
 * @param {object} id  Contract id.
 * @return {any}  NOTE: Return type unknown?
 */
function windowClearInterval(win, id) {
  return win.clearInterval(id);
}

/**
 * Determines whether one node is recursively contained in another.
 * @param parent The parent node.
 * @param child The node to look for in parent.
 * @return parent recursively contains child
 */
function containsNode(parent, child) {
  while (parent != child && child.parentNode) {
    child = child.parentNode;
  }
  return parent == child;
};
/**
 * @fileoverview This file contains javascript utility functions that
 * do not depend on anything defined elsewhere.
 *
 */

/**
 * Returns the value of the length property of the given object. Used
 * to reduce compiled code size.
 *
 * @param {Array | String} a  The string or array to interrogate.
 * @return {Number}  The value of the length property.
 */
function jsLength(a) {
  return a.length;
}

var min = Math.min;
var max = Math.max;
var ceil = Math.ceil;
var floor = Math.floor;
var round = Math.round;
var abs = Math.abs;

/**
 * Copies all properties from second object to the first.  Modifies to.
 *
 * @param {Object} to  The target object.
 * @param {Object} from  The source object.
 */
function copyProperties(to, from) {
  foreachin(from, function(p) {
    to[p] = from[p];
  });
}

/**
 * Iterates over the array, calling the given function for each
 * element.
 *
 * @param {Array} array
 * @param {Function} fn
 */
function foreach(array, fn) {
  var I = jsLength(array);
  for (var i = 0; i < I; ++i) {
    fn(array[i], i);
  }
}

/**
 * Safely iterates over all properties of the given object, calling
 * the given function for each property. If opt_all isn't true, uses
 * hasOwnProperty() to assure the property is on the object, not on
 * its prototype.
 *
 * @param {Object} object
 * @param {Function} fn
 * @param {Boolean} opt_all  If true, also iterates over inherited properties.
 */
function foreachin(object, fn, opt_all) {
  for (var i in object) {
    if (opt_all || !object.hasOwnProperty || object.hasOwnProperty(i)) {
      fn(i, object[i]);
    }
  }
}

/**
 * Appends the second array to the first, copying its elements.
 * Optionally only a slice of the second array is copied.
 *
 * @param {Array} a1  Target array (modified).
 * @param {Array} a2  Source array.
 * @param {Number} opt_begin  Begin of slice of second array (optional).
 * @param {Number} opt_end  End (exclusive) of slice of second array (optional).
 */
function arrayAppend(a1, a2, opt_begin, opt_end) {
  var i0 = opt_begin || 0;
  var i1 = opt_end || jsLength(a2);
  for (var i = i0; i < i1; ++i) {
    a1.push(a2[i]);
  }
}

/**
 * Trim whitespace from begin and end of string.
 *
 * @see testStringTrim();
 *
 * @param {String} str  Input string.
 * @return {String}  Trimmed string.
 */
function stringTrim(str) {
  return stringTrimRight(stringTrimLeft(str));
}

/**
 * Trim whitespace from beginning of string.
 *
 * @see testStringTrimLeft();
 *
 * @param {String} str  Input string.
 * @return {String}  Trimmed string.
 */
function stringTrimLeft(str) {
  return str.replace(/^\s+/, "");
}

/**
 * Trim whitespace from end of string.
 *
 * @see testStringTrimRight();
 *
 * @param {String} str  Input string.
 * @return {String}  Trimmed string.
 */
function stringTrimRight(str) {
  return str.replace(/\s+$/, "");
}

/**
 * Jscompiler wrapper for parseInt() with base 10.
 *
 * @param {String} s String repersentation of a number.
 *
 * @return {Number} The integer contained in s, converted on base 10.
 */
function parseInt10(s) {
  return parseInt(s, 10);
}
/**
 * @fileoverview A simple formatter to project JavaScript data into
 * HTML templates. The template is edited in place. I.e. in order to
 * instantiate a template, clone it from the DOM first, and then
 * process the cloned template. This allows for updating of templates:
 * If the templates is processed again, changed values are merely
 * updated.
 *
 * NOTE: IE DOM doesn't have importNode().
 *
 * NOTE: The property name "length" must not be used in input
 * data, see comment in jstSelect_().
 */


/**
 * Names of jstemplate attributes. These attributes are attached to
 * normal HTML elements and bind expression context data to the HTML
 * fragment that is used as template.
 */
var ATT_select = 'jsselect';
var ATT_instance = 'jsinstance';
var ATT_display = 'jsdisplay';
var ATT_values = 'jsvalues';
var ATT_eval = 'jseval';
var ATT_transclude = 'transclude';
var ATT_content = 'jscontent';
var ATT_src = 'jssrc';
var ATT_href = 'jshref';
var ATT_visibility = 'jsvisibility';
var ATT_checked = 'jschecked';
var ATT_remove = 'jsremove';

/**
 * Names of special variables defined by the jstemplate evaluation
 * context. These can be used in js expression in jstemplate
 * attributes.
 */
var VAR_index = '$index';
var VAR_this = '$this';


/**
 * Context for processing a jstemplate. The context contains a context
 * object, whose properties can be referred to in jstemplate
 * expressions, and it holds the locally defined variables.
 *
 * @param {Object} opt_data The context object. Null if no context.
 *
 * @param {Object} opt_parent The parent context, from which local
 * variables are inherited. Normally the context object of the parent
 * context is the object whose property the parent object is. Null for the
 * context of the root object.
 *
 * @constructor
 */
function JsExprContext(opt_data, opt_parent) {
  var me = this;

  /**
   * The local context of the input data in which the jstemplate
   * expressions are evaluated. Notice that this is usually an Object,
   * but it can also be a scalar value (and then still the expression
   * $this can be used to refer to it). Notice this can be a scalar
   * value, including undefined.
   *
   * @type {Object}
   */
  me.data_ = opt_data;

  /**
   * The context for variable definitions in which the jstemplate
   * expressions are evaluated. Other than for the local context,
   * which replaces the parent context, variable definitions of the
   * parent are inherited. The special variable $this points to data_.
   *
   * @type {Object}
   */
  me.vars_ = {};
  if (opt_parent) {
    copyProperties(me.vars_, opt_parent.vars_);
  }
  this.vars_[VAR_this] = me.data_;
}


/**
 * Evaluates the given expression in the context of the current
 * context object and the current local variables.
 *
 * @param {String} expr A javascript expression.
 *
 * @param {Element} template DOM node of the template.
 *
 * @return The value of that expression.
 */
JsExprContext.prototype.jseval = function(expr, template, isValue) {
  with (this.vars_) {
    with (this.data_) {
      try {
        return (function() {
          return eval('[' + (isValue ? expr : expr.value) + '][0]');
        }).call(template);
      } catch (e) {
        return null;
      }
    }
  }
}


/**
 * Clones the current context for a new context object. The cloned
 * context has the data object as its context object and the current
 * context as its parent context. It also sets the $index variable to
 * the given value. This value usually is the position of the data
 * object in a list for which a template is instantiated multiply.
 *
 * @param {Object} data The new context object.
 *
 * @param {Number} index Position of the new context when multiply
 * instantiated. (See implementation of jstSelect().)
 *
 * @return {JsExprContext}
 */
JsExprContext.prototype.clone = function(data, index) {
  var ret = new JsExprContext(data, this);
  ret.setVariable(VAR_index, index);
  if (this.resolver_) {
    ret.setSubTemplateResolver(this.resolver_);
  }
  return ret;
}


/**
 * Binds a local variable to the given value. If set from jstemplate
 * jsvalue expressions, variable names must start with $, but in the
 * API they only have to be valid javascript identifier.
 *
 * @param {String} name
 *
 * @param {Object} value
 */
JsExprContext.prototype.setVariable = function(name, value) {
  this.vars_[name] = value;
}


/**
 * Sets the function used to resolve the values of the transclude
 * attribute into DOM nodes. By default, this is jstGetTemplate(). The
 * value set here is inherited by clones of this context.
 *
 * @param {Function} resolver The function used to resolve transclude
 * ids into a DOM node of a subtemplate. The DOM node returned by this
 * function will be inserted into the template instance being
 * processed. Thus, the resolver function must instantiate the
 * subtemplate as necessary.
 */
JsExprContext.prototype.setSubTemplateResolver = function(resolver) {
  this.resolver_ = resolver;
}


/**
 * Resolves a sub template from an id. Used to process the transclude
 * attribute. If a resolver function was set using
 * setSubTemplateResolver(), it will be used, otherwise
 * jstGetTemplate().
 *
 * @param {String} id The id of the sub template.
 *
 * @return {Node} The root DOM node of the sub template, for direct
 * insertion into the currently processed template instance.
 */
JsExprContext.prototype.getSubTemplate = function(id) {
  return (this.resolver_ || jstGetTemplate).call(this, id);
}


/**
 * HTML template processor. Data values are bound to HTML templates
 * using the attributes transclude, jsselect, jsdisplay, jscontent,
 * jsvalues. The template is modifed in place. The values of those
 * attributes are JavaScript expressions that are evaluated in the
 * context of the data object fragment.
 *
 * @param {JsExprContext} context Context created from the input data
 * object.
 *
 * @param {Element} template DOM node of the template. This will be
 * processed in place. After processing, it will still be a valid
 * template that, if processed again with the same data, will remain
 * unchanged.
 */
function jstProcess(context, template) {
  var processor = new JstProcessor();
  processor.run_([ processor, processor.jstProcess_, context, template ]);
}


/**
 * Internal class used by jstemplates to maintain context.
 * NOTE: This is necessary to process deep templates in Safari
 * which has a relatively shallow stack.
 * @class
 */
function JstProcessor() {
}


/**
 * Runs the state machine, beginning with function "start".
 *
 * @param {Array} start The first function to run, in the form
 * [object, method, args ...]
 */
JstProcessor.prototype.run_ = function(start) {
  var me = this;

  me.queue_ = [ start ];
  while (jsLength(me.queue_)) {
    var f = me.queue_.shift();
    f[1].apply(f[0], f.slice(2));
  }
}


/**
 * Appends a function to be called later.
 * Analogous to calling that function on a subsequent line, or a subsequent
 * iteration of a loop.
 *
 * @param {Array} f  A function in the form [object, method, args ...]
 */
JstProcessor.prototype.enqueue_ = function(f) {
  this.queue_.push(f);
}


/**
 * Implements internals of jstProcess.
 *
 * @param {JsExprContext} context
 *
 * @param {Element} template
 */
JstProcessor.prototype.jstProcess_ = function(context, template) {
    var me = this;


    var transclude = domGetAttribute(template, ATT_transclude);
    if (transclude) {
        var tr = context.getSubTemplate(transclude);
        if (tr) {
            domReplaceChild(tr, template);
            me.enqueue_([me, me.jstProcess_, context, tr]);
        } else {
            domRemoveNode(template);
        }
        return;
    }

    var select = domGetAttribute(template, ATT_select);
    if (select) {
        me.jstSelect_(context, template, select);
        return;
    }

    var display = domGetAttribute(template, ATT_display);
    if (display) {
        if (!context.jseval(display, template)) {
            displayNone(template);
            return;
        }

        displayDefault(template);
    }

    var visibility = domGetAttribute(template, ATT_visibility);
    if (visibility) {
        if (!context.jseval(visibility, template)) {
            visibilityHidden(template);
            return;
        }

        visibilityDefault(template);
    }

    var checked = domGetAttribute(template, ATT_checked);
    if (checked) {
        if (context.jseval(checked, template)) {
            domSetAttribute(template, 'checked', 'checked');
        }
    }

    var remove = domGetAttribute(template, ATT_remove);
    if (remove) {
        if (!context.jseval(remove, template)) {
            domRemoveNode(template);
            return;
        }
    }

    var values = domGetAttribute(template, ATT_values);
    if (values) {
        me.jstValues_(context, template, values);
    }

    var expressions = domGetAttribute(template, ATT_eval);
    if (expressions) {
        foreach(expressions.split(/\s*;\s*/), function(expression) {
            expression = stringTrim(expression);
            if (jsLength(expression)) {
                context.jseval(expression, template);
            }
        });
    }

    var src = domGetAttribute(template, ATT_src);
    if (src) me.jstSrc_(context, template, src);

    var href = domGetAttribute(template, ATT_href);
    if (href) me.jstHref_(context, template, href);

    var content = domGetAttribute(template, ATT_content);
    if (content) {
        me.jstContent_(context, template, content);

    } else {
        var childnodes = [];
        for (var i = 0; i < jsLength(template.childNodes); ++i) {
            if (template.childNodes[i].nodeType == DOM_ELEMENT_NODE) {
                me.enqueue_(
          [me, me.jstProcess_, context, template.childNodes[i]]);
            }
        }
    }
}


/**
 * Implements the jsselect attribute: evalutes the value of the
 * jsselect attribute in the current context, with the current
 * variable bindings (see JsExprContext.jseval()). If the value is an
 * array, the current template node is multiplied once for every
 * element in the array, with the array element being the context
 * object. If the array is empty, or the value is undefined, then the
 * current template node is dropped. If the value is not an array,
 * then it is just made the context object.
 *
 * @param {JsExprContext} context The current evaluation context.
 *
 * @param {Element} template The currently processed node of the template.
 *
 * @param {String} select The javascript expression to evaluate.
 *
 * @param {Function} process The function to continue processing with.
 */
JstProcessor.prototype.jstSelect_ = function(context, template, select) {
  var me = this;

  var value = context.jseval(select, template);
  domRemoveAttribute(template, ATT_select);

  var instance = domGetAttribute(template, ATT_instance);
  var instance_last = false;
  if (instance) {
    if (instance.charAt(0) == '*') {
      instance = parseInt10(instance.substr(1));
      instance_last = true;
    } else {
      instance = parseInt10(instance);
    }
  }

  var multiple = (value !== null &&
                  typeof value == 'object' &&
                  typeof value.length == 'number');
  var multiple_empty = (multiple && value.length == 0);

  if (multiple) {
    if (multiple_empty) {
      if (!instance) {
        domSetAttribute(template, ATT_select, select);
        domSetAttribute(template, ATT_instance, '*0');
        displayNone(template);
      } else {
        domRemoveNode(template);
      }

    } else {
      displayDefault(template);
      if (instance === null || instance === "" || instance === undefined ||
          (instance_last && instance < jsLength(value) - 1)) {
        var templatenodes = [];
        var instances_start = instance || 0;
        for (var i = instances_start + 1; i < jsLength(value); ++i) {
          var node = domCloneNode(template);
          templatenodes.push(node);
          domInsertBefore(node, template);
        }
        templatenodes.push(template);

        for (var i = 0; i < jsLength(templatenodes); ++i) {
          var ii = i + instances_start;
          var v = value[ii];
          var t = templatenodes[i];

          me.enqueue_([ me, me.jstProcess_, context.clone(v, ii), t ]);
          var instanceStr = (ii == jsLength(value) - 1 ? '*' : '') + ii;
          me.enqueue_(
              [ null, postProcessMultiple_, t, select, instanceStr ]);
        }

      } else if (instance < jsLength(value)) {
        var v = value[instance];

        me.enqueue_(
            [me, me.jstProcess_, context.clone(v, instance), template]);
        var instanceStr = (instance == jsLength(value) - 1 ? '*' : '')
                          + instance;
        me.enqueue_(
            [ null, postProcessMultiple_, template, select, instanceStr ]);
      } else {
        domRemoveNode(template);
      }
    }
  } else {
    if (value == null) {
      domSetAttribute(template, ATT_select, select);
      displayNone(template);
    } else {
      me.enqueue_(
          [ me, me.jstProcess_, context.clone(value, 0), template ]);
      me.enqueue_(
          [ null, postProcessSingle_, template, select ]);
    }
  }
}

/**
 * Sets ATT_select and ATT_instance following recursion to jstProcess.
 *
 * @param {Element} template  The template
 *
 * @param {String} select  The jsselect string
 *
 * @param {String} instanceStr  The new value for the jsinstance attribute
 */
function postProcessMultiple_(template, select, instanceStr) {
  domSetAttribute(template, ATT_select, select);
  domSetAttribute(template, ATT_instance, instanceStr);
}


/**
 * Sets ATT_select and makes the element visible following recursion to
 * jstProcess.
 *
 * @param {Element} template  The template
 *
 * @param {String} select  The jsselect string
 */
function postProcessSingle_(template, select) {
  domSetAttribute(template, ATT_select, select);
  displayDefault(template);
}


/**
 * Implements the jsvalues attribute: evaluates each of the values and
 * assigns them to variables in the current context (if the name
 * starts with '$', javascript properties of the current template node
 * (if the name starts with '.'), or DOM attributes of the current
 * template node (otherwise). Since DOM attribute values are always
 * strings, the value is coerced to string in the latter case,
 * otherwise it's the uncoerced javascript value.
 *
 * @param {JsExprContext} context Current evaluation context.
 *
 * @param {Element} template Currently processed template node.
 *
 * @param {String} valuesStr Value of the jsvalues attribute to be
 * processed.
 */
JstProcessor.prototype.jstValues_ = function(context, template, valuesStr) {
    var values;

    if (valuesStr.value) { values = valuesStr.value.split(/\s*;\s*/); }
    else { values = valuesStr.split(/\s*;\s*/); }

    for (var i = 0; i < jsLength(values); ++i) {
        var colon = values[i].indexOf(':');
        if (colon < 0) {
            continue;
        }
        var label = stringTrim(values[i].substr(0, colon));
        var value = context.jseval(values[i].substr(colon + 1), template, true);

        if (label.charAt(0) == '$') {
            context.setVariable(label, value);

        } else if (label.charAt(0) == '.') {
            template[label.substr(1)] = value;

        } else if (label) {
            if (typeof value == 'boolean') {
                if (value) {
                    domSetAttribute(template, label, label);
                } else {
                    domRemoveAttribute(template, label);
                }
            } else {
                domSetAttribute(template, label, '' + value);
            }
        }
    }
}


/**
 * Implements the jscontent attribute. Evalutes the expression in
 * jscontent in the current context and with the current variables,
 * and assigns its string value to the content of the current template
 * node.
 *
 * @param {JsExprContext} context Current evaluation context.
 *
 * @param {Element} template Currently processed template node.
 *
 * @param {String} content Value of the jscontent attribute to be
 * processed.
 */
JstProcessor.prototype.jstContent_ = function(context, template, content) {
  var value = '' + context.jseval(content, template);
  if (template.innerHTML == value) {
    return;
  }
  while (template.firstChild) {
    domRemoveNode(template.firstChild);
  }
  var t = domCreateTextNode(ownerDocument(template), value);
  domAppendChild(template, t);
}

JstProcessor.prototype.jstSrc_ = function(context, template, src) {
  var value = '' + context.jseval(src, template);
  domSetAttribute(template, 'src', value);
}

JstProcessor.prototype.jstHref_ = function(context, template, href) {
    var hrefValue = href.value.toString();
    var match = /{[^}]+?}/.exec(hrefValue);
    while (match) {
        var value = match.toString().replace(/{|}/g, '');
        hrefValue = hrefValue.replace(match.toString(), context.jseval(value, template, true));
        
        match = /{[^}]+?}/.exec(hrefValue)
    }
    domSetAttribute(template, 'href', hrefValue);
}

/**
 * Helps to implement the transclude attribute, and is the initial
 * call to get hold of a template from its ID.
 *
 * @param {String} name The ID of the HTML element used as template.
 *
 * @returns {Element} The DOM node of the template. (Only element
 * nodes can be found by ID, hence it's a Element.)
 */
function jstGetTemplate(name) {
  var section = domGetElementById(document, name);
  if (section) {
    var ret = domCloneNode(section);
    domRemoveAttribute(ret, 'id');
    return ret;
  } else {
    return null;
  }
}

window['jstGetTemplate'] = jstGetTemplate;
window['jstProcess'] = jstProcess;
window['JsExprContext'] = JsExprContext;

// Copyright 2006 Google
/**
* @pageoverview Some logic for the jstemplates test pages.
*
* @author Steffen Meschkat <mesch@google.com>
*/

/**
* Returns the element with the given ID
*
* @param {String} id  The id of the element to return.
* @param {Document} opt_context  The context in which to search (optional).
* @return {Element}  The corresponding element.
*/
function elem(id, opt_context) {
    if (opt_context && ownerDocument(opt_context)) {
        return ownerDocument(opt_context).getElementById(id);
    } else {
        return document.getElementById(id);
    }
};

/**
* Initializer for interactive test: copies the value from the actual
* template HTML into a text area to make the HTML source visible.
*/
function jsinit() {
    elem('template').value = elem('tc').innerHTML;
};


/**
* Interactive test.
*
* @param {Boolean} reprocess If true, reprocesses the output of the
* previous invocation.
*/
function JsProcessTemplate(template, data) {
    var input = jsEval(data);
    var t = document.createElement('div');
    t.innerHTML = template;
    jstProcess(new JsExprContext(input), t);
    
    return t;
};
//Looks like a dictionary
var Template = function() {
    this.Key = null;
    this.Value = null;
};

var Templates = {

    /// <Summary>
    /// array of Template
    /// </Summary>
    LoadedTemplates: [],

    /// <Summary>
    /// Add a new template into LoadedTemplate list
    /// </Summary>
    Add: function(key, template) {
        var t = new Template();
        t.Key = key;
        t.Value = template;
        Templates.LoadedTemplates.push(t);
    },

    /// <Summary>
    /// Get the Template by templateName key
    /// </Summary>
    Get: function(key, isRetry) {
        for (var i = 0; i < Templates.LoadedTemplates.length; i++) {
            var item = Templates.LoadedTemplates[i].Key;
            if (item == key) return Templates.LoadedTemplates[i].Value;
        }

        //sencond try to get (after load) is the last one
        if (isRetry) return null;

        //is not there: sync request for the template
        Templates.Load(key);

        //try it once again
        return Templates.Get(key, true);

        //cancel navigation action (doesn't mean error)
        return null;
    },

    Load: function(key) {

        var parameters = [];
        parameters.push("snippetTemplate");
        parameters.push(key);

        AjaxHelper.Call(
		    "Templates",
		    "GetByKey",
		    AjaxHelper.JSONSerialize(parameters),
		    false,
		    function(data) {
		        Templates.Add(key, data.d);
		    });
    }
};
var ProductSlideController = {
    TemplateName: 'ProductSlide',
    ContainerId: 'ProductSlideContainer',
    LeftArrowId: 'productListLeftArrow',
    RightArrowId: 'productListRightArrow',
    
    CollNumber : 2,
    Total: 0,
    ActiveElement: null,
    ProductTypeId: 0,
    
    FirstTime : true,

    OnLoadController: function() {
        ProductSlideController.ProductTypeId = UrlHelper.GetProductTypeIdAndSetMenu(location.pathname);
        ProductSlideController.LoadProducts();
    },

    Initialize: function() {   
        jQuery('#slider').jcarousel({
            easing: 'BounceEaseOut',            
            scroll  : 4,
            animation: 1700 
        });
    },

    LoadProducts: function(carousel, state) {
        if (carousel) {
            ProductSlideController.Carousel = carousel;
                
            if (ProductSlideController.Carousel.last >= ProductSlideController.Total) {
                return;
            }
        }
    
        var products = new Products();
        
        products.GetAllProducts(
            ProductSlideController.ProductTypeId,
            ProductSlideController.CollNumber, 
            ProductSlideController.OnLoadProducts);
    },

    OnLoadProducts: function(result) {
        if(ProductSlideController.FirstTime) {
            if(result.Data[0]){
                OtherImagesSlideController.LoadOtherImages(result.Data[0].Items[0].ProductId);
                OtherImagesSlideController.onClick(result.Data[0].Items[0].ProductSkuId);
                ProductDetailsController.LoadDedails(result.Data[0].Items[0].ProductSkuId);
                BuyProductController.LoadProduct(result.Data[0].Items[0].ProductSkuId);
                ProductSlideController.FirstTime = false;
                document.getElementById("BuyProductContainer").style.display="block";
            }
            else {
                // If there is no products at this category
                document.getElementById('BuyProductContainer').style.display = 'none';
                document.getElementById('ProductsContainer').innerHTML = "<center>Esta categoria não contém produtos</center>";
            }
        }
        
        var template = Templates.Get(ProductSlideController.TemplateName);
        $('#' + ProductSlideController.ContainerId).html(JsProcessTemplate(template, result).innerHTML);

        document.getElementById("ProductsContainer").style.display="block";

        ProductSlideController.Total = result.Total;
        ProductSlideController.Initialize();
        
        if (result.Data.length > 0)
            ProductSlideController.onClick(result.Data[0].ProductId, result.Data[0].ProductSkuId);
            
        
    },

    onClick: function(productId, productSkuId) {
        BuyProductController.LoadProduct(productSkuId);
        ProductDetailsController.LoadDedails(productSkuId);
        OtherImagesSlideController.LoadOtherImages(productId);

        ProductSlideController.FormatElement($('#product_' + productId));
    },

    FormatElement: function(element) {
        if (ProductSlideController.ActiveElement) {
            ProductSlideController.ActiveElement.css('border-color', '#E3E3E3');
        }

        ProductSlideController.ActiveElement = element;
        element.css('border-color', '#FF8C00');
    }
};

$(document).ready(function() {
    ProductSlideController.OnLoadController();
});

jQuery.easing['BounceEaseOut'] = function(p, t, b, c, d) {
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
};
 
var ProductDetailsController = {
    TemplateName: 'ProductDetails',
    ContainerId: 'ProductDetailsContainer',

    LoadDedails: function(productSkuId) {
        var productSku = new ProductsSKU();
        productSku.GetByProductSkuId(productSkuId, ProductDetailsController.OnLoadDedailsSuccess);
    },

    OnLoadDedailsSuccess: function(result) {
        var template = Templates.Get(ProductDetailsController.TemplateName);
        $('#' + ProductDetailsController.ContainerId).html(JsProcessTemplate(template, result).innerHTML);
    }
};
var OtherImagesSlideController = {
    TemplateName: 'OtherImagesSlide',
    ContainerId: 'OtherImagesSlideContainer',
    LeftArrowId: 'otherImagesLeftArrow',
    RightArrowId: 'otherImagesRightArrow',

    PageIndex: 0,
    PageSize: 300,
    Total: 0,
    ProductId: 0,
    ActiveElement: null,

    Initialize: function() {
        var previousArrow = $('#' + OtherImagesSlideController.LeftArrowId);
        var nextArrow = $('#' + OtherImagesSlideController.RightArrowId);

        previousArrow.click(OtherImagesSlideController.Previous);
        nextArrow.click(OtherImagesSlideController.Next);

        previousArrow.css('cursor', 'pointer');
        nextArrow.css('cursor', 'pointer');
        
        jQuery('#mycarousel').jcarousel({           
            easing: 'BounceEaseOut',
            animation: 1500,
            scroll  : 4
        });
    },

    LoadOtherImages: function(productId) {
        if (productId)
            OtherImagesSlideController.ProductId = productId;

        var productSKU = new ProductsSKU();
        productSKU.GetByProductId(OtherImagesSlideController.ProductId, OtherImagesSlideController.PageIndex, OtherImagesSlideController.PageSize, OtherImagesSlideController.onLoadOtherImagesSuccess);
    },

    onLoadOtherImagesSuccess: function(result) {
        var template = Templates.Get(OtherImagesSlideController.TemplateName, false);
        $('#' + OtherImagesSlideController.ContainerId).html(JsProcessTemplate(template, result));

        OtherImagesSlideController.Total = result.Total;
        OtherImagesSlideController.Initialize();
        
        jQuery('#mycarousel').jcarousel({
            scroll  : 4
        });
    },

    Previous: function() {
        if (OtherImagesSlideController.PageIndex == 0)
            return;

        OtherImagesSlideController.PageIndex--;
        OtherImagesSlideController.LoadOtherImages();
    },

    Next: function() {
        var numberPages = Math.ceil(OtherImagesSlideController.Total / OtherImagesSlideController.PageSize);
        if (OtherImagesSlideController.PageIndex + 1 >= numberPages)
            return;

        OtherImagesSlideController.PageIndex++;
        OtherImagesSlideController.LoadOtherImages();
    },

    onClick: function(productSkuId) {
        BuyProductController.LoadProduct(productSkuId);
        OtherImagesSlideController.FormatElement($('#otherProduct_' + productSkuId));
        ProductDetailsController.LoadDedails(productSkuId);
    },

    FormatElement: function(element) {
        if (OtherImagesSlideController.ActiveElement) {
            OtherImagesSlideController.ActiveElement.css('border-color', '#E3E3E3');
        }

        OtherImagesSlideController.ActiveElement = element;
        element.css('border-color', '#FF8C00');
    }
};

$(document).ready(function() {
    OtherImagesSlideController.Initialize();
    
});

/**********************
* JCarouselHelper
*********************/
function mycarousel_itemLoadCallback(carousel, state)
{
    // Since we get all URLs in one file, we simply add all items
    // at once and set the size accordingly.
    if (state != 'init')
        return;
 
    jQuery.get('dynamic_ajax.txt', function(data) {
        mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
    });
};
 
function mycarousel_itemAddCallback(carousel, first, last, data)
{
    // Simply add all items at once and set the size accordingly.
    var items = data.split('|');
 
    for (i = 0; i < items.length; i++) {
        carousel.add(i+1, mycarousel_getItemHTML(items[i]));
    }
 
    carousel.size(items.length);
};
 
/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(url)
{
    return '<img src="' + url + '" width="75" height="75" alt="" />';
};

jQuery.easing['BounceEaseOut'] = function(p, t, b, c, d) {
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
};
 


var BuyProductController = {
    TemplateName: 'BuyProduct',
    ContainerId: 'BuyProductContainer',
    BuyLinkId: 'BuyLink',
    productSkuId: 0,

    Initialize: function() {
        var buyLink = $('#' + BuyProductController.BuyLinkId);
        if (HearderMenu.activeId != "corporate") {
            $("#BuyLink").css("display", "block");
            $("#BuyLink").click(function() { BuyProductController.Buy(); });
            BuyProductController.ActiveProductSkuId = BuyProductController.productSkuId;
        }
        else {
            $("#QuoteLink").css("display", "block");
            $("#ContentPrice").css("display", "none");
            $("#QuoteLink").click(function() { QuotePopupController.getProductInfo(BuyProductController.productSkuId); });
        }
    },

    LoadProduct: function(productSkuId) {
        if (productSkuId > 0) {
            BuyProductController.productSkuId = productSkuId;
            var productSku = new ProductsSKU();
            productSku.GetByProductSkuId(productSkuId, BuyProductController.OnLoadProductSuccess);
        }
    },

    OnLoadProductSuccess: function(result) {
        var template = Templates.Get(BuyProductController.TemplateName);
        $('#' + BuyProductController.ContainerId).html(JsProcessTemplate(template, result).innerHTML);

        BuyProductController.Initialize();
    },

    Buy: function() {
        if (HearderMenu.userId) {
            var shoppingCarts = new ShoppingCarts();
            shoppingCarts.InsertItem('ProductSku', BuyProductController.ActiveProductSkuId, HearderMenu.userId, BuyProductController.OnBuySuccess);
        }
        else alert("Você deve estar logado para efetuar a compra");
    },

    OnBuySuccess: function(result) {
        UrlHelper.GotoShoppingCartPage();
    }
};

$(document).ready(function() {
    BuyProductController.Initialize();
});

var Addresses = function() {
	this.ServiceName			= "Addresses";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(addressId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("addressId");
		parameters.push(addressId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var BankAccountReferences = function() {
	this.ServiceName			= "BankAccountReferences";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(id, onSuccess)
	{
		var parameters = new Array();
		parameters.push("id");
		parameters.push(id);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Brands = function() {
	this.ServiceName			= "Brands";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(brandId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("brandId");
		parameters.push(brandId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var CommercialReferences = function() {
    this.ServiceName = "CommercialReferences";
    this.GetByIdMethodName = "GetById";

    this.GetById = function(id, onSuccess) {
        var parameters = new Array();
        parameters.push("id");
        parameters.push(id);

        AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
			    onSuccess(data.d)
			});
    }
};


var Contacts = function() {
	this.ServiceName			= "Contacts";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(id, onSuccess)
	{
		var parameters = new Array();
		parameters.push("id");
		parameters.push(id);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var CustomProducts = function() {
	this.ServiceName			= "CustomProducts";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(customProductId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("customProductId");
		parameters.push(customProductId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var CustomProductsItems = function() {
	this.ServiceName			= "CustomProductsItems";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(productSkuId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("productSkuId");
		parameters.push(productSkuId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Images = function() {
	this.ServiceName			= "Images";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(imageId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("imageId");
		parameters.push(imageId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var OrderItems = function() {
	this.ServiceName			= "OrderItems";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(orderId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("orderId");
		parameters.push(orderId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Orders = function() {
	this.ServiceName			= "Orders";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(orderId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("orderId");
		parameters.push(orderId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var PaymentProviders = function() {
	this.ServiceName			= "PaymentProviders";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(providerId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("providerId");
		parameters.push(providerId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Products = function() {
	this.ServiceName			= "Products";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(productId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("productId");
		parameters.push(productId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var ProductsSKU = function() {
	this.ServiceName			= "ProductsSKU";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(productSkuId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("productSkuId");
		parameters.push(productSkuId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var ProductTypes = function() {
	this.ServiceName			= "ProductTypes";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(id, onSuccess)
	{
		var parameters = new Array();
		parameters.push("id");
		parameters.push(id);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var QuoteItems = function() {
	this.ServiceName			= "QuoteItems";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(quoteId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("quoteId");
		parameters.push(quoteId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Quotes = function() {
	this.ServiceName			= "Quotes";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(quoteId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("quoteId");
		parameters.push(quoteId);		
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var ShoppingCarts = function() {
	this.ServiceName			= "ShoppingCarts";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(userId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("userId");
		parameters.push(userId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Sizes = function() {
	this.ServiceName			= "Sizes";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(sizeId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("sizeId");
		parameters.push(sizeId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var States = function() {
	this.ServiceName			= "States";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(stateId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("stateId");
		parameters.push(stateId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Status = function() {
	this.ServiceName			= "Status";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(statusId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("statusId");
		parameters.push(statusId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};


var Users = function() {
	this.ServiceName			= "Users";
	this.GetByIdMethodName	= "GetById";

	this.GetById = function(userId, onSuccess)
	{
		var parameters = new Array();
		parameters.push("userId");
		parameters.push(userId);
		
		AjaxHelper.Call(
			this.ServiceName,
			this.GetByIdMethodName,
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
};






Contacts.prototype.sendContact = function(name, email, phone, typeUser, department, comments){
    var parameters = new Array();
		parameters.push("name");
		parameters.push(name);
		parameters.push("email");
		parameters.push(email);
		parameters.push("phone");
		parameters.push(phone);
		parameters.push("typeUser");
		parameters.push(typeUser);
		parameters.push("department");
		parameters.push(department);
		parameters.push("comments");
		parameters.push(comments);
		
		AjaxHelper.Call(
			"Contacts",
			"SendEmailContact",
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                ContactController.clearForm(data.d);
        });
    
}
CustomProducts.prototype.Insert = function(userId, productItems, imageId, onSuccess) {
	var param = new Array();
	param.push("userId");
	param.push(userId);
	param.push("productItems");
	param.push(productItems);
	param.push("imageId");
	param.push(imageId);
	AjaxHelper.Call(
		this.ServiceName,
		"Create",
		AjaxHelper.JSONSerialize(param),
		true,
		function(data) { onSuccess(data.d) });
}


Images.prototype.GetNews = function(pageIndex, pageSize) {
    var param = new Array();
    param.push("pageIndex");
    param.push(pageIndex);
    param.push("pageSize");
    param.push(pageSize);

    AjaxHelper.Call(
		"Images",
		"GetNewsImage",
		AjaxHelper.JSONSerialize(param),
		true,
		function(data) {
		    NewsPopup.successPopup(data.d[0].Source, data.d[0].Max);
		});
}
var Misc = function() {
    this.serviceName		= "Misc";
	this.getByIdMethodName	= "GetCompanyImageTemplate";

	this.getCompanyImageTemplate = function(onSuccess)
	{
		AjaxHelper.Call(
			this.serviceName,
			this.getByIdMethodName,
			"{}",
			true,
			function(data) {
                onSuccess(data.d)
        });
	}
}

Orders.prototype.InsertOrder = function(freight, paymentProviderId, onSuccess) {
    var insertMethodName = 'InsertOrder';

    var parameters = new Array();
    parameters.push('freight');
    parameters.push(freight);
    parameters.push('paymentProviderId');
    parameters.push(paymentProviderId);

    AjaxHelper.Call(
        this.ServiceName,
        insertMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
}

Orders.prototype.GetTotalPaged = function(pageIndex, pageSize, status, onSuccess) {
    var parameters = new Array();
    parameters.push('pageIndex');
    parameters.push(pageIndex);
    parameters.push('pageSize');
    parameters.push(pageSize);
    parameters.push('status');
    parameters.push(status);

    AjaxHelper.Call(
        "Orders",
        "GetTotalRecordsPaged",
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
}

Orders.prototype.GetTotalResultsPaged = function(pageIndex, pageSize, status, onSuccess) {
    var parameters = new Array();
    parameters.push('pageIndex');
    parameters.push(pageIndex);
    parameters.push('pageSize');
    parameters.push(pageSize);
    parameters.push('status');
    parameters.push(status);

    AjaxHelper.Call(
        "Orders",
        "GetResultsPaged",
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
}

Orders.prototype.UpdateOrderStatusById = function(orderId, statusId, freight, onSuccess) {
    var parameters = new Array();
    parameters.push('orderId');
    parameters.push(orderId);
    parameters.push('statusId');
    parameters.push(statusId);
    parameters.push('freight');
    parameters.push(freight);

    AjaxHelper.Call(
        "Orders",
        "UpdateOrderStatusAndFreightById",
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
}

Products.prototype.GetPaged = function(pageIndex, pageSize, productTypeId, onSuccess) {
    var getByProductIdMethodName = "GetProducts";

    var parameters = new Array();
    parameters.push("pageSize");
    parameters.push(pageSize);
    parameters.push("pageIndex");
    parameters.push(pageIndex);
    parameters.push("productTypeId");
    parameters.push(productTypeId);

    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

Products.prototype.GetAllProducts = function(productTypeId, collNumber, onSuccess) {
    var getByProductIdMethodName = "GetAllProducts";

    var parameters = new Array();
    parameters.push("productTypeId");
    parameters.push(productTypeId);
    parameters.push("columnNumber");
    parameters.push(collNumber);

    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};


Products.prototype.GetProductById = function(id) {
    var getByProductIdMethodName = "GetProductById";

    var parameters = new Array();
    parameters.push("id");
    parameters.push(id);

    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) {
            QuotePopupController.showPopup(data.d[0]);
        }
    );
};

Products.prototype.GetCustomProducts = function(pageIndex, pageSize, productId, skuPageIndex, displayPageIndex, onSuccess) {
	var param = new Array();
	param.push("pageIndex");
	param.push(pageIndex);
	param.push("pageSize");
	param.push(pageSize);
	param.push("productId");
	param.push(productId);
	param.push("skuPageIndex");
	param.push(skuPageIndex);
	param.push("displayPageIndex");
	param.push(displayPageIndex);
	AjaxHelper.Call(
		this.ServiceName,
		"GetCustomProducts",
		AjaxHelper.JSONSerialize(param),
		true,
		function(data) { onSuccess(data.d) });
};

Products.prototype.CreateMountYoursImage = function(structureTop, structureLeft, structureImage, mainTop, mainLeft, mainImage, onSuccess) {
	var param = new Array();
	param.push("structureTop");
	param.push(structureTop);
	param.push("structureLeft");
	param.push(structureLeft);
	param.push("structureImage");
	param.push(structureImage);
	param.push("imageTop");
	param.push(mainTop);
	param.push("imageLeft");
	param.push(mainLeft);
	param.push("image");
	param.push(mainImage);
	AjaxHelper.Call(
		this.ServiceName,
		"CreateMountYoursImage",
		AjaxHelper.JSONSerialize(param),
		true,
		function(data) { onSuccess(data.d) });
}






ProductsSKU.prototype.GetByProductId = function(productId, pageIndex, pageSize, onSuccess) {
    var getByProductIdMethodName = "GetByProductId";

    var parameters = new Array();
    parameters.push("productId");
    parameters.push(productId);
    parameters.push("pageIndex");
    parameters.push(pageIndex);
    parameters.push("pageSize");
    parameters.push(pageSize);
    
    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};


ProductsSKU.prototype.GetByProductSkuId = function(productSkuId, onSuccess) {
    if (!productSkuId) {
        return;    
    }

    var getByProductIdMethodName = "GetByProductSkuId";

    var parameters = new Array();
    parameters.push("productSkuId");
    parameters.push(productSkuId);

    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

ProductsSKU.prototype.GetTotal = function(productId, onSuccess) {
    var getTotalMethodName = "GetByProductId";

    var parameters = new Array();
    parameters.push("productId");
    parameters.push(productId);

    AjaxHelper.Call(
        this.ServiceName,
        getTotalMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};





Quotes.prototype.sendQuoteProduct = function(id, name, email, phone, description) {
    var getByProductIdMethodName = "SendQuoteProduct";

    var parameters = new Array();
    parameters.push("id");
    parameters.push(id);
    parameters.push("name");
    parameters.push(name);
    parameters.push("email");
    parameters.push(email);
    parameters.push("phone");
    parameters.push(phone);
    parameters.push("description");
    parameters.push(description);

    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) {
            QuotePopupController.showConfimationPopup(data.d);
        }
    );
};

Quotes.prototype.sendSpecialProduct = function(name, email, phone, description) {
    var getByProductIdMethodName = "sendSpecialProduct";

    var parameters = new Array();
    parameters.push("name");
    parameters.push(name);
    parameters.push("email");
    parameters.push(email);
    parameters.push("phone");
    parameters.push(phone);
    parameters.push("description");
    parameters.push(description);

    AjaxHelper.Call(
        this.ServiceName,
        getByProductIdMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) {
            SpecialPopupController.closeSpecialPopup();
        }
    );
};
ShoppingCarts.prototype.GetShoppingCarts = function(userId, onSuccess) {
    var getShoppingCartsMethodName = 'GetShoppingCarts';

    var parameters = new Array();
    parameters.push('userId');
    parameters.push(userId);
    
    AjaxHelper.Call(
        this.ServiceName,
        getShoppingCartsMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

ShoppingCarts.prototype.InsertItem = function(type, id, userId, onSuccess) {
    var removeItemMethodName = 'InsertItem';

    var parameters = new Array();
    parameters.push('type');
    parameters.push(type);
    parameters.push('id');
    parameters.push(id);
    parameters.push('userId');
    parameters.push(userId);

    AjaxHelper.Call(
        this.ServiceName,
        removeItemMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

ShoppingCarts.prototype.RemoveItem = function(type, id, userId, onSuccess) {
    var removeItemMethodName = 'RemoveItem';

    var parameters = new Array();
    parameters.push('type');
    parameters.push(type);
    parameters.push('id');
    parameters.push(id);
    parameters.push('userId');
    parameters.push(userId);

    AjaxHelper.Call(
        this.ServiceName,
        removeItemMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

ShoppingCarts.prototype.RemoveAllItems = function(userId, onSuccess) {
    var removeItemMethodName = 'CleanUserShoppingCart';
    
    var parameters = new Array();
    parameters.push('userId');
    parameters.push(userId);
    
    AjaxHelper.Call(
        this.ServiceName,
        removeItemMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

ShoppingCarts.prototype.CalculateFreight = function(weight, cep, onSuccess) {
    var calculateFreightMethodName = 'CalculateFreight';

    var parameters = new Array();
    parameters.push('weight');
    parameters.push(weight);
    parameters.push('cep');
    parameters.push(cep);

    AjaxHelper.Call(
        this.ServiceName,
        calculateFreightMethodName,
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

ShoppingCarts.prototype.GetShoppingCartsQuantity = function(onSuccess) {
    var getShoppingCartsMethodName = 'GetShoppingCartsQuantity';
    
    AjaxHelper.Call(
        this.ServiceName,
        getShoppingCartsMethodName,
        "{}",
        true,
        function(data) { onSuccess(data.d) }
    );
};

ShoppingCarts.prototype.EditItem = function(type, id, quantity, onSuccess) {    
    var parameters = new Array();
    parameters.push('type');
    parameters.push(type);
    parameters.push('id');
    parameters.push(id);
    parameters.push('quantity');
    parameters.push(quantity);
    
    AjaxHelper.Call(
        "ShoppingCarts",
        "EditItem",
        AjaxHelper.JSONSerialize(parameters),
        true,
        function(data) { onSuccess(data.d) }
    );
};

States.prototype.get = function(onSuccess) {
    var getMethodName = "Get";

    AjaxHelper.Call(
        this.ServiceName,
        getMethodName,
        "{ }",
        true,
        function(data) {
            onSuccess(data.d)
        });
};

Users.prototype.Authenticate = function(userName, password, authenticate, location, onSuccess) {
    var param = new Array();
    param.push("userName");
    param.push(userName);
    param.push("password");
    param.push(password);
    param.push("rememberMe");
    param.push(authenticate);
    param.push("location");
    param.push(location);

    AjaxHelper.Call(
		"Users",
		"Authenticate",
		AjaxHelper.JSONSerialize(param),
		true,
		function(data) {
		    HearderMenu.successCallBack(data.d)
		});
}

Users.prototype.IsRetail = function() {
    AjaxHelper.Call(
		"Users",
		"GetTypeUser",
		"{}",
		true,
		function(data) {
		    HearderMenu.isEnabled(data.d)
		});
}

Users.prototype.logOffUser = function(location) {
    AjaxHelper.Call(
		this.ServiceName,
		"LogOffUser",
		"{}",
		true,
		function(data) {
            window.location = JavaScriptConstants.ApplicationUrl + "moda/relogio-de-pulso/tradicional";
		});
}

Users.prototype.forgotPassword = function(email) {
    var param = new Array();
    param.push("email");
    param.push(email);

    AjaxHelper.Call(
		this.ServiceName,
		"ForgotPassword",
		AjaxHelper.JSONSerialize(param),
		true,
		function() {
		    ForgotPasswordController.changePopup();
		});
}

Users.prototype.insertUser = function(name, birthDate, foundationDate, phoneNumber, mobilePhone, fax, contact, cpf, cnpj, rg, ie, email, 
                                      userType, isApprovate, isRetail, isEnable, password, cep, city, state, address, knowCloseArea,
                                      companyName, fantasyName, country, supplement, addressNumber, news) 
{
    var parameters = new Array();
    parameters.push("name");
    parameters.push(name);
    parameters.push("birthDate");
    parameters.push(birthDate);
    parameters.push("foundationDate");
    parameters.push(foundationDate);
    parameters.push("phoneNumber");
    parameters.push(phoneNumber);
    parameters.push("mobilePhone");
    parameters.push(mobilePhone);
    parameters.push("fax");
    parameters.push(fax);
    parameters.push("contact");
    parameters.push(contact);
    parameters.push("cpf");
    parameters.push(cpf);
    parameters.push("cnpj");
    parameters.push(cnpj);
    parameters.push("rg");
    parameters.push(rg);
    parameters.push("ie");
    parameters.push(ie);
    parameters.push("email");
    parameters.push(email);
    parameters.push("userType");
    parameters.push(userType);
    parameters.push("isApproved");
    parameters.push(isApprovate);
    parameters.push("isRetail");
    parameters.push(isRetail);
    parameters.push("isEnabled");
    parameters.push(isEnable);
    parameters.push("password");
    parameters.push(password);
    parameters.push("cep");
    parameters.push(cep);
    parameters.push("city");
    parameters.push(city);
    parameters.push("state");
    parameters.push(state);
    parameters.push("address");
    parameters.push(address);
    parameters.push("knowCloseArea");
    parameters.push(knowCloseArea);
    parameters.push("companyName");
    parameters.push(companyName);
    parameters.push("fantasyName");
    parameters.push(fantasyName);
    parameters.push("country");
    parameters.push(country);
    parameters.push("supplement");
    parameters.push(supplement);
    parameters.push("addressNumber");
    parameters.push(addressNumber);
    parameters.push("news");
    parameters.push(news);

    AjaxHelper.Call(
			"Users",
			"CreateUser",
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
			    if (data.d != "sucess") {
			        alert(data.d);
			    }
			    else {
			        alert("Cadastro efetuado com sucesso"); 
			        $('#userName').val(RegisterRetailController.email);
                    $('#password').val(RegisterRetailController.password);
		            
		            HearderMenu.authenticate();
			    }
			});

}

Users.prototype.EmailValidate = function(email)
{
    var parameters = new Array();
        parameters.push("email");
		parameters.push(email);
		
		AjaxHelper.Call(
			"Users",
			"EmailValidate",
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
			    if (data.d != "sucess") {
			        alert(data.d);
			    }
			    else {
                    $("#UserDetails").attr("style", "display:none");
                    $("#PartnerDetails").attr("style", "display:block");
                }
        });
}

Users.prototype.insertUserWholesale = function(name, birthDate, foundationDate, phoneNumber, mobilePhone, fax, contact, cpf, cnpj, rg, ie, email, 
userType, isApproved, isRetail, isEnabled, password, cep, city, state, address, knowCloseArea, companyName, fantasyName, address2,  
district, cep2, city2, state2, namePartner1, cpfPartner1, rgPartner1, namePartner2, cpfPartner2, rgPartner2, namePartner3, cpfPartner3, rgPartner3,
companyReferenceName1, phone1, contact1, companyReferenceName2, phone2, contact2, companyReferenceName3, phone3, contact3,bank1, agency1, cc1, phoneBank1, 
manager1,bank2, agency2, cc2, phoneBank2, manager2, country, supplement, addressNumber, news){
    var parameters = new Array();
        parameters.push("name");
		parameters.push(name);
		parameters.push("birthDate");
		parameters.push(birthDate);
		parameters.push("foundationDate");
		parameters.push(foundationDate);
		parameters.push("phoneNumber");
		parameters.push(phoneNumber);
		parameters.push("mobilePhone");
		parameters.push(mobilePhone);
		parameters.push("fax");
		parameters.push(fax);
		parameters.push("contact");
		parameters.push(contact);
		parameters.push("cpf");
		parameters.push(cpf);
		parameters.push("cnpj");
		parameters.push(cnpj);
		parameters.push("rg");
		parameters.push(rg);
		parameters.push("ie");
		parameters.push(ie);
		parameters.push("email");
		parameters.push(email);
		parameters.push("userType");
		parameters.push(userType);
		parameters.push("isApproved");
		parameters.push(isApproved);
		parameters.push("isRetail");
		parameters.push(isRetail);
		parameters.push("isEnabled");
		parameters.push(isEnabled);
		parameters.push("password");
		parameters.push(password);
		parameters.push("cep");
		parameters.push(cep);
		parameters.push("city");
		parameters.push(city);
		parameters.push("state");
		parameters.push(state);
		parameters.push("address");
		parameters.push(address);
		parameters.push("knowCloseArea");
		parameters.push(knowCloseArea);
		parameters.push("companyName");
		parameters.push(companyName);
		parameters.push("fantasyName");
		parameters.push(fantasyName);
		parameters.push("address2");
		parameters.push(address2);
		parameters.push("district");
		parameters.push(district);
        parameters.push("cep2");
		parameters.push(cep2);
        parameters.push("city2");
		parameters.push(city2);
        parameters.push("state2");
		parameters.push(state2);
		parameters.push("namePartner1");
		parameters.push(namePartner1);
        parameters.push("cpfPartner1");
		parameters.push(cpfPartner1);
        parameters.push("rgPartner1");
		parameters.push(rgPartner1);
		parameters.push("namePartner2");
		parameters.push(namePartner2);
		parameters.push("cpfPartner2");
		parameters.push(cpfPartner2);
		parameters.push("rgPartner2");
		parameters.push(rgPartner2);
		parameters.push("namePartner3");
		parameters.push(namePartner3);
		parameters.push("cpfPartner3");
		parameters.push(cpfPartner3);
		parameters.push("rgPartner3");
		parameters.push(rgPartner3);
		parameters.push("companyReferenceName1");
		parameters.push(companyReferenceName1);
		parameters.push("phone1");
		parameters.push(phone1);
		parameters.push("contact1");
		parameters.push(contact1);
		parameters.push("companyReferenceName2");
		parameters.push(companyReferenceName2);
		parameters.push("phone2");
		parameters.push(phone2);
		parameters.push("contact2");
		parameters.push(contact2);
		parameters.push("companyReferenceName3");
		parameters.push(companyReferenceName3);
		parameters.push("phone3");
		parameters.push(phone3);
		parameters.push("contact3");
		parameters.push(contact3);
		parameters.push("bank1");
		parameters.push(bank1);
		parameters.push("agency1");
		parameters.push(agency1);
		parameters.push("cc1");
		parameters.push(cc1);
		parameters.push("phoneBank1");
		parameters.push(phoneBank1);
		parameters.push("manager1");
		parameters.push(manager1);
		parameters.push("bank2");
		parameters.push(bank2);
		parameters.push("agency2");
		parameters.push(agency2);
		parameters.push("cc2");
		parameters.push(cc2);
		parameters.push("phoneBank2");
		parameters.push(phoneBank2);
		parameters.push("manager2");
		parameters.push(manager2);
		parameters.push("country");
        parameters.push(country);
        parameters.push("supplement");
        parameters.push(supplement);
        parameters.push("addressNumber");
        parameters.push(addressNumber);
        parameters.push("news");
        parameters.push(news);
				
		AjaxHelper.Call(
			"Users",
			"CreateUserWholesale",
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
			   alert('Seus dados foram enviados para consulta, por favor aguarde nosso contato!');
                window.location = JavaScriptConstants.ApplicationUrl + "moda/relogio-de-pulso/tradicional"; 
                
        });
    
}

Users.prototype.UpdateUser = function(phoneNumber, mobilePhone, fax, contact, newPassword, password, cep, city, state, address, addressNumber, supplement, country, news)
{
    var parameters = new Array();
        parameters.push("phoneNumber");
		parameters.push(phoneNumber);
		parameters.push("mobilePhone");
		parameters.push(mobilePhone);
		parameters.push("fax");
		parameters.push(fax);
		parameters.push("contact");
		parameters.push(contact);
		parameters.push("newPassword");
		parameters.push(newPassword);
		parameters.push("password");
		parameters.push(password);
		parameters.push("cep");
		parameters.push(cep);
		parameters.push("city");
		parameters.push(city);
		parameters.push("state");
		parameters.push(state);
		parameters.push("address");
		parameters.push(address);
		parameters.push("addressNumber");
		parameters.push(addressNumber);
		parameters.push("supplement");
		parameters.push(supplement);
		parameters.push("country");
		parameters.push(country);
		parameters.push("news");
        parameters.push(news);
		
		AjaxHelper.Call(
			"Users",
			"UpdateUser",
			AjaxHelper.JSONSerialize(parameters),
			true,
			function(data) {
                alert("Dados alterados");
                window.location = JavaScriptConstants.ApplicationUrl + "moda/relogio-de-pulso/tradicional";
        });
};
var JavaScriptConstants = {
ApplicationUrl : "http://www.espacofechado.com.br/",
VirtualPath : "",
BannersUrl : "http://www.espacofechado.com.br/staging/media/Banners/{0}.jpg",
MountYourUrl : "http://www.espacofechado.com.br/staging/media/MountYour/{0}.png"};
