$(document).ready(function() {

	/* [1] Hide the main wrapper */
	$('#wrapper').css({'visibility' : 'hidden'});


	/* [2] Remove all scrollbars and replace with jQuery scrollpanes */
	$('.scrollPane').jScrollPane({
		animateTo: true,
		animateInterval: 1
	});


	/* [3] Create the main sliding viewport */
	jQuery("div#slider1").codaSlider();


	/* [4] Setup behavior for the main navigation
	 * and the tiny footer links */
	setUpNavigationBehavior();


	/* [5] Setup NewsLetter Box behavior */
	 setUpNewsLetterBehavior();


	/* [6] Setup portfolio behavior */
	setUpPortfolioBehavior();


	/* [7] Dummy alter on RSS btn. Link it to something */
	$('#rss').click(function(){
		alert('Link this to your feed.')
	});


	/* [8] Setup the main slideshow */
	$('.removeOnLoad').remove();
	$("#slider").easySlider({
		auto: 			true,
		continuous:		true,
		numeric:		true,
		numericId:		'showNavigation'
	});


	/* [9] Setup the feature list for the services section */
	$.featureList(
		$("#tabs li a"),
		$("#output li"), {
			start_item : 0
		}
	);


	/* [10] Setup the lightbox behavior for the portfolio page */
	$("a[rel='folio']").colorbox({
		transition: 'elastic',
		speed: 400
	});


	/* [11] Setup the basic contact form behavior */
	setUpContactFormBehavior();


	/* [12] Setup navigation state according to startup location */
	setUpStartUpLocation();


	/* all processing done, time to revel everything */
	$('#wrapper').css({'visibility' : 'visible'});
	$('#sliderPics').css({'visibility' : 'visible'});
});
// end: onReady
//-----------------------------------------------------------------


/**
 * delNavActive removes the active css class
 * from all links of the main navigation. It
 * selects the main navigation links through
 * a simple jQuery selector and removes the
 * class from each selected element.
 *
 * @param	none
 * @return	none
 * @see		setUpNavigationBehavior
 */
function delNavActive() {
	$('#mainNavigation li a').each(function() {
		$(this).removeClass('navCurrent');
	});
}


/**
 * setUpNavigationBehavior defines the appearance
 * behavior for two sets of elements. The main
 * navigation, and the small section links in the
 * footer.
 *
 * For the main navigation, whenever a link is
 * clicked, first the active class ('.navCurrent')
 * is removed from all navigation links, and then
 * the class is added back to the clicked element.
 * Also, when any other link than Home is clicked,
 * the slideshow controls and slided up.
 *
 * For the footer links, it's a synchronization of
 * appearance. Whenever a footer link is clicked,
 * we highlight the correct button in the main
 * navigation. Since the order of the nav buttons
 * and the footer links is the same, we merely use
 * the index of the clicked element in the footer
 * and find the corresponding element in the main
 * navigation.
 *
 * @param	none
 * @return	none
 * @see		delNavActive
 */
function setUpNavigationBehavior() {
	//process the main navigation
	$('#mainNavigation li a').bind('click', function() {
		delNavActive();
		$(this).addClass('navCurrent');
		if(0 != $('#mainNavigation li a').index(this)) {
            slideUpShowNav();
        }
		else {
            slideDownShowNav();
        }
	});

	//process the footer links
	$('#footerLinks a.cross-link').bind('click', function() {
		delNavActive();
		var index = $('#footerLinks a.cross-link').index(this);
		$('#mainNavigation li a:nth(' + index + ')').addClass('navCurrent');
		if(index != 0) {
            slideUpShowNav();
		}
		else {
            slideDownShowNav();
		}
	});
}


/**
 * setUpNewsLetterBehavior defines browser specific
 * behavior for the sliding newsletter module by
 * animating it up and down, and also fading it in
 * and out when the browser is not IE6.
 *
 * The sliding newsletter module contains PNG images
 * which are processded via UnitPNGFix for IE6. If
 * jQuery fading in and out is performed on it, IE6
 * faces display problems. So, we do an (unfortunate)
 * sniff for IE6 and setup only the sliding up and
 * down behavior. For all other browsers, we allow
 * the fade in fade out behavior as well.
 *
 * @param	none
 * @return	none
 */
