var console;
if (console == undefined) {
    console = {log: function () {}};
}

function init() {	
	$(window).bind("load", function() {
		
		if (hasPhotoFeature == true) {
			photoFeature();
		}
				
		var pageVars = getUrlVars();
		
		// Get involved form auto open
		var getInvolvedFormVar = pageVars['form'];
		switch (getInvolvedFormVar) {
			case 'tertiary':
			  getInvolvedFormSetup('tertiary')
			  break;
			case 'industry':
			  getInvolvedFormSetup('industry')
			  break;
			case 'npo':
			  getInvolvedFormSetup('npo')
			  break;
		}
	});	
  
	// Store default CSS positioning for venn callouts
	$('#venn-wrapper .callout').each(function(i){
		var el = $(this);
		el.show().data({'defaultHeight':el.height(), 'defaultBottomPos':el.css('bottom')}).hide();
	});		
		
	// Feature paragraphs
	$('.primary-content .inner .content-inner > p:first-child').addClass('feature-paragraph');
		
	$('.content table:not(.sub-row-table)').each(function(){
		$(this).wrap('<div class="table-wrapper" />');
	});
	
	// IE6 z-index love
	$('#body-home, #nav-home').hover(function(){
		$(this).css({'z-index':6})
	},function(){
		$(this).css({'z-index':5})
	})
	
	// Feeds		
	$('#latest-photos-feed .image-frame').jflickrfeed({
		limit: 5,
		qstrings: {
			id: '38449693@N03',
			tags: 'websitefeed'
		},
		itemTemplate:
			'<a class="image" href="{{link}}" title="{{title}}">' +
				'<img src="{{image}}" alt="{{title}}" />' +
			'</a>'
	}, function(data) {
		$(this).imageFrame({ratio:1})
	});
	
	$('.blog-feed').getTumblr();	
	$('.twitter-feed').getTwitter();
	
	// Vimeo Lightbox
	$('a.vimeo-lightbox').click(function() {		
		$.fancybox({
			'padding': 0,
			'autoScale': false,
			'width': 800,
			'height': 450,
			'href': this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=ff008d&clip_id=$1'),
			'type': 'swf',
			'overlayOpacity': 0.9, 
			'overlayColor': '#fff',
			'centerOnScroll': true,
			'hideOnContentClick': false,
			'swf': {'wmode': 'transparent',	'allowfullscreen': 'true'}
		});
		
		return false;
	});
	
	$("a.image-lightbox").fancybox({ 'overlayOpacity' : 0.8, 'overlayColor' : '#000'}); // general image lightbox
	
	// Newsletter Lightbox
	$('#footer-newsletter').fancybox({
		'width': '75%',
		'height': '90%',
		'autoScale': false,
		'overlayOpacity': 0.9, 
		'overlayColor': '#fff',		
		'centerOnScroll': true,
		'hideOnContentClick': false,
		'type': 'iframe'
	});
	
	/* Apply fancybox to general image links */
	$('a.fancybox').fancybox({		
		'centerOnScroll': true,
		'overlayOpacity': 0.9, 
		'overlayColor': '#fff',
		'cycle': 'true'
	});	
	
	forms();
	
	tumblr();
	
	imageFrameTimer = null;
	
	hasPhotoFeature = ($('#photo-feature-column').length > 0) ? true : false;
	hasPhotoFeatureLoaded = false;
	profileFeature = ($('#photo-feature-column').parents('#profile-wrapper').length > 0) ? true : false;		
	photoFeatureTypes = new Array();
	$('#photo-feature-column .photo-feature-content img').each(function(){
		photoFeatureTypes.push($(this).attr('title'));
	});
	
	hasImageFrame = ($('.image-frame').length > 0) ? true : false;	
	isIE6 = (typeof isIE6 === "undefined") ? false : true;
	isIE = (typeof isIE === "undefined") ? false : true;
}

// http://groups.google.com/group/jquery-en/msg/b3138453ce1fca79?
// Delay resize functions to prevent browser lockups
var resizeTimer = null;
$(window).bind('resize', function() {
	if (resizeTimer) clearTimeout(resizeTimer);
	resizeTimer = setTimeout(layout, 50);
	
	watermark();
	$('#footer').css({'background':'transparent'})
});

function scrollElement() {
	// http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
	scrollElement = 'html, body';
	$('html, body').each(function () {
		var initScrollTop = $(this).attr('scrollTop');
		$(this).attr('scrollTop', initScrollTop + 1);
		if ($(this).attr('scrollTop') == initScrollTop + 1) {
			scrollElement = this.nodeName.toLowerCase();
			$(this).attr('scrollTop', initScrollTop);
			return false;
		}    
	});
}

// http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

function layout() {
	windowWidth = $(window).width();
	windowHeight = $(window).height();	
	documentHeight = $(document).height();
		
	if (windowWidth < 1048) {
		windowWidth = 1048;
	} else if (windowWidth > 1620) {
		windowWidth = 1620;
	}
		
	colWidth = Math.floor((windowWidth - 60) / 13);
	colStyles = '';
	colInterval = 0.5;
	
	// Iterate through column CSS
	for (i = 1; i <= (13 / colInterval); i++)	{
		colNum = i * colInterval;
		colNum = colNum.toString(); 
		
		// If an interger leave as is, else change into column's class name format				
		if (colNum.indexOf('.') == -1){
			var classNum = colNum;
		} else {
			classNum = colNum.substr(0, colNum.indexOf('.'))+'p5';
		}
		colStyles += '.col'+classNum+' {width:' + (colWidth * colNum) +'px;} '+'.left'+classNum+' {left:' + (colWidth * colNum) +'px;} '+'.prepend'+classNum+' {margin-left:' + (colWidth * colNum) +'px;} '+'.append'+classNum+' {margin-right:' + (colWidth * colNum) +'px;} ';
	}	
			
	colStyles += '.col2p5label {width:' + ((colWidth * 2.5)-35) +'px;} '+'.col5p5input {width:' + ((colWidth * 5.5)-33) +'px;} '+'.prepend2p5label {margin-left:' + ((colWidth * 2.5)-20) +'px;} '+'.col6inner {width:' + ((colWidth * 6)-40) +'px;} ';	
	colStyles += '.team-profile-thumbnails .item {width:' + (((colWidth * 3)-58)/3) +'px; height:' + (((colWidth * 3)-58)/3) +'px;} ';	
	colStyles += '.appendneg1 {margin-right:' + (((colWidth * 1)*-1)+20) +'px;} .appendneg3 {margin-right:' + ((colWidth * 3)*-1) +'px;}';
		
	// Remove old CSS, add new
	// http://erikandcolleen.com/erik/projects/jquery/cssinject/cssinject3.html
	$('#injectedCss').remove();
	$('head').append('<style id="injectedCss" type="text/css">' + colStyles + '</style>');
	
	if ($(window).width() > 1542) {
		if (!($('body').hasClass('layoutWide'))) {
			layoutWide();
		}		
	} else {
		if (!($('body').hasClass('layoutDefault'))) {
			layoutDefault();
		}
	}	
	
	// Image frames	
	$('.image-frame:not(.ignore)').imageFrame();
	
	// $('.image-frame.fading:not(.ignore)').imageFrame();	
	// 	$('#latest-photos-feed .image-frame.fading').imageFrame({ratio:1});
		
	if ((hasPhotoFeatureLoaded == true) && (hasPhotoFeature == true)) {
		photoFeature();
	}
	
	watermark();
	
	getInvolvedTabsLayout();
	
	scroll();
}

