var syncDelay = 80; // in miliseconds

var selectedWindowBible = null; // just windows to display biblical text
var selectedWindowNews = null;
var lastSelectedWindowBible = null; // because closing window temporarily
var selectedWindowLexicon = null;
// focuses window being closed
var selectedWindowSearch = null; // just windows to display search results
// are in scope
var language = null;
var scrollTimeout = null;
var fontSize = 'middle';
var uniqueId = 0;
closeAllCollapsible();
var gt = new Gettext( {
	domain : 'anything'
});

function bodyOnload(langFromJsp) {
	getSettings();

	if (language == null) {
		language = langFromJsp;
	}
	Gettext.lang = language;

	//ieWarning();

	$("#loading").ajaxStart(function(event, request, settings) {
		$("div#loading").css( {
			'display' : 'block'
		});
	});
	$("#loading").ajaxComplete(function(event, request, settings) {
		$("div#loading").css( {
			'display' : 'none'
		});
	});
	loadBibleTranslations();
	loadLanguages();
	$(document).bind('keydown', 'Ctrl+l', function(evt) {
		$("#queryString").focus();
		evt.stopPropagation();
		evt.preventDefault();
		return false;
	}); // verseQuery
	$(document).bind('keydown', 'Ctrl+k', function(evt) {
		$("#searchInputText").focus();
		evt.stopPropagation();
		evt.preventDefault();
		return false;
	}); // search
	$("#queryString").bind('keydown', 'return', function(evt) {
		searchQuery();
		evt.stopPropagation();
		evt.preventDefault();
		return false;
	});
	$("#searchInputText").bind('keydown', 'return', function(evt) {
		searchSearch();
		evt.stopPropagation();
		evt.preventDefault();
		return false;
	});

	$(window).resize(function() {
		onWindowResize();
	});
	onWindowResize();

	$("#queryString").focus();

	openNewsWindow();
	setAllFontSize('middle');

}

function openNewsWindow() {
	openWindow("news");
	onWindowSelect(selectedWindowNews);
	selectedWindowNews.boTranslationId = null;
	selectedWindowNews.boTranslationName = null;
	selectedWindowNews.boQuery = null;
	$.get("News", {
		query : selectedWindowNews.boQuery,
		lang : language
	}, function(result) {
		viewText(selectedWindowNews, _("bible-online.cz"), result.direction,
				result.error, result.text, "", "", "");
	}, "json");
}

function onWindowResize() {
	var y = $(window).height() - $("#windowArea").position().top - 12;
	$("#windowArea").height(y);
	organizeWindows();
}

function showError(header, message) {
	$.jGrowl(message, {
		header : header,
		theme : 'iphone',
		life : 5000
	});
}

function getUniqueId() {
	uniqueId++;
	return uniqueId;
}

function _(msgid) {
	return gt.gettext(msgid);
}

function showHideNotes() {
	if ($("#showNotes").is(":checked") == true) {
		$(".btNotes").show();
		$(".btReference").show();
		$(".brStrGr").show();
		$(".brStrHeb").show();
		$(".btMorphGreek").show();
		$(".btMorphHebrew").show();
	} else {
		$(".btNotes").hide();
		$(".btReference").hide();
		$(".brStrGr").hide();
		$(".brStrHeb").hide();
		$(".btMorphGreek").hide();
		$(".btMorphHebrew").hide();
	}
}

function showVerseSeparate() {
	if ($("#showVerseSeparate").is(":checked") == true) {
		$(".verse").css( {
			display : 'block'
		});
	} else {
		$(".verse").css( {
			display : 'inline'
		});
	}
}

