// NAMESPACE
var frantic = {};

// GLOBAL UTILS
frantic.utils = {
    emailFixer : function() {
        $('span.liame').each(function(){
            var liame = $(this).html();
            var email = liame.split("").reverse().join("");
            $(this).html('<a href="mailto:'+email+'" class="email" rel="nofollow">'+email+'</a>');
            $(this).attr('class','email');
        });
    },
    
    placeholderFixer : function(elem) {
        if (elem.length > 0) {
            jQuery(elem).each(function(){
                var currentValue = jQuery(this).attr('placeholder');
                jQuery(this).attr('value', currentValue);

                jQuery(this)
                    .focus(function() {
                        jQuery(this).attr('value', '');
                    })
                    .blur(function() {
                        if (jQuery(this).attr('value') == '') {
                            jQuery(this).attr('value', currentValue);
                        }
                    });
            });
        }
    },

    newsletterForm : function() {
        jQuery('#newsletter-form').ajaxForm({
            resetForm: true,
            target: '#newsletter-form-status',
            success: function() {
                jQuery('#newsletter-form-status').fadeIn('slow');
                jQuery('#newsletter-form-email').blur();
            }
        })
    },
    
    browser : function() {
        if(jQuery.browser.mozilla && jQuery.browser.version.substr(0,5) == '1.9.0' ){
            jQuery('html').addClass('moz_30');
        }
        if(jQuery.browser.webkit && jQuery.browser.version.substr(0,3) == '525' ){
            jQuery('html').addClass('webkit_525');
        }

    },

    eventTracker : function() {
        jQuery('a').live('click', function() {
            var $objParents = jQuery(this).parentsUntil('body'),
                parentID = [];

            jQuery($objParents).each(function() {
                if (jQuery(this).attr('id') != 0) {
                    parentID.push(jQuery(this).attr('id'));
                }
            });

            var eventAction = (this.href.match(window.location.hostname)) ? 'drilldown' : 'exit-link',
                eventLabel = parentID.reverse().join('_') + '_' + jQuery(this).text();
            _gaq.push(['_trackEvent', jQuery('body').attr('id'), eventAction, eventLabel]);

            // Just the sales email
            if ($(this).parents('#sales-email').length) {
                _gaq.push(['_trackPageview', '/fake_pv/footer_sales-and-inquiries_sami.relander@frantic.com']);
            }
        });
    },
    
    effects : function(){
        if(jQuery('#logo a').length>0){
            jQuery('#logo a').hover(function(){jQuery(this).fadeTo(250, 0);},function(){jQuery(this).fadeTo(250, 1);});   
        }
    }
};


// CAROUSEL
frantic.carousel = {
    itemsAmount: 0,
    nextItem: 1,
    t : '',
    createTabControls : function(args) {
        var carouselContainer = args.carouselContainer,
            carouselItems = jQuery(carouselContainer).find('> div'),
            carouselTabControls = '<div class="js-carousel-tab-controls"><nav><ul>';

        jQuery(carouselItems).each(function(i) {
            carouselTabControls += '<li><a href="#js-carousel-item-' + i + '" title="' + jQuery(this).attr('data-title') + '">' + jQuery(this).attr('data-title') + '</a></li>';
        });
        carouselTabControls += '</ul></nav></div>';
        jQuery(carouselTabControls).insertBefore(carouselContainer);

        jQuery('.js-carousel-tab-controls li:first').addClass('js-selected');
        frantic.carousel.autoScroll(args);
        jQuery('.js-carousel-tab-controls').find('a').live('click', function() {
            frantic.carousel.stopScroll(); 
            jQuery(this).parent().addClass('js-selected').siblings().removeClass('js-selected').removeClass('js-auto-selected');
            jQuery(carouselContainer).attr('id', jQuery(this).attr('href').split('#')[1]);
            return false;
        });
    },

    scrollCarouselContent : function(args) {
        var carouselDirection = args.carouselDirection,
            carouselScroller = args.carouselScroller,
            carouselItemWidth = args.carouselItemWidth;

        var currentPosition = parseInt(jQuery(carouselScroller).css('left')),
            newPosition = carouselDirection == 'next' ? currentPosition + carouselItemWidth : currentPosition - carouselItemWidth;

        if (currentPosition == 0 && carouselDirection == 'next' || Math.abs(currentPosition) == jQuery(carouselScroller).width() - carouselItemWidth && direction == 'prev') {
            return false;
        }

        if (!Modernizr.csstransitions) {
            jQuery(carouselScroller + ':not(:animated)').animate({
                left: newPosition
            }, 500);
        } else {
            jQuery(carouselScroller).css('left', newPosition);
        }
    }, 
    
    autoScroll : function(args) {
        var carouselContainer = args.carouselContainer,
            carouselItems = jQuery(carouselContainer).find('> div');
        frantic.carousel.itemsAmount = jQuery(carouselItems).length;
        if(frantic.carousel.itemsAmount > 1){
            t = setInterval(function() {
                frantic.carousel.scrollToNext(args)}, 10000);
        };  
    }, 
    scrollToNext : function(args) {
        var carouselContainer = args.carouselContainer,
            carouselItems = jQuery(carouselContainer).find('> div'),
            carouselPage = args.carouselPage;
        if(carouselPage == 'work'){
            jQuery(carouselContainer).attr('id','js-carousel-item-'+frantic.carousel.nextItem);
        } else {
            jQuery(carouselItems).fadeOut(500);
            jQuery(carouselContainer).find('> div:eq(' + frantic.carousel.nextItem + ')').fadeIn(500);
        }
        frantic.carousel.setNextItem();
    },
    setNextItem : function() {
        jQuery('.js-carousel-tab-controls li:eq('+frantic.carousel.nextItem+')').addClass('js-auto-selected').siblings().removeClass('js-selected').removeClass('js-auto-selected');
        if(frantic.carousel.nextItem < (frantic.carousel.itemsAmount-1)){
            frantic.carousel.nextItem++;
        } else {
            frantic.carousel.nextItem = 0;
        };
    },
    stopScroll : function() {
        clearInterval(t);return false;
    }
}

