window.$_dialog = null;
window.$_dialog_Modal = null;
window.$_dialog_AdditionalInfo = null;

function contact_form(title)
{
	var output =
		'<div id="moreInfo">'+
			'<a id="close_moreinfo" href="#">X</a>'+
			'<div class="moreinfo left">'+
				'<div id="moreinfo_container">'+
					'<h3>We’re Here to Help</h3>'+
					'<p>Call PriceDoc at 877.783.2771 from 8:00 AM to 5:00 PM PST, Monday through Friday. Or email us anytime at <a href="mailto:ProviderSupport@pricedoc.com">ProviderSupport@pricedoc.com</a></p>'+
					'<!-- BEGIN LivePerson Button Code -->'+
					'<div id="lpButDivID-1280534891107"></div>'+
					'<script type="text/javascript" charset="UTF-8" src="https://server.iad.liveperson.net/hc/83905930/?cmd=mTagRepstate&site=83905930&buttonID=16&divID=lpButDivID-1280534891107&bt=1&c=1"></script>'+
					'<!-- END LivePerson Button code -->'+
				'</div>'+
			'</div>'+
			'<div class="moreinfo right">'+
				'<div id="form_container">'+
					'<h3>'+ title +'</h3>'+
					'<p>Fill out the form below and a PriceDoc representative will contact you shortly.</p>'+
					'<form id="moreInfoSubmit" method="post" action="#">'+
						'<div class="inputArea">'+
							'<label for="firstName">First Name:</label>'+
							'<input id="firstName" type="text" name="first" />'+
						'</div>'+
						'<div class="inputArea">'+
							'<label for="lastName">Last Name:</label>'+
							'<input id="lastName" type="text" name="last" />'+
						'</div>'+
						'<div class="inputArea">'+
							'<label for="emailInput">E-Mail:</label>'+
							'<input id="emailInput" type="text" name="email" />'+
						'</div>'+
						'<div class="inputArea">'+
							'<label for="zipInput">Zip:</label>'+
							'<input id="zipInput" type="text" name="zip" />'+
						'</div>'+
						'<div class="inputArea" style="padding-top: 5px;">'+
							'<input type="image" src="'+window.$website_info.webroot+'css/join/images/contactme.png" />'+
							'<span id="moreInfoLoading" style="display: none; float: right;">Please wait...</span>'+
							'<br style="clear: both;" />'+
						'</div>'+
					'</form>'+
				'</div>'+
			'</div>'+
			'<br style="clear: both;" />'+
		'</div>'
	;
	return output;
}

