$(function(){
	
	var ref = $('#ref').val();
	
	$.get(ref+'/forms/token.php',function(txt){
		$('.secured').prepend('<input type="hidden" name="ts" value="'+txt+'" />'); // Keep the forms secure
	});
	
	var timer;

	function delay(){
		return function(callback, msec){
			clearTimeout(timer);
			timer = setTimeout(callback, msec);
		};
	};
	
	var $v = $('<span class="tof"></span>'), // Container for the validity symbol
		$c = $v.clone(),
		imgValid = '<img src="'+ref+'/img/valid.png" alt="" />',
		imgInvalid = '<img src="'+ref+'/img/invalid.png" alt="" />';
	
	var validateMe = function(e){
		var $vm = $(this),
			$cont = $('#tof_'+$vm.attr('id')),
			pos = $vm.position(),
			w = $vm.outerWidth(true),
			h = $vm.outerHeight(true),
			y = (h/2)-4,
			data = e.data.chk+'='+$vm.val(),
			test;
		delay(
		/*$.ajax({
				data: data,
				dataType: 'json',
				type: 'POST',
				url: ref+'/forms/validate-me.php',
				async: false,
				success: function(check){
					switch(e.data.chk){
						case 'validEmail': test = check.email; break;
						case 'validName': test = check.name; break;
						case 'validPhone': test = check.phone; break;
						case 'validZip': test = check.zip; break;
						case 'validAddr': test = check.addr; break;
						case 'validDate': test = check.date; break;
					}
					if (test == 'valid'){
						$vm.removeClass('invalid').addClass('valid').css({'background':'#fff'});
						$cont.html(imgValid).css({'top':pos.top+y,'left':pos.left+w+2});
					} else {
						$vm.removeClass('valid').addClass('invalid');
						$cont.html(imgInvalid).css({'top':pos.top+y,'left':pos.left+w+2});
					}
				}
		});*/
			$.post(ref+'/forms/validate-me.php',data,function(check){
				switch(e.data.chk){
					case 'validEmail': test = check.email; break;
					case 'validName': test = check.name; break;
					case 'validPhone': test = check.phone; break;
					case 'validZip': test = check.zip; break;
					case 'validAddr': test = check.addr; break;
					case 'validDate': test = check.date; break;
				}
				if (test == 'valid'){
					$vm.removeClass('invalid').addClass('valid').css({'background':'#fff'});
					$cont.html(imgValid).css({'top':pos.top+y,'left':pos.left+w+2});
				} else {
					$vm.removeClass('valid').addClass('invalid');
					$cont.html(imgInvalid).css({'top':pos.top+y,'left':pos.left+w+2});
				}
			},'json'),
		1000);
	};
	
	$('input.required', 'form.validForm').bind('blur', function(){
		var $r = $(this);
			$cont = $('#tof_'+$r.attr('id'))
			pos = $r.position(),
			w = $r.outerWidth(true),
			h = $r.outerHeight(true),
			y = (h/2)-4;
		if ($r.val() == $r.attr('title') || $r.val() == ''){
			$r.addClass('invalid');
			$cont.html(imgInvalid).css({'top':pos.top+y,'left':pos.left+w+2});
		}
	});
	
	$('input', 'div.validChecks').change(function(){
		var num = 0,
			$div = $(this).parent().parent(),
			$boxes = $div.children().children();
		$boxes.each(function(){
			if ($(this).is(':checked') || $(this).checked) num = 1;
			if (num == 1) $div.addClass('valid').removeClass('invalid');
		});
		if (!num == 1) $div.removeClass('valid').addClass('invalid');
	});
	
	$('select.validSelects').change(function(){
		$select = $(this);
		if ($select.val() != '') $select.addClass('valid').removeClass('invalid');
		else $select.addClass('invalid').removeClass('valid');
	});
	
	$('input.validEmail', 'form').bind('keyup', {chk:'validEmail'}, validateMe);
	$('input.validName', 'form').bind('keyup', {chk:'validName'}, validateMe);
	$('input.validPhone', 'form').bind('keyup', {chk:'validPhone'}, validateMe);
	$('input.validZip', 'form').bind('keyup', {chk:'validZip'}, validateMe);
	$('input.validAddr', 'form').bind('keyup', {chk:'validAddr'}, validateMe);
	$('input.validDate', 'form').bind('keyup', {chk:'validDate'}, validateMe);
	
	$('#donate_form input[type="submit"]').bind('click keypress', function(e){
		e.preventDefault();
		var $donate = $('#donate_form'),
			$warning = $('#not_validated'),
			$req = $donate.find('.required'),
			deny = 0,
			num = 0;
		$req.each(function(i,v){
			if (!$(v).hasClass('valid')){
				num++;
				$(v).addClass('invalid r_'+num).css({'background':'#FBD4E8'});
				deny = 1;	
			}
		});
		if(deny == 1){
			$warning.html('Whoops!  Not all required fields have been properly entered.  Please correct all pink fields to continue.').show();
			$('body').scrollTo('.r_1', 600);
		} else {
			
			$.post(
				ref+'/forms/xtrainfo.php', 
				'custom='+$('input[name="custom"]').val()+'&type='+$('#type').val()+'&designation='+$('#designation').val()+'&dedication='+$('select[name="dedication"]').val()+'&dedication_name='+$('input[name="dedication_name"]').val()+'&ack_name='+$('#ack_name').val()+'&ack_addr1='+$('#ack_addr1').val()+'&ack_addr2='+$('#ack_addr2').val()+'&ack_city='+$('#ack_city').val()+'&ack_state='+$('#ack_state').val()+'ack_zip='+$('#ack_zip').val()+'&ack_email='+$('#ack_email').val()+'&recognition='+$('#donate_recognition').val()+'&signup='+$('input[name="signup"]').val(), 
				function(){
					$donate.submit();
				}
			);
			
		}
	});
	
	function rand ( n ){
	  return ( Math.floor ( Math.random ( ) * n + 1 ) );
	}
	
	$('form.validForm').submit(function(e){
		e.preventDefault();
		var form = this,
			$form = $(form),
			$req = $form.find('.required'),
			fSER = $form.serialize(),
			fID = $form.attr('id'),
			pkg = 'id='+fID+'&'+fSER,
			deny = 0,
			c = 0,
			afterColor;
		$req.each(function(i,v){
			if (!$(v).hasClass('valid')){
				c++;
				$(v).addClass('invalid r_'+c).css({'background':'#FBD4E8'});
				deny = 1;	
			}
		});
		if(deny == 1){
			$('body').scrollTo($('.r_1', $form), 600);
		} else {
			$.post(ref+'/forms/security_checkpoint.php', pkg, function(data){
				var before = $form.outerHeight(true);
				$form.css({height:before+'px'}).html(data);
				var after = $('div', form).outerHeight(true);
				var afterChk = $('div', form).hasClass('form_success') ? 'success' : 'fail';
				if (afterChk == 'success') afterColor = '#EBF9D5';
				else afterColor = '#FBD4E8';
				$form.animate({height:after+'px'}, 500, function(){
					var new_height = $('#page_slider_cont li.visible').outerHeight(true);
					$('#page_slider_cont').animate({height:new_height+'px'}, 500);
				}).css({background:afterColor});
				$('body').scrollTo($form.parent(), 500);
			});
		}
	});
	
	$('input').focusin(function(){
		if($(this).attr('title') == $(this).val()) $(this).val('');
	});
	$('input').focusout(function(){
		if ($(this).val() == '') $(this).val($(this).attr('title'));
	});
	$('textarea').focusin(function(){
		if($(this).attr('title') == $(this).val()) $(this).val('');
	});
	$('textarea').focusout(function(){
		if ($(this).val() == '') $(this).val($(this).attr('title'));
	});
	
	// Sidebox Contact/RSVP Forms
	var deptContact = $('#dept_contact').outerHeight();
	var RSVPcontact = $('#event_RSVP').outerHeight();
	var sendMsg = 'Send Email';
	var RSVP = 'Send RSVP'
	var cancelMsg = 'Cancel';
	$('#dept_contact').css({height:'0'});
	$('#event_RSVP').css({height:'0'});
	$('#send_msg').show().text(sendMsg).toggle(function(){
		$(this).text(cancelMsg);
		$('#dept_contact').animate({height:deptContact+'px'}, 500, function(){
			$('.tof').show();
		});
	}, function(){
		$(this).text(sendMsg);
		$('#dept_contact').animate({height:'0'}, 500).find('.tof').hide();
	});
	$('#send_RSVP').show().text(RSVP).toggle(function(){
		$(this).text(cancelMsg);
		$('#event_RSVP').animate({height:RSVPcontact+'px'}, 500, function(){
			$('.tof').show();
		});
	}, function(){
		$(this).text(RSVP);
		$('#event_RSVP').animate({height:'0'}, 500).find('.tof').hide();
	});
	
	// Job Opportunities Form
	$('#emp_other_chk').click(function(){
		if($(this).is(':checked')) $('#emp_other_field').removeAttr('disabled').focus();
		else {
			$('#emp_other_field').attr('disabled', true);
			$(this).blur().focus();
		}
	});
	
	// Donation Form
	$other = $('#donateOther');
	$amount = $('#amountOther');
	$other.change(function(){
		if($other.is(':checked') || $other.checked) $amount.removeAttr('disabled').focus();
		else $amount.attr('disabled',true);
	});
	$amount.click(function(){
		$other.attr('checked', true);
		$amount.focus();
	});
	$amount.bind('keyup', function(){
		var donate = $amount.val();
		$other.val(donate);
	});
	
	$('#donate_person_type').change(function(){
		switch ($(':selected', this).val()){
			case 'individual':
				$('#donate_anonymous').removeAttr('checked').removeAttr('disabled');
				$('#donate_recognition').val('').removeAttr('disabled');
			break;
			case 'corporation':
				$('#donate_anonymous').removeAttr('checked').removeAttr('disabled');
				$('#donate_recognition').val('').removeAttr('disabled');
			break;
			case 'anonymous':
				$('#donate_anonymous').attr('checked',true).attr('disabled',true);
				$('#donate_recognition').val('Anonymous');
			break;
		}
		$(this).blur().focus();
	})	
	
	$('#donate_anonymous').change(function(){
		if ($(this).is(':checked')) {
			$('#donate_recognition').val('Anonymous');
			$(this).blur().focus();
		}
		else $('#donate_recognition').val('').removeAttr('disabled').focus();
	})
	
	$('#donate_howtogive').change(function(){
		switch ($('#donate_howtogive :selected').val()) {
			case 'online':
				$('#donate_by_mail').hide();
				$('#donate_by_phone').hide();
				$('#donate_notice').hide();
			break;
			case 'mail':
				$('#donate_by_mail').show();
				$('#donate_by_phone').hide();
				$('#donate_notice').show();
			break;
			case 'phone':
				$('#donate_by_mail').hide();
				$('#donate_by_phone').show();
				$('#donate_notice').show();
			break;
		}
		$(this).blur().focus();
	});
	
	// Prescreening Form
	$ps_input = $('#fs_two input.warn');
	$warning = $('#warning');
	$warning.hide();
	
	getNewHeight = function(){
		var new_height = $('#page_slider_cont li.visible').outerHeight(true);
		$('#page_slider_cont').animate({height:new_height+'px'}, 500);
	};
	
	$ps_input.change(function(){
		if ($('.trigger_warning').is(':checked') || $('.trigger_warning').checked){
			$warning.fadeIn(1000);
			getNewHeight();
		} else {
			$warning.fadeOut(500);
			getNewHeight();
		}
	});

	$hhs = $('#hhs');
	$f = $('#hhs div');
	$addMore = $('#addMore');
	$cancel = $('<img title="remove" src="'+ref+'/img/close.png" alt="cancel" />').css({'position':'relative','top':'4px','cursor':'pointer'});
	var hhcounter = 0;
		
	$addMore.click(function(){
		hhcounter++;
		$field = $f.clone(false).attr('id','div_'+hhcounter);
		$nix = 	$cancel.clone().attr('id','hhname_'+hhcounter).click(function(){
					$(this).parent().remove();
					getNewHeight();
				});
		$new = $field.append($nix).appendTo($hhs);
		$new.find('input:eq(0)').attr('name','hhname['+hhcounter+']');
		$new.find('input:eq(1)').attr('name','hhage['+hhcounter+']');
		getNewHeight();
	});
});
