(function() {

	tinymce.create('tinymce.plugins.SNStuff', {
        
//// ImageUpload
		init : function(ed, url) {
			ed.onInit.add(function() {
				if (ed.settings.content_css !== false)
					ed.dom.loadCSS(url + "/css/content.css");
				});

			ed.addCommand('mceSNImages', function() {
				ed.windowManager.open({
					file : url + '/html/image.html',
					width : 490,
					height : 550,
					inline : 1
				}, {
					plugin_url : url
				});
			});
			
			ed.addButton('snimages', {
				title : 'snstuff.img_desc',
				cmd : 'mceSNImages',
				image : url + '/images/insert-image.png'
			});
			
			ed.onNodeChange.add(function(ed, cm, n) {
				cm.setActive('snimages', n.nodeName == 'IMG');
			});
		

/// Link
		ed.addCommand('mceSNLink', function() {
				ed.windowManager.open({
					file : url + '/html/link.html',
					width : 500 + parseInt(ed.getLang('snstuff.snlink_delta_width', 0)),
					height : 180 + parseInt(ed.getLang('snstuff.snlink_delta_height', 0)),
					inline : 1
				}, {
					plugin_url : url
				});
			});

		ed.addButton('snlink', {title : 'snstuff.lnk_desc', cmd : 'mceSNLink', image: url+'/images/insert-link.png'});

		ed.onNodeChange.add(function(ed, cm, n) {
                                        cm.setActive('snlink', false);
					var node = n;
					while(node != null){
						if(node.nodeName == 'A'){
							cm.setActive('snlink', true);
							break;
						}
						node = node.parentNode;
					}
				});


/// Code
		ed.addCommand('mceSNCode', function() {

			handleSNCode(ed,url);

			});
		ed.addButton('sncode', {title : 'snstuff.code_desc', cmd : 'mceSNCode', image: url+'/images/code-context.png'});

		ed.onNodeChange.add(function(ed, cm, n) {
					cm.setActive('sncode', n.nodeName == 'CODE');
				});

/// Infobox
		ed.addCommand('mceSNInfoBox', function() { handleSNInfoBox(ed, url)});
		ed.addCommand('mceSNInfoBoxHead', function() { handleSNInfoBoxHead(ed, url) });
		

		ed.addButton('sninfobox', {title : 'snstuff.infobox_desc', cmd : 'mceSNInfoBox', image: url+'/images/textinfo.png'});
		ed.addButton('sninfoboxhead', {title : 'snstuff.infoboxhead_desc', cmd : 'mceSNInfoBoxHead', image: url+'/images/textinfo_head.png'});
		

		ed.onNodeChange.add(function(ed, cm, n) {
		  var scas = ed.dom.getParent(ed.selection.getStart(), function(n) {return ed.dom.hasClass(n, "snInfoBox");}) != null;
		  var scae = ed.dom.getParent(ed.selection.getEnd(), function(n) {return ed.dom.hasClass(n, "snInfoBox");}) != null;
                  var sca = scas && scae;
                  var scbs = ed.dom.getParent(ed.selection.getStart(), function(n) {return ed.dom.hasClass(n, "snInfoBoxHead");}) != null;
		  var scbe = ed.dom.getParent(ed.selection.getStart(), function(n) {return ed.dom.hasClass(n, "snInfoBoxHead");}) != null;
		  var scb = scbs && scbe;

                  var cs = ed.selection.getContent().length > 0;
		  cm.setDisabled('sninfobox', scae != scas);
		  cm.setDisabled('sninfoboxhead', (!((sca && cs) || scb) || scae != scas));
		  cm.setActive('sninfobox', sca);                  
		  cm.setActive('sninfoboxhead', scb);
                });

/// Quote
		ed.addCommand('mceSNQuote', function() {

			handleSNQuote(ed,url);

			});
		ed.addButton('snquote', {title : 'snstuff.quote_desc', cmd : 'mceSNQuote', image: url+'/images/quote.png'});

		ed.onNodeChange.add(function(ed, cm, n) {

					cm.setActive('snquote', n.nodeName == 'BLOCKQUOTE');
				});

/// LinkVorschlag
		Proposals.url = url;
		ed.addCommand('mceSNProposals', function(ui,v) {
			Proposals.findWordAll(ed);
		  });
		ed.onKeyUp.add(
			function(ed,e){
				var an = ed.dom.getParent(ed.selection.getNode(),function(n){return n.nodeName == 'A'});
				if(an == null && e.keyCode == 32){
					var cm = ed.selection.getBookmark();
					var ps = ed.dom.get(cm.id+'_start').previousSibling;
					var pos = ps.nodeValue.length;
					ed.selection.moveToBookmark(cm);
					Proposals.findWord(ed,ps,pos);
				}else{
					Proposals.closeWin();
				}
			}
		);
		ed.addButton('snproposals', {title : 'snstuff.proposals_desc', cmd : 'mceSNProposals', image: url+'/images/proposals.png'});
		
	ed.onLoadContent.add( SNStuffContentCounter.counter );
	ed.onChange.add( SNStuffContentCounter.counter );
	ed.onUndo.add( SNStuffContentCounter.counter );
	ed.onRedo.add( SNStuffContentCounter.counter );
	
	ed.onKeyPress.add( SNStuffContentCounter.counter );
	
	
	 }, // init


///////////////////////////////////////

		getInfo : function() {
			return {
				longname : 'SN-Stuff (ImageUpload, Quote, Code, Link, etc.)',
				author : 'Member from .de',
				authorurl : 'http://www..de',
				infourl : 'http://www..de',
				version : "1.0"
			};
		}
	});
	
	tinymce.PluginManager.add('snstuff', tinymce.plugins.SNStuff);
})();

 

