//*******************************************
//****   Determine if we can send     *******
//*******************************************

function has_errors(err) {
	if (err != "") {
		alert(err);
		return false;
	} else {
		return true;
	}
}







//*******************************************************
//****   Validate Form  *********************************

// We are using element class names to determine validation
//
// Schema for Class Names
// [title=]constraint|constraint|constraint_arg1,arg2
//
//*******************************************************

function validate_form(fm) {

	var required_good = true;
	var form_elements = fm.elements;
	var err = "";

	for (i=0; i < form_elements.length; i++) {
		element = form_elements[i];
		element_label = document.getElementById('lab_'+element.id)
		element_good = true
		element_err = ""

		if (element.className != "") {

			if (element.type != 'file') {
				element.value = chop(element.value);
			}

			//If no title was supplied
			if (element.className.indexOf('=') == -1) {
				title = "";
				constraints = element.className.split('|');
			} else {
				val_string = element.className.split('=');
				title = val_string[0];
				constraints = val_string[1].split('|');
			}

			//Get Element Value
			val = element.value;

			//Loop Constraints
			for(j=0; j < constraints.length; j++) {

				if(constraints[j] != "") {

					constraint_part = constraints[j].split('_');
					method = constraint_part[0];
					args = constraint_part[1];

					if (method == "required") {
						if (!has_value(val)) {
							required_good = false;
							element_good = false
						}
					} else {
						if (val != "") {
							element_err = check_value(method, args, val, title);

							if (element_err != "") {
								err += element_err
								element_good = false
							}
						}
					}

				}
			}

			//Colorize Label
			highlight_label(element, element_good)

		}
	}


	if (required_good == false)
		err = "You must fill out all required fields.\r\n" + err


	return err;
}


//******************************************************
//****   Highlight Label Function                    ***
//*****************&************************************


function highlight_label(element, element_good) {
	element_label = document.getElementById('lab_'+element.id)
	if (element_label != undefined) {
		if (!element_good) {
			element_label.style.backgroundColor = '#A1312D';
			element_label.style.color = 'white';
		} else {
			//Defaults
			element_label.style.backgroundColor = '';
			element_label.style.color = '';
		}
	}
}





//*****************************************************************
//****   Forward Val, Title, And Args to appropriate function   ***
//*****************************************************************

