// ********************************************************************
//
// WolfClass for validate and send forms to Ajax
//
// ********************************************************************
function wolfClass( )
{
	//
	var onComplete;
	var saveErrorText;
	var connErrorText;
	var validErrorText;
	var htmlElement;
	var ajaxPHP = "";
	var ajaxSTR = "";
	var filler;
	var defaultParam = "";
	var resultPHP;
	var errorFunc;
	var aim_name = "";
	var aim_iframe = false;
	var aim_obj= false;
	//
	var debug = false;
	//
	var inputFields = new Array( );
	var radios = new Array( );
	//
	//
	this.setErrorFunc = function( func ) { errorFunc = func; }
	
	var xhc = new XHConn( );
	if ( !xhc ) { errorFunc( connErrorText ); return false; }
	//
	this.init = function ( )
	{
		var n = 'f' + Math.floor(Math.random() * 99999);
		aim_name = n;
		aim_iframe = document.createElement('DIV');
		//
		aim_iframe.innerHTML = '<iframe style="'+ ( debug ? '' : 'display:none' ) +'" src="about:blank" id="'+n+'" name="'+n+'" width="600px" height="500px" onload="validatorOBJ.formLoaded(\''+n+'\')"></iframe>';
		document.body.appendChild( aim_iframe );
		aim_obj = document.getElementById(n);
	}
	//
	//
	this.collect = function ( )
	{
		//
		inputFields = new Array( );
		radios = new Array( );	
		//
		if ( !htmlElement ) { return false; }
		ARR = htmlElement.getElementsByTagName( 'INPUT' );
		for (var i = 0; i < ARR.length; i++)
		{
			if ( ARR[ i ].type == "radio" )
			{
				if ( !radios[ ARR[ i ].name ] ) radios[ ARR[ i ].name ] = new Array( );
				radios[ ARR[ i ].name ].push( ARR[ i ] );
			}
			else
			{
				inputFields.push( ARR[i] );
			}
		}
		//
		ARR = htmlElement.getElementsByTagName( 'SELECT' );
		for (var i = 0; i < ARR.length; i++) inputFields.push( ARR[i] );
		//
		ARR = htmlElement.getElementsByTagName( 'TEXTAREA' );
		for (var i = 0; i < ARR.length; i++) inputFields.push( ARR[i] );
		//
		//
		return true;
		//
	}
	//
	//
	//
	this.validate = function ( )
	{
		//
		//
		if ( !inputFields.length ) { return false; }
		var reg = new RegExp( "required", "gi" );
		var error = false;
		//

		for ( var i = 0; i < inputFields.length; i++ )
		{
			//
			var req = inputFields[ i ].className ? inputFields[ i ].className.match( reg ) : false;
			if ( req )
			{
				//
				if ( ( inputFields[ i ].type == "text" || inputFields[ i ].type == "textarea" ) && inputFields[ i ].value == "" ) error = inputFields[ i ];
				if ( inputFields[ i ].type == "select-one" && inputFields[ i ].options.selectedIndex == 0 ) error = inputFields[ i ];
				if ( inputFields[ i ].type == "checkbox" && !inputFields[ i ].	checked ) error = inputFields[ i ];
				if ( inputFields[ i ].type == "file" && inputFields[ i ].value == "" ) error = inputFields[ i ];
				//
				if ( error )
				{
					errorFunc( validErrorText );//+" name:"+inputFields[ i ].name  );
					return false;
				}				
				//
				error =false;
			}
		}
		//
		for ( var i in radios )
		{
			//
			var found = true;
			for ( var j in radios[ i ] )
			{
				//
				var req = radios[i][j].className ? radios[i][j].className.match( reg ) : false;
				if ( req )
					if ( radios[i][j].checked == true ) { found = true; break; } else found=false;
				//
			}
			if ( !found )
			{
				errorFunc( validErrorText );//+" radio "+radios[i][j] );
				return false;
			}
		}
		//
		return true;
		//
	}
	//
	//
	this.nl2br = function ( str )
	{
		if ( str )
		{
			str = str_replace(/\n/gi, '<br />', str);
			str = str_replace(/\r/gi, '', str);
		}
		return ( str );
	}
	
	this.br2nl = function ( str )
	{
		if ( str )
		{
			str = str_replace(/<br \/>/g, '\n', str);
			str = str_replace(/<br>/g, '\n', str);
		}
		return ( str );
	} 
	//
	this.createSTR = function ( )
	{
		//
		var str = "";
		var value = 0;
		for ( var i = 0; i < inputFields.length; i++ )
		{
			//
			if ( inputFields[ i ].type == "text" || inputFields[ i ].type == "textarea" ) value = this.nl2br( inputFields[ i ].value );
			if ( inputFields[ i ].type == "select-one" ) value = inputFields[ i ].options.length == 0 ? 0 : inputFields[ i ].options[ inputFields[ i ].options.selectedIndex ].value;
			if ( inputFields[ i ].type == "checkbox" )
			{
				if ( inputFields[ i ].value && !inputFields[ i ].checked ) continue;
				value = inputFields[ i ].value ? inputFields[ i ].value : inputFields[ i ].checked;
			}
			if ( inputFields[ i ].type == "hidden" ) value = inputFields[ i ].value;
			//
			if ( bd.browser=="Explorer" )
			{	
				value = str_replace(/\r/gi, '', value);
				value = encodeURI( value );
			}
			str+= inputFields[ i ].name + "=" + value + "&";
			//
		}
		for ( var i in radios )
			for ( var j in radios[ i ] )
				if ( radios[ i ][ j ].checked == true )
				{
					value = radios[ i ][ j ].value;
					if ( bd.browser=="Explorer" )
					{	
						value = str_replace(/\r/gi, '', value);
						value = encodeURI( value );
					}
					str+= radios[ i ][ j ].name + "=" + value + "&";
					break;
				}
		//
		str=str.substr(0, str.length - 1 );
		str+= defaultParam;
		ajaxSTR = str;
	}
	//
	this.parseResult = function ( OXML )
	{
	}
	//
	this.validateElement = function ( myHtmlElement )
	{
		htmlElement = myHtmlElement;
		if ( !this.collect( ) ) return false;
		return this.validate( );
	}
	//
	this.save = function ( myHtmlElement, myOnComplete, param, post  )
	{
		var method = post ? 'POST' : 'GET';
		//
		onComplete = myOnComplete;
		htmlElement = myHtmlElement;
		//
		if ( !this.collect( ) ) return false;
		if ( this.validate( ) )
		{
			//
			this.createSTR( );
			//
			if ( !xhc.connect( ajaxPHP, method, ajaxSTR, this.func_complete, param ) )
				{ /*console.log ( 'Method: ' + method + '; ajaxPHP:' + ajaxPHP  ); */ errorFunc( connErrorText ); return false; }
			//
		}
	}
	//
	this.custom = function ( obj, myOnComplete, param )
	{
		//
		onComplete = myOnComplete;
		//
		var str = "";
		for ( var i in obj )
		{
			str+= i + "=" + obj[ i ] + "&";
		}
		str = str.substr(0, str.length - 1 );
		str+= defaultParam;
		if ( !xhc.connect( ajaxPHP, "GET", str, this.func_complete, param ) )
			{ errorFunc( connErrorText ); return false; }
		//
	}
	//
	//
	this.formSubmit = function ( form, params )
	{
		//
		aim_params = params;
		var ok = true;
		//
        form.setAttribute( 'target', aim_name );
		//
        if ( params && typeof(params.onComplete) == 'function')
            	onComplete = params.onComplete;
        if ( params && typeof(params.onStart) == 'function' )
				ok = params.onStart( form );
		//
		if ( ok )	form.submit( );
		//
	}
	
	this.formLoaded = function ( obj )
	{
        if (aim_obj.contentDocument) {
            var d = aim_obj.contentDocument;
        } else if (aim_obj.contentWindow) {
            var d = aim_obj.contentWindow.document;
        } else {
            var d = window.frames[aim_name].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }
		//
		var oncomplete = onComplete;
		onComplete = false;
		//
		this.func_complete( d );
		onComplete = oncomplete;
		//
		if (typeof(onComplete) == 'function')
            onComplete( resultPHP, aim_params );		
	}
	//
	//
	//
	var globalvalami;
	this.getvalami = function() { return globalvalami; }
	//
	//
	this.func_complete2 = function ( OXML, param )
	{
//		console.log('func_comp');
		var obj = false;
		try
		{
			if ( OXML.responseXML )
			{
				obj = OXML.responseXML;
			}
			else
			{
				obj = OXML;
			}
		}
		catch( z )
		{
			obj = OXML;
		}
		res = obj.childNodes;
		try
		{
			if ( res[ 0 ].tagName != "phpMessage" )
				res = OXML.XMLDocument.childNodes;
		}
		catch( z )
		{
			return;
		}

		var found = "";
		var error = false;
		resultPHP = { };
		//
		resultPHP['v']=res;
		if ( res[0].tagName != "phpMessage" ) error = true;
		res = res[0].childNodes;
		for ( var i=0;i<res.length;i++ )
		{
			var t = res[ i ].tagName;
			if ( !t ) continue;
			var v;
			try { v = res[ i ].firstChild.nodeValue; } catch( z ) { v = ""; }
			if ( t == "result" && v == "ok" ) found = "ok";
			if ( t == "error" ) found = "error";
			if ( t == "array" )
			{
				resultPHP[ res[ i ].attributes[ 0 ].nodeValue ] = new Array( );
				for ( var j = 0; j < res[ i ].childNodes.length; j++ )
//				for ( var j in res[ i ].childNodes )
				{
					if ( !res[ i ].childNodes[ j ].tagName ) continue;
					var v2;
					try { v2 = res[ i ].childNodes[ j ].firstChild.nodeValue; } catch( z ) { v2 = ""; }
					resultPHP[ res[ i ].attributes[ 0 ].nodeValue ][ res[ i ].childNodes[ j ].tagName ] = v2;
				}
				continue;
			}
			resultPHP[ t ] = v;
		}
		//
	}
	
	this.func_complete = function ( OXML, param )
	{
		//
//		console.log('func_comp');
		var obj = false;
		try
		{
			if ( OXML.responseXML )
			{
				obj = OXML.responseXML;
			}
			else
			{
				obj = OXML;
			}
		}
		catch( z )
		{
			obj = OXML;
		}
		res = obj.childNodes;

		if ( debug ) { console.log( 'response: ', obj.responseText, ' ',obj.responseXML, ' ', obj, ' ',OXML ); }


		try
		{
			if ( res[ 0 ].tagName != "phpMessage" )
				res = OXML.XMLDocument.childNodes;
		}
		catch( z )
		{
			return;
		}

		var found = "";
		var error = false;
		resultPHP = { };
		//
		resultPHP['v']=res;
		if ( res[0].tagName != "phpMessage" ) error = true;
		res = res[0].childNodes;
		for ( var i=0;i<res.length;i++ )
		{
			var t = res[ i ].tagName;
			if ( !t ) continue;
			var v;
			try { v = res[ i ].firstChild.nodeValue; } catch( z ) { v = ""; }
			if ( t == "result" && v == "ok" ) found = "ok";
			if ( t == "error" ) found = "error";
			if ( t == "array" )
			{
				resultPHP[ res[ i ].attributes[ 0 ].nodeValue ] = new Array( );
				for ( var j = 0; j < res[ i ].childNodes.length; j++ )
//				for ( var j in res[ i ].childNodes )
				{
					if ( !res[ i ].childNodes[ j ].tagName ) continue;
					var v2;
					try { v2 = res[ i ].childNodes[ j ].firstChild.nodeValue; } catch( z ) { v2 = ""; }
					resultPHP[ res[ i ].attributes[ 0 ].nodeValue ][ res[ i ].childNodes[ j ].tagName ] = v2;
				}
				continue;
			}
			resultPHP[ t ] = v;
		}
		//
//		console.log('onc:',onComplete);
		if ( found == "ok" && typeof(onComplete) == "function" ) onComplete( param );
		if ( found == "error" ) errorFunc( resultPHP[ 'error' ] );
		//
		if ( found == "" ) errorFunc( connErrorText );
		//
	}
	
	this.getResult = function ( )
	{
			//
			return resultPHP;
			//
	}
	//
	this.setAJAX = function ( myAJAX ) { ajaxPHP = myAJAX; }
	this.setFiller = function ( myFiller ) { filler = myFiller; }
	this.setTexts = function ( saveError, connError, validError	)
	{
		saveErrorText = saveError;
		connErrorText = connError;
		validErrorText = validError;
	}						 
	this.setDefaultParam = function ( myText ) { defaultParam = myText; }
	//
	//
	//
}
// ********************************************************************
//
// check empty input fields
//
//
// ********************************************************************
function checkFields ( )
{
	//
	this._getElementsByClassName = function ( className, obj )
	{
		var childs = new Array ();
		if ( !obj ) return;
		if ( obj.childNodes )
		{
			for ( var i = 0; i < obj.childNodes.length; i++ )
			{
				if ( obj.childNodes[i].className )
				{
					for ( var j=0; j < obj.childNodes[i].className.split (' ').length; j++ )
					{
						if ( obj.childNodes[i].className.split (' ')[j] == className )
						{
							childs[childs.length] = obj.childNodes[i];
							break;
						}
					}
				}
				if ( obj.childNodes[i].childNodes.length > 0 )
				{
					childChilds = this._getElementsByClassName ( className, obj.childNodes[i] );
					if ( childChilds.length > 0 )
					{
						for ( var j = 0; j < childChilds.length; j++ )
						{
							childs[childs.length] = childChilds[j];
						}
					}
				}
			}
		}
		return ( childs );
	}
	//
	this.checkText = function( obj )
	{
		//
		obj.span.className =  obj.value == "" ? "red" : "";
		//
	}
	//
	this.checkSelect = function( obj )
	{
		//
		obj.span.className = obj.selectedIndex == 0 ? "red" : "";
		//
	}
	//
	this.checkRadio = function( obj )
	{
		obj.span.className = !obj.checked ? "red" : "";
	}
	//
	this.setEvent = function( obj, span )
	{
			obj.checkField = this;
			obj.span = span;
			if ( obj.type == "text" || obj.type == "textarea" || obj.type == "file" )
			{
				//
				obj.onkeyup = function ( ) { this.checkField.checkText( this ); }
				obj.onkeydown = function ( ) { this.checkField.checkText( this ); }
				this.checkText( obj );
				//
			}
			if ( obj.type == "file" )
			{
				//
				obj.onchange = function ( ) { this.checkField.checkText( this ); }
				this.checkText( obj );
				//
			}
			if ( obj.type == "select-one" )
			{
				obj.onchange = function ( ) { this.checkField.checkSelect( this ); }
				this.checkSelect( obj );
				//
			}
			if ( obj.type == "radio" )
			{
				//
				obj.onchange = function ( ) { this.checkField.checkRadio( this ); }
				this.checkRadio( obj );
				//
			}
	}
	
	this.setEvents = function( viewManager )
	{
		//
		var inputs = viewManager.getInputs( );
		for ( var i in inputs )
		{
			var obj = inputs[ i ];
			if( !obj.className ) continue;
			var cn = obj.className.split( ' ' );
			//
			var namestr = obj.name;
			if ( obj.name.substr( obj.name.length - 2, 2 ) == "[]" ) namestr = obj.name.substr( 0, obj.name.length-2 );
			//
			for ( var j = 0; j < cn.length; j++ )
				if ( cn[ j ] == "required" )
				{
					obj.checkField = this;
					obj.wrapper = viewManager.wrapper;
					obj.span = viewManager._getElementsByClassName( namestr + "_rq", obj.wrapper )[ 0 ];
					if ( obj.type == "text" || obj.type == "textarea" || obj.type == "file" )
					{
						//
						obj.onkeyup = function ( ) { this.checkField.checkText( this ); }
						obj.onkeydown = function ( ) { this.checkField.checkText( this ); }
						this.checkText( obj );
						//
					}
					if ( obj.type == "file" )
					{
						//
						obj.onchange = function ( ) { this.checkField.checkText( this ); }
						this.checkText( obj );
						//
					}					
					if ( obj.type == "select-one" )
					{
						//
						obj.onchange = function ( ) { this.checkField.checkSelect( this ); }
						this.checkSelect( obj );
						//
					}
					if ( obj.type == "radio" )
					{
						//
						obj.onchange = function ( ) { this.checkField.checkRadio( this ); }
						this.checkRadio( obj );
						//
					}
					break;
				}
		}
		//
	}
	//
}
//
//
//
var checkFieldsOBJ = new checkFields( );
var validatorOBJ = new wolfClass( );
//
//
//