function layoutWide() {	
	// Home page
	$('#home-intro-copy').removeClass('col6').addClass('col4');	
	$('#body-home-b, #latest-tweets-feed-wide, #get-involved-promo-wide').show();
	$('#body-home-a #latest-news-feed, #body-home-a #latest-tweets-feed, #body-home-a #get-involved-promo').hide();
	$('#body-home-a, #venn-home').removeClass('col6').addClass('col4');
	$('#body-home-a-a, #body-home-a-b').removeClass('col3').addClass('col2');
	
	$('.related-col').removeClass('col3').addClass('col2p5 prepend0p5');
	
	$('body').removeClass('layoutDefault').addClass('layoutWide');
}

function layoutDefault() {	
	// Home page
	$('#home-intro-copy').removeClass('col4').addClass('col6');
	$('#body-home-b, #latest-tweets-feed-wide, #get-involved-promo-wide').hide();
	$('#body-home-a #latest-news-feed, #body-home-a #latest-tweets-feed, #body-home-a #get-involved-promo').show();
	$('#body-home-a, #venn-home').removeClass('col4').addClass('col6');
	$('#body-home-a-a, #body-home-a-b').removeClass('col2').addClass('col3');
	
	$('.related-col').removeClass('col2p5 prepend0p5').addClass('col3');
	
	$('body').removeClass('layoutWide').addClass('layoutDefault');
}

function watermark() {
	// Watermark positioning
	var watermarkBodyLeft = $('#logo').offset().left+$('#logo').width()-702;
	// var watermarkBodyLeft = ($('#watermark').width()/2 + ($('#wrapper').width()/2) - $('#logo').parent().width())*-1;
	var watermarkBodyTop = $('#logo').offset().top+$('#logo').height()-163;
	var watermarkFooterLeft = $('#logo').offset().left+$('#logo').width()-702 - (($('body').width()-$('#wrapper').width())/2);
	var watermarkFooterTop = $('#footer').offset().top*-1 + watermarkBodyTop;
	
	// $('#watermark').css({'margin-left':watermarkBodyLeft, 'top':watermarkBodyTop, 'visibility':'visible'}).show();
	$('body').css({'backgroundPosition': watermarkBodyLeft+'px ' + watermarkBodyTop+'px'});
	// $('#footer').css({'backgroundPosition': watermarkFooterLeft+'px ' + watermarkFooterTop+'px'});
}

function getInvolvedTabsLayout() {
	getInvolvedHeights = new Array();
	
	$('#get-involved-tabs .get-involved-tab .featured-link').width($('#get-involved-tabs .get-involved-tab .border').width()-28);
	$('#get-involved-tabs .get-involved-tab .border').height('auto');
		
	$('#get-involved-tabs .get-involved-tab').each(function(){
		getInvolvedHeights.push($(this).height());
	})
	
	function sortNumber(a,b) {
		return b - a;
	}
	
	getInvolvedHeights = getInvolvedHeights.sort(sortNumber);	
	$('#get-involved-tabs:not(.active-tabs) .get-involved-tab .border').height(getInvolvedHeights[0]+15);
	$('#get-involved-tabs.active-tabs .get-involved-tab .border').height(getInvolvedHeights[0]-10);
}

function navigation() {
	$('.footer-nav-strip li:first-child').addClass('first');
	$('.sub-nav li:last-child').addClass('last');	
	$('#nav-footer .nav-main .sub-nav-parent').hover(function(){
		var subNavWidth = $(this).find('.sub-nav').width();
		var parentLinkWidth = $(this).find('.parent-link').width()+17;		
		$(this).addClass('hover');		
		$(this).find('.sub-nav').show().css({'visibility':'hidden'});		
		if (subNavWidth < parentLinkWidth+28){
			$(this).find('.sub-nav').width(parentLinkWidth+28).css({'visibility':'visible'});
			$(this).find('.sub-nav li').width(parentLinkWidth-2);
		} else {
			$(this).find('.sub-nav').css({'visibility':'visible'});
		}
	}, function(){
		$(this).removeClass('hover');
		$(this).find('.sub-nav').hide();
	})
	
	$('#nav-header .nav-main .sub-nav-parent').hover(function(){
		var parentLinkWidth = $(this).find('.parent-link').width()+15;
		var parentLinkHeight = $(this).find('.parent-link').height()+16;
			
		$(this).addClass('hover');
		$(this).find('.parent-link-bg').height(parentLinkHeight).width(parentLinkWidth+16).show();
		$(this).parent('.nav-main').parent().css({'z-index':2});
		
		if($(this).find('.sub-nav li').length == 1) {
			$(this).addClass('single');
			$(this).find('.sub-nav').height($(this).find('.parent-link-bg').height()-10)
		}
		
		$(this).find('.sub-nav').show().css({'left': parentLinkWidth-8})		
		
	}, function(){
		$(this).removeClass('hover');		
		$(this).find('.sub-nav, .parent-link-bg').hide();
		$(this).parent('.nav-main').parent().removeAttr('style');
	})
		
	$('#nav-home .nav-main .sub-nav-parent').hover(function(){
		var parentLinkWidth = $(this).find('.parent-link').width()+15;
		var parentLinkHeight = $(this).find('.parent-link').height()+18;
			
		$(this).addClass('hover');
		$(this).find('.parent-link-bg').height(parentLinkHeight).width(parentLinkWidth+26).show();
		
		if($(this).find('.sub-nav li').length == 1) {
			$(this).addClass('single');
			$(this).find('.sub-nav').height($(this).find('.parent-link-bg').height()-20)
		}
		
		$(this).find('.sub-nav').show().css({'right': ($(this).find('.sub-nav').width()+13)*-1})		
		
	}, function(){
		$(this).removeClass('hover');		
		$(this).find('.sub-nav, .parent-link-bg').hide();
	})	
};

