// eFormulate, The BRS Elemental Formulator (version 5.23.11)
// Copyright Blue Ridge Solutions, Inc.  www.blueridges.com
//
// INSTRUCTIONS
// Required Files: /css/eFormulate.css, /css/eFormulate_colors.css, /images/bg_wht[10-90].png, /js/eFormulate.js, /js/eScreen.js (for prompts)
// Default setup: $('.formulate').eFormulate();

(function($){
	
	// browser support
	var browserSupport = {
		input_placeholder: (function(){ return 'placeholder' in document.createElement('input'); })()
	};
	
	$.fn.eFormulate = function(options){ 

		var settings = {
			formulate : 1, // set to 0 to use validation and basic css only
			formType : 'frontend', // admin, frontend, TODO: account, store, login, etc.
			formLayout : 'vertical', // vertical, horizontal, compact
			validate : 1,
			prompt : 1
			/* TO DO
			helpPosition : 'top', // top, right, bottom, left
			helpDistance : '4px', // distance from input field
			*/
		};
		
		return this.each(function(){  
			var $form = $(this);
			// override settings with parameters
			if (options) $.extend(settings, options);
			
			//console.log('init formulate: '+$(this).attr('id'));
			$form.addClass('eFormulate');
			if(settings.formType=='admin') $form.addClass('eFormulate_admin'); 
			if(settings.formType=='frontend') $form.addClass('eFormulate_frontend');
			$(".skip_validation", $form).click(function() {$form.unbind('submit',validateForm ); } );
			if(settings.validate==1) $form.submit(validateForm);

			if(settings.formulate==1){ // Form setup

				if(settings.formLayout=='compact') { $form.addClass('overlabel'); setTimeout(initOverLabels, 50); } // needs updates
	
				// Remove accessibility labels
				$('label', $form).not('.manual_override,.manual_override *,.form_help,.eFormulated').remove();
				
				// Complete Text Fields and Text Areas with Labels
				$textField = $('input[type=text],input[type=password],textarea,input[type=file]',$form);
				// make sure all fields have an ID and bind events to all fields before filtering
				$textField.each(function() { 
					if(!$(this).attr('id')) $(this).attr('id',$(this).attr('name')); 
					setFocus($(this),'id',$form);
				}); 

				$textField = $textField.not('.manual_override,.manual_override *,.wymeditor,.eFormulated');
				$textField.each(function() {
					if($(this).data('eFormulated')) return;
					$(this).data('eFormulated',true);
					
					var $field = $(this);
					var label = $field.attr('title');
					var id = $field.attr('id');
					var type = $field.attr('type');
					
					if($field.is('textarea')){ $field.addClass('textarea');  type = 'textarea'; }
					if(type=='password') type = 'text password';
					if(type=='file') type = 'text file';
					
					// Identify associated break tags
					$field.next('br').addClass(id);
					$field.addClass(id);


					if(label){
						if(settings.formLayout=='compact') { $('br.'+id).remove(); $(this).wrap('<div class="input_wrapper overlabel '+id+'"></div>'); }
						if($field.hasClass('required')) {
							var asterisk = '&nbsp;<span class="required">*</span>';
							if($field.hasClass('no_star')) asterisk = '';
							$field.before('<label for="'+id+'" class="'+type+' '+id+' required eFormulated" title="This field is required">'+label+''+asterisk+'</label> ');
						} else {
							$field.before('<label for="'+id+'" class="'+type+' '+id+' eFormulated">'+label+'</label> ');
						}
					}
					
					// Position Help Labels
					if ( $('label[for="'+id+'"]',$form).hasClass('form_help')) {
						var $help = $('label[for="'+id+'"].form_help',$form);
						$help.css({display:'none'});
						$field.focus(function(){
							var $fieldPos = $field.position();
							if(settings.formLayout=='compact') $fieldPos = $field.parent().position();
							$help.css({ position:'absolute',top:$fieldPos.top+'px',left:($fieldPos.left + $field.outerWidth() + 4)+'px' });
							$help.fadeIn();
						});
						$field.blur(function(){ $help.fadeOut(); });
					}
					
					// Setup placeholder (if placeholder is not supported natively by the browser)
					if ($field.attr('placeholder')) {
						$field
							// When field is focused, remove placeholder style and clear field
							.focus(function(){
								var $this = $(this),
									placeholder_text = $(this).attr('placeholder');
								if (!browserSupport.input_placeholder && this.value==placeholder_text) this.value='';
								$(this).removeClass('placeholder');
							})
							// When field is blurred, add placeholder style and placeholder text (if empty)
							.blur(function(){
								var $this = $(this),
									placeholder_text = $(this).attr('placeholder');
								if (this.value == '') {
									if (!browserSupport.input_placeholder) this.value = placeholder_text;
									$this.addClass('placeholder');
								}
							})
							// Trigger a blur to initialize the placeholder
							.trigger('blur');
					}
					
				}); // end $textField setup
				
				
				// Complete Checkboxes and Radio Buttons with Labels
				$radioCheck = $(':checkbox,:radio',$form);
				$radioCheck.each(function(){
					if($(this).is(':radio')) {
						setFocus($(this),'name',$form);
					} else {
						setFocus($(this),'id',$form);
					}
				});
				$radioCheck = $radioCheck.not('.manual_override,.wymeditor');
				$radioCheck.each(function(){
					if($(this).data('eFormulated')) return;
					$(this).data('eFormulated',true);

					var $btn_box = $(this);
					var label = $btn_box.attr('title');
					var name = $btn_box.attr('name');
					var id = $btn_box.attr('id');
					var type = $btn_box.attr('type');
					var value = $btn_box.attr('value');
					if (label == '') label = value;
					
					// Create labels from the title attribute
					if ($btn_box.hasClass('required')) {
						var asterisk = '&nbsp;<span class="required">*</span>';
						if($btn_box.hasClass('no_star')) asterisk = '';
						$btn_box.after('<label for="'+id+'" title="This field is required." class="'+type+' '+name+' required eFormulated">'+label+''+asterisk+'</label> ');			
					} else {
						$btn_box.after('<label for="'+id+'" class="'+type+' '+name+' eFormulated">'+label+'</label> ');
					}
					
					if(type == 'radio') {
						// Enable clicking child elements of labels for IE7/8, this allows triggering of buttons as well
						$('label *').click(function(){ $('label.'+name).removeClass('checked'); $(this).parent('label').trigger('click').addClass('checked'); });
						// Look for checked attribute
						if($btn_box.attr('checked')) { $btn_box.addClass('checked'); $('label[for="'+id+'"]').addClass('checked');  }
						
						// Apply class of checked to selected radio buttons
						$('input[name="'+name+'"]').change(function(){ 
							$('input[name="'+name+'"],label.'+name).removeClass('checked');
							var $checked = $('input[name="'+name+'"]:checked');
							$checked.addClass('checked'); 
							$('label[for='+$checked.attr('id')+']').addClass('checked'); 
						});
					}
					
					// Hide inputs for custom buttons and defer focus to their labels
					if($btn_box.hasClass('custom')) { 
						$('label[for="'+id+'"]').prepend('<a name="label_'+id+'"></a>');
						$btn_box.hide(); 
						$('a[name="label_'+id+'"]').focus(function(){ $('.focus').removeClass('focus'); $(this).parent('label').focus().addClass('focus'); });
						
						if(type == 'radio') { 
						// Create custom select menu from custom radio buttons
							if($btn_box.parent().hasClass('custom_select')) {
								var $select = $btn_box.parent();
								$select.wrapInner('<div class="custom_options" />');
								$('.custom_options label',$select[0]).live('click',function(){
									$('label',$select).not('.custom_options label').remove();
									$(this,$select).clone().addClass('manual_override').prependTo($select);
									$('.custom_options',$select).hide();
								});
								
								$('label.manual_override',$select[0]).live('click',function(){ $('.custom_options').not(this).hide(); $('.custom_options',$select).toggle(); });
								//$select.parents().click(function(){ $('.custom_options').hide(); });
							}
						}
					}
					
					$btn_box.focus(function(){ $('.focus').removeClass('focus'); $(this).addClass('focus'); });
				});	 // end $radioCheck setup and custom select fields
				
				
				/* Select the pre-selected option for custom select menus*/
				$('.custom_options').each(function(){
					if(!$(this).children('label.checked').length){
						$(this).children('label:first').addClass('checked');
					}
					$(this).children('label.checked').trigger('click');
				}); 
				$('.custom_options label.checked').trigger('click');
				
				// Complete Select Fields with Optional Labels
				
				$select = $('select',$form);
				$select.each(function(){
					setFocus($(this),'id',$form);
				});
				$select = $select.not('.manual_override, .manual_override *');
				$select.each(function(){
					if($(this).data('eFormulated')) return;
					$(this).data('eFormulated',true);

					$label = $(this).attr('title');
					$id = $(this).attr('id');
					
					$(this).children('option').addClass('option');
					
					if ($(this).attr('title') && $(this).hasClass('required')) {
						$(this).before('<label for="'+$id+'" title="This field is required." class="select required eFormulated">'+$label+'&nbsp;<span class="required">*</span></label> ');			
					}
					else if ($(this).attr('title')) {
						$(this).before('<label for="'+$id+'" title="'+$label+'" class="select eFormulated">'+$label+'</label> ');
					}
				});	
					
				// Setup Conditional Form Segments
				// Place the class conditional on each radio, select or checkbox that determines the show/hide of conditional elements
				// Place the class conditional_for_[name/id] on the wrapper or elements that are conditional
				$('.conditional',$form).each(function(){ checkConditionals(this); });
				
			} // end settings.formulate (form setup)

		}); // formulate each $form
		
	}; // eFormulate Plugin
})(jQuery);
		