function openWindow(type) {

	var myButtons = [];

	if (type == "bible" || type == "lexicon") {
		myButtons = [ {
			id : "btn_license",
			title : _("license information"),
			image : "images/license.gif",
			callback : function(element) {
				viewLicence();
			}
		} ];
	}

	var wnd = $("#windowArea").window( {
		title : "Loading...",
		content : $("#window").html(),
		checkBoundary : true,
		scrollable : true,
		showFooter : false,
		width : 200,
		height : 150,
		x : 20,
		y : 250,
		z : 32,
		showRoundCorner : true,
		custBtns : myButtons,
		onClose : function(c) {
			windowOnClose(c);
		}
	});

	wnd.boType = type;

	if (type == "bible") { // TODO change selectedWindowXXX to
		// selectedWindow[xxx]
		selectedWindowBible = wnd;
	}
	if (type == "news") {
		selectedWindowNews = wnd;
	}
	if (type == "search") {
		selectedWindowSearch = wnd;
	}
	if (type == "lexicon") {
		selectedWindowLexicon = wnd;
	}

	organizeWindows();
	setFontSize(fontSize);
	return wnd;
}

function windowGetAll(type) {
	var wnds = $.window.getAll();
	var ret = [];

	for ( var i = 0; i < wnds.length; i++) {
		if (wnds[i].boType == type)
			ret.push(wnds[i]);
	}
	return ret;
}

function windowOnClose(c) {

	if (c.boType == "bible") {
		var wnds = windowGetAll("bible");
		if (wnds.length > 0) {
			if (lastSelectedWindowBible.getWindowId() == c.getWindowId())
				onWindowSelect(wnds[0]); // TODO change to max instead of 0
			else
				onWindowSelect(lastSelectedWindowBible);
		} else {
			selectedWindowBible = null;
			lastSelectedWindowBible = null;
		}
	}

	if (c.boType == "news") {
		if (lastSelectedWindowBible != null) {
			onWindowSelect(lastSelectedWindowBible);
		}
		selectedWindowNews = null;
	}

	if (c.boType == "search") {
		var wnds = windowGetAll("search");
		if (wnds.length > 0) {
			if (lastSelectedWindowSearch.getWindowId() == c.getWindowId())
				onWindowSelect(wnds[0]); // TODO change to max instead of 0
			else
				onWindowSelect(lastSelectedWindowSearch);
		} else {
			selectedWindowSearch = null;
			lastSelectedWindowSearch = null;
		}
	}

	organizeWindows();
}

function organizeWindows() {
	var wnds = $.window.getAll();
	if (wnds.length > 0) {
		wnds[0].organize($("#windowArea"));
	}
}

function getSettings() {
	language = $.cookie('language');
}

function setLanguage(lang) {
	$.cookie('language', lang, {
		expires : 90
	});
	window.location = "?";
}

function CreateBookmarkLink() {
	title = "Bible Online ... my ultimate study tool";
	url = "http://www.bible-online.cz/";
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	} else if (window.external) { // IE Favorite
		window.external.AddFavorite(url, title);
	} else if (window.opera && window.print) { // Opera Hotlist
		return true;
	}
}

function setAllFontSize(size) {

	fontSize = size;
	
	var sizept = "11";
	if (size == "small")
		sizept = "9";
	if (size == "middle")
		sizept = "11";
	if (size == "big")
		sizept = "13";

	$(".window_frame").css( {
		'font-size' : sizept + 'pt'
	});

	$("#fontSize #small").removeClass("fontSizeActive");
	$("#fontSize #middle").removeClass("fontSizeActive");
	$("#fontSize #big").removeClass("fontSizeActive");

	$("#fontSize #" + size).addClass("fontSizeActive");

}

function setFontSize(size) {

	if (selectedWindowBible) {
		var sizept = "11";
		if (size == "small")
			sizept = "9";
		if (size == "middle")
			sizept = "11";
		if (size == "big")
			sizept = "13";

		$("#" + selectedWindowBible.getWindowId() + " .window_frame").css( {
			'font-size' : sizept + 'pt'
		});
	}
}

function generateQuery(book) {
	var orig = $("#queryString").val();
	var space = orig.indexOf(' ');
	if (space != -1)
		orig = orig.substr(space + 1, orig.length - space - 1);
	$("#queryString").val(book + " " + orig);

	$("#queryString").focus();
	var orig = $("#queryString").val();
	var space = orig.indexOf(' ');
	document.getElementById('queryString').selectionStart = space + 1;
	document.getElementById('queryString').selectionEnd = space + 1;
	closeAllCollapsible();
}