function photoFeature() {	
	$('#photo-feature-column').css({'position':'absolute', 'top':0});

	bodyOffsetTop = $('#body').offset().top;
	windowHeight = $(window).height();		
	columnHeight = $('#photo-feature-column').parent().height();
	
	columnBodyOffset = $('#body').offset().top;
	
	if (profileFeature == true){
		columnBodyOffset = $('#profile-wrapper').offset().top
	}
	
	columnBodyHeight = (windowHeight > columnHeight) ? columnHeight : columnHeight - columnBodyOffset;
	
	windowHeightBodyOffset = windowHeight - columnBodyOffset;
	featureWidth = $('#photo-feature-column .inner').width();
	
	if (columnBodyHeight > windowHeightBodyOffset) {
		var photoHeight = windowHeightBodyOffset;		
	} else {
		var photoHeight = columnBodyHeight;
	}
			
	// Set column height
	$('#photo-feature-column').height(columnHeight);			
	// Give everything dimensions
	$('.photo-feature, .photo-feature-content, .photo-feature-pattern, .photo-feature-link').height(columnHeight).width(featureWidth);
	
	if (profileFeature == false){
		// Top padding offset
		$('.photo-feature, .photo-feature-pattern').css({'padding-top':columnBodyOffset});
		
		// Top positioning offset
		$('.photo-feature-content, .photo-feature-link').css({'top':columnBodyOffset});
	}
		
	// Set photo dimensions to windowHeightBodyOffset or columnBodyHeight
	$('.photo-feature .photo').height(photoHeight).width(photoHeight);
	var photoWidth = $('.photo-feature .photo').width();
				
	if (photoWidth < featureWidth){
		photoWidth = featureWidth;
	}
	
	// Set final photo dimensions and positioning		
	$('.photo-feature .photo').width(photoWidth).height(photoWidth).css({'margin-left':(photoWidth/2*(-1))}).show();
	
	if (profileFeature == false){
		// Reset to photo's dimensions
		$('.photo-feature, .photo-feature-pattern, .photo-feature-link, .photo-feature-content').height($('.photo-feature .photo').height());
	} else {
		// Reset to photo's dimensions
		$('.photo-feature-content').height($('.photo-feature .photo').height());
	}
	
	if (!hasPhotoFeatureLoaded) {
			$('#photo-feature-column').css({'visibility':'visible'});
			
			if (!isIE) {
				$('#photo-feature-column').css({'opacity':0}).animate({
					opacity: 1
					}, 250)
			};
			
			$('#photo-feature-column').removeClass(photoFeatureTypes[0]).addClass(photoFeatureTypes[0]);
						
			var featurePhoto1 = $('.photo-feature .photo').get(0);
			$(featurePhoto1).css({'visibility':'visible'});
			hasPhotoFeatureLoaded = true;
	}
	
	scroll();
	
	totalFeaturePhotos = $('.photo-feature .photo').length;
		
	if ((totalFeaturePhotos > 1) && (!($('#photo-feature-column').hasClass('fading')))) {	
		$('#photo-feature-column').addClass('fading');
						
		if (!isIE){
			$('.photo-feature .name-list li a, .photo-feature .name-list li .separator').css({'opacity':0.9})	
		}

		var featurePhoto1 = $('.photo-feature .photo').get(0);
		var featureName1 = $('.photo-feature .name-list li').get(0);
		$(featurePhoto1).css({'visibility':'visible'});
		$(featureName1).find('a').addClass('active');
		
		if (!isIE){
			$(featureName1).find('a').css({'opacity':1});
		} 
		
		$('.photo-feature-link').attr('href',$(featureName1).find('a').attr('href'));
		setTimeout(function(){featurePhotoFade(0)},4000);
	}
};

function featurePhotoFade(photoNum) {
	var currentPhoto = photoNum;
	
	if((photoNum+1) > totalFeaturePhotos-1){
		var nextPhoto = 0;
	}	else {
		var nextPhoto = photoNum+1;
	}
	
	var currentPhotoElement = $('.photo-feature .photo').get(currentPhoto);
	var nextPhotoElement = $('.photo-feature .photo').get(nextPhoto);
	var currentNameElement = $('.photo-feature .name-list li').get(currentPhoto);
	var nextNameElement = $('.photo-feature .name-list li').get(nextPhoto);
	var currentProfileType = photoFeatureTypes[currentPhoto];
	var nextProfileType = photoFeatureTypes[nextPhoto];
	
	if (!isIE){
		$(currentNameElement).find('a').removeClass('active').css({'opacity':0.9});
		$(nextNameElement).find('a').addClass('active').css({'opacity':1});
		$('.photo-feature-link').hide().attr('href',$(nextNameElement).find('a').attr('href'));
	} else {
		$(currentNameElement).find('a').removeClass('active');
		$(nextNameElement).find('a').addClass('active');
		$('.photo-feature-link').hide().attr('href',$(nextNameElement).find('a').attr('href'));
	}
	
	$('#photo-feature-column').delay(325).removeClass(currentProfileType).addClass(nextProfileType);
	
	$(currentPhotoElement).animate({
		opacity: 0
		}, 750, function(){
			$(this).css('visibility','hidden');		
		}		
	);
	$(nextPhotoElement).css({'visibility':'visible', 'opacity':0}).animate({
		opacity: 1
		}, 750, function(){
			$('.photo-feature-link').show()
			setTimeout(function(){featurePhotoFade(nextPhoto)},4000)
		})
};

function venn() {
	// Hover off timer
	var vennCalloutDelay = null;
	var vennCallout = null;
	var calloutHideTarget = null;
	var vennCalloutCueDelay = window.setInterval(vennCalloutCue, 2500);  	
	
	// Venn callouts
	$('#venn-wrapper .callout').hover(function(){
		// If timer already set clear timeout
		if (vennCalloutDelay) clearTimeout(vennCalloutDelay);		
		// Add hover class
		$(this).addClass('hover-border');
	},
	function(){
		// Remove hover class
		$(this).removeClass('hover-border');		
		// Get associated area ID
		vennMapArea = '#venn-map-'+$(this).attr('id').toString().substr(5);		
		// Start timeout
		vennCalloutDelay = setTimeout(function() {			
			// If associated area doesn't have a hover class
			if(!($(vennMapArea).hasClass('hover'))){
				// Hide venn callout
				vennCalloutHide(vennCallout);
				// Remove class from associated area
				$(this).removeClass('hover');
			}
		}, 50);		
	});
	
	
	// Venn areas
	$('#venn-map area').hover(function(){		
		// Remove class from all areas	
		$('#venn-map area').removeClass('hover');		
		// Add class to this hover
		$(this).addClass('hover');
		// Get associated callout ID
		vennCallout = '#venn-callout-'+$(this).attr('id').toString().substr(9);		
		// If timer already set clear timeout
		if (vennCalloutDelay) clearTimeout(vennCalloutDelay);		
		// If callout	not already open
		if(!($(vennCallout).hasClass('active'))){
			// Show callout
			vennCalloutShow(vennCallout);
		}
	},
	function(){		
		// Start timeout
		vennCalloutDelay = setTimeout(function() {			
			// If callout doesn't have hover class or area doesn't have hover class
			if((!($(vennCallout).hasClass('hover-border'))) || (!($(this).hasClass('hover')))){
				// Hide callout			
				vennCalloutHide(vennCallout);
				// Remove class from area
				$(this).removeClass('hover');
			}
		}, 50);
	});		
}

