
var App = {

    // Enable debug notifications,
    // but only if console.log is supported
    debug: (false && (window.console && window.console.log)),

    // True on first ajax load. do not modify
    initialLoad: true,

    // ajax cache for pages
    pageCache: [],

    // used to track oldContent cleanup
    oldQueue: [],

    clearOld: true,

    // the current transition type to use
    transitionType: 'fadeIn',

    // 'true' to preload pages and images
    usePreload: true,

    // if google maps has loaded async
    gmapIsLoaded: false,

    // A lock to prevent family thumbnail transitions
    animationLock: false,

    events: {
        onswitchsection: new signals.Signal(),
        onsectionloaded: new signals.Signal(),
        subnavemptied: new signals.Signal(),
        subnavtransitioned: new signals.Signal(),
        startsectiontransition: new signals.Signal(),
        endsectiontransition: new signals.Signal()
    },

    routes: {
        'home': homeCallback,
        'about': aboutCallback,
        'work': workCallback,
        'work-list': workListCallback,
        'work-single':workSingleCallback,
        'family': familyCallback,
        'family-single': familySingleCallback,
        'friends': friendsCallback,
        'friend': friendCallback,
        'contact': contactsCallback,
        'contact-detail': contactDetailCallback,
        'careers': careersCallback,
        'career': careerCallback,
        'site-map': sitemapCallback
    },

		setCookie : function(name, value, days) {
      days = days || 30;
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();

			document.cookie = name + "=" + value + expires + "; path=/";
    },

    // if map should be initially visible on city detail page
    showMap : false,

    // what menu should be active when you get to the Careers page,
    // this is because each job posting needs a unique url so it must
    // be a new page
    careerActiveMenu : 'city'
};


/** DOCUMENT READY **********************************************************/
$(document).ready(function() {

    // if(isIOS()) {
    //   document.cookie = "isIOS=true";
    //   window.location.reload();
    // }

    if(isIPAD()) {
      document.cookie = "isIPAD=true";
      window.location.reload();
    } else if(isIPHONE()) {
      document.cookie = "isIPHONE=true";
      window.location.reload();
    }


    $('#logo').fadeIn(1000,function(){
        $('#mainNavigationInner').animate({ 'right': 0 }, 600, function() {
            $('#socialMediaLinks').fadeIn('slow');
            $('#credit').fadeIn('slow');
        });
    });

    $('#mainNavigation a').live('click',function() {
        $('#mainNavigation').find('.current').removeClass('current');
        $('footer').removeClass('current');
        $(this).addClass('current');
    });
    $('#secondaryNavigation a').live('click',function() {
        var self = $(this);
        if (self.hasClass('dropdown_lnk') === false) {
            $('#secondaryNavigation').find('.current').removeClass('current');
            self.addClass('current');
        }
    });

    $('#credit a').bind('click',function() {
        $('#mainNavigation').find('.current').removeClass('current');
        $('.current','footer').removeClass('current');
        $(this).addClass('current');
    });

    // AJAX global event handler
    $('body')
      .ajaxStart(function(){ $('#loading').css('opacity', 1); })
      .ajaxStop(function(){ $('#loading').css('opacity', 0); });

    var html_tag = $('html');
    // if(html_tag.hasClass('video') === false || html_tag.hasClass('no-hashchange') || html_tag.hasClass('bgsizecover') === false) {
    if(html_tag.hasClass('video') === false || html_tag.hasClass('no-hashchange')) {
      $('#splashVideo').remove();
      $('#upgradeYourBrowser').show();
    }

});

/** WINDOW SCROLL ***********************************************************/
// $(window).scroll(function(){
//
//   $('#alert').fadeIn('slow').delay('2000').fadeOut('slow');
//
//   // $('#alert').addClass('active');
//
// });

function getBrowser() {
  if (navigator.userAgent.match(/Chrom/)) {
    return 'chrome';
  }
  if (navigator.userAgent.match(/Safari/)) {
    return 'safari'
  }
  if (navigator.userAgent.match(/Firefox/)) {
    return 'ff';
  }
  return 'other';
}

$(document).ready(function(){
  $('#alert').click(function(){
    removeClass('active');
  });
  URLRedir();

  // Set background image to match video
  var browser = getBrowser(), bg = null;
  $('html').addClass('browser-' + browser);
  switch (browser) {
    case "safari":
      bg = '/images/corporate-identity-safari.png';
      break;
    case "ff":
      bg = '/images/corporate-identity-ff.png';
      break;
  };

  bg && !navigator.userAgent.match(/OS X 10_5/) && $('#ci_bg .i, #header_bg .i').attr('src', bg);
});

/** WINDOW RESIZE ***********************************************************/
$(window).resize(windowResize);

function windowResize() {
  var content = $('#content'),
    contentWidth = content.width(),
    contentHeight = content.height();
  if (contentWidth/contentHeight >= 1.6) {
    // $('.contentInner').css('background-size','100% auto');
    $('#main_background, .background_images img').css({'width' : '100%','height' : 'auto'});
    /* work list view page */
    //$('.backgroundImage').css('background-size','100% auto');
  }
  else {
    // $('.contentInner').css('background-size','auto 100%');
    $('#main_background, .background_images img').css({'width' : 'auto','height' : '100%'});
    //$('.backgroundImage').css('background-size','auto 100%');
  }

  /*** FAMILY DETAIL ****/
  var fam_el = $(".familySingle .right");
  if (fam_el.length) {
    var ratio = fam_el.width() / fam_el.height();
    if (ratio > 1) {
      $('.familySingle .right .bg').css({'width':'100%','height':'auto'});
    }
    else {
      $('.familySingle .right .bg').css({'width':'auto','height':'100%'});
    }
  }
};

