/* MRJSlib (c) 2008 - 2009 Wirtualna Polska www.wp.pl */
/* Do not copy or modify any part of the following code without permition */

if (typeof bliscy == 'undefined') {
	var bliscy = {};
	bliscy.action = {};
	bliscy.event = {};
	bliscy.global = {};
	bliscy.lib = {};

	bliscy.action.alphabeticallist = {};
	bliscy.action.chronology = {};
	bliscy.action.exporttree = {};
	bliscy.action.popuphelp = {};
	bliscy.action.printtree = {};
	bliscy.action.removeCycle = {};
	bliscy.action.removePerson = {};
	bliscy.action.themechanger = {};
	bliscy.action.wpmapy = {};
	bliscy.action.wpmapy.edit = {};
	bliscy.action.wpmapy.profile = {};
	bliscy.action.wpmapy.search = {};

	bliscy.event.alphabeticallist = {};
	bliscy.event.chronology = {};
	bliscy.event.exporttree = {};
	bliscy.event.invite = {};
	bliscy.event.message = {};
	bliscy.event.printtree = {};
	bliscy.event.profile = {};
	bliscy.event.removeCycle = {};
	bliscy.event.removePerson = {};
	bliscy.event.subtree = {};
	bliscy.event.themechanger = {};
	bliscy.event.window = {};

	bliscy.global.actionName = {};
	bliscy.global.viewName = {};

	bliscy.lib.ajax = {};
	bliscy.lib.browser = {};
	bliscy.lib.profiler = {};
	bliscy.lib.tree = {};
	bliscy.lib.vector = {};
	bliscy.lib.window = {};
}

bliscy.global.actionName.createPerson = 'CreatePersonAction';
bliscy.global.actionName.createCycle = 'CreateCycleAction';
bliscy.global.actionName.createMe = 'CreateMeAction';
bliscy.global.actionName.removePerson = 'RemovePersonAction';
bliscy.global.actionName.removeCycle = 'RemoveCycleAction';
bliscy.global.viewName.ajaxView = 'ajax.html';
bliscy.global.viewName.ajaxChronologyView = 'ajaxchronology.html';
bliscy.global.viewName.ajaxPersonView = 'ajaxperson.html';
bliscy.global.viewName.treeView = 'drzewo.html';
bliscy.global.temporaryTree = false;

bliscy.action.alphabeticallist._window = undefined;

bliscy.action.alphabeticallist.prepare = function() {
	if (typeof $('bxAlphabeticalList') != 'object') {
		return;
	}

	var w = new bliscy.lib.window.Window('bxAlphabeticalList', 'mrWindows');
	w.setPosition(w.POS_LEFT, w.POS_TOP);
	w.setOffset(90, 27);
	this._window = w;
}

bliscy.action.alphabeticallist.show = function() {
	this._window.show();
}

bliscy.action.alphabeticallist.hide = function() {
	this._window.hide();
}

bliscy.action.alphabeticallist.slide = function(offset) {
	var child = $('alSlider').childNodes;
	var count = child.length;
	if (0 >= count) {
		return;
	}
	var width = child[0].offsetWidth * count;
	var visibleWidth = 3*190;
	var leftInt = parseInt($('alSlider').style.left) + offset;
	if (leftInt > 0 || width + leftInt < visibleWidth) {
		return;
	}
	$('alSlider').style.left =  leftInt + 'px';
	if (0 == leftInt) {
		$('alLeft').hide();
	} else {
		$('alLeft').show();
	}
	if (width + leftInt == visibleWidth) {
		$('alRight').hide();
	} else {
		$('alRight').show();
	}
}

bliscy.action.chronology._prepared = false;
bliscy.action.chronology._shown = false;
bliscy.action.chronology._window = undefined;
bliscy.action.chronology._slider = undefined;

bliscy.action.chronology.prepare = function() {
	if (typeof $('bxChronology') != 'object') {
		return;
	}

	var w = new bliscy.lib.window.Window('bxChronology', 'mrWindows');
	w.setPosition(w.POS_RIGHT, w.POS_BOTTOM);
	this._window = w;

	w.show();

	var child = $('clSlider').childNodes;
	var count = child.length;
	var width = 0;
	if (count > 0) {
		width = child[0].offsetWidth;
		width *= count;
	}

	w.hide();

	var s = new bliscy.lib.window.Slider('clSlider');
	s.width = width;
	this._slider = s;

	this._prepared = true;
}

bliscy.action.chronology.show = function() {
	this._window.show();
	this._shown = true;
}

bliscy.action.chronology.hide = function() {
	this._window.hide();
	this._shown = false;
}

bliscy.action.chronology.handle = function() {
	if (!this._prepared) {
		var mruidParam = '';
		if (typeof global_mruid != 'undefined') {
			mruidParam = '?mruid=' + global_mruid;
		}
		WP.ajax.get({
			url: bliscy.global.viewName.ajaxChronologyView + mruidParam,
			onSuccess: function(ajax) {
					$('bxChronologicalList').innerHTML = ajax.text;
					WP.event.set('clClose', 'onclick', bliscy.event.chronology.clickClose);
					WP.event.set('clLeft', 'onclick', bliscy.event.chronology.clickLeft);
					WP.event.set('clRight', 'onclick', bliscy.event.chronology.clickRight);
					WP.event.set('clLeft', 'ondblclick', bliscy.event.chronology.clickLeft);
					WP.event.set('clRight', 'ondblclick', bliscy.event.chronology.clickRight);
					bliscy.action.chronology.prepare();
					bliscy.action.chronology.resize();
					bliscy.action.chronology.show();
				}
			});
	} else if (this._shown) {
		this.hide();
	} else {
		this.show();
	}
}

bliscy.action.chronology.resize = function() {
	if (typeof $('bxMojaRodzina') != 'object') {
		return;
	}

	var width = 0;
	width += parseInt($('bxMojaRodzina').style.width);
	width -= 90;
	$('bxChronology').style.width = width + 'px';
	width -= 10;
	$('clNavigation').style.width = width + 'px';
	width -= 25;
	$('clnScroll').style.width = width + 'px';

	if (this._shown) {
		this.hide();
		this.show();
	}
}

bliscy.action.chronology.slide = function(offset) {
	this._slider.move(offset);

	var sWidth = this._slider.width;
	var pWidth = this._slider._window.parentNode.offsetWidth;

	var cur = this._slider._left;
	var max = sWidth - pWidth;
	var pos = cur / max;

	if (max < 0) {
		return;
	}

	var cWidth = $('clnScroll').offsetWidth - 3*19;
	var cLeft = cWidth * pos + 19;
	$('clnSlider').style.left = cLeft + 'px';
}

bliscy.action.cutLongNames = function() {
	if (WP.isSafari || WP.isIE) {
		return;
	}

	if (typeof global_mruid == 'undefined') {
		return;
	}

	var Text = new bliscy.lib.vector.Text();
	var pids = Person.getPids();

	var fn = $('fn-' + global_mruid);
	var ln = $('ln-' + global_mruid);

	var fnw = 0;
	var lnw = 0;

	if (typeof fn == 'object') {
		fnw = parseInt(WP.ie ? fn.offsetWidth : fn.getAttribute('width'));
	}

	if (typeof ln == 'object') {
		lnw = parseInt(WP.ie ? ln.offsetWidth : ln.getAttribute('width'));
	}

	if (!fn) {
		return;
	}

	for (var i in pids) {
		Text.cutToWidth($('fn-' + pids[i]), fnw);
		Text.cutToWidth($('ln-' + pids[i]), lnw);
	}
}

bliscy.action.displayProfile = function(id) {
	window.location.href = 'mruid,' + id + ',profil.html';
}

bliscy.action.displaySubTree = function(id) {
	window.location.href = 'mruid,' + id + ',' + bliscy.global.viewName.treeView;
}

bliscy.action.exporttree._window = undefined;

bliscy.action.exporttree.prepare = function() {
	if (typeof $('bxExportTree') != 'object') {
		return;
	}

	var w = new bliscy.lib.window.Window('bxExportTree', 'mrWindows');
	w.setPosition(w.POS_LEFT, w.POS_TOP);
	w.setOffset(90, 27);
	this._window = w;

	this.hide();
}

bliscy.action.exporttree.show = function() {
	this._window.show();
}

bliscy.action.exporttree.hide = function() {
	this._window.hide();
}

bliscy.action.fitTreeToWindow = function() {
	if (typeof $('bxMojaRodzina') != 'object') {
		return;
	}

	if (WP.cookie.get('bliscyMaximize') == 0) {
		return;
	}

	var header = 0;
	var headerDivs = new Array('wpHeaderCpl', 'wpAdvTop', 'wpNavi', 'wpAdvExtra', 'wpWL', 'wpSearch');

	for (var i = 0; i < headerDivs.length; i++) {
		var hId = headerDivs[i];

		if (typeof $(hId) == 'object') {
			header += $(hId).offsetHeight;
		}
	}

	var minimumHeight = $('mrTreeControls').offsetHeight + $('mrTreeButtons').offsetHeight;
	var minimumWidth = $('wpHeaderCpl').offsetWidth;

	var Window = new bliscy.lib.browser.Window();	
	var treeHeight = Window.getHeight() - (header + 30);
	var treeWidth = Window.getWidth() - 30;

	if (treeHeight < minimumHeight) {
		treeHeight = minimumHeight;
	}

	if (treeWidth < minimumWidth) {
		treeWidth = minimumWidth;
	}

	$('bxMojaRodzina').style.height = treeHeight + 'px';
	$('bxMojaRodzina').style.width = treeWidth + 'px';
	$('wpMain').style.width = treeWidth + 'px';

	Tree.goToXY(Tree.x, Tree.y);
}

bliscy.action.fixImagesInFF2 = function() {
	if (typeof $('bxMojaRodzina') != 'object') {
		return;
	}

	if (!WP.isGecko || typeof document.body.getBoundingClientRect != 'undefined') {
		return;
	}

	var svgNS = 'http://www.w3.org/2000/svg';
	var xlinkNS = 'http://www.w3.org/1999/xlink';

	var imgs = document.getElementsByTagName('image');

	for (var i = 0; i < imgs.length; i++) {
		var p = imgs[i].parentNode;
		var ni = document.createElementNS(svgNS, 'image');

		ni.setAttribute('x', imgs[i].getAttribute('x'));
		ni.setAttribute('y', imgs[i].getAttribute('y'));
		ni.setAttribute('width', imgs[i].getAttribute('width'));
		ni.setAttribute('height', imgs[i].getAttribute('height'));
		ni.setAttribute('id', imgs[i].getAttribute('id'));
		ni.setAttribute('class', imgs[i].getAttribute('class'));
		ni.setAttributeNS(xlinkNS, 'href', imgs[i].getAttribute('xlink:href'));

		p.replaceChild(ni, imgs[i]);
	}
}

bliscy.action.invitePerson = function(id) {
	window.location.href = 'invid,' + id + ',added,' + o('mrTreeImage').mrClass + ',rodzina.html';
}

bliscy.action.popuphelp.prepare = function(pages) {
	if (typeof $('bxPopupHelp') != 'object') {
		return;
	}
	PopupHelp.init(pages);
}

bliscy.action.popuphelp.show = function(page) {
	if (typeof $('bxPopupHelp') != 'object') {
		return;
	}
	PopupHelp.show(page);
}

bliscy.action.printtree._window = undefined;

