
// - - - - - - - - -   G L O B A L   F U N C T I O N S - - - - - - -

// returns object or object style as reference
function o(i)  { if (typeof(i) != "string") return i; with (document) return  getElementById ? getElementById(i) : all[i] }
function os(i) { return o(i).style }

function o_scale(i,p) // p is 'Height' or 'Width'
{
	var s; i = o(i);
	with (i) eval( 's = ' + ( 'offset' + p + ' ? offset' + p  + ' : client' + p )); // with most vers: Mozilla ? Mozilla : IE
	return s ? s : parseInt(i.style[ p.toLowerCase() ]); // IE sometime don't recognize position by offset or client
}
function o_Height(i) { return o_scale(i,'Height') }
function o_Width (i) { return o_scale(i,'Width' ) }

var v_or_h = new Array('hidden', 'visible');
function o_vis(i,v) { os(i)['visibility'] = v_or_h[v] ? v_or_h[v] : v }
function o_Hide(i)  { o_vis(i,0) }; function oH(i) { o_vis(i,0) }
function o_Show(i)  { o_vis(i,1) }; function oS(i) { o_vis(i,1) }
function o_Center(i)
{
	var b = document.body;
	with (os(i))
	{
		left = (o_Width(b) / 2) - (o_Width(i) / 2);
		top  = (o_Height(b)/ 2) - (o_Height(i)/ 2);
	}
}

function o_HTML(i)  { if (arguments.length == 2) o(i).innerHTML = arguments[1]; else return o(i).innerHTML; }

function ws(text)
{
	window.status = text;
	if (arguments[1]) o(arguments[1]).onmouseout = function () { window.status = ''; }
}

// for debugging: alerts values, if cancel pressed, displaying stops
function objbrowse(bo)
{
	bo = o(bo);
	for (var i in bo) if (!confirm(i + ' => ' + bo[i])) return;
}

// function gives possible position variables of object
function graphs(i)
{
	i = o(i);
	var a,b,s = "",c,
		p = ['Height','Width','Left','Top' ],
		g = ['offset','screen','client' ];

	for (a = 0; a < g.length; a++) for (b = 0; b < p.length; b++)
	{
		eval('c = i.' + g[a] + p[b]);
		s += g[a] + p[b] + ": " + c + "\n";
	}
	alert(s);
}

// if you remove some row, this finds what to ask (text) and how to delete!
function rmrow(id,rownr)
{
	cellnr = isNaN(arguments[2])?0:arguments[2];
	if (confirm("Tahad kustuda: \"" + o("content").rows[rownr].cells[cellnr].innerHTML + '\"?'))
		location.replace('./?leht='+leht+'&del='+id);
}

String.prototype.replaces = function(what, how)
{
	var ret = this,i = 0;
	for (; i < what.length; i++)
	{
		if (what[i].charAt(0) != '/') what[i] = '/' + what[i] + '/g';
		eval('ret = ret.replace(' + what[i] + ',how[i])');
	}
	return ret;
}

function dec2hex(i)
{
	var h = '0123456789ABCDEF', d; i = parseInt(i);
	return h.charAt( (i - ( d = i % 16 )) / 16) + h.charAt(d);
}

// - - - - - - - - - - -   M O U S E   M V / D N   S E C T I O N - - - - - -
 /*
  * writing 'event = ...' can't write var: IE will generate error
  * why? if you know, mail me: kaiko@kultuur.edu.ee
  */
document.onmousemove = function ()
{
	if (arguments.length) { event = arguments[0] }
	MouseMvX = event.clientX + document.body.scrollLeft;
	MouseMvY = event.clientY + document.body.scrollTop;
	for (i in mvaction) eval(mvaction[i]);
}
document.onmousedown = function ()
{
	if (arguments.length) { event = arguments[0] }
	MouseDnX = event.clientX + document.body.scrollLeft;
	MouseDnY = event.clientY + document.body.scrollTop;
	for (i in dnaction) eval(dnaction[i]);
}
var
	mvaction = new Array(),
	dnaction = new Array();
var
	MouseMvX=-1, MouseMvY=-1,
	MouseDnX=-1, MouseDnY=-1;