function vennCalloutShow(calloutShowTarget) {	
	// Hide all active callouts
	$('#venn-wrapper .callout.active').each(function(){
		vennCalloutHide(this);		
	})	
		
	// Add class to associated label ID	
	$('#venn-label-'+$(calloutShowTarget).attr('id').toString().substr(13)).addClass('hover-heading');
	
	var defaultBottomPos = $(calloutShowTarget).data('defaultBottomPos');	
	
	// Show new callout		
	$(calloutShowTarget).addClass('active').show().css({'bottom':(parseInt(defaultBottomPos)-40),'opacity':0}).animate({
		bottom: defaultBottomPos,
		opacity: 1
		}, 175, function(){
			// IE love
			if(!jQuery.support.opacity){
				$(this).get(0).style.removeAttribute('filter');
				$('.featured-link', this).css({'zoom':1});
			}
		});
}

function vennCalloutHide(calloutHideTarget) {
	$('#venn-label-'+$(calloutHideTarget).attr('id').toString().substr(13)).removeClass('hover-heading');
		
	// Hide callout
	$(calloutHideTarget).stop().removeClass('active').animate({
		bottom: parseInt($(calloutHideTarget).data('defaultBottomPos'))+20,
		opacity: 0
		}, 50, function(){$(this).hide();}
	);
}

function vennCalloutCue() {
	var cueNum = Math.floor(Math.random()*4);
	var el = $('#venn-labels h3').get(cueNum);	
	$(el).find('.callout-cue').animate({
		top: '-='+10+'px'
	}, 75, function(){
		$(this).animate({
			top: '+='+10+'px'
		}, 200)
	}
	);
}

function forms() {	
	// Bind click to faux submit buttons
	$('form a.button-submit').click(function(){
		$(this).parents('form').submit();
		
		return false;
	});
	
	// Secondary sub input
	$('.input-checkbox-secondary-parent').click(function(){
		if ($(this).find('input').is(':checked')){
			$(this).next().show();
		} else {
			$(this).next().hide();
		}		
	});	
	$('.input-checkbox-secondary-parent .input-checkbox:checked').each(function(){
		$(this).parent().next().show();	
	});
		
	// Contact Form
	$('#contact-form').validate({
		ignoreTitle: true,	
		rules: {
		  'first-name': 'required',
			'last-name': 'required',
			email: {required:true, email:true},
			phone: {required:true, digits:true, minlength:7},
			message: {required:true, minlength:10, maxlength: 1000}
		},
		messages: {
			'first-name':'Please enter your first name',
			'last-name':'Please enter your last name',
			email: {required:'Please enter your email address', email:'Please enter a valid email address'},
			phone: {required:'Please enter a phone number', digits:'Please enter a valid phone number, digits only', minlength: 'Phone number must be longer than 7 digits'},
			message: {required:'Please enter a message', minlength:'Message is too short', maxlength:jQuery.format('Message is too long, please shorten to less than {0} characters')}	
		},
		errorPlacement: function(error, element) {
			element.parent().append(error);
			$(error).css({'display':'block'});
		},
		highlight: function(element, errorClass, validClass) {
			$(element).closest('.form-row').addClass('error-row').removeClass('success-row');
			$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
	  },
	  unhighlight: function(element, errorClass, validClass) {
	    $(element).closest('.form-row').addClass('success-row').removeClass('error-row');
			$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
	  },						
		invalidHandler: function(form, validator) {
	    var errors = validator.numberOfInvalids();
	    if (errors) {
				var message = errors == 1
	        ? 'This form contains 1 error, please correct it before continuing'
	        : 'This form contains ' + errors + ' errors, please correct them before continuing';
				
				$('.form-notification h3.section-heading').html(message);
	      $('.form-notification').show();
	    } else {
	      $('.form-notification').hide();
	    }
	  },
	  submitHandler: function(form) {
	   	form.submit();
	  }
	});
	
	getInvolvedForms();
};

