
//add event listeners to the form fields to get them to go blank onfocus and fill in with their name values + capitalized first letter onblur
filter = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(xGetElementById('contactform')) {
	theForm = xGetElementById('contactform');
	
	//add an onclick event to the goodsubmit button to prevent the form from being submitted
	xAddEventListener(xGetElementById('goodsubmit'),'click',sendMailRequest,false);
}

if(xGetElementById('transaction')) {
	theForm = xGetElementById('transaction');
	//add an onsubmit event to the form - to check the email address
	xAddEventListener(theForm,'submit',checkEmail,false);
}

if(xGetElementById('refundForm')) {
	theForm = xGetElementById('refundForm');
	xAddEventListener(theForm,'submit',checkForRefund,false);
}

if(xGetElementById('forgottenForm')) {
	theForm = xGetElementById('forgottenForm');
	xAddEventListener(theForm,'submit',checkForgotten,false);
}

if(xGetElementById('testimonialForm')) {
	theForm = xGetElementById('testimonialForm');
	xAddEventListener(theForm,'submit',checkTestimonialFields,false);
}

for(i=0;i<theForm.elements.length;i++) {
	if(theForm.elements[i].type != 'submit') {
			xAddEventListener(xGetElementById(theForm.elements[i]),'focus',makeBlank,false);
			xAddEventListener(xGetElementById(theForm.elements[i]),'blur',checkValue,false);
	}
}

function checkTestimonialFields(e) {
	var ev=(!e)?window.event:e;//IE:Moz
	ev.preventDefault?ev.preventDefault():ev.returnValue = false; //syntax = testcond?true:false;

	errorMsg = '';
	for(i=0;i<theForm.elements.length;i++) {
		if(theForm.elements[i].nodeName == "INPUT" || theForm.elements[i].nodeName == "TEXTAREA") {
			if(theForm.elements[i].type != "submit") {
				if(theForm.elements[i].value.replace(/\s/,'') == '' || theForm.elements[i].value.replace(/\s/,'').toLowerCase() == theForm.elements[i].id) {
					errorMsg = "Invalid value for " + theForm.elements[i].id.substr(0,1).toUpperCase() + theForm.elements[i].id.substr(1) + " field";
					if(!xGetElementById('contacterror')) {
						error = document.createElement('span');
						error.id = 'contacterror';
						theForm.getElementsByTagName('fieldset')[0].insertBefore(error,theForm.getElementsByTagName('fieldset')[0].firstChild);
					}
					theForm.elements[i].focus();
					xGetElementById('contacterror').innerHTML = errorMsg;
					
					break;
				}
			}
		}
	}
	
	if(errorMsg == '') {
		theForm.getElementsByTagName('fieldset')[0].style.height = theForm.getElementsByTagName('fieldset')[0].offsetHeight+'px';
	
	
		queryString = new Object();
		queryString['name'] = xGetElementById('name').value;
		queryString['address'] = xGetElementById('address').value;
		queryString['testimonial'] = xGetElementById('testimonial').value;
		if(xGetElementById('testimonialid')) {
			queryString['testimonialid'] = xGetElementById('testimonialid').value;
		}
		
		//do the ajax thing here
		url = prepareURL("scripts/php/sharedfuncs.php",queryString);
		url += "&ajax=addTest";
		addTestimonial = GetXmlHttpObject();
		addTestimonial.open("GET",url,true)
		addTestimonial.onreadystatechange = function() {
			if(addTestimonial.readyState == 4 && addTestimonial.status == 200) {
				loading = document.createElement('img');
				loading.id = 'loading';
				loading.src = 'images/loading.gif';
				loading.width = '80';
				loading.height = '67';
				loading.alt = 'Please Wait...';
				
				sending = document.createElement('span');
				sending.id = 'sending';
				sending.innerHTML = 'Posting testimonial...';
				
				theForm.getElementsByTagName('fieldset')[0].innerHTML = '';
				theForm.getElementsByTagName('fieldset')[0].appendChild(sending);
				theForm.getElementsByTagName('fieldset')[0].appendChild(loading);
				
				setTimeout('if(xGetElementById(\'loading\')) xGetElementById(\'loading\').parentNode.removeChild(xGetElementById(\'loading\')); sending.innerHTML = \'Testimonial posted!<br />This testimonial is now available for viewing on the testimonials page\';',2000);				
				theDoc = addTestimonial.responseXML.documentElement;
				
				
				//determine if this testimonial already exists in the list
				updated = false;
				for(i=0;i<xGetElementById('testimonialList').options.length;i++) {
					if(xGetElementById('testimonialList').options[i].value == theDoc.getElementsByTagName('id')[0].firstChild.nodeValue) {
						
						xGetElementById('testimonialList').options[i].innerHTML = theDoc.getElementsByTagName('name')[0].firstChild.nodeValue + ' - ' + theDoc.getElementsByTagName('address')[0].firstChild.nodeValue;
						updated = true;
						break;
					}
				}
				
				if(!updated) {
					newTestimonial = document.createElement('option');
					newTestimonial.innerHTML = theDoc.getElementsByTagName('name')[0].firstChild.nodeValue + ' - ' + theDoc.getElementsByTagName('address')[0].firstChild.nodeValue;
					newTestimonial.value = theDoc.getElementsByTagName('id')[0].firstChild.nodeValue;
					xGetElementById('testimonialList').appendChild(newTestimonial);
				}
			}
		}
		addTestimonial.send(null);
	}
	
}