// - - - - - - - - - - -   T A B L E   R O W   M O U S E O V E R   C O L O R S  - - - - - -

function color_add(base,add,sign)
{
	if (typeof(sign) == 'undefined') sign = 1;
	else if (!sign.toString().match(/[0-9]/)) sign = sign.match(/[-+]/) ? parseInt((sign[0]?sign[0]:sign) + '1') : 1;
	base = color2arr(base); add  = color2arr(add);
	for (var i = 0 ; i < 3; i++) base[i] = Math.min( 255,  Math.max(  0,  base[i] + (sign * add[i])  ) );
	return arr2color(base);
}

function color2arr(v)
{
	v = v.replace(/[^0-9]/,'');
	for (var r = new Array(), i = 0 ; i < 3; i++) r[i] = parseInt('0x'+v.substr(i*2,2));
	return r;
}
function arr2color(v)
{
	for (var c = '#', i = 0 ; i < 3; i++) c += dec2hex(v[i]);
	return c;
}

function to_overcolor()
{
	with (this)
	{
		color_def = style['background']
		style['background'] = color_ov;
	}
}

function to_defcolor()
{
	with (this) style['background'] = color_def;
}

function tr_coloradd(table,add,def,sign,starttr,endtr)
{
	var trs = o(table).rows, cr, crs, a, gecko = navigator.userAgent.indexOf("Gecko")+1;
	if (isNaN(starttr)) starttr = 1;
	if (isNaN(endtr  )) endtr = trs.length;

	for (var r = starttr; r < endtr; r++)
	{
		cr = trs[r]; crs = trs[r].style;

		trs[r].onmouseover = to_overcolor;
		trs[r].onmouseout  = to_defcolor;

		cr.color_def = (a = crs['background'].match(/rgb\(([^\)]+)/)) ?
			arr2color(a[1].split(', ')) : crs['background'];
		cr.color_ov  = cr.color_def == '' ? def : color_add( cr.color_def, add, sign);

		// Mozilla want that background have defined as transparent if there is no background
		if (!crs['background'] && gecko) crs['background'] = 'transparent';
	}
}

function t_overcolors(tab,defto)
{
	var trs = o(tab).rows;
	var starttr = isNaN(arguments[2])?1:arguments[2];
	var endtr   = isNaN(arguments[3])?trs.length:trs.length - arguments[3];
	for (var r = starttr; r < endtr; r++)
	{
		trs[r].onmouseover = to_overcolor;
		trs[r].onmouseout  = to_defcolor;

		// Mozilla want that background have defined as transparent if there is no background
		if (!trs[r].style['background'] && navigator.userAgent.indexOf("Gecko")+1) trs[r].style['background'] = 'transparent';
		trs[r].color_def  = trs[r].style['background']; // this have to be here because else color_def is treated as usual var
		trs[r].color_ov = defto;
	}
}

// . . . . . . . . A D D I N G   C O L   T A G   T O   C E L L S . . . . . . .

function cols(table)
{
	var c = new Array(), e, E;
	with (o(table))
	{
		for (e = 0; e < childNodes.length; e++)
		{
			E = childNodes.item(e);
			if (E.nodeName.toLowerCase() == 'col') c[c.length] = E.className;
		}
		for(e = 0; e < rows.length; e++) for (E = 0; E < c.length; E++) rows[e].cells[E].className = c[E];
	}
}

// - - - - - - - - - - -   P H P   S E R I A L I Z E   E M U L A T O R S - - -

function serialize(V)
{
	if (!isNaN(V) && typeof(V) != 'boolean') V = parseFloat(V);
	switch (typeof(V))
	{
		case 'boolean':return 'b:' + (V ? '1' : '0');
		case 'number': return (V == Math.round(V) ? 'i:' : 'd:') + V;
		case 'string': return 's:' + V.length + ':"' + V + '"';
		case 'object': var ret = '', len = 0, i;
			for (i in V) { len++; ret += serialize(i) + ';' + serialize(V[i]) + (typeof(V[i])=='object'?'': ';'); }
			return 'a:' + len + ':{' + ret + '}';
	}
}

