var time_reload_stop_flag = false;

var galerieLightBox = null;
var galerieLightBoxData = null;
var galerieLightBoxOpt = null;

function reload_parent(inserted_id) {
	my_form = document.forms['form_edit'];
	if (my_form['parent_form'].value) {
		parent_form = window.opener.document.forms[my_form['parent_form'].value];
		parent_form['s'].value = my_form['parent_s'].value;
		if (parent_form['table']) parent_form['table'].value = parent_form['self_table'].value;
		if (parent_form['id']) parent_form['id'].value = parent_form['self_id'].value;
		if (my_form['parent_input'] && my_form['parent_input'].value != "")
			parent_form[my_form['parent_input'].value].value = inserted_id;
		NoUpdate(parent_form);
		parent_form.submit();
	}
	else {
		window.opener.location.reload(true);
	}

	window.close();
}

function time_reload(time_to_close, atable, countdown) {
	if (frames['iframe_checker'].document.forms['form_checker'] && frames['iframe_checker'].document.forms['form_checker']['not_logged_in'].value == '1')
		location.href = './';  // zrejme uprava aplikace - smazan autentifikacni retezec z db - skok na Login
	if (time_reload_stop_flag) {
		document.getElementById('timereload_headtext').innerHTML = '<font color="red">Synchronizace je vypnuta.</font>';
//		frames['iframe_checker'].location.href = 'index_checker.php?stop=1';  // zastav checker
//		return false;  // konec odpocitavani, zadny reload
	}
	if (!countdown) {  // faze porovnavani verze vypsane tabulky a tabulky v databazi
		if (frames['iframe_checker'].document.forms['form_checker']) {  // je iframe nacten?
			if (frames['iframe_checker'].document.forms['form_checker']['table_version_db_'+atable].value == document.forms['form_writedown']['table_version_'+atable].value) {  // tabulka se v db nezmenila
				setTimeout("time_reload("+time_to_close+", '"+atable+"', false);", 1000);  // dalsi kontrola za nejaky cas
				return false;
			}
			else {  // tabulka se v db zmenila!
				frames['iframe_checker'].location.href = 'index_checker.php?stop=1&beep=1';  // zastav checker a zapipej
				document.body.style.backgroundColor = '#f0f0f0';
				if (!time_reload_stop_flag) {  // pokud je synchronizace off, stopne se time_reload()ovani
					setTimeout("time_reload("+time_to_close+", '"+atable+"', true);", 100);  // spust odpocet
				}
				return false;
			}
		}
		else {  // iframe 'checker' se zrejme zrovna reloaduje, pockame...
//			alert('iframe not loaded!');
			frames['iframe_checker'].document.forms['form_checker'];
			setTimeout("time_reload("+time_to_close+", '"+atable+"', false);", 1000);  // retry za sekundu
			return false;
		}
	}
	else {  // faze odpocitavani casu do reloadu stranky
		document.getElementById('timereload_headtext').innerHTML = 'Stránka se přenačte za '+time_to_close+' sekund.';
		if (time_to_close > 0) {
			time_to_close--;
			setTimeout("time_reload("+time_to_close+", '"+atable+"', true);", 1000);  // dalsi krok odpoctu za sekundu
		}
		else {
			window.location.href = './?s=writedown&table=&'+(document.forms['form_writedown']['writedownall'].value == '1' ? 'writedownall=1' : 'timereload=1');  // okamzity reload
		}
	}
}

function time_reload_stop() {
	document.getElementById('a_time_reload_stop').style.display = 'none';
	time_reload_stop_flag = true;
	return false;
}

//-----------------------------------

function ChangeFilterVisibility(that, id) {
	var e = document.getElementById(id);
	if (e.style.display == 'none') {
		e.style.display = 'block';
		that.innerHTML = '<img src="style/icon_find.png" /> Schovat úpravy výpisu...';
	}
	else {
		e.style.display = 'none';
		that.innerHTML = '<img src="style/icon_find.png" /> Zobrazit úpravy výpisu...';
	}
	return false;
}