function makeBlank(e) {
	targ = getClickedElement(e);
	//first thing to check, if the name is the same as the content, then make it blank
	if(targ.value && targ.value.replace(/\s*/g,'').toLowerCase() == targ.name) {
		targ.value = '';
	} else {
	
		//next thing - make the element blank specifically based on its id	
		switch(targ.id) {
			case 'accesserrorinput': //video error, forgotton accesscode, or refund access code
				targ.style.color = '#5c7f8a';
				if(targ.value == 'Video Access Code')
					targ.value = '';
				break;
			case 'email': //when we're ready to make a purchase, or issuing a refund
				targ.style.color = '#5c7f8a';
				if(targ.value == 'E-mail Address')
					targ.value = '';
				break;
		}
	}
}

function checkValue(e) {
	targ = getClickedElement(e);

		switch(targ.id) {
			case 'accesserrorinput':
				targ.style.color = '#9fd7e8';
				if(targ.value.replace(/\s*/g,'') == '')
				targ.value = 'Video Access Code';
				break;
			case 'email':
				targ.style.color = '#9fd7e8';
				if(targ.value.replace(/\s*/g,'') == '')
				targ.value = 'E-mail Address';
				break;
			default:
				if(targ.value) {
					if(targ.value.replace(/\s*/g,'') == '')
					targ.value = targ.name.substring(0,1).toUpperCase() + targ.name.substring(1);
				}
		}
}


