var taglib = {

  svc: "http://www.huebsch-gemacht.de/radwege/tags/tagsvc.php",

  getAllTags: function(gotTagsFunc) {
    var r = this._asyncRequest("getAllTags", "");
    r.onreadystatechange = function () {
      if (r.readyState == 4) {
        var rt = r.responseText;
	var rx = eval("("+rt+")");
	gotTagsFunc(rx);
      }
    }
    r.send(null);
  },

  getTags: function(uri, gotTagsFunc) {
    var r = this._asyncRequest("getTags", "uri="+uri);
    r.onreadystatechange = function () {
      if (r.readyState == 4) {
        var rt = r.responseText;
	var rx = eval("("+rt+")");
	gotTagsFunc(rx);
      }
    }
    r.send(null);
  },

  getTagsSync: function(uri) {
    var r = this._syncRequest("getTags", "uri="+uri);
    r.send(null);
    var rt = r.responseText;
    var rx = eval("("+rt+")");
    return rx;
  },

  getURIs: function(tag, gotURIsFunc) {
    var r = this._asyncRequest("getURIs", "tag="+tag);
    r.onreadystatechange = function () {
      if (r.readyState == 4) {
        var rt = r.responseText;
	var rx = eval("("+rt+")");
	gotURIsFunc(rx);
      }
    }
    r.send(null);
  },

  createTag: function(tag, createdFunc) {
    var r = this._asyncRequest("createTag", "tag="+tag);
    r.onreadystatechange = function () {
      if (r.readyState == 4) {
        if (createdFunc)
          createdFunc(tag);
      }
    }
    r.send(null);
  },

  setTag: function(uri, tag, setDoneFunc) {
    var r = this._asyncRequest("setTag", "uri="+uri+"&tag="+tag);
    r.onreadystatechange = function () {
      if (r.readyState == 4) {
        if (setDoneFunc)
          setDoneFunc(uri, tag);
      }
    }
    r.send(null);
  },

  removeTag: function(uri, tag, removeDoneFunc) {
    var r = this._asyncRequest("removeTag", "uri="+uri+"&tag="+tag);
    r.onreadystatechange = function () {
      if (r.readyState == 4) {
        if (removeDoneFunc)
          removeDoneFunc(uri, tag);
      }
    }
    r.send(null);
  },

  _asyncRequest: function (request, params) {
    return this._request(request, params, true);
  },

  _syncRequest: function (request, params) {
    return this._request(request, params, false);
  },

  _request: function (request, params, async) {
    var xmlHttp = null;
    // Mozilla, Opera, Safari sowie Internet Explorer 7
    if (typeof XMLHttpRequest != 'undefined') {
        xmlHttp = new XMLHttpRequest();
    }
    if (!xmlHttp) {
        // Internet Explorer 6 und älter
        try {
            xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                xmlHttp  = null;
            }
        }
    }
    if (xmlHttp) {
        xmlHttp.open('POST', this.svc+"?op="+request+"&"+params, async);
    }
    return xmlHttp;
  }
};

function Positioner(_target) {
  this.target = _target;  
};

Positioner.prototype = {
  x: 0,
  y: 0,
  setPos:function(_x, _y) {
	this.x = _x;
	this.y = _y;
	if (this.target) {
		this.target.style['left'] = this.x+"px";
		this.target.style['top'] = this.y+"px";
	}
  },
  moveBy:function(_dx, _dy) {
  	this.setPos(this.x+_dx, this.y+_dy);
  },
};

function $(id) {
    return document.getElementById(id);
}

function array_contains(a, element) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] == element) {
       return true;
    }
  }
  return false;
};

function getAllTags(renderfunc) {
  taglib.getAllTags(renderfunc);
}

function getTags(uri, renderfunc) {
  taglib.getTags(uri, renderfunc);
}

