// add AHAH (Asynchronous Html And Http) submission to forms
function add_ahah(forms) {
	for (f=0; f<forms.length; f++) {
		var form = document.getElementById(forms[f]);
		// add an onSubmit to each form that uses AHAH and overrides the normal form submission
		form.onsubmit = function() {
			if (this.getAttribute('action') == "videoforms.php?form=signup" ) {
				var result = submit_ahah(this.getAttribute('action')+'&mech=ahah', this.getAttribute('method'), this.getAttribute('enctype'), this.getAttribute('id'));
			} else {
				var result = submit_ahah(this.getAttribute('action')+'?mech=ahah', this.getAttribute('method'), this.getAttribute('enctype'), this.getAttribute('id'));
			}

			if (result) {
				return false; // this prevents the regular form submit mechanism from firing
			} else {
				return true; // this allows the regular form submit mechanism to fire
			}
		};
	}
}

// AHAH submission for the forms
function submit_ahah(action,method,enctype,id) {
	var data = compile_form_data(id);
	document.getElementById(id).innerHTML = '<p>Submitting Form...</p>';
	// Firefox, Opera, Safari
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	// IE
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	// either submit the form or throw an error
	if (req) {
		req.onreadystatechange = function() { receive_ahah(id); };
		req.open(method, action, true); // the last parameter might need to be true for GET, I'm not sure
		req.setRequestHeader('Content-Type', enctype);
		req.send(data);
		return true;
	} else {
		return false;
	}
}

// AHAH receipt of data from submit_ahah()
function receive_ahah(id) {
	// only if req is "loaded"
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200 || req.status == 304) {
			var results = req.responseText;
			document.getElementById(id).innerHTML = results;
		} else {
			document.getElementById(id).innerHTML='<h3>Form Submission error:<h3><p>' + req.status + ' ' + req.statusText + '</p>';
		}
	}
}

// this iterates through the contents of a form and compiles the data into one URL encoded string
function compile_form_data(id) {
	var data = new String;
	var form = document.getElementById(id);
	var inputs = form.getElementsByTagName('input');
	for (i=0; i<inputs.length; i++) {
		if (i>0) { data += '&'; }
		data += encodeURIComponent(inputs[i].getAttribute('name')) + '=' + encodeURIComponent(inputs[i].value);
	}
	return data;
}

//quick function to make sure referrer field on Share Video isn't blank or default.
function verify_referrer(name, email) {

  if (name == "First Last" || name == "")
  {
     alert("You must enter 'Your Name' to share this video.\n");
     return false;
  } else if (email == "one@domain.com, two@domain.com" || email == "") {
     alert("You must enter your friends email to share this video with.\n");
     return false;
  } else {
     return true;
  }

}
