/*
----------------------------------------------------------------------
Global JavaScript & jQuery

Target Browsers: IE7, IE8, Firefox 3.6+, Safari 4+, IPAD
Authors: Angela Norlen, Dan Z, Jeremy Carlson
------------------------------------------------------------------------ */

var NERD = NERD || {};

$(function() {
    
    NERD.ExternalLinks.init();
    
   if(('.basic=form select')) {
    $('.basic-form select').addClass('styled');  
   }

    var cf = new CustomFormElements({});
	
	checkCarousel.init();
	checkHeaderSlideshow.init();
	openCarouselMedia.init();
	tooltips.init();
	customSelectLists.init();
	verticalCarouselAnimations.init();
	locationsMap.init();
	
	checkNavSidebar.init();
	checkUKEntries.init();
  languageSelector.init();
  paginationCheck.init();
  lastServiceCategory.init();

  $(document).ready(function() {
    caseStudyFinder.init();
  });
    
});


/* ---------------------------------------------------------------------
ExternalLinks
Author: Nerdery Boilerplate

Launches links with a rel="external" in a new window
------------------------------------------------------------------------ */

NERD.ExternalLinks = {
    init: function() {
        $('a[rel=external]').attr('target', '_blank');
    }
};


/* ---------------------------------------------------------------------
lastServiceCategory
Author: Angela Norlen

Removes extra lines on last items of each of the categories list on case 
studies pages.
------------------------------------------------------------------------ */

var lastServiceCategory =  {
    init: function() {

        if ($('.categories').length !==0) {
            $('.categories').each(function(index) {
                $(this).children('li').last().addClass('last');  
            });
        }
    }
}

/* ---------------------------------------------------------------------
checkNavSidebar
Author: Angela Norlen

Removes extra lines on previous list item link for 4 levels of sidebar navigation
------------------------------------------------------------------------ */

var checkNavSidebar = {
    
  init:function() {  
      
      var navLevel1 = $('.level-1');
      var navLevel2 = $('.level-2');

      if (navLevel2.hasClass('active')) {
          $('.level-2.active').prev('li').css('background' , 'none');
          $('.level-2.active:first-child').parents('.parent-active').children('a').css('background' , 'none');
      } 
      
      if (navLevel2.hasClass('parent-active')) {
          $('.level-2.parent-active').prev('li').children('a').css('background' , 'none');
      }
      
      if ($('.level-1:first-child').hasClass('active')) { 
          $('.level-1.active').parents('.nav-sub-level-1').siblings('.nav-level-1').css('background' , 'none'); 
            
      } else if (navLevel1.hasClass('active')) {
          $('.level-1.active').prev(navLevel1).children('a').css('background' , 'none'); 
          
      } else {}
  }  
}

/* ---------------------------------------------------------------------
checkUKEntries
Author: Angela Norlen

Arranges pages once cookies have been accepted on UK homepage to properly 
display a third blog entry instead of the cookies feature.

------------------------------------------------------------------------ */

var checkUKEntries = {
    init:function() {
        if ($('.uk-home .info-feature').length !==0) {
            $('.uk-home .callout:nth-child(3)').addClass('last');
            $('.uk-home .callout:last').addClass('hidden');
        } else {
            $('.uk-home .callout:nth-child(3)').addClass('last');
        } 
    }
}