// HOME
frantic.home = {
    init : function() {
        // TEASER
        jQuery('.js-carousel-tab-controls').find('a').live('click', function() {
            frantic.home.toggleTeaser(jQuery(this).parent().index());
            jQuery(this).parent().addClass('js-selected').siblings().removeClass('js-selected').removeClass('js-auto-selected');
            frantic.carousel.stopScroll();
            return false;
        });
        frantic.carousel.createTabControls({ carouselContainer : '#main-teaser > .carousel-container', carouselPage : 'main' });
        // making the whole teaser clickable
        jQuery('.carousel-container .teaser-item').each(function(){
            var teaserItem = jQuery(this),
                linkTarget = jQuery(this).find('a').attr('href');
            teaserItem.click(function(){
                window.location = linkTarget;
            });
        });

        this.newsCarousel();
    },

    loadfeeds : function () {
        $('#feeds-twitter').load('/feeds/twitter', { count: 10 }, frantic.home.resizefeeds );
        $('#feeds-flickr').load('/feeds/flickr', { count: 25 }, frantic.home.resizefeeds );
    },

    resizefeeds : function () {
        $(this).data({'loaded': true});
        if ( $('#feeds-twitter').data('loaded') && $('#feeds-flickr').data('loaded') ) {

        if (jQuery('#twitter').length > 0 && jQuery('#flickr').length > 0){
            var twitterHeight = jQuery('#twitter').height(),
                flickrHeight = jQuery('#flickr').height();
            jQuery('#twitter').height(flickrHeight);
        }
        var twitterHeight = jQuery('#twitter').height()-60, // 60 being mystery value and answer to some unrelated questions
            ulHeight = jQuery('#twitter ul').height(),
            liHeight = 0;
        if(ulHeight > twitterHeight){
            jQuery('#twitter li').hide();
            for(i=0;i<jQuery('#twitter li').length;i++){
                liHeight += jQuery('#twitter li:eq('+i+')').height();
                if(liHeight<twitterHeight){ jQuery('#twitter li:eq('+i+')').show(); }
            }
        }

        }
    },

    newsCarousel : function() {
        var carouselRoot = '#news-carousel',
            carouselContainerSelector = '#news-carousel > .carousel-container',
            carouselItemSelector = '.carousel-item',
            carouselContentSelector = '.carousel-content',
            $carouselItems = jQuery(carouselContainerSelector).find(carouselItemSelector),
            carouselItemWidth = $carouselItems.outerWidth(true),
            carouselPosition = 0,
            heightArr = [];

        // TRIM NEWS CAROUSEL HEIGHT
        jQuery(carouselRoot).find(carouselItemSelector).each(function() {
            heightArr.push(jQuery(this).height());
        });
        jQuery(carouselRoot).height(Math.max.apply(Math, heightArr));

        // CREATE PREVIOUS AND NEXT BUTTONS
        if ($carouselItems.length >= 2) {
            jQuery('<div id="js-news-prev" class="js-news-prev-next"></div>').insertBefore(carouselContainerSelector);
            jQuery('<div id="js-news-next" class="js-news-prev-next"></div>').insertAfter(carouselContainerSelector);
            jQuery('#js-news-prev').addClass('js-disabled');
        }

        // CLICK AND SCROLL
        jQuery(carouselRoot).find('.js-news-prev-next').live('click', function() {
            if (this.id == 'js-news-next') { // RIGHT ARROW
                if (carouselPosition == $carouselItems.length - 2) {
                    return;
                }
                carouselPosition++;
            }
            if (this.id == 'js-news-prev') { // LEFT ARROW
                if (carouselPosition == 0) {
                    return;
                }
                carouselPosition--;
            }

            jQuery('.js-news-prev-next').removeClass('js-disabled');
            if (carouselPosition == 0) {
                jQuery('#js-news-prev').addClass('js-disabled');
            }
            if (carouselPosition == $carouselItems.length - 2) {
                jQuery('#js-news-next').addClass('js-disabled');
            }

            // MOVE THE CONTENT
            var scrollerLeft = '-' + carouselPosition * carouselItemWidth + 'px';
            if (!Modernizr.csstransitions) {
                jQuery(carouselContainerSelector).find(carouselContentSelector + ':not(:animated)').animate({
                    left : scrollerLeft
                }, 500);
            } else {
                jQuery(carouselContainerSelector).find(carouselContentSelector).css('left', scrollerLeft);
            }
        });
    },

    toggleTeaser : function(elem) {
        jQuery('#main-teaser .carousel-container > div').fadeOut(500);
        jQuery('#main-teaser .carousel-container > div:eq(' + elem + ')').fadeIn(500);
    }
};