function generateQueryTranslationChanged(trans) {
	var orig = $("#queryString").val();
	var space = orig.indexOf(' ');
	if (space != -1) {
		var oldBook = orig.substr(0, space);
		orig = orig.substr(space + 1, orig.length - space - 1);
		$.post("ConvertBookName", {
			oldBook : oldBook,
			translation : trans
		}, function(result) {
			$("#queryString").val(result.book + " " + orig);
		}, "json");
	}
}

function querySuggest() {
	var q = $("#queryString").val();
	var space = q.indexOf(' ');
	var qs = document.getElementById("queryString");
	var position = qs.selectionStart;
	if (position > space) {
		closeAllCollapsible();
	} else {
		closeAllCollapsible();
		dropDown("#cBooks", "#queryString", 0, 0);
	}
}

function searchQueryNew() {
	selectedWindowBible = null;
	searchQuery();
}

function searchQuery() {
	var q = $("#queryString").val();
	var space = q.indexOf(' ');
	document.getElementById('queryString').selectionStart = space + 1;
	document.getElementById('queryString').selectionEnd = space + 1;
	closeAllCollapsible();

	if (selectedWindowBible == null) {
		openWindow("bible");
	}

	selectedWindowBible.boTranslationId = $("#translationHidden").html();
	selectedWindowBible.boTranslationName = $("#translationLabel").html();

	var wnds = windowGetAll("bible");
	for ( var i = 0; i < wnds.length; i++) { // if ( synchronizable )
		wnds[i].boQuery = $("#queryString").val();
		doQuery(wnds[i]);
	}

	onWindowSelect(selectedWindowBible);
}

function doQuery(wnd) {

	$.post("GetVerses", {
		query : wnd.boQuery,
		wholeChapter : true,
		bookIdType : 'shortName',
		translation : wnd.boTranslationId,
		lang : language,
		searchQuery : ""
	}, function(result) {
		if (result == null)
			showError("Error", "<div>" + _("No passage text was received")
					+ "</div>");
		viewText(wnd, result.query + " " + wnd.boTranslationName,
				result.direction, result.error, result.text, result.focusVerse,
				result.verseHighlight, result.shortLicense);
	}, "json");
}

function viewText(wnd, query, direction, error, text, focusVerse,
		verseHighlight, shortLicense) {
	wnd.setTitle(query);

	if (shortLicense != "")
		shortLicense = "<div class='shortLicense'>" + shortLicense + "</div>";
	
	if (text == "")
		error = error + "<div>" + _("No passage text was received") + "</div>";
	else {
		wnd.setContent(text + shortLicense);
		$("#" + wnd.getWindowId() + " .window_frame").css( {
			'direction' : direction,
			'text-align' : (direction == 'rtl') ? 'right' : 'left'
		});

		if (wnd.getWindowId() != "" && focusVerse != "") {
			scrollToVerse(wnd, focusVerse);
			highlightSelection(wnd, verseHighlight);
		}
		showHideNotes();
		showVerseSeparate()
	}

	if (error != "") {
		showError("Error", error);
	}

}

function viewLexicon(wnd, key, strong, text, error) {
	wnd.setTitle("lexicon");
alert(error);
	if (text == "")
		error = error + "<div>" + _("Lexicon entry not found") + "</div>";
	else {
		wnd.setContent(text);
	}

	if (error != "") {
		showError("Error", error);
	}

}

function onWindowSelect(wnd) {

	if (wnd != null) {
		onWindowDeselect(selectedWindowBible);

		if (wnd.boType == "bible") {
			lastSelectedWindowBible = selectedWindowBible;
			$("#translationLabel").html(wnd.boTranslationName);
			$("#translationHidden").html(wnd.boTranslationId);
			$("#queryString").val(wnd.boQuery);
			selectedWindowBible = wnd;

			// register onScroll listener
			$('#' + wnd.getWindowId() + " .window_frame").scroll(
					synchronizeContentDelay);
		}
		if (wnd.boType == "search") {
			selectedWindowSearch = wnd;
			wnd = selectedWindowSearch.boRelatedWindowBible;
			selectedWindowBible = wnd;
			$("#searchInputText").val(selectedWindowSearch.boQuery);
		}

		if (wnd != null) {
			$("#" + wnd.getWindowId() + " .window_header").addClass(
					"ui-state-default ui-widget-content");
			$("#" + wnd.getWindowId() + " .window_header").removeClass(
					"ui-widget-header");
		}
	}
}