$('.gt').live('click', function(){
  App.transitionType = 'slideLeft';
  $('.lt').hide();
  $('.gt').hide();
});

$('.lt').live('click', function(){
  App.transitionType = 'slideRight';
  $('.lt').hide();
  $('.gt').hide();
});

$('#mainNavigationInner li a').live('click', function() {
  App.transitionType = 'fadeIn';
});

$('#secondaryNavigation div a').live('click', function() {
  App.transitionType = 'fadeIn';
});

$('.thumbnail').live('click', function(){
  App.transitionType = 'slideUp';
});

$('.trans_fadeIn').live('click',function(){
  App.transitionType = 'fadeIn';
});

$('.cities a').live('click',function(){
  App.transitionType = 'fadeIn';
});

$('.close').live('click', function(){
  App.transitionType = 'fadeIn';
});

$('.footerLinks a').live('click', function(){
  App.transitionType = 'fadeIn';
});

// See Map toggle
$('.seeMap').live('click', function(){
  App.showMap = true;
});

$(window).bind('hashchange', function() {
  App.initialLoad = false;
  URLRedir();
});

App.switchTimer = null;

function URLRedir() {
  var url = window.location,
      path = url.href.split('#!/').pop() || 'home';

  App.setCookie('from_ajax', true, 1);

  // Detect the url pattern and if it doesnt have #! in it, redir to #!/pagename
  if (url.href.split('#!/').length != 2) {
    window.location = '/#!/' + url.href.split('/').pop();
  }
  else {
    isIOS() ? switchSection(path, 'fadeIn') : switchSection(path, App.transitionType);
  }
}

function preloadOne(page) {
  if (!page || page.match(/(city|department)/)) {
    return;
  };
  if(App.debug)
    console && console.log(page);
  page = page.replace(/^[^\w]+/, '');
  if (App.pageCache[page]) {
    return;
  };
  setTimeout(function(){
    $.get('/' + page, function(html){
      App.pageCache[page] = html;
      var result = html.match(/\w+.(jpg|jpeg)/g);
      result && $.each(result, function(j, image) {
        if (j < 50) preloadImage(image);
      });
    });
  }, 1);
}

function preloadImage(image) {
  setTimeout(function(){
    var host = 'selectny2.vaesite.net';
    (new Image()).src = 'http://' + host + '/__data/' + image;
  }, 1);
};