bliscy.action.printtree.prepare = function() {
	if (typeof $('bxPrintTree') != 'object') {
		return;
	}

	var w = new bliscy.lib.window.Window('bxPrintTree', 'mrWindows');
	w.setPosition(w.POS_LEFT, w.POS_TOP);
	w.setOffset(90, 27);
	this._window = w;

	this.hide();
}

bliscy.action.printtree.show = function() {
	this._window.show();
	$('ptPreview').src = 'theme,4,format,png,mruid,' + global_mruid + ',drzewo_pobierz.html';
}

bliscy.action.printtree.hide = function() {
	this._window.hide();
}

bliscy.action.removeCycle.confirm = function(mruid, marriageId) {
	if (!confirm('Czy na pewno chcesz usunąć ten cykl?')) {
		return;
	}

	var url = '_action,' + bliscy.global.actionName.removeCycle + ',mruid,' + mruid + ',marriageId,' + marriageId + ',' + bliscy.global.viewName.ajaxView;
	var callback = bliscy.action.removeCycle.refresh;
	var Ajax = new bliscy.lib.ajax.Request(url, callback);
	Ajax.get();
}

bliscy.action.removeCycle.refresh = function(nearestId) {
	var mruid = 0;

	if (nearestId > 0) {
		mruid = nearestId;
	} else {
		mruid = o('mrTreeImage').mrClass;
	}

	window.location.href = 'mruid,' + mruid + ',' + bliscy.global.viewName.treeView;
}

bliscy.action.removePerson.confirm = function(id) {
	if (!confirm('Czy na pewno chcesz usunąć tę osobę z drzewa?')) {
		return;
	}

	var url = '_action,' + bliscy.global.actionName.removePerson + ',mruid,' + id + ',' + bliscy.global.viewName.ajaxView;
	var callback = bliscy.action.removePerson.refresh;
	var Ajax = new bliscy.lib.ajax.Request(url, callback);
	Ajax.get();
}

bliscy.action.removePerson.refresh = function(nearestId) {
	var mruid = 0;

	if (nearestId > 0) {
		mruid = nearestId;
	} else {
		mruid = o('mrTreeImage').mrClass;
	}

	window.location.href = 'mruid,' + mruid + ',' + bliscy.global.viewName.treeView;
}

bliscy.action.sendMessage = function(id) {
	window.location.href = 'mruid,' + id + ',wiadomosc_napisz.html';
}

bliscy.action.themechanger._window = undefined;

bliscy.action.themechanger.prepare = function() {
	if (typeof $('bxThemeChanger') != 'object') {
		return;
	}

	var w = new bliscy.lib.window.Window('bxThemeChanger', 'mrWindows');
	w.setPosition(w.POS_LEFT, w.POS_TOP);
	w.setOffset(90, 27);
	this._window = w;

	this.hide();
}

bliscy.action.themechanger.changeColor = function(node) {
	var colors = o(node).mrClass;
	colors = colors.split(',');

	var action = 'UpdatePersonTreeColorsAction';

	if (bliscy.global.temporaryTree) {
		action = 'UpdateTemporaryPersonTreeColorsAction';
	}

	window.location.href = '?_action=' + action + '&femaleColor=' + colors[1] + '&maleColor=' + colors[0];
}

bliscy.action.themechanger.changeTheme = function(node) {
	var theme = o(node.parentNode).mrUid;
	WP.cookie.set('bliscyTheme', theme);
	window.location.href = window.location.href;
}

bliscy.action.themechanger.changeMaximize = function() {
	var maximize = $('tcMaximize').checked == true ? 1 : 0;
	WP.cookie.set('bliscyMaximize', maximize);
	window.location.href = window.location.href;
}

bliscy.action.themechanger.show = function() {
	this._window.show();
}

bliscy.action.themechanger.hide = function() {
	this._window.hide();
}

bliscy.action.wpmapy.edit.clearFlags = function() {
	var flags = DoCelu.getFlagsIds();

	for (var i = 0; i < flags.length; i++) {
		DoCelu.removeFlag(flags[i]);
	}
}

bliscy.action.wpmapy.edit.displayCountries = function(status, result) {
	if (status.failed) {
		return;
	}

	for (var i in result) {
		var country = result[i];
		var option = document.createElement("option");
		option.value = country;
		option.appendChild(document.createTextNode(country));

		if (typeof UpdatePersonCountry != 'undefined' && country == UpdatePersonCountry) {
			option.setAttribute('selected', 'selected');
		}

		$('uplSelectCountry').appendChild(option);
	}
}

bliscy.action.wpmapy.edit.displayMap = function() {
	if (typeof $('uplMapContainer') != 'object') {
		return;
	}

	var config = {
		'features' : {
			'distanceModule' : false,
			'legend' : false,
			'logo' : false,
			'markLocation' : false,
			'minimap' : false,
			'print' : false,
			'routeModule' : false,
			'ruler' : false,
			'searchInRange' : false,
			'searchMarkerOptions' : false
		}
	}

	DoCelu.loadMap(document.getElementById('uplMapContainer'), config, function() {
		if (typeof UpdatePersonLocation != 'undefined') {
			bliscy.action.wpmapy.edit.setLocation(UpdatePersonLocation);
		}
	});

	DoCelu.getCountries(function(A, B) {
		bliscy.action.wpmapy.edit.displayCountries(A, B);
	});
}

bliscy.action.wpmapy.edit.save = function() {
	var f = DoCelu.getFlagsIds();

	if (f.length == 0) {
		$('uplHiddenLatitude').value = '';
		$('uplHiddenLongitude').value = '';
		return true;
	}

	var p = DoCelu.getFlagPosition(f[0]);

	$('uplHiddenLatitude').value = p.lat;
	$('uplHiddenLongitude').value = p.lon;
	return true;
}

bliscy.action.wpmapy.edit.search = function() {
	var sco = $('uplSelectCountry');
	var tci = $('uplTextCity');

	tci.onfocus();

	var scov = sco.value;
	var tciv = tci.value;

	tci.onblur();

	if (scov == '') {
		return false;
	}

	DoCelu.searchCity(tciv, scov, 0, "size", true, 0, bliscy.action.wpmapy.edit.searchCityHandler);
	return false;
}

bliscy.action.wpmapy.edit.searchCityHandler = function(status, result) {
	if (status.failed || result.count == 0) {
		alert('Nie znaleziono miasta.');
		return false;
	}
	
	var select = $('uplSelectCity');
	var parent = select.parentNode;
	parent.replaceChild(select.cloneNode(false), select);
	
	$('uplSelectCity').onchange = function() {
		return bliscy.action.wpmapy.edit.search2(this.options[this.selectedIndex].locality);
	};

	bliscy.action.wpmapy.edit.search2(result.data[0]);

	if (result.count == 1) {
		$('uplParagraphCity').hide();
		return false;
	}

	$('uplParagraphCity').show();
	var rd = result.data;

	for (var j = 0; j < result.count; j++) {
		var opt = document.createElement('option');
		opt.appendChild(document.createTextNode(rd[j].name + ', ' + rd[j].county));
		opt.value = rd[j].localityId;
		opt.locality = rd[j];
		$('uplSelectCity').appendChild(opt);
	}

	return false;
}

bliscy.action.wpmapy.edit.search2 = function(cityResult) {
	var r = cityResult;
	var i = r.localityId;
	var s = $('uplTextStreet');
	var n = $('uplTextNumber');

	s.onfocus();
	n.onfocus();

	var sv = s.value;
	var nv = n.value;

	s.onblur();
	n.onblur();

	if (sv == '') {
		bliscy.action.wpmapy.edit.setLocation(r.localityGeom, r.zoom);
	} else if (nv == '') {
		DoCelu.searchStreet(sv, i, 0, 1, bliscy.action.wpmapy.edit.searchStreetHandler);
	} else {
		DoCelu.searchBuilding(sv, nv, i, bliscy.action.wpmapy.edit.searchBuildingHandler);
	}

	return false;
}

bliscy.action.wpmapy.edit.searchStreetHandler = function(status, result) {
	if (status.failed || result.count == 0) {
		alert('Nie znaleziono ulicy.');
		return false;
	}

	bliscy.action.wpmapy.edit.setLocation(result.data[0].roadGeom, result.data[0].zoom);
	return false;
}

bliscy.action.wpmapy.edit.searchBuildingHandler = function(status, result) {
	if (status.failed || typeof result.point == 'undefined') {
		alert('Nie znaleziono budynku.');
		return false;
	}
	
	bliscy.action.wpmapy.edit.setLocation(result.point, 16);
	return false;
}

bliscy.action.wpmapy.edit.setLocation = function(location, zoom) {
	bliscy.action.wpmapy.edit.clearFlags();
	DoCelu.addFlag(location);

	if (typeof zoom == 'undefined') {
		zoom = 5;
	}

	location.zoom = zoom;
	DoCelu.setMapView(location);
}

bliscy.action.wpmapy.profile.displayMap = function() {
	if (typeof $('aiMapContainer') != 'object') {
		return;
	}

	var config = {
		'features' : {
			'distanceModule' : false,
			'legend' : false,
			'logo' : false,
			'mapMoving' : false,
			'mapZooming' : false,
			'markLocation' : false,
			'minimap' : false,
			'navigationPanel' : false,
			'print' : false,
			'routeModule' : false,
			'ruler' : false,
			'searchInRange' : false,
			'searchMarkerOptions' : false
		}
	}

	DoCelu.loadMap(document.getElementById('aiMapContainer'), config, function(){
		if (typeof PersonLocation != 'undefined') {
			DoCelu.showCursor(PersonLocation);
			PersonLocation.zoom = 5;
			DoCelu.setMapView(PersonLocation);
		}
	});
}

bliscy.action.wpmapy.search.displayMap = function() {
	if (typeof $('srlMapContainer') != 'object') {
		return;
	}

	var config = {
		'features' : {
			'distanceModule' : false,
			'legend' : false,
			'logo' : false,
			'markLocation' : false,
			'minimap' : false,
			'print' : false,
			'routeModule' : false,
			'ruler' : false,
			'searchInRange' : false,
			'searchMarkerOptions' : false
		}
	}

	DoCelu.loadMap(document.getElementById('srlMapContainer'), config, function() {
		DoCelu.addCategory(poiCategory);
		DoCelu.showCategories([poiCategory.id]);
		DoCelu._flashApp.handlePoiTileResponse(poiStatus, poiResponse);
	});
}

bliscy.event.alphabeticallist.clickMenu = function() {
	Shadow.show();
	bliscy.action.alphabeticallist.show();
}

bliscy.event.alphabeticallist.clickClose = function() {
	bliscy.action.alphabeticallist.hide();
	Shadow.hide();
}

bliscy.event.alphabeticallist.clickLeft = function() {
	bliscy.action.alphabeticallist.slide(+190);
}

bliscy.event.alphabeticallist.clickRight = function() {
	bliscy.action.alphabeticallist.slide(-190);
}

bliscy.event.chronology.clickMenu = function() {
	bliscy.action.chronology.handle();
}

bliscy.event.chronology.clickClose = function() {
	bliscy.action.chronology.hide();
}

bliscy.event.chronology.clickLeft = function() {
	bliscy.action.chronology.slide(-88);
}

bliscy.event.chronology.clickRight = function() {
	bliscy.action.chronology.slide(+88);
}

bliscy.event.exporttree.clickMenu = function() {
	Shadow.show();
	bliscy.action.exporttree.show();
}

