var Core = {};

window.addEvent( 'domready', function() {
	
	var element = $( document ).getElement( '#header .login .form' );
	
	if( !element ) return;
	
	var slide = new Fx.Slide( element, {
		transition: 'expo:out',
		duration: 500,
		onStart: function() {
			$('login_email').focus();
		}
	} ).hide();
	
	$( document ).getElement( '#header .login .button a' ).addEvent( 'click', function( e ) {
		e.stop();
		slide.toggle();
	} );

} );

Core.Navigation = {
	
	setup: function() {
		
		var ul, width;
		
		this.timer = 0;
		
		$$( '#navigation .menu li' ).each( function( li ) {
													
			li.addEvents( {
				'mouseenter': this.show.bind( this, li ),
				'mouseleave': this.hide.bind( this, li )
			} );
			
			/*
			if( ul = li.getElement( 'ul' ) ) {
				ul.setStyle( 'left', li.getPosition( $E( '#navigation .menu' ) ).x - 3 );
			}
			*/
			
		}, this );
	
	},
	
	show: function( li ) {
		this.hideAll( li );
		
		if( li.getElement( 'ul' ) ) {
			li.getElement( 'ul' ).setStyle( 'display', 'block' );
			$( document ).addEvent( 'click', this.closeEvent.bind( this, li ) );
		}
	},
	
	hide: function( li ) {
		if( !li.getElement( 'ul' ) ) return;
		
		this.timer = function() {
			li.getElement( 'ul' ).setStyle( 'display', 'none' );
		}.delay( 1000, this );
	},
	
	hideAll: function( li ) {
		$clear( this.timer );
		$( document ).removeEvent( 'click', this.closeEvent );
		
		li.getSiblings().each( function( l ) {
			if( l.getElement( 'ul' ) ) l.getElement( 'ul' ).setStyle( 'display', 'none' );
		} );
	},
	
	closeEvent: function( li ) {
		this.hideAll( li );
	}

};

window.addEvent( 'domready', Core.Navigation.setup.bind( Core.Navigation ) );

Core.Request = new Class( {
							
	Extends: Request.JSON,
	
	initialize: function( options ) {
		
		this.parent( options );
		
		this.options.url = Meta.get( 'url_root' ) + '/remote/' + this.options.url;
		
	},
	
	success: function( text ) {
		
		this.response.json = JSON.decode( text, this.options.secure );
		
		var result = this.response.json;
		
		var error_msg = '';
		var error_num = 0; // 0=OK, 1=Bad Request, 2=User Defined
	
		switch( true ) {
			case ( result == null ):
				error_num = 1;
				error_msg = 'Request Failed';
				break;
			case ( result.error_number != 0 ):
				error_num = 2;
				error_msg = result.error_message;
				break;
			default:
				error_num = 0;
				error_msg = '';
		}
	
		if ( error_num == 0 ) {
			
			this.onSuccess( result, text );
			
		} else {
		
			this.onFailure( error_num, error_msg, result, text );
		
			if ( error_num == 1 ) $C( text );	
		
		}
		
	},
	
	onFailure: function(){
		
		this.fireEvent( 'onComplete', arguments ).fireEvent( 'onFailure', arguments );
		
	}
	
} );