/* ---------------------------------------------------------------------
checkCarousel
Author: Third Party / Roundabout

Sets up carousel of images and checks to see if it should show 3 or 5 based on page class
------------------------------------------------------------------------ */
var checkCarousel = {
	init:function() {
    var $imgroundabout = $("#imgroundabout");
		if ($('#imgroundabout li').length > 2) {

      /*if ($('#imgroundabout li').length < 7) {
          var shape = 'threeOnly';
      } else {
        // check to see if we're on a services page
        if($('#imgroundabout li').parents('div.content.three-col')) {
          var shape = 'threeOnly';
        } else {
          var shape = 'lazySusan';
        }  
      }*/

      // show big carousel if we have 7 or more items and we're not on a three-col layout
      if ($('#imgroundabout li').length > 6
          && !$('#imgroundabout li').parents('div.content.three-col').length) {
          var shape = 'lazySusan';
      } else {
          var shape = 'threeOnly';
      }

			$imgroundabout.roundabout({
	            minScale: 0.3,
	            maxScale: 1.00,
	            bearing: 1,
	            tilt: 0,
	            minOpacity: 1.0,
				      shape: shape,
	            btnNext: '.next',
	            btnPrev: '.prev',
	            reflect: true
	           
	        });
           // SETUP IPAD SWIPE
          function swipeStatus(event, phase, direction, distance)
          {
            if (phase=="end") {
              if (direction == "right")
                $(".prev").click();
              else if (direction == "left")     
                $(".next").click();
            }
          }
          
          var swipeOptions = {
            triggerOnTouchEnd: false,
            swipeStatus: swipeStatus,
            allowPageScroll: "vertical",
            threshold: 100,
            touches: 1
          };
          $imgroundabout.swipe(swipeOptions);
          
           /*
           $imgroundabout.wipetouch({
                tapToClick: true,
                //preventDefault: false,
                wipeLeft: function(result){
                    $('.next').click();
                },
                wipeRight: function(result){
                    $('.prev').click()
                }
           });
*/
           // WIPETOUCH HACK- the click event is passing to the wrong target.  redirect!
           /*
           $('.roundabout-in-focus img').live('click', function(){
                var p = $(this).parent();
                if (p.hasClass('video-modal')) return true; // video case studies don't link

                window.top.location = $(this).parent()[0].href;
           });
           $('.roundabout-in-focus .view').live('click', function(){
               var p = $(this).parent().parent();
               if (p.hasClass('video-modal')) return true; // video case studies don't link
               var linkLocation = p.attr('href');
               window.top.location = linkLocation;
               return false;
           });
*/
           // clear any offset issues- always start in focus
           $imgroundabout.roundabout_animateToChild(0);
		} else if ($("ul#imgroundabout li").length > 0) {
      if ( ! $imgroundabout.hasClass('static-images')) {
        $imgroundabout.addClass('roundabout-holder static-images roundabout-' + $("ul#imgroundabout li").length);
        $('.nav-media-controls.nav.carousel-controls').addClass('hidden');
      }
    } else {
      // hide carousel
      $('.carousel').addClass('hidden');
      $('.content-header').addClass('hidden');
      $('.nav-media-controls.nav.carousel-controls').addClass('hidden');
    }
	}
}

/* ---------------------------------------------------------------------
verticalCarousal
Author: Third Party / Roundabout / Dan Zdrazil

Vertical carousel animations
------------------------------------------------------------------------ */

var verticalCarouselAnimations =  {
    init:function() {
       $('.career-carousel').css({position:'relative'});
       if( $('.career-carousel').length === 0) {
           return;
       }
       $('.media-items li').css({margin:'0',padding:'0'});
       mediaItemsAnimations.beforeOpen = function(){$('.media-items li').each(function(index, element) {
                //if (index < 3) $(element).css('display', '');
                //else $(element).css('display', 'none');
                // IE 7 HACK- too many styles are getting lost somehwere in the animations...
                $('.media-visual').css({margin: '0px 0px 12px', lineHeight: '1', display:'block'});
            });
        };
        mediaItemsAnimations.beforeClose = function(){$('.media-items li').each(function(index,element){
                //$(element).css('display', '');
                // /$('.media-items').height(343);
            });  
        };
        $('.career-carousel.media-items a').live('click', function() {
            var index = $('.media-items li').index($(this).parents('li'));
            switch (index) {
                case 0: 
                    verticalCarouselAnimations.previous(); 
                    return false;
                case 1: 
                    mediaItemsAnimations.change($(this));
                    break;
                default: 
                    verticalCarouselAnimations.next(index - 2);
                    return false;
            }
            

            return false;
        });

        $('a.jcarousel-next').click(function(){
            verticalCarouselAnimations.next();
            return false;
        });
        $('a.jcarousel-prev').click(function(){
            verticalCarouselAnimations.previous();
            return false;
        });
           // SETUP IPAD SWIPE
          var swipeOptions = {
            triggerOnTouchEnd: false,
            swipeStatus: swipeStatus,
            allowPageScroll: "horizontal",
            threshold: 100,
            touches: 1
          };
          $('.career-carousel').swipe(swipeOptions);
          function swipeStatus(event, phase, direction, distance)
          {
            if (phase=="end") {
              if (direction == "up")
                $('.jcarousel-next').click()
              else if (direction == "down")     
                $('.jcarousel-prev').click();
            }
          }
           /*
           $('.career-carousel').wipetouch({
                tapToClick: true,
                preventDefault: false,
                wipeDown: function(result){
                    $('.jcarousel-prev').click();
                },
                wipeUp: function(result){
                    $('.jcarousel-next').click()
                }
           });
           */
        $('.media-items li:nth-child(2)').find('a').click();
    }
    , closeAnyOpen: function(ary) {
        $(ary).each(function(i,e){
            if ($(e).hasClass('active-media')) {
                 mediaItemsAnimations.change($(e).find('a'));//$(this).find('a').click();
            }
        });
    }
    , previous: function() {
        var promoList = $('.career-carousel');
        var lastLi = $(promoList).find('li:last');
        verticalCarouselAnimations.closeAnyOpen($(promoList).find('li'));

        $(lastLi).prependTo($(promoList)).animate({marginTop: '-62'},0);

        $(lastLi).stop(true,true).animate({'margin-top': '0'}, 350, function(){
            $('.media-items li:nth-child(2)').find('a').click();
        });
    }
    , next: function(depth) {
        depth = depth || 0;
        var promoList = $('.media-items');
        var firstLi = $(promoList).find('li:first');
        
        verticalCarouselAnimations.closeAnyOpen($(promoList).find('li'));
        $(firstLi).clone().appendTo($(promoList));
        $(firstLi).stop(true,true).animate({'margin-top': '-62'}, 350, 'linear', function(){
            $(firstLi).css('margin-top', function(prop){
                return prop ; 
            });
            $(firstLi).remove();
            if (depth--) {
                return verticalCarouselAnimations.next(depth);
            } else {
                $('.media-items li:nth-child(2)').find('a').click();
                return;
            }
        });
    }
}

