
// ExtJs might have added this already, but if not, we add our own
if(typeof Function.prototype.createDelegate == "undefined") {
    Function.prototype.createDelegate = function(obj, args) {
	var method = this;
	return function() {
	    return method.apply(obj || window, arguments);
	};
    }
}

function TagIt(config) {
  this.defaults = {icon:       'http://tagit.se/img/minilogo.png',
		   icon_sx:    16,
		   icon_sy:    16,
		   text:       "TagIt",  
		   noIcon:     false,
		   url:        document.location.href,
		   font:       "Arial, Verdana, sans",
		   fontSize:   "11px",
		   fontColor:  "white",
		   textAlign:  "center",
		   rows: 3,
		   cols: 4,
		   site_icons: true,
		   site_width: 88,
		   site_height:16,
		   show_event: 'mouseover',  // or 'click'
		   element:    "put_tagit_here",
		   newWindow:  true,
		   alwaysOpen: false,
		   background: '#1276ef',
		   className: false,
		   addTags: false,
		   tags: false,  // false=Get automatically from meta keywords tag
		   sites:  false, // all!
		   tagName: "SPAN"};

  this.config = config;
  if(this.config.className) {
      // Use the tagName/className to find tags 
      var els = document.getElementsByTagName(this.config.tagName?this.config.tagName:this.defaults.tagName);
      var cls = this.config.className;
      for(var i=0; i<els.length; i++) {
	  if((' '+els[i].className+' ').indexOf(cls) != -1) {
	      var opts = this.config;
	      var a=function() {
		  var el = els[i];
		  opts.element = el;
		  opts.className = false;
		  opts.url = el.getAttribute("href") ? el.getAttribute("href") : "xxxxx";
		  opts.tags = el.getAttribute("tags") ? el.getAttribute("tags") : false;
		  var t2 = new TagIt(opts);
		  t2.init();
	      }.apply();
	  }
      }
  }


  this.availSites = [
	       {title:"Pusha",
		id: 1,
		name: "pusha"},

	       {title:"Bloggy",
		id: 2,
		name: "bloggy"},

	       {title:"Facebook",
		id: 3,
		name:"facebook"},

	       {title:"Twitter",
		id: 4,
		name: "twitter"},

	       {title:"Digg",
		id: 5,
		name:"digg"},

	       {title:"StumbleUpon",
		id: 6,
		name:"stumbleupon"},

	       {title:"Del.icio.us",
		id: 7,
		name:"delicious"},

	       {title:"MySpace",
		id: 8,
		name:"myspace"},

	       {title:"Google",
		id: 9,
		name:"google"},

	       {title:"Live",
		id: 10,
		name:"live"},

	       {title:"Blogspot",
		id: 11,
		name:"blogspot"},

	       {title:"Add2Any",
		id: 12,
		name:"add2any"}

	       ];

  this.getSite = function(sn) {
      for(var an in this.availSites) {
	  if(this.availSites[an].name==sn)
	      return this.availSites[an];
      }
      return false;
  }

 this.init = function() {
    for(var v in this.defaults) {
      if(typeof this.config[v] != "undefined") {
	this[v] = this.config[v];
      }
      else
	this[v] = this.defaults[v];
    }
    if(!this.sites) {
	this.sites = this.availSites;
    } else {
	var sits = [];
	for(var sn in this.sites) {
	    var s = this.getSite(this.sites[sn]);
	    if(s)
		sits[sits.length] = s;
	}
	this.sites = sits;
    }

    if(typeof(this.element) == "string")
	this.element = document.getElementById(this.element);

    if(!this.noIcon) {
	this.iconElement = document.createElement("img");
	this.iconElement.setAttribute("class",  "tagit_icon");
	this.iconElement.setAttribute("src",    this.icon);
	this.iconElement.setAttribute("width",  this.icon_sx);
	this.iconElement.setAttribute("height", this.icon_sy);
	this.iconElement.setAttribute("border", "0");
	this.iconElement.setAttribute("style",  "cursor:pointer");
    }
    else if(this.text) {
	this.iconElement = document.createElement("a");
	this.iconElement.setAttribute("class",  "tagit_icon");
	this.iconElement.setAttribute("style",  "cursor:pointer");
	this.iconElement.innerHTML = this.text;
    }

     if(!this.showDelegate)
	 this.showDelegate = this.show.createDelegate(this);

    if(this.iconElement) {
	t_aE(this.iconElement, this.show_event, this.showDelegate, false);

	this.element.appendChild(this.iconElement);
	this.hT=false;
    }

    if(this.alwaysOpen)
	this.show(true);
 };

 this.selectMany = function()
 {
     for(var sn in this.ct.childNodes) {
	 var i = this.ct.childNodes[sn];
	 if(i.tagName == "A") {
	     for(var sn2 in i.childNodes) {
		 if(i.childNodes[sn2].tagName == "INPUT") {
		     if(i.childNodes[sn2].style.display=="none")
			 i.childNodes[sn2].style.display="block";
		     else
			 i.childNodes[sn2].style.display="none";
		 }
	     }
	 }
     }
 };

 this.getFontStyle = function() {
     return "font-family:"+this.font+";color:"+this.fontColor+"; font-size:"+this.fontSize+";";
 };

 this.siteElement = function(site, withTitle, ifr) {
     var astyle = "text-decoration:none;"+this.getFontStyle()+"width: "+this.site_width+"px; height:"+this.site_height+"px; border:none; display:inline; float:left; background-color: transparent; ";
     if(this.site_icons)
	 astyle += "background-image: url(http://s7.addthis.com/static/r07/widget01.png); background-repeat: no-repeat; margin-top: 1px; padding-left: 20px; ";
     if(!ifr) {
	 ifr = document.createElement("a");
	 with(ifr) {
	     setAttribute("style", astyle+"background-position: 0 -"+(site.id*16)+"px;");
	     setAttribute("site", site.name);
	     setAttribute("id", "tagit_site_"+site.name);
	     setAttribute("href", "javascript:void 0");
	     setAttribute("title", site.title);
	     if(withTitle)
		 appendChild( document.createTextNode(site.title) );
	 }
     }
     if(!this.tagDelegate)
	 this.tagDelegate  = this.tag.createDelegate(this);
     t_aE(ifr, "mouseover", this.showDelegate, false);
     t_aE(ifr, "click",     this.tagDelegate,  false);
     
     return ifr;
 };

 this.getKeywords = function() {
     if(this.tags)
	 return typeof(this.tags) == "string" ? this.tags : this.tags.join(" ");
     var metas = document.getElementsByTagName('meta');
     for(count=0;count<metas.length;count++){
	 if(metas[count].name.toLowerCase()=='keywords'){
	     var m=metas[count].content;
	     this.tags = m.split(/,\ /);
	     this.tags = this.tags.join(" ");
	     return this.tags;
	 }
     }
     return "";
 },

 this.show = function(evt) {
     if(!evt)
	 evt=window.event;
     if(!evt)
	 return;
     if(this.hT)
	 clearTimeout(this.hT);
     this.hT=false;

     if(this.vI)
	 return false;
     this.vI = true;

     this.dwidth = this.cols * (this.site_width + (this.site_icons?20:0));
     this.dheight = (this.rows * this.site_height) + 2 + (this.addTags?this.site_height:0);

     this.ct = document.createElement("div");
     this.ct.setAttribute("id", "tagit_div");
     this.ct.setAttribute("style", (this.iconElement ? 'position:absolute;' : '') + "overflow: hidden; display: block; text-align: "+this.textAlign+"; padding: 4px; margin:0px; width:"+this.dwidth+"px; height:"+this.dheight+"px; background-color:"+this.background);
     if(!this.alwaysOpen)
	 t_aE(this.ct, "mouseout",  this.hide.createDelegate(this), false);

     if(this.addTags) {
	 var lbl = document.createElement("div");
	 lbl.setAttribute("style", "float:left; height:"+this.site_height+";width: 25%; text-align:right; color:"+this.fontColor+";font-size:"+this.fontSize);
	 lbl.innerHTML="Ange taggar:";
	 this.ct.appendChild(lbl);
	 t_aE(lbl, "mouseover", this.showDelegate, false);

	 this.addTagsInput = document.createElement("input");
	 with (this.addTagsInput) {
	     setAttribute("type", "text");
	     setAttribute("style","height:"+this.site_height+";width: 72%; border:none; float:right; display: block; font-size:"+this.fontSize);
	     setAttribute("value", this.getKeywords());
	 }
	 t_aE(this.addTagsInput, "mouseover", this.showDelegate, false);
	 t_aE(this.addTagsInput, "blur", this.updateTags.createDelegate(this), false);
	 this.ct.appendChild(this.addTagsInput);
     }

     var mn = this.rows*this.cols;
     for(var sid in this.sites) {
	 if(this.sites[sid].id && mn-->0)
	     this.ct.appendChild(this.siteElement(this.sites[sid], true));
     }
     
     if(!this.noIcon)
	 this.iconElement.parentNode.appendChild(this.ct);
     else {
	 this.element.appendChild(this.ct);
     }
 };

 this.updateTags = function() {
     this.tags = this.addTagsInput.value;
 };

 this.hide = function(evt) {
   if (!evt) var evt = window.event;

   if(evt.originalTarget)
     if(evt.originalTarget.tagName == "A")
       return;

   var self=this;
   if(!this.hT) {
     this.hT = setTimeout(function() {self.close();}, 500);
   } else {
     this.close();
   }
 };

 this.close = function() {
   if(this.hT)
     clearTimeout(this.hT);
   this.hT = false;
   this.vI = false;
   if(this.ct)
     this.ct.parentNode.removeChild(this.ct);
   this.ct = undefined;
 };
 
 this.tag = function(elm) {
     var what = elm.target.getAttribute("site");
     if(!what)
	 return;
     var ua = new String(encodeURIComponent(navigator.userAgent.toLowerCase()));
     var str = new String("http://tagit.se/tag/"+
			  new String(what)+
			  "?from="+encodeURIComponent(this.url)+
			  "&tags="+encodeURIComponent(this.tags)+
			  "&ua="+ua.replace(/\ /, "%20"));
     if(this.newWindow == true) {
	 if(!window.open(str, "tagit_"+what)) {
	     alert("Please unblock the popup window and try again.");
	 }
     } else {
	 document.location = str;
     }
 };

}

/** "Universal addEvent function */
t_aE = function(el, eType, fn, uC) {
    if (el.addEventListener) {
	el.addEventListener(eType, fn, uC);
	return true;
    } else if (el.attachEvent) {
	return el.attachEvent('on' + eType, fn);
    } else {
	el['on' + eType] = fn;
    }
};




t_aE(window, "load", 
     function() {
	 if(el = document.getElementById("put_tagit_here")) {
	     var t = new TagIt({element: el});
	     t.init();
	 }

	 new TagIt({className: 'tagit'});
     });
