var USE_SIFR = true;

var SIFR_IMAGO_PATH = RESOURCES_PATH + "sifr/dev_imago.swf";
var SIFR_MINION_ITALIC_PATH = RESOURCES_PATH + "sifr/dev_minion_italic.swf";
var SIFR_MINION_BOLD_ITALIC_PATH = RESOURCES_PATH + "sifr/dev_minion_bold_italic.swf";

var PAGETOOLS_HTML = '\
<ul id="page-tools" class="clearfix">\
	<li><a href="javascript: Tools.print();" id="page-tool-print">' + _.pageTools.print + '</a></li>\
	<li><a href="javascript: Tools.bookmark();" id="page-tool-bookmark">' + _.pageTools.bookmark + '</a></li>\
	<li><a href="javascript: Tools.delicious();" onclick="Tools.delicious(); return false;" id="page-tool-delicious">' + _.pageTools.delicious + '</a></li>\
	<li><a href="javascript: Tools.digg();" onclick="Tools.digg(); return false;" id="page-tool-digg">' + _.pageTools.digg + '</a></li>\
</ul>';

var TEXTRESIZE_HTML = '\
<div id="text-resize">\
	<span id="increase-font"></span>\
	<span id="text-resize-caption" style="background-image: url(/_layouts/_resources/img/' + _.lang + '/text-size.gif); width: 47px; "></span>\
	<span id="decrease-font"></span>\
</div>';

// navigation parameters
var ACTIVE_ENTRY_ID;
ACTIVE_ENTRY_ID = ACTIVE_ENTRY_ID !== undefined ? ACTIVE_ENTRY_ID : null; // set to default

var USE_UNICODE;
USE_UNICODE = USE_UNICODE !== undefined ? USE_UNICODE : false; // set to default
if (USE_UNICODE) USE_SIFR = false; // no sifr when using unicode charsets


var NAV_XML_PATH;
NAV_XML_PATH = NAV_XML_PATH !== undefined ? NAV_XML_PATH : null; // set to default

/********************************************************************/
/* START: initalization                                             */

var tagCloudHtml = true;

if (SIFR_IS_POSSIBLE) {
	tagCloudHtml = false;
	if (USE_SIFR) {
		sIFR.setup();
	}
} else {
	DISABLE_PAGE_NAVIGATION = true;
}


$(document).ready(function() {

    // show text resize tool (including init sIFR)
    if ((typeof DISABLE_PAGE_SIFR == "boolean" && DISABLE_PAGE_SIFR) ||
          (typeof HEADING_USES_SIFR == "boolean" && !HEADING_USES_SIFR)) {
        USE_SIFR = false;

        $("div#content-zone h1").css("visibility", "visible");
        $("div#content-zone h1").css("letter-spacing", "0px");
        $("div.column div.h2 h2").css("visibility", "visible");
        $("div.column div.h2 h2").css("letter-spacing", "0px");
        $("div.column div.medium-quote div.quote").css("visibility", "visible");
        $("div.column div.medium-quote div.quote").css("letter-spacing", "0px");
        $("div.column div.big-quote div.quote").css("visibility", "visible");
        $("div.column div.big-quote div.quote").css("letter-spacing", "0px");
    }

    if (tagCloudHtml) {
        $(".ms-TagCloud").css("letter-spacing", "");
        $(".ms-TagCloud").css("line-height", "40px");
        $(".ms-TagCloud A").css("letter-spacing", "");
        $(".ms-TagCloud A").css("line-height", "");
    }

    $("div#generic-nav-zone.use-text-resize").append(TEXTRESIZE_HTML);
    var textSizeManager = new TextSizeManager("span#decrease-font", "span#increase-font");

    // init flash navigation
    if (!(typeof DISABLE_PAGE_NAVIGATION == "boolean" && DISABLE_PAGE_NAVIGATION)) {
        initNavigation();
    }

    // cancle further initalisation for IE<6
    if (Info.browser.isIEpre6) {
        return;
    }

    // add min-width and max-width to IE<7
    var layoutManager = new LayoutManager;

    if (Info.browser.isIEpre7) {
        layoutManager.register(
			function() {
			    LayoutManager.setMinMaxWidth("div#main-wrapper", 965, 1026);
			    LayoutManager.setMinMaxWidth("div#main-zone", 965, 1024);
			    LayoutManager.setMinMaxWidth("div#footer-zone", 965, 1024);
			}
		);
    }

    // show page tools
    $("div#tool-zone div.use-page-tools").prepend(PAGETOOLS_HTML);
    $("div#page-tool-zone div.use-page-tools").prepend(PAGETOOLS_HTML);

    if (!Tools.isBookmarkable()) {
        $("ul#page-tools li:eq(1)").css("display", "none"); // hide bookmark link
    }

    // measure footer height and correct manual set footer styles

    LayoutManager.repositionFooter();

    // init rating

    $("div#rating a").click(function() {
        RatingManager.clickHandler(this);
    });

    // layer (location selector and site map)

    var layerController = LayerController.getInstance();

    if ($("a#location-selector-handle").length) {
        var locationSelector = new LocationSelector;
        layerController.register(locationSelector);
        locationSelector.toggleWith("a#location-selector-handle");
    }

    if ($("a#sitemap-handle").length) {
        var siteMap = new SiteMap;
        layerController.register(siteMap);
        siteMap.toggleWith("a#sitemap-handle");
    } else if ($("div#sitemap").length) {
        // toggles easy sitemap
        $("div#sitemap dl .toggle").click(function(event) {
            if (event.target.tagName == "A" && event.target != this) { //execute link
                window.location.href = event.target.href;
                return;
            }
            $(this).parents("dl:first").toggleClass("collapsed").toggleClass("expanded");
        });
    }

    // FBA flyout
    if ($("div#fba-handle").length) {
        var fbamenu = new FBAFlyout;
        layerController.register(fbamenu);
        fbamenu.toggleWith("div#fba-handle");
    } else if ($("div#fbamenu").length) {
        // toggles easy sitemap
        $("div#fbamenu dl .toggle").click(function(event) {
            if (event.target.tagName == "A" && event.target != this) { //execute link
                window.location.href = event.target.href;
                return;
            }
            $(this).parents("dl:first").toggleClass("collapsed").toggleClass("expanded");
        });
    }

    // page specific initalization. <body id="body-foo-page">: PageSpecificInit.foo() will be called.

    var pageId = ($("body").attr("id")) ? $("body").attr("id").replace(/^body-(.+)-page$/, "$1") : "";
    if (PageSpecificInit[pageId]) {
        PageSpecificInit[pageId].call();
    }

    $("dl#product-list").productList();

    $("div#productfinder").productfinder();

    if ($(".interactive-image").length && typeof InteractiveImage == "function")
        new InteractiveImage(".interactive-image");


    // init FBA menu controls => java-safe stuff
    $("div#fba-handle").parent().show();
    $("div#generic-nav-zone ul li.fallback").hide();
});