bliscy.event.exporttree.clickClose = function() {
	bliscy.action.exporttree.hide();
	Shadow.hide();
}

bliscy.event.exporttree.clickCancel = function(event) {
	event.returnValue = false;

	if (event.preventDefault) {
		event.preventDefault();
	}

	bliscy.action.exporttree.hide();
	Shadow.hide();
}

bliscy.event.invite.click = function(node) {
	var id = o(node).mrUid;
	bliscy.action.invitePerson(id);
}

bliscy.event.message.click = function(node) {
	var id = o(node).mrUid;
	bliscy.action.sendMessage(id);
}

bliscy.event.printtree.clickMenu = function() {
	Shadow.show();
	bliscy.action.printtree.show();
}

bliscy.event.printtree.clickPrint = function(event) {
	event.returnValue = false;

	if (event.preventDefault) {
		event.preventDefault();
	}

	var url = 'mruid,' + $('ptForm').mruid.value + ',';
	url += 'theme,' + $('ptForm').theme.value + ',';
	url += 'format,' + $('ptForm').format.value + ',';
	url += 'drzewo_pobierz.html';

	var opts = '';
	opts += 'width=640,';
	opts += 'height=480,';
	opts += 'resizable=no,';
	opts += 'scrollbars=yes,';
	opts += 'toolbar=no,';
	opts += 'location=no,';
	opts += 'directories=no,';
	opts += 'status=no,';
	opts += 'menubar=no,';
	opts += 'copyhistory=no';

	var p = window.open(url, 'ptWindow', opts);

	if (WP.isIE) {
		p.print();
	} else {
		p.onload = function() {
			this.print();
			this.close();
		}
	}
}

bliscy.event.printtree.clickClose = function() {
	bliscy.action.printtree.hide();
	Shadow.hide();
}

bliscy.event.printtree.clickCancel = function(event) {
	event.returnValue = false;

	if (event.preventDefault) {
		event.preventDefault();
	}

	bliscy.action.printtree.hide();
	Shadow.hide();
}

bliscy.event.profile.click = function(node) {
	var id = o(node).mrUid;
	bliscy.action.displayProfile(id);
}

bliscy.event.removeCycle.click = function(node) {
	var id = node.id;
	id = id.split('-');
	bliscy.action.removeCycle.confirm(id[1], id[2]);
}

bliscy.event.removePerson.click = function(node) {
	var id = o(node).mrUid;
	bliscy.action.removePerson.confirm(id);
}

bliscy.event.subtree.click = function(node) {
	var id = o(node).mrUid;
	bliscy.action.displaySubTree(id);
}

bliscy.event.themechanger.clickMenu = function() {
	Shadow.show();
	bliscy.action.themechanger.show();
}

bliscy.event.themechanger.clickClose = function() {
	bliscy.action.themechanger.hide();
	Shadow.hide();
}

bliscy.event.themechanger.clickColor = function(event) {
	var node = WP.event.getNode(event);
	bliscy.action.themechanger.changeColor(node);
}

bliscy.event.themechanger.clickTheme = function(event) {
	var node = WP.event.getNode(event);
	bliscy.action.themechanger.changeTheme(node);
}

bliscy.event.themechanger.clickMaximize = function() {
	bliscy.action.themechanger.changeMaximize();
}

bliscy.event.window.load = function() {
	bliscy.action.cutLongNames();
	bliscy.action.fixImagesInFF2();
	bliscy.action.fitTreeToWindow();

	if (null != WP.cookie.get('displayHelp') && WP.cookie.get('displayHelp')) {
		bliscy.action.popuphelp.prepare(6);
		bliscy.action.popuphelp.show(1);
		WP.cookie.erase('displayHelp');
	}

	bliscy.action.wpmapy.edit.displayMap();
	bliscy.action.wpmapy.profile.displayMap();
	bliscy.action.wpmapy.search.displayMap();
}

bliscy.event.window.domload = function() {
	WP.event.set('tbChronology', 'onclick', bliscy.event.chronology.clickMenu);

	WP.event.set('tbAlphabeticalList', 'onclick', bliscy.event.alphabeticallist.clickMenu);
	WP.event.set('alClose', 'onclick', bliscy.event.alphabeticallist.clickClose);
	WP.event.set('alLeft', 'onclick', bliscy.event.alphabeticallist.clickLeft);
	WP.event.set('alRight', 'onclick', bliscy.event.alphabeticallist.clickRight);
	WP.event.set('alLeft', 'ondblclick', bliscy.event.alphabeticallist.clickLeft);
	WP.event.set('alRight', 'ondblclick', bliscy.event.alphabeticallist.clickRight);
	bliscy.action.alphabeticallist.prepare();

	WP.event.set('tbExport', 'onclick', bliscy.event.exporttree.clickMenu);
	WP.event.set('etClose', 'onclick', bliscy.event.exporttree.clickClose);
	WP.event.set('etInputCancel', 'onclick', bliscy.event.exporttree.clickCancel);
	bliscy.action.exporttree.prepare();

	WP.event.set('tbPrint', 'onclick', bliscy.event.printtree.clickMenu);
	WP.event.set('ptClose', 'onclick', bliscy.event.printtree.clickClose);
	WP.event.set('ptInputPrint', 'onclick', bliscy.event.printtree.clickPrint);
	WP.event.set('ptInputCancel', 'onclick', bliscy.event.printtree.clickCancel);
	bliscy.action.printtree.prepare();

	WP.event.set('tbTheme', 'onclick', bliscy.event.themechanger.clickMenu);
	WP.event.set('tcClose', 'onclick', bliscy.event.themechanger.clickClose);
	WP.event.set('tc-0', 'onclick', bliscy.event.themechanger.clickTheme);
	WP.event.set('tc-1', 'onclick', bliscy.event.themechanger.clickTheme);
	WP.event.set('tc-2', 'onclick', bliscy.event.themechanger.clickTheme);
	WP.event.set('tc-3', 'onclick', bliscy.event.themechanger.clickTheme);
	WP.event.set('tcColor-1', 'onclick', bliscy.event.themechanger.clickColor);
	WP.event.set('tcColor-2', 'onclick', bliscy.event.themechanger.clickColor);
	WP.event.set('tcColor-3', 'onclick', bliscy.event.themechanger.clickColor);
	WP.event.set('tcColor-4', 'onclick', bliscy.event.themechanger.clickColor);
	WP.event.set('tcMaximize', 'onclick', bliscy.event.themechanger.clickMaximize)
	bliscy.action.themechanger.prepare();

	$('uplButtonUpdate').onclick = function() {
		return bliscy.action.wpmapy.edit.save();
	};
	$('uplButtonSearch').onclick = function() {
		return bliscy.action.wpmapy.edit.search();
	};
}

bliscy.event.window.resize = function() {
	bliscy.action.fitTreeToWindow();
	Shadow.resize();
}

bliscy.global.AddPerson = {
	position: '',
	relation: '',
	relationPersonId: 0,
	relationMarriageId: 0,

	reset: function() {
		this.position = '';
		this.relation = '';
		this.relationPersonId = 0;
		this.relationMarriageId = 0;
	}
}

bliscy.lib.ajax.Request = function(url, action) {

	this._action = action;
	this._form = undefined;
	this._url = url;

	this.get = function() {
		try {
			WP.ajax.get(this._prepare());
		} catch (e) {
			this._exception(e);
		}
	}

	this.post = function() {
		try {
			WP.ajax.post(this._prepare());
		} catch (e) {
			this._exception(e);
		}
	}

	this.setForm = function(form) {
		this._request.form = form;
	}

	this._error = function() {
		window.location.href = window.location.href;
	}

	this._exception = function(e) {
		this._warning('Operacja nieudana.');
	}

	this._prepare = function() {
		var _this = this;
		return {
			form: this._form,
			onSuccess: function(ajax) {
				_this._success(ajax)
			},
			onError: function(ajax) {
				_this._success(ajax)
			},
			url: this._url
		}
	}

	this._success = function(ajax) {
		var text = ajax.text;

		if (text.indexOf('OK ') == 0) {
			this._action(text.substr(3));
		} else if (text.indexOf('ER ') == 0) {
			this._warning(text.substr(3));
		} else {
			this._error();
		}
	}

	this._warning = function(text) {
		alert(text);
	}
}

bliscy.lib.browser.Body = function() {

	this.getWidth = function() {
		return document.body.clientWidth;
	}

	this.getHeight = function() {
		return document.body.clientHeight;
	}
}

bliscy.lib.browser.Window = function() {

	this.getWidth = function() {
		if (WP.isIE) {
			return document.documentElement.clientWidth;
		} else {
			return window.innerWidth;
		}
	}

	this.getHeight = function() {
		if (WP.isIE) {
			return document.documentElement.clientHeight;
		} else {
			return window.innerHeight;
		}
	}

	this.getX = function() {
		if (WP.isIE) {
			return document.documentElement.scrollLeft;
		} else {
			return window.pageXOffset;
		}
	}

	this.getY = function() {
		if (WP.isIE) {
			return document.documentElement.scrollTop;
		} else {
			return window.pageYOffset;
		}
	}
}

bliscy.lib.profiler.Profiler = function() {
	this._counter = 0;
	this._begin = 0;
	this._end = 0;

	this._container = document.createElement('div');
	this._container.style.background = '#fff';
	this._container.style.border = '1px solid #000';
	this._container.style.position = 'absolute';
	this._container.style.left = '0px';
	this._container.style.top = '0px';
	this._container.style.width = '100px';
	this._container.style.padding = '10px';
	this._container.style.display = 'block';
	this._container.style.zIndex = '100';
	$('wpMain').appendChild(this._container);

	this.begin = function() {
		this._begin = (new Date).getTime();
	}

	this.end = function () {
		this._end = (new Date).getTime();
		this._container.innerHTML += (++this._counter) + ': ' + (this._end - this._begin) + '<br />';
	}
}

bliscy.lib.tree.EventDispatcher = function() {
	this._events = new Array();

	this.add = function(eventClass, eventMethod) {
		this._events[eventClass] = eventMethod;
	}

	this.dispatch = function(e) {

		var node = WP.event.getNode(e);
		var type = o(node).mrClass;
		
		if (typeof this._events[type] == 'undefined') {
			if (WP.isWebkit) {
				node.focus();
			}

			return;
		}

		this._events[type](node);

		if (e.preventDefault) {
			e.preventDefault();
		}

		e.returnValue = false;
	}
}

bliscy.lib.vector.Text = function() {

	this._cache = new Array();

	this.cutToWidth = function(textObj, width) {

		if (width <= 0) {
			return;
		}

		var text = textObj.childNodes[0];

		if (typeof text == 'undefined') {
			return;
		}

		if (this.getWidth(textObj) <= width) {
			return;
		}

		var key, value;
		key = value = WP.string.strip(text.nodeValue);
		//key = value = text.nodeValue.strip();

		if (this._isCached(key)) {
			text.nodeValue = this._get(key);
			return;
		}

		width -= 10;

		if (WP.isIE) {
			textObj.style.width = width;
		}

		while (this.getWidth(textObj) > width) {
			value = value.substr(0, value.length - 1);
			text.nodeValue = value;
		}

		value = WP.string.strip(value);
		//value = value.strip();

		value += '...';
		text.nodeValue = value;

		this._put(key, value);
	}

	this.getWidth = function(textObj) {
		if (WP.isIE) {
			return textObj.scrollWidth;
		} else {
			return textObj.getComputedTextLength();
		}
	}

	this._get = function(key) {
		return this._cache[key];
	}

	this._isCached = function(key) {
		return typeof this._cache[key] != 'undefined';
	}

	this._put = function(key, value) {
		this._cache[key] = value;
	}
};

