$(function() {
    tt_initScroll(true) 
    tt_initMenu();
    
    window.onpopstate = function(stackstate) {  
        if (stackstate.state == 'nofly') {
//            alert(window.location.href);
//            alert(document.location);            
            window.location.href = document.location;
        }
    };  
    
    setTimeout("tt_flyIn()", 1000);    
});    


function tt_info(arg1, arg2)
{
return;
    if (typeof arg2 == 'undefined')
        console.info(arg1);
    else
        console.info(arg1, arg2);    
}

function tt_info2(arg1, arg2)
{
    if (typeof arg2 == 'undefined')
        console.info(arg1);
    else
        console.info(arg1, arg2);    
}


// convert px string to int, like '123px' to 123
function tt_px2int(px) 
{ 
    return parseInt(px.replace(/px/,'')); 
}


// set current <li> item inside an <ul>
function tt_setItemToCurrent(item) 
{
    $(item).parents('ul:first').find('li.current').removeClass('current');
    $(item).addClass('current');
}


// register menu element as 'visited'
function tt_isVisited(url, yesno) 
{
    if (typeof(this.visitedUrls) == 'undefined')
        this.visitedUrls = {};                
    if (typeof(yesno) == 'undefined')
        return typeof(this.visitedUrls[url]) != 'undefined';                    
    this.visitedUrls[url] = 1;                    
    //tt_info(this.visitedUrls);
}    


// this line is a tiny jquery plugin that adds a function $(...).reverse()
jQuery.fn.reverse = [].reverse;




// =============================================================================
//     the logo "fly in" 
// =============================================================================

function tt_flyIn()
{
    var nofly = document.location.href.match(/\?nofly/);
    if (nofly || document.referrer.match(/^http:\/\/(www[.])?(foan-architekten|foan-architects)[.](de|com)/)) {
        $("#pop-background").remove();
        $("#pop-logo-foan").remove();
        $("#pop-logo-architects").remove();  
        $("#pop-logo-forynski-darmawan-architekten").remove();
        $("#pop-logo-language").remove();           
        $("body").css({'overflow' : 'auto'});
        return;
    }

        if (typeof history.pushState != 'undefined') {
            history.pushState('nofly', '', document.location.href+'?nofly');                
        }
        
        var logo         = $("#img-logo").get(0);
        var foanX        = ttPageX(logo);
        var foanY        = ttPageY(logo);
        var architecsX   = foanX + 120; // x beetween FOAN and ARCHITECS
        var darmawanY    = foanY; // y beetween FOAN and DARMAWAN
        var screenWidth  = ttViewportWidth();
        var screenHeight = ttViewportHeight();

        $("#pop-logo-architects").css({left:screenWidth+"px"}).animate({opacity:1, left:architecsX+"px"},  2000);
        $("#pop-logo-forynski-darmawan-architekten").css({top:screenHeight+"px",left:foanX+"px"}).animate({opacity:1, top:50+"px"},  2000);
        $("#pop-logo-language").css({top:screenHeight+"px",left:810+foanX+"px"}).animate({opacity:1, top:526+"px"},  2000);
        $("#pop-logo-foan").animate({opacity:1, left:foanX+"px"},  2000, "swing", function(){
            $("#pop-logo-architects, #pop-logo-forynski-darmawan-architekten, #pop-logo-foan, #pop-logo-language").click(function () {
                $("#pop-background").animate({opacity:0}, 1000, function(){
                    $(this).remove();
                });
                $("#pop-logo-foan").animate({opacity: 0},  1000, function(){
                    $(this).remove();
                });
                $("#pop-logo-architects").animate({opacity: 0}, 1000, function(){
                    $("body").css({'overflow' : 'auto'});
                    $(this).remove();
                });
                $("#pop-logo-language").animate({opacity: 0},  1000, function(){
                    $(this).remove();
                });
                $("#pop-logo-forynski-darmawan-architekten").animate({opacity: 0}, 1000, function(){
                    $(this).remove();
                });
            });
   });
};



// =============================================================================
//     serial scroll and local scroll
// =============================================================================

