jQuery(function($){
	$('ul[id$=accommodation] input').click(function(){
		var clicked = $(this);
		var participant = this.id.match(/participant_set-(\d+)/)[1];
		var trekoption = $('td.trek'+participant);
		if (clicked.val()=='D') {
		    trekoption.hide().find('[value=]').attr('checked', true);
		} else {
			trekoption.show();
		};
	});
    
    $('input[id$=dob_day]').focus(function(){
        var clicked = $(this);
        if (clicked.val()=='dd') {
            clicked.val('');
        }
    })
    $('input[id$=dob_day]').blur(function(){
        var clicked = $(this);
        if (clicked.val()=='') {
            clicked.val('dd');
        }
    })

    $('input[id$=dob_year]').focus(function(){
        var clicked = $(this);
        if (clicked.val()=='yyyy') {
            clicked.val('');
        }
    })
    $('input[id$=dob_year]').blur(function(){
        var clicked = $(this);
        if (clicked.val()=='') {
            clicked.val('yyyy');
        }
    })

    
    $('td#buttons').append('<input type="button" id="next" value="Add another participant"><input type="button" id="prev" value="Remove last participant">')
    function buttons() {
        if (current==6) {
            $('#next').hide();
        } else {
            $('#next').show();
        }
        if (current==1) {
            $('#prev').hide();
        } else {
            $('#prev').show();
        }
    }
    
    function validateParticipant(num) {
        fields = 
        [
            ['firstname', 'You must enter a first name'],
            ['surname', 'You must enter a surname'],
            ['sex', 'You must choose male or female'],
            ['diet', 'You must choose a menu option'],
            ['accommodation', 'You must choose an accommodation option']
        ]
        if (num==1) {
            fields.push(['email', 'You must enter your email address']);
            fields.push(['repeat_email', 'You must repeat your email address']);
        }
        var valid = true;
        message = []
        jQuery.each(fields, function() {
            var field = $('tr.participant' + num + ' :input[name$=' + this[0] + ']');
            if (field.is('input:radio')) {
				var radio = field.filter('input:checked');
		        if (radio.length==0 || radio.val()=="") {
                    valid = false;
                    message.push(this[1]);
				}
            } else if (field.val() == "" || field.val() == 'dd' || field.val() == 'yyyy') {
                valid = false;
                message.push(this[1]);
            }
        })
        if (num==1 & $('tr.participant1 :input[name$=email]').val() != $('tr.participant1 :input[name$=repeat_email]').val()) {
            valid = false;
            message.push('Email addresses must match');
        }
        var d = $('tr.participant' + num + ' :input[name$=day]').val();
        var m = +$('tr.participant' + num + ' :input[name$=month]').val()-1;
        var y = $('tr.participant' + num + ' :input[name$=year]').val();
        var dt = new Date;
        dt.setFullYear(y, m, d);
        if (d != dt.getDate() || m != dt.getMonth() || y != dt.getFullYear()) {
            valid = false;
            message.push('You must enter a valid date of birth');
        }
        var now = new Date;
        if (dt > now) {
            valid = false;
            message.push('Date of birth cannot be in the future');
        }
        
        if (message.length != 0) {
            alert(message.join('\n'));
        };
        return valid;
    }
    
    //for (var i=6;i>0;i--) {
        //if ($('tr.participant' + i + ' input[name$=accommodation]:checked').val() != 'I') {
            //$('tr.participant' + i + ' input[name$=roomtype]').parents('td:first').children().hide();
        //}
        //if ($('tr.participant' + i + ' select[name$=trekoption]').val() != 'C') {
            //$('tr.participant' + i + ' input[name$=bike]').hide().next().hide();
        //}
    //}
    var current = 6;

    for (var i=6;i>1;i--) {
        var show = false;
        $('tr.participant' + i + ' input:text').each(function() {
            var val = $(this).val();
            if (val != '' && val != 'dd' && val != 'yyyy') {
				current = i;
                show = true;
				return false;
            }
        })
        if (!show) {
            $('tr.participant' + i).hide();
        } else {
			if ($('tr.participant' + i + ' input[name$=accommodation]:checked').val() == 'D') {
				$('td.trek' + (i-1)).hide();
			}
 	    break;
		}
    }
	if (i==1 && !show) {
	    current = 1;
    }
    buttons();
    
    $('input#next').click(function(){
        if (validateParticipant(current)) {
            current++;
            $('tr.participant' + current).show();
            buttons();
        }
    });
    
    $('input#prev').click(function(){
        if (confirm("Are you sure?  You will lose any information you have entered for this participant.")) {
            $('tr.participant' + current).hide().find('input:text, select').val('').end()
            .find('input:radio, input:checkbox').attr('checked', false).end()
            .find(':hidden').show();
            current--;
        }
        buttons();
    });

});
