jQuery.noConflict();
var registration = new Class({
	Implements:Options,
	options:{	target:null,
						audiences:{'Prospective/Current Patient':0,'Medical Professional':1},
						ourCountries:{},
						postalRequired:['Canada','United States'],
						audienceValue:0,
						regValidCallback:null,
						regConfirmCallback:null,
						regConfirmSync:'async',
						registrationValues:{}
					},
	initialize:function(options)
		{
			this.setOptions(options);
			this.options.ourCountries = new countries();
			this.options.target = $(this.options.target);
			this.options.target.getParent().adopt(new Element('div',{id:'receipt'}));
			this.options.receipt = $('receipt');
		},
	getRegistrationValues:function()
		{
			return this.options.registrationValues;
		},
	getAudience:function()
		{
			return this.options.audienceValue;
		},
	drawAudienceOption:function(klass,id)
		{
			var audienceEl = new Element('select',{'class':klass,'id':id,events:{'change':this.chooseAudience.bind(this)}});
			audienceEl.grab((new Element('option',{'value':-1,'selected':true,'defaultselected':true})).appendText('Prospective/Current Patient or Medical Professional?'));
			for(op in this.options.audiences)
				{
					audienceEl.grab((new Element('option',{'value':this.options.audiences[op]})).appendText(op));
				}
			this.options.target.adopt(audienceEl);
		},
	chooseAudience:function(e)
		{
			var ev = new Event(e);
			this.options.audienceValue = parseInt(ev.target.getProperty('value'));
			if(this.options.audienceValue==1)
				{
					this.options.target.empty();
					this.drawPhysicianForm();
				}
			else if(this.options.audienceValue==0)
				{
					this.drawPatientForm();
				}
		},
	drawPatientForm:function()
		{
			var patientCopy1 = 'We appreciate your interest in Fraxel. If you have a question not addressed in our ';
			var patientsLink = (new Element('a',{href:'/Patients/'})).appendText('Patient Section');
			var patientCopy2 = ', please use our ';
			var findDocLink = (new Element('a',{href:'/find-a-doctor/'})).appendText('Find a Doctor');
			var patientCopy3 = ' tool to find a qualified and trained medical professional to answer your question.';
			var patientCopy4 = 'Again, we appreciate your interest.';
			var container = (new Element('p')).appendText(patientCopy1).adopt(patientsLink).appendText(patientCopy2).adopt(findDocLink).appendText(patientCopy3).adopt(new Element('p').appendText(patientCopy4));
			this.options.target.adopt(container);
		},
	drawPhysicianForm:function()
		{
			var container,label,input,specialtyOptions,tempCountries,email,practice,telephone,address,city,state,postal,calltime,comments,requiredEl,notRequiredEl,clearEl;
			requiredEl = new Element('span',{'class':'requiredMarker'}).appendText('*');
			notRequiredEl = new Element('span',{'class':'requiredMarker'}).appendText('\u00A0');
			clearEl = new Element('div',{'class':'clear'}).appendText('\u00A0');
			// first name
			container = new Element('div',{id:'firstname','class':'inputContainer'});
			label = new Element('label',{'for':'firstnameInput',id:'firstnameLabel','class':'requiredLabel'}).appendText('First Name');
			input = new Element('input',{name:'firstname',id:'firstnameInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
			container.adopt([label,requiredEl.clone().setProperty('id','firstnameRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//last name
			container = new Element('div',{id:'lastname','class':'inputContainer'});
			label = new Element('label',{'for':'lastnameInput',id:'lastnameLabel'}).appendText('Last Name');
			input = new Element('input',{name:'lastname',id:'lastnameInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
			container.adopt([label,requiredEl.clone().setProperty('id','lastnameRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//title
			container = new Element('div',{id:'title','class':'inputContainer'});
			label = new Element('label',{'for':'titleInput'}).appendText('Title');
			input = new Element('input',{name:'title',id:'titleInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
			container.adopt([label,notRequiredEl.clone().setProperty('id','titleRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//practice name
			container = new Element('div',{id:'practicename','class':'inputContainer'});
			label = new Element('label',{'for':'practicenameInput',id:'practicenameLabel'}).appendText('Practice Name');
			input = new Element('input',{name:'practicename',id:'practicenameInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
			container.adopt([label,notRequiredEl.clone().setProperty('id','practiceNameRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//email
			container = new Element('div',{id:'email','class':'inputContainer'});
			label = new Element('label',{'for':'emailInput',id:'emailLabel','class':'requiredLabel'}).appendText('Email');
			input = new Element('input',{name:'email',id:'emailInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
			container.adopt([label,requiredEl.clone().setProperty('id','emailRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//telephone
			container = new Element('div',{id:'telephone','class':'inputContainer'});
			label = new Element('label',{'for':'telephoneInput',id:'telephoneLabel','class':'requiredLabel'}).appendText('Telephone');
			input = new Element('input',{name:'telephone',id:'telephoneInput',type:'text','length':25,'maxlength':30,styles:{width:160},events:{'blur':this.phoneForm.bind(this)}});
			container.adopt([label,requiredEl.clone().setProperty('id','telephoneRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			/* Specialty is not very useful right now.
			var specialtyOptions =	{	'Dentistry':'Dentistry','Dermatology':'Dermatology','Emergency':'Emergency','ENT':'ENT','Facial Plastic':'Facial Plastic',
																'Family Practice':'Family Practice','General Practice':'General Practice','Gynecology Only':'Gynecology Only',
																'Internal Medicine':'Internal Medicine', 'Obstetrics Only':'Obstetrics Only', 'OB/GYN':'OB/GYN', 'Oculoplastic':'Oculoplastic',
																'Ophthalmology':'Ophthalmology', 'Oncology':'Oncology', 'Plastic Surgery':'Plastic Surgery', 'Other':'Other'
															};*/
			
			//country
			container = new Element('div',{id:'country','class':'inputContainer'});
			label = new Element('label',{'for':'countryInput',id:'countryLabel','class':'requiredLabel'}).appendText('Country');
			input = new Element('select',{name:'country',id:'countryInput',type:'text',styles:{width:160},events:{'change':this.countryForm.bind(this)}});
			input.grab((new Element('option',{'value':'','selected':'true','defaultselected':'true'})).appendText(''));
			tempCountries = this.options.ourCountries.getCountries();
			for(country in tempCountries)
				{
					input.grab((new Element('option',{'value':country,events:{'change':this.countryForm.bind(this)}})).appendText(country));
				}
			container.adopt([label,requiredEl.clone().setProperty('id','countryRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//comments
			container = new Element('div',{id:'comments','class':'inputContainer'});
			label = new Element('label',{'for':'commentsInput','class':'requiredLabel'}).appendText('Comments');
			input = new Element('textarea',{name:'comments',id:'commentsInput','rows':5,'columns':30,styles:{width:160}});
			container.adopt([label,notRequiredEl.clone().setProperty('id','countryRequired'),input,clearEl.clone()]);
			this.options.target.adopt(container);
			
			//submit
			container = new Element('div',{id:'submit','class':'inputContainer'});
			input = new Element('input',{type:'submit',name:'submit',value:'Submit',id:'submitInput',events:{'click':this.validateForm.bind(this)}});
			container.adopt(input);
			this.options.target.adopt(container);
		},
	fillCountries:function(returned)
		{
			
		},
	countryForm:function(e)
		{
			var requiredEl = new Element('span',{'class':'requiredMarker'}).appendText('*');
			var clearEl = new Element('div',{'class':'clear'}).appendText('\u00A0');
			var ev = new Event(e);
			if(this.options.postalRequired.contains($(ev.target.options[ev.target.selectedIndex]).get('text')))
				{
					//postal
					if(!$('postalInput'))
						{
							if($('cityInput')){$('city').dispose();}
							var container = new Element('div',{id:'postal','class':'inputContainer'});
							var label = new Element('label',{'for':'postalInput',id:'postalLabel','class':'requiredLabel'}).appendText('Postal Code');
							var input = new Element('input',{name:'postal',id:'postalInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
							container.adopt([label,requiredEl.clone().setProperty('id','postalRequired'),input,clearEl]);
							container.inject(ev.target.getParent(),'after');
						}
				}
			else
				{
					//city
					if(!$('cityInput'))
						{
							if($('postalInput')){$('postal').dispose();}
							var container = new Element('div',{id:'city','class':'inputContainer'});
							var label = new Element('label',{'for':'cityInput',id:'cityLabel','class':'requiredLabel'}).appendText('City');
							var input = new Element('input',{name:'city',id:'cityInput',type:'text','length':25,'maxlength':30,styles:{width:160}});
							container.adopt([label,requiredEl.clone().setProperty('id','cityRequired'),input,clearEl]);
							container.inject(ev.target.getParent(),'after');
						}
				}
		},
	phoneForm:function(e)
		{ 
			var requiredEl = new Element('span',{'class':'requiredMarker'} ).appendText('*');
			var clearEl = new Element('div',{'class':'clear'}).appendText('\u00A0');
			var ev = new Event(e);
			if(e.target.getProperty('value').length>0 && !$('timesInput'))
				{
					
					var times = {	'09am-10am':'09am-10am',
												'10am-11am':'10am-11am',
												'11am-12am':'11am-12am',
												'12am-01pm':'12am-01pm',
												'01pm-02pm':'01pm-02pm',
												'02pm-03pm':'02pm-03pm',
												'03pm-04pm':'03pm-04pm',
												'04pm-05pm':'04pm-05pm',
												'05pm-06pm':'05pm-06pm',
												'06pm onwards':'06pm onwards'
											};
					var container = new Element('div',{id:'times','class':'inputContainer'});
					var label = new Element('label',{'for':'timesInput',id:'timesLabel','class':'requiredLabel'}).appendText('Best Time to Call');
					var input = new Element('select',{name:'times',id:'timesInput',type:'text',styles:{width:160}});
					input.grab(new Element('option',{'value':''}));
					for(time in times)
						{
							input.grab((new Element('option',{'value':time})).appendText(time));
						}
					container.adopt([label,requiredEl.clone().setProperty('id','timesRequired'),input,clearEl]);
					container.inject(ev.target.getParent(),'after');
					input.focus();
				}
		},
	validateForm:function()
		{
			var labels = [];
			var formData = {};
			var email = $('emailInput').getProperty('value').clean();
			var telephone = $('telephoneInput').getProperty('value').clean();
			var countrySelected = $('countryInput').selectedIndex;
			var messages = '';
			// first name
			if($('firstnameInput').getProperty('value').length < 1){labels[labels.length]={label:'firstnameLabel',field:'firstnameInput',message:'Please enter your first name.'};}
			// last name
			if($('lastnameInput').getProperty('value').length < 1){labels[labels.length]={label:'lastnameLabel',field:'lastnameInput',message:'Please enter your last name.'};}
			//did they fill the phone or the email?
			if(email.length < 1 && telephone.length < 1)
				{
					labels[labels.length]={label:'emailLabel',field:'emailInput',message:'Please enter either your email or your telephone number.'};
					labels[labels.length]={label:'telephoneLabel',field:'telephoneInput',message:''};
				}
			if(telephone.length > 0 && $('timesInput').selectedIndex==0)
				{
					labels[labels.length]={label:'timesLabel',field:'timesInput',message:'Please select a time that is best for us to call.'};
				}
			if(countrySelected != 0) // if they chose a country
				{
					// find out if the postal or the city field exists.
					if($('postalInput'))
						{
							if($('postalInput').getProperty('value').clean().length < 1)
								{
									labels[labels.length]={label:'postalLabel',field:'postalInput',message:'Please enter your postal code.'};
								}
						}
					else
						{
							if($('cityInput').getProperty('value').clean().length < 1)
								{
									labels[labels.length]={label:'cityLabel',field:'cityInput',message:'Please enter your city name.'};
								}
						}
				}
			else
				{
					labels[labels.length]={label:'countryLabel',field:'countryInput',message:'Please enter your country and either a postal code or city name.'};
					labels[labels.length]={label:'postalLabel',field:'postalInput',message:''};
					labels[labels.length]={label:'cityLabel',field:'cityInput',message:''};
				}
			this.options.target.getElements('label[class=requiredLabel]').each(function(el){el.setStyle('color','');});
			if(labels.length > 0)
				{
					labels.each(function(label)
												{
													if($(label.label)){$(label.label).setStyle('color','red');}
													if(label.message.length > 0){messages += label.message + '\n';}
												});
					alert(messages);
				}
			else
				{
					formData.firstname = $('firstnameInput').getProperty('value').clean();
					formData.lastname = $('lastnameInput').getProperty('value').clean();
					formData.title = $('titleInput').getProperty('value').clean();
					formData.practicename = $('practicenameInput').getProperty('value').clean();
					formData.email = $('emailInput').getProperty('value').clean();
					formData.telephone = $('telephoneInput').getProperty('value').clean();
					formData.timetocall = $('timesInput')?$('timesInput')[$('timesInput').selectedIndex].getProperty('value').clean():'';
					formData.country = $('countryInput')[countrySelected].getProperty('value').clean();
					formData.city = $('cityInput')?$('cityInput').getProperty('value').clean():'';
					formData.postal = $('postalInput')?$('postalInput').getProperty('value').clean():'';
					formData.comments = $('commentsInput').getProperty('value');
					formData.formOrigin = escape(window.location.toString());
					this.options.registrationValues = formData;
					this.options.regValidCallback();
					//this.sendForm(this.options.registrationValues);
				}
		},
	sendForm:function(formData)
		{
			//alert(JSON.encode(formData))
			//This code will send a data object via a GET request and alert the retrieved data.
			var jsonRequest = new Request({url:'/contact.cfm?register=fraxel', method:'post',onComplete:this.drawReceipt.bind(this)}).send('stuff='+JSON.encode(formData));
		},
	drawReceipt:function(responseData)
		{	
			this.options.registrationValues.leadId = JSON.decode(responseData).leadId;
			$('receipt').fireEvent('click');
		}
});
