$(document).ready(function() {

    // make autocomplete support if search exists
    if( $('#srch') )
        window.acsb = new AutoCompleteSearchBox($('#srch'));

    // display or hide conditions
    if( $('#conditions') && $('#hide1') ) {
        $('#conditions').click(function(){
            if( $('#hide1').css('display') == 'none' )
                $('#hide1').show();
            else
                $('#hide1').hide();
        });

    }

    // change torrents per page when selectbox exists
    if( $('#itemsPerPage' ) ) {
        $('#itemsPerPage' ).change( function() {
          $.cookie('torrentlist.itemsPerPage', $('#itemsPerPage').val(), {path: '/', expires: 365} );
          location.reload();
        });
    }

    // validation and submit of form  for a comments
    if( $('#ComForm') && $('#SFB') ) {
        $('#SFB').removeAttr('disabled');
        window.comment_cashed = $('#comment').val();

        $('#ComForm').submit(function() {
            return validateComForm();
        } );
        $('#comment').focus( function() {
            if ( $('#comment').val() ==  window.comment_cashed )
                $('#comment').val('');
        });

        $('#comment').blur( function() {
            if( $('#comment').val().toString().length == 0 )
                $('#comment').val( window.comment_cashed);
        });

    }

});

function debug( message ) {
    if( $('debug') ) {
        var date = new Date();
        var h = date.getHours();
        var m = date.getMinutes();
        var s = date.getSeconds();

        var o = $('<div />');
        o.html( h + ":" + m + ":" + s + " - " + message );
        $('#debug').append(o);

    }
}

function rateTorrent( torrentID, value ) {
    $('input:.inputgood').attr('disabled', true);
    $('input:.inputbad').attr('disabled', true);
    $('input:.inputgood').blur();
    $('input:.inputbad').blur();



    $.ajax({
        url: '/ajax/rate/',
        type:'POST',
        data: {
            'torrent' : torrentID,
            'value' : value
        },
        success: function(data) {
            if ( data == 'false') return;

            var val = parseInt(data);
            $('#ajaxRating').empty();
            if ( val >= 60 )
                $('#ajaxRating').html('<span class="good">' + val + '%</span>' );
            else if ( val >= 30 )
                $('#ajaxRating').html('<span class="norm">' + val + '%</span>' );
            else
                $('#ajaxRating').html('<span class="bad">' + val + '%</span>' );
            
            $('input:.inputgood').attr('class', 'inputgood-disabled')
            $('input:.inputbad').attr('class', 'inputbad-disabled')
            $('input:.inputgood-disabled').css('cursor', 'default')
            $('input:.inputbad-disabled').css('cursor', 'default')
        }
    });
    return false;
}

function validateComForm() {
    var res = false;
    if ( $('#comment').val() == '' ||  $('#comment').val() ==  window.comment_cashed ) {
        $('#comform_msg').attr('class','error');
        $('#comform_msg').show();
        return false;
    }
    else {
        var nact = $('#ComForm').attr('action').replace('cage/','add/');
        $('#ComForm').attr('action', nact );
        return true;
    }

    return res;
}

/**
 * @class
 *
 */
