var Validator = (function(){

return {
    msg: []

	,valCheck	: function(cbName) {
			var cb = $('hyperform').getInputs('checkbox', cbName);
			for (var j=0; j < cb.length; j++)
				if (cb[j].checked)
					return true;
            return false;
	}

	,valRadio	: function(rdName) {
			var rd = $('hyperform').getInputs('radio', rdName);
			for (var j=0; j < rd.length; j++)
				if (rd[j].checked)
					return true;
		    return false;
	}

    ,submitForm: function(){

		this.validate = true;
		var els = $('hyperform').getElements();
		$('_msg').innerHTML = '';

		// Specific validation for checkbox and radios.
		var cbNames = [];
		var rdNames = [];
        var tiNames = [];

		els.each( function(el) {

			var req = el.getAttribute('required') || 'false';

            if (el.className == 'time_s'){
                el.value = '';
                var params	= $('hyperform').serialize(true);
                for (var i in params) {
                    if (el.name + '_s' == i && (params[i].constructor == Array && params[i].length == 3)) {
                        if (params[i][2] == 'am' || params[i][2] == 'pm' || params[i][2] == '--'){
                            if (params[i][0] == '--' && params[i][1] == '--' && params[i][2] == '--')
                                el.value = '';
                            else
                                el.value = [params[i][0], ":", params[i][1], " ", params[i][2]].join('');
                        }
                    }
                }
            }
            else if (el.type == 'checkbox') {
                var names = el.name.split('_');
                if (names.length == 2 && names[1] == 'cb'){
                    var hs = $('hyperform').getInputs('hidden', names[0]);
                    for (var j=0; j < hs.length; j++){
                        if (el.checked)
                            hs[j].value = 'on';
                        else
                            hs[j].value = 'off';
                    }
                }
            }

            if( req == 'true'){

                if (el.value == ''){
                    this.msg.push('Please fill all required fields.');
                    this.validate = false;
                }
                else if (el.type == 'checkbox') {
                    if (cbNames.indexOf(el.name) == '-1') {
                        cbNames.push(el.name);
                        if (!this.valCheck(cbNames[cbNames.length-1])){
                            this.msg.push('Please check one of required checkboxes.');
                            this.validate = false;
                        }
                    }
                }
                else if ( el.type == 'radio') {
                    if (rdNames.indexOf(el.name) == '-1') {
                        rdNames.push(el.name);
                        if (!this.valRadio(rdNames[rdNames.length-1])){
                            this.msg.push('Please select one of required radio buttons.');
                            this.validate = false;
                        }
                    }
                }
            }

            if (el.className != '' && el.value != '') {
                var cls = el.className;
                var arr = cls.match(/(\w+)/);
                switch(arr[0]) {
                    case 'date':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                        var ret = el.value.match( /^(0?\d|10|11|12)\/(0?[1-9]|[1-2][0-9]|30|31)\/(\d\d\d\d)$/ );
                        if ( !(ret && ret.length != 0) ) {
                            this.msg.push('You have attempted to enter invalid date into the field '+ label +'. The valid format is mm/dd/yyyy');
                            this.validate = false;
                        };
                        break;

                    case 'time_s':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                        //var time = /^(10|11|12|[1-9]):([0-5]?[0-9])\s(am|pm)$/;
                        var time = /^([0-1]?[0-9]):([0-5]?[0-9])\s(am|pm)$/;                            
                        if (time.test(el.value) == false) {
                            this.msg.push('You have attempted to enter invalid time into the field '+ label +'.');
                            this.validate = false;
                        }
                        break;

                    case 'email':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                        var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
                        if ( email.test(el.value) == false ) {
                            this.msg.push('You have attempted to enter invalid email into the field '+ label +'.');
                            this.validate = false;
                        };
                        break;

                    case 'url':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                        var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
                        if ( url.test(el.value) == false ) {
                            this.msg.push('You have attempted to enter invalid url into the field '+ label +'.');
                            this.validate = false;
                        };
                        break;

                    case 'percent':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                         
                        if(!/^ *[0-9]+ *$/.test(el.value) || parseInt(el.value) > 100 || parseInt(el.value) < 0){
                            this.msg.push('You have attempted to enter invalid percent into the field '+ label +'.The allowed integer number is between 0 and 100.');
                            this.validate = false;
                        }
                        break;

                    case 'number':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                        var number = /^[-]?\d{1,10}$/;
                        if (number.test(el.value) == false) {
                            this.msg.push('You have attempted to enter invalid number into the field '+ label +'.');
                            this.validate = false;
                            break;
                        }
                        if (Math.abs(parseInt(el.value)) > 2147483647) {
                            this.msg.push('You have attempted to enter invalid number into the field '+ label +'. The maximum allowed number is 2147483647.');
                            this.validate = false;
                            break;
                        }
                        if (Math.abs(parseInt(el.value)) < -2147483647) {
                            this.msg.push('You have attempted to enter invalid number into the field '+ label +'. The minimum allowed number is -2147483647.');
                            this.validate = false;
                            break;
                        }
                        break;

                    case 'currency':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;    
                            }
                        }
                        if(!/^[-]?\d{1,15}(\.\d{1,2})?$/.test(el.value)){
                            this.msg.push('You have attempted to enter invalid currency into the field '+ label +'.');
                            this.validate = false;
                            break;
                        }
                        var integral = el.value.split(".")[0];
                        var decimal = el.value.split(".")[1];
                        if(integral){
                            if(parseInt(integral) > 922337203685477){
                                this.msg.push('You have attempted to enter invalid currency into the field '+ label +'. The maximum allowed number is 922337203685477.');
                                this.validate = false;
                                break;
                            }
                            if(parseInt(integral) < -922337203685477){
                                this.msg.push('You have attempted to enter invalid currency into the field '+ label +'. The minimum allowed number is -922337203685477.');
                                this.validate = false;
                                break;    
                            }
                        }
                        if(decimal){
                            if(parseInt(decimal) > 99){
                                this.msg.push('You have attempted to enter invalid currency into the field '+ label +'. The maximum allowed float part should be two digit.');
                                this.validate = false;
                                break;
                            }
                        }
                        break;

                    case 'decimal':
                        var labels = document.getElementsByTagName('label');
                        var label = null;
                        for(var i=0,len=labels.length; i<len; i++){
                            if(labels[i].getAttribute('for') == el.id){
                                label = labels[i].innerHTML;
                            }
                        }
                        if(!/^[-]?[0-9]+(\.[0-9]+)?$/.test(el.value)){
                            this.msg.push('You have attempted to enter invalid decimal into the field '+ label +'.');
                            this.validate = false;
                            break;
                        }
                        var integral = el.value.split(".")[0];
                        var decimal = el.value.split(".")[1];
                        if(integral){
                            if(parseInt(integral) > 999999999999999999){
                                this.msg.push('You have attempted to enter invalid decimal into the field '+ label +'. The maximum allowed number is 999999999999999999');
                                this.validate = false;
                                break;
                            }
                            if(parseInt(integral) < -999999999999999999){
                                this.msg.push('You have attempted to enter invalid decimal into the field '+ label +'. The maximum allowed number is -999999999999999999');
                                this.validate = false;
                                break;
                            }
                        }
                        if(decimal){
                            if(parseInt(decimal) > 9999999999){
                                this.msg.push('You have attempted to enter invalid decimal into the field '+ label +'. The maximum allowed float part is 9999999999');
                                this.validate = false;
                                break;
                            }
                        }
                        break;

                    default:
                        break;
                }
            }

            this.showMsg();

		}, this);

		// Reset the message holder array.
		this.msg = [];

		if (this.validate) {
			$('hyperform').submit();
		}
	}

    ,showMsg	: function() {
        if (this.msg.length != '0') {
            var tpl = '<ul>';
            $('_msg').innerHTML = '';

            for (var i=0; i < this.msg.length; i++) {
                tpl += ['<li>', this.msg[i], '</li>'].join('');
            }

            tpl += '</ul>';

            $('_msg').insert(tpl);
            $('_msg').style.display = 'block';
            return false;
        }

        return true;
    }


}
})();

var teaxareaMaxLength = function(object, maxLen){
    var maxLen = maxLen == "" ? null : maxLen;
    if(maxLen){
        return (object.value.length <= maxLen);
    }
}