/*
 * TODO:
 * fade out of menus
 * this should not be called navigation
 *
 * a  = Array
 * e  = Event
 * d  = Data object
 * f  = Flash
 * fn = Function
 * i  = Integer
 * s  = String
 * o  = Object (DOM object)
 * t  = Timed fn
 * x  = Ext object
 * $  = jQuery object
 */

var Aercoustics = function() {
    var iNavPad = 6;
    var delay   = 0.2;

    var xActive;
    var xNav;
    var xTier;
    var dFxConf = {useDisplay: true, duration: delay, concurrent: true};

    var fLogo     = false;
    var dSections = {'acoustics': 1,'noise': 1,'vibration': 1, 'home': 1}

    var xContent;
    var xLayout;
    var xPost;

    var init = function() {
        // here

        xContent = Ext.get('TzContent');
        xPost    = xContent.child('.post');

        xNav = Ext.get('TzNav');
        xNav.select('a').set({title: ''});
        Ext.fly('TzSubNav').select('a').set({title: ''});

        var xBread = Ext.get('TzBreadcrumbs');
        var iFloor = (xBread ? (xBread.getTop() - iNavPad) : -1);

        new Ext.ux.Menu(xNav, {
            direction:          'vertical'
          , transitionType:     'slide'
          , vAlign:             'middle'
          , floor:              iFloor
          , transitionDuration: 0.2
          , delay:              delay
        });

        xNav.select('> li').addClass('TzSchool');
        xNav.select('ul li').hover(Pad.on, Pad.un);

        PopupInit();

        Logo.init();

        var oFS = new FontSizer(Ext.get('TzFontSelect').setStyle('display', 'block').dom);

        // if (Ext.isMobile) { // todo
        xLayout  = new Ext.ux.FluidLayout(xContent, {constraint: Ext.select('#TzTheContent,div.TzPopupWrapper')});
        xLayout.checkLayout();
        xLayout.on('afterResize', checkPost);
        // }

        oFS.addCallback(xLayout.checkLayout);
        oFS.addCallback(function() {
            var xOpen = Ext.ux.PopupManager.getLastOpened();
            if (xOpen) {
                checkPopups(xOpen.el, xOpen);
            }
        });

        if (Ext.isIE) {
            IE.init();
        }
    }

    var IE = {
        init: function() {
            if (typeof console == 'undefined') { // Just incase we forget to remove all the console.log() calls
                console = function() { return { log: function(s) {  } } }();
            }

            if (Ext.isIE6) {
                IE.IE6();
            }

            if (Ext.isIE7) {
                IE.IE7();
            }
        }

      , IE6: function() {
            IE.IE7();

            Ext.select('.TzPopupGroup').each(function() {
                var xAnchor = this.select('a').item(0);
                var xPopup  = this.select('div.TzPopup').item(0);
    
                xPopup.setLeft(xAnchor.getWidth() + 10).setStyle('visibility', 'hidden');
            });
        }

      , IE7: function() {
            Ext.select('#TzBreadcrumbs li + li').insertHtml('afterBegin', '&nbsp;&gt; ');
            Ext.fly('TzPhoto').addClass('TzPeekaboo7');
        }
    }

    var Logo = {
        init: function() {
            if (!swfobject.hasFlashPlayerVersion('9.0.0')) {
                return;
            }

            var xLogo = Ext.get('TzLogo');
            Ext.fly('TzLogoWrapper').setStyle('background-image', 'url(' + xLogo.dom.src + ')');
            xLogo.setStyle('src', '');

            var sGhost = 'http://' + document.domain + '/';
            var sURI   = window.location.href.replace(sGhost, '');
            var sSect  = (sURI.indexOf('/') == -1 ? 'home' : sURI.split('/')[0]);
            var sFSect = (dSections[sSect] ? sSect : false);
            if (!sFSect) {
                return;
            }

            var att = {data: 'images/logo.swf', width: '169', height: '113'};
            var par = {flashvars: "homeURL=/&section=" + sFSect};
            var id  = 'TzLogo';

            fLogo = swfobject.createSWF(att, par, id);
        }
    }

    var PopupInit = function() {
        Ext.select('div.TzPopupGroup').each(function() { // Get all the HTMl popup groups
            oPop = Ext.ux.PopupManager.create({
                id:          Ext.id(this.child('div.TzPopup'))
              , closeButton: this.child('a.TzDoClose').removeClass('TzDoClose')
              , durationOut: 0.75
              , trigger:     this.child('a.TzDoHover').removeClass('TzDoHover')
            });

            /* Unit tests
            oPop.on('beforeOpen', function() { console.log('beforeOpen'); });
            oPop.on('afterOpen', function() { console.log('afterOpen'); });
            oPop.on('afterClose', function() { console.log('afterClose'); });
            oPop.on('beforeClose', function() { console.log('beforeClose'); });
            */

            oPop.on('startOpen', checkPopups);
            oPop.on('afterOpen', checkPopups);

            var xWrap     = this.child('div.TzPopupWrapper');
            var xArrow    = this.child('div.TzPopupArrow');
            var iHalfWrap = xWrap.getHeight() / 2;

            xArrow.setStyle('margin', 0);
            xWrap.setTop(0 - iHalfWrap + (xArrow.getHeight() / 2));
            oPop.el.setTop(0 - iHalfWrap).setStyle('padding-top', iHalfWrap + 'px'); 
        });
    }

    var checkPopups = function(e, oPop) {
        e = Ext.get(e);
        var xWrap = e.child('div.TzPopupWrapper');
        
        var iPostHeight = xWrap.getBottom() - xWrap.getTop() + e.getOffsetsTo(xContent)[1] + xContent.getScroll().top;

        if (iPostHeight < xContent.getHeight()) { // partially right logic . . . 
            iPostHeight = xContent.getHeight();
        }

        if (iPostHeight > xPost.getHeight()) {
            xPost.setHeight(iPostHeight);
        }
    }

    var checkPost = function() {
        if (xPost.getHeight() < xContent.getHeight()) {
            xPost.setHeight(xContent.getHeight());
        }
    }

    var stopEvents = function(e, t) {
        e.stopEvent();
    }

    var Nav = {
        position: function() {
            Ext.select('#TzActive,#TzActive > ul').setVisible(true);

            xActive.setDisplayed('block').setStyle('position', 'absolute').setY(xTier.getY() + 5);
            xActive.each(function() {
                var xThis = Ext.get(this);
                var xPar  = xThis.prev('li');
                if (!xPar) {
                    xPar = xTier;
                }

                xThis.setX(xPar.getX() + xPar.getWidth() + 15);
            });
            xActive.setDisplayed('none');

            return this;
        }
      , on: new Ext.util.DelayedTask(function() {
            xActive.fadeOut();
        })
      , off: new Ext.util.DelayedTask(function() {
            xActive.fadeIn(dFxConf);
        })
    }

    var Pad = {
        on: function(e, t) {
            var xThis = Ext.get(this).stopFx();
            var xPrev = xThis.prev('li');

            xThis.animate({paddingBottom: {to: iNavPad, from: 0, unit: 'px'}}, delay);

            if (xPrev) {
                xThis.parent('ul').animate({marginTop: {to: (0 - iNavPad), from: 0}}, delay);
                xThis.prev('li').animate({marginBottom: {to: iNavPad, from: 0}}, delay);
            }
        }
      , un: function() {
            var xThis = Ext.get(this);
            var xPrev = xThis.prev('li');

            xThis.animate({paddingBottom: {to: 0, from: iNavPad}}, delay);

            if (xPrev) {
                xThis.parent('ul').animate({marginTop: {to: 0, from: (0 - iNavPad)}}, delay);
                xThis.prev('li').animate({marginBottom: {to: 0, from: iNavPad}}, delay);
            }
        }
    }

    Ext.onReady(init);
    return {
        getLayout: function() {
            return xLayout;
        }
    }
}();



















