/**
 * search Javascript
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }
    
    var search = window.gs.search = {
        // default options/settings
        numResults: 10,
        alwaysDisplayResults: false,
        doAutoComplete: false,
        autoCompleteTimeout: null,
        autoCompleteWait: 200,
        curForm: null,
        
        searchLock: false,
        
        resultsFadeDuration: 500,
        lastQuery: '',
        lastPage: 1,
        
        empty: null
    };
    
    search.init = function() {
        // initialize form handler
        search.handleForm();
    };
    
    search.handleForm = function() {
        var preFormSubmit = function(data, form, options) {
            // make sure query is not null
            if(search.lock) {
                return false;
            }
            search.lock = true;
            
            var query = '', page, type, qKey, pKey, tKey;
            for(var key in data) {
                if(data[key].name=='q') {
                    query = data[key].value.replace(/\s+/g,' ');
                    data[key].value = query;
                    qKey = key;
                }
                if(data[key].name=='page') {
                    page = data[key].value;
                    pKey = key;
                }
                if(data[key].name=='type') {
                    type = data[key].value;
                    tKey = key;
                }
            }
            // hide autocomplete box
            $('#'+$(form).attr('id')+'ac').hide();
            // see if its cached
            var nquery = query.replace(/\s+/, '-');
            debug('query hash: ', type+nquery+page);
            if($('#'+type+nquery+page).length) {
                $('#'+type+nquery+page).show().siblings().hide();
                search.lock = false;
                return false;
            }
            
            if(query=='') {
                search.lock = false;
                return false;
            }
            
            if(query!=search.lastQuery) {
                data[pKey].value = 1;
            }
            search.curForm = form;
            search.lastQuery = query;
            search.lastPage = page;
            $(form).siblings('.results').children(':visible').fadeOut(function() {
                if(window.isIE) {
                   $(this).css('filter', 'none');
                   gs.util.objRedraw();
                }
            });
            $("button.search", search.curForm).addClass("loading");
            //$('#songResults').css('height', $('#songResults').height()+15);
        };
        
        var postFormSubmit = function(response) {
            search.lock = false;
            $("button.search", search.curForm).removeClass("loading");
            $("#searchError").hide();
            var formid = search.curForm.attr('id');
            var autodiv = $('#'+formid+'ac');
            debug($(search.curForm), search.curForm.attr('id'), formid, autodiv);
            // take result and make it drop down
            if(search.alwaysDisplayResults || response.Code) {
                debug('query hash: ', response.Custom.hash);
                $(search.curForm).siblings('.results').prepend('<div id="'+response.Custom.hash+'" style="display:none;">'+response.Custom.html+'</div>');
                //$('#'+response.Custom.hash).show().siblings().hide();
                $('#'+response.Custom.hash).fadeIn(function() {
                    if(window.isIE) {
                       $(this).css('filter', 'none');
                       gs.util.objRedraw();
                    }
                });
            } else {
                // put empty result message here
                if(response.Custom && response.Custom.html) {
                    $(search.curForm).siblings('.results').prepend('<div id="'+response.Custom.hash+'">'+response.Custom.html+'</div>');
                    $('#'+response.Custom.hash).addClass('error').fadeIn();
                }
                //$("#searchError").html("No results were found for '"+$('#query').val()+"'.  Please double-check your spelling, and try broadening your search criteria by searching only for a song title or artist name if the issue persists.").show();
            }
        };
        
        var options = {
            beforeSubmit: preFormSubmit,
            success: postFormSubmit,
            error: function() { search.lock=false; },
            dataType: 'json'
        };
        
        $("#search,#songSearch,#playlistSearch,#singleSongSearch").ajaxForm(options).find('input.search').each(function() {
            var form = $(this).parents('form');
            var type = 'song';
            if(form.attr('id').match('playlist')) {
                type = 'playlist'; 
            }
            var curQuery = '';
            $(this).autocomplete(form.attr('action'),{
                resultsId: form.attr('id')+'ac',
                minChars: 4,
                max: 10,
                delay: search.autoCompleteWait,
                cacheLength: 100,
                width: 520,
                scroll: true,
                scrollHeight: 190,
                matchSubset: false,     // whether to do new query for refinement (false==new query)
                selectFirst: false,     // whether to auto select first item
                extraParams: {auto:1,type:type},
                offsetTop: 10,
                offsetLeft: -9,
                //highlight: false,    // could be a function or false, defaults to true
                /*
                formatItem: function(item) {
                    //debug('format item', item, arguments);
                    return item.toString();
                },
                //*/
                formatResult: function(item) {
                    return item[0];
                }
            });
            $(this).keyup(function(){
                lastQuery = this.value;
            }).result(function(event, item, formatted) {
                debug('result item: '+lastQuery, arguments);
                var type = item[1];
                var id = item[2];
                $.post("/loglinkclick.php", {search:lastQuery, type:type, id:id});
                form.submit();
                if(type=='song') {
                    gs.playlist.addSong(id);
                }
                if(type=='playlist') {
                    gs.playlist.addMusic('playlist', id);
                }
            });
        });
    };
    
    search.resultHide = function(obj)
    {
        debug('result hide');
        $(obj).parent().parent().fadeOut();
        search.setPage(obj, 1, false);
    }
    
    search.next = function() {
        search.changePage(1);
    }
    
    search.prev = function() {
        search.changePage(-1);
    }
    
    search.changePage = function(dir) {
        dir = parseInt(dir);
        var curValue = parseInt(document.forms.search.page.value);
        if(dir<0) {
            curValue -= 1;
        }
        if(dir>0) {
            curValue += 1;
        }
        curValue = Math.max(curValue, 1);
        document.forms.search.page.value = curValue;
        $(document.forms.search).submit();
    }
    
    search.setPage = function(obj, page, doSubmit)
    {
        doSubmit = (typeof doSubmit =='undefined') ? true : doSubmit;
        var form = $(obj).parents('div.results').siblings('form').get(0);
        form.page.value = page;
        if(doSubmit) { $(form).submit(); }
    }
})();
