/**
  * Quich Searcher Class
  *
  * @author  Marc Mignonsin
  * @version 2010-12-16
  *
  */

QuickSearcher = function(panelID, controller, script, inputSelector, resetSelector)
{
	//window.log('QuickSearcher', arguments);
	$('#'+panelID+'.panel').panel('addExternalResource', this, null);
	
	this.reset(); // just in case

	this.controller = controller;
	this.panelID = panelID;
    var panel = $('div#'+this.panelID+'.panel');

    this.inputSelector = inputSelector;
	this.inputElement = panel.find('#'+inputSelector);
    this.inputElement.attr('autocomplete','off');
    
    this.addDefaultValue(this.inputElement.attr('default-value'), this.inputElement.attr('default-color'));

	// this event will assure all browsers compatibility
	this.inputElement.keydown(
		delegate(this, this.onKeyDown)
	);

	this.resetElement = panel.find('#'+resetSelector);
    this.resetElement.click(delegate(this, function(){
    	this.reset();
		if (this.resetCallback) this.resetCallback();
	}));

    this.scriptURL = script;
    
    this.ajaxRequest = new AjaxRequest(
        this.panelID,
        this.controller,
        this.scriptURL,
        'POST',
        'html'
    );
    // display error dialog and return errors in long msgs format
    this.ajaxRequest.errorDialog(true, false);
    this.ajaxRequest.internalErrorDialog(true, false);

    this.ajaxRequest.onSuccess(delegate(this, function(response){
    	$('div#'+this.panelID+'.panel').trigger('panel-displayloader', [false, 'body']).trigger('panel-blockcontent', ['.block-nav', response]);
        this.timerID = -1;
    })).onError(delegate(this, function(response){
    	$('div#'+this.panelID+'.panel').trigger('panel-displayloader', [false, 'body']).trigger('panel-blockcontent', ['.block-nav', response]);
		this.timerID = -1;
    }));
    
	//window.log(this);

	return this;
};

QuickSearcher.prototype.controller = null;
QuickSearcher.prototype.panelID = null;

QuickSearcher.prototype.scriptURL = '';

QuickSearcher.prototype.inputSelector = '';
QuickSearcher.prototype.inputElement = null;
QuickSearcher.prototype.defaultValue = '';
QuickSearcher.prototype.resetElement = null;

QuickSearcher.prototype.lastParms = { };
QuickSearcher.prototype.ajaxRequest = null;
QuickSearcher.prototype.keyPressDelay = 300;
QuickSearcher.prototype.timerID = -1;

QuickSearcher.prototype.keyCodeDelete	= 46;
QuickSearcher.prototype.keyCodeBackspace = 8;
QuickSearcher.prototype.keyCodeUpArrow   = 38;
QuickSearcher.prototype.keyCodeDownArrow = 40;
QuickSearcher.prototype.keyCodeLeftArrow   = 37;
QuickSearcher.prototype.keyCodeRightArrow   = 39;
QuickSearcher.prototype.keyCodeEnter	 = 13;
QuickSearcher.prototype.keyCodeEscape	= 27;
QuickSearcher.prototype.keyCodeTab	   = 9;
QuickSearcher.prototype.keyCodeCmd	   = 91;
QuickSearcher.prototype.keyCodeCmdFF	= 224;

QuickSearcher.prototype.minLengthForRequest = 3;

QuickSearcher.prototype.resetCallback = null;
QuickSearcher.prototype.focusCallback = null;

QuickSearcher.prototype.reset = function()
{
	//window.log('QuickSearcher.reset', arguments);
    this.controller = null;
    this.panelID = null;

	this.scriptURL = '';

    this.inputSelector = '';
	this.inputElement = null;
    this.defaultValue = '';
	this.resetElement = null;

    this.lastParms = { };
	this.ajaxRequest = null;
	this.keyPressDelay = 500;
	this.timerID = -1;

    this.keyCodeDelete	= 46;
    this.keyCodeBackspace = 8;
    this.keyCodeUpArrow   = 38;
    this.keyCodeDownArrow = 40;
    this.keyCodeLeftArrow   = 37;
    this.keyCodeRightArrow   = 39;
    this.keyCodeEnter	 = 13;
    this.keyCodeEscape	= 27;
    this.keyCodeTab	   = 9;

    this.minLengthForRequest = 3;
    
    this.resetCallback = null;
    this.focusCallback = null;
};

QuickSearcher.prototype.destroy = function()
{
	//window.log('QuickSearcher.destroy', arguments);
	if (this.ajaxRequest)
	{
		this.ajaxRequest.abort();
		delete this.ajaxRequest;
		this.ajaxRequest = null;
	}
};