////////////////////////////////////////////////////
var Proposals = {
  url: '',
//   ajaxBlock: tinyMCE.activeEditor.getParam("snstuff_proposals_ajax_block"),
//   ajaxLink: tinyMCE.activeEditor.getParam("snstuff_proposals_ajax_link"),

//   ajaxBlock: "/ajax_block",
//   ajaxLink: "/ajax_link",
  proposalsFrame: undefined,
  proposalsFrameBody: undefined,
  proposalsFrameId: Math.round(Math.random()*1000),

  running: false,
  cancel: function(){
    if(this.running){
	this.running = false;
    }
  },

  findWord: function(ed, node,pos){
    running = true;
    var ntn = node;
    var word;
    var txt = node.nodeValue.substr(0,pos);
    word = txt.replace(/ $/,'').split(/ /).pop();
     if(word.length > 0){
      this.getProposals(ed,ntn, word, pos, false);
     }
  },// find word

  findWordAll: function(ed){
    running = true;
    var wl = new Array();
    this._getContentWordList(ed.getBody(),wl);
    this.getProposals(ed,null,wl.join('+'),-1,true);
  },

  getProposals: function(ed,node, word, pos, block){
    var po = this;
    if(!running){return;}

    tinymce.util.XHR.send({
	  url : block ?  tinyMCE.activeEditor.getParam("snstuff_proposals_ajax_block", "/ajax_block") 
			: tinyMCE.activeEditor.getParam("snstuff_proposals_ajax_link","/ajax_link"),
	  content_type : "application/json",
	  type : "POST",
	  data : block ? "sn_msgbody="+escape(word) : "sn_key="+escape(word),
	  async : true,
	  scope : po,
	  
	  success : function( data, req, o ) {
	      var obj =  tinymce.util.JSON.parse(data);
	      po.showProposals(obj, ed, node, pos, block);
	  },
	  
	  error : function( type, req, o ){ alert("ERROR:"+type+"\n"+req+" - "+o);}
      });
  },

  closeWin: function(){
    this.cancel();
    if(this.proposalsFrame && this.proposalsFrame.style.display != 'none'){
      this.proposalsFrame.style.display = 'none';
    }
  },
  showProposals:function(obj, ed, node, pos, block){
  if(!running){return;}
  // remove used Lnk
    tinymce.grep(ed.dom.select("a"), function(n) {
	var h = n.getAttributeNode('href');
	if(h != null){
	  var v = h.nodeValue;
	  for(var e in obj){
	    if(v == obj[e].Link){
	      delete obj[e];
	    }
	  }
	}
    });

    if(!this.proposalsFrame){this._buildFrame();}
    
    var pf = this.proposalsFrameBody;
    while(pf.hasChildNodes()){
      pf.removeChild(pf.firstChild);
    }
    if(!obj){return;}
    for(var i = 0; i < obj.length; i++){
      if(!obj[i]){continue;}

      var o = obj[i];
      var bgColor = (i%2 == 0) ? "#FFFAB3":"#FFFE9A";
      var root = this._buildHTMLElement("DIV","lnkBody_"+i,"border-bottom:black 1px solid;background-color:"+bgColor);
      var lnk = this._buildHTMLElement("IMG","lnkLnk_"+i,"float:right;cursor:pointer");
      var desc = this._buildHTMLElement("DIV", "lnkDesc_"+i, "",o.Comment);
      var prevLnk = this._buildHTMLElement("A","lnkPrevLnk_"+i,"", o.Link);
      var keyword = this._buildHTMLElement("DIV","lnkKeyWord_"+i, "font-weight:bold", o.Key);
      var small = this._buildHTMLElement("SMALL","lnkSmall_"+i);
      small.appendChild(prevLnk);
      lnk.src = this.url+"/images/add.png";
      lnk.alt = "Link einfügen";
      lnk.title = "Das Wort \""+o.Key+"\" im Text verlinken";
      prevLnk.href = o.Link;
      prevLnk.target = "blank";
      
      root.appendChild(keyword); keyword.appendChild(lnk); root.appendChild(desc);root.appendChild(small);
      this._setOnclickEvent(lnk, {obj:o,block:block,ed:ed,node:node,pos:pos});
      pf.appendChild(root);
    }
    if(this.proposalsFrameBody.hasChildNodes()){
	this.proposalsFrame.style.display = "block";
    }
  },
  _setOnclickEvent:function(lnk, o){
	var p = this;
	lnk.onclick = function(){p._insertAction(o,this)};
    },
  _insertAction:function(o,fn){
    if(!o.block){
      this._insertLink(o);
      this.closeWin();
    }else{
      var fw = this._findWord(o.ed.getBody(),o.obj.Key);
      if(fw){
	this._insertLink(fw.node,fw.pos,o.obj.Link,o.ed);      
	var pe = fn.parentNode.parentNode;
	pe.parentNode.removeChild(pe);
	if(!this.proposalsFrameBody.hasChildNodes()){
	  this.proposalsFrame.style.display = "none";
	}
      }
    }    
  },

  _insertLink: function(o){
    var node = o.node; var pos = o.pos; var lnk = o.obj.Link; var ed = o.ed;
    
    var nv = node.nodeValue;
    var pre = nv.substring(0,pos).replace(/ $/,'').split(/ /);
    var post = " "+nv.substr(pos);
    var w = pre.pop();
    var a = ed.getDoc().createElement('A');
    var ha = ed.getDoc().createAttribute("href");
    var tit = ed.getDoc().createAttribute("title");
    
    tit.nodeValue=o.obj.Comment;
    ha.nodeValue = lnk;
    a.setAttributeNode(ha);
    a.setAttributeNode(tit);
    a.appendChild(ed.getDoc().createTextNode(w));

    var pnode = node.parentNode;
    
    tinyMCE.execCommand("mceBeginUndoLevel");
    pnode.insertBefore(ed.getDoc().createTextNode(pre.join(' ')+' '),node);
    pnode.insertBefore(a,node);
    pnode.insertBefore(ed.getDoc().createTextNode(post),node);
    pnode.removeChild(node);
    tinyMCE.execCommand("mceEndUndoLevel");
    ed.focus();
    ed.selection.select(a);
    ed.selection.collapse();
  },

  _findWord: function(doc, word){
    var node = doc;
    var w;
    while(node != null){
      if(node.nodeType == 1 && node.nodeName != "A"){
	  w = this._findWord(node.firstChild,word);
	  if(w){ return w;}
	}
      
      if(node.nodeType == 3){
	var txt = node.nodeValue.toLowerCase();
	var p = txt.indexOf(word.toLowerCase());
	if(p != -1){
	  return {pos:p+word.length, node: node};
	}
      }
    node = node.nextSibling;
    }
    return w;
  },

  _getContentWordList: function(doc, wlist){
    var node = doc;
  
    while(node != null){
      if(node.nodeType == 1 && node.nodeName != "A"){
	this._getContentWordList(node.firstChild, wlist);
      }
    
      if(node.nodeType == 3){
	var lst = node.nodeValue.split(/ /);
	while(lst.length > 0){
	  var s = lst.pop().replace(/\s/g,"");
	  if(s != ""){
	    wlist.push(s);
	  }
	}
      }
      node = node.nextSibling;
    }
  },
///////////////////////
  _buildFrame: function(){
    var container = tinyMCE.activeEditor.getContentAreaContainer();
    var ot = container.offsetTop;
    var ol = container.offsetLeft + container.offsetWidth;

    if(document.getElementsByTagName("body")[0].offsetWidth < ol+355){
      ol = document.getElementsByTagName("body")[0].offsetWidth - 360;
    }

    var pa = (document.all) ? "absolute":"fixed";

    var p = this._buildHTMLElement("DIV", "proposalsFrame","position:"+pa+";width:350px;left:"+ol+"px;top:"+ot+"px;padding:5px;background-color:#FFFE9A;border:solid black 1px;");
    var h = this._buildHTMLElement("DIV", "proposalsFrameHead","border-bottom:black 1px solid;font-weight:bold;background-color:#FFF27A;cursor:pointer;padding:2px;","Tipps zum Thema");
    var b = this._buildHTMLElement("DIV", "proposalsFrameBody","min-height:100px;max-height:300px;overflow:auto;padding:5px;");
    var c = this._buildHTMLElement("IMG", "proposalsFrameClose","float:right");


    h.onmousedown = function(){
		      var p = this.parentNode;
		      var ox,oy;
		      this.onmouseup = function(){p.onmousemove = function(){}; p.onmouseout = function(){}}
		      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;
		    }

  var me = this;
  c.onclick = function(){me.closeWin()};

  c.alt = "X";
  c.src = this.url+'/images/close.png';
  c.alt = "Fenster schlissen";
  c.title = "Fenster schliessen";

  h.insertBefore(c,h.firstChild);
  p.appendChild(h); p.appendChild(b)

  this.proposalsFrame = p;
  this.proposalsFrameBody = b;

  document.getElementsByTagName("body")[0].appendChild(p);
  },

  _buildHTMLElement: function(n, id, style, txt){
    var e = document.createElement(n);
    var an = document.createAttribute("id");
    an.nodeValue = id+"_"+this.proposalsFrameId;
    var clazz = document.createAttribute("class");
    clazz.nodeValue = id;
    e.setAttributeNode(clazz);
    e.setAttributeNode(an);
  
    e.style.cssText = style;
    if(txt){ e.appendChild( document.createTextNode(txt)); }
    return e;
  }
}


