// Begin BRS Formulator (version 8.5.10)
$(function(){
	// Complete Form Layout
	$('.formulate').each(function(){
		// Remove accessibility labels
		$('label').not('.manual_override,.manual_override *, .form_help').remove();
			   
		// Complete Text Fields and Text Areas with Labels and OverLabels
		$textField = $('input[type=text],input[type=password],textarea,input[type=file]').not('.manual_override,.manual_override *,.wymeditor');
		$textField.each(function() {
			$label = $(this).attr('title');
			$id = $(this).attr('id');
			$type = $(this).attr('type');
			
			// Identify associated break tags
			$(this).next('br').addClass($id);
			$(this).addClass($id);
			
			if($label!=""){
				if ($(this).parents('form').hasClass('overlabel') && $(this).hasClass('required')) {
					$(this).wrap('<span class="input_wrapper '+$id+'"></span>');
					$(this).before('<label for="'+$id+'" title="'+$label+'" class="'+$type+' '+$id+' required">'+$label+'&nbsp;<span class="required">*</span></label> ');
				}
				else if ($(this).parents('form').hasClass('overlabel')) {
					$(this).wrap('<span class="input_wrapper '+$id+'"></span>');
					$(this).before('<label for="'+$id+'" title="'+$label+'" class="'+$type+' '+$id+'">'+$label+'</label> ');
				}
				else if ($(this).hasClass('required')) {
					$(this).before('<label for="'+$id+'" title="'+$label+'" class="'+$type+' '+$id+' required">'+$label+'&nbsp;<span class="required">*</span></label> ');
				}
				else {
					$(this).before('<label for="'+$id+'" title="'+$label+'" class="'+$type+' '+$id+'">'+$label+'</label> ');
				}
			}
			
			// Position Help Labels
			if ( $(this).siblings('label[for='+$id+']').hasClass('form_help') ) {
				var help = $('label[for='+$id+'].form_help');
				help.css({display:'none'});
				$(this).focus(function(){
					var fieldPos = $(this).position();
					help.css({ position:'absolute',top:fieldPos.top+'px',left:(fieldPos.left + $(this).outerWidth() + 4)+'px' });
					help.fadeIn();
				});
				$(this).blur(function(){ help.fadeOut(); });
			}
		});
		
		// Complete Checkboxes and Radio Buttons with Labels
		$radioCheck = $('input[type=checkbox],input[type=radio]').not('.manual_override,.wymeditor');
		$radioCheck.each(function(){
			$label = $(this).attr('title');
			$id = $(this).attr('id');
			$type = $(this).attr('type');
			$value = $(this).attr('value');
			if ($label == '') $label = $value;
			
			if ($(this).hasClass('required')) {
				$(this).after('<label for="'+$id+'" title="This field is required." class="'+$type+' required">'+$label+'&nbsp;<span class="required">*</span></label> ');			
			}
			else {
				$(this).after('<label for="'+$id+'" title="'+$label+'" class="'+$type+'">'+$label+'</label> ');
			}
		});	

		// Complete Select Fields with Optional Labels
		$select = $('select[title]').not('.manual_override');
		$select.each(function(){
			$label = $(this).attr('title');
			$id = $(this).attr('id');
			
			if ($(this).hasClass('required')) {
				$(this).before('<label for="'+$id+'" title="This field is required." class="select required">'+$label+'&nbsp;<span class="required">*</span></label> ');			
			}
			else {
				$(this).before('<label for="'+$id+'" title="'+$label+'" class="select">'+$label+'</label> ');
			}
		});	
	});
	
	// Create Single Message/Error Prompt
	if(!$('.prompt').length){	
		$('body').append('<div class="prompt" style="display:none;"><div class="title_bar">Alert</div><div class="msg">Please fill in or correct all required fields.</div><div class="close">x</div></div>');
		$('.prompt .close').click(function(e){ e.preventDefault(); $(this).parent('.prompt').stop().slideUp(200,function(){ $(this).removeClass('red_alert client_msg'); }); });
	}
	
	// Create Tab Order
	$('input, textarea, select, button').not('[type=hidden],.manual_override').each(function(i){
		i += 1;
		$(this).attr({tabindex:i});
	});
	
	// Assign classes to input types to assist older browsers and add functionality
	$('input[type=checkbox]').addClass('checkbox');
	$('input[type=radio]').addClass('radio');
	$('input[type=text],input[type=password]').addClass('text');
	$('input[type=submit]').addClass('button');
	$('input[disabled=disabled],textarea[disabled=disabled],select[disabled=disabled]').addClass('disabled');
	
	// Create cross browser button hover 
	$('input[class="button"]').hover(
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);
});

