//
//
//
function Filter() 
{
    this.targets = [];

    this.mode_and = 0;
    this.mode_or  = 1;

    this.setTarget = function ( evaluate_target, target_objects  ) {
	this.targets.push( [evaluate_target, target_objects] );
    }

    this.quotemeta = function (tstr, isReg) {
	if ( isReg ) {
	    return tstr;
	} else {
	    qstr = tstr.replace(/(\W)/, "\\$1").replace(/\(/, "\(").replace(/\)/, "\\)");
	    return qstr;
	}
    }

    this.mode = this.mode_and;

    this.generateEvaluator = function ( keystr ) {
	if (! keystr || keystr == "") {
	    return function ( target ) { return true; }
	}
	keystr = keystr.replace('@', ' '); // replace sjis full width space with 0x20
	var keys = keystr.split(' ');
	var res = []
	for( var i=0; i<keys.length; i++ ) {
	    if (keys[i] == '') { continue; }
	    res.push( new RegExp( this.quotemeta(keys[i]), "i") );
	}	    

	if ( this.mode == this.mode_and ) {
	    return function ( target ) { 
		for( var i=0; i<res.length; i++ ) {
		    if( ! target.innerHTML.match( res[i] ) ) {
			return false;
		    }
		}
		return true;
	    }
	} // else
	return function ( target ) { 
	    for( var i=0; i<res.length; i++ ) {
		if( target.innerHTML.match( res[i] ) ) {
		    return true;
		}
	    }
	    return false;
	}
    }

    this.tmpstr = "";
    this.evaluate = function ( keystr ) {
	this.tmpstr += keystr;
	var ev = this.generateEvaluator( keystr );
	var nmatch = 0;
	for( var i in this.targets ) {
	    if ( ev(this.targets[i][0]) ) {
		nmatch++;
		for( var j in this.targets[i][1] ) {
		    this.targets[i][1][j].style.display = "";
		}
	    } else {
		for( var j in this.targets[i][1] ) {
		    this.targets[i][1][j].style.display = "none";
		}
	    }
	}
	return nmatch;
    }    

    this.getTotal = function () {
	return this.targets.length;
    }
}