function createTag(tag, target) {
  taglib.createTag(tag, function createDoneFunc(tag) {
    getAllTags(function getAllTagsDone(tags) {
      getTagsDone("", tags, target);
    });
  });
}

function setTag(uri, callbackfunc) {
  var curTags = taglib.getTagsSync(uri);
  taglib.getAllTags(function f(tags) {
	// d1 Top-Level
	// d2 Titelzeile
	// d3 titel text
	// d4 x-button
	// d5 eintraege
        var d1 = $(uri+"tagdiv");
	if (d1) {
		document.body.removeChild(d1);
	}
	d1 = document.createElement("div");
	d1.id=uri+"tagdiv";
	d1.positioner = new Positioner(d1);
	d1.className = "windowBody";

	d2 = document.createElement("div");
	d2.className = "windowCaption";
	d2.onmousedown = function f(evt) {
		gblPositioner = d1.positioner;
	}

	d3 = document.createElement("div");
	d3.className = "windowTitle";
	tn = document.createTextNode("Tag zuweisen");
	d3.appendChild(tn);
	d2.appendChild(d3);

	d4 = document.createElement("div");
	sp = document.createElement("span");
	d4.className = "windowClose";
	tn = document.createTextNode("x");
	sp.onmousedown = function f(evt) {
		document.body.removeChild(d1);
	}
	sp.appendChild(tn);
	d4.appendChild(sp);
	d2.appendChild(d4);
	d1.appendChild(d2);

        for (var tagpos in tags) {
	  var val = tags[tagpos];
	  if (array_contains(curTags, val))
	    continue;
	  d5 = document.createElement("span");
	  d5.className = "windowEntry pointer";
	  var sp = document.createElement("span");
	  sp.target = uri;
	  sp.txt = tags[tagpos];
	  tn = document.createTextNode(tags[tagpos]);
	  sp.appendChild(tn);
          sp.onmousedown = callbackfunc;
	  d5.appendChild(sp);
	  d1.appendChild(d5);
	  tn = document.createTextNode(" ");
	  d1.appendChild(tn);
	}

/*
	d6 = document.createElement("div");
	fn = document.createElement("form");
	fn.id = uri+"tagdivform";
	var tx = document.createElement("input");
	tx.id = "tag";
	fn.appendChild(tx);
	bn = document.createElement("button");
	bn.onclick = function (evt) {
		createTag(tx.value, $('tags'));
	};
	fn.appendChild(bn);
	d6.appendChild(fn);
	d1.appendChild(d6);
*/

	document.body.appendChild(d1);
	d1.positioner.setPos(gblMouseX, gblMouseY);
  });
}

function removeTag(uri, tag, target) {
  taglib.removeTag(uri, tag, function setReallyDone(uri, tag) {
		getTags(uri, function render(tags) { getTagsDone(uri, tags, $(target));});
  });
}

function showURIs(tag, callbackfunc) {
  taglib.getURIs(tag, function f(taglist) {
        var d1 = $(tag+"uridiv");
	if (d1) {
		document.body.removeChild(d1);
	}
	d1 = document.createElement("div");
	d1.id=tag+"uridiv";
	d1.positioner = new Positioner(d1);
	d1.className = "windowBody";

	d2 = document.createElement("div");
	d2.className = "windowCaption";
	d2.onmousedown = function f(evt) {
		gblPositioner = d1.positioner;
	}

	d3 = document.createElement("div");
	d3.className = "windowTitle";
	tn = document.createTextNode(tag);
	d3.appendChild(tn);
	d2.appendChild(d3);

	d4 = document.createElement("div");
	sp = document.createElement("span");
	sp.className = "windowClose";
	tn = document.createTextNode("x");
	sp.onclick = function f(evt) {
		document.body.removeChild(d1);
	}
	sp.appendChild(tn);
	d4.appendChild(sp);
	d2.appendChild(d4);
	d1.appendChild(d2);

        for (var tagpos in taglist) {
	  var val = taglist[tagpos];
	  d5 = document.createElement("div");
	  d5.className = "windowEntry";
	  var sp = document.createElement("span");
	  sp.target = tag;
	  tn = document.createTextNode(val);
	  sp.appendChild(tn);
	  d5.appendChild(sp);
	  d1.appendChild(d5);
	}



	document.body.appendChild(d1);
	d1.positioner.setPos(gblMousePos.pageX, gblMousePos.pageY);
  });
}


