// Misc functions
var slideInterval = 0;
var $container = $('.elements');
var url_base = "http://www.futerra.co.uk/";


// Slideshow plugin

(function($){
  $.fn.simplestSlideShow = function(settings){
    var config = {
      'timeOut': 3000,
      'speed': 'normal',
      'place': 1
    };
    if (settings) $.extend(config, settings);
    this.each(function(){
      var $elem = $(this);
      var $max = $elem.children().size();
      var $steps = $elem.next().find('.steps');
      //$elem.css('height', $elem.find('img').height());
      $elem.children().hide();
      setTimeout(function(){
    	$elem.children().eq(0).fadeIn();	
      }, 50);
      var place = config['place'];
      slideInterval = setInterval(function(){
      	$steps.find('a').eq(place).addClass('active').siblings().removeClass('active');
      	$elem.children().eq(place).fadeIn(config['speed']).siblings().fadeOut(config['speed']);
        ++place;
    	if(place == $max) {
  			place = 0;
      	}
      }, config['timeOut']);
    });
    return this;
  };
})(jQuery);


// Preload images plugin

(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);



$(document).ready(function(){
	
	//Lazyload
	//$("img:not(.blog)").lazyload();
	
	//Preload some images
	jQuery.preLoadImages(
		url_base + "wp-content/themes/futerra/static/img/minus.png",
		url_base + "wp-content/themes/futerra/static/img/plus_minus.png",
		url_base + "wp-content/themes/futerra/static/img/plus.png",
		url_base + "wp-content/themes/futerra/static/img/share.png",
		url_base + "wp-content/themes/futerra/static/img/cross.png",
		url_base + "wp-content/themes/futerra/static/img/img_end.png",
		url_base + "wp-content/themes/futerra/static/img/career_dots.png",
		url_base + "wp-content/themes/futerra/static/img/footer_bg.png",
		url_base + "wp-content/themes/futerra/static/img/h4_bg.png",
		url_base + "wp-content/themes/futerra/static/img/img_big_end.png",
		url_base + "wp-content/themes/futerra/static/img/loading.gif",
		url_base + "wp-content/themes/futerra/static/img/long_dots.png",
		url_base + "wp-content/themes/futerra/static/img/menu_bg.png",
		url_base + "wp-content/themes/futerra/static/img/side_dotted.png"
	);
	
	//Problem with some width getting bigger on some rezolution
	if($('div.elements').width() >= 1065 && $('div.elements').width() <= 1075){
		$('div.elements').css('max-width', '1050px');
	}
	
	// Isotope
	$container.isotope({
		itemSelector: '.element',
		animationEngine: 'best-available', 
		masonry : {
			columnWidth : 1
		}
	});
	
	//addthis
	$('#at15s').css({left:0});
	$('.addthis_button').live('click', function(e) {
		e.preventDefault();
		ofx = (e.pageX < $(document).width()-270 ? e.pageX+10 : e.pageX-270);
		ofy = (e.pageY < $(document).height()-200 ? e.pageY+10 : e.pageY-200);
		$('#at15s').css({left:ofx,top:ofy});
		//$('title').html('it works');
		//$('#atic_facebook').attr('href', $(this).attr)
	}).live('mouseover', function(e){e.preventDefault();}); 
	
	
	// Placeholder support
	if(!Modernizr.input.placeholder){
	
		$('[placeholder]').focus(function() {
		  var input = $(this);
		  if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		  }
		}).blur(function() {
		  var input = $(this);
		  if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		  }
		}).blur();
		
		$('[placeholder]').parents('form').submit(function() {
		  $(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
			  input.val('');
			}
		  })
		});
	
	}
	
	
	// Elements hover state
	$("#inner_content .element").hover(
		function() {
			$(this).find('.color_helper').stop();
			$(this).find('.small_preview').stop();
			$(this).find('.small_preview').css('display', 'block');
			$(this).find('.color_helper').animate({top: 0, opacity:0.9, avoidTransforms:true}, 250, function(){
				//$(this).siblings('.small_preview').show();
				$(this).parent().find('.small_preview').animate({opacity:1, avoidTransforms:true}, 150);
			});
		},
		function() {
			$(this).find('.color_helper').stop();
			$(this).find('.small_preview').stop();
			$(this).find('.small_preview').css('display', 'none');
			$(this).find('.small_preview').animate({opacity:0, avoidTransforms:true}, 'fast');
			if($(this).hasClass('promo')){
				$(this).find('.color_helper').animate({top: "498px", opacity:0.6, avoidTransforms:true}, 150);
			}else{
				$(this).find('.color_helper').animate({top: "148px", opacity:0.6, avoidTransforms:true}, 150);

			}
		}
	);	
	
	
	// Open elements
	function openElement(element) {
		var href = element.attr( "href" );
		$.bbq.pushState({ go: href });
		if(!element.hasClass('expanded')) {

			element.find('.full_content').html("<div class='loading'></div>");
			
			$('#inner_content .expanded').each(function(){
				$(this).removeClass('expanded');
				$(this).find('.mini_content, .mini_content_static').stop();
				$(this).find('.full_content, .full_content_static').stop();
				$(this).find('.full_content, .full_content_static').fadeOut('fast');
				$(this).find('.mini_content, .mini_content_static').animate({opacity:1, avoidTransforms:true}, 150);
				$(this).find('.full_content iframe').remove();
				
				if($.browser.mozilla && $(this).hasClass('video')) {
				 	$(this).css({left:'auto',top:'auto'});
				}
			});
			
			element.toggleClass('expanded');
			element.find('.mini_content, .mini_content_static').animate({opacity:0, avoidTransforms:true}, 150, function(){
				element.find('.full_content, .full_content_static').css('display', 'block');
				element.find('.full_content, .full_content_static').animate({opacity:1, avoidTransforms:true}, 150);
			});
			
			$container.isotope('reLayout');
			
			$.ajax({
				url: url_base + "ajax-post/",
				type: "post", 
				data: {
					id: element.attr('pid')
				},
				dataType: 'text',
				cache: false,
				success: function(data) {
					
			    	element.find('.full_content').html(data);
			    	
					clearInterval(slideInterval);
					
					if(element.hasClass('photo')) {
						var target = element.find('ul');
						target.children().eq(0).fadeIn().siblings().fadeOut();
						target.next().find('.steps').find('a').eq(0).addClass('active').siblings().removeClass('active');
						target.simplestSlideShow({'timeOut': 4000, 'speed': 1000, 'place': 1});	
						stepsSlider();
					}
					
					if(!$.browser.msie) {
						var str = element.attr('style');
						var pat = /translate(.*)/g;
						var result = pat.exec(str)[1];
						
						var pat2 = /,\s+\d+px/g;
						var scrlTo = pat2.exec(result)[0].replace(/\D*(\d+)\D*/, '$1');
					
						$('html, body').animate({
						    //scrollTop: element.offset().top - 80
						    scrollTop: scrlTo
						}, 1000);
					} else {
						
						$('html, body').animate({
						    //scrollTop: element.offset().top - 80
						    scrollTop: element.css('top')
						}, 1000);
					}
					
					if($.browser.mozilla && element.hasClass('video')) {
						
						var translate = element.css('-moz-transform');
						console.log(translate);
						var pattern = /\d+px/g;
						var matches = translate.match(pattern);
						element.css('-moz-transform','none').css({left:matches[0],top:matches[1]});
					}

				},
				complete: function(){
					var script = 'http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e4a75eb78178240';
					if (window.addthis){
					    window.addthis = null;
					}
					var addthis_config = {
				   		ui_click: true,
				   		ui_open_windows: true,
				   		ui_use_css: false
					};
					var addthis_share = { 
					    url: $('div.addthis_toolbox').attr('addthis:url'),
					    title: $('div.addthis_toolbox').attr('addthis:title'),
					    description: $('div.addthis_toolbox').attr('addthis:description') 
					};
					$.getScript( script );
				}
			});
				
		}
		adjustFooter();
	}
	
	
	//close static text element
	function closeElement() {
		//$.bbq.removeState('go');
		
		$('#static-text').removeClass('expanded');
		$('#static-text .full_content_static').fadeOut('fast');
		$('#static-text .mini_content_static').animate({opacity:1, avoidTransforms:true}, 150);
		
		
		
		$container.isotope('reLayout');
		
		adjustFooter();
	}
	
	
	//close element
	function closeOpenedElement() {
				
		$('#inner_content .expanded').each(function(){
			
			
			
			$(this).removeClass('expanded');
			$(this).find('.mini_content, .mini_content_static').stop();
			$(this).find('.full_content, .full_content_static').stop();
			$(this).find('.full_content, .full_content_static').fadeOut('fast');
			$(this).find('.mini_content, .mini_content_static').animate({opacity:1, avoidTransforms:true}, 150);
			$(this).find('.full_content iframe').remove();
		});
		
		$container.isotope('reLayout');
		adjustFooter();
	}
	
	
	// Elements click state
	function bindElement(element){
		element.click(function(){

			if(!$(this).hasClass('link') /*&& !$(this).hasClass('text')*/) {
				if(!$(this).hasClass('text')) {
					$('#static-text:not(.promo)').remove();
				}
				openElement($(this));
			}
			if($(this).hasClass('link')){
				location.href = $(this).attr( "href" );
			}
		});
	}
	bindElement($('#inner_content .element'));
	
	
	//read less text box
	$('#static-text span.re-collapse a').click(function(){
		$('#static-text').unbind('click');
		closeElement();
		setTimeout(function(){
			bindElement($('#static-text'));
	    }, 500);
	});
	
	
	// Step actions
	function stepsSlider(){
		$('.steps a').click(function(){
			clearInterval(slideInterval);
			$(this).addClass('active').siblings().removeClass('active');
			var slide = $(this).parent().parent().prev();
			slide.children().eq($(this).index()).fadeIn().siblings().fadeOut();
		});
	}
	stepsSlider();
	
	
	// Hashes
	$(window).bind( "hashchange", function(e) {
		var url = $.bbq.getState( "go" );
		
		$("#inner_content .element").each(function(){		
			if(!$(this).hasClass('link')) {
				var href = $(this).attr( "href" );
				if ( href === url ) {
					if(!$(this).hasClass('link') && !$(this).hasClass('text')) {
						$('#static-text:not(.promo)').remove();
					}
					openElement($(this));
				}
			}
		});
		  
		// Menu
		switch(menu){
			case 'work': $active = 0; break;
			case 'clients': $active = 1; break;
			case 'story': $active = 2; break;
			case 'people': $active = 3; break;
			case 'blog': $active = 4; break;
			case 'contact': $active = 5; break;
			default: $active = false; break;
		}
		/*
		$("#side .sub-menu").accordion({ 
			event: 'mousedown',
			autoHeight: false,
			active: $active,
			disabled: true
		});
		*/
		
		$('.slideshow ul').simplestSlideShow({'timeOut': 3000, 'speed': 1000, 'place': 1});
	});

	$(window).trigger( "hashchange" );

	
	// Career expand text
	$('.excerpt span.read-more a').click(function(){
		$(this).parent().parent().hide();
		$(this).parent().parent().parent().find('div.allcontent').slideDown();
	});
	$('.allcontent span.re-collapse a').click(function(){
		$(this).parent().parent().slideUp();
		$(this).parent().parent().parent().find('div.excerpt').fadeIn();
	});
	
	
	//footer adjustment  
	function adjustFooter(){
		if($('body').hasClass('page-blog') || menu=="blog"){
			nrbox = Math.floor( $('#post_list').width() / 180);
		}else{
			nrbox = Math.floor( $('#inner_content').width() / 180);
		}
		
		var w = 0;		
		if($('body').hasClass('page-blog') || menu=="blog"){
			$('#post_list .element').each(function(n){ 
				w += 1;
			});
		}else{
			$('#inner_content .elements .element').each(function(n){ 
				if($(this).css('opacity')!="0"){
					if(($(this).hasClass('expanded') && $(this).hasClass('video')) || $(this).hasClass('promo')){
						w += 3;
					}else if($(this).hasClass('expanded') || $(this).hasClass('text')){
						w += 2;
					}else{
						w += 1;
					}
				}
			});
		}
		
		if($(window).width() >= 1345 && $(window).width() <= 1355){
			//nrbox += 1;
		}
		
		if(w < nrbox){
			nrbox = w;
		}
		
		if($('body').hasClass('page-search')){ /*$('body').hasClass('page-people')*/
			$('#inner_content div.footer').css({width:(720)}).show();
			$('ul.footermenu li.contact').css('margin-right', '4%');
		}else if($('body').hasClass('page-contact')){
			$('#inner_content div.footer').css({width:(773)}).show();
			$('ul.footermenu li.contact').css('margin-right', '4%');
		}else if($('body').hasClass('page-blog') || menu=="blog"){
			final_width = (nrbox+3)*180-20;
			if(final_width<720){
				final_width = 720;
				$('ul.footermenu li.contact').css('margin-right', '4%');
			}
			$('#inner_content div.footer').css({width:(final_width)}).show();
		}else{
			if(nrbox*180-20<720){
				final_width = 720;
				$('ul.footermenu li.contact').css('margin-right', '4%');
			}else{
				final_width = nrbox*180-20;
			}
			$('#inner_content div.footer').css({width:(final_width)}).show();
		}
	};
	
	adjustFooter();
	
	$(window).resize(function() {
		adjustFooter();
	});
	
	
	//filters from submenu
	if($('#career').length){
		$('#menu-sidebar li.people ul.sub-menu li a').each(function(){
			if(!$(this).parent().hasClass('careers')){
				$menuLink = new Array();
				$menuLink = $(this).attr('href').split('/');
				$menuLink[$menuLink.length-1] = "#filter=" + $menuLink[$menuLink.length-1];
				$(this).attr('href', $menuLink.join("/"));
			}
		});
	}else if( useFilterMenu == 1){
		$('#menu-sidebar ul.sub-menu li a').each(function(){
			$menuLink = new Array();
			$menuLink = $(this).attr('href').split('/');
			$menuLink[$menuLink.length-1] = "#filter=" + $menuLink[$menuLink.length-1];
			$(this).attr('href', $menuLink.join("/"));
		});
	}else{
		$('#menu-sidebar ul.sub-menu li a').each(function(){
			if(!$(this).parent().hasClass('menu-item-object-page') && !$(this).parent().hasClass('careers')){
				$(this).removeAttr('href');
				$(this).click(function(){
					$('#menu-sidebar ul.sub-menu li').removeClass('current-menu-item');
					$(this).parent().addClass('current-menu-item');
					
					if($active == 3 && $(this).attr('cat') == "creative"){
						cat_filter = "creative-people";
					}else{
						cat_filter = $(this).attr('cat');
					}
					filter_boxes( cat_filter );
				});
			}
		});
	}
	
	
	//filters from link
	$(window).bind( "hashchange", function(e) {
		var url = $.bbq.getState( "filter" );
		if( url != "" && url != undefined ){
			filter_boxes( url );
		}
	});
	$(window).trigger( "hashchange" );

	
	//filters from footer links
	$('#menu-footer li ul.sub-menu li a').each(function(){
		if(!$(this).parent().hasClass('careers') && !$(this).parent().parent().parent().hasClass('contact') && !$(this).parent().parent().parent().hasClass('blog')){
			$menuLink = new Array();
			$menuLink = $(this).attr('href').split('/');
			$menuLink[$menuLink.length-1] = "#filter=" + $menuLink[$menuLink.length-1];
			$(this).attr('href', $menuLink.join("/"));
		}
	});
	if(menu == "blog"){
		$('#menu-footer li ul.sub-menu li').removeClass('current-menu-item');
	}
	
	
	//filter function
	function filter_boxes( activeFilter ){
		
		$('#menu-sidebar ul.sub-menu li a').each(function(){
			$(this).parent().removeClass('current-menu-item');
			if($(this).html().replace("<span></span>", "").replace(/^\s+|\s+$/g,"") == activeFilter.replace("-", " ")){
				$(this).parent().addClass('current-menu-item');
			}
		});
		
		$('#menu-footer ul.sub-menu li a').each(function(){
			$(this).parent().removeClass('current-menu-item');
			if($(this).html().replace("<span></span>", "").replace(/^\s+|\s+$/g,"") == activeFilter.replace("-", " ")){
				$(this).parent().addClass('current-menu-item');
			}
		});
		
		
		closeOpenedElement();
		
		$('#inner_content .elements').isotope({ filter: '.' + activeFilter });
		
		$('#inner_content .elements .element').each(function(){
			$(this).removeClass("activated");
			$(this).find('.color_helper').stop();
			$(this).find('.small_preview').stop();
			$(this).find('.small_preview').css('display', 'none');
			$(this).find('.small_preview').animate({opacity:0, avoidTransforms:true}, 'fast');
			if($(this).hasClass('promo')){
				$(this).find('.color_helper').animate({top: "498px", opacity:0.6, avoidTransforms:true}, 150);
			}else{
				$(this).find('.color_helper').animate({top: "148px", opacity:0.6, avoidTransforms:true}, 150);
			}
		});
		
		$('#inner_content .elements .element.' + activeFilter).each(function(){
			$(this).addClass("activated");
			$(this).find('.color_helper').stop();
			$(this).find('.small_preview').stop();
			$(this).find('.small_preview').css('display', 'block');
			$(this).find('.color_helper').animate({top: 0, opacity:0.9, avoidTransforms:true}, 250, function(){
				//$(this).siblings('.small_preview').show();
				$(this).parent().find('.small_preview').animate({opacity:1, avoidTransforms:true}, 150);
			});
		});
		
		$("#inner_content .element.activated").hover(
			function() {
				$(this).find('.color_helper').stop();
				$(this).find('.small_preview').stop();
				$(this).find('.small_preview').css('display', 'none');
				$(this).find('.small_preview').animate({opacity:0, avoidTransforms:true}, 'fast');
				if($(this).hasClass('promo')){
					$(this).find('.color_helper').animate({top: "498px", opacity:0.6, avoidTransforms:true}, 150);
				}else{
					$(this).find('.color_helper').animate({top: "148px", opacity:0.6, avoidTransforms:true}, 150);
				}
			},
			function() {
				$(this).find('.color_helper').stop();
				$(this).find('.small_preview').stop();
				$(this).find('.small_preview').css('display', 'block');
				$(this).find('.color_helper').animate({top: 0, opacity:0.9, avoidTransforms:true}, 250, function(){
					//$(this).siblings('.small_preview').show();
					$(this).parent().find('.small_preview').animate({opacity:1, avoidTransforms:true}, 150);
				});
			}
		);	
		
		adjustFooter();

	}
	
	
	// + more functionality on blog sidebar
	function hideSide (item){
		$i = 1;
		$('#'+ item +' ul li').each(function(){
			if($i>10){
				$(this).hide();
			}
			$i++;
		});
	}
	
	function moreLess (item){
		hideSide( item );
		$('#'+ item +' div.more a').click(function(){
			if(item == 'authors' || item == 'archives'){
				$('#'+ item +' ul').css('height', '100%').css('overflow', 'visible');
			}
			$('#'+ item +' ul li').show();
			$(this).parent().parent().find('div.less').show();
			$(this).parent().hide();
			if(item == 'authors'){
				hide_futerra();
			}
		});
		$('#'+ item +' div.less a').click(function(){
			if(item == 'authors' || item == 'archives'){
				$('#'+ item +' ul').css('height', '190px').css('overflow', 'hidden');
			}
			$(this).parent().parent().find('div.more').show();
			$(this).parent().hide();
			hideSide( item );
			if(item == 'authors'){
				hide_futerra();
			}
		});
	}
	
	//authors
	moreLess ( 'authors' );
	//arhives
	moreLess( 'archives' );
	//categories
	moreLess( 'categories' );
	
	
	//replace disqus
	setTimeout(function(){
		_change = 0;
		$('#post_list .post_stats a').each(function(){
			comHtml = $(this).html().replace(" and ", "");
			
			comHtml = comHtml.replace(/([0-9]+) Comments/g, "<b class='comments'>$1</b>");
			comHtml = comHtml.replace(/([0-9]+) Comment/g, "<b class='comments'>$1</b>");
			comHtml = comHtml.replace(/([0-9]+) Reactions/g, "<b class='tweets'>$1</b>");
			comHtml = comHtml.replace(/([0-9]+) Reaction/g, "<b class='tweets'>$1</b>");
			
			_change = 1;
			$(this).html(comHtml);			
		});
		if(_change == 1){
			$('.post_stats').show();
		}
    }, 2000);

	
	//blogroll target blank
	$('ul.blogroll a').attr('target', '_blank');
	
	function hide_futerra(){
		$('#authors ul li a').each(function(){
			if($(this).html() == "Futerra Alumni"){
				$(this).parent().hide();
				$('#authors ul li:eq(10)').show();
			}
		});
	}
	hide_futerra();

});
