var WortDichte = {
  color: [{min:0.01,max:0.015,color:"yellow"},{min:0.025,max:0.03,color:"yellow"},{min:0.015,max:0.025,color:"green"},{min:0.00,max:0.01,color:"red"},{min:0.03,max:1,color:"red"}],

  wdFrame: null,
  wdFrameBody: null,
  wdElmLst : new Array(),

  wordCount:0,
  textBlock:"",
  textBlockList: null,

  idKey:null,
  idTxt:null,

  tagRemove: false,
  wdWordElement:null,

  init: function(idTxt, idKey, tagRemove){
    this.idKey = idKey;
    this.idTxt = idTxt;
    this.tagRemove = tagRemove;
  },

  parseKeyField: function(id){
     var e = document.getElementById(id);
     var noadd = true;
     if(e){
       var v = e.value;//.replace(/\r\n/g,'\n');
       var l = v.split(',');
       this.wdElmLst = new Array();
       for(var i = 0; i < l.length; i++){
         if(l[i].match(/\w/)){
           var n = this.add(l[i].replace(/(^\s+|\s+$)/g,""));
           noadd = false;
         }
       }
      this.recalc();
     }
     if(noadd){this.add();}
  },

  recalc: function(){
    for(var i = 0; i < this.wdElmLst.length; i++){
      this.count(this.wdElmLst[i]);
    }
  },

  buildFrame: function(){
    if(this.wdFrame){this.show();return;}
    var pt = (((window.innerHeight) ? window.innerHeight: document.body.clientHeight)/2)-200;
    var pl = (((window.innerWidth) ? window.innerWidth: document.body.clientWidth)/2)-225;
    var pos = "fixed";
    var srl = "auto";
    if(document.all){
        pt += document.body.scrollTop;
        pos = "absolute";
        srl = "scroll";
    }
    var h = this._buildHTML("DIV","wdFrameHead","background-color:#C0C0C0;font-weight:bold;font-size:larger;padding:3px;border-bottom:1px solid black;");
    var b = this._buildHTML("DIV","wdFrameBody","overflow:"+srl+";min-height:100px;max-height:350px;","");
    var f = this._buildHTML("DIV","wdFrame","display:none;background-color:#EFEFEF;border: solid 3px black;position:"+pos+"; top:"+pt+"px; left:"+pl+"px;width:450px;",h);
    var c = this._buildHTML("DIV","wdControl","margin:2px;border-top:1px solid black;");
    c.innerHTML = '<input id="wdControlCancel" type="button" value="Abbrechen" onclick="WortDichte.show(0)" style="float:right;font-weight:bold;font-size:larger;margin-left:10px;">'
                  +'<input id="wdControlApply" type="button" value="Ok" onclick="WortDichte.apply()" style="float:right;font-weight:bold;font-size:larger;margin-left:10px;">'
                  +'<input id="wdControlReset" type="button" value="Reset" onclick="WortDichte.reset()" style="font-size:larger;margin-left:5px;">';

    h.innerHTML = '<input type="button" value="X" onclick="WortDichte.show(0)" style="float:right;font-weight:bolder;color:red;">'
                 +'<span name="wdFrameHeadText">Wortdichte</span>';

    this.wdFrame = f;
    this.wdFrameBody = b;
    this.wdFrame.appendChild(b);
    this.wdFrame.appendChild(c);

    h.onmousedown = function(){
                     var p = this.parentNode;var ox,oy;
                     this.onmouseup = function(){p.onmousemove = function(){}; p.onmouseout = function(){}}
                     p.onmouseup=this.onmouseup;
                     var m = function(ev){
                                  var px = (!ev) ? window.event.clientX : ev.pageX;var py = (!ev) ? window.event.clientY : ev.pageY;
                                  if(!ox){oy = py - parseInt(this.style.top); ox = px - parseInt(this.style.left); }
                                  this.style.left = (px-ox)+"px"; this.style.top = (py-oy)+"px";
                                  return false;
                                }
                     p.onmousemove = m;p.onmouseout = m;
                     return false;
                   }
    document.getElementsByTagName("body")[0].appendChild(f);
  },

  show: function(b){
    if(!this.wdFrame){this.buildFrame();}
    if(b == null || b){
      this._loadTextBlock(this.idTxt);
      if(this.idKey){this.parseKeyField(this.idKey);}else{this.add();}
      this.wdFrame.style.display = "block";
      

    }else{
      this.wdFrame.style.display = "none";
    }
  },

  reset: function(){
    if(this.idTxt){this._loadTextBlock(this.idTxt);}
    if(this.idKey){this.parseKeyField(this.idKey);}else{this.wdElmLst = new Array();this.recalc();}
  },

  _writeElmLst: function(){
    var b = this.wdFrameBody;

    while(b.hasChildNodes()){
        b.removeChild(b.firstChild);
    }

    for(var i = 0; i < this.wdElmLst.length; i++){
      b.appendChild(this.wdElmLst[i]);
    }
    b.scrollTop = b.offsetHeight;
  },

  add: function(txt){

    if(this.wdElmLst.length > 0){
      var e = this.wdElmLst[this.wdElmLst.length-1];
      var ie = this._getElement(e.firstChild,"wdAdd");
      ie.onclick = function(){WortDichte.remove(this)};
      ie.value = "-";
    }

    var d = this._buildHTML("DIV","wdWordElement","padding:2px;border-bottom:solid 1px black;");

    if(!txt){txt = "";}
    d.innerHTML = '<input name="wdAdd" type="button" value="+" style="float:right;font-weight:bolder;"><input name="wdWordInput" type="text" size="35" value="'+txt+'"><span name="wdCountResult" style="background-color:;" ></span>';
    this.wdElmLst.push(d);
    var func = this.add;
    this._getElement(d.firstChild,"wdAdd").onclick = function(){WortDichte.add()};
    var tfi = this._getElement(d.firstChild,"wdWordInput")
    tfi.onkeyup = function(){WortDichte.count(this.parentNode)};
    tfi.focus();
    this._writeElmLst();
    return d;
  },

  remove: function(n){
    var node = n.parentNode;
    for(var i = 0; i < this.wdElmLst.length; i++){
      if(this.wdElmLst[i] === node){this.wdElmLst.splice(i,1)}
    }
    this._writeElmLst();
  },

  _getElement: function(node,name,r){
     var n = node;
     while(n != null){
       var a = n.getAttribute("name", "false");

       if(a && a == name){
         return n;
       }
       if(r && n.hasChildNodes()){
          var res = this._getElement(n.firstChild,name,r);
          if(res){ return res;}
    
       }
       n = n.nextSibling;
     }

     return null;
  },

  _buildHTML: function(t, id, s, c){
     var n = document.createElement(t);
     var ai = document.createAttribute("name");
     ai.nodeValue = id;
     
//      var as = document.createAttribute("style");
//      as.nodeValue = s;
     n.setAttributeNode(ai);
//      n.setAttributeNode(as);
     n.style.cssText = s;
     if(c){
       if(typeof c == 'object'){
          n.appendChild(c);
       }else{
          n.appendChild(document.createTextNode(c));
       }
     }
     return n;
  },

  count: function(node){

if(!node.hasChildNodes()){return;};
    var n = node.firstChild;

    var txtField = this._getElement(n,"wdWordInput");
    var res = this._getElement(n,"wdCountResult");

    var text = txtField.value.replace(/(^\s+|\s+$)/g,"");

    var color  = "";
    var out = "";

    if(text != ""){
      var re = new RegExp('\\b'+text+'\\b','gi');
      var found = this.textBlock.match(re);
      var count = found ? found.length: 0;
      var pctf = count / this.wordCount;
      var pct = ""+(pctf*100);
      pct = pct.substr(0,pct.indexOf(".")+3);
      out = count+"x ("+pct+"%)";
      for(var e in this.color){
         var o = this.color[e];
         if(pctf >= o.min && pctf <= o.max){color = o.color;}
      }
    }
    res.parentNode.style.backgroundColor = color;
    res.innerHTML = out;
  },

  apply: function(){
    var out = "";
    for(var i = 0; i < this.wdElmLst.length; i++){
      var v = this._getElement(this.wdElmLst[i].firstChild,"wdWordInput").value.replace(/(^\s+|\s+$)/g,"");
      if(v.match(/\w/)){
        out += ((i>0)?", ":"")+v;
      }
    }
    document.getElementById(this.idKey).value = out;
    this.show(0);
  },

  _loadTextBlock: function(id){
     if((typeof tinyMCE != "undefined") && tinyMCE.get(id) && !tinyMCE.get(id).isHidden()){
        this.textBlock = tinyMCE.get(id).getContent().replace(/<br \/>/g,"\n");
        if(this.tagRemove){this.textBlock = this.textBlock.replace(/<.+?>/g," ");}
     }else{
        this.textBlock = document.getElementById(id).value;
        if(this.tagRemove){this.textBlock = this.textBlock.replace(/\[.+?\]/g,"");}
     }
     this.textBlock = this.textBlock.replace(/(^\s+|\s+$)/g,'').replace(/[.;-?=!, \r\n\t]+/gi,' ');
     this.textBlockList = this.textBlock.split(' ');
     this.wordCount = this.textBlockList.length;
     if(this.wdFrame){
       this._getElement(this.wdFrame.firstChild,"wdFrameHeadText", true).innerHTML = "Wortdichte <small>("+this.wordCount+" w&ouml;rter)</small>";
     }
  }

}