(function(w){
var bibleRef = {
	conf: {
		ToolTip: { width: 300, 
			height: 150, // don't change
			timeout: 10, // sec
			hideTime: 0.3, // sec
		}
	},
	xcpt: {
		A: true,
		APPLET: true,
		BODY: true,
		H1: true,
		H2: true,
		H3: true,
		H4: true,
		H5: true,
		H6: true,
		HEAD: true,
		HR: true,
		IMG: true,
		INPUT: true,
		META: true,
		OPTION: true,
		SCRIPT: true,
		SELECT: true,
		TEXTAREA: true
	},
	init: function() {
		bibleRef.loadStyle();
		var el, e, i, j, nid = 0;
		var els = [document.body];
		for (var r = /(?:[^a-zа-я\.]|^)(?:Б(?:ы?т|ытие)|G(?:en|enesis)|Исх(?:од)?|Ex(?:d|od(?:us)?)|Л(?:е?в|евит)|L(?:ev(?:i(?:t(?:icus)?)?)?)|Ч(?:и?с|исла?|исел)|N(?:umb(?:ers?)?)|В(?:т(?:рзк)?|тор(?:озаконие))|D(?:eut?|euteron|(?:eu|ue)teronomy)|Иис(?:ус)?|Нав(?:ин)?|Иис(?:ус)?\.? ?Нав(?:ин)?|J(?:o?sh?|oshua)|С(?:у?д|уд(?:ьи|ей))|J(?:u?dgs?|ud?ges?)|Р(?:у?ф|уфь)|R(?:u?th)|Е(?:зд?|здра?)|Ezra?|Н(?:м|еем(?:ия)?)|N(?:eh(?:em(?:iah)?)?)|[ЕЭ](?:сф?|сфирь)|E(?:s(?:t(?:h(?:er)?)?)?)|Ио?в|Job|П(?:сл?|сал(?:т(?:ирь)?|ом|мы)?)|P(?:s(?:l?m|s|a(?:l(?:ms?)?)?)?)|П(?:р(?:ит(?:ч[иа]?)?)?)|P(?:r(?:[ov]|vbs|ov(?:erbs?)?)?)|Е(?:к(?:кл?|кле[сз]иаст)?)|Э(?:ккл(?:е[зc]иаст)?)|Проповедника?|E(?:c[cl]?l?|cclesia(?:ste)?|cc?lesiastes)|Q(?:oh(?:eleth)?)|П(?:е?сн|ec(?:н(?:ей|и|\.? ?П|(?:\.|[ия] )?Песней)?)?)|S(?:ng|OS)|S(?:on(?:gs?)?)|Sol(?:omon)?|Song of So(?:l|lomon|ngs)|Song? of|Canticle(?:s| of Canticles)|И(?:с(?:а(?:[ий]я)?)?)|Is(?:a(?:[hi]|iah)?)|Иер(?:ем(?:ия)?)?|J(?:er(?:m(?:(?:ia|ai)h)?)?)|Пл(?:а?ч|[\. ]Иер|ач Иеремии)|L(?:am(?:ent(?:ations?)?)?)|И(?:е?з|езек(?:ииль)?)|Ez(?:[ke]?|ek(?:iel))|Д(?:ан(?:иил)?|нл?)|D(?:an(?:iel)?)|Ос(?:ия)?|H(?:os(?:ea)?)|И(?:л|оиль?)|J(?:l|oel?)|Ам(?:о?с)?|Am(?:[os]|os)|Авд(?:ий)|Ob(?:[ad]|ad(?:(?:ia|aia?)h)?)|Иона?|J(?:nh|on(?:ah?)?)|М(?:x|их(?:ей))|Mic(?:ah?)?|Наум|Nah(?:um)?|Авв(?:ак(?:ум)?)?|H(?:bk|ab(?:ak|b?akk?uk)?)|Соф(?:он(?:ия)?)?|Zep(?:h(?:aniah)?)?|Агг(?:ей)|Hag(?:g(?:ai|ia)?|ai|)?|З(?:хр|ах(?:ар(?:ия)?)?) |Zec(?:h(?:ara?iah)?)?|М(?:лх|ал(?:ах(?:ия)?)?)|Mal(?:achi)|Matt?(?:hew)?|Ma?rk|Ma[rt]|Luke?|J(?:no|hn|ohn?)|Дея(?:н(?:ия)?)?|Д\.?А|Acts?|Деяния (?:Св(?:ятых|\.)? )?Апостолов|И(а?к|акова?)|Ja(?:[ms]|ms|mes?)|И(?:д|уд[аы])|Jude?|Rom(?:ans?)?|Gal(?:at(?:ians?|ions)?)?|Eph(?:s|e(?:s(?:ians?)?)?)?|Ph[iplm]|Phil(?:lipp?ians|ipp?(?:ians)?)?|Col(?:os(?:sians?|ians)?)?|Tit(?:us)?|Phlm|Phil(?:lemon|e(?:m(?:on)?)?)?|Heb(?:r(?:e(?:ws?)?)?)?|Отк(?:р(?:\.?Ин|ов(?:ен(?:\.(?:Ин|иоанна)|И[не])(?: от Иоанна|Иоанна(?: Богослова)?)?)?)?)?|Rev(?:elations?)?|Apoc(?:alypse)?|(?:Посл(?:ание|\.) )?(к )?(?:Рим(?:л(?:янам)?)?|Гал(?:ат(?:ам)?)?|[ЕЭ]ф(?:ес(?:янам)?)?|Фл[пм]|Фил(?:ип(?:пийцам)?)?|Кол(?:ос(?:сянам)?)?|Титу?|Филимону?|Евр(?:еям)?)|(?:Св(?:ятое|\.)? )?(Ев(?:ангелие|\.)? )?(?:от )?(М[крфт]|Ма[тр]|Мтф|Мрк|матф(?:е[яй])?|Марка?|Лук[aи]?|Лк|Ин|Иоан(?:н[ау]?)?)|(?:(?:2|ii|[i1]) ?|(?:1[-—–]?(?:а?я|о?е)|Перв(?:ая|ое|\.)|2[-—–]?(?:а?я|о?е)|Втор(?:ая|ое|\.)) )(?:(?:к|Посл(?:ание|\.)?(?: к)?|Кн(?:ига|\.)?) )?(?:Царей|Ца?р|Ц|Царств|Сам|Самуила?|Паралипоменон|Пар|Пр|Хр|Хрон|Хроник|Лет|Летопись|Фесс?|Фессалоникийцам|Сол|Солунянам|Тим|Тимоф|Тимофею|Кор|Коринф|Коринфянам|Иоан|Ин|Иоанн[уа]?|Пет|Птр?|Петра?)|(?:(?:3|iii) ?|(?:3[-—–]?ь?я|Трет(?:ья|\.) ))(?:(?:к|Посл(?:ание|\.)?(?: к)?|Кн(?:ига|\.)?) )?(?:Цар|Цр?|Царств|Ин|Иоанн?|Иоанн[ау])|(?:(?:4|iv) ?|4[-—–]?а?я|Четверт(?:ая|\.) )(Кн(?:ига|\.)? )?(?:Цар|Цр?|Царств)|(?:(?:2|ii|[1i]) ?|(?:First|Frst|Fst|1[-—–]?st|Second|Scnd|Sec|S[ec]|2[-—–]?nd) )(?:[PKJS]|J[no]|P[et]|S[am]|Sam|Sml|Samuel|K[ings]|Kgs|Ki?ng|Kings|C[oh]|Chr?s|Chro?|Chroni?|Chronicl?|Chronicles?|T[imh]|Pete?r|Pete?|Ptr|Jhn|Jno|John?|Cori?|Corin|Corinth|Corinthi|Corinthian|Corinthians|Corth|Cortn|Thess?|Thessal|Thessalonians|Thessalonions|Tim|Timothy|Timoth)|A[cm]|C[lsl]|D[aenut]|E[codp]|G[an]|H[bekosg]|I[s]|J[damnbegru]?|L[amevuk]|M[ilrkta]|N[aeumb]|O[b]|P[hprsm]|R[moevuth]|S[gso]|T[it]|Q[o]|Z[ecp])[\.\s]*((?![1234][\s]*[а-яa-z])(?:(?:[1-9][0-9]?|1[234][0-9]|15[01])(?:[-—–][1-9][0-9]?|1[234][0-9]|15[01])?)(?:[:\.][\s]*\d+(?:[-—–]\d+)?)?(?:,[\s]*(?![1234][\s]*[а-яa-z])\d+(?:[-—–]\d+)?|;[\s]*(?![1234][\s]*[а-яa-z])(?:(?:[1-9][0-9]?|1[234][0-9]|15[01])(?:[-—–][1-9][0-9]?|1[234][0-9]|15[01])?)(?:[:\.][\s]*\d+(?:[-—–]\d+)?)?)*)(?![\d:а-я]|[-—–][^\d]+)(?![^<]*<\/a>)/gims;el = els.pop();)
		{
			if (el.nodeType === 3) {
				if (e = el.nodeValue.match(r)) {
					j = 0;
					var pn = el.parentNode;
					for (i = e.length; j < i; j++) {
						elR = el.nodeValue;
						lnk = e[j];
						if ( /^[^a-zа-я\.]$/i.test(lnk.substr(0,1)) ) lnk = lnk.substr(1,lnk.length-1);
						c = elR.indexOf(lnk);
						bble = document.createElement("a");
						bble.href = "http://bble.ru/"+lnk.replace(/: +/g, ".").replace(/ +/g, "+").replace(/;/g, "%3b").replace(/[-—–]/g, '-');
						bble.className = "BibleOnlineBibleRef";
						bble.target = "_blank";
						bble.id = 'BibleOnlineRef-'+(++nid);
						bble.innerHTML = lnk;
						if(bble.addEventListener){
							bble.addEventListener("mouseover",bibleRef.MouseOver,false);
							bble.addEventListener("mouseout",bibleRef.MouseOut,false)
						} else {
							bble.attachEvent("onmouseover",bibleRef.MouseOver);
							bble.attachEvent("onmouseout",bibleRef.MouseOut)
						}

						el.nodeValue = elR.replace(lnk, "");
						lnk = el.splitText(c);

						el === pn.lastChild ? pn.appendChild(bble) : pn.insertBefore(bble, lnk);
						el = lnk
					}
				}
			}
			else if (el.firstChild) {
				var e = el.childNodes;
				j = 0;
				for (i = e.length; j < i; j += 1) {
					if (e[j].nodeType === 3 && el.nodeValue !== "") { els.push(e[j]);  }
					else { 
						e[j].nodeType === 1 && !bibleRef.xcpt[e[j].tagName.toUpperCase()] && els.push(e[j])
					}
				}
			}
		}
	},
	MouseOut: function (e)
	{
//		e  = e || wndow.event;
//		var target = e.target || e.srcElement;
		var d = document.getElementById('BibleOnlineToolTip');		
		if (d && d.style.visibility == "visible")
		{
			clearTimeout(bibleRef.status.hideTimer);
            		bibleRef.status.hideTimer = setTimeout(function () {
		                d.style.visibility = 'hidden';
		            }, bibleRef.conf.ToolTip.hideTime * 1000)
		}
	},
	MouseOver: function (e)
	{
		var e  = e || wndow.event;
		var target = e.target || e.srcElement;
		bibleRef.status.lastToolTip = [e,target];
		bibleRef.showToolTip(e,target);
	},
	showToolTip: function(e,t)
	{
		var data;
		var ct = bibleRef.conf.ToolTip;
		clearTimeout(bibleRef.status.hideTimer);
		if (bibleRef.marker[t.id])
		{
			var b = bibleRef.marker[t.id];
			var d = document.getElementById('BibleOnlineToolTipContent');
			d.innerHTML  = '';
			document.getElementById('BibleOnlineToolTip').style.visibility = "visible";
			for (var i = 0; i<b.length; i++)
			{
				if (b[i].h2)
				{
					d.innerHTML += '<h2>'+b[i].h2+"</h2>";
				}
				else if (b[i].v)
				{
					d.innerHTML += ' <span class="verse-num">'+b[i].v.n+'&nbsp;</span> '+b[i].v.t;
				}
			}
			var more = document.getElementById('BibleOnlineToolTipMore');
			more.href = 'http://bble.ru/'+document.getElementById(t.id).innerHTML.replace(/&nbsp;/ig, " ").replace(/: +/g, ".").replace(/ +/g, "+").replace(/;/g, "%3b").replace(/[-—–]/g, '-');
		}
		else
		{
			var f="http://api.bibleonline.ru/ref/get/";
			var q=t.innerHTML.replace(/&nbsp;/ig, " ").replace(/: +/g, ".").replace(/ +/g, "+").replace(/;/g, "%3b").replace(/[-—–]/g, '-');
			f+=f.indexOf("?")>-1?"&callback=":"?callback=";
			f+="bibleRef.loaded";
			f+="&q="+q;
			f+="&marker="+t.id;
			var b=document.getElementsByTagName("head")[0];
			var k=document.createElement("script");
			k.setAttribute("id",'script-'+t.id);
			k.setAttribute("src",f);
			k.setAttribute("type","text/javascript");
			setTimeout(function () {
				bibleRef.marker[t.id] || bibleRef.requestFailed(t.id)
			}, 1000 * bibleRef.conf.ToolTip.timeout);
			b.appendChild(k);
			if (!document.getElementById('BibleOnlineToolTip'))
			{
			        c = document.createElement("div");
        			c.id = 'BibleOnlineToolTip';
			        c.className = "BibleOnlineRefTooltip";
			        c.style.position = "absolute";
			        c.style.visibility = "visible";
			        c.style.overflow = "auto";
			        c.style.zIndex = "999";
			        c.style.width = ct.width+'px';
			        c.style.height = ct.height+'px';
				c.innerHTML = '<div class="BibleOnlineRefContent" id="BibleOnlineToolTipContent"></div><div class="BibleOnlineRefFooter"><a target="_blank" class="BibleOnlineRefCopy" href="http://bibleonline.ru/">Библия Онлайн</a><a id="BibleOnlineToolTipMore" target="_blank" href="http://bble.ru/'+q+'" class="BibleOnlineRefMore">в контексте &raquo;</a></div>';

			        document.body.appendChild(c);
				c.onmouseover = function () {
					clearTimeout(bibleRef.status.hideTimer);
				};
				c.onmouseout = function () {
					var d = document.getElementById('BibleOnlineToolTip');		
					if (d && d.style.visibility == "visible")
					{
						clearTimeout(bibleRef.status.hideTimer);
  			          		bibleRef.status.hideTimer = setTimeout(function () {
					                d.style.visibility = 'hidden';
					            }, bibleRef.conf.ToolTip.hideTime * 1000)
					}
				};
			}
			c = document.getElementById('BibleOnlineToolTipContent');
			c.innerHTML = '<div class="BibleOnlineRefLoader"><img width="220" height="19" src="http://y.bibleonline.ru/img/ajax-loader.gif" alt="Loading..." /></div>';
		}
		c = document.getElementById('BibleOnlineToolTip');
		var tbc = document.getElementById(t.id).getBoundingClientRect();
		var body = document.body;
		var docElem = document.documentElement;
		var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
		var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
		var clientTop = docElem.clientTop || body.clientTop || 0;
		var clientLeft = docElem.clientLeft || body.clientLeft || 0;

		var wWidth=0,wHeight=0;
		if (window.innerWidth) wWidth = window.innerWidth;
		else if (docElem && docElem.clientWidth) wWidth = docElem.clientWidth;
		else if (body && body.clientWidth) wWidth = body.clientWidth;

	        if (window.innerHeight) wHeight = window.innerHeight;
	        else if (docElem && docElem.clientHeight) wHeight = docElem.clientHeight;
		else if (body && body.clientHeight) wHeight = body.clientHeight;


		var cTop = Math.round(tbc.bottom + scrollTop - clientTop);
		var cBottom = Math.round(tbc.top + scrollTop - clientTop);
		var cLeft = Math.round(tbc.left + scrollLeft - clientLeft);

		if (cLeft + ct.width + 40 >= wWidth) cLeft = wWidth - ct.width - 40;

		if (cTop + ct.height + 10 >= wHeight   + scrollTop - clientTop)
		{
			cTop = 2 * cBottom  - cTop - ct.height;
			if (cTop <= 10) cTop = 10
		}

		c.style.left = cLeft+'px';
		c.style.top = cTop+'px';
	},
	marker: {},
	status: { hideTimer: null, lastToolTip: null },
	requestFailed: function(tid)
	{
		bibleRef.removeScript(tid);
		var c = document.getElementById('BibleOnlineToolTipContent')
		if (c)
		{
			c.innerHTML = '<div class="BibleOnlineRefLoader">К сожалению, загрузить отрывок не удалось</div>';
		}
	},
	removeScript: function(s)
	{
		var sc = document.getElementById('script-'+s);
		if (sc) sc.parentNode.removeChild(sc);
	},
	loaded: function(r) { 
		bibleRef.marker[r.marker] = r.data;
		bibleRef.removeScript(r.marker);
		if (bibleRef.status.lastToolTip && bibleRef.status.lastToolTip[1].id == r.marker)
		{
			bibleRef.showToolTip(bibleRef.status.lastToolTip[0],bibleRef.status.lastToolTip[1])
		}
	},
	loadStyle: function()
	{
		var dh=document.getElementsByTagName("head")[0],st=document.createElement("link");
		st.type="text/css";
		st.rel="stylesheet";
		st.href="http://api.bibleonline.ru/ref/style.css";
		dh.insertBefore(st,dh.firstChild);
	}
};

w.bibleRef = { loaded: bibleRef.loaded, conf: bibleRef.configure };
if(w.addEventListener){
	w.addEventListener("load",function() { bibleRef.init() } ,false);
} else if (w.attachEvent) {
	w.attachEvent("onload",function() { bibleRef.init() });
}
})(window);

