/* --------------------------------------------------------------
   
   jQUERY
   
-------------------------------------------------------------- */

$(document).ready(function() {


	/* The section specific navigation dropdowns
	-------------------------------------------------------------- */
	
	$("#navigation ul.menu ul").css('display','none'); // Opera Fix

	$("#navigation ul.menu li").hover(function(){
		
		$(this).find('ul:first')
				.css('visibility', 'visible')
				.css('display', 'none')
				.slideDown('fast');
		
		},function(){
		
		$(this).find('ul:first')
				.css('visibility', 'hidden');
		
	});
	
	/* Opportunities filter tabs
	-------------------------------------------------------------- */
	
	$("#filter-tabs").tabs({ cookie: { expires: 30, path: '/' } });
	
	
	/* Make sure the opportunities are all the same height
	-------------------------------------------------------------- */
	
	var tallestDetails = 0;
			
	$('.opportunity .details').each(function(){
	
		if ($(this).height()>tallestDetails)
		{
			tallestDetails = $(this).height();
		}
	
	}).each(function(){
	
		$(this).height(tallestDetails);
	
	});


	/* Landing page section slider
	-------------------------------------------------------------- */

	$('#section-slider .images').cycle({
		speed: 1000,
		sync: 1
	});
	
	$('#slideshow .slides').cycle();
	
	
	/* Show home feature caption on hover
	-------------------------------------------------------------- */
	
	$('#home-feature').hover(
		function(){
			$(this).find('.caption').show();
		},
		function(){
			$(this).find('.caption').hide();
		}
	);
	
	/* Follow the image link of home feature caption clicked
	-------------------------------------------------------------- */

	$('#home-feature .caption').click(function(){
	
		var href = $(this).parent().find('.image a').attr('href');
		
		if (href) {
		
			window.location = href;
		
		}
	
	});


	/* Handle the landing page's expandable standfirst
	-------------------------------------------------------------- */
	
	var more = $('#standfirst #more');
	
	var options = {};

	$('#more-toggle').toggle(function(){
	
		more.slideFadeToggle();
		
		$(this).html('...less');
					
	},
	
	function(){
	
		more.slideFadeToggle();
		
		$(this).html('...more');
	
	});
	
	
	/* Handle dropdowns
	-------------------------------------------------------------- */
	
	$('.dropdown > ul > li > a').click(function() {
	    if ($(this).parent().hasClass('hover')) {
	      $(this).closeMenu();
	    } else {
	      $(this).closeAll();
	      $(this).openMenu();
	      $(this).blur();
	    }
	    return false;
	  });
	  
	  
	$('.dropdown > ul > li > ul > li').hover(
		function(){	$(this).find('ul').css('visibility', 'visible');	},
		function(){	$(this).find('ul').css('visibility', 'hidden');	}
	); 
	  
	/* Handle thumbnail hovers
	-------------------------------------------------------------- */
	  
	$('#thumbnail-grid .thumbnail').hover(
			
		function(){ $(this).find('.link a').addClass('hover'); },
	
		function(){ $(this).find('.link a').removeClass('hover'); }
	
	);
	
	/* Portfolios slider
	-------------------------------------------------------------- */

	$('#portfolio-carousel .panels').cycle({
		fx: 'scrollLeft',
		pager:  '#slider-nav .pager',
		prev:   '#slider-nav .prev',
		next:   '#slider-nav .next',
		pagerAnchorBuilder: function(idx, slide) {
		// return selector string for existing anchor
			return '#slider-nav .pager a:eq(' + idx + ')';
		} 
	});
	
	
	/* Some thumbnail dimming to please Johanna
	-------------------------------------------------------------- */

	$('.thumbnail .image').hover(
	
		function(){ $(this).fadeTo('fast', 0.7); },
		function(){ $(this).fadeTo('fast', 1); }
	
	);
	
	/* Scroll anchor links
	-------------------------------------------------------------- */

	$.localScroll();
	
	
	/* Handle the section links
	-------------------------------------------------------------- */
	
	sectionLinks = $('#section-selector div');

	sectionLinks.fadeLink();
	
	sectionLinks.hover(function(){
		
			$(this).showLink();
	
	}, function(){
	
		if (!$(this).hasClass('active'))
		{
			$(this).fadeLink();
		}
	
	}).click(function(){
	
		href = $(this).find('a').attr('href');
		window.location = href;
	
	});
	
	$('body#agency #section-selector div.agency,body#awards #section-selector div.awards,body#opportunities #section-selector div.opportunities,body#ideasillustrated #section-selector div.ideasillustrated,body#shop #section-selector div.shop,body#landing #section-selector div').showLink(this).addClass('active');
	

	/* Cycle the webcam images
	-------------------------------------------------------------- */
	
	$('div.webcam-images').cycle({
		timeout:       2000,
		speed:         4000
	});
	
	/* Equialise the setion headers on agency page, and thumbnails
	-------------------------------------------------------------- */
	
	$('.section-header .description, div.thumbnail .info, #featured-case-studies .summary, .equalize').equalizeCols();


	/* Handle any fixed right columns
	-------------------------------------------------------------- */

	$( '#right-column.fixed' ).append('<p class="align-right"><a href="#" id="killSwitch">Turn Slide Off</a></p>').scrollFollow();
	
	
	/* Autocomplete the name search
	-------------------------------------------------------------- */
	
	// Autocomplete 
	$("input#portfolio-keywords").autocomplete("/people/_autocompleter/",{ 
		cacheLength: 0, 
		minChars: 3, 
		formatItem: function (row) { return row[0]; }, 
		formatResult: function (row){ return row[0]; } 
	}).result(function(event, item) { 
		$(this).parent().parent().submit();
	}); 
	
	/* Init hint
	-------------------------------------------------------------- */
	
	$('input, textarea').hint();
	
	
	/* Handle say hello dropdown
	-------------------------------------------------------------- */
	
	var sayHelloToggle = $('#say-hello-toggle a');
	var sayHello = $('#say-hello');
	var targetHeight = 326;
	var mainContainer = $('#main-container');
	
	
	sayHelloToggle.click(function(){
	
		$(this).toggleClass('active');
	
		if (!sayHello.hasClass('active')) {
	
			sayHello.animate({ height: targetHeight+'px'}).addClass('active');
		
			mainContainer.animate({ marginTop: targetHeight+'px'});
			
			sayHello.find('button').show();
		
		} else {
		
			sayHello.animate({ height: '0px'}).removeClass('active');
		
			mainContainer.animate({ marginTop: 0});
			
			sayHello.find('button').hide();
		
		}
		
		return false;
	
	});
	
	
	/* Handle the say hello form using ajax
	-------------------------------------------------------------- */
	
	$('#say-hello-form').validate({
		validClass: "success",
		success: "valid",
		errorElement: "em",
		errorClass: "invalid",
		onkeyup: false,
		onfocusout: false,
		focusInvalid: false,
		showErrors: function(errorMap, errorList) {
		
			if (this.numberOfInvalids()>0) {
		
				$("#say-hello .message").html("<p>Your form contains "
	                                   + this.numberOfInvalids() 
	                                   + " errors, see details below.</p>");
				this.defaultShowErrors();
			
			}
			
		},
		invalidHandler: function(form, validator) {
			$('input, textarea').hint();
		},
		rules: {
			name: "required",
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				name: "Please specify your name",
				email: {
					required: "We need your email address to contact you",
					email: "Your email address must be in the format of name@domain.com"
				}
			}
	});
	
	
	
	
	
	$('#section-feature .item .images').cycle();

	

});