//////////////////////////////////////////////////
function handleSNCode(ed, url){
  var enode = ed.selection.getNode();
  var sel = ed.selection.getContent();
  var isBlock = (enode != null && enode.nodeName == 'CODE');

  if(isBlock){

    // Remove element
    if(enode.nodeName == 'CODE'){
      tinyMCE.execCommand("mceBeginUndoLevel");
      i = ed.selection.getBookmark();
      ed.dom.remove(enode, 1);
      ed.selection.moveToBookmark(i);
      tinyMCE.execCommand("mceEndUndoLevel");
      return;
    }
  }

  tinyMCE.execCommand("mceBeginUndoLevel");
  
  if(sel.length == 0 ){

    ed.windowManager.open({
	  file : url + '/html/code.html',
	  width : 410 + parseInt(ed.getLang('snstuff.snlink_delta_width', 0)),
	  height : 480 + parseInt(ed.getLang('snstuff.snlink_delta_height', 0)),
	  inline : 1
	}, {
	  plugin_url : url
	});
  }else{
    ed.execCommand('mceInsertContent', false, '<code>'+ed.selection.getContent()+'</code>', {skip_undo : 1});
  }
  tinyMCE.execCommand("mceEndUndoLevel");
  
}

function handleSNQuote(ed, url){
  var enode = ed.selection.getNode();
  var sel = ed.selection.getContent();
  var isBlock = (enode != null && enode.nodeName == 'BLOCKQUOTE');

  if(isBlock){

    // Remove element
    if(enode.nodeName == 'BLOCKQUOTE'){
      tinyMCE.execCommand("mceBeginUndoLevel");
      i = ed.selection.getBookmark();
      ed.dom.remove(enode, 1);
      ed.selection.moveToBookmark(i);
      tinyMCE.execCommand("mceEndUndoLevel");
      return;
    }
  }

  tinyMCE.execCommand("mceBeginUndoLevel");
  
  if(sel.length == 0 ){

    ed.windowManager.open({
	  file : url + '/html/quote.html',
	  width : 410 + parseInt(ed.getLang('snstuff.snquote_delta_width', 0)),
	  height : 480 + parseInt(ed.getLang('snstuff.snquote_delta_height', 0)),
	  inline : 1
	}, {
	  plugin_url : url
	});
  }else{
    ed.execCommand('mceInsertContent', false, '<blockquote>'+ed.selection.getContent()+'</blockquote>', {skip_undo : 1});
  }
  tinyMCE.execCommand("mceEndUndoLevel");
  
}


