// Use createMailForm to display a contact form.

// Files required: csitools, prototype, pushForm.js

//document.write('<style>.fLink {cursor:hand;cursor:pointer;text-decoration:underline;color:blue} </style>')

function mailForm(myObj){

	// ----- Object methods
	
	// Restrict tabbing to form elements
	this.tabkey = function(e){
		if (e.keyCode != 9)
			return this.specChars(e)
		if (e.srcElement == this.firstInput && event.shiftKey){
			this.lastInput.focus();
			return false;
		}
		if (e.srcElement == this.lastInput && !event.shiftKey){
			this.firstInput.focus();
			return false;
		}
		return this.specChars(e);
	}
	// Ignore special characters
	this.specChars = function(e){
		if (e.keyCode > 52 && e.keyCode < 56)
			return false;
	}
	// Clear the message field when it receives focus
	this.clearPrompt = function(e){
		var elm = this.form.f_msg;
		elm.style.color = 'black';
		if (elm.value == this.msgPrompt){
			elm.value = '';
		}
	}
	// Restore message field when it blurs and is empty
	this.insertPrompt = function(e){
		var elm = this.form.f_msg;
		if (trim(elm.value) == ''){
			elm.value = this.msgPrompt;
			elm.style.color = 'blue';
		}
	}
	// Show and hide the agent name field when the checkbox is clicked
	this.toggleAgent = function(e){
		var chkbx = this.form.f_haveagent;
		var wrapper = this.w_myagent;
		
		if (chkbx.checked){
			wrapper.style.display = 'block';
		} else {
			wrapper.style.display = 'none';
		}
	}
	// Show and hide the best time field when the phone number is entered
	this.toggleBT = function(e){
		var phone = this.form.f_phone;
		var bt_wrapper = this.w_besttime;
		
		if (phone.value == ""){
			bt_wrapper.style.display = 'none';
		} else {
			bt_wrapper.style.display = 'block';
		}		
	}
	// Remove the form from the window if necessary
	this.resetEmail = function(e){
		if (!this.parentElm) {
			popForm();
			//window.onscroll=document.body.onscroll=null;  // stopobserving() see prototype ??? handled by popForm?
		}
	}
	// Send the email using request to Ajax request to CFM script
	this.sendEmail = function(e){
		var eMsg = new Array("Please fix the following errors...");
		if (trim(this.form.f_name.value)=="")
			eMsg[eMsg.length] = "* Your Name is Required.";
		if (trim(this.form.f_email.value)=="")
			eMsg[eMsg.length] = "* Your Email Address is Required.";
		else if (!testEmail(trim(this.form.f_email.value)))
			eMsg[eMsg.length] = "* The Email address entered is not valid.";
		else if (trim(this.form.f_email2.value)=="")
			eMsg[eMsg.length] = "* Please re-type your email in the 'Confirm Email' field.";
		else if (trim(this.form.f_email.value)!=trim(this.form.f_email2.value))
			eMsg[eMsg.length] = "* The 'Confirm' email does not match 'Your' email.";
		if (trim(this.form.f_msg.value)=="" || trim(this.form.f_msg.value)==this.msgPrompt)
			eMsg[eMsg.length] = "* Please type a message to send.";
		if (eMsg.length > 1){
			alert(eMsg.join("\n\n"))
			return;
		}

		if (this.showAgent) {		// we have to override the agent checkbox
			this.form.request({
				method: 'get',
				parameters: { 
					haveAgent: this.form.f_haveagent.checked,
					'did': did, 
					user_id: this.user_id, 
					classid: this.classid,
					search: escape(document.location.search),
					pathname: escape(document.location.pathname)
				}
			});		
		} else {
			this.form.request({
				method: 'get',
				parameters: { 
					'did': did, 
					user_id: this.user_id, 
					classid: this.classid,
					search: escape(document.location.search),
					pathname: escape(document.location.pathname)
				}
			});
		}
		
		/*
		urlstring = '/wwwroot/remaint/ajax/email.cfm?did='+did+'&user_id='+currentForm.user_id+'&classid='+currentForm.classid;
		urlstring += '&e_name='+currentForm.e_name.value
		urlstring += '&e_phone='+currentForm.e_phone.value
		urlstring += '&e_email='+currentForm.e_email.value
		urlstring += '&e_besttime='+currentForm.e_besttime.value
		urlstring += '&e_msg='+currentForm.e_msg.value
		urlstring += '&search='+escape(document.location.search);
		urlstring += '&pathname='+escape(document.location.pathname);
		urlstring += '&myAgent='+currentForm.myAgent.value;
		urlstring += '&haveAgent='+currentForm.haveAgent.checked;
		
		//myAppBox.innerHTML = urlstring;
		//return;
		if(window.XMLHttpRequest) // use prototype ajax request
			var myxmlhttp = new XMLHttpRequest();
		else if(window.ActiveXObject) 
			var myxmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
		myxmlhttp.open("POST", urlstring,true);
		myxmlhttp.send(null);
		*/
		
		createCookie('f_name', this.form.f_name.value, 365);
		createCookie('f_email', this.form.f_email.value, 365);
		createCookie('f_phone', this.form.f_phone.value, 365);
		createCookie('f_besttime', this.form.f_besttime.value, 365);
		if (this.showAgent){
			createCookie('f_myagent', this.form.f_myagent.value, 365);
			createCookie('f_haveagent', this.form.f_haveagent.checked, 365);
		}
		this.resetEmail();
		alert('Your message has been sent!');
	}

	// Initialize form for reuse
	this.init = function(){
		// Event.observe(document.body,'scroll',lockWindow.bindAsEventListener(this) ?? handled by lockWindow?
		this.w_agentname.innerHTML = this.agentname;
//		this.div.style.visibility = 'visible';
		this.w_address.innerHTML = this.address;
		this.toggleBT();
		if (this.showAgent){
			this.toggleAgent();
		}
		this.insertPrompt();

		setTimeout("myMailForm.div.getElementsByTagName('input')[0].focus();",10)  //timeout for firefox delay
	
	}
	
	

	// ----- END Object functions




	// Load default object values
	this.classid = 0;			// Property ID
	this.address = 'Inquiry';	// This is actually the subject line
	this.agentname = null;		// Displayed in form
	this.user_id = null;		// To lookup user info for mail delivery
	this.msgPrompt = 'Enter your message or inquiry here.';
	this.parentElm = null;	// Optional place to insert overlay
	this.title = 'Request More Information';
	this.showAgent = true;		// Determines visibility of agent+name fields
	this.propTypes = null;		// Optional array of choices
	this.regions = null;		// Option array of choices
	this.priceRange = null;		// array for price ranges
	
	//if (this.propTypes)
	
	// If any parameters were sent using JSON, they will override defaults
	Object.extend(this, myObj);
	
	// ----- Prepare the XHTML
	this.div = $(document.createElement('div'));
	//this.div.style.visibility = 'visible';
	this.div.className = 'w_mailForm';
	
	var a = new Array();
	// Descriptive information
	a[a.length] = '<form action="/wwwroot/Lib/mailForm/mailForm.cfm">';
	a[a.length] = '<h2>' + this.title + '</h2>';
	a[a.length] = '<h4>Items marked with <strong>*</strong> are required</h4>';
	
	// Fields
	a[a.length] = '<div class="field w_to"><label>To:</label> <span class="value w_agentname">' + this.agentname + '</span></div>';
	a[a.length] = '<div class="field w_name"><label>Your name: <strong>*</strong></label><div class="value"><input type="text" class="f_name" name="f_name" size="37" maxlength="50" /></div></div>';
	a[a.length] = '<div class="field w_email"><label>Your e-mail: <strong>*</strong></label><div class="value"><input type="text" class="f_email" name="f_email" size="37" maxlength="50" /></div></div>';
	a[a.length] = '<div class="field w_email2"><label>Confirm e-mail: <strong>*</strong></label><div class="value"><input type="text" class="f_email2" name="f_email2" size="37" maxlength="50" /></div></div>';
	a[a.length] = '<div class="field w_phone"><label>Your phone:</label><div class="value"><input type="text" class="f_phone" name="f_phone" size="37" maxlength="30" /></div></div>';
	a[a.length] = '<div class="field w_besttime" style="display: none;"><label><small>Best time to call:</small></label><div class="value"><input type="text" class="f_besttime" name="f_besttime" size="37" maxlength="50" /></div></div>';
	if (this.showAgent){
		a[a.length] = '<div class="field w_haveagent"><input type="checkbox" class="f_haveagent" name="f_haveagent" value="true" /> <label>I am currently working with a real estate agent</label></div>';
		a[a.length] = '<div class="field w_myagent"><label>Agent name:</label><div class="value"><input type="text" class="f_myagent" name="f_myagent" size="37" maxlength="50" /></div></div>';
	}
	if (this.propTypes){
		a[a.length] = '<div class="field w_propTypes"><label>Property Type:</label><div class="value"><select class="f_propTypes" name="f_propTypes">';
		a[a.length] = '<option value=""></option>';
		for (var i=0; i<this.propTypes.length; i++){
			a[a.length] = '<option value="' + this.propTypes[i] + '">' + this.propTypes[i] + '</option>';
		}
		a[a.length] = '</select></div></div>';
	}
	if (this.regions){
		a[a.length] = '<div class="field w_regions"><label>Preferred Area:</label><div class="value"><select class="f_regions" name="f_regions">';
		a[a.length] = '<option value=""></option>';
		for (var i=0; i<this.regions.length; i++){
			a[a.length] = '<option value="' + this.regions[i] + '">' + this.regions[i] + '</option>';
		}
		a[a.length] = '</select></div></div>';
	}
	if (this.priceRange){
		a[a.length] = '<div class="field w_regions" style="width:350px;"><label>Price Range:</label></div><div style="height:25px;width:350px;"><div class="value" style="float:left;width:95px;"> <select class="f_priceRange" name="f_priceRange">';
		a[a.length] = '<option value=""></option>';
		for (var i=0; i<this.priceRange.length; i++){
			a[a.length] = '<option value="' + this.priceRange[i] + '">' + this.priceRange[i] + '</option>';
		}
		a[a.length] = '</select></div></div>';
	}
	
	a[a.length] = '<div class="field w_subject"><label>Subject:</label> <span class="value w_address">' + this.address + '</span></div>';
	a[a.length] = '<div class="field w_message"><textarea rows="5" cols="40" class="f_msg" name="f_msg" style="color:blue;">' +'</textarea></div>';
	a[a.length] = '<div class="field w_buttons"><input type="button" name="f_send" class="f_send" value="Send" />'
	if (!this.parentElm){
		a[a.length] = ' <input type="button" name="f_cancel" class="f_cancel" value="Cancel" />';
	}
	a[a.length] = '</div>';
	a[a.length] = '</form>';
	a[a.length] = '';
	this.div.innerHTML = a.join("\n");
	
	// Add the form to the DOM...
	if (this.parentElm){
		// Inside an existing element...
		this.parentElm.appendChild(this.div);
	} else {
		// Or floating on top of the page's content
		
		//this.div.style.zIndex=5;
		this.div.style.backgroundColor='#ffffdd';
		this.div.style.border='1px solid black';
		document.body.appendChild(this.div);
		this.div.style.position='absolute';
	}
	
	// Create references to field [w]rappers using getElementsByClassName
	this.w_to = this.div.getElementsByClassName('w_to')[0];
	this.w_name = this.div.getElementsByClassName('w_name')[0];
	this.w_agentname = this.div.getElementsByClassName('w_agentname')[0];
	this.w_email = this.div.getElementsByClassName('w_email')[0];
	this.w_email2 = this.div.getElementsByClassName('w_email2')[0];
	this.w_phone = this.div.getElementsByClassName('w_phone')[0];
	this.w_besttime = this.div.getElementsByClassName('w_besttime')[0];
	if (this.showAgent){
		this.w_haveagent = this.div.getElementsByClassName('w_haveagent')[0];
		this.w_myagent = this.div.getElementsByClassName('w_myagent')[0];
	}
	this.w_subject = this.div.getElementsByClassName('w_subject')[0];
	this.w_address = this.div.getElementsByClassName('w_address')[0];
	this.w_message = this.div.getElementsByClassName('w_message')[0];
	this.w_buttons = this.div.getElementsByClassName('w_buttons')[0];	

	// Create only the necessary field references
	this.form = this.div.getElementsByTagName('form')[0];
	this.allInputs = this.form.getElementsByTagName('input');
	this.firstInput = this.allInputs[0];
	this.lastInput = this.allInputs[this.allInputs.length-1];

		
	// Register event listeners/handlers
	Event.observe(this.form,'keypress',this.tabkey.bindAsEventListener(this));		// Converted
	Event.observe(this.form.f_phone,'keypress',this.toggleBT.bindAsEventListener(this));	// Converted
	if (this.showAgent){
		Event.observe(this.form.f_haveagent,'click',this.toggleAgent.bindAsEventListener(this));	// Converted
	}
	Event.observe(this.form.f_msg,'focus',this.clearPrompt.bindAsEventListener(this));	// Converted
	Event.observe(this.form.f_msg,'blur',this.insertPrompt.bindAsEventListener(this));	// Converted
	Event.observe(this.form.f_send,'click',this.sendEmail.bindAsEventListener(this));
	if (!this.parentElm){
		Event.observe(this.form.f_cancel,'click',this.resetEmail.bindAsEventListener(this));
	}

	// Read cookie settings
	this.form.f_name.value = readCookie('f_name') || '';
	this.form.f_email.value = readCookie('f_email') || '';
	this.form.f_email2.value = readCookie('f_email') || '';
	this.form.f_phone.value = readCookie('f_phone') || '';
	this.form.f_besttime.value = readCookie('f_besttime') || '';
	if (this.showAgent){
		this.form.f_myagent.value = readCookie('f_myagent') || '';

		if (!readCookie('f_haveagent') || readCookie('f_haveagent')=='false')
			this.form.f_haveagent.checked = false;
		else
			this.form.f_haveagent.checked = true;
	}

	return this;
}