function checkForRefund(e) {
	var ev=(!e)?window.event:e;//IE:Moz
	ev.preventDefault?ev.preventDefault():ev.returnValue = false; //syntax = testcond?true:false;
	
	if(xGetElementById('email').value == 'E-mail Address' || !filter.test(xGetElementById('email').value) || xGetElementById('accesserrorinput').value == 'Video Access Code') {
		if(!xGetElementById('contacterror')) {
			error = document.createElement('span');
			error.id = 'contacterror';
			theForm.getElementsByTagName('fieldset')[0].insertBefore(error,theForm.getElementsByTagName('fieldset')[0].firstChild);
		}
		
		if(xGetElementById('accesserrorinput').value == 'Video Access Code') {
			error.innerHTML = 'Please enter your video access code';
			xGetElementById('accesserrorinput').focus();
		} else if(xGetElementById('email').value == 'E-mail Address') {
			error.innerHTML = 'Please enter your e-mail address';
			xGetElementById('email').focus();
		} else if(!filter.test(xGetElementById('email').value)) {
			error.innerHTML = 'That\s not a valid e-mail address';
			xGetElementById('email').focus();
		}
		
	} else {
	
		queryString = new Object();
		queryString['email'] = xGetElementById('email').value;
		queryString['accesscode'] = xGetElementById('accesserrorinput').value;
	
		//do the ajax thing here
		url = prepareURL("scripts/php/sharedfuncs.php",queryString);
		url += "&ajax=refund";
		verifyRefund = GetXmlHttpObject();
		verifyRefund.open("GET",url,true)
		verifyRefund.onreadystatechange = function() {
		if(verifyRefund.readyState == 4 && verifyRefund.status == 200) {
			theForm.getElementsByTagName('fieldset')[0].style.height = theForm.getElementsByTagName('fieldset')[0].offsetHeight+'px';
			loading = document.createElement('img');
			loading.id = 'loading';
			loading.src = 'images/searching.gif';
			loading.width = '220';
			loading.height = '27';
			loading.alt = 'Please Wait...';
				
			sending = document.createElement('span');
			sending.id = 'sending';
			sending.innerHTML = 'Verifying e-mail and access code...';
				
			theForm.getElementsByTagName('fieldset')[0].innerHTML = '';
			theForm.getElementsByTagName('fieldset')[0].appendChild(sending);
			theForm.getElementsByTagName('fieldset')[0].appendChild(loading);
		
			setTimeout('theForm.getElementsByTagName(\'fieldset\')[0].innerHTML = verifyRefund.responseText',2000);
		}
		}
		verifyRefund.send(null);
	}
}

function checkForgotten(e) {
	var ev=(!e)?window.event:e;//IE:Moz
	ev.preventDefault?ev.preventDefault():ev.returnValue = false; //syntax = testcond?true:false;

	if(xGetElementById('email').value == 'E-mail Address' || !filter.test(xGetElementById('email').value)) {
		if(!xGetElementById('contacterror')) {
			error = document.createElement('span');
			error.id = 'contacterror';
			error.innerHTML = 'Are you sure the e-mail you entered is correct?';
			theForm.getElementsByTagName('fieldset')[0].insertBefore(error,theForm.getElementsByTagName('fieldset')[0].firstChild);
		}
	} else {
	
		queryString = new Object();
		queryString['email'] = xGetElementById('email').value;
	
		//do the ajax thing here
		url = prepareURL("scripts/php/sharedfuncs.php",queryString);
		url += "&ajax=forgotten";
		checkForgottenCode = GetXmlHttpObject();
		checkForgottenCode.open("GET",url,true)
		checkForgottenCode.onreadystatechange = function() {
		if(checkForgottenCode.readyState == 4 && checkForgottenCode.status == 200) {
			theForm.getElementsByTagName('fieldset')[0].style.height = theForm.getElementsByTagName('fieldset')[0].offsetHeight+'px';
			loading = document.createElement('img');
			loading.id = 'loading';
			loading.src = 'images/searching.gif';
			loading.width = '220';
			loading.height = '27';
			loading.alt = 'Please Wait...';
				
			sending = document.createElement('span');
			sending.id = 'sending';
			sending.innerHTML = 'Searching for Access Codes...';
				
			theForm.getElementsByTagName('fieldset')[0].innerHTML = '';
			theForm.getElementsByTagName('fieldset')[0].appendChild(sending);
			theForm.getElementsByTagName('fieldset')[0].appendChild(loading);
		
			setTimeout('theForm.getElementsByTagName(\'fieldset\')[0].innerHTML = checkForgottenCode.responseText',2000);
		}
		}
		checkForgottenCode.send(null);
	}
}

function checkEmail(e) {
	//remove the error if present
	if(xGetElementById('contacterror')) {
		xGetElementById('contacterror').parentNode.removeChild(xGetElementById('contacterror'));
	}


	//verify the e-mail address is acceptable
	if (!filter.test(xGetElementById('email').value)) {
		//prevent the button from submitting the form and show the error
		error = document.createElement('span');
		error.id = 'contacterror';
		error.innerHTML = 'Are you sure the e-mail you entered is correct?';
		xGetElementById('transaction').insertBefore(error,xGetElementById('transaction').firstChild);
		var ev=(!e)?window.event:e;//IE:Moz
		ev.preventDefault?ev.preventDefault():ev.returnValue = false; //syntax = testcond?true:false;
	}

}