var mediaItemsAnimations = {
    change: function(item) {

        var verticalContentHeight = $('.media-items').innerHeight();

        var linkParent = $(item).parents('li');
        
        if ( $(item).parents('li').children('.media-content').is(':visible') ) {
        
             linkParent.removeClass('active-media');
             mediaItemsAnimations.beforeClose();

             // $(item).parent('.media-caption').animate({
             //     top: '20px',
             //     height: '32px'
             // },200);
            
            linkParent.children('.media-content').stop(true,true).slideToggle(300, mediaItemsAnimations.afterClose);
        
        } else {
        
             linkParent.addClass('active-media');
             mediaItemsAnimations.beforeOpen();

             // $(item).parent('.media-caption').animate({
             //     top: 0,
             //     height: '32px'
             //     },200);

            linkParent.children('.media-content').stop(true,true).slideToggle();
        }
    }
    , afterClose: function(){}
    , afterOpen: function(){}
    , beforeOpen: function(){}
}

/* ---------------------------------------------------------------------
CheckHeaderSlideshow
Author: Third Party

Cycles through homepage slides in header
------------------------------------------------------------------------ */
var checkHeaderSlideshow = {
	init:function() { 
		if( $('.slideshow').length !==0) {
            // remove slides that don't apply
            $('.slideshow-homepage .slide.hidden').remove();

			checkHeaderSlideshow.bind();
		}
	},
		
		bind: function() {
		
		  var currentPosition = 0;
		  var slideWidth = 960;
		  var slides = $('.slide');
		  var numberOfSlides = slides.length;

		  // Remove scrollbar in JS
		  $('.slideshow-container').css('overflow', 'hidden');

		  // Wrap all .slides with #slideInner div
		  slides
		  .wrapAll('<div id="slideInner"></div>')
		  // Float left to display horizontally, readjust .slides width
		  .css({
		    'float' : 'left',
		    'width' : slideWidth
		  });

		  // Set #slideInner width equal to total width of all slides
		  $('#slideInner').css('width', slideWidth * numberOfSlides);

		  // Create event listeners for .controls clicks
		  $('.header-controls li span')
		    .bind('click', function(){
		    // Determine new position
		      currentPosition = ($(this).attr('id')=='rightControl')
		          ? currentPosition+1 : currentPosition-1;
              if (currentPosition < 0) currentPosition = numberOfSlides - 1;
              else if (currentPosition == numberOfSlides) currentPosition = 0;

		      // Move slideInner using margin-left
		      $('#slideInner').stop(true,true).animate({
		        'marginLeft' : slideWidth*(-currentPosition)
		      });
		    });

         // SETUP IPAD SWIPE
        var swipeOptions = {
          triggerOnTouchEnd: false,
          swipeStatus: swipeStatus,
          allowPageScroll: "vertical",
          threshold: 100,
          touches: 1
        };
        $('.slideshow-container').swipe(swipeOptions);
        function swipeStatus(event, phase, direction, distance)
        {
          if (phase=="end") {
            if (direction == "right")
              $("#leftControl").click();
            else if (direction == "left")     
              $("#rightControl").click();
          }
        }
         /*
         $('.slideshow-container').wipetouch({
              tapToClick: true,
              wipeLeft: function(result){
                  $('#rightControl').click();
              },
              wipeRight: function(result){
                  $('#leftControl').click()
              }
         });	
         */
         /*
         $('.slide .btn').live('click', function(){
            window.top.location = $(this).attr('href');
         });
         */
	}
}
// EXAMPLE USAGE: layouts.group/case-study-detail.php
var openCarouselMedia = {
	init:function() {
		if ($('.modal').length !== 0) {
			$('.video-modal').live("click" , function() {
				var relId = $(this).attr('rel');
        for (var i = 0; i < videoModalDetails.length; i++) {
        	var v = videoModalDetails[i];
        	if (v.rel == relId) {
        		var vid = v;
        		break;
        	}
        }
        if ( ! vid) {
        	var vid = v;
        }
        openCarouselMedia.updateModal(vid);
				$('.modal').dialog({
					width: '490',
					modal: 'true'
				});
				$('.close').click(function() {
					$('.modal').dialog('close');
                    flowplayer('video-player').stop();
                    return false;
				});

        if (! $(this).parents('li').hasClass('visited')) {
            $(this).parents('li').addClass('visited');
        }
				return false;
			});
		}
	},
    updateModal: function(video) {
        $('.modal h3.group-title').html(video.title);
        $('#video-player').attr('href',video.src);
        $('.modal p.video-desc').html(video.desc);
        flowplayer('video-player', $('.modal div.video-content').attr('rel'), {
        	clip: {
        		autoPlay: true
        	}
        }).ipad({
        	//simulateiDevice: true
        });
        flowplayer('video-player').play();
        if (video.ajaxURL) {
            jQuery.get(video.ajaxURL);

        }
    }
}