function handleSNInfoBox(ed, url){
  var enode = ed.selection.getNode();
  var sel = ed.selection.getContent();

    ed.windowManager.open({
	  file : url + '/html/infobox.html',
	  width : 250+ parseInt(ed.getLang('snstuff.snquote_delta_width', 0)),
	  height : 100 + parseInt(ed.getLang('snstuff.snquote_delta_height', 0)),
	  inline : 1
	}, {
	  node: enode,
	  plugin_url : url
	});
}

function handleSNInfoBoxHead(ed, url){
  var enode = ed.dom.getParent(ed.selection.getNode(), function(n) {return ed.dom.hasClass(n, "snInfoBoxHead");})
  var sel = ed.selection.getContent();

    tinyMCE.execCommand("mceBeginUndoLevel");
    if(sel.length > 0){
      ed.execCommand('mceInsertRawHTML', false, '<span id="__snInfoBoxHeadTmp">'+ed.selection.getContent()+'</span>',{skip_undo : 1});
      ed.dom.setAttribs('__snInfoBoxHeadTmp', {style:"", class:"snInfoBoxHead"});
      ed.dom.setAttrib('__snInfoBoxHeadTmp', 'id', '');
    }else{
      i = ed.selection.getBookmark();
      ed.dom.remove(enode, 1);
      ed.selection.moveToBookmark(i);
    }
    tinyMCE.execCommand("mceEndUndoLevel");
}
/////////////////////////////////////////////////