function getInvolvedForms() {	
	// Get involved tabs
	$('#get-involved-tabs .get-involved-tab .border').hover(function(){
		$(this).addClass('hover-border');
	},
	function(){
		$(this).removeClass('hover-border');
	});
		
	$('#get-involved-tabs .get-involved-tab .border').click(function(){	
		var pageOffset = $(scrollElement).scrollTop();		
		var getInvolvedTrigger = $(this).closest('.get-involved-tab').index();		
		switch (getInvolvedTrigger) {
			case 0:
			  getInvolvedFormSetup('tertiary')
			  break;
			case 1:
			  getInvolvedFormSetup('industry')
			  break;
			case 2:
			  getInvolvedFormSetup('npo')
			  break;
		}	
		// Don't jump the page
		$(scrollElement).scrollTop(pageOffset);	
		return false;
	});
				
	$.validator.addMethod('ter-team-mate-select', function(value, element) {		
		// Herp derp
		if (($(element).find('option:selected').val() != '') && ($(element).parent().prev().find('input[type=text]').val() != '')) {				
			return true;
		} else {
			return false;
		}
	}, 'Please complete both fields');			
	
	
	// Tertiary Get Involved Form
	$('#get-involved-tertiary-form form').validate({
		ignoreTitle: true,
		ignore: ':not(:visible)',
		rules: {
		  'first_name': 'required',
			'surname': 'required',
			'email': {required:true, email:true},
			'contact_phone': {required:true, digits:true, minlength:7},
			'tertiary_institute': 'required',
			'course': 'required',
			'tutor': 'required',
			'tutor_email': {required:true, email:true},
			'tech_specialities': {required:true, minlength:10, maxlength: 1000},
			'testimonial': {required:true, minlength:10, maxlength: 1000}
		},
		messages: {
			'first_name': 'Please enter your first name',
			'surname': 'Please enter your last name',
			'email': {required:'Please enter your email address', email:'Please enter a valid email address'},
			'contact_phone': {required:'Please enter a phone number', digits:'Please enter a valid phone number, digits only', minlength: 'Phone number must be longer than 7 digits'},
			'tertiary_institute': 'The yMedia Challenge is only open to students of tertiary institutes in Auckland. Please select your school&nbsp;or&nbsp;university.',
			'course': 'Please enter the name of your course',
			'tutor': 'Please provide your tutor&rsquo;s full name',
			'tutor_email': {required:'Please enter your tutor&rsquo;s email address', email:'Please enter a valid email address'},
			'tech_specialities': {required:'Please let us know what your technical specialties are', minlength:'Input is too short', maxlength:jQuery.format('Input is too long, please shorten to less than {0} characters')},
			'testimonial': {required:'Your testimonial helps us to decide which teams are selected to participate in the challenge. Please write a little about yourself and your&nbsp;team', minlength:'Input is too short', maxlength:jQuery.format('Input is too long, please shorten to less than {0} characters')}
		},
		errorPlacement: function(error, element) {		
			if ($(element).parents('.row-group').length > 0){				
				// $(element).parents('.form-sub-row').find('label.error').css({'display':'block'});
			} else {
				$(element).parent().append(error);
				$(error).css({'display':'block'});
			}			
		},
		highlight: function(element, errorClass, validClass) { 
			if ($(element).hasClass('ter-team-mate-select')) {
				$(element).closest('.input-wrapper').parent().addClass('error-row').removeClass('success-row')
				$(element).closest('.form-sub-row').find('label.error').css({'display':'block'});				
			} else {
				$(element).closest('.input-wrapper').parent().addClass('error-row').removeClass('success-row');
				$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
				$(element).closest('.form-sub-row').find('label.error').css({'display':'block'});
			}	
	  },
	  unhighlight: function(element, errorClass, validClass) {
			if ($(element).hasClass('ter-team-mate')) {
				// do nothing
			} else {
		    $(element).closest('.input-wrapper').parent().addClass('success-row').removeClass('error-row');
				// $(element).closest('.input-wrapper').find('label.error').css({'display':'none'});
				// $(element).closest('.form-sub-row').find('label.error').css({'display':'none'});	
			}
	  },						
		invalidHandler: function(form, validator) {
	    var errors = validator.numberOfInvalids();
	    if (errors) {
				var message = errors == 1
	        ? 'This form contains 1 error, please correct it before continuing'
	        : 'This form contains ' + errors + ' errors, please correct them before continuing';
				
				$(this).find('.form-notification h3.section-heading').html(message);
	      $(this).find('.form-notification').show();
	    } else {
	      $(this).find('.form-notification').hide();
	    }
	  },
	  submitHandler: function(form) {
	   	form.submit();
	  }
	});
	
	
	// Industry Get Involved Form
	$('#get-involved-industry-form form').validate({
		ignoreTitle: true,
		ignore: ':not(:visible)',
		rules: {
		  'first_name': 'required',
			'surname': 'required',
			'email': {required:true, email:true},
			'contact_phone': {required:true, digits:true, minlength:7},
			'company': 'required',
			'role': 'required',
			'website': {required:true, url: true},
			'specialties': {required:true, minlength:10, maxlength: 1000},
			'participation_capacity[]': {required:true, minlength:1}
		},
		messages: {
			'first_name': 'Please enter your first name',
			'surname': 'Please enter your last name',
			'email': {required:'Please enter your email address', email:'Please enter a valid email address'},
			'contact_phone': {required:'Please enter a phone number', digits:'Please enter a valid phone number, digits only', minlength: 'Phone number must be longer than 7 digits'},
			'company': 'Please enter the name of your agency or organisation',
			'role': 'Please enter your role at your agency or organisation',
			'website': {required:'Please enter your organisations&rsquo; URL', url: 'Please enter a valid website'},
			'specialties': {required:'Please describe your professional specialties. These will help us to match you with a student team requiring this specialised&nbsp;mentoring', minlength:'Input is too short', maxlength:jQuery.format('Input is too long, please shorten to less than {0} characters')},
			'participation_capacity[]': {required:'Please select how you wish to contribute to the yMedia Challenge this year (you can talk to us about changing this&nbsp;later)', minlength:jQuery.format('You must select at least {0} option')}
		},
		errorPlacement: function(error, element) {		
			if ($(element).parents('.col-wrapper').length > 0){				
				$(element).parents('.input-inner').append(error);				
			} else {
				$(element).parent().append(error);
				$(error).css({'display':'block'});
			}			
		},
		highlight: function(element, errorClass, validClass) {
			$(element).closest('.input-wrapper').parent().addClass('error-row').removeClass('success-row');
			$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
	  },
	  unhighlight: function(element, errorClass, validClass) {
	    $(element).closest('.input-wrapper').parent().addClass('success-row').removeClass('error-row');
			$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
	  },						
		invalidHandler: function(form, validator) {
	    var errors = validator.numberOfInvalids();
	    if (errors) {
				var message = errors == 1
	        ? 'This form contains 1 error, please correct it before continuing'
	        : 'This form contains ' + errors + ' errors, please correct them before continuing';
				
				$(this).find('.form-notification h3.section-heading').html(message);
	      $(this).find('.form-notification').show();
	    } else {
	      $(this).find('.form-notification').hide();
	    }
	  },
	  submitHandler: function(form) {
	   	form.submit();
	  }
	});
	
	
	// NPO Get Involved Form
	$('#get-involved-npo-form form').validate({
		ignoreTitle: true,
		ignore: ':not(:visible)',
		rules: {
		  'first_name': 'required',
			'surname': 'required',
			'email': {required:true, email:true},
			'contact_phone': {required:true, digits:true, minlength:7},
			'npo_name': 'required',
			'district': 'required',
			'areas_of_interest': {required:true, minlength:10, maxlength: 1000},
			'capability': 'required'
		},
		messages: {
			'first_name': 'Please enter your first name',
			'surname': 'Please enter your last name',
			'email': {required:'Please enter your email address', email:'Please enter a valid email address'},
			'contact_phone': {required:'Please enter a phone number', digits:'Please enter a valid phone number, digits only', minlength: 'Phone number must be longer than 7 digits'},
			'npo_name': 'Please enter the name of your not for profit organisation',
			'district': 'Please select the district your organisation resides in, the challenge is open to participants in the Auckland region&nbsp;only',
			'areas_of_interest': {required:'Please enter some text to tell us what you&rsquo;re interested in learning about through participating in the yMedia&nbsp;Challenge', minlength:'Input is too short', maxlength:jQuery.format('Input is too long, please shorten to less than {0} characters')},
			'capability': 'Please rank your current capability'
		},
		errorPlacement: function(error, element) {
			$(element).parent().append(error);
			$(error).css({'display':'block'});
		},
		highlight: function(element, errorClass, validClass) {
			$(element).closest('.input-wrapper').parent().addClass('error-row').removeClass('success-row');
			$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
	  },
	  unhighlight: function(element, errorClass, validClass) {
	    $(element).closest('.input-wrapper').parent().addClass('success-row').removeClass('error-row');
			$(element).closest('.input-wrapper').find('label.error').css({'display':'block'});
	  },						
		invalidHandler: function(form, validator) {
	    var errors = validator.numberOfInvalids();
	    if (errors) {
				var message = errors == 1
	        ? 'This form contains 1 error, please correct it before continuing'
	        : 'This form contains ' + errors + ' errors, please correct them before continuing';
				
				$(this).find('.form-notification h3.section-heading').html(message);
	      $(this).find('.form-notification').show();
	    } else {
	      $(this).find('.form-notification').hide();
	    }
	  },
	  submitHandler: function(form) {
	   	form.submit();
	  }
	});
}

