// dealer.js

function insertSwfHeaderProspectus(title, formID) {	
	// not great but necessary
	// check to see if page uses the main body div 'full' or 'left' and 'right'
	// ALL pages SHOULD have either 'full' or 'left' div tags see UI documentation
	// /Volumes/TRAFFIC/MITSUBISHI_Interactive/Website/Documentation/UIstructure03.html
	width   = "740";
	
	
	// create the h1 tag and swf object for the h1 title
	var markup = "";
	markup += 	'<object type="application/x-shockwave-flash" data="/MMNA/swf/new_header.swf" width='+width+' height="40">';
	markup +=		'<param name="allowScriptAccess" value="sameDomain" />';
	markup +=		'<param name="allowFullScreen" value="false" />';
	markup +=		'<param name="movie" value="/MMNA/swf/new_header.swf" />';
	markup +=		'<param name="quality" value="high" />';
	markup +=		'<param name="wmode" value="transparent" />';
	markup +=		'<param name="scale" value="noscale" />';
	markup +=		'<param name="salign" value="tl" />';
	markup +=		'<param name="flashvars" value="headline='+String(title).replace(/&/, "\%26")+'" />';
	markup +=		title;
	markup +=	'</object>';

	// replace existing default h1 tag with the swf object
	var H1NodeList = $('#' + formID + ' h1').eq(0);
	try {
	    if (H1NodeList.length) {	    	
		    $(H1NodeList).html(markup);
	    }
	} catch (e) {
		alert("ERROR: This page does not follow the MMNA UI architecture and insertSwfHeader() can not be used.");
	}


}



/* login form */
function loginSuccess () {
	$('#formError').hide();
    
	var formData = $('form[name=login]').serialize() + "&method=login";
    
	$.post("/MMNA/prospectusDealerAction.do", formData ,function(respData)
		{
		
			if( respData.indexOf("Success") > -1 ) 
			{
				window.location= '/MMNA/jsp/dealerprospectus/index.do';
			}
			else
			{
				$(['password', 'username']).each ( function () {
					$('label[for=' + this  + ']').removeClass('valid');
	                $('label[for=' + this + ']').addClass('error');
	                $('input[name='+this+']').removeClass ('valid');
	                $('input[name='+this+']').addClass ('error');
	                
	                var theEM = $('input[name='+this+']').siblings('em').eq(0);
	        		//alert (theEM.length);
	        	    if (theEM.length) {
	        		    theEM.removeClass('valid');
	        		    theEM.addClass('error');
	        		    //theEM.html(theMessage);
	        	    } else {
	        	    	$('input[name='+this+']').after("<em class='error'></em>");
	        	    }
			    });
				try {
					$('#formError').show("blind", { direction: "vertical" }, 800);
				} catch (e) {
					$('#formError').show();
					//alert ('jquery ui not loaded');
				}
			}
		});
	
	return true;
}

function loginFailure () {
	try {
		$('#formError').show("blind", { direction: "vertical" }, 800);
	} catch (e) {
		alert ('jquery ui not loaded');
	}
	return true;
}

function loginPreValidate () {
	$('#login .errorMessageStack ul').html('');
	$('#login .errorMessageStack').hide();
}

/* forgotten password form */
function forgotSuccess () {
	
	var formData = $('form[name=forgot]').serialize() + "&method=forgotPassword";
    
	$.post("/MMNA/prospectusDealerAction.do", formData ,function(respData)
		{
			if( respData.indexOf("Success") > -1 ) 
			{
				$('#forgot').hide();
				$('#login').show();
				$('#login .errorMessageStack span').eq(0).html('Your password has been sent to the email address entered. Please check your email for further instructions.');
				$('#login .errorMessageStack').show();
			}
			else
			{

				if( respData.indexOf("NotActive") > -1 ) {
					$('#forgot .errorMessageStack span').eq(0).html("Sorry, the email address you entered is not in our system. Please call your area manager, consult our map for reference.");
				} else {
					$('#forgot .errorMessageStack span').eq(0).html("Sorry, the email address you entered is not in our system. Please call your area manager, consult our map for reference.");
				}
				$('#forgot .errorMessageStack').show();
				
			}
		});
	
	
	return true;
}

function forgotFailure () {
	$('#forgot .errorMessageStack span').eq(0).html('There was an error processing your information. Please ensure that all required fields are filled out in their entirety.')
	$('#forgot .errorMessageStack').show();
	
	return true;
}

function forgotPreValidate () {
	$('#forgot .errorMessageStack ul').html('');
	$('#forgot .errorMessageStack').hide();
	return false;
}

