Tobias Bjerrome Ahlin

// Plugins
jQuery.fn.styleCode = function() {
  return this.each(function() {
    var SCpre = jQuery(this).find(".entry pre");
    if (SCpre.data("isStyled") != true) { // Prevent from styling more than once
      SCpre.wrap('<div class="codebg"><div class="codetop"></div></div>').data("isStyled", true);
    }
  });
};

jQuery.fn.collapse = function() {
  return this.each(function() {
    jQuery(this).stop().animate({
      opacity: 0.0,
      width: 0,
      marginRight: 0,
      padding: 0
    }, 350);
  });
};

jQuery.fn.expand = function(tbwidth) {
  return this.each(function() {
    jQuery(this).stop().animate({
      opacity: 1,
      width: tbwidth,
      marginRight: '18px',
      padding: '0 1px'
    }, 350);
  });
};

$(function() {
  // Preload images in header
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.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);
    }
  }
  $.preLoadImages("wp-content/themes/ta/images/earth.jpg", "wp-content/themes/ta/images/photo.jpg");

  // Effects for profileview
  $("#contact a").mouseenter(function(e) {
    $("#contactinfo").text($(this).text()).fadeIn('fast');
    $(this).stop().parent().stop().animate({
      paddingTop: '7px'
    }, 150).end().animate({
      opacity: 1.0
    }, 100);
  }).mouseleave(function(e) {
    $(this).stop().parent().stop().animate({
      paddingTop: '10px'
    }, 150).end().animate({
      opacity: 0.5
    }, 100);
  });
  $("#contact").mouseleave(function(e) {
    $("#contactinfo").fadeOut('fast');
  });

  $("#fullscreen").css("opacity", 0);

  function showProfile() {
    $("#profile a").parent().parent().addClass('profileactive');
    $("#fullscreen").css("display", "block").animate({
      opacity: 0.5
    }, 200);
    $("#profileview").slideDown(550, function() {
      $(this).find('.closeprofile').fadeIn(200);
    });
    $("#header").animate({
      marginTop: '320px'
    }, 550);
  }
  // Toogle profileview
  $("#profile a").click(function(e) {
    e.preventDefault();
    showProfile();
  });
  $("#sprofile").click(function(e) {
    e.preventDefault();
    $('html,body').animate({
      scrollTop: 0
    }, 550);
    showProfile();
  });
  $("#fullscreen, #profileview .closeprofile").click(function(e) {
    e.preventDefault();
    $("#menu").removeClass('profileactive');
    $("#fullscreen").delay(200).fadeOut('slow');
    $("#profileview").slideUp(550).find('.closeprofile').fadeOut(200);
    $("#header").animate({
      marginTop: '0px'
    }, 550);
  });

  // Initiate gallery
  $("#focusarea").find('li').hide().end().find('li:first').show();
  $markers = $("#feature ul.markers");
  var slides = $("#focusarea").children().length;

  function showSlide(slideNumber) {
    if (slideNumber < 1) {
      slideNumber = slides;
    } else if (slideNumber > slides) slideNumber = 1;
    $("#focusarea").find('li:visible').fadeOut('slow').end().find('li:nth-child(' + slideNumber + ')').fadeIn('slow');
    $markers.find('a.active').removeClass('active').end().find('li:nth-child(' + slideNumber + ') a').addClass('active');
  }

  // Autotoggle gallery
  var toggleSpeed = 7000,
    timerId = setTimeout(autoToggle, toggleSpeed);

  function autoToggle() {
    var newslide = 2 + $markers.find('a.active').parent().index();
    showSlide(newslide);
    timerId = setTimeout(autoToggle, toggleSpeed);
  }

  // Toggle gallery
  $("#focusnext, #focusprev").click(function(e) {
    e.preventDefault();
    clearTimeout(timerId);
    var newslide = (2 * $(this).hasClass("nextslide")) + $markers.find('a.active').parent().index();
    showSlide(newslide);
  });
  $markers.delegate("a", "click", function(e) {
    e.preventDefault();
    clearTimeout(timerId);
    showSlide($(this).parent().index() + 1);
  });

  // Toggle thumbnail info
  $("#thumbnails li").mouseenter(function(e) {
    $(this).find('img').stop().animate({
      opacity: 0.8
    }, 300).end().find('.viewcasestudy').fadeIn('fast');
  }).mouseleave(function(e) {
    $(this).find('img').stop().animate({
      opacity: 1.0
    }, 150).end().find('.viewcasestudy').fadeOut('fast');
  });

  // Toggle filter
  $("#filter a").click(function(e) {
    e.preventDefault();
    $(this).parent().parent().find('li a').removeClass('active').end().end().end().addClass('active');
    //Update adress bar
    window.location.hash = "/" + $(this).text().replace(' ', '-');
    updateFilter($(this).text().replace(' ', '-'));
  });

  // Update filter function
  var tbwidth = $("#thumbnails li:first").width();

  function updateFilter(category) {
    var filtername = category.toLowerCase();
    if (filtername == "everything") {
      $("#thumbnails li").expand(tbwidth);
    } else {
      $("#thumbnails li").not("." + filtername).collapse().end().filter("." + filtername).expand(tbwidth);
    }
  }
  // Initiate filter from hashtag
  var initFilter = window.location.hash;
  if (initFilter != "") {
    var hashvalues = initFilter.split('/');
    updateFilter(hashvalues[1]);
    $("#filter").find('.active').removeClass('active').end().find(".f" + hashvalues[1].toLowerCase()).addClass('active');
  }

  // Find "code" elements and wrap in two divs for styling
  $("#content").styleCode();

  // Fade out graphics over object on play
  $("div.tag-video").click(function(e) {
    $(this).find('span.date').fadeOut('slow');
  });

  var loadPosts = $("#content").children().length - 1,
    loadOffset = $("#content").children().length - 1;
  // totalPosts is defined in php
  // Load more posts with ajax
  $("#loadmoreposts").click(function(e) {
    e.preventDefault();
    var actiondata = "posts=" + loadPosts + "&offset=" + loadOffset;
    $.ajax({
      method: "get",
      url: "../wp-content/themes/ta2/getarticles.php",
      data: actiondata,
      beforeSend: function() {
        //$("#loading").fadeIn("slow");
      },
      complete: function() {},
      //hide loading when complete
      success: function(html) {
        loadOffset += $("#content").append(html).styleCode().find('.moreposts:last').slideDown(600).find('.categoryicon').delay(600).fadeIn('fast').end().children().length;
        if (loadOffset >= totalPosts) {
          $("#loadmoreposts").fadeOut('fast');
        }
        if (isIPad()) {
          $("#content .post.tag-video").hide().filter(".tag-youtube").show();
        }
      }
    });

  });

  stickSidebars();
  $(window).scroll(function(e) {
    stickSidebars();
  });

  function stickSidebars() {
    // Get sidebar to follow
    $("#content .tag-post").each(function(e) {
      var selfOffset = $(this).offset().top - 10,
        selfHeight = $(this).outerHeight(),
        windowOffset = $(window).scrollTop(),
        sidebarHeight = $(this).find(".postInfo").outerHeight(true),
        sidebarPosX = $(this).find(".postInfo").offset().left,
        bottomOffset = 10;

      if (selfOffset - windowOffset < 0 && selfOffset - windowOffset > -selfHeight && selfOffset - windowOffset < bottomOffset + sidebarHeight - selfHeight) {
        $(this).find(".postInfo").data("fixed", "false").css({
          "position": "absolute",
          "right": "0px",
          "left": "auto",
          "bottom": bottomOffset + "px",
          "top": "auto"
        });
      } else if (selfOffset - windowOffset < 0 && selfOffset - windowOffset > -selfHeight) {
        $(this).find(".postInfo").data("fixed", "true").css({
          "position": "fixed",
          "left": sidebarPosX + "px",
          "bottom": "auto",
          "top": "10px"
        });
      } else {
        $(this).find(".postInfo").data("fixed", "false").css({
          "position": "absolute",
          "right": "0px",
          "left": "auto",
          "bottom": "auto",
          "top": "0px"
        });
      }

      var self = this;
      if ($(self).find(".postInfo").data("fixed") == "true") {
        var newLeft = $(self).offset().left + $(self).find(".entry").outerWidth(false) - $(window).scrollLeft();
        $(self).find(".postInfo").css({
          "left": newLeft + compensateLeft + "px"
        });
        console.log($(window).scrollLeft() + " and " + newLeft);
      }
    });
  }

  var compensateLeft = 16;
  $(window).resize(function(e) {
    $("#content .tag-post").each(function(e) {
      var self = this;
      if ($(self).find(".postInfo").data("fixed") == "true") {
        var newLeft = $(self).offset().left + $(self).find(".entry").outerWidth(false) - $(window).scrollLeft();
        $(self).find(".postInfo").css({
          "left": newLeft + compensateLeft + "px"
        });
        console.log($(window).scrollLeft() + " and " + newLeft);
      }
    });
  });

  // Select på klick på bitly
  $("#content").delegate("div.tag-post div.postInfo .shortURL", "click", function(e) {
    selectText(this);
  });

  function selectText(element) {
    var text = element;
    if ($.browser.msie) {
      var range = document.body.createTextRange();
      range.moveToElementText(text);
      range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
      var selection = window.getSelection();
      var range = document.createRange();
      range.selectNodeContents(text);
      selection.removeAllRanges();
      selection.addRange(range);
    } else if ($.browser.webkit) {
      var selection = window.getSelection();
      selection.setBaseAndExtent(text, 0, text, 1);
    }
  }

  // If iPad, hide all videos except youtube
  if (isIPad()) {
    $("#content .post.tag-video").hide().filter(".tag-youtube").show();
  }

  function isIPad() {
    return navigator.platform == "iPad";
  }

});
// Plugins
jQuery.fn.styleCode = function(){
	return this.each(function(){
		var SCpre = jQuery(this).find(".entry pre");
		if(SCpre.data("isStyled") != true){ // Prevent from styling more than once
			SCpre.wrap('<div class="codebg"><div class="codetop"></div></div>')
				.data("isStyled", true);
		}
	});
};