function tt_initScroll(isPageLoad) 
{
    // --- vertical scroll in content ------------------------------------------
    
    $('#panecontent').jScrollPane({scrollbarWidth:10});  
    $('#panecontent_half_left').jScrollPane({scrollbarWidth:10});
    $('#panecontent_half_right').jScrollPane({scrollbarWidth:10});  
    $('#panecontent_architektur').jScrollPane({scrollbarWidth:10});
    $('#panecontent_chronologie').jScrollPane({scrollbarWidth:10});
    $('#panecontent_typologie').jScrollPane({scrollbarWidth:10});
    $('#panecontent_status').jScrollPane({scrollbarWidth:10});
    $('#panecontent-interior-design').jScrollPane({scrollbarWidth:10});
    $('#panecontent-leistungskatalog-interior-design').jScrollPane({scrollbarWidth:10});
    
    // --- drag in portfolio ------------------------------------------
        $("#draggable").draggable({ axis: 'x' });

    // --- horizontal scroll band ----------------------------------------------
    
    var $panels    = $('#slider #element-scroll > div');
    var $container = $('#slider #element-scroll');
    tt_info($panels);
    
    // float the panels left (use position relative as an IE fix to ensure overflow is hidden)
    $panels.css({'float' : 'left', 'position' : 'relative' }); 
  
    // calculate a new width for the container (so it holds all panels)
    $container.css('width', $panels[0].offsetWidth * $panels.length);

    // get scroll object (and set overflow hidden to remove the default scrollbars)
    var $scroll = $('#slider .scroll');//.css('overflow', 'hidden')

    // apply our left + right buttons
    $scroll
        .before('<img class="scrollButtons left" src="/res/img/icon/scroll_left.png" alt="" />')
        .after('<img class="scrollButtons right" src="/res/img/icon/scroll_right.png" alt="" />');

    // offset is used to move to *exactly* the right place, since we use padding, we need to subtract 
    // the amount of padding to the offset. Try removing this to get a good idea of the effect
    var offset = parseInt($container.css('paddingTop') || 0) * -1;

    var scrollOptions = 
    {
        target:     $scroll,          // the element that has the overflow
        items:      $panels,          // can be a selector which will be relative to the target
        navigation: '.navigation a:not(.download)',
        prev:       'img.left',       // these selectors are NOT relative to document, i.e. make sure they're unique
        next:       'img.right',
        axis:       'x',              // allow the scroll to run in horizontal directions
        offset:     offset,
        duration:   500,              // duration of the sliding effect
        easing:     'swing'           // easing - can be used with the easing plugin: http://gsgd.co.uk/sandbox/jquery/easing/
    };

    // serialScroll provides "scroll left" and "scroll right" (on click left or right aside the content "band")
    $('#slider').serialScroll(scrollOptions);
    
    // now apply localScroll to hook any other arbitrary links to trigger the effect
    $.localScroll(scrollOptions);

    // if the URL has an anchor, move to position with minimal duration to avoid scroll in the very first page load. 
    if (isPageLoad) {
        $.localScroll.hash($.extend( {}, scrollOptions, {duration:1} ));
    }
    
    // --- track visited links ---
    // add class 'visited' to each visited <a> in right menu and in "1 2 3 4" navigation
    $('#nav_project a, ul.navigation a').each(function(i) {
        var $this = $(this);
        var href  = $this.attr('href');        
        if (tt_isVisited(href) && !$this.hasClass('visited'))
            $this.addClass('visited');
    });
    
    // --- bind click events to lower right "1 2 3 4" navigation ---
    $("ul.navigation li").click(function() 
    {
        tt_setItemToCurrent(this);
        var $a = $(this).find('a');
        if ($a.attr('href')) 
            tt_isVisited($a.attr('href'), 1);
        if (!$a.hasClass('visited')) 
            $a.addClass('visited');
    });                        
};




// =============================================================================
//     the elastic foan menu 
// =============================================================================

var tt_runningAnimations = 0;     