function onWindowDeselect(wnd) {
	if (wnd != null && (wnd.boType == "bible" || wnd.boType == "news")) {
		$(".window_header").removeClass("ui-state-default ui-widget-content");
		$("#" + wnd.getWindowId() + " .window_header").addClass(
				"ui-widget-header");
		// unregister onScroll listener
		$('#' + wnd.getWindowId() + " .window_frame").unbind('scroll');
	}
}

function loadBibleBooks(trans) {
	$("#cBooks").load(
			'BibleBooks?trans=' + trans + '&lang=' + language
					+ '&selection=false');
}

function loadBibleTranslations() {
	var vip = "";
	if (language == "or")
		vip = "&vip=1";

	$("#cTranslations").load('BibleTrans?lang=' + language + vip);

	$.get("GetDefaultTranslation?lang=" + language + vip, "", function(result) {
		loadBibleBooks(result.defaultTranslation);
	}, "json");
}

function referenceDialog(query) {
	var uid = getUniqueId();
	$("#windowArea").append("<div id=\"dialog" + uid + "\" class=\"flora\" style=\"float: right;\"></div>");
	$("#dialog" + uid).attr("title", _("Lookup verse"));
	$.post("GetVerses", {
		query : query,
		bookIdType : 'shortName',
		translation : selectedWindowBible.boTranslationId,
		lang : language
	}, function(result) {
		$("#dialog" + uid).html(result.text);
	}, "json");
	$("#dialog" + uid).dialog();
}

function gotoVerse(query) {
	$("#queryString").val(query);
	selectedWindowBible.boQuery = query;
	selectedWindowBible.boTranslationId = $("#translationHidden").html();
	selectedWindowBible.boTranslationName = $("#translationLabel").html();
	doQuery(selectedWindowBible);
}

function strongDialog(strong) {
	var wnd = openWindow("lexicon");

	// onWindowSelect(selectedWindowBible);

	$.post("Lexicon", {
		key : "",
		strong : strong,
		lexicon : "",
		lang : language
	}, function(result) {
		viewLexicon(wnd, result.key, result.strong, result.text, result.error);
	}, "json");
}

function translationSelect(datafile, label) {
	$("#translationLabel").html(label);
	$("#translationHidden").html(datafile);
	collapseDropDown("#cTranslations");
	loadBibleBooks(datafile);
	generateQueryTranslationChanged(datafile);
}

function loadLanguages() {
	$("#cLanguages").load('LanguageSelect?lang=' + language);
}

function requestLanguageHelp(langCode, langName) {
	window.location = 'http://pootle.bible-online.cz/projects/bibleonline/';
}

function viewLicence() {
	$.get("Information?translation=" + selectedWindowBible.boTranslationId
			+ "&lang=" + language, "", function(result) {
		var res = "";
		res += _("File Information:") + "\n";
		res += result.information + "\n\n";
		res += _("License:") + "\n";
		res += result.license + "\n\n";
		res += _("Contact information:") + "\n";
		res += result.contact + "\n\n";
		res += _("URL:") + "\n";
		res += result.url;
		alert(res);
	}, "json");
}

// Search
function searchSearchNew() {
	selectedWindowSearch = null;
	searchSearch();
}

function searchSearch() {

	if (selectedWindowSearch == null) {
		openWindow("search");
		onWindowSelect(selectedWindowBible);
	}

	if (selectedWindowBible == null) {
		selectedWindowSearch.boRange = "";
		selectedWindowSearch.boTranslationId = $("#translationHidden").html();
		selectedWindowSearch.boTranslationName = $("#translationLabel").html();
		selectedWindowSearch.boRelatedWindowBible = null;
	} else {
		selectedWindowSearch.boRange = selectedWindowBible.boSelectedRange;
		selectedWindowSearch.boTranslationId = selectedWindowBible.boTranslationId;
		selectedWindowSearch.boTranslationName = selectedWindowBible.boTranslationName;
		selectedWindowSearch.boRelatedWindowBible = selectedWindowBible;
	}

	selectedWindowSearch.boQuery = $('#searchInputText').val();
	ctx = $('input[name=baz]:checked').val();
	sens = "se"; // $('#').val();
	vowels = "vo"; // $('#').val();
	last = "la"; // $('#').val();

	$.post("Search", {
		query : selectedWindowSearch.boQuery,
		books : selectedWindowSearch.boRange,
		ctx : ctx,
		sens : sens,
		vowels : vowels,
		last : last,
		lang : language,
		trans : selectedWindowSearch.boTranslationId
	}, function(result) {
		searchResults(result.results, result.error, result.bookOrder,
				selectedWindowSearch.boQuery,
				selectedWindowSearch.boTranslationName);
	}, "json");
}