function setUpNewsLetterBehavior()
{
	if($.browser.msie && parseInt($.browser.version) <= 6)
	{
		$('#newsletter').click(function(){
			$('#newsLetterSlider').animate({
				height: 770
			}, function(){
				$('#nlEmail').focus();
			});
		});
		$('.closeNLB').click(function(){
			$('#newsLetterSlider').animate({
				height: 0
			});
		});
	}
	else
	{
		$('#newsletter').click(function(){
			$('#newsLetterSlider').animate({
				height: 770
			}, function(){
				$('#newsLetterBox').fadeIn();
				$('#nlEmail').focus();
			});
		});

		$('.closeNLB').click(function(){
			$('#newsLetterBox').fadeOut(
				function() {
					$('#newsLetterSlider').animate({
						height: 0
					});
				}
			);
		});
	}
}


/**
 * focusYear is a portfolio filtering related
 * function which accepts a year as the argument
 * and then filters the portfolio to display
 * only those items which match the year selected
 * by the user.
 *
 * @param	none
 * @return	none
 * @see		setUpPortfolioBehavior
 */
function focusYear(year) {

	var count = $('li.' + year).length;

	/*update the counter at the top right*/
	$('li#folioCount').fadeOut(
		function(){
			if (year == 'noFilter')
			{
				$('li#folioCount').html($('li.folioLi').length + ' project(s) found');
			}
			else
			{
				$('li#folioCount').html(count + ' project(s) found');
			}
			$('li#folioCount').fadeTo(200, 1);
		}
	);

	/*add more into this if you need more years*/
	var years = ['2010', '2009', '2008', '2007',
				 '2006', '2005', '2004', '2003',
				 '2002', '2001', '2000', '1999'];

	/* if the user selected 'show all', we show everything and scroll up */
	if(year == 'noFilter')
	{
		$('li.folioLi').fadeTo(200, 1, function(){
			$("#portFolioContainer")[0].scrollTo(0);
		});
		return;
	}

	/* if no items were found, fade all items */
	if(count == 0)
	{
		$('li.folioLi').fadeTo(200, 0.06);
		return;
	}

	/* fade out all items that are not from the current year */
	$('li.folioLi:not([class=folioLi ' + year + '])').fadeTo(200, 0.06);

	/* fade in the items from the current year */
	$('li.'+year).fadeTo(200, 1);

	/* scroll to the first such item (the -1 is necessary) */
	$("#portFolioContainer")[0].scrollTo($('li.'+year + ':nth(0)')[0].offsetTop - 1);
}


/**
 * setUpPortfolioBehavior binds the portfolio
 * filtering elements with the event handler
 * that actually does the filtering and displaying
 * of portfolio elements.
 *
 * @param	none
 * @return	none
 * @see		focusYear
 */
function setUpPortfolioBehavior() {
	//first, update the count.
	$('li#folioCount').html($('li.folioLi').length + ' project(s) found');

	//bind filter years to the focusYear function
	$('ul#portFolioFilter li a').click(function(e){
		if (!$(this).hasClass('activeFilter'))
		{
			var year = this.title;
			$('ul#portFolioFilter li a').removeClass('activeFilter');
			$(this).addClass('activeFilter');
			focusYear(year);
		}
	});
}


/**
 * setUpContactFormBehavior enables basic behavior
 * for the text input elements and the send and
 * clear buttons on the contact form. Functionality
 * for the clear button is enabled.
 *
 * @param	none
 * @return	none
 * @see		inputFocusHandler
 * 			inputBlurHandler
 * 			clearButtonHandler
 * 			sendButtonHandler
 *
 */
