/* © rusbible.ru 2009 */

function nofrag(href){
    var i = href.indexOf("#");
    return i == -1 ? href : href.substr(0,i);
}
  
function doScroll(){
    var y=0,el = document.getElementById(embed);
    while (el){
        y += el.offsetTop || 0;
        el = el.offsetParent;
    } 
    document.body.scrollTop = y;
}
      
function mwrite(){
    document.write('<'+'a hr'+'ef="ma'+'il'+'to:wm'+'aster-pubm'+'ail-2007' + String.fromCharCode(64) + 'rusbible.ru">wma'+'ster-pubm'+'ail-2007'+String.fromCharCode(64)+'rusbible.ru</a>');
}      

//прокручиваемся к заданному элементу
function scrollToItem(el){
    document.body.scrollTop = $(el).offset().top;
}        

//значение параметра
function param(line,name,def){
	var m = line.match( "(^|&|\\#|\\?)" + name + "=([^&]+)($|&)");
	return m ? m[2] : def;
}

var embed;
var parloc = null, myloc = nofrag(self.location.href);
var helpfile;
var curgl = false,curst="";    

/*
	если сайт расположен на зеркале, пишем стили для показа (или скрытия) ссылок
	на главный сайт (rusbible.ru)
*/
if (window.location.host == 'rusbible.ru' || window.location.host == 'www.rusbible.ru' || window.location.href.indexOf("#notamirror") != -1)
	document.write('<style type="text/css">.mirror {display: none}</style>');
else
	document.write('<style type="text/css">.nomirror {display: none}</style>');

/*
	рисуем стили для скрытия возможностей, недоступных при выключенных скриптах
*/
document.write('<style type="text/css">.scriptcheck { display: none }</style>');
	
/*
	если страница показывается в окошке, используем подходящую таблицу стилей
*/



try {
if (self != parent)
	parloc = nofrag(parent.location.href);
} catch (e){}


if (!embed){
	if (parloc == myloc){ //живём сами в себе - текущий iframe впечатан скриптом в родителя
	   embed = parent.BibleLinks.embed;
	   BibleFilesRoot = parent.BibleFilesRoot;
	}
	else {

		embed = self.location.hash;
		if (embed.substring(0,1)=='#') embed = embed.substring(1);
		embed = param(window.location.href,"embed",false);
		  
		if (embed && self == parent){
			history.go(-1);	//DEBUG обход бага chm+ie: из-за ужасающих открытий фрейма на всё окно
		}
		  
		var m = window.location.href.match(/^mk\:(.*\\)([^\\]+)\:\:([^$]+)(#.*)?$/);

		if (m){
			helpfile = m[2].toLowerCase();
			if (helpfile != "rusbible-ru.chm"){
				BibleFilesRoot = "mk:" + m[1] + 
				(helpfile == "rusbible(ru,all).chm" ? "RusBible(ru,all).chm" : "RusBible(ru).chm")
				+ "::/html/";
			}
		}
	}
}

//загружаем все css файлы из головного модуля
if (location.protocol == "mk:"){
	var i,styles,s;
	styles=document.getElementsByTagName('link');
	for(i=0;i<styles.length;i++) {
		s=styles[i];
		if(s.rel.toLowerCase().indexOf('stylesheet')>=0&&s.href){
			s.href = BibleFilesRoot + s.href.replace(/\.\.\//g,'');
			//alert(s.href);
		}
	}
}
if (embed)
	document.write('<link rel="stylesheet" type="text/css" href="'+BibleFilesRoot+'css/iframe.css" />');

//нормализация ссылок на главу вида ГЛАВА.СТИХ
if (window.location.hash && (m = /^\#?([0-9]+)([\:\.][0-9]+)?$/.exec(window.location.hash))){
	curgl = m[1];
	curst = m[2] ? m[2] : '';
	if (window.location.hash.indexOf(".")>-1){
		$(function(){
			scrollToItem(document.getElementById(curgl + ":" + curst.substr(1)));
		});
	}
}

//если указана в урле конкретная глава
if (curgl){
	document.write('<style type="text/css">'+"\r\n"+'.bar'+curgl+'{font-weight:bold}'+"\r\n"+'</style>');
	$(function(){
		$(".updch a").attr("href",function(){
			var href = $(this).attr("href");
			var m = /\.([0-9]+)\.html(#[^#]*)?/.exec(href);
			if (m)	//страница одноглавная
				return href.replace(/\.([0-9]+)\.html(#[^#]*)?$/,'.'+curgl+'.html#'+curgl+curst);
			else //страница многоглавная
				return href.replace(/\.html#[^#]*$/,'.html#'+curgl+curst);
		});
	});
}

//Переподключение событий
function plugOnClicks(){

	//подсвечиваем блоки, на которые указывают внутренние ссылки
	$('a.inner').click(function(e){ 
			var y,pel,el,id,loc = nofrag(location.href);
			if (this.href.indexOf(loc + "#") == 0){
				id = '#'+this.href.substr(loc.length+1);
				pel = el = $(id).get(0);
				while (pel){
					y += pel.offsetTop || 0;
					pel = pel.offsetParent;
				}
				document.body.scrollTop = y - parseInt($(el).css("margin-top"));
				$(el).addClass('highlited');
				e.stopPropagation();
				setTimeout("$('"+id+"').removeClass('highlited');",2000);
				return false;
			}
	});

	//ходим по примечаниям, расположенным на других страницах
	$('a.prim').click(function(e){
			var m;
			if (

				!(m = window.location.pathname.match(/(.*books\/[^.]+\.[^.]+\.)([^.]+)\.html$/))
			 && !(m = window.location.pathname.match(/(.*sinodal\/[^.]+\.)([^.]+)\.html$/))

			) return true;
		
			var id = $(this).attr("id"),href = $(this).attr("href");
			if (id.indexOf("primsrc") === 0)
				location.href = m[1] + "notes.html" + href.substr(href.indexOf("#"));
			else {
				if (window.location.href.indexOf("#" + id) != -1)
					history.go(-1);
				else
					alert("Возврат к исходному тексту примечания в многостраничном режиме не поддерживается");
			}
			e.stopPropagation();			
			return false;
			
	});
	
	//клик на "наверх" пусть прыгает наверх без перехода страницы
	$("a[href$=#toppagesbar]").click(function(e){
		document.body.scrollTop = 0;
		e.stopPropagation();		
		return false;
	});
	
}

BibleLinksOnHighlight = plugOnClicks;

$(function(){
	
	if (embed) {
		setTimeout('doScroll()',10);
		$(".pagesbar a,.glnav a").attr("href",function(){
			return $(this).attr("href").replace(/#/,'#embed=');
		});
		
	}

	plugOnClicks();
	
	//страница указывает на иной перевод
	var trans = param(location.href,"translate",false);
	if (trans)
		$(".list a[href^=sinodal]").attr("href",function(){
			return $(this).attr("href").replace(/^sinodal\//,trans.replace(/[^a-z]/g,'')+"/");
		});
	
});


if (location.protocol == "mk:"){
	document.write('<link rel="stylesheet" type="text/css" href="'+BibleFilesRoot+'css/chm.css" />');
	document.write('<script type="text/javascript" language="javascript" charset="windows-1251" src="'+BibleFilesRoot+'scripts/chm.js"></script>');
}