function searchResults(results, error, bookOrder, query, boTranslationName) {
	if (error != "")
		showError("Error", error);

	var pager = "<div id=\"pager\" class=\"pager\"><form>";
	pager += "<img src=\"css/i/first.png\" class=\"first\"/>";
	pager += "<img src=\"css/i/prev.png\" class=\"prev\"/>";
	pager += "<input type=\"text\" class=\"pagedisplay\"/>";
	pager += "<img src=\"css/i/next.png\" class=\"next\"/>";
	pager += "<img src=\"css/i/last.png\" class=\"last\"/>";
	pager += "<select class=\"pagesize\"><option selected=\"selected\" value=\"10\">10</option><option value=\"50\">50</option><option value=\"100\">100</option><option value=\"999999\">All</option></select>";
	pager += "</form></div>";

	selectedWindowSearch.setContent(pager + results);
	selectedWindowSearch.setTitle(_("Search results") + ": " + query + " ("
			+ boTranslationName + ")");

	selectedWindowSearch.bookOrder = new BOHash();
	for (i = 0; i < bookOrder.length; i++) {
		selectedWindowSearch.bookOrder.setItem(bookOrder[i], i);
	}

	$.tablesorter.addParser( {
		// set a unique id
		id : 'passages',
		is : function(s) {
			return false;
		},
		format : function(s) {
			var space = s.indexOf(' ');
			var spaceLength = 1;
			if (space == -1) {
				space = s.indexOf('&nbsp;');
				spaceLength = 5;
			}
			var colon = s.indexOf(':');
			if (space != -1 && colon != -1) {
				var b = s.substr(0, space);
				var ch = s.substr(space + spaceLength + 1, colon - space
						- spaceLength - 1);
				var v = s.substr(colon + 1);
				b = selectedWindowSearch.bookOrder.getItem(b);
				if (b != undefined) {
					s = b * 1000000 + parseInt(ch) * 1000 + parseInt(v);
				}
			}
			return s;
		},
		type : 'numeric'
	});

	$("#" + selectedWindowSearch.getWindowId() + " .window_frame .tablesorter")
			.tablesorter( {
				widthFixed : true,
				sortMultiSortKey : 'ctrlKey',
				widgets : [ 'zebra' ],
				headers : {
					1 : {
						sorter : 'passages'
					}
				}
			}).tablesorterPager( {
				container : $("#pager"),
				positionFixed : false
			});

}

function onfocusSearch() {
	closeAllCollapsible();
	if ($("#searchInputText").val() == _("Search phrase"))
		$("#searchInputText").val("");
	else {
		$("#searchInputText").select();
	}
}

function onblurSearch() {
	if ($("#searchInputText").val() == "")
		$("#searchInputText").val(_("Search phrase"));
}

function openSearch(tr, bookSynch, book, chapter, verse) {

	if (selectedWindowBible == null) {
		openWindow("bible");
		selectedWindowSearch.boRelatedWindowBible = selectedWindowBible;
	}

	selectedWindowBible.boTranslationName = selectedWindowSearch.boTranslationName;
	selectedWindowBible.boTranslationId = selectedWindowSearch.boTranslationId;
	selectedWindowBible.boQuery = book + ' ' + chapter + ':' + verse;

	$.post("GetVerses", {
		query : book + ' ' + chapter + ':' + verse,
		wholeChapter : true,
		bookIdType : 'shortName',
		translation : tr,
		lang : language,
		searchQuery : selectedWindowSearch.boQuery
	}, function(result) {
		viewText(selectedWindowBible, result.query + " "
				+ selectedWindowBible.boTranslationName, result.direction,
				result.error, result.text, result.focusVerse,
				result.verseHighlight, result.shortLicense);
	}, "json");
}