function selectCondition(name,input){
	// Show matched conditions based on text or value selections
	$('.conditional_for_'+name).hide().addClass('inactive');
	$('option:selected',input).each(function() {
		var str = '.conditional_for_'+name+'.value_'+$(this).text().replace(' ','_').toLowerCase();
		var val = '.conditional_for_'+name+'.value_'+$(this).val().replace(' ','_').toLowerCase();
		
		if( $(str).length ) $(str).show().removeClass('inactive');
		if( $(val).length ) $(val).show().removeClass('inactive');
	})
}

function checkRadioCondition(name){
	// Show matched conditions based on value selections
	$('.conditional_for_'+name).hide().addClass('inactive');
	$('input[name='+name+']:checked').each(function() {
		var val = '.conditional_for_'+name+'.value_'+$(this).val().replace(' ','_').toLowerCase();
		
		if( $(val).length ) $(val).show().removeClass('inactive');
	});
}

function checkConditionals(input){ // reworked/enhanced (2.24.11)
	var name = $(input).attr('name');
	var type = $(input).attr('type');
	
	if($(input).is('select')) {
		$(input).change(function(){ selectCondition(name,input); });
		selectCondition(name,input);
	}
	
	if(type == 'checkbox' || type == 'radio') { 
		$('input[name='+name+']').change(function(){ checkRadioCondition(name); });
		checkRadioCondition(name);
	}
}

function validatePhoneNumber(strPhone){
	var t = strPhone.replace(/[^\d]/g, "");
	if(t.length == 10) return true;
	return false;
}