function preloadAll() {
  $('a:lt(25)').each(function(){
    if (this.href.match(/#!/)) {
      preloadOne($(this).attr('href'));
    };
  });
}

//pass only the "path" to this function take care of url splitting beforehand
//ex: 'index' should be passed as a param and not '/#!/index'
function switchSection(link, transitionType) {

  link != 'home' && $('#splashVideo').remove();

  if (link == 'work' || link == 'family') {
    transitionType = 'fadeIn';
    App.clearOld = false;
  };

  App.lastPage = App.currentPage || null;
  App.currentPage = link.split('/')[0];
  App.events.onswitchsection.dispatch();

  if (App.pageCache[link]) {
    onSwitchSectionSuccess(link, transitionType);
  }
  else {
    $.get('/' + link, function(html){
      App.pageCache[link] = html;
      onSwitchSectionSuccess(link, transitionType);
    });
  }

  // special case for work
  $('#header_bg_content').empty();
}

function onSwitchSectionSuccess(link, transitionType) {

  _gaq.push(['_trackPageview', link]);

    var data = App.pageCache[link],
        content_div = $('#content'),
        tmp_div,
        out_div,
        in_div,
        win = $(window),
        win_width = win.width(),
        win_height = win.height();

    App.events.onsectionloaded.dispatch();

    //var transitionType = App.getTransitionType(App.currentPage, App.lastPage);

    // 2. make .lastContent the class of .currentContent
    out_div = $('.currentContent').removeClass('currentContent').addClass('oldContent');
    App.oldQueue.push(out_div);

    // 3. create .currentContent section && fill it
    in_div = $('<div class="currentContent">'+data+'</div>');
    in_div.appendTo(content_div);

    App.routes[App.currentPage].call();

    App.events.startsectiontransition.dispatch();

    var duration = 2200;

    switch (transitionType) {
        case 'show':
            in_div.show();
            endSwitchSectionTransition();
            break;

        case 'clearFade':
            if (out_div.length) {
                in_div.hide();
                out_div.fadeOut(300, 'easeOutExpo', function() {
                    in_div.fadeIn(duration, 'easeOutExpo', endSwitchSectionTransition);
                });
            }
            else {
                in_div.hide();
                in_div.fadeIn(duration, 'easeOutExpo', endSwitchSectionTransition);
            }
            break;

        case 'swap':
            endSwitchSectionTransition();
            break;

        case 'fadeIn':
            in_div
                .hide()
                .fadeIn(duration, 'easeOutExpo', endSwitchSectionTransition);

            break;

        case 'slideDown':
            //out_div.animate({'top': -win_height});
            in_div
                .css('top', win_height)
                .animate({'top': 0}, {
                    easing: 'easeOutExpo',
                    duration: duration,
                    complete: endSwitchSectionTransition
                });

            break;

        case 'slideUp':
            //out_div.animate({'top': win_height});
            in_div
                .css('top', -win_height)
                .animate({'top': 0}, {
                    easing: 'easeOutExpo',
                    duration: duration,
                    complete: endSwitchSectionTransition
                });

            break;

         case 'slideLeft':
             out_div.css({'left': 0});
             in_div.css('left', win_width);

             out_div.animate({'left': -win_width +'px'}, {
                easing: 'easeOutExpo',
                duration: duration
             });
             in_div.animate({'left': 0}, {
                 easing: 'easeOutExpo',
                 duration: duration,
                 complete: endSwitchSectionTransition
             });

            break;

         case 'slideRight':
            out_div.css({'left': 0});
            in_div.css('left', -win_width);

            out_div.animate({'left': win_width}, {
                easing: 'easeOutExpo',
                duration: duration
            });
            in_div.animate({'left': 0}, {
                easing: 'easeOutExpo',
                duration: duration,
                complete: endSwitchSectionTransition
             });

            break;

         default:
            break;
    }

    windowResize();

    var sec_nav_new = in_div.find('.secondaryNavigationInner');
    if (App.currentPage === App.lastPage) {
        if (sec_nav_new.length) {
            sec_nav_new.remove();
        }
        App.events.subnavemptied.dispatch();
        App.events.subnavtransitioned.dispatch();

    } else {
        $('#secondaryNavigation').fadeOut(400, function(){
            var $el = $(this);
            $el.css('left','-600px').empty();

            App.events.subnavemptied.dispatch();

            $el.append(sec_nav_new)
                .show(0, function(){
                    $(this).animate({left:'0'}, {
                        duration: 400,
                        complete: function() {
                            App.events.subnavtransitioned.dispatch();
                        }
                    });
                });
        });
    }
}

function endSwitchSectionTransition() {
  App.events.endsectiontransition.dispatch();
  App.oldQueue.length && App.oldQueue.shift().remove();
  $('.currentContent').css('overflow', 'hidden').css('overflow-y', 'auto');
  preloadAll();
  // Namespace the body element
  $('body').removeClass().addClass(App.currentPage.split('/').pop());
};


/**** WORK / FAMILY *********************************************************/
function randomizeFadeIn(images) {
  var max = 1800, c = 0, sub = [];
  while (images.length) {
    sub[c++] = images.splice(0, 10).sort(function(){
      return 0.5 - Math.random();
    });
  };
  for (c in sub) (function(sub, c){
    setTimeout(function(){
      $.each(sub, function(i, value){
        setTimeout(function(){
          $(value)
            .css('opacity', 0)
            .css('display', 'inline')
            .animate({opacity: 1}, 'slow');
        }, Math.min(i * 150, max));
      });
    }, c * 100);
  })(sub[c], c);
  return max;
};

/****************************************************************************/
/**** CALLBACK FUNCTIONS ****************************************************/
/****************************************************************************/

function isIOS() {
  return !!navigator.userAgent.match(/iPad|iPhone|Mobile Safari/i);
};

function isIPAD() {
  return !!navigator.userAgent.match(/iPad/i);
}

function isIPHONE() {
  return !!navigator.userAgent.match(/iPhone/i);
}

// function centerLogo() {
//   var logo = $('#logo-splash');
//   logo.css({
//     'margin-left': logo.width() / 2 * -1 + 'px',
//     'margin-top': logo.height() / 2 * -1 + 'px'
//   });
// };

/**** HOME ****************************/
function homeCallback() {

  // Resize Handler
  // $(window).resize(centerLogo);
  // 
  // centerLogo();

  

  // Fix looping for firefox
  $('video').bind('ended', function(){
    this.play();
  });

  // Fire on next switch section
  App.events.onswitchsection.addOnce(function() {
      $(window).unbind('resize');
  });

  $('.splashScreen').css('opacity', 1);
}

/**** ABOUT ***************************/
function aboutCallback() {
  updateMainNavigation('about');

  var subpage = window.location.href.split('/').pop();
  updateSecondaryNavigation(subpage);

  var $links = $('.lt, .gt').hide();
  App.events.endsectiontransition.addOnce(function(){
    $links.fadeIn();
  });
}

/**** WORK ****************************/
function workCallback(skip_fade) {
    updateMainNavigation('work');

    var obj_cont = $('.currentContent .contentInner.work');
    var contentWrapper = $('.currentContent');
    var styled_a = $('.styledDropdown a');

    var thumbnails = $('.thumbnail', obj_cont),
        thumbnails_fade_a = [];

    var isotope_init = false;

    thumbnails.each(function(idx) {
        var el = $(this);
        el.css('opacity', 0);
        thumbnails_fade_a.push(el);
    });

    // Resize Handler
    var contentWidth;
    var onPageResize = function(skip_computation) {
        var newContentWidth = $(window).width();
        obj_cont.width(newContentWidth+20);
        if (newContentWidth == contentWidth) {
            return;
        }
        contentWidth = newContentWidth;

        var numThumbs = Math.ceil(contentWidth/210);
        var thumbnailSide = contentWidth/numThumbs;

        thumbnails.css({
            'width': thumbnailSide,
            'height': thumbnailSide
        });
        if (isotope_init) {
          obj_cont.isotope('reLayout');
        }
    };
    $(window).bind('resize', onPageResize);
    onPageResize();

    var curr_filters = {
        industries: '',
        media: ''
    };

    var isoOpts = {
        getSortData: {
            searchfilter: function($elem) {
                return $elem.hasClass('isoactive') ? 0 : 1;
            }
        }
    };

    var max_timeout = randomizeFadeIn(thumbnails_fade_a);

    setTimeout(function() {
        thumbnails.css('opacity', 1);
        App.clearOld = true;
        //$('.dropdown_lnk').styleDropdowns();
    }, max_timeout);

    App.events.endsectiontransition.addOnce(function() {

        // Fire on next switch section
        App.events.endsectiontransition.addOnce(function() {
            $(window).unbind('resize', onPageResize);
            if (isotope_init) {
                // Currently not removing because of an IE 8
                // isotope/jquery positioning bug on destroy
                //obj_cont.isotope('destroy');
            }

            // If uncommented, safari will clear the header on next section. wtf
            //$('#header_bg_content').empty();
        });
    });

    styled_a.bind('click', function() {
        var self = $(this);
        var filter = self.attr('data-filter');

        // parent().parent() is the containing ul
        var id = self.parent().parent().attr('id').substr(5);

        curr_filters[id] = filter;

        $('#ft_'+id)
            .text(self.text()+'  X')
            .css({
                'display': 'block',
                'visibility': 'visible'
            });

        processFilterHeaderPositions();

        filterFunc();
    });

    $('.filled_tab').bind('click', function() {
        var id = this.id.slice(3);

        curr_filters[id] = '';
        $(this).fadeOut(400, function() {
            processFilterHeaderPositions();
        });

        filterFunc();
    });

    var processFilterHeaderPositions = function() {
        var leftMargin = 0;

        // If only the second filter is active, align it to the menu hit button
        if (!curr_filters.industries) {
            leftMargin = $('#hit_media').position().left + 8;
        } else {
            leftMargin = 0;
        }

        $('#ft_media').css('margin-left', leftMargin);
    };

    var filterFunc = function() {
        var filter = curr_filters.industries+curr_filters.media;
        var is_empty = !(curr_filters.industries || curr_filters.media);

        thumbnails.removeClass('isoactive');

        setTimeout(function() {
            onPageResize(true);

            if (is_empty) {
                $('.filled_tab_cont').css('display', 'none');

                obj_cont.isotope({
                    sortBy: '*'
                });

            } else {
                $('.filled_tab_cont').css('display', 'block');

                obj_cont.find(filter).addClass('isoactive');
                obj_cont.isotope('updateSortData', thumbnails);
                obj_cont.isotope({
                    sortBy: 'searchfilter'
                });
            }

            contentWrapper.scrollTop(0);
        }, 25);
    };

    // check for link from office
    var hash = window.location.hash.split('/');
    var hash_sel_el;
    var hash_cont_el;
    if (hash.length === 3) {
        var filter = hash.pop();

        if (filter) {
            isoOpts.sortBy = 'searchfilter';

            obj_cont.find('.'+filter).addClass('isoactive');

            if (/industry/.test(filter)) {
                hash_sel_el = $('#ft_industries');
                hash_cont_el = $('#cont_industries');
                curr_filters.industries = '.'+filter;
            } else {
                hash_sel_el = $('#ft_media');
                hash_cont_el = $('#cont_media');
                curr_filters.media = '.'+filter;
            }
        }
    }

    App.events.subnavtransitioned.addOnce(function() {
        var headerBGContent = $('#header_bg_content');
        headerBGContent.empty();
        $('#secondaryNavigationCont').detach().appendTo(headerBGContent);
        $('.dropdown_lnk').styleDropdowns();
        if (hash_sel_el) {
            $('.filled_tab_cont').css('display', 'block');

            processFilterHeaderPositions();

            hash_sel_el
                .text(hash_cont_el.find('[data-filter=".'+filter+'"]').text()+'  X')
                .hide()
                .fadeIn('slow');
        }
    });

    isoOpts.sortBy = 'searchfilter';
    obj_cont.isotope(isoOpts);
    obj_cont.isotope('updateSortData', thumbnails);
    isotope_init = true;
}
/**** Work List View ******************/
function workListCallback() {
  updateMainNavigation('work');

  var obj_cont = $('.contentInner.workList');
  var contentWrapper = $('.currentContent');
  var styled_a = $('.styledDropdown a');
  var work_items = $('.work-itm');

  $('ul li a','.contentInner.workList').hover(function(){
    var url = $(this).attr('rel');
    var itemId = $(this).attr('id');
    var selector = '#backgroundImage' + itemId;
    $(selector).addClass('active');
  }, function() {
    $('.active','.contentInner.workList').removeClass('active');
  });

  styled_a.bind('click', function(ev) {
      ev.preventDefault();

      var self = $(this);
      var filter = self.attr('data-filter');
      // parent().parent() is the containing ul
      var id = self.parent().parent().attr('id').substr(5);

      $('.filled_tab').css('display', 'none');
      $('.filled_tab_cont').css('display', 'block');
      $('#ft_'+id)
          .text(self.text()+'  X')
          .css('display', 'block');

      work_items.hide();
      obj_cont.find(filter).show();

  });

  $('.filled_tab').bind('click', function() {
      $('.filled_tab').css('display', 'none');

      work_items.show();
  });

  App.events.subnavtransitioned.addOnce(function() {
      $('#header_bg_content').empty();
      $('#secondaryNavigationCont').detach().appendTo($('#header_bg_content'));
      $('.dropdown_lnk').styleDropdowns();
  });
}

/**** Work Single View ****************/
function workSingleCallback(){
    updateMainNavigation('work');

    $('.center .i').load(function(){
        $(this).css('opacity',1);
    });

    $('.info').click(function(ev){
        ev.preventDefault();

        $('.left').toggleClass('active');
    });

    $('.workSingle .i').load(function(){
      $(this).css('opacity', 1);
    });

    $('a.videoControls').click(function(){
        var video = $(this).prev('video').get(0);
        var timer;
        var test;

        // Play the video if it is paused
        if (video.paused === true) {
            video.play();
            $(this).addClass('playing');

            test = $(document).bind('mousemove',function() {
                if (timer) {
                    clearTimeout(timer);
                    timer = 0;
                }
                $('a.videoControls').removeClass('hidden');

                timer = setTimeout(function() {
                    $('a.videoControls').addClass('hidden');
                }, 500);
            });

        } else {
            clearTimeout(timer);
            $(test).unbind('mousemove');
            $('a.videoControls').removeClass('hidden');
            video.pause();
            $(this).removeClass('playing');
        }

        return false;
    });

    var $links = $('.lt, .gt').hide();
    App.events.endsectiontransition.addOnce(function(){
      $links.fadeIn();
    });
}

/**** FAMILY **************************/
function familyCallback() {
    updateMainNavigation('family');

    var obj_cont = $('.currentContent .contentInner.family');
    var contentWrapper = $('.currentContent');

    var thumbnails = $('.thumbnail', obj_cont),
        thumbnails_fade_a = [];

    var isotope_init = false;

    thumbnails.each(function(idx) {
        var el = $(this);
        el.css('opacity', 0);
        thumbnails_fade_a.push(el);
    });

    // Resize Handler
    var contentWidth;
    var onPageResize = function(skip_computation) {
        var newContentWidth = $(window).width();
        obj_cont.width(newContentWidth+20);
        if (newContentWidth == contentWidth) {
            return;
        }
        contentWidth = newContentWidth;

        var numThumbs = Math.ceil(contentWidth/210);
        var thumbnailSide = contentWidth/numThumbs;

        thumbnails.css({
            'width': thumbnailSide,
            'height': thumbnailSide
        });
        if (isotope_init) {
            obj_cont.isotope('reLayout');
        }
    };
    $(window).bind('resize', onPageResize);
    onPageResize();

    var curr_filters = {
        offices: '',
        departments: ''
    };

    var isoOpts = {
        getSortData: {
            searchfilter: function($elem) {
                return $elem.hasClass('isoactive') ? 0 : 1;
            }
        }
    };

    var onFirstMouseOver = function(a){
        var el = $(this),
            data = el.data(),
            frame_el;

        if (!data.is_init) {
            el.data('is_init', true);

            for (var n = 1; n <= 3; n++) {
                frame_el = el.find('.anim_frame'+n);
                frame_el
                    .css('background-image', 'url('+frame_el.text()+')')
                    .html('');
            }
        }
    };

    var bgCheckCallback = function() {
        if (App.currentPage === 'family-single') {
            // Add background for individual family members
            var bgs = obj_cont.clone(true);
            bgs.css({
                'overflow-x': 'hidden',
                'overflow-y': 'hidden',
                'height': $('#content').height()
            });
            bgs.appendTo($('#fam_bg'));
            $('#fam_bg .thumbnail').each(function(){
              if (parseInt($(this).css('top')) > $(window).height()) {
                $(this).remove();
              };
            });
            //$('#fam_bg .thumbnail .frame:not(.anim_frame0)').remove();
        } else {
            App.events.onswitchsection.remove(bgCheckCallback);
            setTimeout(function() {
              $('#fam_bg').empty();
            }, 1500);
        }
    };
    App.events.onswitchsection.add(bgCheckCallback);

    var max_timeout = randomizeFadeIn(thumbnails_fade_a);

    setTimeout(function() {
        thumbnails.css('opacity', 1);
        App.clearOld = true;
    }, max_timeout);

    App.events.endsectiontransition.addOnce(function() {

        // Fire on next switch section
        App.events.endsectiontransition.addOnce(function() {
            $(window).unbind('resize', onPageResize);
            if (isotope_init) {
                // Currently not removing because of an IE 8
                // isotope/jquery positioning bug on destroy
                //obj_cont.isotope('destroy');
            }
        });
    });

    obj_cont.AnimateBackgrounds({
        onFirstMouseOver: onFirstMouseOver
    });

    $('.styledDropdown a').bind('click', function() {
        App.animationLock = true;

        var self = $(this);
        var filter = self.attr('data-filter');
        // parent().parent() is the containing ul
        var id = self.parent().parent().attr('id').substr(5);

        curr_filters[id] = filter;

        $('#ft_'+id)
            .text(self.text()+'  X')
            .css('display', 'block');

        processFilterHeaderPositions();

        filterFunc();
    });

    $('.filled_tab').bind('click', function() {
        var id = this.id.slice(3);

        curr_filters[id] = '';
        $(this).fadeOut(400, function() {
            processFilterHeaderPositions();
        });

        filterFunc();
    });

    var processFilterHeaderPositions = function() {
        var leftMargin = 0;

        // If only the second filter is active, align it to the menu hit button
        if (!curr_filters.offices) {
            leftMargin = $('#hit_departments').position().left + 8;
        } else {
            leftMargin = 0;
        }

        $('#ft_departments').css('margin-left', leftMargin);
    };

    var filterFunc = function() {
        var filter = curr_filters.offices+curr_filters.departments;
        var is_empty = !(curr_filters.offices || curr_filters.departments);

        // reset each active thumbnail to grey thumb
        obj_cont.find('.isoactive').each(function() {
            var el = $(this);

            el.find('.frame').css('display', 'none');
            el.find('.anim_frame0').css('display', 'block');
            el.removeClass('isoactive');
        });

        onPageResize();

        if (is_empty) {
            $('.filled_tab_cont').css('display', 'none');

            obj_cont.isotope({
                sortBy: '*'
            });

        } else {
            $('.filled_tab_cont').css('display', 'block');

            obj_cont.find(filter).addClass('isoactive').each(function() {
                var el = $(this);
                // Preload thumbs
                onFirstMouseOver.call(this);

                el.find('.frame').css('display', 'none');
                el.find('.anim_frame1').css('display', 'block');
            });
            obj_cont.isotope('updateSortData', thumbnails);
            obj_cont.isotope({
                sortBy: 'searchfilter'
            });
        }

        contentWrapper.scrollTop(0);

        // this is a dumb hack, but isotope doesn't have an event callback system
        setTimeout(function() {
            App.animationLock = false;
        }, 600);
    };

    // check for link from office
    var hash = window.location.hash.split('/');
    if (hash.length === 3) {
        var filter = hash.pop();
        var hash_sel_el;
        var hash_cont_el;

        if (filter) {
            isoOpts.sortBy = 'searchfilter';
            obj_cont.find('.'+filter).addClass('isoactive').each(function() {
                var el = $(this);
                // Preload thumbs
                onFirstMouseOver.call(el);

                el.find('.frame').css('display', 'none');
                el.find('.anim_frame1').css('display', 'block');
            });

            if (/city/.test(filter)) {
                hash_sel_el = $('#ft_offices');
                hash_cont_el = $('#cont_offices');
            } else {
                hash_sel_el = $('#ft_departments');
                hash_cont_el = $('#cont_departments');
            }
        }
    }

    App.events.subnavtransitioned.addOnce(function() {
        var headerBGContent = $('#header_bg_content');
        headerBGContent.empty();
        $('#secondaryNavigationCont').detach().appendTo(headerBGContent);
        $('.dropdown_lnk').styleDropdowns();
        if (hash_sel_el) {
            $('.filled_tab_cont').css('display', 'block');

            processFilterHeaderPositions();

            hash_sel_el
                .text(hash_cont_el.find('[data-filter=".'+filter+'"]').text()+'  X')
                .hide()
                .fadeIn('slow');
        }
    });

    obj_cont.isotope(isoOpts);
    isotope_init = true;
}

/**** FAMILY SINGLE *******************/

function familySingleCallback() {
    updateMainNavigation('family');

    $('.hidden_images img').imagesLoaded(function() {
        $('.right').css('visibility','visible');
    });

    var intervalId;
    var intervalIdx = 1;
    var imgCont = $('.hidden_images');

    $('.playpause').toggle(function() {
        var self = $(this);
        self.addClass('playing');
        intervalId = setInterval(function() {
            imgCont.find('.image'+intervalIdx).css('display', 'none');
            if (++intervalIdx > 3) {
                intervalIdx = 1;
            }
            imgCont.find('.image'+intervalIdx).css('display', 'block');
        }, 400);

    }, function() {
        var self = $(this);
        self.removeClass('playing');

        clearInterval(intervalId);
        imgCont.find('.image'+intervalIdx).css('display', 'none');
        imgCont.find('.image1').css('display', 'block');

    });

    var $links = $('.lt, .gt').hide();
    App.events.endsectiontransition.addOnce(function(){
      $links.fadeIn();
    });
}


/**** FRIENDS *************************/
function friendsCallback() {

    var friend_bgs = $('.friend_background');

    updateMainNavigation('friends');

    $('#friendList').delegate('a', {
        'mouseover': function(){
            var selected_friend = $(this).attr('id').substr(7);

            friend_bgs.removeClass('active');
            $('#friend_bg_'+selected_friend).addClass('active');

        },
        'mouseout': function(){
            friend_bgs.removeClass('active');
        },
        'click': function(ev){
            var selected_friend = $(this).attr('id').substr(7);

            ev.preventDefault();

            $('.left').removeClass('active');
            $('#descr_'+selected_friend).addClass('active');
        }
    });

    $('.close').click(function(ev){
        ev.preventDefault();
        $(this).parent().parent().removeClass('active');
    });

    $('.info').click(function(){
      $('.active').removeClass('active');
      $('.friendsInfo').addClass('active');
      return false;
    });
}

/**** Friend **************************/
function friendCallback() {
  var friend_bgs = $('.friend_background');

  updateMainNavigation('friends');

  $('#friendList').delegate('a', {
      'mouseover': function(){
          var selected_friend = $(this).attr('id').substr(7);

          friend_bgs.removeClass('active');
          $('#friend_bg_'+selected_friend).addClass('active');

      },
      'mouseout': function(){
          friend_bgs.removeClass('active');
      },
      'click': function(ev){
          var selected_friend = $(this).attr('id').substr(7);

          ev.preventDefault();

          $('.left').removeClass('active');
          $('#descr_'+selected_friend).addClass('active');
      }
  });

  $('.close').click(function(ev){
      ev.preventDefault();
      $(this).parent().parent().removeClass('active');
  });

  $('.info').click(function(){
    $('.active').removeClass('active');
    $('.friendsInfo').addClass('active');
    return false;
  });
}

/**** CONTACT *************************/
function contactsCallback() {
    updateMainNavigation('offices');

    $('.cities a,.interpartners a').each(function(){
      var image = $('#' + $(this).attr('escaped_url'));
      $(this).hover(function(){
        image.addClass('current');
      }, function(){
        image.removeClass('current');
      });
    });

    $('.info').click(function(){
        $('.infoButton').removeClass('active');
        $('.infoInfo').addClass('active');
        return false;
    });

    $('.close').click(function(){
        $('.infoButton').addClass('active');
        $('.infoInfo').removeClass('active');
        return false;
    });

    App.events.onswitchsection.addOnce(function(){
      $('.background_images img:not(#main_background)').remove();
    });

		$(window).load(function(){
			windowResize();
		});
}

/**** CONTACT DETAIL ******************/
function initializeMap() {
    App.gmapIsLoaded = true;
    var map,
        par_el = $(".currentContent"),
        lat = par_el.find('.c-latitude').text(),
        lng = par_el.find('.c-longitude').text(),
        pindrop_logo = par_el.find('.pindrop_logo').text(),
        mapLatLng = new google.maps.LatLng(lat, lng),
        map_canvas_el = $('.currentContent .map_canvas'),
        map_canvas_id = map_canvas_el.attr('id'),
        stylez = [
            {
                featureType: "all",
                elementType: "all",
                stylers: [
                    { saturation: -100 }
                ]
            }
        ],
        mapOptions = {
            zoom: 16,
            center: mapLatLng,
            disableDefaultUI: true,
            mapTypeControlOptions: {
                 mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'tehgrayz']
            }
        };

		function setMapHeight() {
		  var height = $('.currentContent .left').height();
			$('.currentContent .map_canvas').height(height);
		};
		$(window).resize(setMapHeight); setMapHeight();

    map = new google.maps.Map(document.getElementById(map_canvas_id), mapOptions);
    var mapType = new google.maps.StyledMapType(stylez, { name:"Grayscale" });
    map.mapTypes.set('tehgrayz', mapType);
    map.setMapTypeId('tehgrayz');

    //var markerLatLng = new google.maps.LatLng(lat, lng);
    var markerImg = new google.maps.MarkerImage(pindrop_logo);
    var marker = new google.maps.Marker({
         position: mapLatLng,
         title:"Hello World!",
         icon: markerImg
    });

    // To add the marker to the map, call setMap();
    marker.setMap(map);
    App.events.onswitchsection.addOnce(function() {
        //map_canvas_el.empty().remove();
    });

    // Pan the map to the right to make the marker off-center
    map.panBy(-200,0);

    // var image = 'beachflag.png';
    //  var myLatLng = new google.maps.LatLng(-33.890542, 151.274856);
    //  var beachMarker = new google.maps.Marker({
    //      position: myLatLng,
    //      map: map,
    //      icon: image
    //  });
    // https://s3.amazonaws.com/data.verbcms.com/f2b440fda9b5be72e29832f4b8a6888970bb641f.png
    //map_canvas_el.hide();


    $('.viewMap').click(function(){
      setMapHeight();
      if (map_canvas_el.css('visibility') == 'visible') {
        $(this).html('View Map');
        $('.contentInner.contact .left').removeClass('active');
        $('.contentInner.contact form').removeClass('active');
        map_canvas_el.css('visibility','hidden');
      }
      else {
        $(this).html('Hide Map');
        map_canvas_el.css('visibility','visible');
        $('.contentInner.contact .left').addClass('active');
        $('.contentInner.contact form').addClass('active');
      }
      return false;
    });

    // 'see Map' link from Careers section is clicked
    if (App.showMap) {
      map_canvas_el.css('visibility', 'visible');
      $('.contentInner.contact .left').addClass('active');
      $('.contentInner.contact form').addClass('active');
      App.showMap = false;
    }

    if (map_canvas_el.css('visibility') == 'visible') {
      $('.viewMap').html('Hide Map');
    }
}

