// createToc(headingSelector / nodes)
var createToc;


gloader.load(["glow", "1", "glow.dom", "glow.events", "glow.anim", "glow.widgets.Overlay", "glow.widgets.InfoPanel", "glow.widgets.AutoSuggest"], {
    async: true,
    onLoad: function(glow) {

        var dom = glow.dom,
			$ = glow.dom.get,
			events = glow.events,
			anim = glow.anim;
		
		//for level 2 browsers
		if (!glow.isSupported) {
			document.documentElement.className = "";
			document.getElementById("js-warning").innerHTML = "Sorry, Glow does not fully support your browser so some site features may be disabled. See the <a href='http://www.bbc.co.uk/guidelines/futuremedia/technical/browser_support.shtml'>BBC Browser Support Standard</a> for details.";
		}
		
		
		//pretify scripts
		glow.ready(function() {
			prettyPrint();
		});
		
		//accordion api script
		(function(){
			function getFullHeight(myNodeList) {
				var currentHeight = myNodeList[0].style.height;
				
				if (!myNodeList[0].style.width && !glow.env.ie) {
					//right, we need to set the width css property else it'll try and shrink to fit
					myNodeList.css( "width", myNodeList[0].offsetWidth - myNodeList.css(["padding-left", "padding-right", "border-left-width", "border-right-width"]) );
				}
				
				var fullHeight = myNodeList.css("visibility", "hidden").
						css("position", "absolute").
						css("height", "auto")[0].offsetHeight;

                myNodeList.css("visibility", "").
						css("position", "").
						css("height", currentHeight);

                return fullHeight;
            }

            function getContentForLink(accordionLink) {
                return accordionLink.parent().next().get(" > div.apiFurtherDetail")
            }

            function slideOpenContent(accordionContent, accordionArrow) {
                if (accordionContent[0].__anim) {
                    accordionContent[0].__anim.stop();
                }

                var slideAnim = anim.css(accordionContent, 0.3, {
                    height: { to: getFullHeight(accordionContent) }
                }, { tween: glow.tweens.easeBoth() });

                var arrowAnim = new glow.anim.Animation(0.3, {
                    tween: glow.tweens.easeBoth()
                });

                var animVals = [];

                for (var i = 0; i < 11; i++) {
                    animVals[i] = -(i * 31) + 2;
                }

                events.addListener(arrowAnim, "frame", function() {
                    var val = Math.floor(this.value * (animVals.length - 1));
                    accordionArrow.css("background-position", "0 " + animVals[val] + "px");
                })

                accordionContent[0].__completeListener = events.addListener(slideAnim, "complete", function() {
                    accordionContent.css("height", "auto");
                });

                var openAnim = accordionContent[0].__anim = new glow.anim.Timeline([
					[slideAnim],
					[arrowAnim]
				]);

                openAnim.start();

                accordionContent[0].__isOpen = true;
            }

            function slideCloseContent(accordionContent, accordionArrow) {
                if (accordionContent[0].__anim) {
                    accordionContent[0].__completeListener && (events.removeListener(accordionContent[0].__completeListener));
                    accordionContent[0].__anim.stop();
                }
                var slideAnim = anim.css(accordionContent, 0.3, {
                    height: { from: accordionContent[0].offsetHeight, to: 0 }
                }, { tween: glow.tweens.easeBoth() });

                var arrowAnim = new glow.anim.Animation(0.3);

                var animVals = [];

                for (var i = 0; i < 11; i++) {
                    animVals[10 - i] = -(i * 31) + 2;
                }

                events.addListener(arrowAnim, "frame", function() {
                    var val = Math.floor(this.value * (animVals.length - 1));
                    accordionArrow.css("background-position", "0 " + animVals[val] + "px");
                })

                var closeAnim = accordionContent[0].__anim = new glow.anim.Timeline([
					[slideAnim],
					[arrowAnim]
				]);

                closeAnim.start();

                accordionContent[0].__isOpen = false;
            }

            function accordionTitleClick() {
                var accordionLink = $(this),
					accordionContent = getContentForLink(accordionLink);

                if (accordionContent[0].__isOpen) {
                    slideCloseContent(accordionContent, accordionLink.children());
                } else {
                    slideOpenContent(accordionContent, accordionLink.children());
                }
                //prevent default
                return false;
            }

            function initAccordion(accordionNode) {
                $(accordionNode).get("dt.furtherDetailHeading").each(function() {
                    this.innerHTML = '<a href="#">' + this.innerHTML + '</a>';
                }).each(function() {
                    events.addListener($(this).get("a"), "click", accordionTitleClick);
                });
                /*
                this fixes a safari 2 bug that randomly positions this element
                in the middle of bloody nowhere, pretending to be position:absolute.
					
					I'm not joking say I've wasted an afternoon on this. The webkit
                team owe me chocolate.
                */
                if (glow.env.webkit < 500) {
                    $("div.apiFurtherDetail").css("display", "run-in");
                }
            }

            function expandAll() {
                $("dt.furtherDetailHeading").get("code, span").css("background-position", "0 -308px");
                $("div.apiFurtherDetail").each(function() {
                    if (this.__anim) {
                        this.__completeListener && (events.removeListener(this.__completeListener));
                        this.__anim.stop();
                    }
                    this.__isOpen = true;
                }).css("height", "auto");
                return false;
            }

            function collapseAll() {
                $("dt.furtherDetailHeading").get("code, span").css("background-position", "0 2px");
                $("div.apiFurtherDetail").each(function() {
                    if (this.__anim) {
                        this.__completeListener && (events.removeListener(this.__completeListener));
                        this.__anim.stop();
                    }
                    this.__isOpen = false;
                }).css("height", "0");
                return false;
            }


            var lastHash = window.location.hash;
            function checkHash() {
                var newHash = window.location.hash;
                if (newHash != lastHash) {
                    revealByHash();
                    lastHash = newHash;
                }
            }

            //open the section the hash points to
            function revealByHash() {
                var element = document.getElementById(
					window.location.hash.slice(1)
				);
                if (!element) { return; }
                var term = $(element),
					link = term.get("a");

                if (term.hasClass("furtherDetailHeading") && !link.hasClass("open")) {
                    var content = getContentForLink(link);
                    content.css("height", "auto")[0].__isOpen = true;
                    link.addClass("open");
                    window.location.hash = window.location.hash;
                }
            }

            glow.ready(function() {
                var apiDiv = $("#api");

                //stuff for the API
                if (!apiDiv[0]) { return; }

                apiDiv.each(function() {
                    initAccordion(this);
                });

                var expandLinks = $("#apiOptions").html(
					'<ul><li class="first"><a href="#">Expand All</a> </li> <li><a href="#">Collapse All</a> </li> </ul>'
				).get("a");

                events.addListener(expandLinks[0], "click", expandAll);
                events.addListener(expandLinks[1], "click", collapseAll);

                //watch for changes in hash
                window.setInterval(checkHash, 30);
                revealByHash();
            });

        })();


        //quickref stuff
        (function() {

            var quickRefHolder = $("#quickRef div.sectionInner");
            // exit if there isn't a quickref holder on this page

            if (!quickRefHolder[0]) {

                return;
            }
            glow.ready(function() {

                // build the form for quickref
                quickRefHolder.html(
					'<form action="#">' +
					'<h2>API Quick Reference</h2>' +
					'<div><input type="text" id="quickRefInput" /></div>' +
					'</form>'
				);

                // build our quickref
                // FE change: var quickRef = new glow.widgets.AutoSuggest("#quickRefInput", "/glow/docs/" + quickRefVersion + "/allsymbols.json", {


                var quickRef = new glow.widgets.AutoSuggest("#quickRefInput", "/glow/docs/" + "1" + "/allsymbols.json", {
                    anim: "roll",
                    maxListLength: 12,
                    width: 285,
                    delim: ".",
                    formatItem: function(data) {
                        return '<div class="name">' + data.name + '</div><div class="memberOf">' + data.memberOf + '</div><div class="type">' + data.type + '</div>';
                    },
                    onItemSelect: function(event) {
                        window.location.href = "/glow/docs/" + quickRefVersion + "/api/" + event.selectedItem.href;
                    }
                });
                quickRef.overlay.content.attr("id", "quickRefResults");
            })

        })();

        // TOC script
        (function() {
            var tocNum = 0;

            createToc = function(selector) {
                tocNum++;

                var headings = $(selector).sort(),
					toc = glow.dom.create('<ol></ol>'),
					currentHeadingLevel,
					initialHeadingLevel,
					lastListItem,
					currentTree = [toc],
					currentList = toc;

                headings.each(function(i) {
                    var thisHeadingLevel = this.nodeName.slice(1, 2);
                    this.id = this.id || "tocHeading" + tocNum + "." + i;

                    if (currentHeadingLevel && thisHeadingLevel > currentHeadingLevel) {
                        if (thisHeadingLevel - currentHeadingLevel != 1) {
                            throw new Error("Heading structure is anti-semantic");
                        }
                        currentList = currentTree[currentTree.length] = glow.dom.create("<ol></ol>").appendTo(lastListItem);
                    } else if (currentHeadingLevel && thisHeadingLevel < currentHeadingLevel) {
                        if (thisHeadingLevel < initialHeadingLevel) {
                            throw new Error("Heading structure is anti-semantic");
                        }
                        currentTree = currentTree.slice(0, thisHeadingLevel - currentHeadingLevel);
                        currentList = currentTree[currentTree.length - 1];
                    }

                    lastListItem = glow.dom.create('<li><a href="#' + this.id + '">' + this.innerHTML + '</a></li>').appendTo(currentList);

                    if (!initialHeadingLevel) {
                        initialHeadingLevel = thisHeadingLevel;
                    }
                    currentHeadingLevel = thisHeadingLevel;
                })

                return toc;
            }
        })();
		
		// documentation version selector
		// FE: replaced versions = versionNums with versions = 1
		glow.ready(function() {
			var currentDocVersion = (/\/glow\/docs\/([^\/]+)\//.exec(window.location) || [,,])[1],
				// todo, get these from mason
				versions = 1,
				// links to versions numbers will be built in this string
				versionList = '<ol>',
				overlay,
				versionSpan = $("#pageHeading span.version");
			
			// if we're not on a documentation page, return
			if ( !currentDocVersion || !versionSpan[0] ) { return; }
			
			for (var i = 0, len = versions.length; i < len; i++) {
				versionList += '<li><a href="' + location.href.replace(currentDocVersion, versions[i]) + '">Version ' + versions[i] + '</a></li>';
			}
			
			versionList += '</ol>';
			
			// create our overlay
			overlay = new glow.widgets.Overlay( glow.dom.create(versionList), {
				autoPosition: false,
				id: 'versionContextual'
			});
			
			glow.events.addListener(document.documentElement, "click", function(e) {
				var clickedElm = $(e.source),
					spanOffset;
					
				if ( clickedElm[0] == versionSpan[0] && !overlay.isShown ) {
					spanOffset = versionSpan.offset();
					
					overlay.container
						.css( "top", spanOffset.top + versionSpan[0].offsetHeight )
						.css( "left", spanOffset.left - 2 );
						
					overlay.show();
				}
				else if ( !clickedElm.isWithin(overlay.container) ) {
					overlay.hide();
				}
			});			
			
		});
    }
});