
var INET = {};

INET.src = function(src) {
    var uri = "";
 	var rx = /^[a-z]+:\/\//;
	if (src.match(rx)) {

        uri = src;

	}
	else {
		uri = encodeURI(src);
	}
	return uri;
}

INET.addCSS = function(src, media) {
	document.write("<link rel=\"stylesheet\" type=\"text/css\" media=\""+ media +"\" href=\""+ INET.src(src) +"\" />");
};

INET.addJS = function(src) {
	document.write("<script type=\"text/javascript\" src=\""+ INET.src(src) +"\"></script>");
};


INET.isEmail = function(s) {
	var rx = /^[a-z0-9\-_\.]*[a-z0-9\-_]@([a-z0-9\-\.])+\.[a-z]{2,4}$/i;
	return s.match(rx);
};

INET.isURL = function(s) {
	var rx = /^([a-z]+:\/\/)?([^\s\/\.]+\.)+([a-z0-9]{2,4})(:\d+)?(\/.*)?$/i;
	return s.match(rx);
};

INET.isInteger = function(s) {
	var rx = /^-?\d+$/;
	return s.match(rx);
};

INET.str2Int = function(str) {
	var num = parseInt(str);
	if (isNaN(num)) {
		return 0;
	}
	else {
		return num;
	}
};

INET.trim = function(s) {
	return jQuery.trim(s);
};

INET.hasClassName = function(obj, cname) {
	return jQuery(obj).hasClass(cname);
};

INET.addClassName = function(obj, cname) {
	jQuery(obj).addClass(cname);
};

INET.removeClassName = function(obj, cname) {
	jQuery(obj).removeClass(cname);
};


/*******************/
/**** INET form ****/

INET.form = function() {
	var _this = this;

	this.id = null;
	this.obj = null;
	this.submitObj = null;
	this.elements = [];

	//Adds an element to the form - must provide type, requirements, maxlength etc.:
	this.addElement = function(params) {
		var objElement = new INET.formElement(params);
	    objElement.setValidation();

	    // Add non-hidden child elements for selects, radio groups and checkbox groups:
	    switch (objElement.type) {
	    
	        case "select":
	            var arrOption = jQuery(objElement.obj).find("option");	
		        if (arrOption.length > 0) {
			        jQuery.each(arrOption, function() {
				        var objOption = this;
				        var defVal = false;
				        jQuery.each(objElement.defaultValues, function() {
				            if (this.id == INET.str2Int(objOption.value)) {
				                defVal = this.defaultValue;
				                return false;
				            }
				        });
				        objElement.addElement({"obj": objOption, "id": "IDFormElement" + objOption.value, "defaultValue": defVal, "parent": objElement});
			        });
		        }
		        break;
		        
	        case "radiogroup":
	        case "checkboxgroup":
		        var arrInput = jQuery(objElement.obj).find("input");
		        if (arrInput.length > 0) {
			        jQuery.each(arrInput, function() {
			            var objInput = this;
				        if (objInput.type != "hidden") {  
					        var defVal = false;
				            jQuery.each(objElement.defaultValues, function() {
				                if (this.id == INET.str2Int(objInput.value)) {
				                    defVal = this.defaultValue;
				                    return false;
				                }
				            });  
					        objElement.addElement({obj: objInput, id: "IDFormElement" + objInput.value, type: objElement.type.replace("group", ""), defaultValue: defVal, parent: objElement});
				        }
			        });
		        }
		        break;
		    
		    default:
		        break;
	    }

	    _this.elements.push(objElement);
	};
    
	this.validate = function() {
		var res = true;
		var msg = "";

		//Recursively validate elements:
		jQuery.each(_this.elements, function() {
			if (!this.validate()) {
			    var objLabel = this.getLabel();
			    msg += (objLabel != null ? "- " + jQuery(objLabel).text() +"\n" : "");
			    res = false;
			}
		});

		//Only display error message if this is not a poll:
		if (!INET.hasClassName(_this.obj, "IDFormPoll")) {
			if (!res) {
				msg = ":\n\n" + msg; 
				alert(msg);
			}
		}

		return res;
	};
	
	this.submit = function() {
		if (_this.submitObj != null) {
			if (_this.submitObj.name == "IDFormNext") {
				return _this.validate();
			}
			else {
				return true;
			}
		}
		else {
			return _this.validate();
		}
	};
    
    this.reset = function() {
        var defaultFound = false;
	    jQuery.each(_this.elements, function() {
		    if (this.reset()) {
			    defaultFound = true;
		    }
	    });

	    if (defaultFound) {
	        return false;   // prevent default reset behaviour
	    }
	    return true;
	};
};


