var BUFFED_DB_TT		= null;
var BUFFED_BASEURL		= {};
BUFFED_BASEURL['wow']   = {deDE:"http://wowdata.buffed.de/res/wow/tooltips/live/deDE", ruRU:"http://wowdata.buffed.ru/res/wow/tooltips/live/ruRU", enGB:"http://wowdata.getbuffed.com/res/wow/tooltips/live/enGB", deDEptr: "http://wowdata.buffed.de/res/wow/tooltips/test/deDE", cataclysm: "http://cataclysm.buffed.de/res/wow/tooltips/beta/deDE", iconPath: 'http://wowdata.buffed.de/res/wow/icons/40/'};
BUFFED_BASEURL['rom']   = {deDE:"http://romdata.buffed.de/res/rom/tooltips/deDE", enGB:"http://romdata.getbuffed.com/res/rom/tooltips/enUS", ruRU:"http://romdata.buffed.ru/res/rom/tooltips/ruRU", iconPath: 'http://romdata.buffed.de/res/rom/icons/40/'};
BUFFED_BASEURL['war']	= {deDE:"http://wardata.buffed.de/res/war/tooltips/deDE", ruRU:"http://wardata.buffed.ru/res/war/tooltips/ruRU", enGB:"http://wardata.getbuffed.com/res/war/tooltips/enGB", iconPath: 'http://wardata.buffed.de/res/war/icons/40/'};