/// FUNCTIONS
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,reverse){
	// Show matched conditions based on value selections
	$('.conditional_for_'+name).hide().addClass('inactive');
		$('input[name="'+name+'"]').each(function() {
			var val = '.conditional_for_'+name+'.value_'+$(this).val().replace(' ','_').toLowerCase();
			
			if($(val).length){
				if(reverse==1) { if(!$(this).is(':checked')) $(val).show().removeClass('inactive'); }
				else { if($(this).is(':checked')) $(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); }).trigger('change');
	}
	
	if(type == 'checkbox' || type == 'radio') { 
		$('input[name="'+name+'"]').change(function(){ if($(this).hasClass('reverse')) checkRadioCondition(name,1); else checkRadioCondition(name,0); }).trigger('change');
	}
}

// BRS promptUser (5.26.11)
// TODO: Setup in place messages like the form_help labels make form_alert labels, tie in with server side validation, create confirmation screens Y/N
function promptUser(title,message,status,format){
	var type;
	if($('#lft_controls').length && format!='prompt'){ // add flag to toolbar
		type = 'iConfirm';
		if(status==1) type='iAlert'; 
		$('#'+type+',.'+type).remove();
		$('#lft_controls').append('<div id="'+type+'" class="promptUser info_box"><h5>'+title+'</h5>'+message+'</div><img class="ico '+type+'" src="/images/spacer.gif" alt="'+title+'" longdesc="#'+type+'" />');
		styleControls(status);
	} else if((($('#brs_notice').length && status==0) || ($('#brs_error').length && status==1)) && format!='prompt'){ // add note to top
		type = 'brs_notice';
		if(status==1) type = 'brs_error';
		$('#'+type+'').html('<h5>'+title+'</h5>'+message).slideDown(300);
	} else { // add screen prompt to center
		type = 'brs_notice';
		if(status==1) type = 'brs_error';
		$('html').eScreen({html:'<div id="brs_prompt" class="promptUser '+type+'"><h5>'+title+'</h5><div>'+message+'</div></div>',opacity:0.4});
	}
}


function validateForm(event) {
	var form$ = event.currentTarget;
	
	formulateValidate(form$, event);
}
// Begin BRS Validation Script (version 8.5.10)
function formulateValidate(target, event) {
	var a,e,e2,good;
	var i,inputs,input,value;
	
	good = true;
	
	// clean up any old notifications
	$('.red_alert', target).removeClass('red_alert');
	
	// check the text fields, radio buttons and select boxes
	inputs = $('input, select, textarea', target).not('.inactive, .inactive *');
	//console.log(inputs);
	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 default values
			if(input.hasClass('default')) errorFound = true;
			
			// 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')+'"]').not('.form_help').addClass('red_alert').show();
		}
	}

	if(good) {
		checkForm();
		
		if( $(target).hasClass('ajax') ) {
			if(event) event.preventDefault();
			
			if($(target).parents('#overlay_content').length = 0) $("body").eScreen({html:'<div class="eFormulate_submission"><p><img src="/admin/images/progress1.gif" alt="Submitting form..." /></p><p style="margin-bottom:0px;">Submitting form...<br />Please wait...</p></div>'});
			
			var thedata = $(target).serializeArray();
			var theurl = $(target).attr('action');
			$.post(theurl, thedata, function(data) { 
				if($(target).parents('#overlay_content').length = 0) $.eScreen_close();
				$(target).hide();
				var thanks = $(target).siblings('.thanks');
				$('.thank_you',thanks).replaceWith('<strong>Thank you, '+ $('input[name=name_field]',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);
		}
		if(event) event.preventDefault();
	}
	
	return good;
} // validateForm

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					
}

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 = $('div.overlabel label').not('.manual_override,.manual_override *,.wymeditor,.form_help');
	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 setFocus(element,attr,$form){
	element
		.focus(function(){ $(this).addClass('focus'); $('label[for="'+$(this).attr(attr)+'"]',$form).not('.form_help').addClass('focus');   })
		.blur(function(){ $(this).removeClass('focus'); $('label[for="'+$(this).attr(attr)+'"]',$form).not('.form_help').removeClass('focus');  })
	;
}