function ChangePagesVisibility(that, id) {
	var e = document.getElementById(id);
	if (e.style.display == 'none') {
		e.style.display = 'inline';
		that.style.display = 'none';
	}
	else {
		e.style.display = 'none';
		that.style.display = 'inline';
	}
	return false;
}

function ChangeVisibility(id) {
	var e = document.getElementById(id);
	if (e.style.display == 'none') {
		e.style.display = 'block';
	}
	else {
		e.style.display = 'none';
	}
	return false;
}

function ChangeSemaphoreState(animg, aformname, aninputname) {
	var aninput = document.forms[aformname][aninputname];
	if (aninput.value == '0') {
		aninput.value = '1';
	}
	else if (aninput.value == '1') {
		aninput.value = '2';
	}
	else {
		aninput.value = '0';
	}
	animg.src = 'style/semaphore_' + aninput.value + '.gif';
}

function ChangeBooleanState(animg, aformname, aninputname) {
	var aninput = document.forms[aformname][aninputname];
	if (aninput.value == '1') {
		aninput.value = '0';
	}
	else {
		aninput.value = '1';
	}
	animg.src = 'style/boolean_' + aninput.value + '.gif';
}

function PotvrdZmenu() {
	return confirm('Opravdu chcete změnit tuto položku?');
}

function PotvrdSmazani() {
	return confirm('Opravdu chcete smazat tuto položku?');
}

function PotvrdOdhlaseni() {
	return confirm('Opravdu se chcete odhlásit?');
}

function ChangeWritedownTRState(tr_id) {
	var tr = document.getElementById('writedown_tr_' + tr_id);
	changed = tr.className.indexOf('tr_state_abnormal');
	if (changed >= 0)
		tr.className = tr.className.replace('tr_state_abnormal', 'tr_state_normal');
	else
		tr.className = tr.className.replace('tr_state_normal', 'tr_state_abnormal');
	return true;
}


// nulovani podstatnych inputu pri kazde akci [update, delete, ...] je nutne kvuli IE pri pouzivani navigace ZPET, VPRED
// hodnota hidden inputu totiz po Zpet zustane nastavena, tzn. ze se napr. odesle update==delete==1
function NoUpdate(aform) {
	if (aform['action']) aform['action'].value = '';
}

// odeslani formularu po kliku na <a href...> nebo na odesilaci tlacitka provadi tato funkce
function SubmitForm(anaction, aform, atable, anid, parents, valid_data) {
	document.forms[aform]['table'].value = atable;
	document.forms[aform]['id'].value = anid;
	document.forms[aform]['parents'].value = parents;
	NoUpdate(document.forms[aform]);

	if (anaction == 'delete') {
		if (!PotvrdSmazani())
			return false;
		document.forms[aform]['s'].value = document.forms[aform]['self_s'].value;
		document.forms[aform]['action'].value = anaction;
	}
	else if (anaction == 'update' || anaction == 'direct_edit' || anaction == 'cancel') {
		document.forms[aform]['s'].value = document.forms[aform]['self_s'].value;
		document.forms[aform]['action'].value = anaction;
	}
	else if (anaction == 'new_mail') {
		document.forms[aform]['s'].value = 'posta';
		document.forms[aform]['action'].value = anaction;
	}
	else if (anaction == 'command') {
		document.forms[aform]['s'].value = 'writedown';
		document.forms[aform]['action'].value = anaction;
	}
	else {
		document.forms[aform]['s'].value = anaction;
	}

	if (typeof(document.forms[aform]['valid_data']) != "undefined") {
		if (valid_data) {
			document.forms[aform]['valid_data'].value = '1';
		}
		else {
			document.forms[aform]['valid_data'].value = '0';
		}
	}

	document.forms[aform].submit();  // odeslani formulare
	return false;
}

