/* @author lance.cooper */

(function($) {
    $(function() {

        $('body').addClass('js')
        $('li:last-child,.column:last-child').addClass('last');
        $('ul.executiveList li:nth-child(5)').addClass('last');
        $('.extra .module:gt(0)').not('').addClass('divider');
        $("div.row:last-child,div.row div.cell:last-child").addClass("last");
        $("a[href*='http://']:not([href*='" + location.hostname + "'])").click(function() {
            window.open($(this).attr('href'));
            return false;
        });

        //HIDE DOWNLOAD LINKS
        $(".contentBlock .remove").remove();

		//CUFON ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		Cufon.set('fontFamily', 'gotham-book').replace('.topNavBar p,.newsBar .title,.introText p,.introText ul,.moduleLargeText p');
		Cufon.set('fontFamily', 'gotham-medium').replace('.introText h1,#content h2,#content h3,.introText p strong');
		Cufon.set('fontFamily', 'gotham-book').replace('.newsBar .title h2,#brandFinder .blurb h2,.ContainsSpotlight p');
		//with hoverables set
		Cufon.set('fontFamily', 'gotham-medium').replace('#topNav li a', { hover: true, hoverables: { a: true} });
		
		//SEARCH~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        $('.search').useTitleForValue();


        //VIEW GALLERY FIXES
        $(".gallery-featured a.colorbox").each(function() {
            $(this).colorbox({ caption: '<div class="btn-sec"><a href="' + $(this).attr('rel') + '">View Gallery</a></div> <div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Image</a></div>' });
        });
        $("a.colorbox").append('<img src="/images/interface/icon_zoom.gif" class="zoomIcon" />');

        //COLORBOX ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        $("a[rel='colorbox']").each(function() {
            $(this).colorbox({ caption: '<div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Image</a></div>' });
        });
        $("a[rel='colorbox']").append('<img src="/images/interface/icon_zoom.gif" class="zoomIcon" />');
        $("a[rel='popupProfile']").click(function() {
            var popContents = $(this).attr('href') + ' #profile';
            $.fn.colorbox({ title: $(this).attr('title'), opacity: .9, href: popContents, open: true });
            return false;
            return false;
        });
        $("a[rel='popUpDetail']").click(function() {
            var popContents = $(this).attr('href') + ' #detail';
            $.fn.colorbox({ title: $(this).attr('title'), opacity: .9, href: popContents, open: true });
            return false;
        });
        $("a.popUpInline").click(function() {
            var _url = $(this).attr('href');
            var _title = $(this).attr('title');
            $.fn.colorbox({ title: _title, inline: true, opacity: .9, href: _url, open: true });
            return false;
        });
        $("a[rel='video']").prepend('<img src="/images/interface/play-btn.png" alt="Play button" class="play-btn" />');
        $("a[rel='popupMap']").click(function() {
            var popContents = $(this).attr('href') + ' #mapContents';
            $.fn.colorbox({ title: $(this).attr('title'), opacity: .9, href: popContents, open: true });
            return false;
            return false;
        });

        //IMAGE LIBRARY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        $("div.cell input[type=checkbox]").click(function() {
            $(this).parents("div.cell").toggleClass('cell-active');
        });
        $("input[type=checkbox][checked]").each(function() {
            $(this).parents("div.cell").addClass('cell-active');
        });
        $("a.select-none").click(function() {
            $("input[type=checkbox]").attr('checked', false);
            $("div.cell").removeClass('cell-active');
            return false;
        });
        $("a.select-all").click(function() {
            $("input[type=checkbox]").attr('checked', true);
            $("div.cell").addClass('cell-active');
            return false;
        });

        $("a.gallery").not("a.gallery.media").append('<img src="/images/interface/icon_zoom.gif" class="zoomIcon" />');
        $("a.gallery.media").append('<img src="/images/interface/icon_play.gif" class="zoomIcon" />');
        $("a.gallery").not("a.gallery.media").each(function() {
            $(this).colorbox({ caption: '<div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Image</a></div>' });
        });
        $(".gallery-featured a.gallery").not("a.gallery.media").each(function() {
            $(this).colorbox({ caption: '<div class="btn-sec"><a href="/media/image-library/event/">View Gallery</a></div> <div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Image</a></div>' });
        });
        $("a.gallery.media").click(function() {
            var _url = $(this).attr('href');
            var _title = $(this).attr('title');
            $.fn.colorbox({ title: _title, inline: true, opacity: .9, href: _url, open: true, caption: '<div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Media</a></div>' });
            return false;
        });
        $(".gallery-featured a.gallery.media").click(function() {
            var _url = $(this).attr('href');
            var _title = $(this).attr('title');
            $.fn.colorbox({ title: _title, inline: true, opacity: .9, href: _url, open: true, caption: '<div class="btn-sec"><a href="/media/image-library/event/">View Gallery</a></div> <div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Media</a></div>' });
            return false;
        });
		
		// CSR PHASE VIDEO IN LIGHTBOX / Dev Owen Cowdry 2011/06/07
		$("a.video_spot").click(function() {
            var _url = $(this).attr('href');
            var _title = $(this).attr('title');
            $.fn.colorbox({ title: _title, inline: true, opacity: .9, href: _url, open: true, caption: '<div class="btn-sec alignRight"><a href="' + $(this).attr('href') + '">Download Media</a></div>' });
            return false;
        });

        //CAREERS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //$("#load-app").hide()
        $(".inline").click(function() {
            var _url = $(this).attr('href');
            $.fn.colorbox({ inline: true, opacity: .9, href: _url, open: true });
            return false;
        });
        //Date Picker for Job Application (using jQuery UI)
        $('.datepicker').datepicker({ maxDate: '+0m +0w' });

        //BRAND FINDER SCROLLER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        $('.brandSelector').prepend('<a href="#" class="scroll-left">Left</a>');
        $('.brandSelector').append('<a href="#" class="scroll-right">Right</a>');
		$('.scroller ul li:first').before($('.scroller ul li:last'));
        $('.scroll-right').click(function() {
            var item_width = $('.scroller ul li').outerWidth() + 10;
            var left_indent = parseInt($('.scroller ul').css('left')) - item_width;
            $('.scroller ul:not(:animated)').animate({ 'left': left_indent }, 500, function() {
                $('.scroller ul li:last').after($('.scroller ul li:first'));
                $('.scroller ul').css({ 'left': '-125px' });
            });
            return false;
        });
        $('.scroll-left').click(function() {
            var item_width = $('.scroller ul li').outerWidth() + 10;
            var left_indent = parseInt($('.scroller ul').css('left')) + item_width;
            $('.scroller ul:not(:animated)').animate({ 'left': left_indent }, 500, function() {
                $('.scroller ul li:first').before($('.scroller ul li:last'));
                $('.scroller ul').css({ 'left': '-125px' });
            });
            return false;
        });

        // BUSINESS FINDER FUNCTIONALITY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        $('ul#mapPins').not("ul#mapPins.brand").after('<p class="business-filter"><select id="filterCountrySelect"><option value="showall">Filter by country:</option><option value="showall">Show all</option><option value="australia">Australia</option><option value="belgie">Belgie</option><option value="brazil">Brazil</option><option value="canada">Canada</option><option value="chile">Chile</option><option value="denmark">Denmark</option><option value="deutschland">Deutschland</option><option value="espana">Espana</option><option value="france">France</option><option value="greece">Greece</option><option value="ireland">Ireland</option><option value="italia">Italia</option><option value="luxembourg">Luxembourg</option><option value="nederland">Nederland</option><option value="nz">New Zealand</option><option value="norway">Norway</option><option value="poland">Poland</option><option value="portugal">Portugal</option><option value="romania">Romania</option><option value="serbia">Serbia</option><option value="slovenia">Slovenia</option><option value="sweden">Sweden</option><option value="switzerland">Switzerland</option><option value="turkey">Turkey</option><option value="uk">UK</option><option value="usa">USA</option></select></p>');

        $('#filterCountrySelect').change(function() {
            $('#mapPins li li').hide();
            $('#mapContent li').hide();
            $('.europe').removeClass('active').hide();
            var countryID = $(this).attr('value');
            var countryContentID = '#' + countryID + 'Content';
            $('#mapPins #' + countryID).show();
            $(countryContentID).show();
            if (countryID == 'showall') {
                $('#mapPins li').show();
                $('#mapContent li').show();
            }
            if ($('#mapPins .europe').find('#' + countryID).size()) {
                $('#mapPins .europe').addClass('active').show();
            }
        });

        $('#mapPins li.europe').not("#mapPins.brand li.europe").click(function() {
            $(this).toggleClass('active');
        });

        /* Information on hover */
        function addContent() {
            var linkTarget = $(this).children("a.contentLink").attr('href');
            $(this).addClass('moveToTop').append('<div class="mapOverview"><div class="close"><a href="#" title="Close"><img src="/images/interface/icon-close.gif" alt="Close" /></a></div>' + $($(linkTarget)).find('div').html() + '</div>')
            $(this).children("div.mapOverview").fadeIn('fast');
            $(".close a").click(function() {
                $('.mapOverview').fadeOut('fast');
                return false;
            });
        }
        function removeContent() {
            $(this).children("div.mapOverview").remove();
            $(this).removeClass('moveToTop');
        }
        var mapPinConfig = {
            interval: 100,
            sensitivity: 4,
            over: addContent,
            timeout: 100,
            out: removeContent
        };
        $("#mapPins li").not("#mapPins li#blurb,#mapPins li#key,#mapPins li.europe,#mapPins.brand li").hoverIntent(mapPinConfig);

        $("#mapPins li a").not("#mapPins.brand li a").click(function() {
            return false;
        });
        $("#mapContent").addClass("map-hide");
        $("#viewList").click(function() {
            $("#mapContent").toggleClass("map-hide");
        });

        // ACCORDIAN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        /*
		$('#content ul.accordian div.accContent').hide();
        $('#content ul.accordian div.accTitle').click(function() {
            $('#content ul.accordian div.accContent').not($(this).next('div.accContent')).slideUp('fast');
            $(this).next('div.accContent').slideToggle('fast');
            $('#content ul.accordian div.accTitle').not($(this)).removeClass('expanded');
            $(this).toggleClass('expanded');
        });
		*/
		
		accordian = {
			// Global variables
			$accordians: $('ul.accordian'),
			$accContent: $('ul.accordian div.accContent'),
			$accTriggers: $('#content ul.accordian div.accTitle'),
			// Initialise accordian
			init: function(){
				$(accordian.$accContent).hide();
				accordian.triggerClick();
			},
			// Trigger accordian open, close
			triggerClick : function(){
				$(accordian.$accTriggers).click(function(){
					var $_this = $(this);
					var myParentList = $(this).closest('ul.accordian');
					var $localLis = $(myParentList).children();
					var localTriggers = $($localLis).children('div.accTitle');
					var localHiddenContent = $($localLis).children('div.accContent'); 
					var myHiddenContent = $(this).next('div.accContent');	
					
					/*
						Slide this section up and removed the expanded class.
					*/
					function hideMyContent(){
						$(myHiddenContent).slideUp(300);
						$($_this).toggleClass('expanded');
					};					
					/*						
						Slide down this section
						Toggle the expanded class
					*/
					function showMyContent(){
						$(myHiddenContent).slideDown(300);
						$($_this).toggleClass('expanded');
					};
					/*
						Slide up all the sections except this one.
						Toggle the class of the previously open section.
					*/
					function closeOpenSection(){
						var openSectionTrigger = $($localLis).children('div.expanded');
						var openSection = $(openSectionTrigger).next('div.accContent');
						$(openSection).slideUp(300);
						$(openSectionTrigger).toggleClass('expanded');
					};
					
					// If statement to check if there are open sections or not.						
					if($($_this).hasClass('expanded')){
						hideMyContent();
					} else if($(localTriggers).hasClass('expanded')){
						closeOpenSection();
						showMyContent();
					} else {
						showMyContent();
					}
					
				});		
			}
		};
		
		accordian.init();
		
		/* -- START PIE CHART HOVER FUNCTIONS -- */
		/* @author owen.cowdry */
		
		pieHover = {
			// Global variables
			$chartSections: $('div.chart ul.chart_list li a'),
			$hiddenContent: $('ul.hidden_content li'),
			init: function(){
				pieHover.sectionHover();
			},
			sectionHover: function(){
				$(pieHover.$chartSections).hover(function(){
					var $_this = $(this);
					var myHref = $(this).attr('href');
					var $myDetail = $(pieHover.$hiddenContent).filter(myHref);
					$($myDetail).show();
				},
				function(){
					var $_this = $(this);
					var myHref = $(this).attr('href');
					var $myDetail = $(pieHover.$hiddenContent).filter(myHref);
					$($myDetail).hide();
				});
			}
		};
		
		pieHover.init();
		
		
		/* -- END PIE CHART HOVER FUNCTIONS -- */

    
        // TIMELINE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        /* Preload active image */
        jQuery.preLoadImages("/images/interface/timeline-overlay-active.png");
        /* Animate background */
        $('.js #timelineNav').css('backgroundPosition', '-296px 100%');
        var animating = false;
        var currentPos = 1;
        var maxPos = 8;
        var onAnimationComplete = function() {
            animating = false;
            $('#timelineNav li').removeClass('active');
            if (currentPos == 1) { $('#navBeg').addClass('active'); }
            if (currentPos == 2) { $('#nav50').addClass('active'); }
            if (currentPos == 3) { $('#nav60').addClass('active'); }
            if (currentPos == 4) { $('#nav70').addClass('active'); }
            if (currentPos == 5) { $('#nav80').addClass('active'); }
            if (currentPos == 6) { $('#nav90').addClass('active'); }
            if (currentPos == 7) { $('#navToday').addClass('active'); }
        }
        var moveTimelineNavBg = function(pos) {
            if (pos < maxPos && pos > 0) {
                currentPos = pos;
                var newPos = -((40 * (8 - pos)) + 20);
                $('#timelineNav').animate({ backgroundPosition: newPos + 4 + "px 100%" }, 500);
            }
        }
        /* Scroll the content when a link is clicked */
        var timelineNavItemWidth = $('#timelineNav > li').outerWidth();
        var timelineItemWidth = $('#timelineContent li').outerWidth();
        $("#timelineNav > li a").each(function(i) {
            var id = i;
            $(this).click(function() {
                $('#timelineContent > ul').animate({ left: -timelineItemWidth * id }, 500, onAnimationComplete, false);
            });
        });
        /* When an explicit link is clicked animate the background position and add arrow to current */
        $('#navBeg').addClass('active');
        $('#navBeg a').click(function() { moveTimelineNavBg(1); return false });
        $('#nav50 a').click(function() { moveTimelineNavBg(2); return false });
        $('#nav60 a').click(function() { moveTimelineNavBg(3); return false });
        $('#nav70 a').click(function() { moveTimelineNavBg(4); return false });
        $('#nav80 a').click(function() { moveTimelineNavBg(5); return false });
        $('#nav90 a').click(function() { moveTimelineNavBg(6); return false });
        $('#navToday a').click(function() { moveTimelineNavBg(7); return false });

        /* Left and right links */
        $('#timelineNav').prepend('<li id="navLeft"><a href="#">left</a></li>');
        $('#timelineNav').append('<li id="navRight"><a href="#">right</a></li>');

        $('#navLeft a').click(function() {
            if (!animating && currentPos - 1 > 0) {
                moveTimelineNavBg(currentPos - 1);
                animating = true;
                var timelineContent = $("#timelineContent > ul");
                var timelineposition = timelineContent.position();
                var timelinepositionLeft = timelineposition.left + timelineItemWidth;
                $('#timelineContent > ul').animate({ left: timelinepositionLeft }, 500, onAnimationComplete);
            }
            return false;
        });
        $('#navRight a').click(function() {
            if (!animating && currentPos + 1 < maxPos) {
                moveTimelineNavBg(currentPos + 1);
                animating = true;
                var timelineContent = $("#timelineContent > ul");
                var timelineposition = timelineContent.position();
                var timelinepositionRight = timelineposition.left - timelineItemWidth;
                $('#timelineContent > ul').animate({ left: timelinepositionRight }, 500, onAnimationComplete);
            }
            return false;
        });
		
		//RESIN HOME PAGE TAKEOVER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		
		/* Player seek controls */
		var resinToolbarHeight = '69px';
		$(".resinToolbar").css("bottom","-" + resinToolbarHeight);
		$(".seekNav").show();
		$(".resinPlayerWrap").hoverIntent(seekShow,seekHide);
		function seekShow(){
			$('.resinToolbar').show().animate({ bottom: '0'}, 200 );
		}
		function seekHide(){
			$('.resinToolbar').animate({ bottom: '-' + resinToolbarHeight }, 200 );
			
		}
		$(".resinPlayerWrap li .button").hover(resinAddClass,resinRemoveClass);
		function resinAddClass(){
			$(this).addClass('hover');
		}
		function resinRemoveClass(){
			$(this).removeClass('hover');
		}
		
		
		/* Set up specific seek buttons */
		$("#seek1").click(function(){
			seek(6);
		});
		$("#seek2").click(function(){
			seek(48);
		});
		$("#seek3").click(function(){
			seek(67);
		});
		
    });
})(jQuery);
 
//PLUGINS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

jQuery.fn.useTitleForValue = function() { 
	this.each(function(){
		i = $(this);
		if (i.attr("title").length) {
			i.addClass("inactive").attr({
				"value": i.attr("title")
			});
			i.focus(function(){
				if ($(this).val() == $(this).attr("title")) { $(this).removeClass("inactive").removeAttr("value");}
			})
			.blur(function(){
				if ($(this).val() == "") {$(this).addClass("inactive").attr({"value": $(this).attr("title")});}
			})
		}
	})
	return this;
};

/* Preload images */
(function($) {
  var cache = [];
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);
}; 