function unserialize(V)
{
	var l; unser_length = (l = V.indexOf(';')) ? l : V.length ;
	switch (V.charAt(0))
	{
		case 'b': return parseInt(  V.charAt(2)) ? true : false;
		case 'i': return parseInt(  V.substr(2,l));
		case 'd': return parseFloat(V.substr(2,l));
		case 's':
			l = parseInt(V.match(/^s:([0-9]+):/)[1]);
			unser_length = 5 + l.toString().length + l;
			return V.substr(4 + l.toString().length, l);
		case 'a':
			var i, k, c = V.match(/^a:([0-9]+):/)[1], A = new Object();
			V = V.substr((l = 4) + c.toString().length);
			for (i = 0; i < c; i++)
			{
				k    = unserialize(V); V = V.substr(++unser_length); l += unser_length;
				A[k] = unserialize(V); V = V.substr(++unser_length); l += unser_length;
			}
			unser_length = l + 1;
			return A;
		default:
			return new Object();
	}
}


// - - - - - - - - - - -   S E R V E R   Q U E R Y   S E C T I O N - - - - - -
paringu_nr = 0;
func_ifanswer = '';
sq_answer = new Array();

// first parameter: func_ifanswer, then 'variable' = 'value'
function squery()
{
	if (arguments.length)
		func_ifanswer = arguments[0];

	paringu_nr++;

	var q = '';
	for (var i = 1; i < arguments.length; i+=2)
		q += '&'+arguments[i] + '='+arguments[i+1];

	sq_answer = new Array();

	// Mozilla needs <script> is rewritten. don't know why?!
	o("divsquery").innerHTML = 'ie<script id="squery'+paringu_nr+'"></'+'script>';
	o("squery"+paringu_nr).src = "squery.php?pnr="+paringu_nr+q;

	// debugging
	if (o("squery_info")) o("squery_info").innerHTML = "squery.php?pnr="+paringu_nr+q;

	// visul things for user
	window.status = "Ootan serverilt vastust...";
	document.body.style['cursor'] = 'wait';
}

function squery_end()
{
	document.body.style['cursor'] = 'auto';

	if (func_ifanswer) eval(func_ifanswer);
	func_ifanswer = '';

	// debugging
	if (o("squery_info"))
		o("squery_info").innerHTML += "<br /><b>Vastus:</b><br /><pre>" + o("squery"+paringu_nr).innerHTML + "</pre>";

	// message for 3 seconds
	window.status = 'Vastus serverilt olemas';
	setTimeout('window.status=""',3000);
}

// - - - - - - - - - - -   P O S T O F F I C E   Z O N E - - - - - - (sending variables with post)

// this if for changing if needed
postaddress = location.href;
function postoffice()
{
	if (arguments[0]) postaddress = arguments[0];

	var q = '';
	for (var i = 1; i < arguments.length; i+=2)
		q += '<input type="hidden" name="'+arguments[i] + '" value="'+arguments[i+1]+'" />'+"\n";
  
	q += '<input type="hidden" name="screen_pos" value="'+document.body.scrollTop+'" />' +"\n";
  
	o("postoffice").innerHTML = '<form name="postoffice" method="post">'+q+'</form>';
	document.postoffice.submit()
}

//  --- --- --- --- fields check
var cf_err = new Array();
function check_fields(form)
{
	var el = document[form].elements, t = "", eo, lp = "label_for_";

	for (e = 0; e < cf_err.length; e++)
	{
		os(lp + cf_err[e])["color"] = o(lp + cf_err[e]).defcolor;
		os(lp + cf_err[e])["font-weight"] = "normal";
	}

	cf_err = new Array();
	for(var e = 0; e < el.length; e++) with (el[e])
		if (type == "hidden" || type == "select-one" || type == "textarea" || type == "text")
		if (value == "" || value == 0)
		if (o(lp + name)) // label for this field exists
			cf_err[cf_err.length] = name;

	for (e = 0; e < cf_err.length; e++) with (eo = o(lp + cf_err[e]))
	{
		eo.defcolor = style["color"];
		style["color"] = "#FF0000";
		style["font-weight"] = "bold";
	}
	return !cf_err.length;
}