bliscy.lib.window.Slider = function(window) {
	this.width = 0;
	this._window = $(window);
	this._left = 0;

	this.move = function(offset) {
		var max = this.width - this._window.parentNode.offsetWidth;

		if (max <= 0) {
			return;
		}

		this._left += offset;

		if (this._left < 0) {
			this._left = 0;
		}

		if (this._left > max) {
			this._left = max;
		}

		this._window.style.left = (-this._left) + 'px';
	}
}

bliscy.lib.window.Window = function(window, parent) {
	window = $(window);

	if (typeof parent != 'undefined') {
		parent = $(parent);
	}

	if (typeof parent == 'object') {
		parent.appendChild(window);
	} else {
		document.body.appendChild(window);
	}

	this._window = window;
	this._parent = parent;

	this.POS_LEFT = 1;
	this.POS_TOP = 1;
	this.POS_CENTER = 2;
	this.POS_RIGHT = 3;
	this.POS_BOTTOM = 3;

	this._positionHorizontal = this.POS_LEFT;
	this._positionVertical = this.POS_TOP;
	this._offsetX = 0;
	this._offsetY = 0;

	this.setPosition = function(horizontal, vertical) {
		this._positionHorizontal = horizontal;
		this._positionVertical = vertical;
	}

	this.setOffset = function(x, y) {
		this._offsetX = x;
		this._offsetY = y;
	}

	this.show = function() {
		var w = this._window;
		var p = this._parent;
		var x = this._offsetX;
		var y = this._offsetY;

		var left = 0;
		var top = 0;

		this._window.show();

		if (typeof p == 'undefined') {
			var Window = new bliscy.lib.browser.Window();
			p = {
				offsetWidth: Window.getWidth(),
				offsetHeight: Window.getHeight()
			};
			left += Window.getX();
			top += Window.getY();
		}

		if (this._positionHorizontal == this.POS_LEFT) {
			left += x;
		} else if (this._positionHorizontal == this.POS_RIGHT) {
			left += p.offsetWidth - w.offsetWidth - x;
		} else if (this._positionHorizontal == this.POS_CENTER) {
			left += (p.offsetWidth / 2) - (w.offsetWidth / 2) + x;
		}

		if (this._positionVertical == this.POS_TOP) {
			top += y;
		} else if (this._positionVertical == this.POS_BOTTOM) {
			top += p.offsetHeight - w.offsetHeight - y;
		} else if (this._positionVertical == this.POS_CENTER) {
			top += (p.offsetHeight / 2) - (w.offsetHeight / 2) + y;
		}

		w.style.left = left + 'px';
		w.style.right = '';
		w.style.top = top + 'px';
		w.style.bottom = '';
	}

	this.hide = function() {
		this._window.hide();
	}
}










// -------------------------------------------------------------------------- //

function mrPreventEvent(e) {
	if (!e) {
		e = window.event;
	}

	if (e.preventDefault) {
		e.preventDefault();
	}

	e.returnValue = false;

	return e;
}

function o(obj) {

	obj = $(obj);

	if (typeof obj != 'object') {
		return obj;
	}


	if (obj.id && obj.id.indexOf('-') != -1) {
		obj.mrUid = obj.id.substr(obj.id.indexOf('-') + 1);
	} else {
		obj.mrUid = '';
	}

	if (WP.isWebkit) {
		obj.mrClass = obj.getAttribute('class');
	} else if (typeof obj.className == 'object') {
		obj.mrClass = obj.className.baseVal;
	} else {
		obj.mrClass = obj.className;
	}

	if (obj.mrClass == null) {
		obj.mrClass = '';
	}


	obj._svalue = function(v) {
		var t = this.type;

		try {
			this.onfocus();
		} catch(e) {}

		if (t == 'text' || t == 'hidden') {
			this.value = v;
		} else if (t == 'select-one') {
			for (var i = 0; i < this.options.length; i++) {
				if (this.options[i].value == v) {
					this.selectedIndex = i;
					break;
				}
			}
		} else if (t == 'checkbox' || t == 'radio') {
			this.checked = (v == 'true' || v == true || v == '1' || v == 1);
		}

		try {
			this.onblur();
		} catch(e) {}
	}


	obj._gvalue = function() {
		var t = this.type;
		var ret = undefined;

		try {
			this.onfocus();
		} catch(e) {}

		if (t == 'text' || t == 'hidden') {
			ret = this.value;
		} else if (t == 'select-one') {
			ret = this.options[this.selectedIndex].value;
		} else if (t == 'checkbox' || t == 'radio') {
			ret = this.checked ? 'true' : 'false';
		}

		try {
			this.onblur();
		} catch(e) {}

		return ret;
	}

	return obj;
}

var Shadow = {

	_parentId: '',
	_isTree: false,
	_shown: false,
	_shadow: undefined,
	_window: undefined,

	init: function() {

		if (typeof o('bxMojaRodzina') == 'object') {
			this._isTree = true;
			this._parentId = 'mrWindows';
		} else {
			this._parentId = 'wpMain';
			$(this._parentId).style.position = 'relative';
		}

		var s = document.createElement('div');
		s.style.width = $(this._parentId).offsetWidth + 'px';
		s.style.height = $(this._parentId).offsetHeight + 'px';
		s.style.position = 'absolute';
		s.style.backgroundColor = '#fff';
		s.style.opacity = 0.6;
		s.style.filter = 'alpha(opacity = 60);';
		s.style.zIndex = 30;
		this._shadow = s;

		this._window = new bliscy.lib.window.Window(s, this._parentId);

	}, // init()

	hide: function() {

		if (typeof this._window == 'undefined') {
			this.init();
		}

		this._shown = false;

		this._window.hide();

		if (this._isTree) {
			TreeEvents.enable();
			TreeSlider.enable();
			TreeNavigator.enable();
		}

	}, // hide()

	show: function() {

		if (typeof this._window == 'undefined') {
			this.init();
		}

		this._shown = true;

		this._shadow.style.width = $(this._parentId).offsetWidth + 'px';
		this._shadow.style.height = $(this._parentId).offsetHeight + 'px';

		if (this._isTree) {
			TreeEvents.disable();
			TreeSlider.disable();
			TreeNavigator.disable();
		}

		this._window.show();

	}, // show()

	resize: function() {
		if (!this._shown) {
			return;
		}

		this.hide();
		this.show();
	}

} // Shadow

var Tree = {

	ID: 'mrTreeImage',
	MARRIAGE_ID_PREFIX: 'mid-',
	PERSON_ID_PREFIX: 'pid-',

	x: 0,
	y: 0,

	scale: 1.0,
	scaleMax: 1.0,
	scaleMin: 0.1,

	touchedId: null,
	rootId: null,

	init: function() {
		if (global_mruid > 0) {
			this.rootId = this.PERSON_ID_PREFIX + global_mruid;
		}

		if (global_added > 0) {
			this.touchedId = this.PERSON_ID_PREFIX + global_added;
		}

		if (WP.isIE) {
			var text = document.getElementsByTagName(WP.isIE ? 'textbox' : 'text');

			for (var i = 0; i < text.length; i++) {
				text[i].style.fontSizeOrig = parseInt(text[i].style.fontSize);
				text[i].style.leftOrig = parseInt(text[i].style.left);
				text[i].style.topOrig = parseInt(text[i].style.top);
				text[i].style.widthOrig = parseInt(text[i].style.width);
			}
		}

		if (!this.touchedId) {
			this.goToPerson(this.rootId);
		} else if (o(this.touchedId) != this.touchedId) {
			this.goToPerson(this.touchedId);
		} else {
			var mruid = this.touchedId.substr(this.touchedId.indexOf('-') + 1);
			window.location.href = 'mruid,' + mruid + ',' + bliscy.global.viewName.treeView;
		}
	}, // init()

	goToPerson: function(pid) {
		var width;
		var height;
		
		if (WP.isIE) {
			width = $(pid).offsetWidth;
			height = $(pid).offsetHeight;
		} else {
			width = $(pid).getAttribute('width');
			height = $(pid).getAttribute('height');
		}

		var x, y;

		if (WP.isIE) {

			x = parseInt(o(pid).style.left);
			y = parseInt(o(pid).style.top);

		} else {

			var tmp = o(pid).getAttribute('transform');
			tmp = tmp.replace('translate(', '');
			tmp = tmp.replace(')', '');
			tmp = tmp.split(',');

			x = parseInt(tmp[0]);
			y = parseInt(tmp[1]);

		}

		x = (x + width / 2) * this.scale;
		y = (y + height / 2) * this.scale;

		Tree.goToXY(x, y);
	}, // goToPerson(pid)

	goToXY: function(x, y) {

		this.x = x;
		this.y = y;

		x -= $('bxMojaRodzina').offsetWidth / 2;
		y -= ($('bxMojaRodzina').offsetHeight - $('bxTreeName').offsetHeight )/ 2;

		if (WP.isWebkit) {
			o('tiNodeContainer').setAttribute('transform', 'translate(' + (-x) + ',' + (-y) + '), scale(' + this.scale + ')');
		} else {
			o('mrTreeImage').style.left = -x + 'px';
			o('mrTreeImage').style.top = -y + 'px';
		}

		return false;

	}, // goToXY(x, y)

	getScale: function() {
		return this.scale;
	}, // getScale()

	setScale: function(scale) {

		var old = this.scale;
		var q = scale/old;

		if (scale == old) {
			return;
		}

		if (scale <= this.scaleMin) {
			scale = this.scaleMin;
		}

		if (scale > this.scaleMax) {
			scale = this.scaleMax;
		}

		this.scale = scale;

		if (this.scale >= this.scaleMax * 0.6) {
			$('bxMojaRodzina').className = '';
		} else {
			$('bxMojaRodzina').className = 'noarrows';
		}

		if (WP.isIE) {
			$('tiNodeContainer').style.zoom = this.scale;
		} else if (!WP.isWebkit) {
			$('tiNodeContainer').setAttribute('transform', 'scale(' + this.scale + ')');
		}

		this.x = Math.round(this.x * q);
		this.y = Math.round(this.y * q);

		this.goToXY(this.x, this.y);

	} // setScale(scale)
	
} // Tree