function SubmitCommand(aform, atable, anid, acommand, parents) {
	document.forms[aform]['command'].value = acommand;
	return SubmitForm('command', aform, atable, anid, parents, true);
}

function SubmitListing(aform, atable, listingtable, thefirst, parents) {
	document.forms[aform]['writedown_listing_first_' + listingtable].value = thefirst;
	return SubmitForm(document.forms[aform]['self_s'].value, aform, atable, document.forms[aform]['self_id'].value, parents, true);
}

function SubmitListingAll(aform, atable, listingtable, parents) {
	document.forms[aform]['writedown_listing_perpage_' + listingtable].value = '0';
	return SubmitForm(document.forms[aform]['self_s'].value, aform, atable, document.forms[aform]['self_id'].value, parents, true);
}

function SubmitOrdering(aform, atable, orderby_idx, direction_idx, parents) {
	document.forms[aform]['razeni_' + atable + '_sloupec'].selectedIndex = orderby_idx;
	document.forms[aform]['razeni_' + atable + '_smer'].selectedIndex = direction_idx;
	return SubmitForm(document.forms[aform]['self_s'].value, aform, document.forms[aform]['self_table'].value, document.forms[aform]['self_id'].value, parents, true);
}

function SubmitDirectEdit(aform, atable, anid, acolumn, avalue, parents) {
	if (!PotvrdZmenu())
		return false;
	document.forms[aform]['direct_edit_column'].value = acolumn;
	document.forms[aform]['direct_edit_value'].value = avalue;
	return SubmitForm('direct_edit', aform, atable, anid, parents, true);
}

function PrintTableItem(table, id) {
	okno = window.open('index_print.php?table=' + table + '&id=' + id, 'print', 'left=5,top=5,scrollbars=yes,width=830,height=590,resizable=yes,menubar=yes');
	okno.focus();
	return false;
}

function SubmitSetMail(aform, anid, predmet, id_prijemce, parents) {
	document.forms[aform]['action'].value = 'new_mail';
	if (predmet !== false) {
		document.forms[aform]['edit_zpravy_predmet__preset'].value = predmet;
	}
	if (id_prijemce !== false) {
		document.getElementById('secondaryedit_uzivatele_vyber_000').name = 'secondaryedit_uzivatele_vyber_'+id_prijemce;
		document.getElementById('secondaryedit_uzivatele_vyber_000').value = '1';
	}
	return SubmitForm(anid == '0' ? 'new_mail' : 'posta', aform, 'zpravy', anid, parents, true);
}

function SubmitShowDetail(atable, anid) {
	var o = document.getElementById('detail_iframe');
//	o.onload = function(){ DetailOnLoad(); };
	document.getElementById('body').onresize = function(){ BodyResized(); };
	var odoc = (o.contentDocument ? o.contentDocument : o.contentWindow.document);
	odoc.getElementById("body").innerHTML = 'loading...';
	BodyResized();
	ResizeDisabler(true);
//	o.style.visibility = 'visible';
	o.src = './?s=detail&show_content_only=1&table='+atable+'&id='+anid;
	return false;
}
function DetailOnLoad() {
	ResizeDisabler(true);
	ResizeDetailIframe(true);
}
function ParentDetailOnLoad() {
	if (window.parent)
		window.parent.DetailOnLoad();
}

function BodyResized() {
	ResizeDisabler(false);
	ResizeDetailIframe(false);
}