function sendMailRequest(e) {
	//prevent the button from submitting the form
	var ev=(!e)?window.event:e;//IE:Moz
	ev.preventDefault?ev.preventDefault():ev.returnValue = false; //syntax = testcond?true:false;

	//loop through the form elements to get them all in an associative array
	queryString = new Object();
	for(i=0;i<theForm.elements.length;i++) {
		/*if(theForm.elements[i].name != 'goodsubmit') {
			theForm.elements[i].style.borderWidth = '0'; //reset any error that may be shown
		}*/
		
		
		if(theForm.elements[i].nodeName == 'INPUT' || theForm.elements[i].nodeName == 'TEXTAREA' || theForm.elements[i].nodeName == 'SELECT') {
		
			//note: exclude the "badsubmit" button from being sent - just by
			//executing this JS we know that this isn't a robo-spam request
			if(theForm.elements[i].nodeName != 'SELECT') {
				if(theForm.elements[i].value.replace(/\s/g,'').toLowerCase() == theForm.elements[i].name || theForm.elements[i].value.replace(/\s/g,'') == '') {
					var error = xGetElementById(theForm.elements[i]);
					break;
				}
			} else {
				if(theForm.elements[i].options[theForm.elements[i].selectedIndex].value == theForm.elements[i].name) {
					var error = xGetElementById(theForm.elements[i]);
					break;
				}
			}
		
			if(theForm.elements[i].name == 'email') {
				//verify the e-mail address is acceptable
				if (!filter.test(theForm.elements[i].value)) {
					var error = xGetElementById(theForm.elements[i]);
				}
			}
		
			if(theForm.elements[i].name != 'badsubmit') {
				queryString[theForm.elements[i].name] = theForm.elements[i].value;
			}
		}
	}
	
	if(error) {
		//show the error on the form
		error.focus();
		//error.style.border = '1px solid #f00';
		//add an error message right before the form
		if(!xGetElementById('contacterror')) {
			errorDiv = document.createElement('span');
			errorDiv.id = 'contacterror';
			theForm.parentNode.insertBefore(errorDiv,theForm);
		} else {
			errorDiv = xGetElementById('contacterror');
		}
		
		errorDiv.innerHTML = 'Invalid value for '+error.name.substring(0,1).toUpperCase()+error.name.substring(1)+' field';
		
	} else {
		if(xGetElementById('contacterror')) {
			xGetElementById('contacterror').parentNode.removeChild(xGetElementById('contacterror'));
		}
		
		//do the ajax thing here
		url = prepareURL("scripts/php/sharedfuncs.php",queryString);
		url += "&ajax=contact";
		sendMail = GetXmlHttpObject();
		sendMail.open("GET",url,true)
		sendMail.onreadystatechange = function() {
			if(sendMail.readyState == 4 && sendMail.status == 200) {
				loading = document.createElement('img');
				loading.id = 'loading';
				loading.src = 'images/loading.gif';
				loading.width = '80';
				loading.height = '67';
				loading.alt = 'Please Wait...';
				
				sending = document.createElement('span');
				sending.id = 'sending';
				sending.innerHTML = 'Sending Message...';
				
				theForm.innerHTML = '';
				theForm.appendChild(sending);
				theForm.appendChild(loading);
				
				setTimeout('loading.src = \'images/sent.gif\'; loading.alt = \'Message Sent\'; sending.innerHTML = \'Message Successfully Sent!<br />Thanks for your comments!\';',3000);
			}
		}
		sendMail.send(null);
	}
	
}


function prepareURL(prefix,pairs) {
	
	//create a query string from the url
	var url = '';
	for(key in pairs) {
		//encode all the parameters to be paased
		url = url+'&'+key+'='+pairs[key];
	}
	
	//encode the url using a custom function from phpjs.org
	//url = urlencode(url);

	//prevent caching of ajax calls
	t = new Date();
	url = url+'&t='+t.getTime();
	return prefix+'?'+url;
}

function urlencode( str ) {                            
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}