var TreeEvents = {

	isDragging: false,

	dragBegin: {
		x: 0,
		y: 0
	},

	dragEnd: {
		x: 0,
		y: 0
	},

	dragTimeoutId: false,

	dragInterval: 40,

	scrollDelta: 0,

	isDisabled: false,

	init: function() {

		WP.event.set(Tree.ID, 'onmousedown', this.mouseDownHandle);
		WP.event.set(window, 'onmouseup', this.mouseUpHandle);
		WP.event.set(window, 'onmousemove', this.mouseMoveHandle);
		WP.event.set(window, 'onmousewheel', this.mouseScrollHandle);
		WP.event.set('bxMojaRodzina', 'onmousedown',  this.mouseDownHandle);

		if (window.addEventListener) {
			window.addEventListener('DOMMouseScroll', this.mouseScrollHandle, false);
		}

		if (WP.isIE || WP.isWebkit) {
			WP.event.set(document, 'onmouseup', this.mouseUpHandle);
			WP.event.set(document, 'onmousemove', this.mouseMoveHandle);
			WP.event.set(document, 'onmousewheel', this.mouseScrollHandle);
		}

	}, // init()

	intervalHandle: function() {

		if (!TreeEvents.isDragging || TreeEvents.isDisabled) {
			return;
		}

		var x = Tree.x - TreeEvents.dragEnd.x + TreeEvents.dragBegin.x;
		var y = Tree.y - TreeEvents.dragEnd.y + TreeEvents.dragBegin.y;

		Tree.goToXY(x, y);

		TreeEvents.dragBegin.x = TreeEvents.dragEnd.x;
		TreeEvents.dragBegin.y = TreeEvents.dragEnd.y;

	}, // intervalHandle()

	mouseDownHandle: function(event) {

		event = mrPreventEvent(event);

		if (TreeEvents.isDisabled) {
			return;
		}

		if (WP.isIE && event.srcElement.id == TreeSlider.id) {
			return;
		}

		TreeEvents.isDragging = true;

		TreeEvents.dragEnd.x = TreeEvents.dragBegin.x = parseInt(event.clientX);
		TreeEvents.dragEnd.y = TreeEvents.dragBegin.y = parseInt(event.clientY);

		TreeEvents.dragTimeoutId = setInterval(TreeEvents.intervalHandle, TreeEvents.dragInterval);

	}, // mouseDownHandle(event)

	mouseMoveHandle: function(event) {

		event = mrPreventEvent(event);

		if (!TreeEvents.isDragging || TreeEvents.isDisabled) {
			return;
		}

		TreeEvents.dragEnd.x = parseInt(event.clientX);
		TreeEvents.dragEnd.y = parseInt(event.clientY);

	}, // mouseMoveHandle(event)

	mouseScrollHandle: function(event) {

		event = mrPreventEvent(event);

		if (TreeEvents.isDisabled) {
			return;
		}

		TreeEvents.scrollDelta = 0;

		if (WP.isOpera) {
			TreeEvents.scrollDelta = -event.wheelDelta / 320;
		} else if (WP.isGecko) {
			TreeEvents.scrollDelta = event.detail / 6;
		} else if (WP.isIE) {
			TreeEvents.scrollDelta = -event.wheelDelta / 256;
		} else if (WP.isWebkit) {
			TreeEvents.scrollDelta = -event.wheelDelta / 960;
		}

		TreeEvents.scrollDelta *= 8;

		if (TreeEvents.scrollDelta) {
			TreeSlider.setPosition(TreeSlider.getPosition() + TreeEvents.scrollDelta);
		}

	}, // mouseScrollHandle(event)

	mouseUpHandle: function(event) {

		event = mrPreventEvent(event);

		TreeEvents.isDragging = false;

		TreeEvents.dragBegin.x = TreeEvents.dragEnd.x = 0;
		TreeEvents.dragBegin.y = TreeEvents.dragEnd.y = 0;

		clearInterval(TreeEvents.dragTimeoutId);

	}, // mouseUpHandle(event)

	disable: function() {
		this.isDisabled = true;
	}, // disable()

	enable: function() {
		this.isDisabled = false;
	} // enable()

} // TreeEvents

var TreeNavigator = {

	ID_UP: 'tcUp',
	ID_DOWN: 'tcDown',
	ID_LEFT: 'tcLeft',
	ID_RIGHT: 'tcRight',
	ID_CENTER: 'tcCenter',

	isNavigating: false,

	timeoutId: null,
	interval: 10,
	step: 10,

	offsetX: 0,
	offsetY: 0,

	isDisabled: false,

	init: function() {

		WP.event.set(this.ID_UP, 'onmousedown', this.mouseDownHandleUp);
		WP.event.set(this.ID_DOWN, 'onmousedown', this.mouseDownHandleDown);
		WP.event.set(this.ID_LEFT, 'onmousedown', this.mouseDownHandleLeft);
		WP.event.set(this.ID_RIGHT, 'onmousedown', this.mouseDownHandleRight);
		WP.event.set(this.ID_CENTER, 'onclick', this.mouseDownHandleCenter);

		WP.event.set(this.ID_UP, 'onmouseout', this.mouseUpHandle);
		WP.event.set(this.ID_UP, 'onclick', this.mouseUpHandle);
		WP.event.set(this.ID_DOWN, 'onmouseout', this.mouseUpHandle);
		WP.event.set(this.ID_DOWN, 'onclick', this.mouseUpHandle);
		WP.event.set(this.ID_LEFT, 'onmouseout', this.mouseUpHandle);
		WP.event.set(this.ID_LEFT, 'onclick', this.mouseUpHandle);
		WP.event.set(this.ID_RIGHT, 'onmouseout', this.mouseUpHandle);
		WP.event.set(this.ID_RIGHT, 'onclick', this.mouseUpHandle);
		WP.event.set(window, 'onmouseup', this.mouseUpHandle);

	}, // init()

	intervalHandle: function() {

		if (!TreeNavigator.isNavigating || TreeNavigator.isDisabled) {
			return;
		}

		Tree.goToXY(Tree.x + TreeNavigator.offsetX, Tree.y + TreeNavigator.offsetY);

	}, // intervalHandle()

	mouseDownHandle: function(event, x, y) {
		event = mrPreventEvent(event);

		if (TreeNavigator.isDisabled) {
			return;
		}

		TreeEvents.disable();
		
		TreeNavigator.offsetX = x * TreeNavigator.step;
		TreeNavigator.offsetY = y * TreeNavigator.step;

		TreeNavigator.isNavigating = true;
		TreeNavigator.timeoutId = setInterval(TreeNavigator.intervalHandle, TreeNavigator.interval);
	}, // mouseDownHandle(event, x, y)

	mouseDownHandleCenter: function() {
		Tree.goToPerson(Tree.rootId);
	}, // mouseDownHandleCenter()

	mouseDownHandleDown: function(event) {
		TreeNavigator.mouseDownHandle(event, 0, +1);
	}, // mouseDownHandleDown(event)

	mouseDownHandleLeft: function(event) {
		TreeNavigator.mouseDownHandle(event, -1, 0);
	}, // mouseDownHandleLeft(event)

	mouseDownHandleRight: function(event) {
		TreeNavigator.mouseDownHandle(event, +1, 0);
	}, // mouseDownHandleRight(event)

	mouseDownHandleUp: function(event) {
		TreeNavigator.mouseDownHandle(event, 0, -1);
	}, // mouseDownHandleUp(event)

	mouseUpHandle: function(event) {
		event = mrPreventEvent(event);

		TreeEvents.enable();

		clearInterval(TreeNavigator.timeoutId);
		TreeNavigator.isNavigating = false;
		TreeNavigator.x = 0;
		TreeNavigator.y = 0;
	}, // mouseUpHandle(event)

	disable: function() {
		this.isDisabled = true;
	}, // disable()

	enable: function() {
		this.isDisabled = false;
	} // enable()

} // TreeNavigator

var TreeSlider = {

	ID: 'tcSlider',
	ID_ADD: 'tcAdd',
	ID_SUB: 'tcSub',

	isDisabled: false,
	isZooming: false,

	position: 30,
	positionMin: 30,
	positionMax: 125,
	y: 0,
	zoom: 0,

	init: function() {

		o(this.ID).style.top = this.position + 'px';
		this.zoom = Tree.getScale();

		WP.event.set(this.ID, 'onmousedown', this.mouseDownHandle);
		WP.event.set(window,  'onmousemove', this.mouseMoveHandle);
		WP.event.set(window,  'onmouseup', this.mouseUpHandle);

		if (WP.isIE) {
			WP.event.set(document, 'onmousemove', this.mouseMoveHandle);
			WP.event.set(document, 'onmouseup', this.mouseUpHandle);
		}

		WP.event.set(this.ID_ADD, 'onclick', this.addHandle);
		WP.event.set(this.ID_SUB, 'onclick', this.subHandle);
		WP.event.set(this.ID_ADD, 'ondblclick', this.addHandle);
		WP.event.set(this.ID_SUB, 'ondblclick', this.subHandle);

	}, // init()

	getPosition: function() {
		return this.position;
	}, // getPosition()

	setPosition: function(position) {

		if (this.isDisabled) {
			return;
		}

		if (position > this.positionMax) {
			position = this.positionMax;
		} else if (position < this.positionMin) {
			position = this.positionMin;
		}

		this.position = position;

		o(this.ID).style.top = position + 'px';

		var range = this.positionMax - this.positionMin;
		var rangeCur = this.positionMax - this.position;

		var z = rangeCur / range;

		z += Tree.scaleMin * (1 - z);
		z *= 100;
		z = Math.round(z);
		z /= 100;

		this.setZoom(z);

	}, // setPosition(position)

	setZoom: function(zoom) {

		if (this.isDisabled) {
			return;
		}

		this.zoom = zoom;
		Tree.setScale(this.zoom);

	}, // setZoom(zoom)

	addHandle: function() {
		TreeSlider.setPosition(TreeSlider.getPosition() - 10);
	}, // addHandle()

	mouseDownHandle: function(event) {

		mrPreventEvent(event);

		if (TreeSlider.isDisabled) {
			return;
		}

		TreeEvents.disable();
		TreeSlider.isZooming = true;
		TreeSlider.y = parseInt(event.clientY);

	}, // mouseDownHandle(event)

	mouseMoveHandle: function(event) {

		mrPreventEvent(event);

		if (TreeSlider.isDisabled) {
			return;
		}

		if (!TreeSlider.isZooming) {
			return;
		}

		var yOld = TreeSlider.y;
		var yNew = parseInt(event.clientY);

		var position = TreeSlider.position + yNew - yOld;

		if (position <= TreeSlider.positionMax && position >= TreeSlider.positionMin) {
			TreeSlider.y = yNew;
		}

		TreeSlider.setPosition(position);

	}, // mouseMoveHandle(event)

	mouseUpHandle: function(event) {

		mrPreventEvent(event);

		TreeEvents.enable();
		TreeSlider.isZooming = false;
		TreeSlider.y = 0;

		Tree.setScale(TreeSlider.zoom);

	}, // mouseUpHandle(event)

	subHandle: function() {
		TreeSlider.setPosition(TreeSlider.getPosition() + 10);
	}, // subHandle()

	disable: function() {
		this.isDisabled = true;
	}, // disable()

	enable: function() {
		this.isDisabled = false;
	} // enable()

} // TreeSlider

var Person = {

	pids: new Array(),

	init: function() {

		var groups = o(Tree.ID).getElementsByTagName(WP.isIE ? 'group' : 'g');

		for (var i in groups) {

			if (!groups[i].id || groups[i].id.indexOf(Tree.PERSON_ID_PREFIX) != 0) {
				continue;
			}

			var pid = groups[i].id.substr(groups[i].id.indexOf('-') + 1);

			this.pids.push(pid);
		}

	}, // init()

	marriages: function(pid) {

		var mdata = o(pid).mrClass;		
		mdata = WP.string.strip(mdata);
		//mdata = mdata.strip();
		mdata = mdata.split(' ');

		var marriages = new Array();

		for (var i = 0; i < mdata.length; i += 2) {

			var c = Tree.PERSON_ID_PREFIX + mdata[i+1];

			if (o(c) == c && c != (Tree.PERSON_ID_PREFIX + '0')) {
				continue;
			}

			marriages[marriages.length] = {
				mid: mdata[i],
				pid: c
			};
		}

		return marriages;

	}, // marriages(pid)

	name: function(pid) {

		if (typeof o(pid) != 'object') {
			return false;
		}

		pid = pid.substr(pid.indexOf('-') + 1);

		var fn, ln;

		if (WP.isIE) {
			fn = o('fn-' + pid).innerHTML;
			ln = o('ln-' + pid).innerHTML;
		} else {
			fn = o('fn-' + pid).textContent;
			ln = o('ln-' + pid).textContent;
		}

		if (!fn) {
			fn = '';
		}

		if (!ln) {
			ln = '';
		}

		return {
			first: fn,
			last: ln
		};

	}, // name(pid)

	getPids: function() {
		return this.pids;
	} // getPids()

} // Person