BUFFED_DB_TOOLTIPS = function() {

	this.cache	= {};
	
	this.lastrequest_id 	= null;
	this.lastrequest_x  	= null;
	this.lastrequest_y		= null;

	this.browser 			= 'firefox';
	this.current_game		= 'wow';
	this.is_buffed_page		= null;
	this.is_buffed_de		= null;
	
	this.bfd_domains = {"buffed.de": 1, "buffed.ru": 1, "getbuffed.com": 1, "murloc2.ma": 1}; // FIXDEV
	
	this.fn_checkLocation = function() {
		var d_split = window.location.hostname.split('.');
		var d = window.location.hostname.replace(d_split[0] + '.', '');
		if(this.bfd_domains[d]) {
			this.is_buffed_page = true;
		}
		if(d == 'buffed.de') {
			this.is_buffed_de = true;
		}
	}
	
	this.fn_getBrowser = function() {
		if (navigator.appName=="Microsoft Internet Explorer") {
			this.browser = 'ie';
		} else if (navigator.userAgent.search(/Opera/)!=-1) {
			this.browser = 'opera';
		} else if (navigator.userAgent.search(/Safari/)!=-1) {
			this.browser = 'safari';
		} else {
			this.browser = 'firefox';
		}
		if(this.browser != 'safari' && navigator.appName=="Netscape") {
			this.browser = 'gecko';
		}
	}
	
	this.fn_addEventListener = function(obj, eventType, func) {
	
		if(obj.addEventListener) {
			obj.addEventListener(eventType, func, false);
			return true;
		} else if(obj.attachEvent) {
			var retVal=obj.attachEvent("on"+eventType, func);
			return retVal;
		} else {
			return false;
		}	
	}
	
	this.fn_loadHeaderData = function() {

		var h=document.getElementsByTagName("head")[0];
		if(!h) {h = document.getElementsByTagName("body")[0];}
		if(h) {
			var d = new Date();
			var stamp = d.getDay() + d.getMonth() + d.getFullYear();
			//var css_path = (this.is_buffed_de) ? '' : 'http://wowdata.buffed.de';
			var css_path = 'http://wowdata.buffed.de';
			//var css_path = ''; // FIXDEV
			
			var l=document.createElement("link");
			l.type="text/css";
			l.href=css_path+"/css/buffed-db-tooltip.css?v="+stamp;
			l.rel="stylesheet";
			h.appendChild(l);
		
			if(this.browser == 'ie') {
				var ie_l=document.createElement("link");
				ie_l.type="text/css";
				ie_l.href=css_path+"/css/buffed-ext-tooltip-ie.css";
				ie_l.rel="stylesheet";
				h.appendChild(ie_l);
			}
		}
		this.fn_addEventListener(document, "mouseover", this.fn_handleMouseover);
	}

	this.fn_handleMouseover = function(e) 
	{
        var t;

		if(!e) {e=window.event;}
		if(!(t=e.target?e.target:e.srcElement)) return;

		var count = 0;
	
		while(t && t.nodeName!="A" && t.nodeName!="a" && count < 4) {
			t=t.parentNode;
            count = count + 1;
		}
		if(!t || (t.nodeName!="A" && t.nodeName!="a") || !t.href.length) {
			return;
		}
		if(t.rel == "nott") {return;}

		var m=t.href.match(/^http:\/\/(\w+\.)?buffed\.(de|ru|es|fr|local)\/?\?(i|q|s|a)=([0-9]+)/);
		if(!m) {
			m=t.href.match(/^http:\/\/(\w+\.)?getbuffed\.(com)\/?\?(i|q|s|a)=([0-9]+)/);
		}
		if(!m) {
			m=t.href.match(/^http:\/\/(\w+\.)?murloc2\.(ma)\/?\?(i|q|s|a)=([0-9]+)/);
		}
	
		var type,id,domain = '',tld = '';
		if(m) {
			domain = m[1];tld = m[2];type = m[3];id = m[4];
		} else {
			var m2 = window.location.hostname.match(/^(\w+\.)?buffed\.(de|ru|es|fr)$/)
			if(!m2) {m2 = window.location.hostname.match(/^(\w+\.)?getbuffed\.(com)$/)}
			if (m2) {
				domain = m2[1];
				tld = m2[2];
				m=t.href.match(/^\/?\?(i|q|s|a)=([0-9]+)/);
				if(m) {
					type = m[1];id = m[2];
				}
			}
		}

        var ttid = t.rel.match(/TTID=(.*)/);
        if(ttid) {
            id = ttid[1];
        }
	
		if(!domain) return;

		var locale = 'deDE';
		switch(tld) {
			default: case 'de':
				switch(domain) {
					default:locale = 'deDE';break;
					case 'wowptr.':locale = 'deDEptr';break;
					case 'cataclysm.':locale = 'cataclysm';break;
				}
			break;
			case 'ru':locale = 'ruRU';break;
			case 'com':locale = 'enGB';break;
		}

		if(m) {
			if(t.title) {
				// Titel beißt sich mit Tooltip
				t.title = '';
			}
			if(!t.onmousemove) {
				t.onmousemove=BUFFED_DB_TT.fn_mousemove;
				t.onmouseout=BUFFED_DB_TT.fn_mouseout;
			}

			switch(domain) {
				default:return;break;
				case 'www.':
				case 'wowptr.':
				case 'cataclysm.':
				case 'devz2.':
				case 'devm.':
				case 'wowdata.':BUFFED_DB_TT.current_game = 'wow';break;
				case 'devr.':
				case 'romdata.':BUFFED_DB_TT.current_game = 'rom';break;
				case 'wardata.':BUFFED_DB_TT.current_game = 'war';break;
			}

			BUFFED_DB_TT.fn_show(locale, type, id, e, null, null, t);

			return;
		}
	}

	// Mouse & Window stuff
	this.fn_mousemove = function(event){
		BUFFED_DB_TT.fn_setTooltipPos(BUFFED_DB_TT.fn_getMousePos(event).x, BUFFED_DB_TT.fn_getMousePos(event).y);
	}

	this.fn_getMousePos = function(event, p_type) {

		var pos = {x:0,y:0};
		
		if(this.browser == 'ie') {
			pos.x = window.event.clientX;
			pos.y = window.event.clientY;
		}
		else {
			pos.x = event.pageX;
			pos.y = event.pageY;
		}

		return pos;
	}

	this.fn_mouseout = function(){
		BUFFED_DB_TT.lastrequest_id = null;
		BUFFED_DB_TT.fn_hide();
	}

	this.fn_hide = function() {
		var BUFFEDTT = document.getElementById("BUFFED_TOOLTIP");
		if(BUFFEDTT) {
			BUFFEDTT.style.visibility="hidden";
			BUFFEDTT.style.display="none";
		}
	}

	this.fn_show = function(locale, type, id, e, xpos, ypos, el) {

		if(!this.cache[this.current_game]) {
			this.cache[this.current_game] = [];
		}
		if(!this.cache[this.current_game][locale]) {
			this.cache[this.current_game][locale] = [];
		}	
		if(!this.cache[this.current_game][locale][type]) {
			this.cache[this.current_game][locale][type] = [];
		}	
		var current_cache = this.cache[this.current_game][locale][type];

		if(!current_cache[id]) {
			if(e) {
				this.lastrequest_id = id;
				this.lastrequest_x=this.fn_getMousePos(e).x;
				this.lastrequest_y=this.fn_getMousePos(e).y;

                this.fn_requestTooltip(type, id, locale);
            }

		} else {

			if(!current_cache[id]) {return;}

            var comp_ids, comp_tt = [], comp_stats = [], comp_box;
            if(typeof BUFFED_CHAR_COMP !=='undefined' && type == 'i') {
                var slot_id = current_cache[id].slot;
                var comp_ids = BUFFED_CHAR_COMP.getCompareIds(slot_id);

                for(var i = 0; i<comp_ids.length; i++) {
                    if(current_cache[comp_ids[i]]) {
                        comp_tt.push(current_cache[comp_ids[i]].tt);
                        comp_stats.push(current_cache[comp_ids[i]].stats || []);
                    } else {
                          this.fn_requestTooltip(type, comp_ids[i], locale);
                    }
                }
                comp_box = BUFFED_CHAR_COMP.getStatCompareBox(slot_id, current_cache[id].stats, comp_stats);
            }

			var tooltip = current_cache[id].tt;
			var icon = current_cache[id].icon;
			if(typeof icon == 'object' && icon != null) icon = icon[0];
			var ttdiv=document.getElementById("BUFFED_TOOLTIP");

			if(!ttdiv) {
				var b=document.getElementsByTagName("body")[0];
				if(!b) {return;}
				ttdiv=document.createElement("div");
				ttdiv.id="BUFFED_TOOLTIP";
				ttdiv.className = 'BUFFED_TOOLTIP';
				ttdiv.style.display="none";
				ttdiv.style.visibility="hidden";
				var inner_db_class = (this.current_game == 'war') ? 'db-war-tooltip' : 'db-tooltip';
				ttdiv.innerHTML = '<div class="'+inner_db_class+'">\n\
                        <table>\n\
                        <tr><td>\n\
                           <table><tr><td id="BUFFED_TOOLTIP_DATA"></td></tr></table>\n\
                         </td><th style="background-position: top right"></th></tr>\n\
                        <tr><th style="background-position: bottom left;text-align:left;" id="db-tooltip-footer"></th>\n\
                            <th style="background-position: bottom right"></th>\n\
                        </tr></table>\n\
                        <div id="BUFFED_TOOLTIP_ICON"></div>\n\
                        <div id="BUFFED_TOOLTIP_COMP1" class="db-tooltip">Hallo Welt</div>\n\
                        <div id="BUFFED_TOOLTIP_COMP2" class="db-tooltip">Hallo Welt</div>\n\
                        </div>';
				b.appendChild(ttdiv);
			}

            var cttdiv1 = document.getElementById("BUFFED_TOOLTIP_COMP1");
            if(cttdiv1) {
                cttdiv1.innerHTML = "";
            }
            var cttdiv2 = document.getElementById("BUFFED_TOOLTIP_COMP2");
            if(cttdiv2) {
                cttdiv2.innerHTML = "";
            }

			ttdiv.style.visibility="hidden";
			ttdiv.style.display="none";
	
			this.fn_setTooltipPos(0,0);

			document.getElementById("BUFFED_TOOLTIP_DATA").innerHTML=tooltip;
			document.getElementById("BUFFED_TOOLTIP_ICON").innerHTML="";
			if(this.current_game != 'war' && icon && icon != 'undefined') {
				document.getElementById("BUFFED_TOOLTIP_ICON").innerHTML="<img src=\""+BUFFED_BASEURL[this.current_game].iconPath+icon+".png\" />";
			}
			/*document.getElementById('db-tooltip-footer').innerHTML = (!this.is_buffed_page) ? '<div class="db-tooltip-footer"><img src="http://wowdata.buffed.de/fileadmin/favicon.gif" align="absmiddle"> Tooltip powered by buffed.de</div>' : '';
			*/

            var inner;
            for(var i=0; i<2; i++) {
                if(comp_tt && comp_tt[i]) {
                    inner ='<table>\n\
                            <tr><td>\n\
                               <table><tr><td>Zur Zeit angelegt:<br>'+comp_tt[i]+'</td></tr></table>\n\
                             </td><th style="background-position: top right"></th></tr>\n\
                            <tr><th style="background-position: bottom left;text-align:left;" id="db-tooltip-footer"></th>\n\
                                <th style="background-position: bottom right"></th>\n\
                            </tr></table>';
                    if(comp_box && comp_box[i]) {
                        inner +='<table>\n\
                            <tr><td>\n\
                               <table><tr><td>'+comp_box[i]+'</td></tr></table>\n\
                             </td><th style="background-position: top right"></th></tr>\n\
                            <tr><th style="background-position: bottom left;text-align:left;" id="db-tooltip-footer"></th>\n\
                                <th style="background-position: bottom right"></th>\n\
                            </tr></table>';

                    }
                    if(i == 0) {
                        cttdiv1.innerHTML = inner;
                    } else {
                        cttdiv2.innerHTML = inner;
                    }
                }
            }


			ttdiv.cheight=ttdiv.clientHeight;
	
			if(!(xpos && ypos) && e) {
				xpos=this.fn_getMousePos(e).x;
				ypos=this.fn_getMousePos(e).y;
			}
			this.fn_setTooltipPos(xpos, ypos);
			ttdiv.style.visibility="visible";
			ttdiv.style.display="block";
			ttdiv.style.width="320px";
		}
	}
	
	this.fn_getScrollPos = function() {
		var scroll = {x:0,y:0};

		if(this.browser == 'gecko' || this.browser == 'opera' || this.browser == 'safari') {
			scroll.x = window.pageXOffset;
			scroll.y = window.pageYOffset;
		} else if(document.documentElement != 'undefined' && document.documentElement.scrollLeft != 'undefined') {			
			scroll.x=document.documentElement.scrollLeft;
			scroll.y=document.documentElement.scrollTop;			
		} else if(document.body != 'undefined' && document.body.scrollLeft != 'undefined') {
			scroll.x = document.body.scrollLeft;
			scroll.y = document.body.scrollTop;	
		}
		return scroll;
	}
	
	this.fn_getWindowSize = function() {
		
		var win = {w:0,h:0};
		
		if(window.innerWidth) {
		    win.w = window.innerWIDTH;win.h = window.innerHeight;
	  	} else if(document.documentElement && document.documentElement.clientWidth) {	
	    	win.w = document.documentElement.clientWidth;
	    	win.h = document.documentElement.clientHeight;
		} else if(document.body && document.body.clientWidth) {
			win.w = document.body.clientWidth;
			win.h = document.body.clientHeight;
		}

		return win;
	}
	
	this.fn_setTooltipPos = function(xpos,ypos) {		
		var BFDTTDIV=document.getElementById("BUFFED_TOOLTIP");
		if(BFDTTDIV) {
			var windowwidth=this.fn_getWindowSize().w;
			var windowheight=this.fn_getWindowSize().h;
			var height=BFDTTDIV.clientHeight;
			var width=BFDTTDIV.clientWidth;
			var xoffset=-40;
			var yoffset=20;
			var xscroll=this.fn_getScrollPos().x;
			var yscroll=this.fn_getScrollPos().y;
			var xzero=0;
			var yzero=0;
			
			if((xpos+width) > (windowwidth+xscroll-5)) {
				xzero=-width+xzero;
			}
			if((xpos+xzero) < xscroll) {
				xzero=0;
			}
			if((ypos+height) > (windowheight+yscroll-20)) {
				yzero=-height-25+yzero;
			}
			if((ypos+yzero) < yscroll) {
				yzero=0;
			}

			BFDTTDIV.style.left = (xpos+xoffset+xzero+((this.browser == 'ie')?xscroll:0) +"px");
			BFDTTDIV.style.top = (ypos+yoffset+yzero+((this.browser == 'ie')?yscroll:0) +"px");
			BFDTTDIV.style.zIndex=11111;
		}
	}

    this.fn_requestTooltip = function(type, id, locale) {
        var base_href = BUFFED_BASEURL[this.current_game][locale];

        switch(this.current_game) {
            default:return;break;
            case 'wow':
                if(type == "i"){
                    this.fn_request(base_href+"/items/js/"+id+".js");
                }
                if(type == "q"){
                    this.fn_request(base_href+"/quests/js/"+id+".js");
                }
                if(type == "s"){
                    this.fn_request(base_href+"/spells/js/"+id+".js");
                }
                if(type == "a"){
                    this.fn_request(base_href+"/achievements/js/"+id+".js");
                }
            break;
            case 'rom':
                if(type == "i"){
                    this.fn_request(base_href+"/items/js/"+id+".js");
                }
                if(type == "s"){
                    this.fn_request(base_href+"/spells/js/"+id+".js");
                }
            break;
            case 'war':
                if(type == "i"){
                    this.fn_request(base_href+"/items/js/"+id+".js");
                }
                if(type == "q"){
                    this.fn_request(base_href+"/quests/js/"+id+".js");
                }
                if(type == "a"){
                    this.fn_request(base_href+"/abilities/js/"+id+".js");
                }
            break;
        }
    }

	this.fn_request = function(address) {
	
		var element=document.getElementById("BUFFED_TT_REQUEST");
		var h=document.getElementsByTagName("head")[0];
	
		if(element != null) {
			element.parentNode.removeChild(element);
		}

		element=document.createElement("script");
		element.id="BUFFED_TT_REQUEST";
		element.type="text/javascript";
		element.src=address;
		h.appendChild(element);
	}
	
	this.fn_addTooltip = function(data) {
	
		if(!this.current_game) return;

		if(!data || !data.type || !data.id) {return;}
	
		var locale = 'deDE';
		if(data.l) {locale = data.l;}

		if(!this.cache[this.current_game]) {
			this.cache[this.current_game] = [];
		}
		if(!this.cache[this.current_game][locale]) {
			this.cache[this.current_game][locale] = [];
		}
		if(!this.cache[this.current_game][locale][data.type]) {
			this.cache[this.current_game][locale][data.type] = [];
		}

		this.cache[this.current_game][locale][data.type][data.id] = data;
//		this.fn_show(locale, data.type, data.id, null, this.lastrequest_x, this.lastrequest_y);
		this.fn_show(locale, data.type, this.lastrequest_id, null, this.lastrequest_x, this.lastrequest_y);
	}
	
	this.init = function() 
	{
		this.fn_checkLocation();
		this.fn_loadHeaderData();
		this.fn_getBrowser();		
	}

    this.st = function(tooltip, e, xpos, ypos) {
		var ttdiv=document.getElementById("BUFFED_TOOLTIP");

        if(!ttdiv) {
            var b=document.getElementsByTagName("body")[0];
            if(!b) {return;}
            ttdiv=document.createElement("div");
            ttdiv.id="BUFFED_TOOLTIP";
            ttdiv.className = 'BUFFED_TOOLTIP';
            ttdiv.style.display="none";
            ttdiv.style.visibility="hidden";
            var inner_db_class = (this.current_game == 'war') ? 'db-war-tooltip' : 'db-tooltip';
            ttdiv.innerHTML = '<div class="'+inner_db_class+'"><table><tr><td><table><tr><td id="BUFFED_TOOLTIP_DATA"></td></tr></table></td><th style="background-position: top right"></th></tr><tr><th style="background-position: bottom left;text-align:left;" id="db-tooltip-footer"></th><th style="background-position: bottom right"></th></tr></table><div id="BUFFED_TOOLTIP_ICON"></div></div>';
            b.appendChild(ttdiv);
        }

        ttdiv.style.visibility="hidden";
        ttdiv.style.display="none";

        this.fn_setTooltipPos(0,0);

        document.getElementById("BUFFED_TOOLTIP_DATA").innerHTML=tooltip;
        document.getElementById("BUFFED_TOOLTIP_ICON").innerHTML="";

        ttdiv.cheight=ttdiv.clientHeight;

        if(!(xpos && ypos) && e) {
            xpos=this.fn_getMousePos(e).x;
            ypos=this.fn_getMousePos(e).y;
        }
        this.fn_setTooltipPos(xpos, ypos);
        ttdiv.style.visibility="visible";
        ttdiv.style.display="block";
        ttdiv.style.width="320px";
    }
}

BUFFED_ADDTOOLTIP = function(data) {
	BUFFED_DB_TT.fn_addTooltip(data);
}

BUFFED_DB_TOOLTIPS_INIT = function() {
	BUFFED_DB_TT = new BUFFED_DB_TOOLTIPS();
	BUFFED_DB_TT.init();
}
BUFFED_DB_TOOLTIPS_INIT();