function tt_initMenu()
{
    var settings = 
    {
        'left_menu'   : { 'y_top': 62, 'y_offset': 17 },    
        'middle_menu' : {},
        'right_menu'  : { 'y_top': 30, 'y_offset': 15, 'y_bottom': 187 }
    };
    
    // -------------------------------------------------------------------------
    //    menu selection change callbacks
    // -------------------------------------------------------------------------    
    
    function onNavMainChanged()
    {
        var currentItem = $('#nav_main li.current').get(0);
        tt_info('onNavMainChanged', currentItem);

        if (currentItem)
        {
            if (typeof jsnav[currentItem.id] != 'undefined') 
            {
                $('#nav_sub').animate({ opacity:0 }, 200, "easeInOutQuad", function() {
                    $(this).html(jsnav[currentItem.id]).animate({ opacity:1 }, 300);
                    onNavSubChanged();
                });
            }
            else {
                switchContent(currentItem);                        
            }
        }
    }
    

    function onNavSubChanged()
    {
        var currentItem = $('#nav_sub li.current').get(0);    
        tt_info('onNavSubChanged', currentItem);
        
        if (currentItem)
        {
            if (typeof jsnav[currentItem.id] != 'undefined') 
            {
                $('#nav_project').animate({ opacity:0 }, 200, "easeInOutQuad", function() {
                    $(this).css({right:"-200px"}).html(jsnav[currentItem.id]).animate({ right:"0px", opacity:1 }, 300, function() {
                        onNavProjectChanged();
                    });                        
                });
            }
            else {
                switchContent(currentItem);                        
            }
        }
    }


    function onNavProjectChanged()
    {
        tt_info('onNavProjectChanged');
        switchContent();                        
    }

    
    function switchContent()
    {
        tt_info('SWITCHCONTENT...');                    
        bindMenuItemEvents();                
        
        var currentMenuItem = null;
        if (!currentMenuItem) currentMenuItem = $('#nav_project li.current').get(0);            
        if (!currentMenuItem) currentMenuItem = $('#nav_sub li.current').get(0);            
        if (!currentMenuItem) currentMenuItem = $('#nav_main li.current').get(0);            

        if (currentMenuItem)
        {
            var menuItemId = currentMenuItem.id.replace(/^js-menu-/, '');
            var href       = $(currentMenuItem).find('a').attr('href');
            var anchor     = href.indexOf('#') > 0 ? href.replace(/^.*#/, '') : '';                            
            var anchorElem = anchor ? document.getElementById(anchor) : null;

            // try HTML5 history.pushState
            if (typeof history.pushState != 'undefined') {
                var hrefWithoutAnchor = href.indexOf('#') > 0 ? href.replace(/#.*$/, '') : href;                                            
                history.pushState('nofly', '', hrefWithoutAnchor+'?nofly');                
            }
                
            if (anchorElem) 
            {
                tt_info('...SWITCHCONTENT [TO ANCHOR ' + anchor + ']', href);                
                $('#slider .scroll').scrollTo(anchorElem, {duration:500});  // do scroll
            }
            else 
            {
                tt_info('...SWITCHCONTENT [LOAD]', href);                    
                var hrefWithoutAnchor = href.replace(/#.*$/, '');                                
                var contentUrl = hrefWithoutAnchor+'?content'; // +'#'+anchor;                
                tt_isVisited(href, 1);
                $("#js-maincontent").css({opacity:0}).load(contentUrl, {}, function() {
                    tt_initScroll(false);
                    $("#js-maincontent").animate({opacity:1}, 200);
                });
            }
        }
    }
    
    
    // -------------------------------------------------------------------------
    //    menu item definition 
    // -------------------------------------------------------------------------    
    
    function $getMiddleNavItems()
    { 
        return $('#nav_sub li'); 
    }

    function $getLeftNavItems()
    { 
        var elems = $('#nav_main li.js-item').get();
        for(var i=0 ; i < elems.length; i++) {        
            if (i > 0 && tt_px2int(elems[i].style.top) < tt_px2int(elems[i-1].style.top)) {
                elems = elems.slice(i).concat(elems.slice(0,i));
                break;
            }
        }
        return $(elems);
    }
    
    function $getRightNavItems()
    { 
        var elems = $('#nav_project li').get();
        for(var i=0 ; i < elems.length; i++) {        
            if (i > 0 && tt_px2int(elems[i].style.top) < tt_px2int(elems[i-1].style.top)) {
                elems = elems.slice(i).concat(elems.slice(0,i));
                break;
            }
        }
        return $(elems).reverse();
    }


    // -------------------------------------------------------------------------
    //    bind menu events  
    // -------------------------------------------------------------------------

    function unbindMenuItemEvents($items)
    {
        return $items.unbind().click(function() { return false; });
    }


    function bindMenuItemEvents(menuType)
    {
        tt_info('bindAllMenuItemEvents', menuType);        
        if (typeof menuType == 'undefined' || menuType == 'left_menu')
        {
            unbindMenuItemEvents($getLeftNavItems()).click(function() {
                if (tt_runningAnimations > 0)
                    return false;
                tt_setItemToCurrent(this);
                runLeftNavAnimation(this);
                return false;
            });
        }

        if (typeof menuType == 'undefined' || menuType == 'middle_menu')
        {
            unbindMenuItemEvents($getMiddleNavItems()).click(function() {        
                if (tt_runningAnimations > 0)
                    return false;
                tt_setItemToCurrent(this);
                runMiddleNavAnimation(this);
                return false;
            });
        }

        if (typeof menuType == 'undefined' || menuType == 'right_menu')
        {
            unbindMenuItemEvents($getRightNavItems()).click(function() {        
                if (tt_runningAnimations > 0)
                    return false;
                tt_setItemToCurrent(this);
                runRightNavAnimation(this);
                return false;
            });
        }
    };

    bindMenuItemEvents();


    // -------------------------------------------------------------------------
    //    animation
    // -------------------------------------------------------------------------

    function getSelectedItemContext(menuType, itemsFunc, currentMenuItem) 
    {
        var $itemList = itemsFunc();
        
        var result = $.extend({ 
            shiftWidth      : 0, 
            shiftHeight     : 0,             
            itemCount       : $itemList.length,
            selectedItemIdx : -1
        },  
        settings[menuType]);
        
        $itemList.each(function(i) 
        {
            if (this == currentMenuItem) {
                result.selectedItemIdx = i; 
                return false;
            }                    
            switch (menuType)
            {
                case 'middle_menu': result.shiftWidth  += $(this).outerWidth(); break;
                case 'left_menu':   result.shiftHeight += result.y_offset; break;
                case 'right_menu':  result.shiftHeight += result.y_offset; break;                
            }
        });

        
        result.startOfAnimation = function()
        {
            tt_runningAnimations++;
        };

        
        result.endOfAnimation = function()        
        {
            if (--tt_runningAnimations == 0)
            {
                tt_info('endOfAnimation: START', tt_runningAnimations);            
                itemsFunc().each(function(i) // we need the actual items so dont use $itemlist here!                 
                {
                    if (menuType == 'middle_menu') 
                    {
                        if (i < result.selectedItemIdx)
                            $(this).remove();
                        else
                            this.style.left = 0;
                    }
                });
                switch (menuType)
                {
                    case 'left_menu':   onNavMainChanged(); break;
                    case 'middle_menu': onNavSubChanged(); break;
                    case 'right_menu':  onNavProjectChanged(); break;
                }
                tt_info('endOfAnimation: DONE', tt_runningAnimations);
            }
        };
        
        result.animate = function($elem, params, duration, easing, callback) 
        {
            result.startOfAnimation();                    
            $elem.animate(params, duration, easing, function() {
                if (callback != null)
                   callback();
                result.endOfAnimation();
            });
        };
        
        return result;
    };    
    
    
    function runMiddleNavAnimation(currentMenuItem) 
    {
        var ease      = "easeInOutQuad";
        var basetime  = 140;
        var durations = [2, 5, 6, 7, 7, 7, 7, 7, 7 ,7];
    
        var context = getSelectedItemContext('middle_menu', $getMiddleNavItems, currentMenuItem);
        if (context.shiftWidth == 0)
            return false;

        $getMiddleNavItems().each(function(i) 
        {
            var $item = $(this);
            var time1 = basetime * durations[Math.min(i, durations.length-1)];            
            var time2 = basetime * durations[durations.length-1];
            if (i < context.selectedItemIdx) // item is before current
            {
                context.animate($item, { 'left':-context.shiftWidth+'px', 'opacity':0 }, time1, ease, function() {
                    var $newRightItem = $item.clone().css( {'left':'0px', 'opacity':0 } );
                    $item.parent().append($newRightItem);
                    context.animate($newRightItem, { 'left':-context.shiftWidth+'px', 'opacity':1 }, time2, ease, null);
                });
            }
            else
            {
                context.animate($item, { "left":-context.shiftWidth+'px' }, time1, ease, null);
            }
        });
    };

    function runLeftNavAnimation(currentMenuItem) 
    {
        var ease      = "easeInOutQuad";
        var basetime  = 140;
        var durations = [3, 5, 5, 5];
    
        var context = getSelectedItemContext('left_menu', $getLeftNavItems, currentMenuItem);
        if (context.shiftHeight == 0)
            return false;

        $getLeftNavItems().each(function(i) 
        {
            var $item   = $(this);        
            var time1   = basetime * durations[Math.min(i, durations.length-1)];            
            var time2   = basetime * durations[durations.length-1];
            var top     = tt_px2int($item.css('top'));                                    
            if (i < context.selectedItemIdx) // item is above current
            {
                var newTop = context.y_top + (context.itemCount - context.selectedItemIdx + i) * context.y_offset;            
                context.animate($item, { 'top':'-200px', 'opacity':1 }, time1, ease, function() {
                    $item.css( {'top':top+150+'px', 'opacity':0 } );                
                    context.animate($item, { 'top':newTop+'px', 'opacity':1 }, time2, ease, null);
                });
            }
            else if (i == context.selectedItemIdx) // item is current
            {
                context.animate($item, { 'top':context.y_top+'px' }, time1, ease, null);
            }
            else
            {
                var newTop = context.y_top - (context.selectedItemIdx - i) * context.y_offset;                                                                
                context.animate($item, { 'top':newTop+'px' }, time1, ease, null);
            }
        });
    };

    function runRightNavAnimation(currentMenuItem) 
    {
        var MAX_VISIBLE_PROJECTS = 9;
        var ease      = "easeInOutQuad";
        var basetime  = 120;
        var durations = [2, 5, 6, 7];
    
        var context   = getSelectedItemContext('right_menu', $getRightNavItems, currentMenuItem);
        if (context.shiftHeight == 0)
            return false;
        if (context.itemCount > MAX_VISIBLE_PROJECTS) 
            context.y_top -= context.y_offset * (context.itemCount-MAX_VISIBLE_PROJECTS);

        $getRightNavItems().each(function(i) 
        {
            var $item = $(this);        
            var top   = tt_px2int($item.css('top'));                        
            var time1 = basetime * durations[Math.min(i, durations.length-1)];            
            var time2 = basetime * durations[durations.length-1];
            
            var funcItemIsVisible = function(yTop) { 
                return true; 
                /*return yTop > 45;*/ 
            };                    
            var funcAfter = function(isVisible) { 
                $item.css('opacity', isVisible ? 1 : 0);                            
                $item.css('display', isVisible ? 'block' : 'none');
            };

            if (i < context.selectedItemIdx) // item is below current
            {
                var newTop  = context.y_top + (context.selectedItemIdx - i + 1) * context.y_offset;   
                var visible = funcItemIsVisible(newTop);
                context.animate($item, { 'top':top+context.y_bottom+'px', 'opacity':(visible?1:0) }, time1, ease, function() {
                    $item.css( {'top':'-100px', 'opacity':0 } );
                    context.animate($item, { 'top':newTop+'px', 'opacity':(visible?1:0) }, time2, ease, funcAfter(visible));
                });
            }
            else if (i == context.selectedItemIdx) // item is current
            {
                var newTop  = context.y_bottom;
                var visible = funcItemIsVisible(newTop);
                context.animate($item, { 'top':newTop+'px' }, time1, ease, funcAfter(visible));
            }
            else
            {
                var newTop  = top + context.shiftHeight;
                var visible = funcItemIsVisible(newTop);
                context.animate($item, { 'top':newTop+'px' }, time1, ease, funcAfter(visible));
            }
        });
    };
};

