/**
 * @author alexander.farkas
 */

jQuery.noConflict();
(function($){

    function callOnDomReady() {
        $("ul.tabs").tabs("div.panes > form");
        $(":range").rangeinput({progress:true});
        $('form.calculator').updateInfo();
        $('html').addClass('js-on'); // html class
        $('body').removeClass('js-off');
        //Zebra-Tables
        /* $('div.text tbody tr:nth-child(odd)').addClass('odd'); */

        addPrintLink();
        
        /* temporary add in to enable Unica external link tracking for LivePerson chat
        $('#lpButDivID-1310155001 a').addClass('external').attr('rel', 'external');
        $('#lpButDivID-1310155001 .lpStaticButtonTR a').attr('title', 'sales.liveperson.net | Live Chat'); */
        //	.data('linkEventData', { linkType: 'exit', link: 'chat now'});
        
        //$('div#extras div.youtube a.external,div#extras div.facebook a.external,div#extras div.twitter a.externa').data('linkEventData', { linkType: 'social'});
         
        // link tracking and external links
        $('a.external, a[rel~=external]').attr('target', '_blank');
        $('#home div#teaser-1 a').attr('rel', 'featured');
        
       /* $('a.external, a[rel~=external]').click(function() {
        	var $this = $(this);
        	if (typeof $this.data('linkEventData') != "undefined") {
		    	$.each($this.data('linkEventData'), function(key, value) {
		    		ntptAddPair(key, value);
		    	});
		    	if (!$this.data('linkEventData').link) {
		    		ntptAddPair('link', $this.attr('href'));
		    	}
        	}else{
        		ntptAddPair('linkType', 'exit');
        		ntptAddPair('link', $this.attr('href'));
        	}
            ntptAddPair('lk', '1');
            ntptEventTag('ev=link');
        });
        $('a.download').click(function() {
            ntptEventTag('ev=download&downloadFormat='+$(this).attr('type')+'&link='+$(this).attr('href'));  
        });
       
        $('#home div#teaser-1 a').click(function() {
        	ntptEventTag('ev=link&linkType=featured link&linkLocation=ways to join&link='+$(this).attr('href'));  
        });
        $('.social-b li a').click(function() {
            ntptEventTag('ev=share&shareType='+$(this).parent().attr('class')+'&share='+document.title);  
        }); */
        
        //wait for the swfobject DOM-Ready, so we can return a proper reference to flash object
        swfobject.addDomLoadEvent(function(){
            $('div.flash').embedSWF({
                version: "10.0",
                expressInstall: contextPath+"/dms/navy/flash/expressInstall.swf"
            });
        });
        
        $('#nav-global.megamenu').simpleMenu({
            generateSkip: true,
            skipStructure: '<a class="menu-skip" href="#" title="Untermenü {from} überspringen">direkt zu Menü {to} springen</a>',
            skipEndStructure: '<a class="menu-skip" href="#" title="ans Ende vom Menu springen">Untermenü {from} überspringen</a>',
            init: function(e, ui){
                
            },
            //showHiddenOnFocus: true,
            show: function(e, ui){
                var menuBox = $('> div.menu-box', ui.menu)
                    .css({
                        top: ui.menu.outerHeight({margin: true}) * -1
                    });
                
                ui.menu.addClass('menu-open');
                menuBox.stop(true, true)
                    .animate({
                        top: 0
                    });
            },
            hide: function(e, ui){
                var menuBox = $('> div.menu-box', ui.menu);
                menuBox.animate(
                    {
                        top: ui.menu.outerHeight({margin: true}) * -1
                    },
                    {complete: function(){
                        ui.menu.removeClass('menu-open');
                        menuBox.css({top: 0});
                    }}
                );
                
            }
        });
        
        // add a value to the search boxes
        var searchValue = "Search NavyReserve.com";
        $('form.search-form input').each(function() {
            // set value initially if none is specified
            if(this.value == '') {
                this.value = searchValue;
            } else {
                return;
            };
        });
        
        // var searchStart = false;
        // remove values on focus
        $('form.search-form input').focus(function() {
            $(this).parents(".search-box").addClass("focusField");
            if( this.value == searchValue ) this.value='';
        });
        
        // place values back on blur
        $('form.search-form input').blur(function() {
            $(this).parents(".search-box").removeClass("focusField");
            if(this.value==searchValue || this.value=='') this.value=searchValue;
        });
        
        // initialize form validation 
        $('form.validity').validity();

        //initialize flowplayer
        window.contextPath = window.contextPath ||
            '';
        
        $("div.audio a").each(function() {
            $(this).flowplayer(contextPath + "/.resources/navy-templating-kit/swf/flowplayer.commercial-3.2.5.swf", {
                plugins: { 
                    controls: {
                        autoHide:"never",
                        fullscreen: false, 
                        height: 24,
                        tooltips: null
                    },
                    captions: {
                        button: false
                    } 
                }, 
                clip: { 
                    autoPlay: false,
                    // custom property
            		title: $(this).attr('title').replace(/\'/g,"&#8217;"),
            		// FIXME: This should really be onStart, 
            		// but there is a bug in the audio plugin that causes onStart not to fire.
            		// We should change this to onStart once we update the audio plugin to 3.2.4
                    onBegin: function(clip) {
                        ntptEventTag('ev=audio&audioAction=start' 
                        	+ '&audioTitle=' + $(this)[0].getClip().title
                        	+ '&audio=' + $(this)[0].getClip().url);        
                    },
                    onFinish: function() {
                         ntptEventTag('ev=audio&audioAction=finish' 
                             + '&audioTitle=' + $(this)[0].getClip().title
                             + '&audio=' + $(this)[0].getClip().url);
                    }
                }
            });
        });
            
        $('div.video').each(function() {
            $(this).flowplayer({
               src: contextPath + "/.resources/navy-templating-kit/swf/flowplayer.commercial-3.2.5.swf", 
               version: [10,0],
               expressInstall: "/dms/navy/flash/expressInstall.swf"
               },{
                   key: '#$3bf2498ea5ccccc1d69',
                   cachebusting: true,
                   onBeforeClick: function() {
                        var isStage = $(this.getParent()).parents('#stage').length == 1 ? true : false;
                        var isMasthead = $(this.getParent()).parents('#masthead').length == 1 ? true : false;
                        var isRack = $(this.getParent()).parents('.rack').length == 1 ? true : false;
                            
                    /* if (isStage && isRack) {
                        // -- if video player is in #stage element

                        // unload previously loaded player 
                        this.unload();
                                
                        // get wrapper element as jQuery object 
                        var wrap = $(this.getParent());
                                
                        if (isRack) {
                            // -- if video player is in #stage element and paging teaser
                                    
                            // start growing animation
                            $(".pagination").fadeOut();
                            wrap.find("img").fadeOut();
                            wrap.parents('.rack-teaser').find('.video-teaser').hide();
                            wrap.parents(".rack").animate({ height:529 }, "fast", function() {
                                wrap.parents(".rack-teaser").animate({ height:529 }, "fast");
                                wrap.animate({ height:529 }, "fast", function() { 
                                    // when animation finishes we will load our player 
                                    $f(this).load(); 
                                });
                            });
                        } else {
                            // -- if video player is in #stage element by itself
                            wrap.find("img").fadeOut();
                            $f(this).load();
                            return false;
                        };
                    } else if (isMasthead) {
                        // -- if video player is in #masthead element
                        $(this.getParent()).find("img").fadeOut();
                                
                        if (isRack) {
                            // -- if video player is in #masthead element and paging teaser
                            $(".pagination").fadeOut();
                        };
                    }; */
                },
                onUnload: function() { 
                    var isStage = $(this.getParent()).parents('#stage').length == 1 ? true : false;
                    var isMasthead = $(this.getParent()).parents('#masthead').length == 1 ? true : false;
                    var isRack = $(this.getParent()).parents('.rack').length == 1 ? true : false;
                    
                    // get wrapper element as jQuery object 
                    var wrap = $(this.getParent());
                    wrap.find("img").fadeIn();
                            
                    // start growing animation
                    /* if (isStage) {
                        if (isRack) {
                            wrap.animate({ height:400 }, "slow");
                            wrap.parents(".rack-teaser").animate({ height:400 }, "slow");
                            wrap.parents(".rack").animate({ height:400 }, "slow", function() {
                                $(".pagination").fadeIn();
                                $(".video-teaser", this).fadeIn();
                                $(".video-teaser h2", this).css({bottom: "3.5em"});
                                $(".video-teaser p", this).css({bottom: "28px"});
                            });
                        }
                    } else if (isMasthead) {
                        if (isRack) {
                            $(".pagination").fadeIn();
                        };
                    } */
                },
                clip: { 
                    url: $(this).find('a').attr('href'),
                    captionUrl: $(this).find('a').attr('href').replace('/videos','/xml').replace('.mp4','.xml'),
                    scaling: 'fit',
                //    accelerated: true,
                    // custom property
            		title: $(this).find('a').attr('title').replace(/\'/g,"&#8217;"),
                    autoPlay: true,
                    // on last second, fade out screen
                    onLastSecond: function() {
                        this.getScreen().animate({opacity: 0.5}, 3000);
                    },
                            
                    // on movie pause
                    onPause: function() {
                        var wrap = $(this.getParent());
                        var isStage = $(this.getParent()).parents('#stage').length == 1 ? true : false;
                        var isMasthead = $(this.getParent()).parents('#masthead').length == 1 ? true : false;
                        var isRack = $(this.getParent()).parents('.rack').length == 1 ? true : false;
                                
                        /* if (isStage && isRack) {
                            wrap.parents(".rack-teaser").animate({ height:372 }, "fast");
                            
                            wrap.parents(".rack").animate({ height:400 }, "fast", function() {
                                $(".pagination").fadeIn();
                                $(this).find("object").animate({ marginTop: "-65px" }, "fast");
                                $(".video-teaser", this).fadeIn();
                                $(".video-teaser h2", this).css({bottom: "2.5em"});
                                $(".video-teaser p", this).css({bottom: "0px"});
                            });
                        } else if (isMasthead && isRack) {
                            $(".pagination").fadeIn();
                            this.getControls().hide();
                        }; */
                    },

                    // on movie resume
                    onResume: function() {
                        var isStage = $(this.getParent()).parents('#stage').length == 1 ? true : false;
                        var isMasthead = $(this.getParent()).parents('#masthead').length == 1 ? true : false;
                        var isRack = $(this.getParent()).parents('.rack').length == 1 ? true : false;
                                
                        /* if (isStage && isRack) {
                            var wrap = $(this.getParent());
                            $(".pagination").fadeOut();
                            wrap.parents(".rack").animate({ height:529 }, "fast");
                            wrap.parents('.rack-teaser').find('.video-teaser').hide();
                            wrap.parents(".rack-teaser").animate({ height:529 }, "fast", function() {
                                $(this).find("object").animate({ marginTop: "0px" }, "fast");
                            });
                        } else if (isMasthead && isRack) {
                            $(".pagination").fadeOut();
                            this.getControls().show();
                        }; */
                    },
        
                    // if screen is hidden, show it upon startup
                    onStart: function(clip) {
                        this.getScreen().css({opacity: 1});
                        ntptEventTag('ev=video&videoAction=start' 
                            + '&videoTitle=' + $(this)[0].getClip().title
                            + '&video=' + $(this)[0].getClip().url);                       
                    },
        
                    // when movie is done, unload movie
                    onFinish: function() {
                        if (this.isFullscreen() && jQuery.browser.msie) {
                        	this.toggleFullscreen();
                            document.body.focus();
                            unload = this.unload;
                            setTimeout(function(){eval("unload()")},50);
                        } else {
                            this.unload();
                            document.body.focus();
                        }
                        ntptEventTag('ev=video&videoAction=finish' 
                            + '&videoTitle=' + $(this)[0].getClip().title
                            + '&video=' + $(this)[0].getClip().url);
                       
                    },
                            
                    // when movie is stopped, unload movie
                    onStop: function() {
                        if (this.isFullscreen() && (jQuery.browser.safari || jQuery.browser.msie)) {
                            this.toggleFullscreen();
                            document.body.focus();
                            unload = this.unload;
                            setTimeout(function(){eval("unload()")},50);

                        } else {
                            this.unload();
                            document.body.focus();
                        }
                    }
                } ,
                plugins: {
                	viral: {
            			// load the viral videos plugin
            			url:  contextPath + "/.resources/navy-templating-kit/swf/flowplayer.viralvideos-3.2.3.swf",
            			
            			// define a video title used in sharing
            			embed: false,
            			email:$(this).hasClass("email") ?  {
            				script: ($.url().attr("host").indexOf(".com")!=-1)? "https://"+$.url().attr("host")+"/ws/emailService/send" : "/ws/emailService/send"
                    		} :false,
            			share: $(this).hasClass("share") ? { 	
            				// use a custom URL when sharing (by default the embedding page's URL is used)
							shareUrl: window.location.href.split('#')[0].split('?')[0].replace(".html","") + "/share-video/" +$(this).attr("id"),
							myspace: false,
							livespaces: false,
							orkut: false,
							stumbleupon: false,
							bebo: false,
							onBeforeShare: "trackFlashEvent"
            			} : false
            		}
                } 
            }).hover(
                function() { 
                    // find span.info element inside the player container and show it 
                    // $("span.info", this).fadeTo("slow", 0.7);
                    /* if ($.support.opacity) {
                        $("span.play-video", this).fadeTo("slow", 1); 
                    } */
                }, 
                function() { 
                    // when mouse is removed - hide the info 
                    // $("span.info", this).fadeTo("slow", 0);
                    /* if ($.support.opacity) {
                        $("span.play-video", this).fadeTo("slow", 0.5);
                    } */
                }
            );  
        
            // initially all info elements are hidden 
            // $("span.info", this).css("opacity", 0);
            /* if ($.support.opacity) {
                $("span.play-video", this).css("opacity", 0.5);
            } */
        });

        //different tabs
        createTabs();
        faqToc();

        //Teaser-Switchers
        
        $('div.teaser-wrapper:not(.tw-paging,.tw-slider)').each(function() {
            $('div.pager', this).append('<div class="prev"><span /></div><div class="next"><span /></div>');
            $(this).scroller();
        });

        pagingTeaserSwitcher();
        slidingTeaserSwitcher();

        createShowBox();
        
        slidingTabs();
        
        addLandmarks();

        $.socialbookmark.init('li.social-b a');

        createYoutubeList();
        
        /*    Need to add jquery-jflickrFeed.js
            $('div.flickr-box').jflickrfeed({
                flickrWrapper: 'div.flickr-photos',
                maxItemCount: 6,
                wrapperTmpl: '<ul><%=items%></ul>',
                template: '<li><a href="<%=imglink%>"><img src="<%=imgsrc%>" alt="<%=imgtitle%>" title="<%=imgtitle%>" /></a></li>'
            }); */
        
        
        /* Add last-child class to last list item in nav-box, for browsers that don't support
           :last-child pseudo class (IE, I'm looking at you).
        */
        $('#nav-box>ul>li:last-child, #nav-meta>ul>li:last-child,.links>ul>li:last-child').addClass('last-child');
        
        /* NOSC Locations */
        $.fn.exists = function () {
            return $(this).length !== 0;
        }    
        if ($('#nosc-map').exists()) {    
            reserveCenters.loadMapScript('reserveCenters.loadMap');
            $('form#nosc-sort #state').change(function() { 
        		reserveCenters.filterByState($(this).val());
        	});
        }
        
        // $.fn.netinsight.defaults.debug = true;
		// Initialize NetInsight Plugin for Event Tracking
        $('body').netinsight({ mapClassNamesToRels:true });

        // add unica tracking for live chat with Monitor tag
      	if($('#lpchat').length>0){
      	  var timer = setInterval(function(){
      	  	  if($('#lpchat a').length>0){
      	  		   	$('#lpchat a').addClass('external').attr('rel', 'external');
       	  			$('#lpchat a').attr('title', 'sales.liveperson.net | Live Chat');
     	  	     	$('#lpchat').netinsight({ mapClassNamesToRels:true });
       	   		  	clearInterval(timer);
         		 }
      		},500);
         }	
    }
    
    function createYoutubeList() {
        var ytDataCFG = {
            complete: function(data, status) {
                if (status == 'success') {
                    startYTPlayer(data.DOMFeed.parent());
                }
            },
            youTubeParams: {
                'max-results': 3 //youtube feed generator: http://gdata.youtube.com/demo/index.html
            },
            itemTmpl: 
                '<li>' +
                    '<a class="youtube-video" href="<%=link%>">' +
                        '<img src="<%=thumbnail.url%>" alt="" />' +
                    '</a>' +
                    '<h3><a class="youtube-video" href="<%=link%>"><%=title%></a></h3>' +
                    '<p><%=description%></p>' +
                '</li>'
        },
        carouselExtension = {
            feedWrapperTmpl: '<div class="teaser-wrapper tw-switcher"><div class="pager"></div><div class="rack"><div class="rack-design"><%=items%></div></div></div>',
            youTubeParams: {
                'max-results': 20 //youtube feed generator: http://gdata.youtube.com/demo/index.html
            },
            itemTmpl: 
                '<div class="rack-teaser">' +
                    '<a class="youtube-video" href="<%=link%>">' +
                        '<img src="<%=thumbnail.url%>" alt="" />' +
                    '</a>' +
                    '<h2><a class="youtube-video" href="<%=link%>"><%=title%></a></h2>' +
                    '<p><%=description%></p>' +
                '</div>'
        };
        function startYTPlayer(jElm){
            swfobject.addDomLoadEvent(function() {
                $('div.youtube-player-wrapper', jElm).html('<div class="youtube-player"></div>');
                jElm.youtubeList(
                    {player: 'div.youtube-player'}
                );
                if (jElm.is('.carousel')) {
                    $('div.pager', jElm).html('<div class="prev"><span/></div><div class="next"><span class="show"/></div>');
                    $('div.teaser-wrapper', jElm).scroller();
                }
            });
        }
        
        $('div.youtube-widget:not(.youtube-feed, .carousel)').each(function() {
            startYTPlayer($(this));
        });
        
        $('a.youtube-feed').each(function() {
            var jElm = $(this);
            jElm.youtubeData( (jElm.parent().is('.carousel')) ? $.extend({}, ytDataCFG, carouselExtension) : ytDataCFG);
        });
    }
    
    function createShowBox(){
        var showboxCFG = {
            setInitialContent: {
                'showbox-title': $('h1').html(), 
                prev: 'previous',
                next: 'next',
                'close-button': 'close',
                'play-pause': 'play'
            },
            getTextContent: function(opener, content, ui) {
                // Um Text aus einer dl-Structure zu holen (Magnolia-Style)    
                var dl  = opener.closest('dl'), //hole das nächst höhere dl
                    dds = $('dd', dl), // hole die dd
                    img = $('img', dl), // hole das img 
                    extraContent = ''
                ;
                    
                //content objekt dient zur befüllung der lightbox mit weiterem content
                //die eigenschaftsnamen stimmen mit den Klassen-Namen überein
                    
                //content['multimedia-box'] ist bereits mit dem grossen Bild vorbelegt
                //und wird nun mit dem alt Attribut des kleinen Bildes versehen
                content['multimedia-box'].attr('alt', img.attr('alt'));
                    
                content['text-content'] = ''; // String in dem wir unser gesamt content zusammefügen
                    
                dds.each(function() {
                    var dd  = $(this),
                        html = dd.html()
                    ;
                    if (dd.is('.caption')) {
                        content['text-content'] += '<h2 class="caption">'+ html +'</h2>';
                    } else if (dd.is('.longdesc')) {
                        content['text-content'] += '<p class="longdesc">'+ html +'</p>';
                    } else if (!dd.is('.zoom')) {
                        extraContent += '<li class="'+ this.className +'">'+ html +'</li>';
                    }
                });
                    
                if (extraContent) {
                    content['text-content'] += '<ul class="sb-extra">'+ extraContent +'</ul>';
                }
            },
            showContentAnim: function(ui, img, e, extras) {
                var contentBox = $('div.content-box', ui.element);
                contentBox.queue(function() {
                    var duration = 300,
                        width = img[0].width, 
                        height
                    ;
                            
                    ui.element.css({height: ui.element.height()});
                    ui.fillContent();
                    width = ui.calcWidth(img, width);
                            
                    contentBox.css({width: width}).animate(
                        {opacity: 1}, 
                        {duration: duration}
                    );
                                
                    ui.element.animate(
                        {
                            height: contentBox.outerHeight({margin: true}) + $('div.showbox-head', ui.element).outerHeight({margin: true})
                        }, 
                        {
                            duration: duration,
                            complete: function() {
                                ui.element.css({height: ''});
                            }
                        }
                    );
                            
                    contentBox.dequeue();
                });
            }
        };
        
        $('div.tw-images').each(function() {
            $('a[rel=showbox]', this).addClass('showboxed').showbox(
                $.extend({}, 
                    showboxCFG, 
                    {
                        setInitialContent: {
                            'showbox-title': $(':header', this).html(), 
                            prev: 'previous',
                            next: 'next',
                            'close-button': 'close',
                            'play-pause': 'play'
                        }
                    }
                )
            )
        });
        
        $('a[rel=showbox]:not(.showboxed)').showbox(showboxCFG);
    }

    function addLandmarks() {
        var landmarks = {
            navigation: '#nav-global, #nav, #breadcrumb',
            search: '#search-box',
            article: 'div.text, div.teaser, div.opener, #comments li',
            complementary: '#extras',
            banner: '#branding',
            main: '#main',
            contentinfo: 'div.text-data, #site-info'
        };
        
        $.each(landmarks, function(landmark, sel) {
            $(sel).attr({role: landmark});
        });
    }

    function slidingTabs() {
        $.fn.mySlide = function(fn) { 
            fn = fn || function() {};
            return this.animate({
                height: 'toggle',
                opacity: 'toggle'
            }, {
                duration: 500,
                complete: fn,
                deque: true
            });
        };
        
        $('ol.superpromos-toc').each(function() {
            $(this).bind('tabtreecollapse', function(e, ui) {
                ui.panel.stop(true, true).animate(
                    {
                        height: 'hide',
                        opacity: 0
                    }, 
                    {
                        duration: 500
                    }
                );
            }).bind('tabtreeexpand', function(e, ui) {
                ui.panel.stop(true, true).animate(
                    {
                        height: 'show',
                        opacity: 1
                    }, 
                    {
                        duration: 500
                    }
                );
            }).tabtree({
                activeButtonClass: 'on', 
                selectEvents: 'mouseenter focus',
                handleDisplay: 'initial'
            }).find('a').bind('click', function(e) {
                if (e.pageX !== 0 && e.pageY !== 0) {
                    var url = $($(this).attr('href')).find('a:first').attr('href');
                    if (url) {
                        location = url;
                    }
                }
            });
        });
    }

    function pagingTeaserSwitcher(){
        function myPag(status) {
            if (status == 'inactive') {
                $('a',this).animate({opacity: 0.5},{duration: 500});
            } else {
                $('a',this).animate({opacity: 1},{duration: 500});
            }
        }
        function myLink(status){
            if(status == 'show'){
                this.animate({opacity: 1},{duration: 500});
            } else {
                this.animate({opacity: 0},{duration: 500});
            }
        }
        $('div.teaser-wrapper.tw-paging').scroller({
            pagination: 'div.pagination',
            paginationFn: myPag,
            linkFn: myLink,
            paginationTitleFrom: 'h2',
            paginationAtoms: '<li class="pa-$number" title="$title"><a href="#">$number</a></li>'
        });
    }

    function slidingTeaserSwitcher(){
        $('div.teaser-wrapper.tw-slider').each(function() {
            var jElm = $(this), 
                slider = $('div.slider', this).css({display: 'block'}).wrap('<div class="slider-bar" />');
                
            $('div.slider-bar', this).append('<span class="prev" /> <span class="next" />');
                
            function slideSliderCall(e, o, ui) {
                ui = ui ||
                    o;
                var val = (ui && isFinite(ui.value))? ui.value : (o) ? o.value : false;
                jElm.scroller('moveTo', val + '%', false);
            }
                
            slider.slider({maxValue: 100}).bind('slide', slideSliderCall);
            jElm.scroller({
                prevLink: 'div.slider-bar span.prev',
                nextLink: 'div.slider-bar span.next'
            }).bind('uiscrollerslide', function(e, d){
                slider.slider('value', d.percentPos);
            });
        });
    }


    function addPrintLink() {
        function print() {
            window.print();
            return false;
        }

        $('<li class="print"><a href="#">Print</a></li>').prependTo('ul#text-features').find('a').click(print);
    }

    function faqToc() {
        var hash         = location.hash,
            tabWidgets    = $('div.super-list'),
            tabs         = $('h3 a', tabWidgets)
        ;

        if (hash) {
            tabs.filter('[href='+hash+']').addClass('on');
        }

        tabWidgets.bind('tabtreecollapse', function(e, ui) {
            ui.panel.stop(true, true).slideParentUp();
        }).bind('tabtreeexpand', function(e, ui) {
            ui.panel.stop(true, true).slideParentDown();
        }).tabtree({
            buttonSel: 'h3 a',
            activeButtonClass: 'on',
            toggleButton: true,
            multiSelectable: true, 
            handleDisplay: 'initial'
        });
    }

    $.fn.tabChangeAddon = function() {
        this.bind('tabtreecollapse', function(e, ui) {
            ui.button.parent().removeClass('on');
        }).bind('tabtreeexpand', function(e, ui) {
            ui.button.parent().addClass('on');
        });

        $('a.on', this).parent().addClass('on');
        return this;
    };

    function createTabs(){
        $('ol.text-box-toc, ol.toc-box-toc').each(function() {
            $(this).tabtree({
                activeButtonClass: 'on'
            }).tabChangeAddon();
        });
    }


    $('html').addClass('js-on'); // html class

    $.extend($.ui.scroller.prototype.options, {
        //Elements Classes
        atoms: 'div.rack-teaser',
        prevLink: 'div.prev span',
        nextLink: 'div.next span'
    });


    $(callOnDomReady);
})(jQuery);