var tooltips = {
	init: function() {
		if($('.tooltip').length !==0) {
			$('.link-items li, .tooltip, .Blogger').hover(function() {
				$(this).children('.tooltip').show();
			}, function() {
				$('.tooltip').hide();
			});
		}
		
	}
}

var paginationCheck =  {
    init: function() {
        if ( $('.pagination').length !== 0 ) {
            var paginationPage = $('.pagination .active').text();
            var paginationTotal = $('.total-pages').text();
            $('.pagination li').each(function() {
                if ($(this).text() == '1') {
                   $('.ellipse1').hide(); 
                }
                if ($(this).text() == paginationTotal) {
                    $('.ellipse2').hide();
                }
            });
        }
    }
}

/* ---------------------------------------------------------------------
customSelectLists

Checks for custom selects with custom dropdowns and calls script (custom select dropdown)
**Form elements must have name and id attributes for this to behave properly
------------------------------------------------------------------------ */


var customSelectLists = {
    elements: null,
    init: function () {
        var self = this;
        if ($('select').length !== 0) {
            this.elements = $('.custom-select').sbCustomSelect();
            $('.sb-dropdown').die('focus');
        }
    }
};

/* ---------------------------------------------------------------------
CaseStudyFinder
Author: Angela Norlen Dan Zdrazil

Grabs category selected and industry selected and creates url for list of case studies
------------------------------------------------------------------------ */

var caseStudyFinder = {
    
    categoryUrl: undefined,
    industryUrl: undefined,
    caseStudyUrl: undefined,
    
    init: function() {
        $('input[readonly]').focus(function(){this.blur()});
        if( $('.case-studies-finder').length === 0) {
            return;
        }

        var self = this;

        // caching and save defaults
        self.categoryUrl =  $('#select-category').find(':selected').val();
        self.industryUrl =  $('#select-industry').find(':selected').val();
        self.caseStudyUrl = ctx.siteUrl + 'case-studies/' + self.categoryUrl;

        self.bind();
    },

    bind: function(){
        var self = this;

        $('#select-category').bind('change', function(e){
            self.categoryUrl = $(this).find(':selected').val();
        });

        $('#select-industry').bind('change', function(e){
            self.industryUrl = $(this).find(':selected').val();
        });

        $('#find-case-studies').bind('click', function() {

            // http://siteurl.com/path/case-studies/{categoryUrl}/industries/{industryUrl}/
            if (self.categoryUrl === 'all') {
                self.caseStudyUrl = ctx.siteUrl + 'case-studies/' + self.categoryUrl;
                if (self.industryUrl != 'all') {
                    self.caseStudyUrl += '/industries/' + self.industryUrl;
                }
            } else {
                var industrySegment = '';
                if (self.industryUrl != 'all') {
                    industrySegment = '/industries/' + self.industryUrl;
                }
                self.caseStudyUrl = ctx.siteUrl + 'case-studies/' + self.categoryUrl + industrySegment;
            }

            /*if(console.log)
            {
              console.log(self.caseStudyUrl);
            }*/

            // Note: window.top will pop the user out of an iframe if they are in.
            window.top.location = self.caseStudyUrl;
        });
    }    
};