function setUpContactFormBehavior() {
	$('form#contactForm a#clearBtn').bind('click',			clearButtonHandler);
	$('form#contactForm a#sendBtn').bind('click',			sendButtonHandler);
	$('form#contactForm input[type=text]').bind('focus',	inputFocusHandler);
	$('form#contactForm input[type=text]').bind('blur',		inputBlurHandler);
	$('form#contactForm textarea').bind('focus',			inputFocusHandler);
	$('form#contactForm textarea').bind('blur',				inputBlurHandler);
}


/**
 * Handler for the focus event of the input text
 * fields and the textarea in the contact form.
 * Add a highlighting class to bring out the
 * field under focus.
 *
 * @param	none
 * @return	none
 * @see		setUpContactFormBehavior
 *
 */
function inputFocusHandler() {
	$(this).addClass('focusInput');
}


/**
 * Handler for the blur event of the input text
 * fields and the textarea in the contact form.
 * Removes the highlighting class from the field
 * that just lost focus.
 *
 * @param	none
 * @return	none
 * @see		setUpContactFormBehavior
 *
 */
function inputBlurHandler() {
	$(this).removeClass('focusInput');
}


/**
 * Handler for the clear button in the form.
 * Blanks out text fields, clear checkboxes,
 * clears textareas. Ideally, this should not
 * be so. Function should reset the form to
 * its default state, as the form might have
 * error loaded from the server with default
 * data. Alternate code included (commented
 * out).
 *
 * @param	none
 * @return	none
 * @see		setUpContactFormBehavior
 *
 */
function clearButtonHandler() {
	$('form#contactForm input[type=text]').each(function(index){
		this.value = '';
	});
	$('form#contactForm input[type=checkbox]').each(function(index){
		this.checked = false;
	});
	$('form#contactForm textarea').each(function(index){
		this.value = '';
	});
	//document.getElementById('contactForm').reset();
}


/**
 * This is the function that will be called
 * when the send button in the contact form
 * is clicked. You would want to write some
 * validation (client side), or just submit
 * the form as is and check everything server
 * side, (say in your servlet/controller
 * whatever.).
 *
 * @param	none
 * @return	none
 * @see		setUpContactFormBehavior
 *
 */
function sendButtonHandler() {
	//form submission or validation, et al.
}


/**
 * Slides up the main slideshow navigation
 * after a delay of 500 milliseconds.
 *
 * @param	none
 * @return	none
 * @see		setUpStartUpLocation
 * 			setUpNavigationBehavior
 *
 */
function slideUpShowNav() {
	$.timer(500, function (timer) {
        $('#showNavigation li').slideUp(350);
        timer.stop();
    });
}


/**
 * Slides down the main slideshow navigation
 * after a delay of 500 milliseconds.
 *
 * @param	none
 * @return	none
 * @see		setUpStartUpLocation
 * 			setUpNavigationBehavior
 *
 */
function slideDownShowNav() {
	$.timer(500, function (timer) {
        $('#showNavigation li').slideDown(350);
        timer.stop();
    });
}


/**
 * When a document is loaded to a section
 * directly, this function will set the
 * state of the navigation buttons correctly.
 *
 * @param	none
 * @return	none
 * @see		setUpContactFormBehavior
 *
 */
function setUpStartUpLocation()
{
	try {
		var url = window.location.href;
		if(url.split(/#/).length > 1) {
			var index = url.split(/#/)[1] - 1;
			delNavActive();
			$('#mainNavigation li a:nth(' + index + ')').addClass('navCurrent');
			if (index > 0) {
				slideUpShowNav();
			}
			else {
				$('#mainNavigation li a:nth(0)').addClass('navCurrent');
				slideDownShowNav();
			}
		}
		else {
			delNavActive();
			$('#mainNavigation li a:nth(0)').addClass('navCurrent');
			slideDownShowNav();
		}
	}
	catch (e) {
		if(null != typeof console) {
			console.warn('Exception in setting navigation state. Problems extracting from the URL.');
		}
		$('#mainNavigation li a:nth(0)').addClass('navCurrent');
	}
}