// WORK
frantic.work = {
    init : function() {
        this.tooltip();
        frantic.carousel.createTabControls({ carouselContainer : '.carousel-container', carouselPage : 'work' });
        if(jQuery('.moz_30').length>0 || jQuery('.webkit_525').length>0){
            jQuery('#work #content > article > section:eq(1)').addClass('rightCol');
        }
        
        // Add facebook recommend button
        var pageUrl = jQuery(location).attr('href');
        pageUrl = jQuery.URLEncode(pageUrl);        
        jQuery('article').append('<iframe src="//www.facebook.com/plugins/like.php?href=' + pageUrl +  '&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=recommend&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>');
        jQuery('article').append('<br/><g:plusone></g:plusone>');
    },

    // Tooltip could be moved to frantic.utils
    tooltip : function() {
        var tooltipSelectorId = '#js-work-nav-tooltip';

        // Create tooltip for current active work
        createTooltip(jQuery('#work-nav li > span > img'));

        // Create tooltips on navigation mouseover
        jQuery('#work-nav li > a > img')
            .mouseover(function() {
                jQuery(tooltipSelectorId).remove();
                createTooltip(jQuery(this));
            })
            .mouseout(function() {
                jQuery(tooltipSelectorId).remove();
                jQuery('#work-nav ul').mouseleave(function() {
                    createTooltip(jQuery("#work-nav li > span > img"));
                })
            });

        // Create the tooltip
        function createTooltip(elem) {
            jQuery(tooltipSelectorId).remove();
            jQuery(elem).parent().parent().append('<div id="' + tooltipSelectorId.split('#')[1] + '">' + jQuery(elem).attr('alt') + '<div id="js-work-nav-tooltip-arrow"></div></div>');
            positionTooltip(elem);
        };

        // Position (center) the tooltip
        function positionTooltip(elem) {
            var tooltipWidth = jQuery(tooltipSelectorId).outerWidth(),
                elemWidth = jQuery(elem).outerWidth(),
                newTooltipPosition = tooltipWidth > elemWidth ? '-' + (tooltipWidth - elemWidth) / 2 : (elemWidth - tooltipWidth) / 2;

            // Change tooltip position
            jQuery(tooltipSelectorId).css('left', newTooltipPosition + 'px');
        };
    }
};


