(
	function(){
		var UA=navigator.userAgent;
		is_ie=/msie/i.test(UA)&&!(/opera/i.test(UA))&&!(/mac_powerpc/i.test(UA));
		is_khtml=/Konqueror|Safari|KHTML/i.test(UA);
		is_gecko=/gecko/i.test(UA)&&!is_khtml;
	}
)();

function CMSmenu( cms_data, curr_link ) {
	this.cms_data = cms_data || new Array();
	this.oldPageContent = document.body.innerHTML;
	this.newPageContent = '';
	this.elements = new Array();
	this.sections = new Array();
	this.config = new Array(); 
	this.config['imgPath'] = 'images/menu_icons/';
	this.config['imgLink'] = 'item_default.gif';
	this.config['imgSection'] = 'lnk_sec.gif';
	this.config['imgCell'] = '16px';
	this.config['openPointer'] = '<img src="'+this.config['imgPath']+'open.gif'+'" />'; //'&#9660;';
	this.config['closePointer'] = '<img src="'+this.config['imgPath']+'close.gif'+'" />'; //'&#9658;';
	this.config['animateSpeed'] = 100;
	this.config['animateEase'] = 2;
	this.config['cookieName'] = 'CMSmenuUser';
	this.config['loginUserName'] = '';
	this.config['loginErr'] = '';
	this.config['imgLogin'] = 'login.gif';
	this.config['imgHelp'] = 'help.gif';
	this.currentLink_link = curr_link;
//	this.currentSection = 0;
//	this.currentLink = 0;
	this.currentHelp = '';


	// BUILDS MENU ==================
	this.build = function() {
		document.body.innerHTML = '';
		// help bubble
		_bubble = this.addElement('div',document.body , 0, 'id=bubble');
		_bubble.style.visibility = 'hidden';
		_bubble.style.display = 'none';
		_bubble.style.position = 'absolute';
		_bubble.style.zIndex = '1';
		_bubble.style.left = '1px';
		_bubble.style.top = '1px';
		// new content
		this.elements['cms_page'] = this.addElement('table',document.body , 1, 'id=cms_page|width=100%|height=100%|cellspacing=0|cellpadding=0|border=0');
		_tbody = this.addElement('tbody', this.elements['cms_page'], 1);
		_tr_big = this.addElement('tr', _tbody, 1);
		this.elements['cms_menu_holder'] = this.addElement('td', _tr_big, 0, 'id=cms_menu_holder');
//		this.elements['cms_page'] = this.addElement('div',document.body , 1, 'id=cms_page');
//		this.elements['cms_menu_holder'] = this.addElement('div', this.elements['cms_page'], 0, 'id=cms_menu_holder');
		this.elements['cms_menu'] = this.addElement('div', this.elements['cms_menu_holder'], 0, 'id=cms_menu');
		this.buildSection('Help');
		// builds content of the menu
		if(this.config['loginUserName']!='') {
			// sections
			for(var i in this.cms_data) {
				if(this.cms_data[i].parent == '') {
					_section = this.buildSection(
															this.cms_data[i].id,
															this.cms_data[i].name,
															this.cms_data[i].title,
															this.cms_data[i].img );
				}
			}
			// links
			for(var i in this.cms_data) {
				if(this.cms_data[i].parent != '') {
					_link = this.buildItem(
													this.cms_data[i].id,
													this.cms_data[i].name,
													this.cms_data[i].parent,
													this.cms_data[i].title,
													this.cms_data[i].target,
													this.cms_data[i].img,
													this.cms_data[i].help );
				}
			}
		}
		// adding login section
		this.buildSection('Log In');
		this.elements['cms_menu'].appendChild( this.sections['Log In']['section'] );
		_spacer = this.addElement('div', this.elements['cms_menu'], 0, 'className=spacer');
		this.elements['cms_menu'].appendChild( this.sections['Help']['section'] );
		this.reSetHelp();
		// adding old page content
		this.elements['cms_content'] = this.addElement('td', _tr_big, 1, 'id=cms_content');
//		this.elements['cms_content'] = this.addElement('div', this.elements['cms_page'], 1, 'id=cms_content');
		this.elements['cms_content_body'] = this.addElement('div', this.elements['cms_content'], 1, 'id=body');
		this.elements['cms_content_body'].innerHTML = this.oldPageContent;
		for(var i in this.sections) {
			this.sections[i]['container']._initHeight = this.sections[i]['container'].offsetHeight;
			if(i != 'Help')
				this.sections[i]['container'].style.height = this.sections[i]['container'].offsetHeight;
			else
				this.sections[i]['container'].style.height = 'auto';
		}
//		this.newPageContent = this.elements['cms_page'];
	}


	// BUILDS SECTION ==================
	this.buildSection = function( _id, _name, _title, _img ) {
		var _self = this;
		var _parent = (_id!='Help' ? this.elements['cms_menu'] : '');
		this.sections[_id] = new Array();
		this.sections[_id]['section'] = this.addElement('div', _parent, 0, 'className=section');
		this.sections[_id]['section'].onmouseover = function(ev){
																			_self.mOver(this);
																		}
		this.sections[_id]['section'].onmouseout = function(ev){
																			_self.mOut(this);
																		}
		// section title
		this.sections[_id]['title'] = this.addElement('table', this.sections[_id]['section'], 0, 'className=title|title='+(_id=='Help' ? 'help section' : (_id=='Log In' ? 'log-in section' : _title)));
		this.sections[_id]['title'].onclick = function(ev){
																		_self.animationToggle(_id);
																	}
		_temp_tbody = this.addElement('tbody', this.sections[_id]['title'], 1);
		_temp_tr = this.addElement('tr', _temp_tbody);
		if(_id=='Help' && this.config['imgHelp']) {
			_temp_td = this.addElement('td',_temp_tr,0,'width=15|valign=top');
			_temp_td.style.padding='0px';
			this.addElement('img',_temp_td,0,'src='+this.config['imgPath']+this.config['imgHelp']);
		}
		else if(_id=='Log In' && this.config['imgLogin']) {
			_temp_td = this.addElement('td',_temp_tr,0,'width=15|valign=top');
			_temp_td.style.padding='0px';
			this.addElement('img',_temp_td,0,'src='+this.config['imgPath']+this.config['imgLogin']);
		}
		else {
			if(_img) {
				_temp_td = this.addElement('td',_temp_tr,0,'width=15|valign=top');
				_temp_td.style.padding='0px';
				this.addElement('img',_temp_td,0,'src='+this.config['imgPath']+_img);
			}
		}
		_temp_td = this.addElement('td',_temp_tr,0,'innerHTML='+(_id=='Help' ? 'Help' : (_id=='Log In' ? 'Log In' : _name)));
		this.sections[_id]['title_pointer'] = this.addElement('td',_temp_tr, 0, 'align=right');
		this.sections[_id]['title_pointer'].innerHTML = this.config['openPointer'];
		this.sections[_id]['title_pointer'].style.fontFamily = 'Arial,sans-serif';
		// section content
		this.sections[_id]['container'] = this.addElement('div', this.sections[_id]['section'], 1, 'className=container|_state=opened');
		this.sections[_id]['body'] = this.addElement('div', this.sections[_id]['container'],0,'className=body');
		if(_id=='Help') {
			this.sections[_id]['help_container'] = this.addElement('div', this.sections[_id]['body'],0,'className=help_container');
		}
		else if(_id=='Log In') {
			this.buildLogin(_id);
		}
		if(_id != 'Help')
			this.addElement( 'div', this.elements['cms_menu'], 0, 'className=spacer' );
	}


	// BUILDS ITEM ==================
	this.buildItem = function( _id, _name, _parent, _title, _target, _img, _help, _noatt) {
		var _attachParent = (_noatt ? '' : this.sections[_parent]['body']);
		if(_target == 'separator') {
			_separator= this.addElement('div', _attachParent,0,'className=separator');
			this.addElement('hr', _separator);
			return;
		}
		var _self = this;
		var _item = new Array();
		_item['table'] = this.addElement('table', this.sections[_parent]['body'], 0, 'className=item|title='+(_title ? _title : ''));
		if(this.currentLink_link == _target) { // _id se smeni na _target
			_item['table'].className += ' selected_item';
			this.currentHelp = _help;
		}
		else {
			_item['table'].onmouseover = function(ev){
														_self.mOver(this);
														_self.setHelp(_help ? _help : '* * *');
													}
			_item['table'].onmouseout = function(ev){
														_self.mOut(this);
														_self.reSetHelp();
													}
			if(_target) {
				_item['table']._href = _target;
				_item['table'].onclick = function(ev){
														_self.mClick(_self, this._href);
													}
			}
		}
		_item['tbody'] = this.addElement('tbody', _item['table'], 1);
		_item['tr'] = this.addElement('tr', _item['tbody']);
		if(_img || this.config['imgLink']) {
			_item['td_1'] = this.addElement('td', _item['tr'], 0, 'className=img_holder');
			_item['td_1'].style.width = this.config['imgCell'];
			_item['img'] = this.addElement('img', _item['td_1'],0,'src='+(_img ? this.config['imgPath']+_img : this.config['imgPath']+this.config['imgLink']));
		}
		_item['td_2'] = this.addElement('td', _item['tr'], 0, 'className=link|innerHTML='+(_name ? _name : 'link '+_id));
		if(_noatt)
			return _item['table'];
		else
			_separator= this.addElement('div', _attachParent, 0, 'className=item_spacer');
	}


	// BUILDS LOGIN ==================
	this.buildLogin = function(section) {
		_self = this;
		_form = this.addElement('form', this.sections[section]['body'], 0, 'name=login_form|method=post');
		if(this.config['loginUserName']=='') {
			_table = this.addElement('table', _form, 0, 'className=item|title=log-in section');
			_tbody = this.addElement('tbody', _table);
			if(this.config['loginErr'] != '') {
				_tr = this.addElement('tr', _tbody);
				_td = this.addElement('td', _tr, 0, 'className=err|innerHTML='+this.config['loginErr']);
			}
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr, 0, 'innerHTML=User');
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr, 0, 'align=center');
			_input = this.addElement('input', _td, 1, 'name=login_user|id=login_user|type=text');
//			_input.style.setProperty("-moz-user-select","normal","");
//			_input.style.setProperty("-moz-user-input","enabled","");
			_tr = this.addElement('tr', _tbody);

			_td = this.addElement('td', _tr, 0, 'innerHTML=Pass');
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr, 0, 'align=center');
			_input = this.addElement('input', _td, 1, 'name=login_pass|id=login_pass|type=password');
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr);
			_input = this.addElement('input', _td, 1, 'name=login_remember|id=login_remember|type=checkbox|value=remember');
			_input.style.width = '20px';
			_td.innerHTML += ' remember me';
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr, 0, 'align=center');
			_input = this.addElement('input', _td, 1, 'name=login_go|type=button|value=Log In');
			_input.onclick = function(ev) {
										var b = new Array('login_user','login_pass');
										for(var i=0;i<b.length;i++) {
											var c = '';
											c = eval('_form.'+b[i]+'.value');
											if(c == '' || c == 'fill this' || c == '--') {
												eval("_form."+b[i]+".value = 'fill this'");
												eval("_form."+b[i]+".select()");
												return false;
											}
										}
										if(_form.login_remember.checked==true)
											_self.login_save(_form);
										_form.submit();
									};
			_spacer = this.addElement('div', _form, 0, 'className=item_spacer');
	
			// link "forgot password"
			_item = this.buildItem(
									'login_forgot',
									'forgot password',
									'Log In',
									'request password if you forgot it',
									function(ev) {
										var email = window.prompt('Enter Your e-mail addres to receive new password.','');
										if(email==null || email=='')
											return false;
										_form.login_email.value = email;
										_form.submit();
									},
									'', // img
									'Forgot your password? Click here and enter your already registered e-mail address. Check it to see your new password.',
									'noAttach');
			_form.appendChild(_item);
	
			this.login_read(_form);
			_spacer = this.addElement('div', this.sections[section]['body'], 0, 'className=item_spacer');
		}
		else {
			// link "change password"
			_item = this.buildItem(
									'login_change',
									'change password',
									'Log In',
									'change your user password',
									function(ev) {
										pass1 = window.prompt('Enter new password.','');
										if(pass1==null || pass1=='')
											return false;
										pass2 = window.prompt('Re enter new password.','');
										if(pass2==null || pass2=='')
											return false;
										if(pass1 != pass2)
											return false;
										_form.login_new_pass.value = pass2;
										_form.submit();
									},
									'', // img
									'Click here to change your current password.',
									'noAttach');
			_form.appendChild(_item);
			_separator= this.addElement('div', _form, 0, 'className=item_spacer');
	
			// log-out
			_table = this.addElement('table', _form, 0, 'className=item|title=log-out section');
			_tbody = this.addElement('tbody', _table);
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr, 0, 'innerHTML=<strong>'+this.config['loginUserName']+'</strong>');
			_tr = this.addElement('tr', _tbody);
			_td = this.addElement('td', _tr, 0, 'align=center');
			_input = this.addElement('input', _td, 1, 'name=login_out|type=submit|value=Log Out');
		}
		_input = this.addElement('input', _form, 0, 'name=login_email|id=login_email|type=hidden');
		_input = this.addElement('input', _form, 0, 'name=login_new_pass|id=login_new_pass|type=hidden');
	}

	// SAVE LOGIN IN COOKIES ==================
	this.login_save = function(form) {
		var ckyDate = new Date;
		ckyDate.setDate(ckyDate.getDate( ) + 60);
		_name = (form.login_user.value);
		document.cookie = (this.config['cookieName']+'=' + escape(_name) + ';expires=' + ckyDate.toGMTString( ) + ';');
	}

	// READ LOGIN FROM COOKIES ==================
	this.login_read = function(form) {

		var aCookies = document.cookie.split("; ");
		for (var i=0;i<aCookies.length;i++) {
			var aOneCookie = aCookies[i].split('=');
			if (aOneCookie[0] == this.config['cookieName']) {form.login_user.value = unescape(aOneCookie[1]);}
		}
	}


	// SETS HELP CONTENT TO content ==================
	this.setHelp = function(content) {
		this.sections['Help']['help_container'].innerHTML = content;
	}

	// RETURNS HELP CONTENT TO DEFAULT ==================
	this.reSetHelp = function() {
		this.sections['Help']['help_container'].innerHTML = this.currentHelp;
	}

	// ON MOUSE OVER SOME ELEMENT ==================
	this.mOver = function(target) {
		target.className = target.className.replace(/(\S+)/g,'$1 $1-over');
	}

	// ON MOUSE OUT FROM LINK ==================
	this.mOut = function(target) {
		target.className = target.className.replace(/(\S+) .+/g, "$1");
	}

	// ON MOUSE CLICK ON LINK ==================
	this.mClick = function(target, linkTarget) {
		if(typeof(linkTarget)!='string' && typeof(linkTarget)!='number'){
			linkTarget();
			return;
		}
		var _link = linkTarget.replace(/<blank>/g, '');
		if(_link == linkTarget)
			window.location.href = '?mod='+_link;
		else {
			window.open(_link, 'newWindow');
		}
	}

	// CREATES HTML ELEMENT ==================
	this.addElement = function(type,parent,nouns,parms){
		var _element=null;
		if(document.createElementNS)
			_element=document.createElementNS("http://www.w3.org/1999/xhtml",type);
		else
			_element=document.createElement(type);
		if(parms!=undefined) {
			var _parms = this.string2Par(parms);
			for(var i in _parms) {
				eval('_element.'+i+' = "'+_parms[i]+'"');
			}
		}
		if(!nouns){
			if(is_ie)
				_element.unselectable="on";
			else if(is_gecko)
				_element.style.setProperty("-moz-user-select","none","");
		}
		if(parent)
			parent.appendChild(_element);
		return _element;
	}

	// SPLITS STRING INTO PARAMETERS ==================
	this.string2Par = function(stringParameters) {
		var _params = stringParameters.split('|');
		var _chunks = new Array();
		var params = new Array();
		for(var i in _params) {
			_chunks[i] = _params[i].split('=');
			params[_chunks[i][0]] = _chunks[i][1];
		}
		return params;
	}

	// STARTS ANIMATON
	this.animationToggle = function(target){
		var to = 1;
		var from = 1;
		if(this.sections[target]['container']._state == 'opened') {
			this.sections[target]['container']._initHeight = this.sections[target]['container'].offsetHeight
			from = this.sections[target]['container']._initHeight;
			this.sections[target]['container']._state = 'closed';
			this.sections[target]['title_pointer'].innerHTML = this.config['closePointer'];
		}
		else {
			to = this.sections[target]['container']._initHeight;
			this.sections[target]['container']._state = 'opened';
			this.sections[target]['title_pointer'].innerHTML = this.config['openPointer'];
		}
		this.sections[target]['container'].style.display = '';
		var animObj = new Accelimation(
													this.sections[target]['container'].style,
													'height',
													to,
													from,
													this.config['animateSpeed'],
													this.config['animateEase'],
													'px'
												);
		animObj._coller = this;
		animObj.onend = this.animationStop;
		animObj.start();
	}

	this.animationStop = function(_self){
		for(var i=0 in _self.sections) {
			if(_self.sections[i]['container']._state == 'closed')
				_self.sections[i]['container'].style.display = 'none';
			else {
				if(i == 'Help')
					_self.sections[i]['container'].style.height = 'auto';
				else
					_self.sections[i]['container'].style.height = _self.sections[i]['container']._initHeight;
			}
		}
	}
}