jQuery.fn.collapse = function(){
	return this.each(function(){
		jQuery(this).stop().animate({opacity: 0.0, width: 0, marginRight: 0, padding: 0}, 350);
	});
};

jQuery.fn.expand = function(tbwidth){
	return this.each(function(){
		jQuery(this).stop().animate({opacity: 1, width: tbwidth, marginRight: '18px', padding: '0 1px'}, 350);
	});
};

$(function(){
	// Preload images in header
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.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);
	  }
	}
	$.preLoadImages("wp-content/themes/ta/images/earth.jpg", "wp-content/themes/ta/images/photo.jpg");
			
	// Effects for profileview
	$("#contact a").mouseenter(function(e){
		$("#contactinfo").text($(this).text()).fadeIn('fast');
		$(this).stop().parent().stop().animate({paddingTop: '7px'}, 150).end().animate({opacity: 1.0}, 100);
	}).mouseleave(function(e){
		$(this).stop().parent().stop().animate({paddingTop: '10px'}, 150).end().animate({opacity: 0.5}, 100);
	});
	$("#contact").mouseleave(function(e){
		$("#contactinfo").fadeOut('fast');
	});
	
	$("#fullscreen").css("opacity", 0);
	function showProfile(){
		$("#profile a").parent().parent().addClass('profileactive');
		$("#fullscreen").css("display", "block").animate({opacity: 0.5}, 200);
		$("#profileview").slideDown(550, function(){ $(this).find('.closeprofile').fadeIn(200); });
		$("#header").animate({marginTop: '320px'}, 550);
	}
	// Toogle profileview
	$("#profile a").click(function(e){
		e.preventDefault();
		showProfile();
	});
	$("#sprofile").click(function(e){
		e.preventDefault();
		$('html,body').animate({scrollTop: 0}, 550);
		showProfile();		
	});
	$("#fullscreen, #profileview .closeprofile").click(function(e){
		e.preventDefault();
		$("#menu").removeClass('profileactive');
		$("#fullscreen").delay(200).fadeOut('slow');
		$("#profileview").slideUp(550).find('.closeprofile').fadeOut(200);
		$("#header").animate({marginTop: '0px'}, 550);
	});
	
	// Initiate gallery
	$("#focusarea").find('li').hide().end().find('li:first').show();
	$markers = $("#feature ul.markers");
	var slides = $("#focusarea").children().length;
	
	function showSlide(slideNumber) {
		if(slideNumber < 1) { slideNumber = slides; }
		else if(slideNumber > slides) slideNumber = 1;
		$("#focusarea").find('li:visible').fadeOut('slow')
			.end().find('li:nth-child(' + slideNumber + ')').fadeIn('slow');
		$markers.find('a.active').removeClass('active').end().find('li:nth-child(' + slideNumber + ') a').addClass('active');
	}
	
	// Autotoggle gallery
	var toggleSpeed = 7000,
		timerId = setTimeout(autoToggle, toggleSpeed);
	
	function autoToggle(){
		var newslide = 2 + $markers.find('a.active').parent().index();
		showSlide(newslide);
		timerId = setTimeout(autoToggle, toggleSpeed);
	}
	
	// Toggle gallery
	$("#focusnext, #focusprev").click(function(e){
		e.preventDefault();
		clearTimeout(timerId);
		var newslide = (2*$(this).hasClass("nextslide"))+$markers.find('a.active').parent().index();
		showSlide(newslide);
	});
	$markers.delegate("a", "click", function(e){
		e.preventDefault();
		clearTimeout(timerId);
		showSlide($(this).parent().index()+1);
	});
	
	// Toggle thumbnail info
	$("#thumbnails li").mouseenter(function(e){
		$(this).find('img').stop().animate({opacity: 0.8}, 300).end().find('.viewcasestudy').fadeIn('fast');
	}).mouseleave(function(e){
		$(this).find('img').stop().animate({opacity: 1.0}, 150).end().find('.viewcasestudy').fadeOut('fast');
	});
	
	// Toggle filter
	$("#filter a").click(function(e){
		e.preventDefault();
		$(this).parent().parent().find('li a').removeClass('active').end().end().end().addClass('active');
		//Update adress bar
    	window.location.hash = "/" + $(this).text().replace(' ','-');
		updateFilter($(this).text().replace(' ','-'));
	});
	
	// Update filter function
	var tbwidth = $("#thumbnails li:first").width();
	function updateFilter(category) {
		var filtername = category.toLowerCase();
		if(filtername == "everything") {
			$("#thumbnails li").expand(tbwidth);
		} else {
			$("#thumbnails li").not("." + filtername).collapse().end()
				.filter("." + filtername).expand(tbwidth);
		}
	}
	// Initiate filter from hashtag
	var initFilter = window.location.hash;
    if(initFilter != "") {
	    var hashvalues = initFilter.split('/');
		updateFilter(hashvalues[1]);
		$("#filter").find('.active').removeClass('active').end().find(".f" + hashvalues[1].toLowerCase()).addClass('active');
    }
    
	// Find "code" elements and wrap in two divs for styling
	$("#content").styleCode();
    
    // Fade out graphics over object on play
    $("div.tag-video").click(function(e){
    	$(this).find('span.date').fadeOut('slow');
    });
    
    var loadPosts = $("#content").children().length-1,
	    loadOffset = $("#content").children().length-1;
	// totalPosts is defined in php
    // Load more posts with ajax
    $("#loadmoreposts").click(function(e){
    	e.preventDefault();
    	var actiondata = "posts=" + loadPosts + "&offset=" + loadOffset;
    	$.ajax({
    	    method: "get",
    	    url: "../wp-content/themes/ta2/getarticles.php",
    	    data: actiondata,
    	    beforeSend: function(){
    	    	//$("#loading").fadeIn("slow");
    	    },
    	    complete: function(){ }, //hide loading when complete
    	    success: function(html){ 
    	    	loadOffset += $("#content").append(html).styleCode().find('.moreposts:last').slideDown(600)
    	    					.find('.categoryicon').delay(600).fadeIn('fast').end()
    	    					.children().length;
    	    	if(loadOffset >= totalPosts){
    	    		$("#loadmoreposts").fadeOut('fast');
    	    	}
    	    	if(isIPad()){
  				  $("#content .post.tag-video").hide().filter(".tag-youtube").show();
  				}
    	    }
    	});

    });
    
	stickSidebars();    
    $(window).scroll(function(e){
		stickSidebars();
    });
    
    function stickSidebars(){
		// Get sidebar to follow
   		$("#content .tag-post").each(function(e){
   			var selfOffset = $(this).offset().top-10,
   				selfHeight = $(this).outerHeight(),
   				windowOffset = $(window).scrollTop(),
   				sidebarHeight = $(this).find(".postInfo").outerHeight(true),
   				sidebarPosX = $(this).find(".postInfo").offset().left,
   				bottomOffset = 10;
   			
   			if(selfOffset - windowOffset < 0 && selfOffset - windowOffset > -selfHeight && selfOffset - windowOffset < bottomOffset+sidebarHeight-selfHeight){
   			    $(this).find(".postInfo")
   			    	.data("fixed", "false")
   			    	.css({
   			  			"position" : "absolute",
   			  			"right" : "0px",
   			  			"left" : "auto",
   			  			"bottom" : bottomOffset + "px",
   			  			"top" : "auto"
   			  		});
   			} else if(selfOffset - windowOffset < 0 && selfOffset - windowOffset > -selfHeight){
   			    $(this).find(".postInfo")
   			    	.data("fixed", "true")
   			    	.css({
   			    		"position": "fixed",
   			    		"left" : sidebarPosX + "px",
   			    		"bottom" : "auto",
   			    		"top" : "10px"
   			    	});
   			} else {
   			    $(this).find(".postInfo")
   			    	.data("fixed", "false")
   			    	.css({
   			    		"position" : "absolute",
   			    		"right" : "0px",
   			    		"left" : "auto",
   			    		"bottom" : "auto",
   			    		"top" : "0px"
   			    	});
   			}
   			
    		var self = this;
    		if($(self).find(".postInfo").data("fixed") == "true"){
    			var newLeft = $(self).offset().left + $(self).find(".entry").outerWidth(false) - $(window).scrollLeft();
    			$(self).find(".postInfo").css({"left": newLeft + compensateLeft + "px"});
    			console.log($(window).scrollLeft() + " and " + newLeft);
    		}
   		});
    }
    
    var compensateLeft = 16;
    $(window).resize(function(e){
    	$("#content .tag-post").each(function(e){
    		var self = this;
    		if($(self).find(".postInfo").data("fixed") == "true"){
    			var newLeft = $(self).offset().left + $(self).find(".entry").outerWidth(false) - $(window).scrollLeft();
    			$(self).find(".postInfo").css({"left": newLeft + compensateLeft + "px"});
    			console.log($(window).scrollLeft() + " and " + newLeft);
    		}
    	});
    });
    
    // Select på klick på bitly
    $("#content").delegate("div.tag-post div.postInfo .shortURL", "click", function(e){
    	selectText(this);
    });
    
    function selectText(element) {
  	  var text = element;
  	  if ($.browser.msie) {
  	      var range = document.body.createTextRange();
  	      range.moveToElementText(text);
  	      range.select();
  	  } else if ($.browser.mozilla || $.browser.opera) {
  	      var selection = window.getSelection();
  	      var range = document.createRange();
  	      range.selectNodeContents(text);
  	      selection.removeAllRanges();
  	      selection.addRange(range);
  	  } else if ($.browser.webkit) {
  	      var selection = window.getSelection();
  	      selection.setBaseAndExtent(text, 0, text, 1);
  	  }
	}
    
    // If iPad, hide all videos except youtube
    if(isIPad()){
    	$("#content .post.tag-video").hide().filter(".tag-youtube").show();
    }
    
    function isIPad(){
    	return navigator.platform == "iPad";
    }

});