function getInvolvedFormSetup(getInvolvedForm) {				
	$(scrollElement).stop().animate({scrollTop: $('#get-involved-tabs').offset().top-25}, 150);
	$('#get-involved-tertiary-form, #get-involved-industry-form, #get-involved-npo-form').hide();
	$('#get-involved-tabs .border.active').removeClass('active');
	$('#get-involved-tabs').addClass('active-tabs');		
	
	getInvolvedTabsLayout();
	
	$('#get-involved-'+getInvolvedForm+'-tab .border').addClass('active');
	$('#get-involved-'+getInvolvedForm+'-form').show();
			
	if ($('#ter-num-teammates').length > 0){
		var number = $('#ter-num-teammates').val();
		var total = $('#ter-num-teammates').find('option').length;
		showTeamMates(number, total)
	}
	
	// $(scrollElement).scrollTop(pageOffset);
	
	$('#ter-num-teammates').change(function(){
		var number = $(this).val();				
		var total = $(this).find('option').length;
		showTeamMates(number, total)
	})

	function showTeamMates(number, total){
		var number = number;
		var total = total;
		for (i=1; i<=total; i++) {
			if (i <= number) {								
				$('#ter-team-mates .form-sub-row:eq('+i+')').show();				
			} else {
				$('#ter-team-mates .form-sub-row:eq('+i+')').hide();
			}
		}
	}
};

function tumblr() {
	// Images	
	$('.post .content img').each(function(){
		$(this).wrap('<span class="image-wrapper appendneg1" />')		
	})
	
	// Blockquotes
	$('.post.quote .quotation blockquote').each(function(){
		
		if ($(this).find('p').length == 0) {
			$(this).wrapInner('<p></p>');
		}
		
		$('p:first', this).prepend('<span class="left">&ldquo;</span>');
		$('p:last', this).append('<span class="right">&rdquo;</span>');
	})
	
	// Photosets
	$('.post.photo .media .html_photoset').each(function(){
		
		var photoSet = $(this);	
		var imageWidths = [];
		var totalImages = $(this).find('img').length;
		var loadedImages = 0;
		
		$(this).find('img').each(function() {			
			if(!($(this)[0].complete)){
				$(this).bind('load', function(){					
					imageWidths.push($(this).width());					
					loadedImages += 1;
					centerPhotoContent();
				})
			} else {
				imageWidths.push($(this).width());				
				loadedImages += 1;
				centerPhotoContent();
			}			
		})
		
		function sortNumber(a,b) {
			return b - a;
		}
		
		function centerPhotoContent() {			
			if(loadedImages == totalImages){
				imageWidths = imageWidths.sort(sortNumber);				
				$(photoSet).width(imageWidths[0]);				
			}
		}		
	})
	
	
	/*
		Better Vimeo Embeds on Tumblr by Matthew Buchanan
		http://matthewbuchanan.name/141302328
	*/	
	$(".post.video object[data^='http://vimeo.com']").each(function() {
			var parent = $(this).parent();
			var vimeoCode = parent.html();
			var params = "";
			if (vimeoCode.toLowerCase().indexOf("<param") == -1) {
				$("param", this).each(function() {
					params += $(this).get(0).outerHTML;
				});
			}
			var oldOpts = /show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=00ADEF/g;
			var newOpts = "show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=FF008D";
			vimeoCode = vimeoCode.replace(oldOpts, newOpts);
			if (params != "") {
				params = params.replace(oldOpts, newOpts);
				vimeoCode = vimeoCode.replace(/<embed/i, params + "<embed");
			}
			parent.html(vimeoCode);
		});
		
		
		/*
			Widescreen YouTube Embeds by Matthew Buchanan & Hayden Hunter
			http://matthewbuchanan.name/451892574
			http://blog.haydenhunter.me

			Released under a Creative Commons attribution license:
			http://creativecommons.org/licenses/by/3.0/nz/
		*/		
		$(".post.video object").each(function () {
			if ($(this).find("embed[src^='http://www.youtube.com']").length > 0) {
				// Identify and hide embed(s)
				var parent = $(this).parent();
				parent.css("visibility","hidden");
				var youtubeCode = parent.html();
				var params = "";
				if (youtubeCode.toLowerCase().indexOf("<param") == -1) {
					// IE doesn't return params with html(), so…
					$("param", this).each(function () {
						params += $(this).get(0).outerHTML;
					});
				}
				// Set colours in control bar to match page background
				var oldOpts = /rel=0/g;
				var newOpts = "rel=0&amp;color1=0xF2F2F2&amp;color2=0xF2F2F2";
				youtubeCode = youtubeCode.replace(oldOpts, newOpts);
				if (params != "") {
					params = params.replace(oldOpts, newOpts);
					youtubeCode = youtubeCode.replace(/<embed/i, params + "<embed");
				}
				// Extract YouTube ID and calculate ideal height
				var youtubeIDParam = $(this).find("embed").attr("src");
				var youtubeIDPattern = /\/v\/([0-9A-Za-z-_]*)/;
				var youtubeID = youtubeIDParam.match(youtubeIDPattern);
				var youtubeHeight = Math.floor(parent.find("object").width() * 0.75 + 25);
				var youtubeHeightWide = Math.floor(parent.find("object").width() * 0.5625 + 25);
				// Test for widescreen aspect ratio
				$.getJSON("http://gdata.youtube.com/feeds/api/videos/" + youtubeID[1] + "?v=2&alt=json-in-script&callback=?", function (data) {
					oldOpts = /height="?([0-9]*)"?/g;
					if (data.entry.media$group.yt$aspectRatio != null) {
						newOpts = 'height="' + youtubeHeightWide + '"';
					} else {
						newOpts = 'height="' + youtubeHeight + '"';
					}
					youtubeCode = youtubeCode.replace(oldOpts, newOpts);
					if (params != "") {
						params = params.replace(oldOpts, newOpts);
						youtubeCode = youtubeCode.replace(/<embed/i, params + "<embed");
					}
					// Replace YouTube embed with new code
					parent.html(youtubeCode).css("visibility","visible");
				});
			}
		});
		
		
		
		
	

	
}

jQuery.fn.imageFrame = function(options) {	
	var defaults = {ratio: 0.75};	
	var opts = jQuery.extend(defaults, options);
	
	return this.each(function() {		
		
		$(this).hide();
				
		var frameWidth = $(this).parent().width();
		var frameHeight = frameWidth*opts.ratio;	
					
		$(this).height(frameHeight).width(frameWidth).css({'zoom':1}).show();
		
		var frameDimensions = {w:frameWidth, h:frameHeight};
				
		var totalImages = $(this).find('.image').length;
		var loadedImages = 0;
					
		$(this).find('.image:not(.loaded)').each(function() {
			$(this).css({'visibility':'hidden', 'opacity':0});
			
			if(!($(this).find('img')[0].complete)){				
				$(this).find('img').bind('load', function(){
					loadedImages += 1;
					$(this).parent().imageScale(loadedImages, totalImages, frameDimensions);
				})
			} else {				
				loadedImages += 1;
				$(this).imageScale(loadedImages, totalImages, frameDimensions);
			}
		})		
						
		$(this).find('.image.loaded').each(function() {
			loadedImages += 1;
			$(this).imageScale(loadedImages, totalImages, frameDimensions);		
		})
		
	})
};