function AutoCompleteSearchBox(input) {
    this.input = input;

    this.focused            = false;
    this.originalText       = input.val();
    this.searchExpression   = '';
    this.data               = new Array();
    this.boxVisible         = false;
    this.timer              = null;
    this.limit              = 300;
    this.form               = $('form:first');
    this.actualIndex        = null;

    /**
     * @final
     */
    var self = this;

    this.hideAutoCompleteBox = function() {
        $('#searchOpts').empty();
        $('#searchOpts').hide();
        this.actualIndex = null;
        this.boxVisible = false;
    };

    /**
     * Display autocomplete box with words
     */
    this.showAutoCompleteBox = function() {
        this.hideAutoCompleteBox();

        var ul      = $('<ul />');

        $.each( this.data, function(index) {
            var li  = self.generateBoxItem( self.data[index] );
            li.children('a').attr( 'id', 'search-' + index );
            ul.append( li );


        });
        $('#searchOpts').append(ul);
        $('#searchOpts').show();

        this.boxVisible = true;
    };



    this.generateBoxItem = function( item ) {
        var li      = $(document.createElement('li'));
        var link    = $(document.createElement('a'));
        var span    = $(document.createElement('span'));
        span.addClass('searchListName');
        span.html(item['tag']);
        link.append( span );
        link.append( item['count'] + 'x' );
        ///link.attr('href','javascript:void();');
        li.append( link )

        link.click(function() {
            self.setTextByIndex();
            $('form:first').submit();
        });

        link.mouseover(function() {
            var index = $(this).attr('id').replace('search-', '');
            self.focusItem( parseInt(index) );
        });
        return li;
    };

    this.setTextByIndex = function() {
        if ( this.actualIndex != null )
            this.input.val( this.data[this.actualIndex]['tag'] );
    };

    this.pressDown = function(){
        if ( this.boxVisible == false ) return;
        if ( this.data.length == 0  ) return;
        
        if ( this.actualIndex == null ) {
            this.focusItem( 0 );
        }
        else {
            for( var i = 0; i < this.data.length; i++ ) {
                if( this.actualIndex == i && ( this.data.length - 1 ) > i ) {
                    this.focusItem( (i+1) );
                    break;
                }
            }
        }
        this.setTextByIndex();

        return;
    };

    this.pressUp = function() {
        if ( this.boxVisible == false ) return;
        if ( this.data.length == 0  ) return;

        for( var i = 0; i < this.data.length; i++ ) {
            if( this.actualIndex == i && i > 0 ) {
                this.focusItem( (i-1) );
                break;
            }
        }
        this.setTextByIndex();

        return;
    };

    this.focusItem = function( index ) {

        if ( this.actualIndex != null )
            $('#search-' + this.actualIndex ).attr('class','');

        $('#search-' + index ).attr('class', 'hover');
        this.actualIndex = index;

        return;
    };

    this.processData = function(response) {
        this.data =  new Array();

        try {
            this.data = jQuery.parseJSON( response );
        }
        catch(e) {
            throw e;
        }
    };

    this.resetTimer = function() {
        if ( this.timer != null )
            clearTimeout( this.timer );

        this.timer = setTimeout(function() {
            self.request();
        }, this.limit );
    }

    this.request = function() {
        $.ajax({
            url: '/ajax/tags/',
            type:'POST',
            data: {
                'search' : self.input.val()
            },
            dataType: 'text',
            success: function(data) {
                self.processData( data );
                self.showAutoCompleteBox();
            }
        });
    }

    this.form.submit( function() {
        if ( self.input.val() == self.originalText || self.input.val() == '' )
            return false;
        else {
            $(this).attr('action', '/search/' + self.input.val());
            return true;
        }
    });

    input.focus(function() {
        self.focused = true;
        if($.trim( input.val() ) == self.originalText )
            input.val('');
    });

    input.blur(function() {
        self.focused = false;
        if( $.trim(input.val()) == '' )
            input.val( self.originalText );

        if ( self.boxVisible == true )
            setTimeout( function() {
                self.hideAutoCompleteBox()
            }, 200 );
    });

    input.keyup( function(e) {
        // key UP
        if ( e.keyCode == '38' ) {
            self.pressUp();
        }
        // key DOWN
        else if ( e.keyCode == '40' ) {
            self.pressDown();
        }
        // ENTER
        else if ( e.keyCode == '13' ) {
            if ( self.actualItem != null ) {
                self.input.val( self.actualItem.children('span').html() );
            }
            self.hideAutoCompleteBox();
        }
        // If text is changed
        else if ( self.input.val() != '' && ( self.searchExpression != self.input.val() ) ) {
            self.searchExpression = self.input.val();
            self.resetTimer();
        }
        return;
    });

}

