/**
 *	fires when the dom is ready
 *
 */
$(document).ready(function() {
	blockLink();
	externalLinks();
	autoLightBox();
	modernizrActiveJS();
	animatedScroll();
	tabs();
	infieldHandler();
    slider();
    fetchTweets();
    checkForCloudButtons();
    checkForActiveState();
    checkForOnlineState();
});


function checkForCloudButtons() 
{
    if ( jQuery('#nav .cloud').length == 0 )
        return false;
     
    jQuery('#nav .cloud a').each( function(i, e) {
       jQuery(e).wrapInner('<span>');
    });
}

function checkForActiveState() 
{
    if ( jQuery('#nav .active').length == 0 )
        return false;
     
    jQuery('#nav > ul > li.active').each( function(i, e) {
       jQuery(e).append('<span id="active_nav">');
    });
    
    jQuery('#nav > ul > li.active-ancestor').each( function(i, e) {
       jQuery(e).append('<span id="active_nav">');
    });
}

function checkForOnlineState() 
{
    if ( jQuery('.cb_online a').length == 0 )
        return false;
     
    jQuery('.cb_online a').each( function(i, e) {
       jQuery(e).removeAttr('href');
    });
    
}

/**
 *	Add Tweets to the frontpage
 *
 */
function fetchTweets() {
	
	if ($('#tweet').length > 0) {
		var usernames = new Array(twitterUsernames);	

		$("#tweet").tweet({
			count: 1,
			fetch: 20,
			username: usernames,	
			loading_text: "",
			template: "<p>{text}</p><span class='meta'><span class='tweet_time'>{tweet_relative_time}</span> <span class='link'><a class='blend' rel='external' href='{user_url}'>Meer updates</a></span></span>"
		})
		.bind("empty", function() { 
			$(this).append(""); 
		});
	}
}

/**
 *	animated Slider
 *
 */
function slider() {
	var slider 	 	= $('#slider .slides');
	var bgs 	 	= $('#slider .bgs');
	var nextprev 	= $('#slider .control');
	var slidecount 	= $('li',slider).length;
	
	if ( slider.length > 0 ) {
	
		// slider
		slider.cycle({ 
			fx:     'fade', 
			speed:  'fast',
			timeout: 0, 
			pause: 	1,
			prev:   '#control_prev', 
			next:   '#control_next', 	
			pager: 	'#controls',
			cleartype: true,
			cleartypeNoBg: true,
			after:   onAfter, // callback 
			pagerAnchorBuilder: pagerFactory 
		});			
		
		// on hover
		$('#slider').hover(
			function() { 
				nextprev.show(); 			
			},
			function() { 
				nextprev.hide(); 
			}		
		);
	}
	
	// callback
	function onAfter(previous, current) {	
		var index = $(current).attr('id').replace('slide','');
		
		// animate backgrounds
		bgs.hide().css({ marginLeft: '120px'});
		$('#bgs'+index).animate({ marginLeft: '0px', opacity: 'show'}, 200);
	}
	
	// display pagers
	function pagerFactory(idx, slide) {	
		if (slidecount < 2 ) 
			return false;
			
		//var s = idx > 2 ? ' style="display:none"' : '';
		return '<li><a href="#">'+(idx+1)+'</a></li>';
	};
}

/**
 * wordpress theme url
 *
 */
function wpUrl() {
	return $('link[href$="reset.css"]').attr('href').replace('/assets/css/reset.css','');
}

/**
 *	Adds a link/hover to it's parent
 *
 */
function blockLink() {
	// click
	var elements = '.blocklink';	
	$(elements).each(function(){
		var thelink = $(this).attr('href');		
		var theDiv 	= $(this).parent();		
		if ((thelink != '')&&(thelink != '#')) {
			theDiv.css({'cursor':'hand','cursor':'pointer'})			
			.click(function(){
				window.location.href = thelink;			
			});
		}		
	});
	
	// hover
	var elements = '.blockhover';
	$(elements).each(function(){			
		var theDiv 	= $(this).parent();
		if ($(this).hasClass('blockhover')) {			
			theDiv.hover( function(){
				theDiv.addClass('active')
			}, function() { 
				theDiv.removeClass('active') 
			});
		}
	});	
};