/***** Ghost source below, need to reverse it for the popups ****/

/**
     * Slides the element while fading it out of view.  An anchor point can be optionally passed to set the 
     * ending point of the effect.
     * Usage:
     *


// default: slide the element downward while fading out
el.ghost();

// custom: slide the element out to the right with a 2-second duration
el.ghost('r', { duration: 2 });

// common config options shown with default values
el.ghost('b', {
    easing: 'easeOut',
    duration: .5,
    remove: false,
    useDisplay: false
});


     * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
     * @param {Object} options (optional) Object literal with any of the Fx config options
     * @return {Ext.Element} The Element
     */
/*
,
*/


/*********** REST OF INIT METHOD ----> Making nav items appear when not hovering **********
        Ext.select('a').each(function() {
            this.dom.onclick = function() { return false; };
        }).on('click', dynNav.load);
*/

//        Ext.fly('TzCopy').slideIn('l', {duration: 0.6, concurrent: true, callback: function() { Ext.fly('TzPhoto').fadeIn({duration: 0.75}); }});
//        Ext.select('#TzSubNav li > a').on('click', function() { Ext.fly(this).frame('C2CD23', 1, {duration: 0.5}); });

/*
        var xTmpActive = xNav.select('> li.current_page_ancestor .current_page_ancestor,#TzNav > li.current_page_ancestor .current_page_item');
        if (xTmpActive.getCount() > 0) {
            Ext.DomHelper.append(xNav, '<li id="TzActive"><ul></ul></li>');

            xTmpActive.each(function() {
                var oClone = this.dom.cloneNode(true);
                oClone.className = 'current_page_ancestor TzActiveClone';
                oClone.rel = this.dom.id;
                Ext.fly('TzActive').child('ul').dom.appendChild(oClone);
            });

            xActive   = Ext.select('.TzActiveClone').setStyle('width', '').on('mouseenter', stopEvents).on('mouseout', stopEvents);
            xTier     = xNav.child('li.current_page_ancestor');
            var sTier = xTier.child('a').dom.firstChild.nodeValue.toLowerCase();
            xActive.addClass('Tz' + sTier.substr(0, 1).toUpperCase() + sTier.substr(1));

//console.log(sTier.substr(0, 1).toUpperCase() + sTier.substr(1));
//console.log(xNav.select('> li.current_page_ancestor > a').item(0).dom.firstChild.nodeValue.toLowerCase());

            xNav.hover(function() { Nav.off.cancel(); Nav.on.delay(0); }, function() { Nav.on.cancel(); Nav.off.delay(delay*1000); });
            Nav.position().off.delay(0);
        }
*/



/************* DYNAMIC NAVIGATION methods *********
    var dynNav = {
        load: function() {
            Ext.Ajax.request({
                url:     TzXHRLoad.url
              , success: dynNav.success
              , failure: dynNav.failure
              , params:  {link: this.href}
            });
        }

      , success: function() {
//            Ext.fly('TzPhoto').fadeOut({duration: 0.75, callback: function() { Ext.fly('TzContent').slideOut('r', {duration: 0.6, remove: true}); }});
//            Ext.fly('TzPhoto').fadeOut({duration: 0.75, callback: function() { Ext.fly('TzCopy').slideOut('r', {duration: 0.6, callback: function() { Ext.fly('TzContent').switchOff({remove: true}); }})}});
        }

      , failure: function() {
            console.log(arguments);
        }
    }
*/