/**************************/
/**** INET formElement ****/


INET.formElement = function(params) {
    var _this = this;
	this.obj = params.obj || null; //reference to HTML element
	this.id = params.id || (this.obj != null ? jQuery(this.obj).attr("id") : null);
	this.type = params.type || null; //text, textarea, select, radiogroup, checkboxgroup, etc.
	this.subType = params.subType || null; //integer, email, etc.
	this.required = params.required || false;
	this.defaultValue = params.defaultValue || null;
	this.defaultValues = params.defaultValues || [];
	this.maxLength = params.maxLength || 0;
	this.elements = []; //subelements
	this.parent = params.parent || null;

	//Reset this form element - depends on type
	this.reset = function() {
	    var res = false;
	    
		switch (_this.type) {
			
			case "radiogroup":
			case "checkboxgroup":
			    jQuery.each(_this.elements, function() {
	                var objElm = this;
	                var objInp = objElm.obj;
	                if (Boolean(objElm.defaultValue)) {
	                    objInp.checked = objElm.defaultValue;
	                }
	                else {
	                    objInp.checked = false;
	                }
	                res = true;
                });
                _this.warning(false);
                break;
                
			case "select":
				jQuery.each(_this.elements, function() {
	                var objElm = this;
	                var objOpt = objElm.obj;
	                if (Boolean(objElm.defaultValue)) {
	                    objOpt.selected = objElm.defaultValue;
	                }
	                else {
	                    objOpt.selected = false;
	                }
	                res = true;
                });
                _this.warning(false);
				break;
				
			case "text":
			case "textarea":
				if (_this.defaultValue != null) {
				    jQuery(_this.obj).val(_this.defaultValue);
				    res = true;
				}
				else {
				    jQuery(_this.obj).val("");
				}
				_this.warning(false);
				break;
				
			default: 
				break;
		}
		return res;
	};
	
	// Get label
	this.getLabel = function() {
	    var objLabel = null;

	    switch (_this.type) {
	    
		    case "radiogroup":
		    case "checkboxgroup":
		    case "select":
			    objLabel = document.getElementById(_this.id + "Title");
			    break;
			    
		    default:
			    var arrLabel = _this.obj.form.getElementsByTagName("LABEL");
			    if (arrLabel.length > 0) {
				    jQuery.each(arrLabel, function() {
					    if (this.htmlFor == _this.id) {
						    objLabel = this;
						    return false;
					    }
				    });
			    }
			    break;
	    }
	    return objLabel;
    };
    
    // Changes class of element and its label - use to highlight incomplete fields:
    this.warning = function(b) {
	    var oLabel = _this.getLabel();

	    if (!b) {
		    INET.removeClassName(_this.obj, "incomplete");
		    INET.removeClassName(oLabel, "incomplete");
	    }
	    else {
		    INET.addClassName(_this.obj, "incomplete"); 
		    INET.addClassName(oLabel, "incomplete"); 
	    }
    };
    
    // Validates entered / selected values of a form element while user is interacting with it:
    this.liveValidate = function(e) {

	    if (_this != null) {
		    var rx = /^\s+/i;

		    var val = _this.obj.value;
		    var newval = val;
		    newval = (val.match(rx) ? val.replace(rx, "") : newval);

		    switch(_this.type) {
		    
			    case "text":
				    switch (_this.subType) {
					    
					    case "email":
						    var rx = /\s|,/g;
						    newval = (newval.match(rx) ? newval.replace(rx, "") : newval);
						    break;
						    
					    case "integer":
						    var rx = /[^\d\-]/g;
						    newval = (newval.match(rx) ? newval.replace(rx, "") : newval);
						    var rx = /^(-?)\D*(\d*)\D*$/;
						    newval = (newval.match(rx) ? newval.replace(rx, "$1$2") : newval);
						    break;
						    
					    default:
						    break;
				    }
				    if (val != newval) {
					    _this.obj.value = newval;
				    }
				    break;
				    
			    case "textarea":
				    if (val != newval) {
					    _this.obj.value = newval;
				    }
				    break;
		    }
	    }
    };
    
    // Validate this object's value:
    this.validate = function() {
	    var res = true;

	    if (_this != null) {
		    switch(_this.type) {
			    
			    case "text": 
				    var val = INET.trim(_this.obj.value);
				    val = (_this.maxLength > 0 ? val.substring(0, _this.maxLength) : val);

				    switch (_this.subType) {
					    
					    case "email":
						    if (INET.isEmail(val)) {
							    _this.warning(false);
						    }
						    else {
							    if (_this.required) {
								    _this.warning(true);
								    res = false;
							    }
							    else {
								    if (val == "") {
									    _this.warning(false);
								    }
								    else {
									    _this.warning(true);
									    res = false;
								    }
							    }
						    }
						    break;
						    
					    case "integer":
						    if (INET.isInteger(val)) {
							    _this.warning(false);
						    }
						    else {
							    if (_this.required) {
								    _this.warning(true);
								    res = false;
							    }
							    else {
								    if (val == "") {
									    _this.warning(false);
								    }
								    else {
									    _this.warning(true);
									    res = false;
								    }
							    }
						    }
						    break;
						    
					    case "url":
						    var rx = /^([a-z]+):\/\//;
						    var newval = val;
						    if (!newval.match(rx)) {
							    newval = "http://" + newval;
						    }
						    if (INET.isURL(newval)) {
							    val = newval;
							    _this.warning(false);
						    }
						    else {
							    if (_this.required) {
								    _this.warning(true);
								    res = false;
							    }
							    else {
								    if (val == "") {
									    _this.warning(false);
								    }
								    else {
									    _this.warning(true);
									    res = false;
								    }
							    }
						    }
						    break;
						    
					    default:
						    if (_this.required) {
							    if (val != "") {
								    _this.warning(false);
							    }
							    else {
								    _this.warning(true);
								    res = false;
							    }
						    }
						    break;
				    }
				    _this.obj.value = val;
				    break;
				    
			    case "textarea":
				    var val = INET.trim(_this.obj.value);
				    val = (_this.maxLength > 0 ? val.substring(0, _this.maxLength) : val);
				    _this.obj.value = val;

				    if (_this.required) {
					    if (_this.obj.value != "") {
						    _this.warning(false);
					    }
					    else {
						    _this.warning(true);					
						    res = false
					    }
				    }
				    break;
				    
			    case "select":
				    if (_this.required) {
					    var count = 0;
					    
					    jQuery.each(_this.elements, function() {
						    if (this.obj.selected) {
							    count++;
							    return false;
						    }
					    });
					    if (count == 0) {
						    _this.warning(true);
						    res = false;
					    }
					    else {
						    _this.warning(false);
					    }
				    }
				    else {
					    _this.warning(false);
				    }
				    break;
				    
			    default:
				    switch (_this.type) {
					    
					    case "radiogroup":
					    case "checkboxgroup":
						    if (_this.required) {
							    var count = 0;
							    jQuery.each(_this.elements, function() {
								    if (this.obj.checked) {
									    count++;
									    return false;
								    }
							    });
							    if (count == 0) {
								    _this.warning(true);
								    res = false;
							    }
							    else {
								    _this.warning(false);
							    }
						    }
						    else {
							    _this.warning(false);
						    }
						    break;
						    
					    default:
						    break;
				    }
				    break;
		    }
	    }
	    else {
		    res = false;
	    }
	    return res;
    };
    
    // Trap key
    this.trapKey = function(e) {
	    var k = e.keyCode;
	    switch (k) {
		    case 8: //backspace
		    case 9: //tab
		    case 37: //left
		    case 38: //up
		    case 39: //right
		    case 40: //down
			    return true;
			    break;
	    }

	    var res = true;
	    
	    switch(_this.type) {
		    
		    case "text":
			    switch(_this.subType) {
				    
				    case "email":
					    if (e.keyCode == 32) {
						    res = false;
					    }
					    break;

				    case "integer":
					    if (((k >= 48) && (k <= 57)) || ((k >= 96) && (k <= 105)) || ((k == 109) || (k == 189) || (k == 191))) {
						    res = true;
					    }
					    else {
						    res = false;
					    }
					    break;

				    case "url":
					    break;

				    default:
					    break;
			    }
			    break;
			    
		    default:
			    break;
	    }

	    return res;
    };
    
    // Set element validation
    this.setValidation = function() {
	    var oLabel = null;
	    
	    switch(_this.type) {
		    
		    case "text": //standard text input field
			    _this.obj.onblur = function() {
				    _this.validate();
			    }
			    _this.obj.onkeyup = function(e) {
				    if (!e) var e = window.event;
				    _this.liveValidate(e);
			    }
			    _this.obj.onkeydown = function(e) {
				    if (!e) var e = window.event;
				    return _this.trapKey(e);
			    }
			    break;
			    
		    case "radio":
			    _this.obj.onchange = function() {
				    _this.parent.validate();
			    }
			    break;
			    
		    case "checkbox":
			    _this.obj.onclick = function() {
				    _this.parent.validate();
			    }
			    break;
			    
		    case "textarea": //textarea field
			    _this.obj.onblur = function() {
				    _this.validate();
			    }

			    _this.obj.onkeyup = function(e) {
				    if (!e) var e = window.event;
				    _this.liveValidate(e);
			    }
			    break;
			    
		    case "select": //select, possibly multiple
			    _this.obj.onchange = function() {
				    _this.validate()
			    }
			    break;
			    
		    default: //radiogroup, checkboxgroup
			    //do nothing here ...
			    break;
	    }
    };
    
    // Add child element
    this.addElement = function(params) {
	    var objElement = new INET.formElement(params);
	    objElement.setValidation();
	    _this.elements.push(objElement);
    };
};