/* apply form */
function applySuccess (obj) {
	var phoneVal = '(' + $('#phoneAreaCode').val() + ')' +$('#phonePrefix').val() + '-' + $('#phoneSuffix').val();
	var formData = $('form[name=apply]').serialize() + "&phone="+phoneVal + "&method=register";
    
	$.post("/MMNA/prospectusDealerAction.do", formData ,function(respData)
		{
			if( respData.indexOf("Success") > -1 ) 
			{
				$('#apply').hide();
				$('#thankYou').show();
			}
			else
			{
				if( respData.indexOf("InvalidUser") > -1 ) 
				{
					$('#apply .errorMessageStack span').eq(0).html("There was a User already registered with the provided email. If you forgotten your password, please request one!");
				}
				else
				{
					$('#apply .errorMessageStack span').eq(0).html("There was an error while processing your request. Please fill all the required fields and try again!");
				}
					$('#apply .errorMessageStack').show();
			}
		});
	
	return false;
	
}

function applyFailure (obj) {
	//$('#applyError').html();
	//$('#applyError').show();
	$('#apply .errorMessageStack span').eq(0).html('There was an error processing your information. Please ensure that all required fields are filled out in their entirety.')
	$('#apply .errorMessageStack').show();
	return false;
}

function applyPreValidate () {
	$('#apply .errorMessageStack ul').html('');
	$('#apply .errorMessageStack').hide();
	return false;
}

function clearApplyForm () {
	$('#apply .errorMessageStack ul').html('');
	$('#apply .errorMessageStack').hide();
	return false;
}

// Defines fields, messages, and how to validate
// see validation.js for more documentation
var localBinding = {
		'login' : {
	        'onValidate' : {loginSuccess : {}},
	        'onValidationFail' : {loginFailure : {}},
	        'preValidate' : loginPreValidate
		},
		'apply' : {
			'confirmEmail' : { 'validate' : {mustMatch : {'compareTo' : 'email'}, validateMinLength : {'minLength' : 1}}, 'onSuccess' : {genericValidate : {}}, 'onFailure' : {genericValidate : {message : "Email addresses must match."}} },
			'phoneAreaCode' : {'validate' : {validateRegEx: {expression: /^[0-9]+$/}, validateMinLength : {'minLength' : 1}}},
			'phonePrefix' : {'validate' : {validateRegEx: {expression: /^[0-9]+$/}, validateMinLength : {'minLength' : 1}}},
			'phoneSuffix' : {'validate' : {validateRegEx: {expression: /^[0-9]+$/}, validateMinLength : {'minLength' : 1}}},
			'marketCity' : {'validate' : {validateRegEx : {expression: /^[a-zA-Z\s]+$/}, validateMinLength : {'minLength' : 1}}, 'onSuccess' : {genericValidate : {}}, 'onFailure' : {genericValidate : {message : "Sorry, the city name you entered is not a valid city name. Please check the spelling and try again."}}},
			'marketState' : {'validate' : {validateDropdown: {}}, 'onSuccess' : {genericValidate : {}}, 'onFailure' : {genericValidate : {message : "Sorry, you must select a state from the dropdown."}}},
			'onClear' : clearApplyForm,
			'onValidate' : {applySuccess : {}},
		    'onValidationFail' : {applyFailure : {}},
		    'preValidate' : applyPreValidate
		},
		'forgot' : {
			'onValidate' : {forgotSuccess : {}},
			'onValidationFail' : {forgotFailure : {}},
			'preValidate' : forgotPreValidate
		}
	};

// Defines 'grouped' fields which must all validate as one
// onSuccess and onFailure are required until the fallbacks are tweaked accordingly.
// as of right now, it is supposed to fall back to the single field but due to some changes, it no longer works properly
var groupedFields = {
		'apply' : {
	        'phone' : {
	            fields: ['phoneAreaCode', 'phonePrefix', 'phoneSuffix'],
	            onSuccess: {groupValidatePass : {message: ''}},
	            onFailure: {groupValidateFail : {message: 'Sorry, the phone number you entered is not a valid phone number. Please check the number, punctuation marks are not necessary.'}}
            }/*,
            'complete_address' : { 
            	fields: ['addressOne', 'city', 'state', 'zip'],
            	onSuccess: {groupValidatePass : {}},
            	onFailure: {groupValidateFail : {message: 'Sorry, you must enter all address fields.'}},
            },
            'market' : {
            	fields: ['marketCity', 'marketState'],
            	onSuccess: {groupValidatePass : {}},
            	onFailure: {groupValidateFail : {message: 'Sorry, you must enter both City and State.'}}
            }*/
        }
    };



