/* 
 *************************************************** USAGE:
 *
 * <form ... onsubmit="return validateForm(this);">* 
 * 
 ***
 * SETTING VALID FIELD MASK
 * <input .. validtype="nonempty" />
 * Fires alert if field is empty
 * 
 * <input .. validtype="email" />
 * Fires alert if field's value is not an e-mail address
 * Other filters can be added (see isFieldValid() function)
 *
 *** 
 * SETTING ERROR MESSAGE
 * <input .. error="Telephone number" />
 * Adds a friendly field name to the error message
 *   
 * <input .. error="#Telephone number is required." />
 * Hash on the begining: Error message is
 * displayed as value provided in this attribute
 * 
 * <input .. /> (no 'error' attribute)
 * Predefined error message will be displayed
 *   
 *** 
 * DISABLING VALIDATION
 * By hiding field:
 * <input .. style="display: none" /> or
 * <input .. style="visibility: hidden" />
 * 
 * By hiding any level of field's parent nodes:
 * <div style="display: none"><input ... /></div> or
 * <div style="visibility: hidden"><input ... /></div>
 * 
 */
function validateForm(form) {
	with(form) {
		for(i=0; i<elements.length; i++) {
			if(elements[i].style.display != 'none' && elements[i].style.visibility != 'hidden') {
				if(!isFieldValid(elements[i])) {
					displayError(elements[i]);
					return false;
				}
			}
		}
	}
	
	return true;
}

function filter_default(field) {
	return field.value.length > 0 ? true : false
}

function filter_isEmail(field) {
	atPos  = field.value.indexOf("@");
	dotPos = field.value.lastIndexOf(".");
	return !(atPos < 2 || dotPos < 4 || dotPos < atPos || dotPos > (field.value.length-3));
}

// Checks if all fields' parent nodes (including itself) are visible
function isNodeVisible(field) {
	if(!field.tagName || field.tagName.toLowerCase == 'html')
		return true;
	
	if(field.style.visibility == 'hidden' || field.style.display == 'none')
		return false;

	return isNodeVisible(field.parentNode);
}

function isFieldValid(field) {
	var isValid		= true;
	
	with(field) {

		// If field has attributes 'error' or 'validtype', perform validation
		if(cbGetAttribute('', 'validtype', field) || cbGetAttribute('', 'error', field)) {
			
			// Do not perform field validation if it's not visible
			if(!isNodeVisible(field))
				return true;
			
			if(cbGetAttribute('', 'validtype', field)) {
				switch(cbGetAttribute('', 'validtype', field)) {

					case 'email':
										return filter_isEmail(field);
										break;
					
					case 'nr_prawa':
										return !(value.length < 2 && !document.getElementById('bez_prawa').checked);;
										break;
										
					case 'instytucja':
										if(value.length > 2) {
											if(value == 'inna') {
												if(document.getElementById('instytucja_inna').value.length > 2) return true;
												else return false;
											}
											else return true;
										}
										else {
											if(document.getElementById('bez_prawa').checked) return true;
											else {
												if(document.getElementById('instytucja_inna').value.length > 2) return true;
												else return false;
											}
										}
										break;
										
					case 'nip1':
										if(document.getElementById('firma1_radio').checked) {
											return !(value.length < 2); 
										}
										else return true;
										break;
					
					case 'faktura2':
										if(document.getElementsByName('faktur').value == 2) {
											return filter_default(field);
										}
										else return true;
										break
										
					case 'nip2':
										if(document.getElementById('firma2_radio').checked) {
											return !(value.length < 2); 
										}
										else return true; 
										break;
					
					// Filter not specified - use default
					case 'required':
					default:
										return filter_default(field);
				}
			}
			
			// Radio buttons - any selected makes radios correct
			if(cbGetAttribute('', 'type', field) == 'radio') {
				var radios = document.getElementsByName(name);
				isValid = false;
				for(r=0; r<radios.length; r++) {
					if(radios[r].checked) {
						return true;
					}
				}
				return false;
			}
			
			// Checkboxes
			if(cbGetAttribute('', 'type', field) == 'checkbox') {
				return checked;
			}
			
			// Filter not specified - use default
			return filter_default(field);
		}
	}
	return isValid;
}


// Displays error messages
function displayError(field) {
	var defaultError		= "To pole nie może pozostać puste.";
	var defaultError_en	= "This field is required.";
	
	var customError			= "Pole ^ nie może pozostać puste."; // ^ is the place where friendly field name goes
	var customError_en	= "Field ^ cannot be empty."; // ^ is the place where friendly field name goes
	var lang = 'pl';
	
	with(field) {
		if(cbGetAttribute('', 'lang', field) != null) {
			lang = cbGetAttribute('', 'lang', field);
		}
		
		if(field) {
			// Default message
			if(!cbGetAttribute('', 'error', field)) {
				switch(lang) {								
					case 'en':	alert(defaultError_en); break;	
					default:		alert(defaultError);
				}
				
			}
			
			else {
				// Individual message
				if(cbGetAttribute('', 'error', field).indexOf('#') > -1) {
					msg = cbGetAttribute('', 'error', field);
					alert(msg.substr(1, msg.length));
				}
				
				// Message with customized field name
				else {
					switch(lang) {								
						case 'en':	alert(customError_en.replace('^', cbGetAttribute('', 'error', field))); break;
						default:		alert(customError.replace('^', cbGetAttribute('', 'error', field)));
					}
					
				}
			}
			
			focus();
			return true;
		}
		else {
			return false;
		}
	}	
}

////////////////////////////////////////////////////// LIBS
/**
* Cross browser getAttribute function with namespace support.
* @return string -- Contents of an attribute on a given element, or an empty string on failure.
* @author Robert Græsdal
*/
function cbGetAttribute(nsPrefix, attribute, elem) {
	if( attribute.length < 1 || !elem ) return '';
	
	if( elem.getAttributeNS ) { 
		var doc = elem.ownerDocument;
		var root = doc.documentElement;
		var prefix = (nsPrefix.length > 0) ? (nsPrefix+':xmlns') : 'xmlns';
		
		var namespaceURI = '';
		if(nsPrefix.length > 0) {
			namespaceURI = (root.attributes[nsPrefix]) ? 
			(root.attributes[nsPrefix].value) : (root.getAttribute('xmlns:'+nsPrefix));
		} 
		
		var res = elem.getAttributeNS(namespaceURI, attribute) != '' ? 
		elem.getAttributeNS(namespaceURI, attribute) : 
		elem.getAttribute(nsPrefix+':'+attribute);
		
		return (res != null) ? res : '';
	}
	else { // Last resort (IE6 will take this one)
		var prefix = (nsPrefix.length > 0) ? (nsPrefix+':'+attribute) : attribute;
		
		var res;
		try {
			res = (prefix == 'class') ? elem.className : elem.getAttribute(prefix);
		} catch (ex) {
			// Sometimes IE will throw an exception here.
			// alert('Error# '+ex.code+' "'+ex+'" '+typeof(ex));
		}
	
		return (!res) ? '' : res; // Return empty string instead of null
	}
}