/***************************/
/**** IDFormHandlerClass ***/

INET.formHandler = function() {
    var _this = this;
	this.forms = [];

    //Add a form to the list of monitored forms - handles onsubmit and onreset event
    this.addForm = function(obj) {
	    var objForm = null;

		//Loop through forms array and retrieve matching INET.form element:
		jQuery.each(_this.forms, function() {
			if (this.id == jQuery(obj).attr("name")) {
				objForm = this;
				return false;
			}
		});

		//Form not found, add it:
		if (objForm == null) {
			objForm = new INET.form();
			objForm.obj = obj;
			objForm.id = jQuery(obj).attr("name");
			
			objForm.obj.onsubmit = function() {
			    return objForm.submit();
		    }

		    objForm.obj.onreset = function() {
			    return objForm.reset();
		    }

			_this.forms.push(objForm);
		}
		return objForm;
    };


    //Return the INET.form having supplied id:
	this.getForm = function(id) {
		var res = null;
		jQuery.each(_this.forms, function() {
			if (jQuery(this.obj).attr("name") == id) {
				res = this;
				return false;
			}
		});
		return res;
	};

    //Check if a form exists:
	this.formExists = function(id) {
		var res = false;
		jQuery.each(_this.forms, function() {
			if (this.id == id) {
				res = true;
				return false;
			}
		});
		return res;
	};


    // Register a form element for validation purposes - MUST be done via the formhandler object
    this.setValidation = function(params) {
	    var obj = document.getElementById(params.id);
	    if (obj) {
	        params.obj = obj;
	        
		    switch(params.type) {
		    
			    case "radiogroup":
			    case "checkboxgroup":
				    var arrInput = obj.getElementsByTagName("INPUT");
				    var objForm = null;
				    if (arrInput.length > 0) {
					    objForm = _this.addForm(arrInput[0].form);
					    objForm.addElement(params);
				    }
				    break;
			    
			    default:
			        var objForm = _this.addForm(obj.form);
				    objForm.addElement(params);
				    break;
		    }
	    }
    };
    
    this.setSubmit = function(obj) {
	    if (obj != null) {
		    var objForm = obj.form;
		    if (objForm != null) {
			    objForm = _this.getForm(objForm.name);
			    if (objForm) {
				    objForm.submitObj = obj;
			    }
		    }
	    }
    };
}

// Initialize the IDFormHandler object
var IDFormHandler = new INET.formHandler();