// - - - - - - - - - - -   M O U S E O V E R  I M G   Z O N E  - - - - (sending variables with post)

function add_pic(src) { pilt[src] = new Image(); pilt[src].src = src + '.gif'; }
function pildid_load(ps)
{
  var p = ps.split(',');
  for(var i = 0;i < p.length; i++) if (p[i].length)
  {
    add_pic(p[i]);
    for(var lisa=1; lisa<(arguments.length);lisa++) add_pic(p[i] + arguments[lisa])
  }
}

function pildid_aktiveeri(ps)
{
	var p = ps.split(',');

	for(var i = 0; i < p.length; i++) if (p[i].length)
	{
		document.images[p[i]].onclick     = function () { ch_n(act); ch_n(act = this.name,'_ov') }
		document.images[p[i]].onmouseover = function () { if (this.name != act) ch_n(this,'_ov') }
		document.images[p[i]].onmouseout  = function () { if (this.name != act) ch_n(this) }
	}
	ch_n(act = document.images[p[0]].name,'_ov');
}

function ch_n(n)
{
  if (typeof(n) == 'string') n = document.images[n]; // edastada v6ib seega this'i (pildi obj) v6i pildi nime
  var lisa = typeof(arguments[1]) == 'string' ? arguments[1] : '';
  n.src = pilt[n.name+lisa].src;
}


// . . . . . .   . ..    f o l k   m u s i c   f e s t i v a l   z o n e

var pilt = new Array();
var loc_str = window.top.location.toString()
var Iam_eng = loc_str.indexOf('eng')+1;
var LANG = Iam_eng ? 'en' : 'et';
var ISEST = LANG == 'et', ISENG = LANG == 'en';
var tagasi_prepared = false;
var bgi_ov  = '#400000';
var MSIE = navigator.userAgent.indexOf("MSIE") + 1;

if (window == window.top)
if (loc_str.indexOf("no_frame_ask") == -1) // kui keegi tahab, siis vőib sellega kysimust vĂ¤ltida
if (typeof(no_frame_ask) == 'undefined')
if (confirm('See aken on mĂµeldud vaatamiseks raamaknas! Kas paneme ta nii nagu mĂµeldud on?'))
{
  var reg_path = new RegExp('(.*/)(.*)'); var p = reg_path.exec(window.location);
  if (loc_str.indexOf("/navi") == -1)
    window.location.replace(p[1] + '?link=' + p[2]);
  else window.location.replace('/2003/');
}

// . . . . . b a c k g r o u n d   i n f o   c r e a t o r s . . . .

function lCh_color(obj,color)
{
	color = color ? color : obj.lastChild.lastColor;
	with (obj.lastChild) if (nodeName == 'SPAN')
	{
		obj.lastChild.lastColor = style.color;
		style.color = color;
	}
}

function chhtml(area_id,breaker,breaker_new,repl,repl_to)
{
	var el = o_HTML(area_id); el = "\n" + el;
  eval('el = el.split(' + breaker + ')');

  repl_to = repl_to.replace(/"/g,'\\"'); // for vim highlight bug ' )
  for (var i = 0; i < el.length; i++)
    eval ('el[i] = el[i].replace(' + repl + ',"' + repl_to + '")');

  o_HTML(area_id,el.join(breaker_new));
}

function bginfo(area_id,bTag,tobg)
{
  chhtml(area_id,
    '/<' + bTag + '>/i','<' + bTag + ' onmouseover="lCh_color(this,bgi_ov)" onmouseout="lCh_color(this)">',
    '/' + tobg + '/','<span class="bginfo"> $1</span>');
}

function maainfo(i) { bginfo(i,'li','(\\([^<]*)') }
function kontinfo(i){ bginfo(i,'li','( - [^<]*)') }

// . . . . . . . . . . . . 