var AddMenu = {

	POS_TOP: 't',
	POS_BOTTOM: 'b',
	POS_LEFT: 'l',
	POS_RIGHT: 'r',

	_childWindow: undefined,
	_parentWindow: undefined,
	_siblingWindow: undefined,

	init: function() {
		var c = new bliscy.lib.window.Window('menu_child', 'mrWindows');
		c.setPosition(c.POS_CENTER, c.POS_CENTER);
		c.setOffset(0, 103);
		this._childWindow = c;

		var p = new bliscy.lib.window.Window('menu_parent', 'mrWindows');
		p.setPosition(p.POS_CENTER, p.POS_CENTER);
		p.setOffset(0, -103);
		this._parentWindow = p;

		var s = new bliscy.lib.window.Window('menu_sibling', 'mrWindows');
		s.setPosition(s.POS_CENTER, s.POS_CENTER);
		this._siblingWindow = s;
	}, // init()

	hide: function() {

		this._childWindow.hide();
		this._parentWindow.hide();
		this._siblingWindow.hide();
		o('add_husband').hide();
		o('add_wife').hide();
		o('add_partnerm').hide();
		o('add_partnerf').hide();

	}, // hide()

	show: function() {
		var pos = bliscy.global.AddPerson.position;

		if (pos == 't') {
			this._parentWindow.show();
		} else if (pos == 'b') {
			this._childWindow.show();
		} else if (pos == 'r') {
			o('add_husband').show();
			o('add_partnerm').show();
			this._siblingWindow.setOffset(155, 0);
			this._siblingWindow.show();
		} else if (pos == 'l') {
			o('add_wife').show();
			o('add_partnerf').show();
			this._siblingWindow.setOffset(-155, 0);
			this._siblingWindow.show();
		}
	}, // show()

	menuBackHandle: function() {
		AddMenu.hide();
		Shadow.hide();
	}, // menuBackHandle()

	mouseClickHandle: function(node) {

		bliscy.global.AddPerson.reset();
		bliscy.global.AddPerson.position = o(node).mrClass.substr(1);
		bliscy.global.AddPerson.relationPersonId = o(node).mrUid;

		Tree.goToPerson('pid-' + o(node).mrUid);

		Shadow.show();
		AddMenu.show();
	} // mouseClickHandle()

} // AddMenu

var AddForm = {

	_window: undefined,

	init: function() {

		WP.event.set('add_brother', 'onclick', this.mouseClickHandle);
		WP.event.set('add_sister', 'onclick', this.mouseClickHandle);
		WP.event.set('add_husband', 'onclick', this.mouseClickHandle);
		WP.event.set('add_wife', 'onclick', this.mouseClickHandle);
		WP.event.set('add_partnerm', 'onclick', this.mouseClickHandle);
		WP.event.set('add_partnerf', 'onclick', this.mouseClickHandle);
		WP.event.set('add_father', 'onclick', this.mouseClickHandle);
		WP.event.set('add_mother', 'onclick', this.mouseClickHandle);
		WP.event.set('add_daughter', 'onclick', this.mouseClickHandle);
		WP.event.set('add_son', 'onclick', this.mouseClickHandle);

		WP.event.set('apChoosePerson', 'onclick', this._switchToCreatePerson);
		WP.event.set('apChooseCycle', 'onclick', this._switchToCreateCycle);
		WP.event.set('apChooseMe', 'onclick', this._switchToCreateMe);

		var groups = o('tiNodeContainer').getElementsByTagName(WP.isIE ? 'group' : 'g');

		for (var i = 0; i < groups.length; i++) {
			if (groups[i].id.indexOf('mid') == 0) {
				WP.event.set(groups[i], 'onclick', this.placeholderHandle);
			}
		}

		o('add_person_isalive').onclick = this.isAliveHandle;
		o('add_person_reset').onclick = this.resetHandle;
		o('add_person_submit').onclick = this.submitHandle;
		$('apSelectCycleId').onchange = this._changeSelectCycleId;

		var w = new bliscy.lib.window.Window('add_person', 'mrWindows');
		w.setPosition(w.POS_CENTER, w.POS_CENTER);
		this._window = w;

	}, // init()

	hide: function() {

		this._switchToCreatePerson();

		document.forms.addPerson.mruid.value = '';
		document.forms.addPerson.relationMarriageId.value = '';
		document.forms.addPerson.relation.value = '';
		document.forms.addPerson.reset();

		this._window.hide();
		o('add_person_death').hide();
		o('add_person_inactive').hide();

		var h2 = o('add_person').getElementsByTagName('h2');

		for (var i = 0; i < h2.length; i++) {
			h2[i].style.display = 'none';
		}

		o('paSelectMarriageType').disabled = false;

	}, // hide()

	show: function() {

		var rel = bliscy.global.AddPerson.relation;
		var pos = bliscy.global.AddPerson.position;

		o('header_add_' + rel).show();

		if (rel == 'partnerm') {
			document.forms.addPerson.relation.value = 'husband';
		} else if (rel == 'partnerf') {
			document.forms.addPerson.relation.value = 'wife';
		} else {
			document.forms.addPerson.relation.value = rel;
		}
		document.forms.addPerson.mruid.value = bliscy.global.AddPerson.relationPersonId;
		document.forms.addPerson.relationMarriageId.value = bliscy.global.AddPerson.relationMarriageId;

		if (pos == 't') {
			this._window.setOffset(0, -103);
		} else if (pos == 'b') {
			this._window.setOffset(0, 103);
		} else if (pos == 'l') {
			this._window.setOffset(-155, 0);
		} else if (pos == 'r') {
			this._window.setOffset(155, 0);
		}

		this._window.show();
		document.forms.addPerson.firstName.focus();

		if (rel == 'husband' || rel == 'wife' || rel == 'partnerm' || rel == 'partnerf') {
			o('add_person_inactive').show();

			if (rel == 'husband' || rel == 'wife') {
				o('paSelectMarriageType').disabled = true;
			} else {
				o('paSelectMarriageType').selectedIndex  = 2;
			}
		}
	}, // show()

	_fields: new Array('firstName', 'lastName', 'email', 'birthDay', 'birthMonth', 'birthYear', 'deathDay', 'deathMonth', 'deathYear'),

	_switchToCreatePerson: function() {
		$('apParagraphCycle').hide();
		$('apParagraphChoosePerson').hide();
		$('apParagraphChooseCycle').show();

		var f = document.forms.addPerson;
		f._action.value = bliscy.global.actionName.createPerson;

		for (var i = 0; i < AddForm._fields.length; i++) {
			var field = AddForm._fields[i];
			f[field].disabled = false;
			f[field].value = "";
		}

		f.isAlive.disabled = false;
		f.isAlive.checked = true;
		o('add_person_isalive').onclick();
	},

	_switchToCreateCycle: function() {
		$('apParagraphCycle').show();
		$('apParagraphChoosePerson').show();
		$('apParagraphChooseCycle').hide();
		
		var f = document.forms.addPerson;
		f._action.value = bliscy.global.actionName.createCycle;
		
		for (var i = 0; i < AddForm._fields.length; i++) {
			var field = AddForm._fields[i];
			f[field].disabled = true;
		}

		f.isAlive.disabled = true;

		AddForm._changeSelectCycleId();
	},

	_changeSelectCycleId: function() {
		var s = $('apSelectCycleId');
		var id = s.options[s.selectedIndex].value;
		var person = peopleList[id];

		var f = document.forms.addPerson;
		f.firstName.value = person.firstName;
		f.lastName.value = person.lastName;
		f.email.value = person.email;

		if (person.deathDate == "") {
			f.isAlive.checked = true;
		} else {
			f.isAlive.checked = false;
		}

		var birthDate = person.birthDate.split('-');

		if (birthDate.length == 3) {
			var birthYear = parseInt(birthDate[0]);
			var birthMonth = parseInt(birthDate[1]);
			var birthDay = parseInt(birthDate[2]);

			f.birthYear.value = birthYear;
			f.birthMonth.selectedIndex = birthMonth;
			f.birthDay.selectedIndex = birthDay;
		}

		var deathDate = person.deathDate.split('-');

		if (deathDate.length == 3) {
			var deathYear = parseInt(deathDate[0]);
			var deathMonth = parseInt(deathDate[1]);
			var deathDay = parseInt(deathDate[2]);

			f.deathYear.value = deathYear;
			f.deathMonth.selectedIndex = deathMonth;
			f.deathDay.selectedIndex = deathDay;
		}

		$('add_person_isalive').onclick();
	},
	
	_switchToCreateMe: function() {
		
		var f = document.forms.addPerson;
		f._action.value = bliscy.global.actionName.createMe;
		
		for (var i = 0; i < AddForm._fields.length; i++) {
			var field = AddForm._fields[i];
			f[field].disabled = true;
		}

		f.isAlive.disabled = true;
			
		var myMruid = f.myMruid.value;
		var person = peopleList[myMruid];

		f.firstName.value = person.firstName;
		f.lastName.value = person.lastName;
		f.email.value = person.email;

		if (person.deathDate == "") {
			f.isAlive.checked = true;
		} else {
			f.isAlive.checked = false;
		}

		var birthDate = person.birthDate.split('-');

		if (birthDate.length == 3) {
			var birthYear = parseInt(birthDate[0]);
			var birthMonth = parseInt(birthDate[1]);
			var birthDay = parseInt(birthDate[2]);

			f.birthYear.value = birthYear;
			f.birthMonth.selectedIndex = birthMonth;
			f.birthDay.selectedIndex = birthDay;
		}

		var deathDate = person.deathDate.split('-');

		if (deathDate.length == 3) {
			var deathYear = parseInt(deathDate[0]);
			var deathMonth = parseInt(deathDate[1]);
			var deathDay = parseInt(deathDate[2]);

			f.deathYear.value = deathYear;
			f.deathMonth.selectedIndex = deathMonth;
			f.deathDay.selectedIndex = deathDay;
		}

		$('add_person_isalive').onclick();		
	},

	handleAjaxError: function(ajax) {
		window.location.href = window.location.href;
	},

	ajaxHandle: function(ajax) {

		var t = ajax.text;

		if (t.indexOf('OK ') == 0) {
			var added = t.substr(3);
			var mruid = Tree.rootId.substr(Tree.rootId.indexOf('-') + 1);
			
			if (2 == global_type || 3 == global_type) {
				window.location.href = 'type,' + global_type + ',added,' + added + ',mruid,' + mruid + ',' + bliscy.global.viewName.treeView;
			} else {
				window.location.href = 'added,' + added + ',mruid,' + mruid + ',' + bliscy.global.viewName.treeView;
			}
				
		} else if (t.indexOf('ER ') == 0) {
			alert(t.substr(3));
			o('add_person_submit').disabled = false;
		} else {
			window.location.href = window.location.href;
		}

	}, // ajaxHandle(ajax)

	isAliveHandle: function() {

		if (this.checked) {
			o('add_person_death').hide();
		} else {
			o('add_person_death').show();
		}

	}, // isAliveHandle()

	mouseClickHandle: function(e) {

		var target = WP.event.getNode(e);
		var relation = target.id.substr(target.id.indexOf('_') + 1);
		bliscy.global.AddPerson.relation = relation;

		AddMenu.hide();
		AddForm.hide();

		if (relation == 'son' || relation == 'daughter') {
			AddMarriageChooser.show();
		} else {
			AddForm.show();
		}

	}, // mouseClickHandle(e)

	placeholderHandle: function(e) {

		var target = WP.event.getNode(e).parentNode;

		Tree.goToPerson(target.id);

		Shadow.show();
		AddForm.hide();

		bliscy.global.AddPerson.reset();
		bliscy.global.AddPerson.position = 'c';
		bliscy.global.AddPerson.relationMarriageId = o(target).mrUid;

		if (o(target).mrClass == 'm') {
			bliscy.global.AddPerson.relation = 'husband';
		} else {
			bliscy.global.AddPerson.relation = 'wife';
		}

		AddForm.show();

	}, // placeholderHandle(e)

	resetHandle: function() {

		AddMenu.hide();
		AddForm.hide();

		var pos = bliscy.global.AddPerson.position;

		if (pos == 'c') {
			Shadow.hide();
		} else {
			AddMenu.show();
		}

		return false;

	}, // resetHandle()

	submitHandle: function() {

		if (typeof this.disabled != 'undefined' && this.disabled) {
			return false;
		}

		this.disabled = true;

		try {
			WP.ajax.post({
				url: bliscy.global.viewName.ajaxView,
				form: 'add_person_form',
				onSuccess: AddForm.ajaxHandle,
				onError: AddForm.handleAjaxError
			});
		} catch (e) {
			alert('Operacja nieudana.');
			this.disabled = false;
		}

		return false;

	} // submitHandle()

} // AddForm