jQuery.fn.imageScale = function(loadedImages, totalImages, frameDimensions) {	
	return this.each(function() {
		
		$(this).width('auto').height('auto');				
		$('img', this).removeAttr('width').removeAttr('height').removeAttr('style');
		
		var parentFrameDimensions = frameDimensions;
		var sortFrameDimensions = (parentFrameDimensions.w >= parentFrameDimensions.h) ? ['w', 'h'] : ['h', 'w'];
		var frameLargeSide = sortFrameDimensions[0];
		var frameOtherSide = sortFrameDimensions[1];
			
		var origImageDimensions = {w:$(this).width(), h:$(this).height()};		
		var sortImageDimensions = (origImageDimensions.w >= origImageDimensions.h) ? ['w', 'h'] : ['h', 'w'];
		var imageLargeSide = sortImageDimensions[0];
		var imageOtherSide = sortImageDimensions[1];
		
		if (origImageDimensions['w'] == origImageDimensions['h']){
			var scaleFactor = parentFrameDimensions[frameLargeSide] / origImageDimensions[frameLargeSide];
		} else {
			var scaleFactor = parentFrameDimensions[imageOtherSide] / origImageDimensions[imageOtherSide];			
		}
		
		var newDimensions = {w:Math.floor(origImageDimensions['w'] * scaleFactor), h:Math.floor(scaleFactor * origImageDimensions['h'])};
				
		$(this).width(newDimensions['w']).height(newDimensions['h']).css({'top':'50%', 'left':'50%', 'margin-left':(newDimensions['w']/2)*-1, 'margin-top':(newDimensions['h']/2)*-1});
				
		if((loadedImages == totalImages) && (!($(this).parent().hasClass('fading')))) {
			$(this).parent().addClass('fading');
				
			var image1 = $(this).parent().find('.image').get(0);
			
			$(image1).css({'visibility':'visible', 'opacity':0}).animate({
				opacity: 1
			}, 250, function(){
				$(this).parent().find('.image').addClass('loaded');
				var targetFrame = $(this).parent();
				
				if (totalImages > 1) {
					setTimeout(function(){imageFade(targetFrame, 0)},4000);
				}
			})
		}		
	})
};

function imageFade(targetFrame, imageNum) {
	var totalImages = $(targetFrame).find('.image').length;		
	var currentImage = imageNum;
	
	if((currentImage+1) > (totalImages-1)){
		nextImage = 0;
	}	else {
		nextImage = currentImage+1;
	}
	
	var imageElementsArray = $(targetFrame).find('.image');
	
	$(imageElementsArray[currentImage]).animate({
		opacity: 0
		}, 750, function(){
			$(this).css('visibility','hidden');		
		}		
	);
	$(imageElementsArray[nextImage]).css({'visibility':'visible', 'opacity':0}).animate({
		opacity: 1
		}, 750, function(){
			setTimeout(function(){imageFade(targetFrame, nextImage)},4000);			
	});
};

jQuery.fn.duplicateFeed = function(options) {
	// opts for duplication source and number of items		
	var opts = jQuery.extend(options);
	
	return this.each(function() {
		var sourceHTML = opts.source.find('.feed-content').html()		
		$(this).find('.feed-content').html(sourceHTML);
		
		$(this).find('.feed-content .item').each(function(i){
			if (i+1 <= opts.items) {
				$(this).show();
			} else {
				$(this).hide();
			}
		})
	})
};

jQuery.fn.getTwitter = function(options) {
	var defaults = {
		username: null,
		numItems: 3,
		numWideItems: 6
	};
	
	return this.each(function() {		
		var wrapper = $(this);
		
		// If inline params exist replace the function's params
		if(wrapper.attr('title') != ''){
			var options = [], item;
			var optionsInline = wrapper.attr('title').split(',');		
			for(var i = 0; i < optionsInline.length; i++) {
				item = optionsInline[i].split(':');
				options.push(item[0]);
				options[item[0]] = item[1];
			}
		}
				
		var opts = jQuery.extend(defaults, options);
		
		var numItems = parseInt(opts.numItems);
		var numWideItems = parseInt(opts.numWideItems);
		
		// Get maximum number of tweets to load (whatever is greater, normal or wide)		
		var maxItems = (numWideItems >= numItems) ? numWideItems : numItems;
		
		$.getJSON('http://twitter.com/statuses/user_timeline/'+opts.username+'.json?count='+maxItems+'&callback=?', function(tweets) {
						
			// http://twitter.com/javascripts/blogger.js
			var statusHTML = '';
		  for (var i=0; i<tweets.length; i++){
		    var username = tweets[i].user.screen_name;
		    var status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
		      return '<a href="'+url+'">'+url+'</a>';
		    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
		      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
		    }).replace(/\B#(\w+)/ig, function(hashtag) {
					return '<a class="hashtag" href="http://twitter.com/search?q=%23'+hashtag.substring(1)+'">'+hashtag+'</a>';
				});
		    statusHTML += '<li class="item"><p>'+status+'</p> <p class="meta"><a href="http://twitter.com/'+username+'/statuses/'+tweets[i].id+'">'+relative_time(tweets[i].created_at)+'</a></p></li>';
		  }
			
			wrapper.empty().append('<ul class="content-brief-list">'+statusHTML+'</ul>');
			
			wrapper.find('.content-brief-list li').each(function(i){
				if(i+1 > numItems){
					$(this).hide();
				}
			});
			
			// Duplicate content
			$('#'+wrapper.parent().attr('id')+'-wide').duplicateFeed({items:numWideItems, source:wrapper.parent()});
			
			function relative_time(time_value) {
			  var values = time_value.split(" ");
			  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
			  var parsed_date = Date.parse(time_value);
			  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
			  delta = delta + (relative_to.getTimezoneOffset() * 60);

			  if (delta < 60) {
			    return 'less than a minute ago';
			  } else if(delta < 120) {
			    return 'about a minute ago';
			  } else if(delta < (60*60)) {
			    return (parseInt(delta / 60)).toString() + ' minutes ago';
			  } else if(delta < (120*60)) {
			    return 'about an hour ago';
			  } else if(delta < (24*60*60)) {
			    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
			  } else if(delta < (48*60*60)) {
			    return '1 day ago';
			  } else {
			    return (parseInt(delta / 86400)).toString() + ' days ago';
			  }
			}			
		});		
	})
};

