// © 20-20 Technologie Inc. 2015 
// All Rights Reserved
//11.03.16
function Key(key, data) {
   this.key = key;
   this.data = data;
}

function copyKeys(keys) {
   var copy = new Array();
   for (var i = 0; i < keys.length; i++) {
      copy.push(new Key(keys[i].key, keys[i].data));
   }
   return copy;
}

function KeyMap(key) {
   this.key = key;
   this.keys = new Array();

   this.keyCount = function() {
	   var count = 0;
	   for (var i = 0; i < this.keys.length; i++){
		   if (this.keys[i] instanceof KeyMap) {
			   count += this.keys[i].keyCount();
		   }
		   else {
			   count++;
		   }
	   }
	   return count;
   }
   
   this.addKey = function(keys) {
      for (var j = 0; j < keys.length; j++) {
         var key = keys[j];
         keys.splice(j,1);
         if (key.key == this.key) {continue;}
         var found = false;
         for (var i = 0; i < this.keys.length; i++) {
            if (this.keys[i].key < key.key) {continue;}
            else if (this.keys[i].key == key.key && this.keys[i] instanceof Key) {
               found = true;
               break;
            }
            else if (this.keys[i].key == key.key && this.keys[i] instanceof KeyMap) {
               this.keys[i].addKey(copyKeys(keys));
               found = true;
               break;
            }
            else if (this.keys[i].key > key.key) {
               if (keys.length > 0) {
                  var keymap = new KeyMap(key.key);
                  this.keys.splice(i,0,keymap);
                  keymap.addKey(copyKeys(keys));
               }
               else {
                  this.keys.splice(i,0,key);
               }
               found = true;
               break;
            }
         }
         if (!found) {
            if (keys.length > 0) {
               var keymap = new KeyMap(key.key);
               this.keys.push(keymap);
               keymap.addKey(copyKeys(keys));
            }
            else {
               this.keys.push(key);
            }
         }
         keys.splice(j,0,key);
      }
   }

   this.getKeys = function(keys,matches,level) {
      for (var i = 0; i < this.keys.length; i++) {
         if (this.keys[i] instanceof Key) {
            matches.insert(this.keys[i],level);
         }
         else {
            for (var j = 0; j < keys.length; j++) {
               if (this.keys[i].key == keys[j].key) {this.keys[i].getKeys(keys,matches,level+1);}
            }
         }
      }
   }
}

function Matches() {
   this.matches = new Array();
   this.insert = function(key,level) {
      for (var i = 0; i < this.matches.length; i++) {
         if (this.matches[i][0].key == key.key) {return;}
         else if (this.matches[i][0].key < key.key) {continue;}
         else if (this.matches[i][0].key > key.key) {this.matches.splice(i,0,[key,level]);return;}
      }
      this.matches.push([key,level]);
   }
}

function PL(level) {
   this.flag = level;
}

function Flag(flag) {
   this.flag = flag;
}