var AddMarriageChooser = {

	_window: undefined,

	init: function() {
		o('marriage_back').onclick = this.backHandle;
		var w = new bliscy.lib.window.Window('marriage', 'mrWindows');
		w.setPosition(w.POS_CENTER, w.POS_CENTER);
		w.setOffset(0, 103);
		this._window = w;
	}, // init()

	hide: function() {

		this._window.hide();

		var ls = o('marriage').childNodes;

		for (var i = ls.length - 1; i >= 0; i--) {

			//TODO: wywalić pierwszy człon if-a gdy zostanie poprawiona funkcja $() w WPJSLIB-ie
			if (typeof ls[i].className == 'undefined' || o(ls[i]).hasClass('back')) {
				continue;
			}

			o('marriage').removeChild(ls[i]);
		}

	}, // hide()

	show: function() {

		var pid = Tree.PERSON_ID_PREFIX + bliscy.global.AddPerson.relationPersonId;
		var marriages = Person.marriages(pid);

		if (marriages.length < 2) {
			bliscy.global.AddPerson.relationMarriageId = marriages[0].mid;
			AddForm.show();
			return;
		}

		var back = o('marriage').childNodes[0];

		for (var i in marriages) {

			var p = document.createElement('p');

			p.style.clear = 'both';
			o('marriage').insertBefore(p, back);

			var s1 = document.createElement('span');
			var s2 = document.createElement('span');

			var s1n = Person.name(pid);
			s1.innerHTML = s1n.first + '<br />' + s1n.last;

			if (marriages[i].pid != (Tree.PERSON_ID_PREFIX + '0')) {
				var s2n = Person.name(marriages[i].pid);
				s2.innerHTML = s2n.first + '<br />' + s2n.last;
			} else {
				s2.innerHTML = '(brak osoby)';
			}

			s1.mid = marriages[i].mid;
			s2.mid = marriages[i].mid;

			o(s1).addClass('left');
			o(s2).addClass('right');

			s1.onclick = s2.onclick = AddMarriageChooser.mouseClickHandle;

			p.appendChild(s1);
			p.appendChild(s2);
		}

		this._window.show();
	}, // show()

	backHandle: function() {
		AddMarriageChooser.hide();
		AddMenu.show();
	},

	mouseClickHandle: function() {
		bliscy.global.AddPerson.relationMarriageId = this.mid;
		AddMarriageChooser.hide();
		AddForm.show();
	} // mouseClickHandle()

} // AddMarriageChooser

var PopupHelp = {

	_window: undefined,
	_numberOfPages: 0,
	_currentPage: 1,

	init: function(pages) {

		var w = new bliscy.lib.window.Window('bxPopupHelp', 'mrWindows');
		w.setPosition(w.POS_LEFT, w.POS_TOP);
		w.setOffset(90, 150);
		this._window = w;
		this._numberOfPages = pages;

		o('phExit').onclick = this._onClickExitHandle;
		o('phPrev').onclick = this._onClickPrevHandle;
		o('phNext').onclick = this._onClickNextHandle;
		o('tbHelp').onclick = this._onClickHandle;
	},

	show: function(page) {

		if (typeof page == 'undefined') {
			page = 1;
		}

		this._currentPage = page;

		for (var i = 1; i <= this._numberOfPages; i++) {
			o('ph' + i).hide();
		}

		Shadow.show();
		o('ph' + page).show();
		this._window.show();
	},

	hide: function() {
		this._window.hide();
		Shadow.hide();
	},

	_onClickPrevHandle: function() {

		var prev = PopupHelp._currentPage - 1;

		if (prev < 1) {
			PopupHelp.hide();
		} else {
			PopupHelp.show(prev);
		}

		return false;

	},

	_onClickNextHandle: function() {

		var next = PopupHelp._currentPage + 1;

		if (next > PopupHelp._numberOfPages) {
			PopupHelp.hide();
		} else {
			PopupHelp.show(next);
		}

		return false;

	},

	_onClickExitHandle: function() {
		PopupHelp.hide();
		return false;
	},

	_onClickHandle: function() {
		PopupHelp.show(1);
		return false;
	}

}

var Tabs = {

	_tabs: new Array(),

	add: function(tab) {
		if (typeof o(tab) != 'object') {
			return;
		}

		o(tab).onclick = this._onClickHandle;
		this._tabs[this._tabs.length] = tab;
	},

	show: function(tab) {
		if (typeof o(tab) != 'object') {
			return;
		}

		for (var i = 0; i < this._tabs.length; i++) {
			o(this._tabs[i]).deleteClass('on');
			o(this._tabs[i] + 't').hide();
		}

		o(tab).addClass('on');
		o(tab + 't').show();
	},

	_onClickHandle: function() {
		Tabs.show(this.id);
	}

}

var DefaultValues = {

	_defaults: {
		upTextStreet: 'ulica',
		upTextCode: 'kod',
		upTextRegion: 'region',
		upTextCity: 'miasto',
		upTextCountry: 'kraj',
		upTextBirthCity: 'miasto',
		upTextBirthCountry: 'kraj',
		upTextMarriageCity: 'miasto',
		upTextMarriageCountry: 'kraj',
		uplTextStreet: 'ulica',
		uplTextNumber: 'nr. domu',
		uplTextCity: 'miasto'
	},

	init: function() {
		for (var i in this._defaults) {
			var obj = o(i);

			if (typeof obj != 'object') {
				continue;
			}

			obj.onfocus = this._onFocusHandle;
			obj.onblur = this._onBlurHandle;
			obj._defaultValue = this._defaults[i];
			obj.onfocus();
			obj.onblur();
		}
	},

	unset: function() {
		for (var i in this._defaults) {
			var obj = o("fPersonEdit")[i];

			if (typeof obj == 'undefined') {
				continue;
			}

			obj.onfocus();
		}
	},

	_onBlurHandle: function() {
		if (this.value == '') {
			this.value = this._defaultValue;
			this.style.color = '#aaa';
		}
	},

	_onFocusHandle: function() {
		if (this.value == this._defaultValue || this.value == '') {
			this.value = '';
			this.style.color = '';
		}
	}
}

