$(document).ready(function() {
	initializeHelperFunctions();
	
	// set up homepage carousel
	jQuery(jQuery('.homepage-carousel ul')[0]).jcarousel({
		auto: 8,
		scroll: 1,
		wrap: 'last',
		initCallback: carousel_initCallback,
		itemVisibleInCallback: {
           onAfterAnimation: carousel_itemVisibleInCallbackAfterAnimation
        },
		itemFallbackDimension: 100
	});
	
	// sidebar menu expand/collapse
	jQuery('.sidebar ul.menu ul')
	.each(function(){
		var $span = $('<span />');
		var $ul = $(this);
		$span
			.insertBefore($ul)
			.addClass('expander')
			.click(function(){
				$ul.slideToggle(200);
				$span.toggleClass('open');
			});
	})
	.css({display:'none'});
	jQuery('.sidebar ul.menu li.active-trail span.expander').click();
	
	
});

function initializeHelperFunctions() {
	// replicates html5 placeholder attribute in browsers that do not support it
	if('placeholder' in document.createElement('textarea') == false) {
		$('input[placeholder], textarea[placeholder]').each(function(){
			var input = $(this);
			var placeholder = input.attr('placeholder');
			if (input.val() == placeholder) input.addClass('placeholder');
			input
				.focus(function(){
					if(input.val() == placeholder) input.val('').removeClass('placeholder');
				})
				.blur(function(){
					if(input.val() == '') input.val(placeholder).addClass('placeholder');
				});
		});
	};
}

function makeRoundedCorners() {
	var $roundedBox = $('.jcarousel-clip');
	
	$(document.createElement('div')).addClass('maskTopLeft').appendTo($roundedBox)
    $(document.createElement('div')).addClass('maskTopRight').appendTo($roundedBox)
    $(document.createElement('div')).addClass('maskBottomLeft').appendTo($roundedBox)
    $(document.createElement('div')).addClass('maskBottomRight').appendTo($roundedBox)
}

function carousel_initCallback(carousel) {
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});
	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});
	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
	
	$('.carousel-controls div.views-row').bind('click', function() {
		carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
		return false;
	});
	
	makeRoundedCorners();
}; 

function carousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
	$('.carousel-controls div.views-row:nth-child('+$(item).attr('jcarouselindex')+')').addClass('active').siblings().removeClass('active');
};