// ------------------------- CODE REMAINING TO CONVERT

function createMailForm(myObj){
	if (!window.myMailForm)
		myMailForm = new mailForm(myObj);
	else {
		Object.extend(myMailForm, myObj);
	}
	
	myMailForm.init();

	// replace the following with pushForm(this.div)  will set visibility and z-index 
	pushForm(myMailForm.div,{enableBack:true,opacity:.5});

	return;
	
}








/*
function centerMe(){  // function lockWindow(elm,screen_top)  place in csitools
	if (window.pageYOffset)
	{
		  var scrollTop = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		var scrollTop = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  var scrollTop = document.body.scrollTop
	}
	
	if (window.innerHeight)
	{
		var clientHeight = window.innerHeight
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		var clientHeight = document.documentElement.clientHeight
	}
	else if (document.body)
	{
		var clientHeight = document.body.clientHeight
	}
	
	//alert(document.body.clientHeight)
	//alert(document.documentElement.clientHeight)
	
	if (clientHeight >= currentForm.form.offsetHeight){
		//alert(document.body.scrollTop)
		if (scrollTop < screen_top){
			//alert(currentForm.form.offsetTop+':'+currentForm.form.offsetHeight+':::'+scrollTop+':'+clientHeight)
			if (currentForm.form.offsetTop+currentForm.form.offsetHeight > scrollTop+clientHeight){
				scroll(0,currentForm.form.offsetTop+currentForm.form.offsetHeight-clientHeight)
				screen_top = currentForm.form.offsetTop+currentForm.form.offsetHeight-clientHeight
			}
		}
		if (scrollTop > screen_top){
			if (scrollTop > currentForm.form.offsetTop){
				scroll(0,currentForm.form.offsetTop)
				screen_top = currentForm.form.offsetTop
			}
		}
	}
	else {
		if (scrollTop < screen_top){
			//alert()
			if (currentForm.form.offsetTop > scrollTop){
				//alert()
				scroll(0,currentForm.form.offsetTop)
				screen_top = currentForm.form.offsetTop
			}
		}
		if (scrollTop > screen_top){
			if (currentForm.form.offsetTop+currentForm.form.offsetHeight < scrollTop+clientHeight){
				scroll(0,currentForm.form.offsetTop+currentForm.form.offsetHeight-clientHeight)
				screen_top = currentForm.form.offsetTop+currentForm.form.offsetHeight-clientHeight
			}
		}
	}
		
}
*/