var EditForm = {

	_window: undefined,
	_inputs: new Array(),

	_isTree: false,

	_refreshId: 0,

	_showAbout: false,

	_showContact: false,

	init: function() {

		this._isTree = typeof o('bxMojaRodzina') == 'object';

		var w;

		if (this._isTree) {
			w = new bliscy.lib.window.Window('bxPersonEdit', 'mrWindows');
		} else {
			w = new bliscy.lib.window.Window('bxPersonEdit');
		}

		w.setPosition(w.POS_CENTER, w.POS_CENTER);
		this._window = w;

		o('peInputReset').onclick = this.resetHandle;
		o('peInputSubmit').onclick = this.submitHandle;
		o('peSelectMarriageType').onchange = this.relationTypeHandle;
		o('peARemoveThumb').onclick = this.removeThumbHandle;

	}, // init()

	show: function() {

		this._window.show();

		if (this._showContact == true) {
			o('ept2').onclick();
		} else if (this._showAbout == true) {
			o('ept4').onclick();
		} else {
			o('ept1').onclick();
		}

		document.forms.editPerson.firstName.focus();

	}, // show()

	hide: function() {

		var form = o('fPersonEdit');

		form.mruid.value = '';
		form.reset();

		for (var j = EditForm._inputs.length - 1; j >= 0; j--) {
			o('fPersonEdit').removeChild(EditForm._inputs[j]);
			EditForm._inputs.pop();
		}

		if (typeof o('peSelectMarriage') == 'object') {
			var options = o('peSelectMarriage').getElementsByTagName('option');

			for (var k = options.length - 1; k >= 0; k--) {
				o('peSelectMarriage').removeChild(options[k]);
			}
		}
		
		o('peInputSubmit').disabled = false;
		this._window.hide();
		o('peDeathDate').hide();

	}, // hide()

	handleAjaxError: function(ajax) {
		window.location.href = window.location.href;
	},

	ajaxGetHandle: function(ajax) {

		var form = document.forms.editPerson;
		var xml = ajax.text;

		xml = WP.string.strip(xml);
		//xml = xml.strip();

		if (WP.isIE) {
			var par = new ActiveXObject('Microsoft.XMLDOM');
			par.async = 'false';
			par.loadXML(xml);
			xml = par;
		} else {
			par = new DOMParser();
			xml = par.parseFromString(xml, 'text/xml');
		}
		
		o(form.mruid)._svalue(EditForm.getXMLValue(xml, 'id'));

		if (typeof $('upAnchorMap') == 'object') {
			$('upAnchorMap').href = 'mapa_edytuj.html?mruid=' + EditForm.getXMLValue(xml, 'id');
		}

		var name = EditForm.getXMLValue(xml, 'firstName') + ' ' + EditForm.getXMLValue(xml, 'lastName');
		o('peHeaderName').innerHTML = name
		o('peHeaderThumb').alt = name;
		o('peHeaderThumb').src = EditForm.getXMLValue(xml, 'thumb');

		if (EditForm.getXMLValue(xml, 'sex') == 'm') {
			o('peInputMale')._svalue(true);
		} else {
			o('peInputFemale')._svalue(true);
		}

		if (EditForm.getXMLValue(xml, 'isAlive') == 'true') {
			o('peInputAlive').checked = true;
			o('peInputAlive').onclick();
		} else {
			o('peInputDead').checked = true;
			o('peInputDead').onclick();
		}

		var fields = new Array('firstName', 'secondName', 'lastName', 'maidenName',
			'phone', 'email', 'street', 'code', 'city', 'region', 'country',
			'birthCity', 'birthCountry', 'birthYear', 'deathYear', 'comSpik',
			'comGG', 'comSkype', 'comTlen');

		for (var i in fields) {
			var field = fields[i];
			EditForm.setValueFromXML(field, xml);
		}

		o(form.occupation).value = EditForm.getXMLValue(xml, 'occupation');
		o(form.education).value = EditForm.getXMLValue(xml, 'education');
		o(form.hobby).value = EditForm.getXMLValue(xml, 'hobby');

		o(form.birthDay)._svalue(EditForm.getXMLValue(xml, 'birthDay'));
		o(form.birthMonth)._svalue(EditForm.getXMLValue(xml, 'birthMonth'));
		o(form.deathDay)._svalue(EditForm.getXMLValue(xml, 'deathDay'));
		o(form.deathMonth)._svalue(EditForm.getXMLValue(xml, 'deathMonth'));
		o(form.nameDay)._svalue(EditForm.getXMLValue(xml, 'nameDay'));
		o(form.nameMonth)._svalue(EditForm.getXMLValue(xml, 'nameMonth'));

		var marriageTab = false;
		
		if (EditForm._isTree) {

			var mfields = new Array('marriageDay', 'marriageMonth', 'marriageYear', 'active', 'type', 'city', 'country');
			var marriages = xml.getElementsByTagName('marriages')[0];
			
			for (var j = 0; typeof marriages != 'undefined' && j < marriages.childNodes.length; j++) {
				var marriage = marriages.childNodes[j];
				var partners = marriage.getElementsByTagName('partner');
				
				if (partners.length < 2) {
					continue;
				}

				marriageTab = true;

				var mid = EditForm.getXMLValue(marriage, 'id');
				var len = EditForm._inputs.length;
				var option = document.createElement('option');

				option.value = mid;

				var p0 = partners[0].firstChild ? partners[0].firstChild.nodeValue : '';
				var p1 = partners[1].firstChild ? partners[1].firstChild.nodeValue : '';

				option.innerHTML = p0 + ' - ' + p1;

				o('peSelectMarriage').appendChild(option);

				for (var k in mfields) {
					var mfield = mfields[k];
					var input = document.createElement('input');

					input.type = 'hidden';
					input.id = 'marriage[' + mid + '][' + mfield + ']';
					input.name = input.id;
					input.value = EditForm.getXMLValue(marriage, mfield);

					o('fPersonEdit').appendChild(input);
					EditForm._inputs[len++] = input;
				}
				
			}


			var opts = o('peSelectMarriage').options;

			if (opts.length > 0) {
				opts[0].selected = true;
				o('peSelectMarriage').oldId = false;
				o('peSelectMarriage').onchange = EditForm.changeHandle;
				o('peSelectMarriage').onchange();
			}
		}

		if (marriageTab && EditForm._isTree) {
			o('ept3').show();
		} else {
			o('ept3').hide();
		}


		EditForm.show();

	}, // ajaxHandle(ajax)

	ajaxPutHandle: function(ajax) {

		var t = ajax.text;

		if (t.indexOf('OK ') == 0) {

			var added = EditForm._refreshId;
			
			if (EditForm._isTree) {
				var mruid = Tree.rootId.substr(Tree.rootId.indexOf('-') + 1);
				
				if (2 == global_type || 3 == global_type) {
					window.location.href = 'type,' + global_type + ',added,' + added + ',mruid,' + mruid + ',' + bliscy.global.viewName.treeView;
				} else {
					window.location.href = 'added,' + added + ',mruid,' + mruid + ',' + bliscy.global.viewName.treeView;	
				}
								
			} else {
				window.location.href = window.location.href;
			}

		} else if (t.indexOf('ER ') == 0) {
			alert(t.substr(3));
			o('peInputSubmit').disabled = false;
		} else {
			window.location.href = window.location.href;
		}

	}, // ajaxPutHandle(ajax)

	changeHandle: function() {

		var form = o('fPersonEdit');

		var newId = o(this)._gvalue();
		var oldId = this.oldId;
		this.oldId = newId;

		var prefix = '';

		if (oldId) {

			prefix = 'marriage[' + oldId + ']';

			o(prefix + '[marriageDay]')._svalue(o(form.marriageDay)._gvalue());
			o(prefix + '[marriageMonth]')._svalue(o(form.marriageMonth)._gvalue());
			o(prefix + '[marriageYear]')._svalue(o(form.marriageYear)._gvalue());
			o(prefix + '[city]')._svalue(o(form.marriageCity)._gvalue());
			o(prefix + '[country]')._svalue(o(form.marriageCountry)._gvalue());
			o(prefix + '[active]')._svalue(o(form.isInactive)._gvalue() != 'true' ? 'true' : 'false');
			o(prefix + '[type]')._svalue(o(form.type)._gvalue());
		}

		prefix = 'marriage[' + newId + ']';

		o(form.marriageDay)._svalue(o(prefix + '[marriageDay]')._gvalue());
		o(form.marriageMonth)._svalue(o(prefix + '[marriageMonth]')._gvalue());
		o(form.marriageYear)._svalue(o(prefix + '[marriageYear]')._gvalue());
		o(form.marriageCity)._svalue(o(prefix + '[city]')._gvalue());
		o(form.marriageCountry)._svalue(o(prefix + '[country]')._gvalue());
		o(form.isInactive)._svalue(o(prefix + '[active]')._gvalue() != 'true' ? 'true' : 'false');
		o(form.type)._svalue(o(prefix + '[type]')._gvalue());

		EditForm.relationTypeHandle();

	}, // changeHandle()

	relationTypeHandle: function() {
		var value = o('peSelectMarriageType')._gvalue();

		if (0 == value) {
			$('peParMarriageDate').show();
			$('peParMarriagePlace').show();
		} else {
			$('peParMarriageDate').hide();
			$('peParMarriagePlace').hide();
		}
	},

	editHandle: function(node) {

		EditForm.hide();
		Shadow.show();

		EditForm._refreshId = o(node).mrUid;

		if (o(node).id.indexOf('ee') == 0) {
			EditForm._showContact = true;
		} else if (o(node).id.indexOf('ea') == 0) {
			EditForm._showAbout = true;
		}

		try {
			WP.ajax.get({
				url: 'mruid,' + o(node).mrUid + ',' + bliscy.global.viewName.ajaxPersonView,
				onSuccess: EditForm.ajaxGetHandle,
				onError: EditForm.handleAjaxError
			});
		} catch (e) {
			alert('Operacja nieudana.');
		}

		return false;

	}, // editHandle(e)

	resetHandle: function() {

		EditForm.hide();
		Shadow.hide();

		return false;

	}, // resetHandle()

	removeThumbHandle: function() {

		o('removeThumb').value = '1';
		return EditForm.submitHandle();

	}, // removeThumbHandle

	submitHandle: function() {

		this.disabled = true;

		if (typeof o('peSelectMarriage') == 'object' && o('peSelectMarriage').options.length > 0) {
			o('peSelectMarriage').onchange();
		}

		DefaultValues.unset();

		try {
			WP.ajax.post({
				url: bliscy.global.viewName.ajaxView,
				form: 'fPersonEdit',
				onSuccess: EditForm.ajaxPutHandle,
				onError: EditForm.handleAjaxError
			});
		} catch (e) {
			alert('Operacja nieudana.');
			this.disabled = false;
		}

		return false;

	}, // submitHandle()

	getXMLValue: function(xml, field) {

		var elem = xml.getElementsByTagName(field)[0];

		if (!elem || elem.childNodes.length != 1) {
			return '';
		}

		return elem.firstChild.nodeValue;

	}, // getXMLValue(xml, field)

	setValue: function(field, value) {

		var obj = o("fPersonEdit")[field];

		o(obj)._svalue(value);

	}, // setValue(field, value)

	setValueFromXML: function(field, xml) {

		var value = EditForm.getXMLValue(xml, field);
		EditForm.setValue(field, value);

	} // setValueFromXML(field, xml)

} // EditForm

var Description = {
		
		_window: undefined,
	
		init: function() {

			if (typeof o('hideDesc') == 'object') {
				o('hideDesc').onclick = function() { Description.hide('descr',2,'') };
			}
			if (typeof o('showDesc') == 'object') {
				o('showDesc').onclick = function() { Description.show('descr',2,'') };
			}
	 		if (typeof o('hideMod') == 'object') {
	 			o('hideMod').onclick = function() { Description.hide('mod',3,'') };
	 		}
			if (typeof o('showMod') == 'object') {
				o('showMod').onclick = function() { Description.show('mod',3,'') };
			}

		},
	
	 	show: function(id, align, valign) {

			w = new bliscy.lib.window.Window(id, 'mrWindows');
			w.setPosition(align, w.POS_TOP);
			w.setOffset(0, 0);			
			this._window = w;

			Shadow.show();
			this._window.show();

		},
		
		hide: function(id, align, valign) {
			
			/*o(id).hide();*/
			this._window.hide();
			Shadow.hide();								

			return false;
		}
}

WP.event.set(window, WP.isIE || WP.isWebkit ? 'onload' : 'ondomload', function() {
	if (typeof o('bxMojaRodzina') == 'object') {
		Tree.init();
		TreeEvents.init();
		TreeNavigator.init();
		TreeSlider.init();
		Person.init();
		AddMenu.init();
		AddForm.init();
		AddMarriageChooser.init();
		/*PopupHelp.init(6);*/
		Description.init();
	}

	Tabs.add('ept1');
	Tabs.add('ept2');
	Tabs.add('ept3');
	Tabs.add('ept4');
	Tabs.show('ept1');

	DefaultValues.init();
	EditForm.init();

	o('peInputAlive').onclick = function() {
		o('peDeathDate').hide()
	};
	o('peInputDead').onclick = function() {
		o('peDeathDate').show()
	};
});

/* -------------------------------------------------------------------------- */



var EventDispatcher = new bliscy.lib.tree.EventDispatcher();
EventDispatcher.add('rc', bliscy.event.removeCycle.click);
EventDispatcher.add('r', bliscy.event.removePerson.click);
EventDispatcher.add('p', bliscy.event.profile.click);
EventDispatcher.add('t', bliscy.event.subtree.click);
EventDispatcher.add('fc', bliscy.event.subtree.click);
EventDispatcher.add('i', bliscy.event.invite.click);
EventDispatcher.add('m', bliscy.event.message.click);
EventDispatcher.add('e', EditForm.editHandle);
EventDispatcher.add('at', AddMenu.mouseClickHandle);
EventDispatcher.add('ab', AddMenu.mouseClickHandle);
EventDispatcher.add('al', AddMenu.mouseClickHandle);
EventDispatcher.add('ar', AddMenu.mouseClickHandle);
EventDispatcher.add('menu_back', AddMenu.menuBackHandle);

WP.event.set(document, 'onclick', function(e) {
	EventDispatcher.dispatch(e);
});

WP.event.set(window, 'onload', bliscy.event.window.load);
WP.event.set(window, 'ondomload', bliscy.event.window.domload);
WP.event.set(window, 'onresize', bliscy.event.window.resize);