/* END: initalization                                               */
/********************************************************************/
/* START: sifr     */

var SifrManager = {

    painted: false,

    paint: function(cSelector) {
        if (!SIFR_IS_POSSIBLE || !USE_SIFR) return false;
        if (SifrManager.painted) {
            if (cSelector) {
                sIFR.rollback(named({ sSelector: cSelector + " *" }));
            } else {
                sIFR.rollback();
            }
        }

        //replace publishing header styles
        //		var spans = document.getElementsByTagName("SPAN");
        //		var replacements = new Array();
        //		for (var i = 0; i < spans.length; i += 1) {
        //			var span = spans[i];
        //			var h = null;
        //			if (span.className.indexOf("ms-rteCustom-Heading1") > -1) {
        //				h = document.createElement("h1");
        //			} else {
        //				if (span.className.indexOf("ms-rteCustom-Heading2") > -1) {
        //					h = document.createElement("h2");
        //				} else {
        //					if (span.className.indexOf("ms-rteCustom-Heading3") > -1) {
        //						h = document.createElement("h3");
        //					}
        //				}
        //			}

        //			if (h) {
        //				h.innerHTML = span.innerHTML;
        //				replacements.push({ newChild: h, oldChild: span })
        //			}
        //		}

        //		for (var i = 0; i < replacements.length; i += 1) {
        //			var replacement = replacements[i];
        //			replacement.oldChild.parentNode.replaceChild(replacement.newChild, replacement.oldChild);
        //		}

        sIFR.replaceElement(named(
			{ sSelector: "div#content-zone h1",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: ($("div.error-page").length) ? "#cc0033" : "#333333",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.h2-overline h2" : "div#content-zone div.h2-overline h2",
			    sFlashSrc: SIFR_IMAGO_PATH,
			    sColor: "#333333",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: "div#related-links div.h2 h2",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#cc0033",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.h2 h2" : "div.column div.h2 h2",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.big-quote div.quote" : "div.column div.big-quote div.quote",
			    sFlashSrc: SIFR_MINION_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.medium-quote div.quote" : "div.column div.medium-quote div.quote",
			    sFlashSrc: SIFR_MINION_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.small-quote p.quote" : "div.column div.small-quote p.quote",
			    sFlashSrc: SIFR_MINION_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.small-quote-alternative-style p.quote" : "div.column div.small-quote-alternative-style p.quote",
			    sFlashSrc: SIFR_MINION_ITALIC_PATH,
			    sColor: "#333333",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.big-quote p.cite" : "div.column div.big-quote p.cite",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.medium-quote p.cite" : "div.column div.medium-quote p.cite",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.small-quote p.cite" : "div.column div.small-quote p.cite",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent",
			    sFlashVars: "offsetTop=-1"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: cSelector ? cSelector + " div.small-quote-alternative-style p.cite" : "div.column div.small-quote-alternative-style p.cite",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#333333",
			    sWmode: "transparent",
			    sFlashVars: "offsetTop=-1"
			}
		));
        sIFR.replaceElement(named(
			{ sSelector: "div#productfinder div.h2 h2",
			    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
			    sColor: "#666666",
			    sWmode: "transparent"
			}
		));

        sIFR.replaceElement(named(
		{ sSelector: "div#tool-zone h1",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#333333",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: "div#content-zone h2",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: "div#tool-zone h2",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: "div#content-zone h3",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: "div#tool-zone h3",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: ".ms-rteCustom-Heading1",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#333333",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: ".ms-rteCustom-Heading2",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));

        sIFR.replaceElement(named(
		{ sSelector: ".ms-rteCustom-Heading3",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));

        if (!tagCloudHtml) {
            sIFR.replaceElement(named(
		{ sSelector: ".ms-TagCloud",
		    sFlashSrc: SIFR_MINION_BOLD_ITALIC_PATH,
		    sColor: "#666666",
		    sWmode: "transparent"
		}));
        }
        SifrManager.painted = true;
    }

};

/* END: sifr                                                        */
/********************************************************************/
/* START: common layout                                             */

var LayoutManager = function() { };

$.extend(LayoutManager.prototype, {

    register: function(fn) {
        fn.call();
        $(window).resize(fn);
    }
});

$.extend(LayoutManager, {

    repositionFooter: function() {
        // ak: it could happen that we have several elements on the page with id = footer
        var footerConstant = ($("div#footer-zone div#footer").height() + 47) + "px";
        $("div#footer-zone").css({ height: footerConstant, marginTop: "-" + footerConstant });
        $("div#main-zone").css("paddingBottom", footerConstant);
    },

    setMinMaxWidth: function(selector, minWidth, maxWidth) {
        var stylesheet = IEStylesheet.getImportedStylesheet("import/specific-ie.css");
        if (stylesheet) {
            var rule = IEStylesheet.getRuleBySelector(stylesheet, "html " + selector);
            if (rule) {
                rule.style.width = Utilities.minMax($(window).width(), minWidth, maxWidth) + "px";
            }
        }
    }

});

/* END: common layout                                               */
/********************************************************************/
/* START: text resizing                                             */

var TextSizeManager = function(decreaseNodeSelector, increaseNodeSelector) {
    this.decreaseJqo = $(decreaseNodeSelector);
    this.increaseJqo = $(increaseNodeSelector);
    this.init();
};

$.extend(TextSizeManager.prototype, {

    fontsize: null,

    init: function() {
        this.getFontsize();
        this.setFontsize();

        var _this = this;

        this.decreaseJqo.click(function() {
            if (_this.fontsize > 1) {
                _this.fontsize--;
                _this.setFontsize();
            }
        });
        this.increaseJqo.click(function() {
            if (_this.fontsize < 3) {
                _this.fontsize++;
                _this.setFontsize();
            }
        });

    },

    getFontsize: function() {
        this.fontsize = Cookie.get("fontsize");
        if (!/^[123]$/.test(this.fontsize)) {
            this.fontsize = 1;
        }
    },

    setFontsize: function() {
        var mainWrapper = $("div#main-wrapper");
        var _this = this;
        $.each({ 1: "text-size-m", 2: "text-size-l", 3: "text-size-xl" }, function(key, className) {
            if (key == _this.fontsize) {
                mainWrapper.addClass(className);
            } else {
                mainWrapper.removeClass(className);
            }
        });

        if (this.fontsize == 1) {
            this.decreaseJqo.removeClass("active");
        } else {
            this.decreaseJqo.addClass("active");
        }
        if (this.fontsize == 3) {
            this.increaseJqo.removeClass("active");
        } else {
            this.increaseJqo.addClass("active");
        }

        SifrManager.paint();
        LayoutManager.repositionFooter();

        Cookie.set("fontsize", this.fontsize, 365);
    }

});

/* END:   text resizing                                             */
/********************************************************************/
/* START: rating                                                    */

var RatingManager = function() { };

$.extend(RatingManager, {

    clickHandler: function(obj) {
        grade = parseInt(obj.id.match(/[1-6]$/));
        RatingManager.rate(grade);
    },

    displayFeedback: function(msg, grade, error) { // protected
        $("div#rating p").remove(".error").remove(".success");
        var className = (error) ? "error" : "success";
        $("div#rating p").eq(0).after("<p class=\"" + className + "\">" + msg + "</p>");
        $("div#rating a").each(
			function(dummy, item) {
			    var itemGrade = parseInt(item.id.match(/[1-6]$/));
			    var background = (itemGrade > grade) ? "#bababa" : "#06c";
			    $(item).css("background", background);
			}
		);
    },

    displayError: function(msg) {
        RatingManager.displayFeedback(msg, -1, true);
    },

    displaySuccess: function(msg, grade) {
        RatingManager.displayFeedback(msg, grade, false);
    }

});

/* END: rating                                                      */
/********************************************************************/
/* START: KeyEventManager                                           */

var KeyEventManager = function() {
    this.handlers = [];
    var _this = this;

    $("html").keydown(function(e) {
        var keyCode = (e) ? e.which : event.keyCode;
        if ((keyCode < 37 || keyCode > 40) && keyCode != 32) return; //only handle arrow keys and space bar
        var preventDefault = _this.handleKeyup(keyCode);
        if (preventDefault) {
            e.preventDefault();
            return false;
        } else {
            return true;
        }
    });

    $("html").keyup(function(e) {
        var keyCode = (e) ? e.which : event.keyCode;
        if ((keyCode >= 37 && keyCode <= 40) || keyCode == 32) return; //do not handle arrow keys and space bar
        var preventDefault = _this.handleKeyup(keyCode);
        if (preventDefault) {
            e.preventDefault();
            return false;
        } else {
            return true;
        }
    });
};

KeyEventManager.getInstance = function() {
    this.instance = this.instance || new this;
    return this.instance;
};

$.extend(KeyEventManager.prototype, {

    handleKeyup: function(keyCode) {
        var preventDefault = false;
        for (i = 0; i < this.handlers.length; i++) {
            preventDefault = preventDefault || this.handlers[i].callback.call(this.handlers[i].obj, keyCode);
        }
        return preventDefault;
    },

    register: function(handlerObj, callbackFunc) {
        if (!handlerObj) return false;
        if (!callbackFunc && typeof callbackFunc != "function") return false;
        for (i = 0; i < this.handlers.length; i++) {
            if (this.handlers[i].obj == handlerObj) {
                this.handlers[i].callback = callbackFunc;
                return;
            }
        }
        this.handlers.push({ obj: handlerObj, callback: callbackFunc });
    },

    unregister: function(handlerObj) {
        if (!handlerObj) return false;
        for (i = 0; i < this.handlers.length; i++) {
            if (this.handlers[i].obj == handlerObj) {
                this.handlers.splice(i, 1);
                break;
            }
        }
    }
});

/* END: KeyEventManager                                             */
/********************************************************************/
/* START: KeyScrollable                                             */

var KeyScrollable = function() {
    this.initKeyScrolling();
};

$.extend(KeyScrollable.prototype, {
    initKeyScrolling: function(selectors) {

        var defaultSelectors = {
            selectList: 'div.keyScrollable',
            mask: 'div.scrollableMask',
            slider: 'div.slider'
        };

        this.selectors = $.extend(defaultSelectors, selectors);
    },

    onOpen: function() {
        if (KeyEventManager) var keyEventManager = KeyEventManager.getInstance();
        else return;
        keyEventManager.register(this, this.onKeyPressed);
    },

    onClose: function() {
        $(this.selectors.selectList + " li.selected:first").removeClass("selected");
        var $curContent = this.currentContent || $(this.selectors.selectList);
        var $curSlider = $(this.selectors.slider + ":visible", $curContent);
        $curSlider.slider("moveTo", 0);
        if (KeyEventManager) var keyEventManager = KeyEventManager.getInstance();
        else return;
        keyEventManager.unregister(this);
    },

    onKeyPressed: function(keyCode) {
        var $curContent = this.currentContent || $(this.selectors.selectList);
        var $curSlider = $(this.selectors.slider + ":visible", $curContent);
        var self = this;

        var syncSliderWithSelection = function() {
            var $selected = $curContent.find("li.selected");
            if ($selected.length == 0) return;
            var maskHeight = $curContent.find(self.selectors.mask).height();
            var liTop = $selected.position().top - parseInt($curContent.find("ul").css("padding-top"));
            var liOuterHeight = $selected.outerHeight();
            var listTop = $curContent.find("ul").position().top;

            var tempPos = liTop + listTop;
            if (tempPos < 0 || tempPos + liOuterHeight > maskHeight) {
                $curSlider.slider("moveTo", liTop);
            }
        };

        var moveToNextBlock = function() {
            var maskHeight = $curContent.find(self.selectors.mask).height();
            var listTop = $curContent.find("ul").position().top;
            var listHeight = $curContent.find("ul").height();

            var nextPos = maskHeight - listTop;
            if (nextPos < listHeight) {
                $curSlider.slider("moveTo", nextPos);
            }
        };

        var transformUmlaut = function(letter) {
            switch (letter) {
                case "\u00C4": //Ä
                    letter = "A";
                    break;
                case "\u00D6": //Ö
                    letter = "O";
                    break;
                case "\u00DC": //Ü
                    letter = "U";
                    break;
            }
            return letter;
        }

        var preventDefault = false;
        switch (keyCode) {
            case 38: //up
                $curContent.find("li.selected:first").removeClass("selected").prev().addClass("selected");
                if ($curContent.find("li.selected").length == 0) {
                    $curContent.find("li:last").addClass("selected");
                }
                syncSliderWithSelection();
                preventDefault = true;
                break;
            case 40: //down
                $curContent.find("li.selected:first").removeClass("selected").next().addClass("selected");
                if ($curContent.find("li.selected").length == 0) {
                    $curContent.find("li:first").addClass("selected");
                }
                syncSliderWithSelection();
                preventDefault = true;
                break;
            case 32: //space
                preventDefault = true;
                moveToNextBlock();
                break;
            case 13: //enter
                $curContent.find("li.selected:first a").click(function() { if (this.href) window.location.href = this.href; }).trigger("click");
                break;
            default:
                if ((keyCode >= 65 && keyCode <= 90) || (keyCode >= 48 && keyCode <= 57)) {
                    //letters
                    var letter = String.fromCharCode(keyCode).toUpperCase();
                    $curContent.find("li.selected").removeClass("selected");
                    var $listItemToMark = null;
                    $curContent.find("li a").each(function() {
                        var firstLetter = transformUmlaut($(this).text().charAt(0).toUpperCase());
                        if (firstLetter == letter) {
                            $listItemToMark = $(this).parents("li:first");
                            return false;
                        } else if (firstLetter > letter) {
                            $listItemToMark = $(this).parents("li:first").prev();
                            return false;
                        }
                    });
                    $listItemToMark = $listItemToMark || $curContent.find("li:last");
                    $listItemToMark.addClass("selected");
                    syncSliderWithSelection();
                }
        }

        return preventDefault;
    }

});

/* END: KeyScrollable                                               */
/********************************************************************/
/* START: layer                                                     */

var LayerController = function() {
    this.layers = [];
    this.currentLayer = null;
    this.instance = null;

    var _this = this;
    $("body").click(function() {
        _this.closeCurrentLayer();
    });
    $("body").keyup(function(e) {
        var keyCode = (e) ? e.which : event.keyCode;
        if (keyCode == 27) {
            _this.closeCurrentLayer();
        }
    });
};

LayerController.getInstance = function() {
    this.instance = this.instance || new this;
    return this.instance;
};

$.extend(LayerController.prototype, {

    closeCurrentLayer: function() {
        if (this.currentLayer)
            this.currentLayer.close();
    },

    register: function(layer) {
        this.layers.push(layer);
        layer.owner = this;
    }

});

/********************************************************************/

var Layer = function(cssSelector) {
    this.construct(cssSelector);
};

$.extend(Layer.prototype, {

    construct: function() {
        this.isOpen = false;
        this.isInited = false;
        this.contentJqo = null;
    },

    close: function(newLayer) {
        this.beforeHide();
        this.hide(newLayer);
        if (this.iframeLining) {
            this.iframeLining.hide();
        }

        this.afterHide();
        this.isOpen = false;
        this.owner.currentLayer = null;
        return true;
    },

    getContent: function() { },

    hide: function() {
        this.contentJqo.hide();
    },

    open: function() {
        this.owner.closeCurrentLayer();
        if (!this.isInited) {
            this.contentJqo = this.getContent();
            this.init();
            this.isInited = true;
            if (Info.browser.isIEpre7 || Info.os.isMac) {
                this.iframeLining = new iframeLining(this);
            } else {
                this.iframeLining = null;
            }
            this.contentJqo.click(function(e) { e.stopPropagation(); });
        }
        this.beforeShow();
        this.show();
        if (this.iframeLining) {
            this.iframeLining.show();
        }
        this.afterShow();
        this.isOpen = true;
        this.owner.currentLayer = this;
        return true;
    },

    reposition: function() {
        if (this.iframeLining) {
            this.iframeLining.reposition();
        }
    },

    show: function() {
        this.contentJqo.show();
    },

    toggle: function() {
        if (this.isOpen) {
            this.close();
        } else {
            this.open();
        }
    },

    toggleWith: function(cssSelector) {
        var _this = this;

        $(cssSelector).click(function(e) {
            _this.toggle();
            return false;
        });
    },

    afterHide: function() { },
    afterShow: function() { },
    beforeHide: function() { },
    beforeShow: function() { }

});

/********************************************************************/

var LocationSelector = function() {
    this.construct();

    this.selectors = {
        selectList: 'div#location-selector',
        mask: 'div#location-list-wrapper',
        slider: 'div.slider'
    };

    this.initKeyScrolling(this.selectors);
};

$.extend(LocationSelector.prototype, Layer.prototype);

$.extend(LocationSelector.prototype, KeyScrollable.prototype);

$.extend(LocationSelector.prototype, {
    afterHide: function() {
        $("a#location-selector-handle").parent().css("z-index", "10");

        this.onClose();
    },

    beforeShow: function() {
        $("a#location-selector-handle").parent().css("z-index", "11");

        this.onOpen();
    },

    init: function() {
        var numberOfLocations = $("div#location-selector li").length;
        var visibleLocations = 20;
        if (numberOfLocations < visibleLocations) {
            $("div#location-selector div.slider").hide();
        } else {
            var sliderHeight = 300;
            var visibleHeight = 300;
            var handleHeight = Math.round(sliderHeight * visibleLocations / numberOfLocations);
            $("div#location-selector div.handle").css("height", handleHeight + "px");
            var locationListHeight = $("div#location-selector ul").height();

            var syncLayer = function(e, ui) {
                var newLocationListOffset = parseInt(-ui.value);
                $("div#location-selector ul").css("top", newLocationListOffset);
            }

            var $slider = $("div#location-selector div.slider").slider({
                minValue: 0,
                maxValue: (locationListHeight - visibleHeight),
                slide: syncLayer,
                change: syncLayer
            });
            /*		
            $(this.selectors.selectList).mousewheel(function(event, delta) {
            if (delta > 0) {
            $slider.slider("moveTo", $slider.slider("value")-(delta+10));
            } else if (delta < 0) {
            $slider.slider("moveTo", $slider.slider("value")-delta+10);
            }
            event.preventDefault();
            event.stopPropagation();
            });
            */
        }
    }
});

/********************************************************************/

var SiteMap = function() {
    this.construct();
};

$.extend(SiteMap.prototype, Layer.prototype);

$.extend(SiteMap.prototype, {

    getContent: function() {
        return $("div#sitemap");
    },

    init: function() {
        var handleLeftOffset = $("a#sitemap-handle").parent().position().left;
        var handleWidth = $("a#sitemap-handle").outerWidth();
        $("div#sitemap-tab").css({
            left: (handleLeftOffset - 32) + "px",
            width: (handleWidth + 20) + "px"
        });
        this.toggleWith("div#sitemap-tab");

        var _this = this;
        $("div#sitemap dl .toggle").click(function(event) {
            if (event.target.tagName == "A" && event.target != this) { //execute link
                window.location.href = event.target.href;
                return;
            }
            $(this).parents("dl:first").toggleClass("collapsed").toggleClass("expanded");
            _this.reposition();
        });
    }

});

/********************************************************************/

var FBAFlyout = function() {
    this.construct();
};

$.extend(FBAFlyout.prototype, Layer.prototype);

$.extend(FBAFlyout.prototype, {

    getContent: function() {
        return $("div#fbamenu");
    },

    init: function() {
        var fbaMenu = $("div#fbamenu");
        var handleLeftOffset = $("div#fba-handle").parent().position().left;
        var handleWidth = $("div#fba-handle").outerWidth();
        var fbaMenuWidth = fbaMenu.outerWidth();
        var fbaTabLeft = handleLeftOffset - 32 - 330;

        fbaMenu.css({
            left: (handleLeftOffset - 20) + "px"
        });

        $("div#fba-tab").css({
            left: (8) + "px",
            width: (handleWidth + 20) + "px"
        });

        this.toggleWith("div#fba-tab");

        var _this = this;
        $("div#fbamenu dl .toggle").click(function(event) {
            if (event.target.tagName == "A" && event.target != this) { //execute link
                window.location.href = event.target.href;
                return;
            }
            $(this).parents("dl:first").toggleClass("collapsed").toggleClass("expanded");
            _this.reposition();
        });
    }

});

/********************************************************************/

var iframeLining = function(layer) {
    this.layer = layer;
    this.liningJqo = $('<iframe src="javascript:false" class="lining" frameborder="0" scrolling="no"></iframe>');
    this.layer.contentJqo.parent().prepend(this.liningJqo); // parent is of type "div.layer-wrapper"
};

$.extend(iframeLining.prototype, {

    hide: function() {
        this.liningJqo.hide();
    },

    reposition: function() {
        var contentJqo = this.layer.contentJqo;
        this.liningJqo.css({
            width: contentJqo.outerWidth() + "px",
            height: contentJqo.outerHeight() + "px",
            left: this.layer.contentJqo.css("left"),
            top: this.layer.contentJqo.css("top")
        });
    },

    show: function() {
        this.reposition();
        this.liningJqo.show();
    }
});

/* END: layer                                                       */
/********************************************************************/
/* START: tools and utilities                                       */

var Tools = {

    bookmark: function() {
        var url = location.href;
        var title = document.title;

        if (Info.browser.isIE) {
            window.external.AddFavorite(url, title);
        } else if (window.sidebar) {
            window.sidebar.addPanel(title, url, "");
        }
    },

    isBookmarkable: function() {
        var url = location.href;
        var server = /^(https?|ftp):/i.test(url);
        if (Info.browser.isIE7 && server) return true;
        if (Info.browser.isIEpre7) return true;
        if (Info.browser.isMozilla && window.sidebar && server) return true;
        return false;
    },

    delicious: function() {
        window.open("http://del.icio.us/post?url=" + encodeURIComponent(location.href) + "&title=" + encodeURIComponent(document.title));
    },

    digg: function() {
        window.open("http://digg.com/submit?url=" + encodeURIComponent(location.href) + "&title=" + encodeURIComponent(document.title));
    },

    print: function() {
        window.print();
    }
};

var Utilities = {

    minMax: function(value, minValue, maxValue) {
        if (value < minValue) {
            return minValue;
        } else if (value > maxValue) {
            return maxValue;
        } else {
            return value;
        }
    }
};

var EventHelper = {
    target: function(e) {
        var t;
        if (!e) var e = window.event;
        if (e.target) t = e.target;
        else if (e.srcElement) t = e.srcElement;
        if (t.nodeType == 3) // defeat Safari bug
            t = t.parentNode;

        return t;
    }
};

/* END: tools and utilities                                         */
/********************************************************************/
/* START: cookie                                                    */

var Cookie = {

    set: function(key, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + days * 86400000);
            var expires = "; expires=" + date.toGMTString();
        }
        document.cookie = key + "=" + value + expires + "; path=/";
    },

    get: function(key) {
        if (key) {
            var obj = Cookie.get();
            return obj[key];
        } else {
            var obj = {};
            if (document.cookie) {
                var pairs = document.cookie.split(";");
                for (i in pairs) {
                    var pair = pairs[i].split("=");
                    if (pair.length == 2) {
                        obj[pair[0].replace(/^\s+/, "")] = pair[1];
                    }
                }
            }
            return obj;
        }
    },

    unset: function(key) {
        Cookie.set(key, "", -1);
    }
};

/* END: cookie                                                      */
/********************************************************************/
/* START: stylesheet helper for IE                                  */

var IEStylesheet = {

    getImportedStylesheet: function(href) {

        for (var i = 0, li = document.styleSheets.length; i < li; ++i) {
            var stylesheet = document.styleSheets(i);
            if (stylesheet.imports) {
                for (j = 0, lj = stylesheet.imports.length; j < lj; ++j) {
                    var imported = stylesheet.imports(j);
                    if (imported.href == href) {
                        return imported;
                    }
                }
            }
        }
        return null;
    },

    getRuleBySelector: function(stylesheet, selector) {
        for (var i = 0, l = stylesheet.rules.length; i < l; ++i) {
            var rule = stylesheet.rules.item(i);
            if (rule.selectorText.replace(/^\s/, "").replace(/\s$/, "").toLowerCase() == selector.toLowerCase()) {
                return rule;
            }
        }
        return null;
    }
};

/* END: stylesheet helper for IE                                    */
/********************************************************************/
/********************************************************************/
/* START: resizing the flyoutnav containers for flash flyoutnavs at runtime */

var ZINDEX_ACTIVE = 100;
var ZINDEX_INACTIVE = 1;
var PRIM_NAV_HEIGHT_CLOSED = 42;
var PRIM_NAV_HEIGHT_NO_BORDER = 41;

function primNavHasNoBorder() {
    if ($("#stage-zone").length || $("#primary-nav-zone.no-border").length) {
        return true;
    }
    return false;
}

if (Info.browser.isIE) {
    /*functions for internet explorer*/
    resizeNavigation = function(divid, options) {
        var $flyoutnav = $("#" + divid);
        var $flyoutnav_parent = $flyoutnav.parents(".flyoutnav_positioner:first");

        var newZIndex = ZINDEX_ACTIVE;
        var newHeight;

        if (options.height) {
            newHeight = options.height;
            if (primNavHasNoBorder() && newHeight == PRIM_NAV_HEIGHT_CLOSED) {
                newHeight = PRIM_NAV_HEIGHT_NO_BORDER; // hide bottom border
            }
            $flyoutnav.height(newHeight);
        }
    }
} else {
    /*functions for all browsers except internet explorer*/

    resizeNavigation = function(divid, options) {
        var $flyoutnav = $("#" + divid);
        var $flyoutnav_parent = $flyoutnav.parents(".flyoutnav_positioner:first");

        if (options) {
            calculateClipping($flyoutnav, $flyoutnav_parent, options);
        }
    }
}

function calculateClipping($flyoutnav, $flyoutnav_parent, options) {
    var newWidth = $flyoutnav_parent.width();
    var newHeight = $flyoutnav_parent.height();
    var newOffsetTop = 0;
    var newOffsetLeft = 0;

    if (options) {
        newWidth = options.width ? options.width : $flyoutnav_parent.width();
        newHeight = options.height ? options.height : $flyoutnav_parent.height();

        if (options.valign && options.valign == "bottom" && $flyoutnav.hasClass("open")) {
            newOffsetTop = $flyoutnav.height() - $flyoutnav_parent.height();
            newHeight = $flyoutnav_parent.height();
        }

        if (options.align && options.align == "right" && $flyoutnav.hasClass("open")) {
            newOffsetLeft = $flyoutnav.width() - $flyoutnav_parent.width();
            newWidth = $flyoutnav_parent.width();
        }
    }

    $flyoutnav.css({ clip: "rect(" + newOffsetTop + "px, " + newWidth + "px, " + newHeight + "px, " + newOffsetLeft + "px)" });
    if (primNavHasNoBorder() && newHeight == PRIM_NAV_HEIGHT_CLOSED) {
        newHeight = PRIM_NAV_HEIGHT_NO_BORDER; // hide bottom border
    }
    $flyoutnav.height(newHeight);
}

function initNavigation() {
    if ($("#primary-nav-zone").length != 0 && Info.flash.major >= 8) {
        $("#sub-nav-zone").remove();
        $("#primary-nav-zone").addClass("flyoutnav_positioner").empty().append("<div id='prim-nav' class='flyoutnav'></div>");

        if (primNavHasNoBorder()) {
            $("#prim-nav").height(PRIM_NAV_HEIGHT_NO_BORDER); // hide bottom border
            $("#primary-nav-zone").css("border-bottom", "none");
            if ($("#stage-zone").length) $("#stage-zone").css("margin-top", "0");
            $("#header-zone").css("z-index", "10");
        }
        if (NAV_UNICODE == true) {
            var NAV_SWF_PATH = "swf/RocheUnicode/navigation.swf";
        }
        else {
            var NAV_SWF_PATH = "swf/RocheLatinExtended/navigation.swf";
        }
        var so_lf = new SWFObject(RESOURCES_PATH + NAV_SWF_PATH, "navigation_swf", "100%", "100%", "8", "#ffffff");

        so_lf.addParam("wmode", "transparent");
        so_lf.addParam("scale", "noscale");
        so_lf.addParam("salign", "tl");
        so_lf.addVariable("containerID", "prim-nav");
        so_lf.addVariable("noCache", "true");
        /***** add additional params as variables *****/
        // path where xml containing navigation entries is located
        if (NAV_XML_PATH) so_lf.addVariable("navXML", NAV_XML_PATH);
        else so_lf.addVariable("navXML", RESOURCES_PATH + "/swf/nav.xml");
        // ID of selected navigation entry to highlight
        if (ACTIVE_ENTRY_ID) so_lf.addVariable("activeEntryID", ACTIVE_ENTRY_ID);
        // use unicode version if xml contains unicode charset
        if (USE_UNICODE) so_lf.addVariable("useUnicode", USE_UNICODE);


        so_lf.write("prim-nav");

        var mouseOutTimeout;

        function getFlashMovieObject(movieName) {
            if (window.document[movieName]) return window.document[movieName];
            if (document.embeds && document.embeds[movieName]) return document.embeds[movieName];
            else return document.getElementById(movieName);
        }

        function closeNavigation() {
            if (getFlashMovieObject("navigation_swf")) document.getElementById("navigation_swf").SetVariable("mouseIsOver", "0");
        }

        $("#prim-nav").hover(
			function() {
			    clearTimeout(mouseOutTimeout);
			},
			function() {
			    clearTimeout(mouseOutTimeout);
			    mouseOutTimeout = window.setTimeout(function() { closeNavigation(); }, 1000);
			}
		);

        if (Info.browser.isIEpre7 || Info.os.isMac) createIFrame($("#prim-nav").children().get(0));
    }
}
/* END: resizing the flyoutnav containers for flash flyoutnavs at runtime */
/********************************************************************/
/********************************************************************/
/* START: iframe for navigation in ie6                              */
function createIFrame(obj) {
    var iframe = $(obj).next("iframe.opaque:first").get(0);
    if (!iframe) {
        $(obj).after("<iframe src='javascript:false' class='opaque' frameBorder='0' scrolling='no'></iframe>");
        iframe = $(obj).next("iframe.opaque:first").get(0);
    }
    obj.iframe = iframe;

    return iframe;
}
/* END: iframe for navigation in ie6                                */
/********************************************************************/
/* START: page specific initalization                               */

var PageSpecificInit = {

    error: function() {

        // add "autojump" functionality to pulldowns: an url is called after changing the value

        $("select.autojump").change(function() {
            location.href = this.value;
        }).next("div.button").remove();

    },

    faq: function() {

        // collapse and expand toc chapters

        $("div.toc h3 a").click(function() {
            $(this).parent().parent().toggleClass("expanded");
            return false;
        });

    },


    "order-now": function() {

        // add tooltip functionality to order-now-page

        $("body#body-order-now-page p.annotation").prev("h3").each(function(i) {

            var h3 = $(this);
            var p = $(this).next("p.annotation");
            var trigger = h3.append("<span>&nbsp;</span>").children("span");

            p.css({
                left: trigger.position().left + "px",
                top: trigger.position().top + "px"
            });

            trigger.mouseover(function() {
                p.css("display", "block");
            }).mouseout(function() {
                p.css("display", "none");
            });
        });

        // improve reset functionality to order-now-page (rests just the check-boxes)

        $("body#body-order-now-page button[type=reset]").click(function() {
            $("input[type=checkbox]").attr("checked", false);
            return false;
        });
    }
};

/* END: page specific initalization                                 */
/********************************************************************/
/* START: Productfinder                                             */
/* accordion functionality and slider for each accordion element    */
(function($) {
    $.productfinder = {};

    $.fn.extend($.productfinder, {
        defaults: {
            accordionClass: "accordion",
            menuContentClass: "menu-content",
            SLIDER_HTML: '<div class="slider"><div class="handle ui-slider-handle"></div></div>'
        }
    });

    $.fn.extend({
        productfinder: function(options) {
            // setup configuration
            options = $.extend({}, $.productfinder.defaults, options);
            var element = this;
            if (!$('.' + options.accordionClass, element).length) {
                return;
            }

            new ProductfinderInstance(this, options);
            return this;
        }
    });

    var s, o, e;

    var ProductfinderInstance = function(element, options) {
        s = this;
        o = options;
        e = element;

        this.currentContent;

        this.initSlider();
        this.initAccordion();

        this.selectors = {
            selectList: 'div#productfinder div.menu-content',
            mask: 'div.menu-wrapper',
            slider: 'div.slider'
        };

        this.initKeyScrolling(this.selectors);

        var layerController = LayerController.getInstance();
        if (layerController) layerController.register(this);
    };

    var handleClickOutside = function(event) {
        var a = $('.accordion', e);
        //looking for stored element-data "opened"
        if (!a.data("opened")) return;

        var target = EventHelper.target(event);
        if (!$(target).parents("div#productfinder").length) {
            a.activate(false);
            $(".selected", a).removeClass("selected");
        }
    };

    $.extend(ProductfinderInstance.prototype, KeyScrollable.prototype);

    $.extend(ProductfinderInstance.prototype, {

        addCloseHandler: function() {
            $(document.body).click(handleClickOutside);
        },

        removeCloseHandler: function() {
            $(document.body).unbind("click", handleClickOutside);
        },

        initSlider: function() {
            var selector = "." + o.accordionClass + " div." + o.menuContentClass;
            $(selector, e).each(function() {
                $(this).append(o.SLIDER_HTML);
            });
        },

        initAccordion: function() {
            $('.accordion', e).accordion({
                header: '.trigger',
                active: false,
                autoHeight: false,
                alwaysOpen: false
            }).change(function(event, newHeader, oldHeader, newContent, oldContent) {
                var self = $(this);
                //if the accordion is closed programmatically, newHeader would be null
                if (!newHeader) {
                    self.removeData("opened");
                    s.onClose();
                    return;
                }

                //if user closed the opened element, newMenu would represent the closed one, so do nothing
                var newMenu = newHeader.parents("div.menu:first");
                if (!$(newMenu).hasClass("selected")) {
                    self.removeData("opened");
                    s.onClose();
                    return;
                }

                var menuContent = $("div.menu-content", newMenu);
                self.data("opened", "true");
                s.currentContent = menuContent;
                s.onOpen();
                //if accordion-element always be initialize, we would do nothing (stored for the element itself)
                if (!menuContent.data("init")) {
                    //initialise slider for each element once
                    s.initSliding(menuContent);
                }
            }).click(function(e) { e.stopPropagation(); });
        },

        initSliding: function(menuContent) {
            $(menuContent).data("init", "true");
            var visibleHeight = 236;
            var menuHeight = $("ul.menu", menuContent).height();

            if (menuHeight < visibleHeight) {
                $("div.slider", menuContent).hide();
            } else {
                $("div.slider", menuContent).show();
                var sliderHeight = 236;
                var visibleHeight = 236;
                var handleHeight = Math.round(sliderHeight * visibleHeight / menuHeight);
                $("div.handle", menuContent).css("height", handleHeight + "px");

                var syncLayer = function(e, ui) {
                    var newLocationListOffset = parseInt(-ui.value);
                    $("ul", menuContent).css("top", newLocationListOffset);
                }

                var s = $("div.slider", menuContent).slider({
                    minValue: 0,
                    maxValue: (menuHeight - visibleHeight),
                    slide: syncLayer,
                    change: syncLayer
                });

                menuContent.mousewheel(function(event, delta) {
                    if (delta > 0) {
                        s.slider("moveTo", s.slider("value") - (delta + 10));
                    } else if (delta < 0) {
                        s.slider("moveTo", s.slider("value") - delta + 10);
                    }
                    event.preventDefault();
                    event.stopPropagation();
                });
            }
        },

        onOpen: function() {
            KeyScrollable.prototype.onOpen.call(this);

            if (this.owner.currentLayer != this) {
                this.owner.closeCurrentLayer();
                this.owner.currentLayer = this;
            }
        },

        onClose: function() {
            this.currentContent = null;

            KeyScrollable.prototype.onClose.call(this);
            if (this.owner.currentLayer == this) {
                this.owner.currentLayer = null;
            }
        },

        open: function() {
            $('.accordion', e).activate(0);
        },

        close: function() {
            $('.accordion', e).find("div.menu.selected:first").removeClass("selected");
            $('.accordion', e).activate("false");
        }
    });
})(jQuery);
/* START: Productfinder                                             */
/********************************************************************/
/********************************************************************/
/* START: Productlist                                               */
(function($) {
    $.fn.extend({
        productList: function() {
            var entries = $("dt a", this).filter(function() { return true; $(this).hasClass("handler") });
            entries.each(function(i) {
                var isFirst = i == 0;
                if ($(this).hasClass("handler-external")) {
                    ProductList.handleExternalLink(this);
                } else {
                    ProductList.handle(this, isFirst);
                }
            });
        }
    });

    var ProductList = function() { };

    $.extend(ProductList, {
        handleExternalLink: function(link) {
            $(link).click(function() {
                window.open(this.href); return false;
            });
        },
        handle: function(link, isFirst) {
            $(link).click(function() {
                if (ProductList.opened) {
                    var openedDt = ProductList.opened[0];
                    var openedContent = ProductList.opened[1];
                    openedDt.show();
                    openedContent.hide();
                }
                var dt = $(this).parents(":first");
                var content = dt.next("dd").find("div.section");
                ProductList.opened = [dt, content]
                dt.hide();
                if (isFirst) content.css({ 'padding-top': '1px' });
                content.show();
            });
        },

        opened: null
    });
})(jQuery);
/* END: Productlist                                               */
/********************************************************************/

/* ************************************************************ */

//the function that is called on heading2 button click
function Heading2ButtonOnClick(strBaseElementID, arguments) {

	//get the document that is being edited
	var docEditor = RTE_GetEditorDocument(strBaseElementID);

	//if nothing is being edited quit               
	if (docEditor == null) { return; }

	//get range (selected text)
	var selection = docEditor.selection;
	var rngSelection;
	if (selection.type == "Control") {
		selection.clear();
		rngSelection = selection.createRange();
		if (rngSelection == null) { return; }
	}
	else {
		rngSelection = selection.createRange();
	}

	//get html from selection
	var html = AdaptHeadingSelection(rngSelection.htmlText, "ms-rteCustom-Heading2");
	//set html
	rngSelection.pasteHTML(html);

	//restore the button state (make it clickable again)                       
	RTE_RestoreSelection(strBaseElementID);

	return true;
}

//the function that is called on heading3 button click
function Heading3ButtonOnClick(strBaseElementID, arguments) {

	//get the document that is being edited
	var docEditor = RTE_GetEditorDocument(strBaseElementID);

	//if nothing is being edited quit               
	if (docEditor == null) { return; }

	//get range (selected text)
	var selection = docEditor.selection;
	var rngSelection;
	if (selection.type == "Control") {
		selection.clear();
		rngSelection = selection.createRange();
		if (rngSelection == null) { return; }
	}
	else {
		rngSelection = selection.createRange();
	}

	//get html from selection
	var html = AdaptHeadingSelection(rngSelection.htmlText, "ms-rteCustom-Heading3");
	//set html
	rngSelection.pasteHTML(html);

	//restore the button state (make it clickable again)                       
	RTE_RestoreSelection(strBaseElementID);

	return true;
}

function AdaptHeadingSelection(strSelection, strHeadingStyle) {
	//remove all html tags
	strSelection = strSelection.replace(/<(.|\n)*?>/g, "");
	//rebuild html
	var html = "<P class='margin'><SPAN class=" + strHeadingStyle + ">" + strSelection + "</SPAN></P>";
	return html;
}

// The function that is called when the button's state is reset.
function HeadingButtonOnResetState(strBaseElementID, arguments) {

	//get the document that is being edited                             
	var docEditor = RTE_GetEditorDocument(strBaseElementID);

	//if nothing is being edited quit                               
	if (docEditor == null) { return; }

	//actually enable the button                     
	// Parameters: 
	// 1 - Pass in the ID of the actual editor (which automatically is sent over on the reset call)        
	// 2 - Boolean, True to turn it back on, False to keep it off                          
	// 3 - The name of the button to turn on

	RTE_TB_SetEnabledFromCondition(strBaseElementID, true, 'heading2Button');
	RTE_TB_SetEnabledFromCondition(strBaseElementID, true, 'heading3Button');

	return true;
}
// end hiding contents