function rangeSelectShow() {

	if ($("#searchRangeSelect").css("display") == "none") {
		$("#searchRangeSelect").load(
				'BibleBooks?trans=' + selectedWindowBible.boTranslationId
						+ '&lang=' + language + '&selection=true', function() {
					setSelectedBooksFromWindowToRange(selectedWindowBible);
				});
		dropDown("#searchRangeSelect", "#buttonSearchRange", -193, 0);
	} else {
		collapseDropDown("#searchRangeSelect");
	}
}

function setSelectedBooksFromRangeToWindow(wnd) {
	if (wnd != undefined && wnd != "") {
		var books = "";
		var selCssBooks = $(".searchSelectedBook");
		for ( var i = 0; i < selCssBooks.length; i++) {
			books += selCssBooks[i].id + "~";
		}
		wnd.boSelectedRange = books;
	}
}

function setSelectedBooksFromWindowToRange(wnd) {

	// remove any selection
	$(".sbBook").removeClass("searchSelectedBook");

	if (wnd.boSelectedRange != undefined && wnd.boSelectedRange != "") {
		var books = wnd.boSelectedRange.split("~");
		for ( var i = 0; i < books.length; i++) {
			if (books[i] != "") {
				$("#" + books[i]).addClass("searchSelectedBook");
			}
		}
	}
}

function dropDown(element, caller, xx, yy) {
	if ($(element).css("display") == "block") {
		closeAllCollapsible();
	} else {
		closeAllCollapsible();
		$(element).css( {
			'left' : $(caller).position().left + xx,
			'top' : $(caller).position().top + $(caller).height() + 4 + yy,
			'display' : 'block'
		});
	}
}

function collapseDropDown(element) {
	if (element == "#searchRangeSelect") {
		setSelectedBooksFromRangeToWindow(selectedWindowBible);
	}

	$(element).css( {
		'display' : 'none'
	});
}

function closeAllCollapsible() {
	collapseDropDown('#cTranslations');
	collapseDropDown('#cBooks');
	collapseDropDown('#cLanguages');
	collapseDropDown('#cQueryHistory');
	collapseDropDown('#cSearchHistory');
	collapseDropDown('#cQueryExamples');
	collapseDropDown('#cSearchExamples');
	collapseDropDown('#cSearchSettings');
	collapseDropDown('#searchRangeSelect');
}

function searchSelectBook(itemId) {
	if ($("#" + itemId).hasClass("searchSelectedBook")) {
		$("#" + itemId).removeClass("searchSelectedBook");
	} else {
		$("#" + itemId).addClass("searchSelectedBook");
	}
}

function sectionSelection(keyString) { // add tick boxes to show a book has
	// been inserted to search
	var keys = eval('(' + keyString + ')');
	var len = keys.books.length;
	for ( var i = 0; i < len; i++) {
		searchSelectBook("sbIt_" + keys.books[i]);
	}
}

function scrollToVerse(windowId, focusTo) { // jQuery selector; focusTo can be
	// #NTJoh_3_16~-87
	if (focusTo != NaN) {
		$("#" + windowId.getWindowId() + " .window_frame").scrollTop(0);
		var frameTop = $("#" + windowId.getWindowId() + " .window_frame")
				.offset().top;
		focusCombined = focusTo.split("~");
		if (focusCombined.length > 1) // additional delta defined
			focusDelta = focusCombined[1];
		else
			focusDelta = 0;

		var focusTop = $(
				"#" + windowId.getWindowId() + " .window_frame #"
						+ focusCombined[0]).offset().top;
		$("#" + windowId.getWindowId() + " .window_frame").scrollTop(
				focusTop - frameTop - focusDelta);
	}
}

function highlightSelection(wnd, verseHighlight) {
	for ( var int = 0; int < verseHighlight.length; int++) {
		$("#" + wnd.getWindowId() + " .window_frame #" + verseHighlight[int])
				.css( {
					'background' : '#FFFBC1'
				});
	}
}