jQuery.fn.getTumblr = function(options) {
	var defaults = {
		username: null,
		numItems: 3,
		numWideItems: 6,
		truncation: 140,
		tagged: '',
		filterText: ''
	};
	
	return this.each(function() {		
		var wrapper = $(this);
		
		// If inline params exist replace the function's params
		if(wrapper.attr('title') != ''){
			var options = [], item;
			var optionsInline = wrapper.attr('title').split(',');		
			for(var i = 0; i < optionsInline.length; i++) {
				item = optionsInline[i].split(':');
				options.push(item[0]);
				options[item[0]] = item[1];
			}
		}
				
		var opts = jQuery.extend(defaults, options);
		
		var numItems = parseInt(opts.numItems);
		var numWideItems = parseInt(opts.numWideItems);
		var truncation = parseInt(opts.truncation);
		var tagged = '&tagged='+opts.tagged;
		var filterText = (opts.filterText == 'true') ? '&filter=text' : '';
		
		// Get maximum number of tweets to load (whatever is greater, normal or wide)		
		var maxItems = (numWideItems >= numItems) ? numWideItems : numItems;
		var maxRetreiveItems = (maxItems+10 > 25) ? 50 : 25;
		
		$.getJSON('http://'+opts.username+'.tumblr.com/api/read/json?&num='+maxRetreiveItems+'&callback=?'+tagged+filterText, function(posts) {
			
			var postsHTML = '';
			var postsCount = 0;
			
			for (var i=0; i<posts.posts.length; i++){
				if (postsCount < maxItems){
									
					// Regular post	
					if (posts.posts[i].type == 'regular'){
						var currentPost = posts.posts[i];
						var postURL = currentPost.url;
						var postTitle = currentPost['regular-title'];
						
						if (opts.filterText == 'true') {		
							var postBody = currentPost['regular-body'].substring(0, truncation);					
							var postBody = postBody.replace(/\w+$/, '');
							var postBody = postBody.substring(0, postBody.length-1);							
							postsHTML += '<li class="item"><h3><a href="'+postURL+'">'+postTitle+'</a></h3><p>'+postBody+'&hellip;&nbsp;<a href="'+postURL+'" class="truncation-link">Read&nbsp;More</a></p>'
						}	else {
							var postBody = currentPost['regular-body'];							
							if (postBody.indexOf('<!-- truncate -->') != -1) {
								var truncationPoint = postBody.indexOf('<!-- truncate -->');
								var postBody = postBody.substring(0, truncationPoint);
							}						
							postsHTML += '<li class="item"><h3><a href="'+postURL+'">'+postTitle+'</a></h3>'+postBody+'<p><a href="'+postURL+'" class="truncation-link">Read&nbsp;More</a></p>'							
						}						
						postsCount += 1;
					}
				
					// Link post
					if (posts.posts[i].type == 'link'){
						var currentPost = posts.posts[i];
						var postURL = currentPost.url;
						var postTitle = currentPost['link-text'];
						var postLinkURL = currentPost['link-url'];
					
						if (opts.filterText == 'true') {				
							var postBody = currentPost['link-description'].substring(0, truncation);					
							var postBody = postBody.replace(/\w+$/, '');
							var postBody = postBody.substring(0, postBody.length-1);
							
							postsHTML += '<li class="item"><h3><a href="'+postLinkURL+'">'+postTitle+'</a></h3><p>'+postBody+'&hellip;&nbsp;<a href="'+postURL+'" class="truncation-link">Read&nbsp;More</a></p>'					
						}	else {
							var postBody = currentPost['link-description'];							
							if (postBody.indexOf('<!-- truncate -->') != -1) {
								var truncationPoint = postBody.indexOf('<!-- truncate -->');
								var postBody = postBody.substring(0, truncationPoint);
							}
							postsHTML += '<li class="item"><h3><a href="'+postLinkURL+'">'+postTitle+'</a></h3>'+postBody+'<p><a href="'+postURL+'" class="truncation-link">Read&nbsp;More</a></p>'
						}
						postsCount += 1;
					}
				
					// Photo post
					if (posts.posts[i].type == 'photo'){
						var currentPost = posts.posts[i];
						var postURL = currentPost.url;
						var postPhotoURL = currentPost['photo-url-400'];
						var postPhotoLinkURL = postURL;
						var postSlug = currentPost['slug'];
					
						if (currentPost['photo-link-url'] != null){
							var postPhotoLinkURL = currentPost['photo-link-url'];
						}
						
						if (opts.filterText == 'true') {
							var postBody = currentPost['photo-caption'].substring(0, truncation);					
							var postBody = postBody.replace(/\w+$/, '');
							var postBody = postBody.substring(0, postBody.length-1);
							postsHTML += '<li class="item"><p class="photo"><a href="'+postPhotoLinkURL+'"><img src="'+postPhotoURL+'" alt="'+postSlug+'" /></a></p><p>'+postBody+'&hellip;&nbsp;<a href="'+postURL+'" class="truncation-link">Read&nbsp;More</a></p>'
						} else {
							var postBody = currentPost['photo-caption'];
							if (postBody.indexOf('<!-- truncate -->') != -1) {
								var truncationPoint = postBody.indexOf('<!-- truncate -->');
								var postBody = postBody.substring(0, truncationPoint);
							}
							postsHTML += '<li class="item"><p class="photo"><a href="'+postPhotoLinkURL+'"><img src="'+postPhotoURL+'" alt="'+postSlug+'" /></a></p>'+postBody+'<p><a href="'+postURL+'" class="truncation-link">Read&nbsp;More</a></p>'
						}
						postsCount += 1;
					}
				}				
		  }
		
			wrapper.empty().append('<ul class="content-brief-list">'+postsHTML+'</ul>');
			
			wrapper.find('.content-brief-list li').each(function(i){
				if(i+1 > numItems){
					$(this).hide();
				}
			});
			
			// Duplicate content			
			$('#'+wrapper.parent().attr('id')+'-wide').duplicateFeed({items:numWideItems, source:wrapper.parent()});				
				
		});		
	})
};

function debug(){
	
}

function scroll() {	
	var scrollOffsetTop = $(scrollElement).scrollTop();
	var scrollOffsetBottom = $(scrollElement).scrollTop()+windowHeight;
	var footerOffset = $('#footer').offset().top;
	
	if (hasPhotoFeature == true && !isIE6 && (hasPhotoFeatureLoaded == true)) {		
		
		var photoOffsetTop = columnBodyOffset;
		var photoOffsetBottom = columnBodyOffset+$('.photo-feature .photo').height();
		var photoHeight = $('.photo-feature .photo').height();
		var photoFeature = $('.photo-feature');
		var photoFeatureContent = $('.photo-feature-content');
		
		if (profileFeature == true){
			if (scrollOffsetBottom > photoOffsetBottom && (scrollOffsetBottom < footerOffset)) {
				photoFeatureContent.css({'position':'fixed', 'top':'auto', 'bottom':0})
			} else if (scrollOffsetBottom <= photoOffsetBottom){
				photoFeatureContent.css({'position':'relative', 'top':0, 'bottom':'auto'})
			} else if (scrollOffsetBottom > footerOffset) {
				photoFeatureContent.css({'position':'absolute', 'top':'auto', 'bottom':0})
			}		
		} else {
			if (scrollOffsetBottom > photoOffsetBottom && (scrollOffsetBottom < footerOffset)) {
				photoFeature.css({'position':'fixed', 'top':-columnBodyOffset - (photoHeight - windowHeight)})
			} else if (scrollOffsetBottom <= photoOffsetBottom){
				photoFeature.css({'position':'relative', 'top':0})
			} else if (scrollOffsetBottom > footerOffset) {
				photoFeature.css({'position':'absolute', 'top':columnBodyHeight-photoHeight})
			}			
		}	
	}
}

$(function() {	
	scrollElement();
	init();
	layout();
	navigation();
	venn();
	$(window).scroll(function() {
		scroll();
  });
	// debug();
});