/**
 * search - handle search related functionality 
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }
    
    var search = window.gs.search = {
        // default options/settings
        numResults: 10,
        alwaysDisplayResults: false,
        curForm: null,
        
        searchLock: false,
        
        resultsFadeDuration: 500,
        container: 'promotion',
        useJson: true,
        isMain: false,
        lastQuery: '',
        lastPage: 1,
        
        doAutoComplete: false,
        autoCompleteTimeout: null,
        autoCompleteWait: 200,
        
        empty: null
    };
    
    search.init = function() {
        // initialize form handler
    };

    search.initCatalogSearch = function() {
        $('input.search.catalog').each(function(){
            $(this).keydown(function(event) {
                if(event.charCode==13 || event.which==13){
                    gs.search.doCatalogSearch(this);
                    if(event.preventDefault) event.preventDefault();
                    if(event.stopPropagation) event.stopPropagation();
                    event.returnValue=false;
                    return false;
                }
            })
            .siblings('button').click(function() {
                debug('button click for search ', this);
                search.doCatalogSearch($(this).siblings('.catalog'));
            });
        });
    }
    search.doCatalogSearch = function(obj) {
        debug('get params for catalog search', obj);
        if(search.lock) {
            return false;
        }
        search.lock = true;
        var isSong = $(obj).is('.song');
        var keyword = $(obj).val();
        var index = $(obj).siblings('.index').val();
        var size = $(obj).siblings('.size').val();
        var adbuilder = $(obj).siblings('.adbuilder').val() || 0;
        var method = (isSong) ? 'cataloguedSongs' : 'artistMatch';
        var type = (isSong) ? 'song' : 'artist';
        var url = '/'+search.container+'/'+method;
        url += (search.useJson) ? '.json' : '';
        var params = {keyword:keyword, index:index, size:size, adbuilder:adbuilder};

        if(search.isMain && !keyword.length) {
            debug('using signup, and no keyword length');
            $('#autocomplete').hide();
            search.lock = false;
            return false;
        }

        if(keyword!=search.lastQuery) {
            index = 1;
            params.index = index;
            $(obj).siblings('.index').val(index);
        }

        // see if its cached
        var nquery = keyword.replace(/\s+/, '-').replace(/\W/, '');
        var hash = type+nquery+index;
        debug('js query hash: '+hash);
        if($('#'+hash).length) {
            $('#'+hash).show().siblings().hide();
            search.lock = false;
            return false;
        }
        search.lastQuery = keyword;
        search.lastPage = index;
        //debug($(obj).siblings('.results.search').children(':visible').get());
        $(obj).siblings('.results.loading').show();
        if(!search.isMain) {
            $(obj).siblings('.results.search').children(':visible').hide();
        }
        $.getJSON(url, params, function(json) {
            debug('search return', json);
            search.lock = false;
            $(obj).siblings('.results.loading').hide();
            if(json && json.html) {
                debug('what is obj', obj, $(obj).siblings('.results.search'));
                if(search.isMain) {
                    debug('autocomplete result', $('#autocomplete').find('.inner ul'));
                    $('#autocomplete').find('.inner ul').html(json.html);
                    $('#autocomplete').show();
                } else {
                    $(obj).siblings('.results.search').show().get(0).innerHTML += '<div id="'+json.hash+'" style="display:none;">'+json.html+'</div>';
                }
                setTimeout(function() {
                    debug('settimeout');
                    $('#'+json.hash).fadeIn(function() {
                        debug('fade in');
                        $(this).show().css('opacity','1');
                        if(window.isIE) {
                           $(this).css('filter', 'none');
                           gs.util.objRedraw();
                        }
                    });
                }, 100);
            } else {
                $(obj).siblings('.results.search').hide();
            }
            debug('done with every');
        });
    }

    search.hideResult = function(obj)
    {
        debug('search result hide');
        $(obj).parent().parent().parent().fadeOut();
        search.setPage(obj, 1, false);
        return false;
    }
    
    search.next = function(obj) {
        search.changePage(obj,1);
        return false;
    }
    
    search.prev = function(obj) {
        search.changePage(obj,-1);
        return false;
    }
    
    search.changePage = function(obj,dir) {
        dir = parseInt(dir);
        var searchInput = $(obj).parent().parent().parent().parent().parent().parent().siblings('input.search');
        var index = searchInput.siblings('.index');
        var button = searchInput.siblings('button');
        debug('change page, inp, page', searchInput, index, button, obj); 
        var curValue = parseInt(index.val());
        if(dir<0) {
            curValue -= 1;
        }
        if(dir>0) {
            curValue += 1;
        }
        curValue = Math.max(curValue, 1);
        index.val(curValue);
        debug(index);
        search.doCatalogSearch(searchInput);
    }
    
    search.setPage = function(obj, page, doSubmit)
    {
        doSubmit = (typeof doSubmit=='undefined') ? true : doSubmit;
        var searchInput = $(obj).parent().parent().parent().siblings('.search');
        $(searchInput).siblings('.page').val(page);
        if(doSubmit) {
            $(searchInput).siblings('button').click();
        }
    }
})();

/*
dddd
 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+/, '-').replace(/\W/, '');
    debug('js 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), 'audodiv: ', autodiv);
    // take result and make it drop down
    if(search.alwaysDisplayResults || response.Code) {
        debug('response 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();
    }
};
*/
