/**
 * Provides the following ajax searchfunctions for ejscore:
 * - realtime searchresults
 * - searchterm suggestions
 * 
 * @author  Sander van den Akker
 * @package Myxt Global
 * @version 1.1
 * @requires Jquery UI autocomplete, eZFind
 */

$(function () {
    
    /*
     * Returns nodes based on a query.
     * 
     * Example:
     * $('#searchtext').globalsearch({
     *     url: '/ezjscore/call/ezjsc::search',
     *     limit: 10
     * });
     * 
     */
    $.fn.search = function( options )
    {  
        var field = $(this);
        var defaults = {
            offset: 0,
            limit: 20,
            subtree: 2,
            classes: '',
            attributes: '',
            container: field.attr('rel')
        }
        var options =  $.extend( defaults, options );
        
        field.autocomplete({
            
            source: function(req, add) {
                var str = field.val() + '*';
                var query = str.toLowerCase();
                
                if( options.attributes != '' ) {
                    query = '( ';
                    
                    var attributes = options.attributes.split(',');
                    
                    var stringParts = [];
                    for( var i in attributes ) {
                        stringParts[i] = 'attr_' + jQuery.trim( attributes[i] ) + '_t:(' + str + ')';
                    }
                    query += stringParts.join( ' OR ' );
                    
                    var keywordParts = [];
                    for( var i in attributes ) {
                        keywordParts[i] = 'attr_' + jQuery.trim( attributes[i] ) + '_lk:(' + str.toLowerCase() + ')';
                    }
                    query += keywordParts.join( ' OR ' );
                    
                    query += ' )';
                }

                $.ez( 'ezjsc::search', {
                    'SearchStr': query,
                    'SearchOffset': options.offset,
                    'SearchLimit': options.limit,
                    'SearchSubTreeArray': options.subtree,
                    'SearchContentClassIdentifier': options.classes
                }, function( data ) {
                    var results = [];
                    $.each( data.content.SearchResult, function( i, val ) {
                        results.push({
                            value: val.url_alias,
                            label: val.name
                        });  
                    });
                    add( results );
                });
            },
            select: function( event, ui ) {
                $('#loading').show();
                window.location.href = ui.item.value;
            }
            
        });

    }

   /*
    * Example:
    * $('#searchtext').globalautocomplete({
    *      url: '/ezjscore/call/ezjsc::autocomplete',
    *      limit: 10
    * });
    *
    */
    $.fn.globalautocomplete = function( configuration ) {

        $(this).autocomplete({
            source: function( request, response ) {

                $.ajax({
                    url: configuration.url + "::" + request.term + "::" + configuration.limit + "?ContentType=json",
                    success: function( data ) {
                        response( $.map( data.content, function( item, index ) {
                            return {
                                label: item[0] + ' (' + item[1] + ')',
                                value: item[0]
                            }
                        }));
                    }
                });
            },
            minLength: 3
        });

    }
    
    var currentValue = $('input.searchtext').val();
    $('input.searchtext').focus(function() {
        if(currentValue == 'Zoekterm' || currentValue == 'Trefwoord' || currentValue == 'Keyword' || currentValue == 'Searchterm')
            $(this).val('');
    }).blur(function() {
        if($(this).val() == '')
            $(this).val(currentValue);
    });
   

});