//========[ ACCELIMATION ]==============
function Accelimation(obj, prop, to, from, time, zip, unit) {
	if (typeof zip  == "undefined") zip  = 0;
	if (typeof unit == "undefined") unit = "px";

	if (zip > 2 || zip <= 0)
		throw new Error("Illegal value for zip. Must be less than or equal to 2 and greater than 0.");

	this.obj  = obj;
	this.prop = prop;
	this.x1   = to;
	this.x0   = from
	this.dt   = time;
	this.zip  = zip;
	this.unit = unit;
//	this.x0		= parseInt(this.obj[this.prop]);
	this.D		= this.x1 - this.x0;
	this.A		= this.D / Math.abs(Math.pow(time, this.zip));
	this.id		= Accelimation.instances.length;
	this.onend	= null;
	this._coller= null;
}
Accelimation.prototype.start = function() {
	this.t0 = new Date().getTime();
	this.t1 = this.t0 + this.dt;
	var dx	= this.x1 - this.x0;
	Accelimation._add(this);
}
Accelimation.prototype.stop = function() {
	Accelimation._remove(this);
}
Accelimation.prototype._paint = function(time) {
	if (time < this.t1) {
		var elapsed = time - this.t0;
		this.obj[this.prop] = Math.abs(Math.pow(elapsed, this.zip)) * this.A + this.x0 + this.unit;
	}
	else this._end();
}
Accelimation.prototype._end = function() {
	Accelimation._remove(this);
	this.obj[this.prop] = this.x1 + this.unit;
	this.onend(this._coller);
}
Accelimation._add = function(o) {
	var index = this.instances.length;
	this.instances[index] = o;
	if (this.instances.length == 1) {
		this.timerID = window.setInterval("Accelimation._paintAll()", this.targetRes);
	}
}
Accelimation._remove = function(o) {
	for (var i = 0; i < this.instances.length; i++) {
		if (o == this.instances[i]) {
			this.instances = this.instances.slice(0,i).concat( this.instances.slice(i+1) );
			break;
		}
	}
	if (this.instances.length == 0) {
		window.clearInterval(this.timerID);
		this.timerID = null;
	}
}
Accelimation._paintAll = function() {
	var now = new Date().getTime();
	for (var i = 0; i < this.instances.length; i++) {
		this.instances[i]._paint(Math.max(now, this.instances[i].t0));
	}
}
Accelimation.instances = [];
Accelimation.targetRes = 10;
Accelimation.timerID = null;