/* jQuery functions
-------------------------------------------------------------- */

$.fn.slideFadeToggle = function(speed, easing, callback) {
  return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};

$.fn.openMenu = function() {
	$(this).addClass('arrow-up').removeClass('arrow-down');
	$(this).parent().addClass('hover').addClass('no-bot-bg').children('ul:first',this).css('visibility', 'visible');
	$(this).blur();
};

$.fn.closeMenu = function() {
	$(this).removeClass('arrow-up').addClass('arrow-down');
	$(this).parent().removeClass('hover').removeClass('no-bot-bg').children('ul:first',this).css('visibility', 'hidden');
	$(this).blur();
};

$.fn.closeAll = function() {
	$('.dropdown > ul li').removeClass("hover").removeClass('no-bot-bg').children('ul').css('visibility', 'hidden');
	$('.dropdown > ul > li > a').removeClass('arrow-up').addClass('arrow-down');
};

$.fn.showLink = function() {
  return this.fadeTo(0, 1);
};

$.fn.fadeLink = function() {
  return this.fadeTo(0, 0.4);
};

$.fn.equalizeCols = function(){
	var height = 0,
		reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";

	return this
		.css("height", reset)
		.each(function() {
			height = Math.max(height, this.offsetHeight);
		})
		.css("height", height)
		.each(function() {
			var h = this.offsetHeight;
			if (h > height) {
				$(this).css("height", height - (h - height));
			}
		});
		
};





