Element.extend({
	getSimpleValue: function(){
		switch (this.getTag()){
			case 'select':
				if (this.selectedIndex != -1){
					var opt = this.options[this.selectedIndex];
					return opt.value;
				}
				break;
			case 'input': if (!(this.checked && ['checkbox', 'radio'].test(this.type)) && !['hidden', 'text', 'password'].test(this.type)) break;
			case 'textarea': return this.value;
		}
		return false;
	}
} );

String.prototype.parseURLQuery = String.prototype.parseURLQuery || function () {
	var opt = new Object();
	if( this != '' && this != null && this != undefined && this != 'undefined' )
	{
		var strObj = new String( this ).trim().replace( "\&amp;", "\&" ).split( "&" );
		for( var i=0; i<strObj.length; i++ )
		{
			var tmp = strObj[i].split( "=" );
			opt[tmp[0]] = tmp[1];
		}
	}
	
	opt.getOpt = function ( name ) {
		for( t_name in this )
		{
			if( t_name == name )
				return this[name];
		}
		return false;
	}
	
	return opt;
};

var MyTips = Tips.extend({
	build: function(el){
		el.myTitle = el.href ? el.href.replace('http://', '') : (el.rel || false);
		if (el.MyTip){
			var dual = unescape(el.MyTip).split('::');
			if (dual.length > 1) {
				el.myTitle = dual[0].trim();
				el.myText = dual[1].trim();
			} else
				el.myText = el.MyTip;
		} else {
			el.myText = false;
		}
		if (el.myTitle && el.myTitle.length > this.options.maxTitleChars) el.myTitle = el.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
		el.addEvent('mouseover', function(event){
			this.start(el);
			this.locate(event);
		}.bindWithEvent(this));
		el.addEvent('focus', function(event){
			this.start(el);
			this.locate(event);
		}.bindWithEvent(this));
		if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
		el.addEvent('mouseout', this.end.bindWithEvent(this));
		el.addEvent('blur', this.end.bindWithEvent(this));
	},
	
	locate: function(event){
		if( event.type == 'focus' )
		{
			var dims = event.target.getCoordinates();
			var tPos = { 'x': dims.left, 'y': dims.top };
			var tSize = { 'x': dims.width, 'y': dims.height };
		}
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		for (var z in prop){
			if( event.type == 'focus' )
				var t = tPos[z] + tSize[z];
			else
				var t = event.page[z];	
			var pos = t + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > win[z]) pos = t - this.options.offsets[z] - tip[z];
			this.toolTip.setStyle(prop[z], pos + 'px');
		};
		event.stop();
	}
});

var autoFormCheck = new Class({
	initialize: function () {
		this.forms = new Array();
		$ES('form').each( function ( obj ) {
			opts = String( obj.getProperty('title')).parseURLQuery();
			if( opts.getOpt( 'formCheck' ) == 'on' )
				this.forms.push( new formCheck( obj ) );
		}, this );
	}
});