function check_value(method, args, val, val_title) {

	method = method.toLowerCase();
	err = ""

	switch (method) {
		case 'email':
			exp = /^([a-zA-Z_0-9\-\.]+)@([a-zA-Z_0-9\.\-]+)\.[a-zA-Z0-9]{2,5}$/;
			e_msg = "Invalid Email";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'url':
			exp = /^(http:\/\/|https:\/\/)+[\.a-zA-Z0-9-]+\.[a-zA-Z0-9.]{2,5}.*$/;
			e_msg = "Invalid URL, Must start with http:// OR https:// and end with a valid extension";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'domain':
			if (val.substr(0,4) == "www.")
				return val_title + "Invalid Domain, Please dont use the www. in the domain, Example: yoursite.com";
			exp = /^[\.a-zA-Z0-9-]+\.[a-zA-Z0-9.]{2,5}$/;
			e_msg = "Invalid Domain, Example: yoursite.com";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'phone':
			exp = /^([0-9]{3})\-([0-9]{3})\-([0-9]{4})$/;
			e_msg = "Invalid Phone, Example: 555-555-5555";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'date':
			exp = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
			e_msg = "Invalid Date, Example: mm/dd/yyyy";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'zip':
			exp = /^([0-9]{5})$/;
			e_msg = "Invalid Zip, Must be five digits only";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'price':
			exp = /^[0-9]*(\.[0-9]{1,2})?$/;
			e_msg = "Invalid Price, Must use digits and decimal only - no dollar sign allowed";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'number':
			exp = /^[0-9]+$/;
			e_msg = "Invalid Number, Must use digits only";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'alphanum':
			exp = /^[a-zA-Z0-9\,\.\-]+$/;
			e_msg = "Invalid Text, Only numbers, letters, and characters: . , - (No Spaces)";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'alpha num':
			exp = /^[a-zA-Z0-9 \-\,\?\^\.\!\)\(\;\:\_\']+$/;
			e_msg = "Invalid Text, Only numbers, letters, and characters: . , - ? ^ ' _ : ; ! ( )";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'password':
			exp = /^[a-zA-Z0-9\_\-]{6,}$/;
			e_msg = "Invalid Password, Must be 6 characters and only numbers, letters, and some special characters";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'date':
			exp = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
			e_msg = "Invalid Date, Example: MM/DD/YYYY";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'orb-url':
			exp = /^[a-zA-Z0-9\-\_]+$/;
			e_msg = "Invalid Text, Only numbers, letters, hyphens and underscores";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'text':
			exp = /^[a-zA-Z0-9 \-\,\?\^\.\!\)\(\;\:\_\']+$/;
			e_msg = "Invalid Text, Only numbers, letters, and characters: . , - ? ^ ' _ : ; ! ( )";
			err = validate_regexp(val, val_title, exp, e_msg);
			break;

		case 'compare':
			err = validate_compare(val, args);
			break;

		case 'video':
			err = validate_filetype(val, val_title, 'video')
			break;

		case 'audio':
			err = validate_filetype(val, val_title, 'audio')
			break;

		case 'image':
			err = validate_filetype(val, val_title, 'image')
			break;

		case 'styles':
			err = validate_filetype(val, val_title, 'styles')
			break;
	}

	return err;

}






//******************************************************
//****   Functions Called By Check Value Funcion     ***
//*****************&************************************

//Email Validation
function validate_regexp(val, val_title, exp, e_msg) {

	if (val_title != "")
		val_title = val_title + " - "

	if (!exp.test(val)) {
		return val_title + e_msg + "\r\n";
	} else {
		return "";
	}

}

function validate_compare(val, args) {

	argument = args.split(',')
	message = argument[0]
	target_name = argument[1]

	target = document.getElementsByName(target_name);

	if (val != target[0].value) {
		return message + "\r\n";
	} else {
		return "";
	}
}


function validate_filetype(val, val_title, filetype) {

	if (val_title != "")
		val_title = val_title + " - "


	switch (filetype) {

		case 'video':
			var valid_ext_types = new Array('avi', 'mp4', 'mpg', 'flv');
			break;

		case 'audio':
			var valid_ext_types = new Array('mp3', 'wav');
			break;

		case 'image':
			var valid_ext_types = new Array('bmp', 'gif', 'jpg', 'jpeg', 'tif');
			break;

		case 'styles':
			var valid_ext_types = new Array('css', 'gif', 'jpg', 'jpeg', 'png');
			break;

	}

	//Get Extension
	filename_parts = val.split('.');
	my_ext = filename_parts.pop();

	//See if Extension is in the list of valid extensions
	is_valid_ext = false
	for (k in valid_ext_types) {
		if (my_ext.toLowerCase() == valid_ext_types[k]) {
			is_valid_ext = true;
		}
	}

	//Return
	if (is_valid_ext) {
		return '';
	} else {

		//Make a string of valid extensions
		types_list = valid_ext_types.join(', ');

		return val_title + 'Invalid File, valid file types are ' + types_list + "\r\n";;

	}

}





//********************************************
//****   Helper Functions            *********
//********************************************


function date_clear(element) {
	if (element.value == "MM/DD/YYYY") {
		element.value = "";
	}
}

function date_fill(element) {
	if (element.value == "") {
		element.value = "MM/DD/YYYY";
	} else {
		element.value = make_good_date(element.value)
	}
}

function make_good_date(val) {

	//Replace other common delimiters with forward slash
	val = val.replace(/[-\.]/g,"\/")


	//If no delimiters were used, put some in
	num_exp = /^([0-9]{8})$/;

	if (num_exp.test(val)) {
		val = val.substr(0,2) + "/" + val.substr(2,2) + "/" + val.substr(4,4)
	}


	//If no leading zeros were used, put some in
	parts = val.split("/")

	if (parts[0].length == 1) {
		parts[0] = "0" + parts[0]
	}

	if (parts[1].length == 1) {
		parts[1] = "0" + parts[1]
	}

	val = parts[0] + "/" + parts[1] + "/" + parts[2]



	// Return a nice date
	return val

}


function char_check(obj, max_chars) {

	my_text = document.getElementById(obj.id).value

	if (my_text.length > max_chars) {
		alert("This field may only have " + max_chars + " characters")
		document.getElementById(obj.id).value = my_text.substr(0,max_chars)
	}

	document.getElementById('chars_'+obj.id).innerHTML = "&nbsp;";

}

function char_count(obj, max_chars) {

	num_chars = document.getElementById(obj.id).value.length

	if (num_chars < max_chars) {
		document.getElementById('chars_'+obj.id).innerHTML = "You are using " + num_chars + "/" + max_chars + " characters."
	} else {
		document.getElementById('chars_'+obj.id).innerHTML = "<font color='red'>You are using " + num_chars + "/" + max_chars + " characters.</font>"
	}
}

function has_value(val) {

	if (val == "") {
		return false;
	} else {
		return true;
	}
}

function chop(val){
	var tmp = ""
	var val_length = val.length;
	var val_length_minus_1 = val.length - 1;
	var i
	for (i = 0; i < val_length; i++) {
    		if (val.charAt(i) != ' ') {
			tmp += val.charAt(i)
		} else {
			if (tmp.length > 0) {
				if (val.charAt(i+1) != ' ' && i != val_length_minus_1) {
					tmp += val.charAt(i)
				}
			}
		}
	}

	return tmp
}

function set_focus(element_object) {
	//Puts focus on thisField
	element_object.focus()
}