//========[ DOM EVENTS ]==============
var __DomEvents__ = new function() {
   var registry = {};
   function registryKey(id, type, fn) {
      return id + "#" + type + "#" + fn;
   }
   function isInRegistry(key) {
      return registry[key] != null;
   }
   function invoke(key, evt) {
      if(!isInRegistry(key))
         return null;
      _evt = __DomEvents__.alterEventObject(evt);
      if(typeof _evt == "object")
         evt = _evt;
      
      var handler = registry[key];
      var scope = handler.scope;
      scope.__DomEvents_listener__ = handler.listener;
      scope.__DomEvents_listener__(evt);
      scope.__DomEvents_listener__ = null;
   }
   var targetIdCount = 0;
   function targetId(target) {
      if(target == document)
         return "__DomEvents_ID_document";
      if(target == window)
         return "__DomEvents_ID_window";
      
      var id = target.getAttribute("id") || target.uniqueID;
      
      if(id == null){
         id = "__DomEvents_ID_" + targetIdCount++;
         target.setAttribute("id", id);
      }
      
      return id;
   }
   window.addEvent = function(target, type, listener, scope)  {
      var key = registryKey(targetId(target), type, listener);
      scope = scope || target;
      if(isInRegistry(key))
         return false;
      handler = {
         listener:   listener,
         scope:      scope,
         invoker:    function(evt)
                     {
                        invoke(key, evt);
                     }
      }
      
      registry[key] = handler;
      
      if(target.addEventListener){
         target.addEventListener(type, handler.invoker, false);
      } else if(target.attachEvent){
         target.attachEvent("on" + type, handler.invoker);
      } else {
         return false;
      }
      
      // Reset variables:
      target = listener = scope = null;
      
      return true;
   }
   window.removeEvent = function(target, type, listener, scope) {
      var key = registryKey(targetId(target), type, listener);
      
      if(!isInRegistry(key))
         return false;
         
      var invoker = registry[key].invoker;
      
      registry[key] = null;

      if(target.removeEventListener){
         target.removeEventListener(type, invoker, false);
      } else if(target.detachEvent) {
         target.detachEvent("on" + type, invoker);
      } else {
         return false;
      }
      
      return true;
   }
   this.alterEventObject = function(){};
}
