/**
 *
 *
 *
 */

var Comparator = {
  kRegexp:'regexp',
  kCompare:'compare',

  type:'regexp',

  column:'filename',

  get isDefault(){
    var el    = document.getElementById( "fileFormat_any");
    var isAny = (el.getAttribute('checked') == 'true');

    var pattern   = document.getElementById('urlpattern');
    var isDefault = (pattern.value == '');

    return isAny && isDefault;
  },

  get func(){
    // XXX UI Depedent ! It's bad
    var selector   = document.getElementById('selector');
    var comparison = function( aString ){
      return true;
    };

    // Generate the right function
    switch( this.type ){
      case this.kRegexp:
        var start   = selector.getAttribute('beginReg');
        var end     = selector.getAttribute('endReg');
        var invert  = parseInt(selector.getAttribute('invert'));
        
        comparison = function( aString ){
          var pattern   = ow.app.kernel.prefs.getString("oWDocs.autocatch.urlpattern", "");
          var finalPattern = new RegExp( start + pattern + end, 'i');
          if( invert ) return !finalPattern.test( aString );

          return finalPattern.test( aString );
        };
      break;
      
      /* UNUSED
      case this.kCompare:
        var compar  = parseInt(selector.getAttribute('compar'));
        var invert  = parseInt(selector.getAttribute('invert'));

        comparison = function( aString ){
          var pattern   = ow.app.kernel.prefs.getString("oWDocs.autocatch.urlpattern", "");
          var finalCompare = aString + compar + pattern;
          if( invert ) return !evl(finalCompare);
          return evl(finalCompare);
        }
      break;
      */
    }
    return comparison;
  }
};


Comparator.checkType = function( aName ){
  if (ow.app.kernel.prefs.getBool("oWDocs.autocatch.any", false) == true) {
    return true;
  }

  var documentType = aName.split(".");
  documentType = documentType[documentType.length-1];
  documentType = documentType.toLowerCase();
  var types = optionsCtrl.fileTypes;

  var found = false;
  for( var type in types ){
    var toCheck = ow.app.kernel.prefs.getBool("oWDocs.autocatch." + type, "");
    if( toCheck ) {
      var subTypes = types[type];
      for( var i = 0 ; i < subTypes.length ; i++ ){
        if (documentType == subTypes[i]) {
          found = true;
          break;
        }
      }
    }
  }
  return found;
};

Comparator.apply = function(forceSelect){
  try {
  gContainer.unselectAll();

  if( this.isDefault && !forceSelect ) {
    return;
  }
        
  var comparison  = this.func;

  var items = gContainer.items;
  var rv = [];
  for( var i = 0 ; i < items.length ; i++ ){
    if( comparison( items[i][this.column] ) && Comparator.checkType( items[i].filename) ) rv.push(i);
  }
  gContainer.select( rv );
  }
  catch(e) {
    dump("Comparator.apply error : " + e + "\n");
  }
};