/* ---------------------------------------------------------------------
Locations map
Author: Jeremy Carlson

Manages the offices and markers on the locations map
------------------------------------------------------------------------ */

var locationsMap = {
	init:function() { 
        if( $('.office-location').length === 0) {
            return;
        }

        // move markers
        locationsMap.setMarkers();

        // hide all offices to start
        locationsMap.hideOffices();

        // hide location nameplates
        locationsMap.hideNameplates();

        // get the default office
        var defaultLocation    = jQuery.trim($('#countries_default_location').text());

        // get the default country (for nav)
        var defaultCountry     = jQuery.trim($('#countries_default_country').text());

        // set the default country in nav
        $('.nav-sidebar ul.nav-sub-level-1 .level-1 li').each(
          function() {
            if(jQuery.trim($(this).text()) == defaultCountry)
            {
                $(this).addClass('active');
            }
        });

        // Client asked that this be disabled, can be removed
        // reveal the default nameplate and coordinate
        $('.location-name .location-content').each(
            function() {
                if(jQuery.trim($(this).text()) == defaultLocation)
                {
                    $(this).parent('.location-name').removeClass('hidden');
                    $(this).parents('.coordinate-container').addClass('active').addClass('placeholder');
                    //$(this).parents(coordinateWrap).addClass('placeholder');
                }
        });
        
        
        // reveal the default office location
        $('.media-items .media-caption').each(
            function() {
                if(jQuery.trim($(this).text()) == defaultLocation)
                {
                    $(this).parents('ul').removeClass('hidden');
                }
        });

        // toggle the office location
        $('.location-coordinates a.map-coordinate').live('click', 
            function() {
                var attrs   = $(this).parent('li').attr('rel').split('|');
                // hide "old" data
                locationsMap.hideOffices();
                locationsMap.hideNameplates();
                $('.section-location-map .location-coordinates li').removeClass('active').removeClass('placeholder');
                
                // show "new" data
                $(this).parent('li').addClass('active').addClass('placeholder');
                $('.media-items.office-location-' + attrs[3]).removeClass('hidden');

                return false;
        });

        // check to see if we're on a touch device. If so, skip the hover state, allow click to dominate
        if(!Modernizr.touch)
        {
            $('.map-coordinate').hover(function() {
                $('.placeholder').removeClass('active');
                $(this).parent('.coordinate-container').addClass('active');
            }, function() {
                $(this).parent('.coordinate-container').removeClass('active');
                
                /* Client requested to "have no location selected when user moves from one location to another"
                // only change if current item isn't the placeholder
                if(!$(this).parent('li').hasClass('placeholder'))
                {
                    $(this).parent('.coordinate-container').removeClass('active');
                    $('.placeholder').addClass('active');
                }*/
            });
        }
	},
		
	setMarkers: function() {
      var mapWidth   = parseInt($('.section-location-map').css('width'));

        // move markers, align location names to markers
		$('.coordinate-container a').each(
			function() {
				var attrs	= $(this).parent('li').attr('rel').split('|');

        // move markes
				$(this).css('left', attrs[0] - 7 + 'px')
                       .css('top', attrs[1] - 7 + 'px');
                
        // align name plates
        if( (mapWidth / 2) > mapWidth - attrs[0] ) // hang to the left
        {
            $(this).parent().children('.location-name').css('right', mapWidth + 7 - attrs[0] + 'px')
                                                       .css('top', attrs[1] - 12 + 'px');
        }
        else // hang to the right
        {
            $(this).parent().children('.location-name').css('left', parseInt(attrs[0]) + 14 + 'px')
                                                       .css('top', attrs[1] - 12 + 'px')
                                                       .addClass('location-name-west');
        }
			}
		);
	},

    hideNameplates: function() {
        $('.location-name').addClass('hidden');
    },

    hideOffices: function() {
        $('.section-main-aside .media-items').addClass('hidden');
    }
}

/* ---------------------------------------------------------------------
Language Selector
Author: Dan Zdrazil

Trigger the users's change of language
------------------------------------------------------------------------ */

var languageSelector = {
    init: function() {
        $('#select_language, #select-language').change(languageSelector.changeLanguage);
    }, 
    
    changeLanguage: function() {
        if($(this).find('option:selected').val() == '') return false;

        var url = ctx.rootUrl 
                  + $(this).find('option:selected').val().toLowerCase().replace('_', '-') 
                  + '/';
        window.location = url;
    }
}