function tegijad(tegijad,template)
{
	var ret = '',t = 0, nimi = 0, pilt = 1, amet = 2 +(Iam_eng?1:0),info = 4,
		raam = ('tegija_raam.' + ((navigator.userAgent.indexOf("MSIE")+1)? 'gif' : 'png'));

	template = template.replaces(
		['%R','/(<table )/i'],
		['<img title="" alt="" src="'+raam+'" />','$1background="tiim/%P" ']);
	tegijad = tegijad.replaces(
		['([a-z]*)=att=([\\.a-z]*)'                       ,'\\s*\\|\\s*'],
		['<a class="mailto" href="mailto:$1@$2">$1@$2</a>','<br />'     ]).split(/\s*\^\s*/);

	for (t; t < tegijad.length; t += 5)
	{
		NIMI = tegijad[t + nimi]; AMET = tegijad[t + amet];
		INFO = Iam_eng ? tegijad[t + info].replace(/0(43|5\d) /g,'+372 $1 ') : tegijad[t + info];
		PILT = tegijad[t + pilt]; PILT = PILT == '-' ? 'logo.gif' : ( PILT + '.jpg');

		ret += (((t/5) % 3)?'</td><td>':'</td></tr><tr><td>');
		ret += (template.replaces(['%I','%N','%P','%A'],[INFO,NIMI,PILT,AMET]));
	}
	return ret;
}


function tagasi_prep()
{
  var nimi   = Iam_eng?'Back':'Tagasi';
  var tagasi = Iam_eng?'Back':'Tagasi (nagu Back nupp)';
  var nn = nimi.toLowerCase();

  pildid_load(nn,'down');

	tagasi_str = '<a href="javascript:history.go(-1)" target="sisu"'
  +  'onmousedown="ch_n(\''+nn+'\',\'down\');" onmouseover="window.status=\''+tagasi+'\'; return true;" onmouseout="ch_n(\''+nn+'\'); window.status=\'\';" onmouseup="window.status=\'\'">'
  +  '<img src="'+nn+'.gif" name="'+nn+'" border="0" alt="'+nimi+'" /></a>';

  tagasi_prepared = true;
}

function tagasi() {
  if (!tagasi_prepared) tagasi_prep();
  // if (history.length > 0)
  document.writeln(tagasi_str);
}

function set_paike()
{
	document.writeln('<img src="p2ike.gif" id="paike" alt="" />');
	os('paike').left = Math.round(Math.random() * o('pageframe').offsetWidth + 1)  - o('paike').width;
	os('paike').top  = Math.round(Math.random() * o('pageframe').offsetHeight + 1) - o('paike').height;
}

var act = ""; // aktiivne nupp
function writenavi(imgs)
{
	var exist = new Array(), donavi, n, L, tpl = new Array();
		tpl['n-img']   = '<img src="%N.gif" name="%N" id="%N" alt="%N" title="" />';
		tpl['n-plain'] = '%I';
		tpl['n-link']  = '<a href="../%L.php" class="imglink">%I</a>';

	N = imgs.replace(/\s/g,'').split(',');
	for (n = 0; n < N.length; n++)
	{
		if (link = /\(([^)]+)\)/.exec(N[n]))
		{
			L = link[0].replace(/\)|\(/g,'');
			N[n] = N[n].replace(/\([^)]+\)/,'');
		}
		else L = N[n].replace(/-/,'');

  	if (donavi = N[n].indexOf('-')+1)
			N[n] = N[n].replace(/-/,'');
		else exist[exist.length] = N[n];

		document.write(tpl[donavi?'n-plain':'n-link'].replace(
			/%I/ , tpl['n-img']).replace(
			/%N/g, N[n]        ).replace(
			/%L/g, L           ).replace(
			/%n/g, n           ));
	}
	pildid_load(P = exist.join(','),'_ov');
	pildid_aktiveeri(P);
}

// nupud loetakse ainult juurikas olevate failide peale
loc_osad  = loc_str.split('/');
self_osad = self.location.toString().split('/');
if (typeof no_send_and_back_buttons == 'undefined' &&
  loc_osad[loc_osad.length-2] == self_osad[self_osad.length-2])
{
	pildid_load(LANG == 'et' ? 'saada' : 'send','_down','_ov');
	pildid_load('tagasi,back','_down','_ov');
	if (navigator.userAgent.indexOf("MSIE")+1)
		document.writeln('<link rel="stylesheet" type="text/css" href="folk-ie.css" />');

}