/* *** */

QuickSearcher.prototype.onReset = function(callback)
{
	//window.log('QuickSearcher.onReset', arguments);
	this.resetCallback = callback;
	return this;
};

QuickSearcher.prototype.onFocus = function(callback)
{
	//window.log('QuickSearcher.onFocus', arguments);
	this.focusCallback = callback;
	return this;
};

QuickSearcher.prototype.setStringLengthThreshold = function(length)
{
	//window.log('QuickSearcher.setStringLengthThreshold', arguments);
	this.minLengthForRequest = length;
};

QuickSearcher.prototype.setDefaultParms = function(parms)
{
    //window.log('QuickSearcher.setDefaultParms', arguments);
    this.lastParms = parms;
};

QuickSearcher.prototype.addDefaultValue = function(value, defaultColor)
{
    //window.log('QuickSearcher.addDefaultValue', arguments);
    this.defaultValue = value;

    this.inputElement.css('color', defaultColor);
    this.inputElement.val(value);

    var self = this;
    this.inputElement.focus(function(){
        if (this.value == value)
        {
        	this.style.color = '#222222';
        	this.value = '';
        }
        if (self.focusCallback) self.focusCallback();
        return false;
    });
    
    this.inputElement.blur(function(){
        if (this.value == '')
        {
            this.style.color = defaultColor;
            this.value = value;
        }
        return false;
    });
};

QuickSearcher.prototype.reset = function(reloadPage){
	//window.log('QuickSearcher.reset', arguments);
	if (this.inputElement != null)
	{
		this.inputElement.val('');
        this.inputElement.blur();

        if ((reloadPage !== false) && (this.lastParms[this.inputSelector]))
        {
            this.loadPage(1);
        }
	}
};

QuickSearcher.prototype.loadPage = function(page)
{
    //window.log('QuickSearcher.load', arguments);
    this.lastParms.page = page;

	if (this.timerID != -1)
	{
		clearTimeout(this.timerID);
        this.timerID = -1;
	}

    // immediate request
    this.request(true);

    return false;
};

QuickSearcher.prototype.onKeyDown = function(event)
{
    //window.log('QuickSearcher.onKeyDown', arguments);
    //window.log(event.which);

     switch(event.which)
	 {
		case this.keyCodeBackspace:
		case this.keyCodeDelete:
			break;

		case this.keyCodeEnter:
			// force immediate request
		    this.lastParms.page = 1;
			if (this.timerID != -1)
			{
				clearTimeout(this.timerID);
			}
			this.request(true);		
			return true; // discard ajax request
			break;

		case this.keyCodeEscape:        
            //this.reset();
            // does not work => keeps the focus
            return true;
            break;

		case this.keyCodeUpArrow:
		case this.keyCodeDownArrow:         
        case this.keyCodeTab:
        case this.keyCodeLeftArrow:
        case this.keyCodeRightArrow:
        case this.keyCodeCmd:
        case this.keyCodeCmdFF:
			return true; // discard ajax request
			break;

		default:
            if (event.keyCode < 32)
            {
                return true;
            }
			break;
	}

    // reset page
    this.lastParms.page = 1;

	// send delayed request
	if (this.timerID != -1)
	{
		clearTimeout(this.timerID);
	}

	this.timerID = setTimeout(delegate(this, this.request), this.keyPressDelay);
};

QuickSearcher.prototype.request = function(disableLengthCheck)
{
	//window.log('QuickSearcher.request', arguments);
	var inputString = this.inputElement.val();

	if (disableLengthCheck != true)
	{
		if (inputString.length < this.minLengthForRequest)
    	{
        	return false;
    	}
    }

    if (inputString != this.defaultValue)
    {
        this.lastParms[this.inputSelector] = inputString;
    }
    else
    {
        this.lastParms[this.inputSelector] = '';
    }

	// cancel previous request
	this.ajaxRequest.abort();
	
    $('div#'+this.panelID+'.panel').trigger('panel-displayloader', [true, 'body']);

    // display error dialog and return errors in long msgs format
    this.ajaxRequest.send(this.lastParms);

	return false;
};

QuickSearcher.prototype.refresh = function()
{
    //window.log('QuickSearcher.refresh', arguments);
    //$(this.controller).panelslider('cutChildrenPanels', this.panelID);

    if (this.lastParms.page >= 1)
    {
        this.request();
    }
    else
    {
        this.loadPage(1);
    }
};