
/**
 * SFN UI
 *
 * @author Roman Pistek, Studio Fresh Net, s.r.o.
 * @copyright 2011 SFN
 */
var sfnUI = function() {
    
    // privates
    var /*setTopPadding = function() {
            var top = Math.round($(window).height() * 0.25 / 20) * 20;
            $('.page-content').css({ paddingTop: top + 'px' });
            return top;
        },*/
        resetNavTimer,
        isMobile = navigator.userAgent.match(/Android/i) ||
                   navigator.userAgent.match(/webOS/i) ||
                   navigator.userAgent.match(/iPhone/i) ||
                   navigator.userAgent.match(/iPod/i),
        isOldIE = $.browser.msie && parseInt($.browser.version.slice(0, 1)) <= 8,

        getCurrPage = function() {
            var hash = location.hash.replace('#', '');
            return hash ? hash : 'home';
        },

        getCurrPageId = function() {
            return $('#nav a[href$=#' + getCurrPage() + ']').attr('class').replace(/\s*active\s*/, '');
        },

        highlightNav = function(trigger) {
            trigger = (!trigger || typeof trigger == 'undefined') ? $('html') : trigger;
            clearTimeout(resetNavTimer);
            $('#nav a.active').removeClass('active');
            $('#nav a.' + getCurrPageId()).addClass('active');
            $('#nav a span').hide();
            $('#nav a.active span').show();
        },

        realignLayout = function() {
            $('.page-content').each(function() {
                var topPadding = $(this).vAlign('padding', $(window), 'symetry');
                if (topPadding > 40) {
                    $(this).css({
                        'padding-top': parseInt($(this).css('padding-top'), 10) + 40 + 'px',
                        'padding-bottom': parseInt($(this).css('padding-bottom'), 10) - 40 + 'px'
                    });
                }
                if (!refDetailPage && $(this).parents('#refs-page')) {
                    var offset = $('html').width() - 960;
                }
            });
            $('#services-list strong').vAlign('padding');
            $('#refs-page .slidedown-button').css('left', (parseInt($(window).height(), 10) < 620) ? '173px' : '50%');
        },

        titleCarousel = function() {
            $('#title-carousel .carriage:first-child').fadeOut(400, function() {
                $(this).addClass('invisible').appendTo('#title-carousel');
            });
            $('#title-carousel .carriage:nth-child(2)').hide().removeClass('invisible').fadeIn(800);
        },

        refsSwitchViews = function() {
            var view = 'top';
            $('#refs-switch a.top').addClass('active');
            $('#refs-switch a').live('click', function() {
                if ($(this).hasClass('list') && view != 'list') {
                    view = 'list';
                } else
                if ($(this).hasClass('top') && view != 'top') {
                    view = 'top';
                } else {
                    return false;
                }
                refsSlideViews(view);
            });
            $.nette.afterSuccess = function(payload) {
                 {
                    if (payload.openRefDetail == true) {
                        view = 'detail';
                        refsSlideViews(view);
                        Cufon.replace('h2', { fontFamily: 'PT Sans', textShadow: '0px 1px 0px #ddd' });
                    } else {
                        if (getCurrPageId() == 'refs' && view == 'detail') {
                            // back to all refs...
                            view = 'list';
                            refsSlideViews(view);
                        }
                    }
                }
            }
        },
        
        refsSlideViews = function(view) {
            var margins = [],
                backgroundPos = (site == 'SF') ? [395, 290] : [160, 250];
            switch (view) {
                case 'list':
                    margins = [-3960, 0];
                    break;
                case 'detail':
                    margins = [-6960, -3960];
                    break;
                default:
                    margins = [0, 0];
            }
            $('#refs-switch a').removeClass('active');
            $('#refs-switch a.' + view).addClass('active');
            $('#refs-carousel').animate({marginLeft: margins[0] + 'px'});
            $('#refs-list').animate({marginLeft: margins[1] + 'px'});
            $('#refs-page .wrapper').animate({backgroundPosition: (margins[0] + backgroundPos[0]) + 'px ' + backgroundPos[1] + 'px'});
        },

        refsKeyTooltip = function() {
            var timer,
                tooltip = $('#refs-carousel .keys-tip');
            timer = setInterval(function() {
                tooltip.fadeIn(200, function() {
                    setTimeout(function() {tooltip.fadeOut(100);}, 2500);
                });
            }, 15000);
            $(document).bind($.browser.webkit ? 'keyup' : 'keypress', function(event) {
                var key = (event.which > 0) ? event.which : event.keyCode;
                if (getCurrPageId == 'refs' && key == '37' || key == '39') {
                    tooltip.fadeOut(100);
                    clearInterval(timer);
                }
            });
        },

        clientsCarousel = function() {
            var container = $('#clients-page'),
                mignifiedLogoUri = function(thumbUri) {
                    var uri = thumbUri || '';
                    uri =  thumbUri.replace(/-small/, '');
                    $.preloadImages(uri);
                    return uri;
                },
                firstLogoUri = mignifiedLogoUri($('.clients-nav a:first-child img', container).attr('src'));

            $('.client-detail p:last-child', container).css('background', 'transparent url(' + firstLogoUri + ') 50% 100% no-repeat').show();
            $('.clients-nav a', container)
                .mouseenter(function() {
                    var logoUri = mignifiedLogoUri($('img', this).attr('src'));
                    var prevDetail = $('.client-detail p:last-child', container);
                    $('.client-detail', container).append('<p style="background: transparent url(' + logoUri + ') 50% 100% no-repeat"></p>');
                    $('.client-detail p:last-child', container).fadeIn(isOldIE ? 0 : 500);
                    prevDetail.remove();
                })
                .click(function() {return false;});
        },

        whatwedoBubbles = function() {
            var bubbles = $('#services-list dt'),
                coords =  (site == 'SF') ? [[-50, 10], [146, 80], [312, -40], [505, 110], [623, -25], [760, 110]]
                                         : [[10, 40], [238, 10], [392, 67], [520, 110], [684, 16]],
                textTimer,
                lastActive;
            bubbles.css({'position': 'absolute'});
            $('dd', bubbles.parent()).css('position', 'absolute').hide();
            bubbles.each(function(i) {
                $(this).css({'left': coords[i][0], 'top': coords[i][1]});
            });
            bubbles.mouseenter(function() {
                var bubble = $(this);
                var index = $(this).index($(this).get(0).tagName);
                lastActive = index;
                bubbles.each(function(i) {
                    if (index != i && $(this).position().top > coords[i][1]) {
                        clearTimeout(textTimer);
                        $(this).next('dd').hide();
                        Cufon.replace($('#services-list dt.active'), {fontFamily: 'PT Sans', color: '#fff'});
                        $(this).animate({'top': coords[i][1]}, 100).removeClass('active');
                    }
                });
                $(this).animate({
                    'top': (240 - $(this).height() / 2) + 'px'
                }, {
                    duration: 300,
                    complete: function() {
                        textTimer = setTimeout(function() {
                            if (lastActive != index || bubble.position().top <= coords[index][1]) {
                                return false;
                            }
                            var text = bubble.next('dd'),
                                pos = bubble.position(),
                                size = {width: bubble.innerWidth(), height: bubble.innerHeight()};
                            $('dd', bubbles.parent()).hide();
                            Cufon.replace($('#services-list dt.active'), {fontFamily: 'PT Sans', color: '#fff'});
                            bubbles.removeClass('active');
                            bubble.addClass('active');
                            Cufon.replace(bubble, {fontFamily: 'PT Sans'});
                            text.css({
                                top: pos.top + size.height - 20,
                                left: pos.left + size.width + 10 - ((pos.left > 500) ? (text.width() + size.width) : 0)
                            }).show();
                        }, 0);
                    }
                });
            }).mouseleave(function() {
                clearTimeout(textTimer);
            });
        },

        /*afterScroll = function() {
            if (getCurrPageId() == 'refs') {
                alert(clientsCarousel.foo);
                $(window).keypress(clientsCarousel.handleKeypress);
            } else {
                $(window).unbind('keypress', clientsCarousel.handleKeypress);
            }
        },*/

        bindEvents = function() {

            // browser window resized...
            $(window).resize(function() {
                realignLayout();
            });

            // main navigation behavior
            $('#nav a, .slidedown-button a, .slideup-button a')
                .click(function(e) {
                    loc = window.location;
                    var currentUrl = loc.href.replace(loc.protocol + '//' + loc.hostname, '');
                    if (currentUrl.replace(/#.*/, '') != $(this).attr('href').replace(/#.*/, '')) {
                        return true;
                    }
                    var nextPage = $(this).attr('class').replace(/\s*active\s*/, '');
                    if (getCurrPageId() == nextPage) {return false;}
                    var pageSel = nextPage + '-page';
                    $('body').scrollTo(
                        '#' + pageSel + ' .page-content',
                        777,
                        {
                            axis: 'y',
                            easing: 'easeInOutQuart',
                            onAfter: function() {highlightNav();}
                        });
                });
            $('#nav a')
                .mouseover(function() {
                    highlightNav(this);
                });
            $('#nav a span').live('mouseleave', function() {
                highlightNav(this);
            });

            // forms
            $('form input')
                .live('focus', function() {$(this).addClass('active');})
                .live('blur', function() {$(this).removeClass('active');});

            // block Ctrl+f keyshort
            // BUG: knihovna jquery.shortcuts pretezuje binds v ui.js...
            /*$(document).bind('keydown', 'Ctrl+f', function (event) {
                event.stopPropagation();
                event.preventDefault();
                return false;
            });*/
        },

        initialize = function() {
      
            if (window.fbRefPage !== undefined) {
                return;
            }
            
            // for mobiles...
            if (isMobile) {
                $('.page').css('min-height', '500px').css('padding-top', '60px');
                $('#nav, #logo, .link-sf, .link-sfn').css({ position: 'absolute' });
                $('.slidedown-button').hide();
            }
            
            // CUFON
            if (!isOldIE) {
                Cufon.replace('#title-carousel h2', { fontFamily: 'PT Sans Caption' });
                Cufon.replace('#home-page .slogan', { fontFamily: 'PT Sans', textShadow: '0px 1px 0px #fff' });
                Cufon.replace('#services-list dt strong, #services-list dd', { fontFamily: 'PT Sans' });
                Cufon.replace('#about-page p, #about-page li', { fontFamily: 'PT Sans' });
                Cufon.replace('#career-page p, #career-page li', { fontFamily: 'PT Sans' });
                Cufon.replace('#contact-page h2', { fontFamily: 'PT Sans Caption', textShadow: '0px 1px 0px #dae5a6' });
                Cufon.replace('h2, h3, h4', { fontFamily: 'PT Sans', textShadow: '0px 1px 0px #ddd', onAfterReplace: function() {
                    $('#_fog').remove();
                }});
            } else {
                $('#_fog').remove();
            }

            // conditional ajax anchor
            if ($.browser.msie
                || ($.browser.mozilla && parseInt($.browser.version.slice(0,1), 10) < 2)) {
            } else {
                $('a._ajax').addClass('ajax');
            }
            
            $('html').height($(window).height());
            $('#nav a').each(function() {
                $(this).append('<span></span>');
            });
            highlightNav();
            
            if (!refDetailPage) {
                $('body').scrollTo('#' + getCurrPageId() + '-page .page-content', 0, {
                    axis: 'y'
                });

                $('#title-carousel .slogan').each(function() {
                    $(this).append('<img src="' + _baseUri + '/images/mask/title-page-slogan-box-shadow.png" class="shadow" alt="shadow" width="' + $(this).width() + '" height="15">')
                           .append('<span class="le"></span>').append('<span class="re"></span>');
                });
                setInterval(function() {titleCarousel();}, 6000);
                $('#refs-carousel').freshCarousel({
                    duration: isOldIE ? 0 : 300,
                    classes: {
                        wrapper:    'refs',
                        carriage:   'ref',
                        navWrapper: 'refs-nav'
                    },
                    enableKeypressOn: function() {
                        return (getCurrPageId() == 'refs') ? true : false;
                    }
                });
                refsSwitchViews();
                $('#refs-list').freshCarousel({
                    interval: false,
                    duration: isOldIE ? 0 : 300,
                    classes: {
                        wrapper:    'list-wrapper',
                        carriage:   'row',
                        navWrapper: 'refs-nav'
                    }
                });
                /*refsKeyTooltip();*/
                clientsCarousel();
                whatwedoBubbles();
            }

            realignLayout();
        };


   // public
   return {
       init: function() {
           bindEvents();
           initialize(); 
       }
   }
}();



// Caching images
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preloadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);