var gblMouseDown = false, gblMouseDownPos = null, gblMousePos = null;
var glbMouseX = 0, gblMouseY = 0;

document.onmousedown=function f(evt) {
	gblMouseDownPos = evt;
	gblMouseDown = true;
	if('undefined'!=typeof evt.pageX) {
		gblMouseX = evt.pageX;
		gblMouseY = evt.pageY;
	}
	else
	{
		gblMouseX = evt.clientX + document.body.scrollLeft;
		gblMouseY = evt.clientY + document.body.scrollTop;
	}
};

document.onmouseup=function f(evt) {
	gblMouseDownPos = null;
	gblMouseDown = false;
	gblPositioner = null;
};

document.onmousemove=function f(evt) {
	gblMousePos = evt;
	if (gblMouseDown && gblPositioner) {
		if('undefined'!=typeof evt.pageX) {
			mouseX = evt.pageX;
			mouseY = evt.pageY;
		}
		else
		{
			mouseX = evt.clientX + document.body.scrollLeft;
			mouseY = evt.clientY + document.body.scrollTop;
		}

		var deltaX = mouseX - gblMouseX;
		var deltaY = mouseY - gblMouseY;
		gblPositioner.moveBy(deltaX, deltaY);
		gblMouseDownPos = evt;
		gblMouseX = mouseX;
		gblMouseY = mouseY;
	}
}

function _target(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}

function setTagDone(evt) {
	var t = _target(evt);
	taglib.setTag(t.target, t.txt, function setReallyDone(uri, tag) {
		getTags(t.target, function render(tags) { getTagsDone(t.target, tags, $(t.target));});
	});
	document.body.removeChild($(t.target+"tagdiv"));
}
         
//echo "<a href=\"tagpage.php?tag=$tag\">$tag</a>";
//echo "<span class=\"pointer\" onclick='removeTag(\"$uri\", \"$tag\", \"$uri\")'>*</span>";

function getTagsDone(uri, tags, target) {
	var l = target.childNodes.length;
	for (var nodepos=0; nodepos < l; nodepos++) {
	  target.removeChild(target.childNodes[0]);
	}
	var first = 1;
	if (!tags) {
	  tn = document.createTextNode("keine ");
	  target.appendChild(tn);
	} else {
        for (var tagpos in tags) {
          var tag = tags[tagpos];
	  if (first == 1) {
	    first = 0;
          } else {
	    tn = document.createTextNode(", ");
	    target.appendChild(tn);
	  }
	  var  a = document.createElement("a");
	  a.href = "tagpage.php?tag="+tag;
	  var tn = document.createTextNode(tag);
	  a.appendChild(tn);
	  target.appendChild(a);

	  var sp = document.createElement("span");
	  var tn = document.createTextNode("*");
          sp.target = uri;
	  sp.txt = tag;
	  sp.className = "pointer";
	  sp.appendChild(tn);
          //opera.postError(tag);
          callback = function f(evt) { 
	  	var t = _target(evt);
		removeTag(t.target, t.txt, t.target);
	  };
	  sp.onclick = callback;
	  target.appendChild(sp);
/*
	  var sp = document.createElement("span");
	  var tn = document.createTextNode(tag);
          sp.target = tag;
	  sp.appendChild(tn);
          //opera.postError(tag);
          callback = function f(evt) { 
		t = this.target;
		showURIs(t, null);
	  };
	  sp.onclick = callback;
	  target.appendChild(sp);
*/
	}
	}
}