var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';var err_style = '';
					try{
					    err_style = mc_custom_error_style;
					} catch(e){
					    err_style = 'margin: 1em 0 0 0; padding: 1em 0.5em 0.5em 0.5em; background: ERROR_BGCOLOR none repeat scroll 0% 0%; font-weight: bold; float: left; z-index: 1; width: 80%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: ERROR_COLOR;';
					}
					var head= document.getElementsByTagName('head')[0];
					var style= document.createElement('style');
					style.type= 'text/css';
					if (style.styleSheet) {
					  style.styleSheet.cssText = '.mce_inline_error {' + err_style + '}';
					} else {
					  style.appendChild(document.createTextNode('.mce_inline_error {' + err_style + '}'));
					}
					head.appendChild(style);
					$(document).ready( function($) {
					  var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){}  };
					  var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
					  options = { url: 'http://ycnonline.us1.list-manage2.com/subscribe/post-json?u=5f26c55dbe44ae2413a4452e4&id=5fe7fec4a2&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
					                beforeSubmit: function(){
					                    $('#mce_tmp_error_msg').remove();
					                    $('.datefield','#mc_embed_signup').each(
					                        function(){
					                            var txt = 'filled';
					                            var fields = new Array();
					                            var i = 0;
					                            $(':text', this).each(
					                                function(){
					                                    fields[i] = this;
					                                    i++;
					                                });
					                            $(':hidden', this).each(
					                                function(){
					                                	if ( fields[0].value=='MM' && fields[1].value=='DD' && fields[2].value=='YYYY' ){
					                                		this.value = '';
														} else if ( fields[0].value=='' && fields[1].value=='' && fields[2].value=='' ){
					                                		this.value = '';
														} else {
						                                    this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
						                                }
					                                });
					                        });
					                    return mce_validator.form();
					                }, 
					                success: mce_success_cb
					            };
					  $('#mc-embedded-subscribe-form').ajaxForm(options);
					
					});
					function mce_success_cb(resp){
					    $('#mce-success-response').hide();
					    $('#mce-error-response').hide();
					    if (resp.result=="success"){
					        $('#mce-'+resp.result+'-response').show();
					        $('#mce-'+resp.result+'-response').html('Thanks! To confirm the sign up please click the link in the email we just sent you.');
					        $('#mc-embedded-subscribe-form').each(function(){
					            this.reset();
					    	});
					    	$('#mc-embedded-subscribe').hide();
					    } else {
					        var index = -1;
					        var msg;
					        try {
					            var parts = resp.msg.split(' - ',2);
					            if (parts[1]==undefined){
					                msg = resp.msg;
					            } else {
					                i = parseInt(parts[0]);
					                if (i.toString() == parts[0]){
					                    index = parts[0];
					                    msg = parts[1];
					                } else {
					                    index = -1;
					                    msg = resp.msg;
					                }
					            }
					        } catch(e){
					            index = -1;
					            msg = resp.msg;
					        }
					        try{
					            if (index== -1){
					                $('#mce-'+resp.result+'-response').show();
					                $('#mce-'+resp.result+'-response').html(msg);            
					            } else {
					                err_id = 'mce_tmp_error_msg';
					                html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
					                
					                var input_id = '#mc_embed_signup';
					                var f = $(input_id);
					                if (ftypes[index]=='address'){
					                    input_id = '#mce-'+fnames[index]+'-addr1';
					                    f = $(input_id).parent().parent().get(0);
					                } else if (ftypes[index]=='date'){
					                    input_id = '#mce-'+fnames[index]+'-month';
					                    f = $(input_id).parent().parent().get(0);
					                } else {
					                    input_id = '#mce-'+fnames[index];
					                    f = $().parent(input_id).get(0);
					                }
					                if (f){
					                    $(f).append(html);
					                    $(input_id).focus();
					                } else {
					                    $('#mce-'+resp.result+'-response').show();
					                    $('#mce-'+resp.result+'-response').html(msg);
					                }
					            }
					        } catch(e){
					            $('#mce-'+resp.result+'-response').show();
					            $('#mce-'+resp.result+'-response').html(msg);
					        }
					    }
					}