function synchronizeContentDelay(masterHtmlWindow) {
	if (scrollTimeout != null)
		window.clearTimeout(scrollTimeout);

	var parentNode = masterHtmlWindow.target.parentNode;
	if (parent == undefined)
		parentNode = masterHtmlWindow.target.parentElement;
	var masterWindowId = parentNode.id;
	scrollTimeout = window.setTimeout(function() {
		synchronizeContent(masterWindowId);
		masterWindowId = null;
	}, syncDelay);
	// synchronizeContent(masterWindowId);
}

function synchronizeContent(masterWindowId) {

	if (typeof (masterWindowId) == "string")
		masterWindowId = $.window.getWindow(masterWindowId);

	var wnds = windowGetAll("bible");
	if (wnds.length > 1) {
		var verseId = getGetTopVerseId(masterWindowId);
		if (verseId != "") {
			for ( var i = 0; i < wnds.length; i++) {
				if (wnds[i].getWindowId() != masterWindowId.getWindowId()) {
					scrollToVerse(wnds[i], verseId);
				}
			}
		}
	}
}

function getGetTopVerseId(windowId) {
	var result = "";

	var firstId = $(
			"#" + windowId.getWindowId() + " .window_frame .verse:first").attr(
			"id");
	if (firstId != undefined) {
		var id1 = firstId.substring(0, firstId.length - 1);
		var lastId = $(
				"#" + windowId.getWindowId() + " .window_frame .verse:last")
				.attr("id");
		var maxId2 = lastId.substring(firstId.length - 1, lastId.length);
		var frameTop = $("#" + windowId.getWindowId() + " .window_frame")
				.offset().top;

		var verseTop = -99999;
		var minTop = 99999;
		var selectorPrefix = "#" + windowId.getWindowId() + " .window_frame #"
				+ id1;
		for ( var id2 = 1; id2 <= maxId2; id2++) {
			verseTop = $(selectorPrefix + id2).offset().top - frameTop;
			if (Math.abs(verseTop) < Math.abs(minTop)) {
				minTop = verseTop;
				result = id1 + id2 + "~" + verseTop;
			}
		}
	}
	return result;
}

function ieWarning() {
	$("#ieWarning").dialog( {
		dialogClass : 'alert',
		modal : true,
		resizable : false,
		width : 540,
		title : _("Notification"),
		buttons : {
			"OK" : function() {
				$(this).dialog("close");
			}
		}
	});
}

function submitPoll(container) {
	var v = $("#poll form input:radio:checked").val();
	if (v == undefined) {
		alert('Select an answer');
	} else {
		if (v == "own") {
			v = $("#poll form textarea").val();
		}
		$.get("Poll", {
			poll : "1",
			question : "1",
			answer : v
		}, function(result) {
			if (result.status == 1)
				$("#poll").html("Your vote has been submited. Thank you.");
			else
				$("#poll").html("Error");
		}, "json");
	}
}

function ownIdeaOnclick() {
	$("#poll form input:radio[value=own]").attr('checked', true);
}

function BOHash() {
	this.length = 0;
	this.items = new Array();
	for ( var i = 0; i < arguments.length; i += 2) {
		if (typeof (arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}

	this.removeItem = function(in_key) {
		var tmp_previous;
		if (typeof (this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_previous = this.items[in_key];
			delete this.items[in_key];
		}

		return tmp_previous;
	};

	this.getItem = function(in_key) {
		return this.items[in_key];
	};

	this.setItem = function(in_key, in_value) {
		var tmp_previous;
		if (typeof (in_value) != 'undefined') {
			if (typeof (this.items[in_key]) == 'undefined') {
				this.length++;
			} else {
				tmp_previous = this.items[in_key];
			}

			this.items[in_key] = in_value;
		}

		return tmp_previous;
	};

	this.hasItem = function(in_key) {
		return typeof (this.items[in_key]) != 'undefined';
	};

	this.clear = function() {
		for ( var i in this.items) {
			delete this.items[i];
		}

		this.length = 0;
	};
}