$(function(){
	
				//Here begins Join Now Submit w/Validation
    	var jnform = $('form#join_now_form');
    	var validate_jnf = {
	        errorClass: 'invalid',
	        errorPlacement: function(error, element) {
						error.appendTo( element.prev('label') );
					},
	        submitHandler: function(jnform) {
		       // do other stuff for a valid form
		       var vars = $(jnform).serialize();	       
		       $.ajax({
	            url: '../join/joinnow.ajax.php',
	            async: false,
	            beforeSend: function() {
	            	$('#joinnowsubmit').hide();
	            	$('img.ldr').show();
	            },
	            data: vars,	            
	            success: function(html){
	            	if(html !='capnomatch')
	            	{
	            		//We're good notify UI
	            		$('img.ldr').hide();
	            		$(':input').clearForm();
	            		$('<div class="uinotice">Thank you!<br/>Your information has been received and you will hear from PriceDoc.</div>').insertBefore('input#joinnowsubmit');
	            	}
	            	else
	            	{
	            		//Captcha No Beuno :(
	            		$('img.ldr').hide();
	            		$('#joinnowsubmit').hide();
	            		$('<div class="uinotice" style="color:red; font-weight:bold;">CAPTCHA Text is not valid!</div>').insertBefore('input#joinnowsubmit');
	            	
	            	}					
				
					window.setTimeout(function(){						
	            	$('div.uinotice').remove();
	            	$('#joinnowsubmit').show();
					}, 3000);					
	                return true;
	            }
        });
		      	   		
			},
	        rules: {
	          BusinessName: {
	            required: true
	          },
	          ProviderType: {
	            required: true
	          },
	          FirstName: {
	            required: true
	          },
	          LastName: {
	            required: true
	          },
	          StreetAddress: {
	            required:true
	          },
	          City: {
	            required:true
	          },
	          State: {
	            required:true
	          },
	          Zip: {
	            required:true
	          },
	          NameOnCard: {
	            required:true,
	          },
	          BillingAddress: {
	            required:true,
	          },
	          BillingCity: {
	            required:true
	          },
	          BillingState: {
	            required:true
	          },
	          BillingZip: {
	            required:true
	          },
	          CardNumber: {
	            required:true
	          },
	          Expiration: {
	            required:true
	          },
	          CVV: {
	            required:true
	          },
	          Agree: {
	          	required:true
	          }
	        },
	        messages: {
	          BusinessName: {
	            required: "Required"
	          },
	          ProviderType: {
	            required: "Required"
	          },
	          FirstName: {
	            required: "Required"
	          },
	          LastName: {
	            required: "Required"
	          },
	          StreetAddress: {
	            required: "Required"
	          },
	          City: {
	            required: "Required"
	          },
	          State: {
	            required: "Required"
	          },
	          Zip: {
	            required: "Required"
	          },
	          NameOnCard: {
	            required: "Required"
	          },
	          BillingAddress: {
	            required: "Required"
	          },
	          BillingCity: {
	            required: "Required"
	          },
	          BillingState: {
	            required: "Required"
	          },
	          BillingZip: {
	            required: "Required"
	          },
	          CardNumber: {
	            required: "Required"
	          },
	          Expiration: {
	            required: "Required"
	          },
	          CVV: {
	            required: "Required"
	          },
	          Agree: {
	          	required: "Required"
	          }
	        }
	      }
	     
    	jnform.validate(validate_jnf);

//Here ends Join Now
	
				//Here begins Learn More Submit w/Validation
    	var lmform = $('form#learn_more_form');
    	var validate_lmf = {
	        errorClass: 'invalid',
	        errorPlacement: function(error, element) {
						error.appendTo( element.prev('label') );
					},
	        submitHandler: function(jnform) {
		       // do other stuff for a valid form
		       var vars = $(lmform).serialize();	       
		       $.ajax({
	            url: '../join/joinnow.ajax.php',
	            async: false,
	            beforeSend: function() {
	            	$('#learnmoresubmit').hide();
	            	$('img.ldr').show();
	            },
	            data: vars,	            
	            success: function(html){
	            	if(html !='capnomatch')
	            	{
	            		//We're good notify UI
	            		$('img.ldr').hide();
	            		$(':input').clearForm();
	            		$('<div class="uinotice">Thank you!<br/>Your information has been received and you will hear from PriceDoc.</div>').insertBefore('input#learnmoresubmit');
	            	}
	            	else
	            	{
	            		//Captcha No Beuno :(
	            		$('img.ldr').hide();
	            		$('#learnmoresubmit').hide();
	            		$('<div class="uinotice" style="color:red; font-weight:bold;">CAPTCHA Text is not valid!</div>').insertBefore('input#learnmoresubmit');
	            	
	            	}					
				
					window.setTimeout(function(){						
	            	$('div.uinotice').remove();
	            	$('#learnmoresubmit').show();
					}, 3000);					
	                return true;
	            }
        });
		      	   		
			},
	        rules: {
	          FirstName: {
	            required: true
	          },
	          LastName: {
	            required: true
	          },
	          EmailAddress: {
	            required: true
	          },
	          PhoneNumber: {
	            required: true
	          }
	        },
	        messages: {
	          FirstName: {
	            required: "Required"
	          },
	          LastName: {
	            required: "Required"
	          },
	          EmailAddress: {
	            required: "Required"
	          },
	          PhoneNumber: {
	            required: "Required"
	          }
	        }
	      }
	     
    	lmform.validate(validate_lmf);

//Here ends Join Now
	$('.modal').click(function()
	{
		var _message;
		switch($(this).attr('rel'))
		{
			case 'tos':
				_message = window.$load_TOSAgreement;
				break;
			case 'additional_details':
				_message = window.$load_AdditionalInfo;
				break;
			default:
				alert('woopsy');
		}
		DialogFactory.openDialog({
			message: _message,
			closeOnEscape: true,
			modal: true,
			title: $(this).attr('title'),
			width: 900,
			height: 600,
			buttons: {}
		});

		return false;
	});

	$('#contactus_btn, .advanced_request').click(function(){

		var _title = $(this).attr('title');
		$('#moreInfoSubmit input').val('');
		$('#moreInfoSubmit input').removeClass('inputError');
		var _message = contact_form(_title);
		if(window.$_dialog == null)
		{
			window.$_dialog =
				DialogFactory.openDialog({
					message: _message,
					reserve:true,
					closeOnEscape: true,
					dialogClass: 'moreinfo_dialog',
					modal: true,
					title: 'Need More Info?',
					width: 600,
					buttons: {}
			});
		}
		else
		{
			 window.$_dialog =
				DialogFactory.openDialog({
					message: _message,
					reserve:true,
					dialog:window.$_dialog,
					closeOnEscape: true,
					dialogClass: 'moreinfo_dialog',
					modal: true,
					title: 'Need More Info?',
					width: 600,
					buttons: {}
				});
		}

		$('#close_moreinfo').live('click',function(){
			$(window.$_dialog.dialogDiv).dialog('close');
			return false;
		});

		return false;
	});

	$('#moreInfoSubmit').live('submit',function(){

		if ($('#moreInfoLoading:visible').length == 1)
		//If request already made - wait till that has been processed
		{
			return false;
		}

		//First make sure all input fields are valid:
		Validation.validateInput({
			input: document.getElementById('firstName'),
			validationFunction: Generics.validation.validateNonEmpty,
			errorClass: 'inputError'
			});
		Validation.validateInput({
			input: document.getElementById('lastName'),
			validationFunction: Generics.validation.validateNonEmpty,
			errorClass: 'inputError'
			});
		Validation.validateInput({
			input: document.getElementById('emailInput'),
			validationFunction: Generics.validation.validateEmail,
			errorClass: 'inputError'
			});
		Validation.validateInput({
			input: document.getElementById('zipInput'),
			validationFunction: Generics.validation.validateZipCode,
			errorClass: 'inputError'
			});
		if ($('#moreInfoSubmit input').hasClass('inputError')){
			//Invalid Input !
			DialogFactory.openDialog({
				message: 'One or more of the fields are invalid.<br />Please correct the errors and try again.',
				title: 'Error',
				modal: true
				});

			return false;
		}

		//All inputs are valid - submit data to server
		var firstName = document.getElementById('firstName').value;
		var lastName = document.getElementById('lastName').value;
		var userEmail = document.getElementById('emailInput').value;
		var userZip = document.getElementById('zipInput').value;

		$('#moreInfoLoading').show();
		AjaxHelpers.sendRequest({
			data:
				'data=' +
				Generics.serialize({
					data: [
						userZip,
						userEmail,
						lastName,
						firstName
					],
					separator: 'A',
					encodeFunction: function(param){ return Base64.encode(param); }
					//ascendingOrder: false,
					//method: 0
				})
				,
			url: window.$website_info.webroot+'join/salesforce.ajax.php',
			//type: null,
			//method: null,
			onValid: function(data, textStatus)
			{
				$('.moreInfo :input').val('');
				DialogFactory.openDialog({
					message: data,
					title: 'Request Submitted',
					modal: true
					});
			},
			onExplicitlyInvalid: function(data, textStatus)
			{
				DialogFactory.openDialog({
					message: data,
					title: 'Request Failed',
					modal: true
					});
			},
			onImplicitlyInvalid: function(data, textStatus)
			{
				DialogFactory.openDialog({
					message: 'An unexpected error has occured. Please contact the site\'s management.',
					title: 'Request Failed',
					modal: true
					});
			},
			onError: function(xhr, textStatus, errorThrown)
			{
				DialogFactory.openDialog({
					message: 'A server error has occured. Please contact the site\'s management.',
					title: 'Request Failed',
					modal: true
					});
			},
			onNonErrorNonEmpty: function(data, textStatus)
			{
				$('#moreInfoLoading').hide();
			},
			decodeFunction: function(data)
			{
				return Base64.decode(data);
			},
			validResponseIndicator: 'OK',
			invalidResponseIndicator: 'BAD'
		});//End of AjaxHelpers.sendRequest

		$(window.$_dialog.dialogDiv).dialog('close');
		return false;
	});//End of $('#moreInfoSubmit').click()

	Validation.startInputValidation({
		input: document.getElementById('firstName'),
		validationFunction: Generics.validation.validateNonEmpty,
		errorClass: 'inputError',
		validateOnBlur: true,
		validateOnChange: false,
		validateOnKeyup: false
		});
	Validation.startInputValidation({
		input: document.getElementById('lastName'),
		validationFunction: Generics.validation.validateNonEmpty,
		errorClass: 'inputError',
		validateOnBlur: true,
		validateOnChange: false,
		validateOnKeyup: false
		});
	Validation.startInputValidation({
		input: document.getElementById('emailInput'),
		validationFunction: Generics.validation.validateEmail,
		errorClass: 'inputError',
		validateOnBlur: true,
		validateOnChange: false,
		validateOnKeyup: false
		});
	Validation.startInputValidation({
		input: document.getElementById('zipInput'),
		validationFunction: Generics.validation.validateZipCode,
		errorClass: 'inputError',
		validateOnBlur: true,
		validateOnChange: false,
		validateOnKeyup: false
		});
});

$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};