function ResizeDisabler(show) {
	var o = document.getElementById('disabler');
	var o2 = document.getElementById('disabler_loading');
	var winw = WinW();
	var winh = WinH();
	var docsize = GetScrollXY();
	var docleft = docsize[0];
	var doctop = docsize[1];

	o.style.left = Math.round(docleft) + 'px';
	o.style.width = Math.round(winw) + 'px';
	o.style.height = Math.round(Math.max(document.body.scrollHeight, winh)) + 'px';
/*
	o.style.top = Math.round(doctop) + 'px';
	o.style.width = Math.round(Math.max(document.body.scrollWidth, winw)) + 'px';
	o.style.height = Math.round(winh) + 'px';
*/
	o2.style.left = Math.round(docleft + (winw - 39) / 2) + 'px';
	o2.style.top = Math.round(doctop + (winh - 39) / 2) + 'px';
	if (show) {
		o2.style.visibility = o.style.visibility = 'visible';
	}
}
function ResizeDetailIframe(show) {
	var o = document.getElementById('detail_iframe');
	var oclose = document.getElementById('detail_close');
	var winw = WinW();
	var winh = WinH();
	var docsize = GetScrollXY();
	var docleft = docsize[0];
	var doctop = docsize[1];
	var width = Math.round(winw * 0.75);
	var odoc = (o.contentDocument ? o.contentDocument : o.contentWindow.document);
	var height = Math.max(Math.min(odoc.getElementById("body").scrollHeight, winh * 0.9), 10);
	o.style.width = width + 'px';
	o.style.height = height + 'px';
	o.style.left = Math.round(docleft + (winw - width) / 2) + 'px';
	o.style.top = Math.round(doctop + (winh - height) / 2) + 'px';
	oclose.style.left = Math.round(docleft + (winw + width) / 2 + 20) + 'px';
	oclose.style.top = o.style.top; //Math.round(doctop + (winh + height) / 2 - 48) + 'px';
	if (show) {
		o.style.visibility = 'visible';
		oclose.style.visibility = 'visible';
		o.focus();
	}
}
function HideDetail() {
	var o = document.getElementById('detail_iframe');
	o.style.visibility = 'hidden';
	document.getElementById('detail_close').style.visibility = 'hidden';
	document.getElementById('disabler').style.visibility = 'hidden';
	document.getElementById('disabler_loading').style.visibility = 'hidden';
	var odoc = (o.contentDocument ? o.contentDocument : o.contentWindow.document);
	odoc.getElementById("body").innerHTML = '';
}

function WinW() {
if (document.documentElement && document.documentElement.clientWidth)
	/* MSIE6 v std. režimu, popr. Opera a Mozilla */
	return document.documentElement.clientWidth;
else if (window.innerWidth)
	/* NN4 a kompatibilní prohlížeče */
	return window.innerWidth;
else if (document.body && document.body.clientWidth)
	/* starší MSIE + MSIE6 v quirk režimu */
	return document.body.clientWidth;
else
	return null;
}
function WinH() {
if (document.documentElement && document.documentElement.clientHeight)
	/* MSIE6 v std. režimu, popr. Opera a Mozilla */
	return document.documentElement.clientHeight;
else if (window.innerHeight)
	/* NN4 a kompatibilní prohlížeče */
	return window.innerHeight;
else if (document.body && document.body.clientHeight)
	/* starší MSIE + MSIE6 v quirk režimu */
	return document.body.clientHeight;
else
	return null;
}
function GetScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}


function FillInputNow(aform, aninput) {
//	now = new Date();
//	document.forms[aform][aninput].value = now.getDate() + '.' + (now.getMonth() + 1) + '.' + now.getFullYear() + ' ' + (unescape(now.getHours()).length < 2 ? '0' : '') + now.getHours() + ':' + (unescape(now.getMinutes()).length < 2 ? '0' : '') + now.getMinutes()/* + ':' + (unescape(now.getSeconds()).length < 2 ? '0' : '') + now.getSeconds()*/;
	if (document.forms[aform][aninput + '__actual'] && document.forms[aform][aninput + '__actual'].checked) {
		document.forms[aform][aninput + '__old_value'].value = document.forms[aform][aninput].value;
		document.forms[aform][aninput].style.display = 'none';
		document.forms[aform][aninput].value = '--actual--';
	}
	else {
		document.forms[aform][aninput].value = document.forms[aform][aninput + '__old_value'].value;
		document.forms[aform][aninput].style.display = 'inline';
	}
	return true;
}