function contactDetailCallback() {
    updateMainNavigation('offices');

    if (false === App.gmapIsLoaded) {
        var script = document.createElement("script");
          script.type = "text/javascript";
          script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initializeMap";
          document.body.appendChild(script);
    } else {
        initializeMap();
    }

    var form = $('.currentContent #requestForm');
    form_height = form.height();
    form.css({
        'opacity': 0//,
        // 'bottom': -form_height
    });

    var form_open = false;
    $('.requestForCaseStudyMeeting').click(function() {
        if (!form_open) {
            form.animate({
                'opacity': 1//,
                // 'bottom': 0
            });
        } else {
            form.animate({
                'opacity': 0//,
                // 'bottom': "-="+form_height
            });
        }

        form_open = !form_open;
        return false;
    });

    form.bind('submit',function(ev){
        ev.preventDefault();
        var $el = $(this);

        form.animate({
            'opacity': 0//,
            // 'bottom': -form_height
        });
        form_open = false;

        var data_serial = $el.serializeArray();
        var data  = {};
        jQuery.each(data_serial, function(i, field) {
            var k = field.name;
            data[k] = field.value;
        });

        $.ajax({
            type: 'POST',
            url: $el.attr('action'),
            data: data,
            success: function() {}
        });
    });

    $('label[for="case-study"], label[for="meeting"], label[for="brand-epic"]').click(function(){
        var id = $(this).attr('for');
        var selector = '#' + id;
        var check = $(selector).prop('checked');
        selector = '.' + id + '-check';
        if(!check) {
            $(selector).html('&times;');
        } else {
            $(selector).html(' &nbsp; ');
        }
    });

    $('.gt,.lt').click(function() {
        if ($('.map_canvas').css('visibility') == 'visible') {
            App.showMap = true;
        }
    });

    var $links = $('.lt, .gt').hide();
    App.events.endsectiontransition.addOnce(function(){
      $links.fadeIn();
    });
}