// AGENCY
frantic.agency = {
    listContainerId : 'agency-people',
    
    createFilters : function() {
        var filtersId = 'js-agency-people-filters',
            filtersContainerId = 'agency-people-filters-container',
            filters = ['All', 'Strategy', 'Design', 'Development', 'Operations'];

        // Set WAI-ARIA roles
        jQuery('#' + this.listContainerId)
            .find('.vcard')
            .each(function() {
                jQuery(this)
                    .attr('role', 'tabpanel')
                    .attr('aria-labelledby', jQuery(this).attr('id'));
            });

        // Create filters list above the people list
        var filtersList = '<ul role="tablist" id="' + filtersId + '">';
        for (var i = 0, j = filters.length; i < j; i++) {
            filtersList += '<li><a href="#' + filters[i].replace(/\s+/g, '-') + '">' + filters[i] + '</a></li>';
        }
        filtersList += '</ul>';
        jQuery('#' + filtersContainerId).append(filtersList);

        // Click events to filter list elements
        jQuery('#' + filtersId)
            .find('a')
            .click(function() {
                var hash = jQuery(this).attr('href').split('#')[1];
                frantic.agency.filterCards(hash);

                jQuery(this)
                    .parent()
                    .addClass('js-selected')
                    .siblings()
                    .removeClass('js-selected');

                return false;
            });

        jQuery('#' + filtersId + ' li:first').addClass('js-selected');
    },

    filterCards : function(community) {
        var disabledVCardClass = 'js-disabled-vcard';

        jQuery('#' + this.listContainerId + ' li')
            .removeClass(disabledVCardClass)
            .removeAttr('aria-disabled');
        if (community !== 'All') {
            jQuery('#' + this.listContainerId + ' .vcard:not(.data-community-' + community + ')')
                .addClass(disabledVCardClass)
                .attr('aria-disabled', true);
        }
    },

    toggleCardSide : function() {
        jQuery('#agency-people').find('.vcard .photo-overlay, .vcard .vcard-open, .vcard .back').click(function() {

            var fadeSpeed = 250;
            
            // If CSS3 3D Transforms are not supported use fading
            if (!Modernizr.csstransforms3d) {
                if (jQuery(this).hasClass('photo-overlay', 'vcard-open')) {
                    jQuery(this).parents('.vcard').find('.front').fadeOut(fadeSpeed);
                    jQuery(this).parents('.vcard').find('.back').fadeIn(fadeSpeed);
                } else {
                    jQuery(this).parents('.vcard').find('.back').fadeOut(fadeSpeed);
                    jQuery(this).parents('.vcard').find('.front').fadeIn(fadeSpeed);
                }
            }
            // Otherwise use CSS3 3D Transforms from CSS
            jQuery(this).parents('.container').toggleClass('js-flipped');
        });
    },

    init : function() {
        // Set WAI-ARIA roles
        jQuery('body').attr('role', 'application');

        //this.createFilters();
        this.toggleCardSide();
        
        // hover transitions for cards
        jQuery('#agency-people .vcard .front').hover(function(){jQuery(this).find('.photo-overlay').fadeTo(250, 1);},function(){jQuery(this).find('.photo-overlay').fadeTo(250, 0);});

        // GA for card flip
        jQuery('#agency-people').find('.vcard .photo-overlay, .vcard .vcard-open').click(function() {
            _gaq.push(['_trackEvent', jQuery('body').attr('id'), 'vcard-open', jQuery(this).parent().parent().parent().attr('id')]);
        });
        jQuery('#agency-people').find('.vcard-close').click(function() {
            _gaq.push(['_trackEvent', jQuery('body').attr('id'), 'vcard-close', jQuery(this).parent().parent().parent().attr('id')]);
        });
    }
};

// GRAND ONE 2011
frantic.grandone = {
    init : function() {
        jQuery('.grandone-form-status').hide();
        if(!$.browser.opera){
            jQuery('input[type="submit"]').click(function(){
                var _fieldOK = 0;
                var _fieldAmount = jQuery('#grandone-form input.text, #grandone-form input.email').length;
                jQuery('#grandone-form input[type="text"], #grandone-form input[type="email"]').each(function(){
                    console.log('placeholder = '+jQuery(this).attr('placeholder'));
                    if((jQuery(this).val()!='')&&(jQuery(this).val()!=''+jQuery(this).attr('placeholder'))) { 
                        _fieldOK += 1;
                     }
                });
                if(_fieldOK==_fieldAmount){
                    jQuery('#grandone-form').ajaxForm({
                            resetForm: true,
                            success: function() {
                                jQuery('.replace-me').hide();
                                jQuery('.error').hide();
                                jQuery('.grandone-form-status').fadeIn('slow');
                                jQuery('#grandone-form').blur();
                                jQuery('#grandone-form').addClass('disabled').find('input').attr('disabled','disabled');
                            }
                        });
                 } else {
                    jQuery('#grandone-form-container .required').hide();
                    jQuery('#grandone-form-container .error').fadeIn();
                    return false;
                 };
            });
        }
    }
};



// ONLOAD
frantic.utils.emailFixer();
frantic.utils.newsletterForm();
frantic.utils.eventTracker();
frantic.utils.browser();
frantic.utils.effects();

if (!Modernizr.input.placeholder) {
    frantic.utils.placeholderFixer('#newsletter input[type="email"], #grandone-form input[type="email"], #grandone-form input[type="text"]');
}

switch(jQuery('body').attr('id')) {
    case 'home' :
        frantic.home.init();
        $(document).ready( function() { frantic.home.loadfeeds() } );
        break;
    case 'work' :
        frantic.work.init();
        break;
    case 'agency' :
        frantic.agency.init();
        break; 
    case 'grandone11' :
        frantic.grandone.init();
}

