


$j(function() {
	
	var fieldsetCount = $j('#formElem').children().length;
	
	var current 	= 1;
 
	var stepsWidth	= 0;
    var widths 		= new Array();
	$j('#steps .step').each(function(i){
        var $jstep 		= $j(this);
		widths[i]  		= stepsWidth;
        stepsWidth	 	+= $jstep.width();
    });
	$j('#steps').width(stepsWidth);
	
	
	$j('#formElem').children(':first').find(':input:first').focus();	
	
	
	$j('#imagesubnav').show();
	
    $j('#imagesubnav a').bind('click',function(e){
		var $jthis	= $j(this);
		var prev	= current;
		$jthis.closest('ul').find('li').removeClass('selected');
        $jthis.parent().addClass('selected');
		
		current = $jthis.parent().index() + 1;
		
        $j('#steps').stop().animate({
            marginLeft: '-' + widths[current-1] + 'px'
        },500,function(){
			if(current == fieldsetCount)
				validateSteps();
			else
				validateStep(prev);
			$j('#formElem').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();	
		});
        e.preventDefault();
    });
	
	
	$j('#formElem > fieldset').each(function(){
		var $jfieldset = $j(this);
		$jfieldset.children(':last').find(':input').keydown(function(e){
			if (e.which == 9){
				$j('#imagesubnav li:nth-child(' + (parseInt(current)+1) + ') a').click();
				
				$j(this).blur();
				e.preventDefault();
			}
		});
	});
	
	
	function validateSteps(){
		var FormErrors = false;
		for(var i = 1; i < fieldsetCount; ++i){
			var error = validateStep(i);
			if(error == -1)
				FormErrors = true;
		}
		$j('#formElem').data('errors',FormErrors);	
	}
	
	
	function validateStep(step){
		if(step == fieldsetCount) return;
		
		var error = 1;
		var hasError = false;
		$j('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
			var $jthis 		= $j(this);
			var valueLength = jQuery.trim($jthis.val()).length;
			
			if(valueLength == ''){
				hasError = true;
				$jthis.css('background-color','#FFEDEF');
			}
			else
				$jthis.css('background-color','#FFFFFF');	
		});
		var $jlink = $j('#imagesubnav li:nth-child(' + parseInt(step) + ') a');
		$jlink.parent().find('.error,.checked').remove();
		
		var valclass = 'checked';
		if(hasError){
			error = -1;
			valclass = 'error';
		}
		$j('<span class="'+valclass+'"></span>').insertAfter($jlink);
		
		return error;
	}

	$j('#registerButton').bind('click',function(){
		if($j('#formElem').data('errors')){
			alert('Please correct the errors in the Form');
			return false;
		}	
	});
});