/**** CAREERS *************************/
function careersCallback() {
    updateMainNavigation('career');

    // $('.right').hide().load('career-feed?view-by=city');

    // make the .right div extend all the way down to the end of the screen.
    var careersRightHeight = $('.careersRight').parent().height();    
    $('.careersRight').css('min-height',careersRightHeight);
    
    

    App.events.endsectiontransition.addOnce(function(){
      $('.right').show();
    });

    switch(App.careerActiveMenu) {
      case "city":
        $('.city','.viewBy').addClass('active');
        $('.cityList').addClass('active');
        break;

      case 'department':
        $('.department','.viewBy').addClass('active');
        $('.departmentList').addClass('active');
        break;

      default:
        break;
    }


    $('a.active','.viewBy').live('click',function(ev){
      ev.preventDefault();
      $(this).addClass('active');
    });

    $('a.city','.viewBy').live('click',function(ev){
      App.careerActiveMenu = 'city';
      ev.preventDefault();
      $(this).addClass('active');
      $('.right').removeClass('visible');
      $('.city,.cityList').addClass('active');
      $('.department,.departmentList,.departmentList a').removeClass('active');

      $('.contentInner.career .right').removeClass('visible');
    });


    $('a.department','.viewBy').live('click',function(ev){
      App.careerActiveMenu = 'department';
      ev.preventDefault();
      $('.right').removeClass('visible');
      $('.department,.departmentList').addClass('active');
      $('.city,.cityList,.cityList a').removeClass('active');

      $('.contentInner.career .right').removeClass('visible');
    });

    $('.cityList a').click(function(ev){
        ev.preventDefault();

        $('.departmentList a').removeClass('active');
        $('.cityList a').removeClass('active');

        $(this).addClass('active');

        var url = $(this).attr('href');
        $('.right').load(url,function(){
            $('.contentInner.careers .right').addClass('visible');
        });
    });

    $('.departmentList a').click(function(ev){
        ev.preventDefault();

        $('.contentInner.career .right').removeClass('active');
        $('.departmentList a').removeClass('active');
        $('.cityList a').removeClass('active');

        $(this).addClass('active');

        var url = $(this).attr('href');
        $('.right').load(url,function(){
          $('.contentInner.careers .right').addClass('visible');
        });
    });

    // $('a.availablePosition','.right').live('click',function(){
    //   var url = $(this).attr('href');
    //   $('.right').load(url,function(){
    //     $('.right').addClass('visible');
    //   });
    //   return false;
    // });
}
/**** CAREER **************************/
function careerCallback() {
  updateMainNavigation('career');

  // make the .right div extend all the way down to the end of the screen.
  var current_content_height = $('.currentContent').height();    

  $('.careersRight').css('min-height',current_content_height);

  switch(App.careerActiveMenu) {
    case "city":
      $('.city','.viewBy').addClass('active');
      $('.cityList').addClass('active');
      break;

    case 'department':
      $('.department','.viewBy').addClass('active');
      $('.departmentList').addClass('active');
      break;

    default:
      break;
  }

  $('a.active','.viewBy').live('click',function(){
    $(this).addClass('active');

    return false;
  });

  $('a.city','.viewBy').live('click',function(){
    App.careerActiveMenu = 'city';

    $(this).addClass('active');
    $('.right').removeClass('active');
    $('.city,.cityList').addClass('active');
    $('.department,.departmentList,.departmentList a').removeClass('active');

    $('.contentInner.career .right').removeClass('active');

    return false;
  });


  $('a.department','.viewBy').live('click',function(){
    App.careerActiveMenu = 'department';

    $('.right').removeClass('active');
    $('.department,.departmentList').addClass('active');
    $('.city,.cityList,.cityList a').removeClass('active');

    $('.contentInner.career .right').removeClass('active');

    return false;
  });



  $('.cityList a').click(function(){

    $('.departmentList a').removeClass('active');
    $('.cityList a').removeClass('active');

    $(this).addClass('active');

    var url = $(this).attr('href');
    $('.right').load(url,function(){
      $('.contentInner.career .right').addClass('active');
    });
    return false;
  });

  $('.departmentList a').click(function(){
      $('.contentInner.career .right').removeClass('active');
    $('.departmentList a').removeClass('active');
    $('.cityList a').removeClass('active');

    $(this).addClass('active');

    var url = $(this).attr('href');
    $('.right').load(url,function(){
      $('.contentInner.career .right').addClass('active');
    });
    return false;
  });

  $('.right').addClass('active');
}

function sitemapCallback() {
    updateMainNavigation('siteMap');
}

/**** Navigation Functions **************************************************/
function updateMainNavigation(page) {
  $('a.current').removeClass('current');
  $('a.' + page).addClass('current');
}

function updateSecondaryNavigation(subpage) {
  $('a.current','#secondaryNavigation').removeClass('current');
  $('a.' + subpage).addClass('current');
}

