$(function() {
	
	$('#other_periodic').hide();
    $('#increase_div').hide();
    
    $('input[name="periodic_payments"]').click(function() {

        switch ( $(this).val() ) {

        case 'Yes' : //if by cause, show cause, hide foundation
            $('#other_periodic').slideDown();
        break;

        case 'No' : //if by cause, show cause, hide foundation
            if( $('#other_periodic').is(":visible") ) {
                  $('#other_periodic').slideUp();
                  $('#nav').slideDown();
              } else {
                    $('#nav').slideDown();
              }
        break;
        }

    });



    $('#nextPaymentStream').click(function() {
        $("#nextPaymentStream").html("Loading... <img src='../asset/ajax.gif' />");
		
		var name = $("#name").val();
        var email = $("#email").val();
        var phone = $("#phoneNumber").val();

      if($("#name").valid(), $("#email").valid(), $("#phoneNumber").valid()) {
		  
		  		  
		  $("#total1").html("6");
		 
        $('#nextPaymentStream').load("../includes/initial.php",{"name" : name,"email" : email,"phone" : phone}, function() { 
        $('#steps').stop().animate({
            marginLeft: '-335px'
        });
		return false;
    });
      } else {
         $("#nextPaymentStream").html("Next");
      }
    return false;
    });
    


    $('input[name="periodic_payments"]').click(function() {

        switch ( $(this).val() ) {

        case 'Yes' : //if by cause, show cause, hide foundation
            $('#steps').stop().animate({
            marginLeft: '-1005px'
        });
		
		
		
		$('#total3').html(4);
        return false;
        break;

        case 'No' : //if by cause, show cause, hide foundation
        $('#steps').stop().animate({
            marginLeft: '-2010px'
        });
		
		
		
		$('#total6').html(1);
        return false;
        break;
        }

    });
    
    $('input[name="frequency"]').click(function() {
         $('#steps').stop().animate({
            marginLeft: '-1340px'
        });
		
		
		
		$('#total3').html("4");
        return false;
     });
    
    $('input[name="increase"]').click(function() {

        if($("#nextPayment").valid(), $("#finalPayment").valid(), $("#periodicAmount").valid()) {

            switch ( $(this).val() ) {

            case 'Yes' : //if by cause, show cause, hide foundation
                $('#steps').stop().animate({
                marginLeft: '-1675px'
            });
			
			
			
		    $('#total5').html(2);
            break;

            case 'No' : //if by cause, show cause, hide foundation
               $('#steps').stop().animate({
                marginLeft: '-2010px'
            });
			
	   $('#total6').html(1);
            break;
            }
        
        } else {
            $("#increase").removeAttr("checked");
        }
    });


    $('#nextPeriodic').click(function() {
        $("#nextPeriodic").html("Loading... <img src='../asset/ajax.gif' />");

        if($("#payment_type").valid(),$("#insuranceCompany").valid()) {
			
        $('#steps').stop().animate({
            marginLeft: '-670px'
        });
		
	    $("#total2").html("5");
        return false;
        } else {
            $("#nextPeriodic").html("Next");
        }
    });
    
    $('#nextLumpSum').click(function() {
        $("#nextLumpSum").html("Loading... <img src='../asset/ajax.gif' />");
        $('#steps').stop().animate({
            marginLeft: '-2010px'
        });
		
	$('#total6').html(1);
        return false;
    });

    $('#calculate').click(function() {

         $("#calculate").html("Loading... <img src='../asset/ajax.gif' />");

        var name = $("#name").val();
        var email = $("#email").val();
        var phone = $("#phoneNumber").val();
        var payment_type = $('#payment_type').val();
        var insurance_company = $('#insuranceCompany').val();
        var next_payment = $('#nextPayment').val();
        var final_payment = $('#finalPayment').val();
        var frequency = $('#frequency').val();
        var amount = $('#periodicAmount').val();
        var increase_date = $('#increaseDate').val();
        var increase_amount = $('#increaseAmount').val();
        var lump1d = $('#lump1d').val();
        var lump1a = $('#lump1a').val();
        var lump2d = $('#lump2d').val();
        var lump2a = $('#lump2a').val();
        var lump3d = $('#lump3d').val();
        var lump3a = $('#lump3a').val();
        var lump4d = $('#lump4d').val();
        var lump4a = $('#lump4a').val();
        


        if($('input[name=periodic_payments]:checked', '#formElem').val() == "No") {
            
             if($("#lump1a").valid(), $("#lump1d").valid()) {
              $('#calculate').load("../includes/longForm.php",{
                "name" : name,
                "email" : email,
                "phone" : phone,
                "payment_type" : payment_type,
                "insurance_company" : insurance_company,
                "next_payment" : next_payment,
                "final_payment" : final_payment,
                "frequency" : frequency,
                "amount" : amount,
                "increase_date" : increase_date,
                "increase_amount" : increase_amount,
                "lump1d" : lump1d,
                "lump1a" : lump1a,
                "lump2d" : lump2d,
                "lump2a" : lump2a,
                "lump3d" : lump3d,
                "lump3a" : lump3a
                

                }
                , function() {
                $('#steps').stop().animate({
                    marginLeft: '-2345px'
                });
                return false;
            }
        );
     } else {
          $("#calculate").html("Calculate");
            }
        } else {
            
         $('#calculate').load("../includes/longForm.php",{
        "name" : name,
        "email" : email,
        "phone" : phone,
        "payment_type" : payment_type,
        "insurance_company" : insurance_company,
        "next_payment" : next_payment,
        "final_payment" : final_payment,
        "frequency" : frequency,
        "amount" : amount,
        "increase_date" : increase_date,
        "increase_amount" : increase_amount,
        "lump1d" : lump1d,
        "lump1a" : lump1a,
        "lump2d" : lump2d,
        "lump2a" : lump2a,
        "lump3d" : lump3d,
        "lump3a" : lump3a
      
        }
        , function() {
        $('#steps').stop().animate({
            marginLeft: '-2345px'
        });
        return false;
    }
);
        }
    return false;
    });

    $('.date-pick').datepicker({
			changeMonth: true,
			changeYear: true,
            yearRange: '2011:2050'
		});




	/*
	number of fieldsets
	*/
	var fieldsetCount = $('#formElem').children().length;
	
	/*
	current position of fieldset / navigation link
	*/
	var current 	= 1;
    
	/*
	sum and save the widths of each one of the fieldsets
	set the final sum as the total width of the steps element
	*/
	var stepsWidth	= 0;
    var widths 		= new Array();
	$('#steps .step').each(function(i){
        var $step 		= $(this);
		widths[i]  		= stepsWidth;
        stepsWidth	 	+= $step.width();
    });
	$('#steps').width(stepsWidth);
	
	/*
	to avoid problems in IE, focus the first input of the form
	*/
	$('#formElem').children(':first').find(':input:first').focus();	
	
	/*
	show the navigation bar
	*/
	$('#navigation').show();
	
	/*
	when clicking on a navigation link 
	the form slides to the corresponding fieldset
	*/
    $('#navigation a').bind('click',function(e){
		var $this	= $(this);
		var prev	= current;
		$this.closest('ul').find('li').removeClass('selected');
        $this.parent().addClass('selected');
		/*
		we store the position of the link
		in the current variable	
		*/
		current = $this.parent().index() + 1;
		/*
		animate / slide to the next or to the corresponding
		fieldset. The order of the links in the navigation
		is the order of the fieldsets.
		Also, after sliding, we trigger the focus on the first 
		input element of the new fieldset
		If we clicked on the last link (confirmation), then we validate
		all the fieldsets, otherwise we validate the previous one
		before the form slided
		*/
        $('#steps').stop().animate({
            marginLeft: '-' + widths[current-1] + 'px'
        },500,function(){
			if(current == fieldsetCount)
				validateSteps();
			else
				validateStep(prev);
			$('#formElem').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();	
		});
        e.preventDefault();
    });
	
	/*
	clicking on the tab (on the last input of each fieldset), makes the form
	slide to the next step
	*/
	$('#formElem > fieldset').each(function(){
		var $fieldset = $(this);
		$fieldset.children(':last').find(':input').keydown(function(e){
			if (e.which == 9){
				$('#navigation li:nth-child(' + (parseInt(current)+1) + ') a').click();
				/* force the blur for validation */
				$(this).blur();
				e.preventDefault();
			}
		});
	});
	
	/*
	validates errors on all the fieldsets
	records if the Form has errors in $('#formElem').data()
	*/
	function validateSteps(){
		var FormErrors = false;
		for(var i = 1; i < fieldsetCount; ++i){
			var error = validateStep(i);
			if(error == -1)
				FormErrors = true;
		}
		$('#formElem').data('errors',FormErrors);	
	}
	
	/*
	validates one fieldset
	and returns -1 if errors found, or 1 if not
	*/
	function validateStep(step){
		if(step == fieldsetCount) return;
		
		var error = 1;
		var hasError = false;
		$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
			var $this 		= $(this);
			var valueLength = jQuery.trim($this.val()).length;
			
			if(valueLength == ''){
				hasError = true;
				$this.css('background-color','#FFEDEF');
			}
			else
				$this.css('background-color','#FFFFFF');	
		});
		var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
		$link.parent().find('.error,.checked').remove();
		
		var valclass = 'checked';
		if(hasError){
			error = -1;
			valclass = 'error';
		}
		$('<span class="'+valclass+'"></span>').insertAfter($link);
		
		return error;
	}
	
	/*
	if there are errors don't allow the user to submit
	*/
	$('#registerButton').bind('click',function(){
		if($('#formElem').data('errors')){
			alert('Please correct the errors in the Form');
			return false;
		}	
	});
});