// Repeater Plugin
(function ($) {
$.fn.repeat = function(times, string, callback) {
    // For each item matched
    this.each(function(){  
        var buff = '';
        for(var i = 1; i <= times; i++){
            var rel = callback(i);
            string = rel ? $('<div>').append($(string).clone().attr('rel', rel)).remove().html() : string;
            buff += string;
        }  
        $(this).append(buff);
    });  
    return this;  
};
})(jQuery);



// Vertically align function
(function ($) {
$.fn.vAlign = function(property, parent, symetry) {
    var prop = (property == 'padding') ? (symetry ? 'padding' : 'padding-top') : 'margin-top';
    var topPadding;
    /*return */this.each(function(i) {
        var ah = $(this).height();
        var ph = (parent ? parent : $(this).parent()).height();
        var mh = Math.ceil((ph - ah) / 2);
        if (i == 0) {topPadding = mh;}
        $(this).css(prop, mh + 'px' + (symetry ? ' 0' : ''));
    });
    return topPadding;
};
})(jQuery);



// init...
$(document).ready(function() {

    sfnUI.init();
    $('.slidedown-button a[title], .slideup-button a[title], .slideleft-button a[title]').qtip({
        show: {
            delay: 400
        },
        position: {
            corner: {target: 'rightMiddle', tooltip: 'leftMiddle'},
            adjust: {x: 10}
        },
        style: {
            //tip: true,
            name: 'dark',
            width: {
                min: 0,
                max: 380
            },
            padding: '3px 6px',
            border: {
                width: 0,
                radius: 3,
                color: '#000'
            },
            color: '#eee',
            background: '#000',
            fontSize: '10.7px'
        }
    });
    $('#fresh-people img[title]').qtip({
        show: {
            delay: 600
        },
        position: {
            corner: {target: 'bottomMiddle', tooltip: 'topMiddle'},
            adjust: {x: 10}
        },
        style: {
            tip: true,
            name: 'dark',
            width: {
                min: 0,
                max: 380
            },
            padding: '3px 6px',
            border: {
                width: 0,
                radius: 3,
                color: '#000'
            },
            color: '#eee',
            background: '#000',
            fontSize: '10.7px'
        }
    });
});

