/*
 * Steve's Simple PHP Forms
 * Javascript Form Validator
 *
 * This script is open source, free for use and modification.
 * Please leave this notice in tact to credit me for creating it.
 *
 * Author: Steven Moseley
 * Homepage: http://www.stevenmoseley.com
 * Business: http://www.transio.com
 *
 */
// Validates all fields in the specified form
function validate(form) {
	var inputs = form.getElementsByTagName('*');
	var valid = true;
	var message = '';
	// Search for invalid inputs
	var i;
	for (i = 0; i < inputs.length; i++) {
		var ok = true;
		var input = inputs[i];
		var tagName = input.tagName ? input.tagName : '';
		var title = input.getAttribute('title') ? input.getAttribute('title') : '';
		var required = input.getAttribute('required') && input.getAttribute('required').toLowerCase() == 'true';
		var minlength = !isNaN(input.getAttribute('minlength')) && input.getAttribute('minlength') > 0 ? input.getAttribute('minlength') : 0;
		var format = input.getAttribute('format') ? input.getAttribute('format') : '';
		var confirm = input.getAttribute('confirm') ? input.getAttribute('confirm') : '';
	
		// Required radio list
		if (required && input.getAttribute('type') == 'radio') {
			if (!checkRadio(input.getAttribute('name'))) {
				message += '"' + title + '" is required.  Please select one.\n';
				ok = false;
			}
		}
		// Required Input test
		if (required && minlength <= 0 && format.length == 0) {
			if (tagName == 'select') {
				if (!input.options || input.options.length == 0 || !input[input.selectedIndex].value || input[input.selectedIndex].value == '') {
					message += '"' + title + '" is required.  Please make a selection.\n';
					ok = false;
				}
			} else {
				if (input.value.length == 0) {
					message += '"' + title + '" is a required field.\n';
					ok = false;
				}
			}
		}
		// Minlength test
		if (minlength > 0) {
			if (input.value.length < minlength) {
				message += '"' + title + '" has a minimum required length of ' + minlength + ' characters.\n';
				ok = false;
			}
		}
		// Format test
		if (format.length > 0) {
			if (format.toLowerCase() == 'email') {
				if (input.value.indexOf('@') <= 0 || input.value.indexOf('.') <= 0  || input.value.length < 6) {
					message += '"' + title + '" is not a proper email format.\n';
					ok = false;
				}
			} else if (format.toLowerCase() == 'mmdd') {
				//var mm = input.value.substring(0, 2);
				//var dd = input.value.substring(2);
				if (input.value.length < 4 || Math.isNaN(input.value)) {
					message += '"' + title + '" is not a proper MMDD date format.\n';
					ok = false;
				}
			} else if (format.toLowerCase() == 'numeric') {
				if (!isFloatingPointNumber(input.value)) {
					message += '"' + title + '" must be a number.\n';
					ok = false;
				}
			} else if (format.toLowerCase() == 'int') {
				if (!isInt(input.value)) {
					message += '"' + title + '" must be a whole number.\n';
					ok = false;
				}
			}
			// Regular Expressions
			//regex = input.format;
			//ok = ok && regex.exec(input.value);
		}
		// Confirm input test
		if (confirm.length > 100) {
			confirmInput = document.getElementById(confirm);
			if (confirmInput && input.value != confirmInput.value) {
				confirmTitle = confirmInput.getAttribute('title') ? confirmInput.getAttribute('title') : 'Input';
				message += '"' + confirmTitle + '" and "' + title + '" do not match.\n';
				ok = false;
			}
		}
		// Focus on first bad input
		if (!ok) {
			input.style.backgroundColor = '#FF0000';
			input.style.color = '#FFFFFF';
			if (valid) {
				try {
					input.focus();
				} catch (e) {
				}
			}
			valid = false;
		} else {
			input.style.backgroundColor = '';
			input.style.color = '';
		}
	}
	if (message.length > 0) {
		window.alert(message);
	}
	return valid;
}
function checkRadio(name) {
	var inputs = document.getElementsByName(name);
	var checked = false;
	var i;
	for (i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		checked = checked || input.checked;
	}
	return checked;
}
function allowOnlyFloatingPointNumbers(textbox, val){
	val = val.replace(/[^0-9.-]/g, ''); // strip non-digit chars
	val = stripDuplicateChars(val, '.', 1, 0); // strip excess decimals
	val = stripDuplicateChars(val, '-', 0, 1); // strip excess minus signs
	textbox.value = val; // replace textbox value
	if (!isFloatingPointNumber(val)){ alert('This is not a valid number, please correct it...');}
}
function isFloatingPointNumber(val) {
	return isNumeric(val, false);
}
function isInt(val) {
	return isNumeric(val, true);
}
function isNumeric(val, isInt) {
	var validChars = "0123456789" + (isInt ? "" : ".");
	var isNumber = true;
	for (var i = 0; i < val.length && isNumber == true; i++) {
		var char = val.charAt(i);
		isNumber = isNumber && validChars.indexOf(char) > -1;
	}
	return isNumber;
}
function stripDuplicateChars(str, strip, n, s){
	var count=0; var stripped=str.substring(0, s); var chr;
	for (var i=s; i<str.length; i++){ chr = str.substring(i, i+1);
		if (chr == strip) {
			count++;
			if (count<n+1) {
				stripped = stripped + chr;
			}
		} else {
			stripped = stripped + chr;
		}
	}
	return stripped;
}
// Focuses on the first <input> or <select> field in the specified form
function focusForm(formId) {
	var elements = (formId)
			? document.getElementById(formId).getElementsByTagName('*')
			: document.getElementsByTagName('*');
	for (var i = 0; i < elements.length; i++) {
		input = elements[i];
		if (input.tagName.toLowerCase() == 'input' ||
				input.tagName.toLowerCase() == 'select') {
			input.focus();
			break;
		}
	}
	return true;
}
function toggleCheckbox(id) {
	var checkbox = document.getElementById(id);
	checkbox.checked = !checkbox.checked;
}
// Shows or hides the specified form
function showForm(formId) {
	document.getElementById(formId).style.display = '';
	document.getElementById('hide_' + formId).style.display = '';
}
function hideForm(formId) {
	document.getElementById(formId).style.display = 'none';
	document.getElementById('hide_' + formId).style.display = 'none';
}
function confirmDelete(itemName, deleteUrl) {
	if (window.confirm('Are you sure you want to delete:\n' + itemName + '?')) {
		window.location = deleteUrl;
	}
}
function loadSelected(pageUrl, selectField, persistedParameters) {
	var idName = selectField.name;
	var id = selectField[selectField.selectedIndex].value;
	if (id > 0) {
		var location = pageUrl + '?' + idName + '=' + id;
		for (var i = 0; i < persistedParameters.length; i++) {
			location += '&' + persistedParameters[i][0] + '=' + persistedParameters[i][1];
		}
		window.location.href = location;
	}
}
function loadType(typeField) {
	var typeId = typeField[typeField.selectedIndex].value;
	var subtypeField = document.getElementById("listing_subtype_id");
	for (var i = 0; i < subtypeField.length; i++) {
		var option = subtypeField[i].id;
		var optionTypeId = option.substring(option.indexOf("_") + 1, option.indexOf("."));
		if (optionTypeId == typeId || optionTypeId == '') {
			subtypeField[i].style.display = '';
		} else {
			subtypeField[i].style.display = 'none';
		}
	}
}

function getParameter(key) {
	var querystring = window.location.search.substring(1);
	var parameters = querystring.split('&');
	for (var i = 0; i < parameters.length; i++) {
		var pos = parameters[i].indexOf('=');
		if (pos > 0) {
			if (key == parameters[i].substring(0, pos)) {
				return '&' + parameters[i];
			}
		}
	}
	return '';
}
function popWindow(url, width, height) {
	var popup = window.open(url, 'popup', 'width=' + width + ', height=' + height + ', toolbars=no,  status=no, menu=no, scrollbars=yes');
}
function showFocusInfo(element) {
    var focusInfo = document.getElementById('focus_info_' + element.id);
    if (focusInfo) {
        var pos = findPos(element);
        focusInfo.style.display = 'block';
        focusInfo.style.position = 'absolute';
        focusInfo.style.left = '' + (pos[0] + 12) + 'px';
        focusInfo.style.top = '' + (pos[1] - focusInfo.offsetHeight - element.offsetHeight + 4) + 'px';
    }
}
function hideFocusInfo(element) {
    var focusInfo = document.getElementById('focus_info_' + element.id);
    if (focusInfo) {
        focusInfo.style.display = 'none';
    }
}
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}