function OpenCalendar(aform, aninput, table, column, cas) {
	if (document.forms[aform][aninput + '__actual'] && document.forms[aform][aninput + '__actual'].checked == true) {
		document.forms[aform][aninput + '__actual'].checked = false;
		FillInputNow(aform, aninput);
	}
	okno = window.open('index_kalendar.php?form=form_edit&input=edit_' + table + '_' + column + '&cas=' + cas + '&datum=' + document.forms['form_edit']['edit_' + table + '_' + column].value, 'kalendar', 'left=400,top=100,scrollbars=yes,width=415,height=415,resizable=yes');
	okno.focus();
	return false;
}

function ShowTableList() {
	HidePreferences();
	return ShowOrHideElement('menu_table_list', 'show');
}
function HideTableList() {
	return ShowOrHideElement('menu_table_list', 'hide');
}
function ShowOrHideTableList() {
	return ShowOrHideElement('menu_table_list', 'toggle');
}
function ShowPreferences() {
	HideTableList();
	return ShowOrHideElement('menu_preferences', 'show');
}
function HidePreferences() {
	return ShowOrHideElement('menu_preferences', 'hide');
}
function ShowOrHidePreferences() {
	return ShowOrHideElement('menu_preferences', 'toggle');
}
function ShowSubMenu(id_parent) {
	return ShowOrHideElement('submenu_' + id_parent, 'show');
}
function HideSubMenu(id_parent) {
	return ShowOrHideElement('submenu_' + id_parent, 'hide');
}



function ShowOrHideElement(element_id, command) {
	var e = document.getElementById(element_id);
	if (!e) return false;
	if (command == 'show')
		e.style.display = 'block';
	else if (command == 'hide')
		e.style.display = 'none';
	else {
		if (e.style.display != 'block')
			e.style.display = 'block';
		else
			e.style.display = 'none';
	}
	return false;
}

function CheckAll(aform, input_name, id_writtendown) {
	var ids = document.forms[aform][id_writtendown].value.split(",");
	for (var i = 0; i < ids.length; i++) {
		document.forms[aform][input_name+'_'+ids[i]].checked = true;
	}
	return false;
}

function UnCheckAll(aform, input_name, id_writtendown) {
	var ids = document.forms[aform][id_writtendown].value.split(",");
	for (var i = 0; i < ids.length; i++) {
		document.forms[aform][input_name+'_'+ids[i]].checked = false;
	}
	return false;
}

function FocusLogin() {
	document.forms['form_login']['login'].focus();
}

function Init() {
	var lightBoxOpt = {
		galleryClassName: "lightBox2",
		zIndex: 7,
		useShadow: true,
		imagePath: 'lightbox/img/shadow-',
		usePageShader: true,
		components: {
			strip: SZN.LightBox.Strip.Scrollable,
			navigation: SZN.LightBox.Navigation.Basic,
			anchorage: SZN.LightBox.Anchorage.Fixed,
			main: SZN.LightBox.Main.CenteredScaled,
			description: SZN.LightBox.Description.Basic,
			transition: SZN.LightBox.Transition.Fade
		},
		stripOpt : {
			activeBorder : 'outer'
		},
		navigationOpt : {
			continuous: false,
			showDisabled: true
		},
		transitionOpt: {
			interval: 300,
			overlap: 0.8
		}
	};
	
	if (document.getElementsByTagName) {
		var galerie_counter = 0;
		var p_tags = document.getElementsByTagName("p");
		for (var i = 0; i < p_tags.length; i++) {
			if (p_tags[i].className == 'galerie') {
				galerie_counter++;
				p_tags[i].setAttribute("id", "galerie_" + galerie_counter);
				var lightBoxx = SZN.LightBox.create("galerie_" + galerie_counter, lightBoxOpt);
			}
		}
	}
	
	if (document.getElementById('galerie_fotky') && galerieLightBoxData) {
		galerieLightBox = new SZN.LightBox(galerieLightBoxData, lightBoxOpt);
		galerieLightBox.bindAnchors('galerie_fotky');
	}
}