function validateEmailAddress(str){
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (str.indexOf(' ')!=-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;
	
	return true					
}

// BRS eCenter (8.6.10)
function eCenter(selector){
	$(selector).each(function(){ 
		var height = $(this).outerHeight() / 2;
		var width = $(this).outerWidth() / 2;
		
		$(this).css({
			position:'fixed',left:'50%',top:'50%', 
			marginTop:'-'+height+'px',
			marginLeft:'-'+width+'px',
			zIndex:'1000'
		});
		
		if($.browser.msie && $.browser.version < 7) {
			$(this).css({position:'absolute'});
			$('html,body').animate({scrollTop:$('body').offset().top},500);
		}
	});
}

// BRS promptUser (12.10.10)
function promptUser(title,message,status){
	if($('#lft_controls').length){
		if(status==0) {
			$('#lft_controls').append('<div id="iConfirm" class="info_box"><strong>'+title+'</strong><br />'+message+'</div><img class="ico iConfirm" src="images/spacer.gif" alt="'+title+'" longdesc="#iConfirm" />');
		}
		if(status==1) { 
			$('#iAlert,.iAlert').remove();
			$('#lft_controls').append('<div id="iAlert" class="info_box"><strong>'+title+'</strong><br />'+message+'</div><img class="ico iAlert" src="images/spacer.gif" alt="'+title+'" longdesc="#iAlert" />');
		}
		styleControls(status);
	} else {
		$('.prompt .title_bar').html(title);
		$('.prompt .msg').html(message);
		//eCenter('.prompt');
		if(status==0) $('.prompt').fadeIn(300).delay(4000).fadeOut(400);
		if(status==1) $('.prompt').addClass('red_alert').slideDown(200);
		if(status==2) $('.prompt').addClass('confirmation').slideDown(200); 
	}
}

// Begin BRS Validation Script (version 8.5.10)
function validateForm(event) {
	var a,e,e2,good;
	var i,inputs,input,value;
	
	good = true;
	
	// clean up any old notifications
	$('.red_alert', event.target).removeClass('red_alert');
	
	// check the text fields, radio buttons and select boxes
	inputs = $('input, select, textarea', event.target).not('.inactive, .inactive *');
	for(i=0; i<inputs.length; i++) {
		input = $(inputs.get(i));
		
		errorFound = false;
		
		// check for radio selection
		if (input.attr('type') == 'radio') { value = $('input[name=' + input.attr('name') + ']:checked').val() ? "1" : ""; }
		else { value = input.val(); }
		
		if(input.hasClass('required')) {
			// check for any input value
			if(value.length == 0 ) errorFound = true;
			
			// validate select fields
			if(input.is('select')) {
				if(input.val()=="null") errorFound = true;
			}
		}
		
		// check for minimum length
		if(input.attr('minlength') && (input.attr('minlength') < value.length) && value.length) errorFound = true;
		
		// validate phone numbers
		if(input.hasClass('phone') && $.trim(value).length) {
			if(!validatePhoneNumber(value)) errorFound = true;
		}

		// validate email address
		if(input.hasClass('email') && $.trim(value).length) {
			if(!validateEmailAddress(value)) errorFound = true;
		}

		if(errorFound) {
			good = false;
			// apply styles
			input.addClass('red_alert');
			$('label[for='+input.attr('id')+']').addClass('red_alert');			
		}
	}

	if(good) {
		checkForm();
		
		if( $(event.currentTarget).hasClass('ajax') ) {
			event.preventDefault();
			var thedata = $(event.target).serializeArray();
			var theurl = $(event.target).attr('action');
			$.post(theurl, thedata, function(data) { 
				$(event.target).hide();
				var thanks = $(event.target).siblings('.thanks');
				$('.thank_you',thanks).replaceWith('<strong>Thank you, '+ $('input[name=name_field]',event.target).val() +'.</strong>');
				thanks.show();
			} );
		}
	} else {
		if($('.prompt').hasClass('client_msg') === false) { // Don't override specific module messages
			promptUser("Alert","Please fill in or correct all required fields.",1);
		}
		event.preventDefault();
	}

}

// Spam prevention
function checkForm() {
		$('#accesskey').val('j' + $('#accesskey').val() );
		$('#accesskey2').val('j' + $('#accesskey2').val() );
}

// Begin OverLabel Scripts (version 2.2.10)
function initOverLabels () {
	var labels, id, input;
	
	// Set focus and blur handlers to hide and show for overlabel forms
	labels = $('form.overlabel label');
	for (var i = 0; i < labels.length; i++) {
		var theLabel = $(labels.get(i));
		
		// Skip labels not associated with a field.
		id = theLabel.attr('for');
		input = $('#' + id);
		if (input.length != 1) { continue; }
		
		// Apply overlabel class to label.
		theLabel.addClass('overlabel');
		
		// Hide any fields having an initial value.
		if (input.val() !== '') { hideLabel(input.attr('id'), true); }
		
		// Set handlers to show and hide labels. [jq_1.4]
		input.focusin(function() { hideLabel($(this).attr('id'), true);  });
		input.focusout(function() { if ($(this).val() == '') { hideLabel($(this).attr('id'), false); } });
	}
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = $('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = $(labels[i]).attr('for'); 
    if (field_for == field_id) {
      $(labels[i]).css('text-indent', (hide) ? '-1000px' : '0px' );
      //labels[i].className = 'overlabel-marker'; `BKS
      return true;
    }
  }
}

$(function() {
	if($('form').hasClass('overlabel')){ setTimeout(initOverLabels, 50); }
		
	// Setup Conditional Form Segments
	$('.conditional').each(function(){ checkConditionals(this); });
	
	$('form.validate').submit(validateForm);
	
	eCenter('.prompt');	
	
});