/**
 * External Link; New-Window Links in a Standards-Compliant W3C
 */
function externalLinks() {	
	$("a[rel*=external]").each(function(i){
		this.target="_blank";
	});
}

/**
 *	Adds lightbox to post images that are wrapped in a imagelink
 *
 */
function autoLightBox() {	
	var include = '.entry img';
	var exclude = '.entry .gallery img';
	
	// fancybox exists?
	if(typeof fancybox != 'function')
		return false;	
	
	// add auto lightbox
	$(include).not(exclude).each( function() {		
		var title 		= $(this).attr('title');
		var link 		= $(this).parents('a');		
		if( title && link ) {
			var href 	= link.attr('href');
			if ( href ) {
				if (href.match(/\.(jpg|png|gif)/) ) {
					link.fancybox({
						'opacity'			: true,
						'href'				: href,
						'overlayColor'		: '#000',
						'hideOnContentClick': true,
						'overlayOpacity'	: 0.7,
						'centerOnScroll'	: true				
					});	
				}
			}
		}
	});	
}

/**
 *	Change Class from noJS to activeJS
 */
function modernizrActiveJS() {
	if ($("body").hasClass("noJs")) {
		$("body").removeClass("noJs").addClass("activeJs");
	}
}

/**
 *	animated Scroll
 *
 */
function animatedScroll() {
	$('a[href*="#"]').click( function(event){		
		var full_url 	= this.href;
		var parts 		= full_url.split("#");
		var trgt 		= parts[1];		

		// check if element exists
		if ( !$("#"+trgt).length )
			return;
		
		// element found, prevent click		
		event.preventDefault();	
		
		// get offset
		var target_offset 	= $("#"+trgt).offset();
		var target_top 		= target_offset.top;
		
		// animate
		$('html, body').animate({scrollTop:target_top}, 500);
	});
	
	// Back To Top
	$('.back_to_top').click(function(){
		$('html, body').animate({scrollTop:0}, 1000);
		return false;
	});
	
	// display message on scroll
	var scroll_timer;
	var displayed 	= false;
	var $message 	= $('.back_to_top');
	var $window 	= $(window);
	var top 		= $(document.body).children(0).position().top;
	
	$window.scroll(function () {
		window.clearTimeout(scroll_timer);
		scroll_timer = window.setTimeout(function () { 
			if($window.scrollTop() <= top) {
				displayed = false;
				$message.fadeOut(500);
			}
			else if(displayed == false) {
				displayed = true;
				$message.stop(true, true).show().click(function () { $message.fadeOut(500); });
			}
		}, 100);
	});
	
	// when user reaches page by hash
	if (window.location.hash) {
		$message.fadeIn(800);
	}	
}

/**
 * tab functions
 *
 */
function tabs() {	
	$("ul.tabs").tabs("ul.tabs_content > li");
};

/**
 *	Allows for input and textarea elements to have infield labels
 *
 */
function infieldHandler() {

	if ( !$('#searchform').length )
		return false;
	
	$('#searchform .infield').each( function(index, e) {

					
		// don't show value if something is filled in
		if ( $(e).val() != '' ) {
			getInfieldTarget(this).css('opacity', 0);
		}
		
		// what happens on focus
		$(e).focus( function() {
			getInfieldTarget(this).addClass('infield_focus');
		// what happens on blur
		}).blur( function() {
			// restore if empty
			if ( $(this).val() == '') {
				getInfieldTarget(this).animate({
					opacity: 1
				}, 450);
			}
			
			getInfieldTarget(this).removeClass('infield_focus');
		});
		
		// check value on keypress
		$(e).keypress( function() {
			if ( $(this).value != '')
				getInfieldTarget(this).css('opacity', 0);
		});
		
		// ie fix for transparency
		$(e).prev('.infield_label').click( function() {
			$(this).closest('p').find('.infield').focus();
		});
	});
}

function getInfieldTarget(e) {
	// common parent of each form elements
	var parentTag = 'p';
	
	return $(e).closest(parentTag).find('.infield_label span');
}