var formCheck = new Class({
	initialize: function ( fObj ) {
		this.formObject = $(fObj);
		this.reportDiv = null;
		this.overlay = null;
		
		this.tipsObjs = new Array();
		this.fields = new Array();
		this.errors = new Array();
		
		this.formObject.cleanUp = true;
		
		$A( this.formObject.elements ).each( function ( obj ) {
			var opts = String( $(obj).getProperty( 'title' ) ).trim();
			if( opts != '' ) {
				opts = opts.parseURLQuery();
				//$(obj).removeAttribute( 'title' );
				this.fields.push( { field: obj, options: opts } );
				if( opts.getOpt( 'tip' ) != false )
				{
					$(obj).MyTip = opts.getOpt( 'tip' );
					this.tipsObjs.push( $(obj) );
				}
			}
		}, this );
		this.tips = new MyTips( this.tipsObjs, {
			maxTitleChars: 50
		});
		this.formObject.onsubmit = this.checkSubmit.bindAsEventListener( this );
		
		if( $chk( window.__auto_object_loader ) )
			window.__auto_object_loader.next();
	},
	
	checkSubmit: function () {
		this.fields.each( function ( obj ) {
			var str = String( obj.field.getSimpleValue() ).trim();
			
			switch( obj.field.type ) {
				case 'checkbox':
					if( obj.options.getOpt( 'fc_req' ) && !obj.field.checked )
						this.errors.push( "Field '" + unescape(obj.options.getOpt( 'fc_label' )) + "' is required" );
					break;
				default:
					if( obj.options.getOpt( 'fc_req' ) && str == '' )
						this.errors.push( "Field '" + unescape(obj.options.getOpt( 'fc_label' )) + "' is required" );
					break;
			}
			
			var type = obj.options.getOpt( 'fc_type' );
			if( str != '' && type )
			{
				if( typeof this['check' + String( type ).capitalize()] == 'function' )
				{
					if( !this['check' + String( type ).capitalize()]( obj.field ) )
						this.errors.push( "Field '" + unescape( obj.options.getOpt( 'fc_label' ) ) + "' is in wrong format" );
				}
			}
		}, this );
		
		if( this.errors.length > 0 )
		{
			this.reportError( this.errors.join( "<br />" ) );
			this.errors = new Array();
		}
		else
		{
			this.formObject.send( {
				onRequest: this.disableForm.bind( this ),
				//onSuccess: this.reportSuccess.bind( this ),
				onSuccess: this.reportResult.bind( this ),
				onFailure: this.reportError.bind( this )
			} );
		}
		
		return false;
	},
	
	checkInteger: function ( obj ) {
		return this.checkField( obj, /^[0-9]*$/ );
	},
	
	checkFloat: function ( obj ) {
		return this.checkField( obj, /^[0-9]*[\.]{0,1}[0-9]*$/ );
	},
	
	checkEmail: function ( obj ) {
		return this.checkField( obj, /^[\w\d]+@[\w\d]{1,1}[\w\d\.]*\.[\w]{2,4}$/ );
	},
	
	checkPostcode: function ( obj ) {
		return this.checkField( obj, /^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))[0-9][ABD-HJLNP-UW-Z]{2})$/ );
	},
	
	checkField: function ( obj, pattern ) {
		var str = String( obj.getValue() );
		if( !str.test( pattern ) && str.trim() != '' )
			return false;
		else
			return true;
	},
	
	showTip: function ( event ) {
		var event = new Event(event);
		var obj = $(event.target);
		//$('debug').innerHTML += event.type + "<br />";
		if( obj.mouseoverEvent != true && obj.focusEvent != true )
		{
			//do tip show
		}
		obj[event.type+'Event'] = true;
	},
	
	reportError: function ( txt ) {
		this.reportType = 'error';
		this.reportTxt = txt;
		this.report();
	},
	
	reportSuccess: function ( txt ) {
		this.reportType = 'success';
		this.reportTxt = txt;
		this.report();
	},
	
	reportResult: function ( res ) {
		res = Json.evaluate( res );
		switch( res.type )
		{
			case 'success':
				this.reportSuccess( res.message );
				break;
			case 'error':
				this.reportError( res.message );
				break;
		}
	},
	
	report: function () {
		this.disableForm();
		var dims = this.formObject.getCoordinates();
		var sTop = window.getScrollTop();
		var boxWidth = Math.min( dims.width - 40, 300 );
		this.reportObjs = new Object();
		this.reportObjs.frame = new Element( 'div' ).addClass( 'formAlertFrame' ).addClass( 'messageType'+String( this.reportType ).capitalize() ).injectInside( document.body ).setStyles( {
			width: boxWidth + 'px',
			position: 'absolute',
			top: sTop + 20 + 'px',
			left: ( dims.left + ( dims.width - boxWidth ) / 2 ) + 'px'
		} );
		this.reportObjs.content = new Element( 'div' ).addClass( 'formAlertContent' ).injectInside( this.reportObjs.frame );
		this.reportObjs.title = new Element( 'h1' ).setHTML( String( this.reportType ).capitalize() ).injectInside( this.reportObjs.content );
		this.reportObjs.text = new Element( 'span' ).setHTML( this.reportTxt ).injectInside( this.reportObjs.content );
		this.reportObjs.button = new Element( 'a' ).setProperty( 'href', '#' ).setHTML( 'Ok' ).injectInside( this.reportObjs.content );
		this.reportObjs.button.onclick = this.reportClose.bindAsEventListener( this );
		this.reportObjs.button.focus();
	},
	
	reportClose: function () {
		this.reportObjs.button.remove();
		this.reportObjs.text.remove();
		this.reportObjs.title.remove();
		this.reportObjs.content.remove();
		this.reportObjs.frame.remove();
		this.reportObjs = null;
		this.enableForm();
		return false;
	},
	
	disableForm: function () {
		if( this.overlay == null )
			this.overlay = new Element( 'div' ).addClass( 'formOverlay' ).setOpacity( 0 ).injectInside( document.body );
		var dims = window.getSize();
		this.overlay.setStyles( {
			width: Math.max( dims.size.x, dims.scrollSize.x ) + 'px',
			height: Math.max( dims.size.y, dims.scrollSize.y ) + 'px',
			top: '0px',
			left: '0px',
			position: 'absolute'
		} ).setOpacity( 0.5 );
		for( var e=0; e<this.formObject.elements.length; e++ )
			this.formObject.elements[e].disabled = true;
	},
	
	enableForm: function () {
		if( this.overlay != null )
			this.overlay.setOpacity( 0 );
		for( var e=0; e<this.formObject.elements.length; e++ )
			this.formObject.elements[e].disabled = false;
	}
});

if( !$chk(window.__auto_object_loader) )
	window.__auto_object_loader = new AutoLoader();

window.__auto_object_loader.add( function() {
		var __auto__formCheck = new autoFormCheck();
} );

