// WINDOW INIT
var step2visible = false;

Event.observe(window, 'load', function() {
	
	__sfga(); // Salesforce AdWords tracking code

	if ($('save_rfq_form'))
		Event.observe('save_rfq_form', 'click', saveForm);

	if ($('save_af_config'))
		Event.observe('save_af_config', 'click', saveConfig);

		
	if ( $('rfq') ) {
		var Step1Valid = false;
		var Step2Valid = false;

		var visibleStep = false;
	
		Event.observe('rfq', 'submit', RFQSubmit);
		Event.observe('rfq_next', 'click', RFQShowStep2);
		Event.observe('rfq_back', 'click', RFQShowStep1); 
		
		// Valid model years range from 1930 - 2019
		$('year').valPattern = '^(19[3-9][0-9])|(20[0-1][0-9])$';
		
		// Make must be at least three letters long.
		$('make').valPattern = '^[a-zA-Z]{3,}$';
		
		// Make must be at least one letter or number in length.
		$('model').valPattern = '^[a-zA-Z0-9]{1,}$';
		
		$('name').valPattern = '^[a-zA-Z ]{2,}$';
		$('zip').valPattern = '^[0-9]{5}$';
		$('email').valPattern = '^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$';
		$('phone').valPattern = /^\(?[2-9]\d{2}([\)-\.])?\s?\d{3}([-\.\s])?\d{4}$/;
		
		// When the form fields receive focus, we check it's validation pattern and nuke it's tooltip
		// if it passes validation.
		Event.observe($('year'), 'focus', ToolTipDelete.bindAsEventListener(this));
		Event.observe($('make'), 'focus', ToolTipDelete.bindAsEventListener(this));
		Event.observe($('model'), 'focus', ToolTipDelete.bindAsEventListener(this));
		
		// Get all non-hidden input elements in the RFQ forms
		$$('#rfq input:not([type~=hidden])').each(function(o, index) {
			Event.observe(o, 'keyup', function(e) {
				// If user is on step 1 and presses enter, we take them to the next step.
				// Else, we submit the form.
				if(Event.KEY_RETURN == e.keyCode) {
					if( !step2visible ) RFQShowStep2();
					else if( step2visible ) RFQSubmit;
				}
			});
		});


	};

});

function RFQSubmit(e) {
	Event.stop(e);
	if( frmValidate(2) )  {
		placeCall( $('name').value, $('phone').value);
		return;
	}
	
}

function saveConfig() {
	var btn = $('save_af_config');
	btn.value = "Saving...";
	btn.disabled = true;
	new Ajax.Request('/wp-content/plugins/asterforce/save_settings_ajax.php',
          {
                method:'post',
                parameters: {file: 'config', content: $('rfq_ini_src').value},
                onComplete: function(transport) {
                	btn.value = "Save Config";
                	btn.disabled = false;
                }
          });

}

function saveForm() {
	var btn = $('save_rfq_form');
	btn.value = "Saving...";
	btn.disabled = true;
	new Ajax.Request('/wp-content/plugins/asterforce/save_settings_ajax.php',
          {
                method:'post',
                parameters: {file: 'form', content: $('rfq_form_src').value},
                onComplete: function(transport) {
                	btn.value = "Save RFQ Form";
                	btn.disabled = false;
                }
          });

}



function placeCall() {
	var name = $('name').value;
	var phone = $('phone').value;

	new Ajax.Request('/wp-content/plugins/asterforce/ajax_wrapper.php',
          {
                method:'post',
                parameters: {name: name, phone: phone},
                onComplete: function(transport) {
                	$('rfq').stopObserving('submit', RFQSubmit);
                	$('rfq').submit();
                }
          });

}

function ToolTipDelete(e) {
	o = Event.element(e);

	if( o.validate )
 		Tips.remove(this);
}

function SwapPages(hide, show) {
	new Effect.Parallel([
		  new Effect.BlindUp(hide, { sync: true}), 
		  new Effect.Opacity(hide, { sync: true, from: 1, to: 0 }),   
		  new Effect.BlindDown(show, { sync: true}), 
		  new Effect.Opacity(show, { sync: true, from: 0, to: 1 }) 
		], {
		  duration: 0.8,
		  delay: 0.1
		});
		
		step2visible = (step2visible ? false : true);
}


function RFQShowStep2() {
	Tips.hideAll();
	if( frmValidate(1) ) {
		SwapPages( $('rfq_1'), $('rfq_2') ) 
		visibleStep = 1;
	};
}


function RFQShowStep1() {
	Tips.hideAll();
    SwapPages( $('rfq_2'), $('rfq_1') );
    visibleStep = 2;
}

function frmValidate(step) {
	var valErr = false;	
	
	if( step == 1 ) {
		var fields = new Array (
			 new Array ('year', 'Please enter the model year (2007, 2008, etc.) of your vehicle.')
			,new Array ('make', 'Please enter the make (Ford, Chevy, etc.) of your vehicle.')
			,new Array ('model', 'Please enter the model (Liberty, Cobalt, F150, etc.) of your vehicle.')
		);
		
		Step1Valid  = !validateFields(fields);
		return Step1Valid;

	} else if( step == 2 ) {
		var fields = new Array (
			 new Array ('name', 'Please enter your name.')
			,new Array ('zip', 'Please enter your 5-digit ZIP code.')
			,new Array ('email', 'Please enter a valid email address. (We hate spam as much as you do and only use your email address to communicate with you regarding your quote.)')
			,new Array ('phone', 'Please enter a valid 10-digit, US phone number.  We will only call you regarding your quote.')
		);
		
		Step2Valid  = !validateFields(fields);
		return Step2Valid;
	}

}


function validateFields(fields) {
	var valErr = false;

	// Iterate through each of the form fields
	fields.each(function(field, index) {

		// We already have a validation error, no need to check the other fields;
		if( valErr ) return valErr;

		var el = $(field[0]); // Field ID
		var msg = field[1]; // The validation error message for this field

		el.validateEntry=function() {
			var pattern = new RegExp(this.valPattern);	
			var match = pattern.test(this.value);
			return match;
		}

		if ( !el.validateEntry() ) {
			   if( !el.prototip )
			  toolTip(el, 'Required Information', msg);
			   el.prototip.show();
		   valErr = true;
			} else {  // If no validation error here, we remove any existing tooltip
		   if( el.prototip )
			  Tips.remove(el);
			}
	}); // End field iterator
	
	return valErr;

}

function toolTip(el, title, content) {

        new Tip(el, content, {
          title: title,
          style: 'protoblue',
          stem: 'bottomLeft',
          fixed: true,
          hideOn: 'focus',
          hideOthers: true,
          hook: { target: 'topRight', tip: 'bottomLeft', mouse: false },
          offset: { x: 0, y: 0 }
        });
}