SNStuffContentCounter = {
    elm: Array(),
    
    isInit:false,
    init: function(ed){
    
      var elm = ed.getParam("snstuff_contentcounter","").replace(/ /g,"").split(",");
      for(var e = 0; e < elm.length; e++){
	var l = new Object();
	
	var cv = ed.getParam("snstuff_charcolor_"+elm[e],"none").replace(/ /g,"");
	
	if(cv != "none"){
	  var a = new Array();
	  cc = cv.split(",");
	  for(var cci = 0; cci < cc.length; cci++){
	    var v = cc[cci].split(":");
	    a.push({v:v[0],c:v[1]});
	  }
	  l.c = a.sort(function(a,b){return a.v-b.v});
	}
      
	var wv = ed.getParam("snstuff_wordcolor_"+elm[e],"none").replace(/ /g,"");
	
	if(wv != "none"){
	  var a = new Array();
	  wc = wv.split(",");
	  for(var wci = 0; wci < wc.length; wci++){
	    var v = wc[wci].split(":");
	    a.push({v:v[0],c:v[1]});
	  }
	  l.w = a.sort(function(a,b){return a.v-b.v});
	}
      
	this.elm[elm[e]] = l;
	
      }
      
    this.isInit = true;
    },
    
    counter : function(ed,e){
      if(!SNStuffContentCounter.isInit){
	SNStuffContentCounter.init(ed);
      }
      if(SNStuffContentCounter.elm[ed.id]){
	var c = ed.getContent().replace(/<br \/>/g," ").replace(/<.+?>/g,"").replace(/ {1,}/g," ").replace(/^ | $/g,"");
	var cl = c.length;
	var wl = c.split(" ").length;
	var p = tinymce.DOM.get(ed.id + '_path_row');
	html = "";
	
	var cvl = SNStuffContentCounter.elm[ed.id];
	if(cvl.c){
	  var col = "";
	  for(var i = 0; i < cvl.c.length; i++){
	    if(cl > cvl.c[i].v){
	      col = "color:"+cvl.c[i].c;
	    }
	  }
	  html += ' <span style="'+col+'"> Zeichen:'+cl+' </span> ';
	}
	
	if(cvl.w){
	  
	  var col = "";
	  for(var i = 0; i < cvl.w.length; i++){
	    if(wl > cvl.w[i].v){
	      col = "color:"+cvl.w[i].c;
	    }
	  }
	  html += ' <span style="'+col+'"> W&ouml;rter:'+wl+' </span> ';
	}
	tinymce.DOM.setHTML(p,html);
      }
    }
}



