(function($) {
    $.fn.checkScreenName = function( options ){
        var oldValue, timeOutID;
        var semaforSend = false;
        var input = this;

        var settings = {
            statusbar:  null,   // mandotory
            url:        'register.html',
            image:      '/com/img/anirollersmall.gif',
            delay:      1,  // sec
            timeout:    null,  // sec
            colorFine:  'green',
            colorFail:  'red'
        };

        $.extend( settings, options || {} );

        settings.delay = parseFloat( settings.delay ) * 1000;
        settings.timeout = parseFloat( settings.timeout ) * 1000;

        if ( settings.statusbar == null || $( '#'+ settings.statusbar ).size() == 0 ) {
            return this;
        }

        var statBar = $( '#'+ settings.statusbar );

    	$( this )
            .filter(':text')
            .attr('autocomplete','off')
            .bind('keyup.screenname change.screenname',_onChange);

        return this;

        /* internal functions */
        function _onChange(e) {
            var newValue = $( input ).val();

            if ( oldValue == newValue ) {
                if ( e.type == 'change' && timeOutID ) {
                    clearTimeout( timeOutID );

                    _checkData( newValue );
                }
            }
            else {
                oldValue = newValue;

                $( input ).css('color','');
                $( statBar ).hide().css('color','').empty();

                timeOutID && clearTimeout( timeOutID );

                if ( e.type == 'change' ) {
                    _checkData( newValue );
                }
                else {
                    timeOutID = setTimeout( function(){
                            timeOutID = null;
                            _checkData( newValue );
                        }, settings.delay );
                }
            }
        };

        function _checkData( value ) {
            if ( value == '' ) {
                return;
            }

            if ( !validateScreenName( value ) ) {
                $( statBar )
                    .css('color', settings.colorFail)
                    .html( translate( 244 ) )
                    .show();
                    
                if ( $.fn.inputHint ) {
                    $( input ).inputHint({ hide:true });
                }
                return;
            }

            _requestData( value );
        }

    	function _requestData( reqValue ) {
            if ( semaforSend ) {
                return;
            }

            semaforSend = true;

            $.ajax({
                async:      true,
                type:       'POST',
                timeout:    settings.timeout,
                url:        settings.url,
                data:       { ajaxCheckID: 1, ajaxCheckValue: reqValue },
                dataType:   'json',
                cache:      false,
                success: function( data ) {
                        _onResponse( data );

                        semaforSend = false;
                    },
                error: function() {
                        $( statBar ).html( statusText ).show();

                        if ( $.fn.inputHint ) {
                            $( input ).inputHint({ hide:true });
                        }

                        semaforSend = false;
                    }
            });
    	};

        function _onResponse( json ) {
            switch ( json.status ) {
                case 1:
                        $( input ).css('color', settings.colorFine);
                        $( statBar ).hide().css('color','').empty();
                    return;
                default:
                    $( statBar )
                        .css('color', settings.colorFail)
                        .html( translate( 243 ) )
                        .show();
                        
                    if ( 'screenNames' in json ) {
                        $.each( json.screenNames, function(idx, sn) {
                            $('<div class="screenNameSuggest">'+
                                    '<input type="radio" name="screenNameSuggest" id="sn-'+ sn +'">'+
                                    '<label for="sn-'+ sn +'">'+ sn +'</label>'+
                                '</div>')
                                .find('input')
                                    .bind('click',function(){
                                        oldValue = sn;
                                        $( input ).val( sn ).css('color',settings.colorFine).focus();
                                        $( statBar ).hide().css('color','');
                                    })
                                .end()
                                .appendTo( $( statBar ) );
                        });
                    }
            };
            
            if ( $.fn.inputHint ) {
                $( input ).inputHint({ hide:true });
            }
        };
    };
})(jQuery);
