// requires jQuery and colorFlash extension

//Bind Form Submission Function
$(function() {
	$('.dform#form1').each(function() {
		var tid = this.id;
		$('.submit_button',this).click(function() { contactSubmit(tid); });
	});
});

function contactSubmit(formID) {

	//Generic
	var jQ = $;
	var query = '';
	var amp = '';

	var submitURL = "http://"+document.location.hostname+"/contact-us"; // may need to be changed per site.
	var subscribeURL = "http://"+document.location.hostname+"/campaign/list/subscribe"; // may need to be changed per site.
	
	var foundError = false;
	var errorFields = new Array();

	jQ("input,textarea","#"+formID).each(function() {
		if(this.value != this.defaultValue || this.checked || $(this).is("[type=hidden]")) {
			query += amp+this.name+'='+this.value.replace('&','%26'); // hackish urlencoding
			amp = '&';
		}else{
			switch(this.name){
				case 'company':
				case 'phone':
				case 'subscriber_lists[]':
				case 'questions-comments':
					break;
				default:
					foundError = true;
					errorFields.push(this.name);
					break;
			}
		}
	});

	if(foundError){
		for(i=0; i < errorFields.length; i++) {
			jQ("#"+formID+" input[@name="+errorFields[i]+"]").colorFlash({ speed: "fast" });
		}
	}else{
		$.ajax({
			type:'POST',
			url:subscribeURL,
			data:query,
			dataType:'xml'			
		});
		$.ajax({
			type:'POST',
			url:submitURL,
			data:query,
			dataType:'html',
			complete:function(xh,s) {
				var jQ = $;
				successResponder(formID);
			}
		});
	}
}

function resetForm(formID) {
	/* Reset the form upon successful submission */
	$('input, textarea','#' + formID).each(function() {
		this.value = this.defaultValue;
		if(this.checked) this.checked = false;
		$(this).removeClass("mod");
	});
}

function successResponder(formID) {
	$('#'+formID+'_response').html("<span class=\"success\">Thank You for contacting ATV Maine. We look forward to answering any questions you may have.</span>");
	/* Reset the form upon successful submission */
	resetForm(formID);
	$('#'+formID+'_response').fadeIn('fast');
}