
var Kajax = new Class({
  Extends: Request, 
  options: { secure:false },
	initialize: function(aoptions) { 
	  this.parent(aoptions);
    this.jsonResponse = null;
    this.addEvent('onSuccess', this.onComplete, true);
		this.setHeader('X-Request', 'JSON');	
		this.setHeader('Content-Type', 'application/jsonrequest');
		this.setHeader('Content-Encoding', this.options.encoding); 
		this.setHeader('Accept', 'application/jsonrequest, application/json');
	},

	send: function(obj) {
		return this.parent(JSON.encode(obj));
	},
	
	rpc: function(name, aparams, rpid) {
	if (this.options.link='cancel') this.cancel();
    var jsonRPC = { method: name,params: aparams,id: rpid, module: this.options.module };
    this.send(jsonRPC);
  },  

  processHTML: function(text){
		var container = new Element('div');
		
		return $try(function(){
			var root = '<root>' + text + '</root>', doc;
			
			if (Browser.Engine.trident){
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = false;
				doc.loadXML(root);
			} else {
				doc = new DOMParser().parseFromString(root, 'text/xml');
			}
			root = doc.getElementsByTagName('root')[0];
			for (var i = 0, k = root.childNodes.length; i < k; i++){
				var child = Element.clone(root.childNodes[i], true, true);
				if (child) container.grab(child);
			}
			return container;
		})() || container.set('html', text);
	},

 
  processAS: function(args) {	
    var elems = $$(args[1]);
    for (var i = 0, l = elems.length; i < l; i++) { 
      elems[i].empty();
      elems[i].set('html', args[2]);
    }
  },
  
  processVL: function(args) {
    $each($$(args[1]), function(el) { el.value = args[2]; });
  },
  
  processAP: function(args) {
    $each($$(args[1]), function(el) { el.set('html', el.innerHTML.concat(args[2])); });
  },
  
  processPP: function(args) {
    $each($$(args[1]), function(el) { el.set('html', args[2].concat(el.innerHTML)); });
  },
  
  processAC: function(args) {
    $$(args[1]).addClass(args[2]);
  },
  
  processRC: function(args) {
    $$(args[1]).removeClass(args[2]);
  },
  
  runScript: function(scripts) {
    (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);
  },  
  
  processSC: function(args) {
    this.runScript(args[1]); 
  },  
  
  processAL: function(args) {
    alert(args[1]);
  },
  
  processRD: function(args) {
    window.location = args[1];
  },
  
  processHH: function(args) {
    //globalScroller.scrollTowards(args[1]);  
    window.location.hash = args[1];
  },      

  processInstructions: function() {
    if ($defined(this.jsonResponse) && $defined(this.jsonResponse.code))
      if ( ['array', 'object', 'collection'].contains($type(this.jsonResponse.code)) ) {
      	$each(this.jsonResponse.code, function(value){
		      if ($type(value)=='array') {
            switch (value[0]) {
              case 'AS':
                if (value.length > 3)
                  this.processAS.delay(value[3], this, [value]);
                else
                  this.processAS(value);
                     
                break;
                
              case 'VL':
                if (value.length > 3)
                  this.processVL.delay(value[3], this, [value]);
                else
                  this.processVL(value);
                     
                break;

              case 'AP':
                if (value.length > 3)
                  this.processAP.delay(value[3], this, [value]);
                else
                  this.processAP(value);
                     
                break;
                
              case 'PP':
                if (value.length > 3)
                  this.processPP.delay(value[3], this, [value]);
                else
                  this.processPP(value);
                     
                break;   
                
              case 'AC':
                if (value.length > 3)
                  this.processAC.delay(value[3], this, [value]);
                else
                  this.processAC(value);
                     
                break;    
                
              case 'RC':
                if (value.length > 3)
                  this.processRC.delay(value[3], this, [value]);
                else
                  this.processRC(value);
                     
                break;   
                
              case 'SC':
                if (value.length > 2)
                  this.processSC.delay(value[2], this, [value]);
                else
                  this.processSC(value);
                     
                break;  
                                                 
              case 'AL':
                if (value.length > 2)
                  this.processAL.delay(value[2], this, [value]);
                else
                  this.processAL(value);
                     
                break;  

              case 'RD':
                if (value.length > 2)
                  this.processRD.delay(value[2], this, [value]);
                else
                  this.processRD(value);
                     
                break;
                
              case 'HH':
                if (value.length > 2)
                  this.processHH.delay(value[2], this, [value]);
                else
                  this.processHH(value);
                     
                break;  
                      
              
            }
          }
	      }, this); 
      }
  },
  
  processCallIdentification: function() {
    this.latestRPID = null;
    if ($defined(this.jsonResponse))
      if ($defined(this.jsonResponse.id))
        this.latestRPID = this.jsonResponse.id;
  },
  onSuccess: function(){
    this.fireEvent('onSuccess', arguments).callChain();
	},
  
	onComplete: function(){
		this.jsonResponse = null;
		
    this.jsonResponse = JSON.decode(this.response.text, this.options.secure);
		
    var problem = false;
		try {
      this.result = this.jsonResponse.result || null;
		  
		  if ($defined(this.jsonResponse.error)) 
		    throw true;
		  else
		    this.error = null;
		  
		  this.processCallIdentification()
      this.processInstructions();
    }
    catch(e) {
      alert(e);
		  problem = true;
	  } 
	  
	  
    	  
	  if (problem) {
      this.fireEvent('onFailure', [this, problem]);
	  }
	  else                                
	    this.fireEvent('onComplete', [this, problem]);
    
	},
	
	onFailure: function(){      
    this.latestRPID = null;
    this.result = null;
    this.error = null;
	  this.jsonResponse = null;
	  
	  this.fireEvent('onFailure', [this, true]);
	}

});

var tinyMCE = null;
var disableEffects = $empty;
var enableEffects = $empty;
var commonCompleteHandler = $empty;
var global_xindi_elem = null;
var xindi = $empty();
var ResScripts = {};

var changeHash = function(newhash) {
	var tempid, el = $(newhash);
	if (el) { tempid = el.get('id'); el.set('id', 'hashtemporary_id'); }
	window.location.hash = '#' + newhash;
	if (el) { el.set('id', tempid); }
}

String.implement({LToC: function() { return this.replace(',', '.').replace(/[^\d\.]/g, ''); } } );
var submitListFilterForm = function(form, mainid, suffix) {
  if (validateForm(form))
  {
    bform = $(mainid+suffix+"bindingform");
    
    $tfn(xindi,this,[mainid+suffix+"searchform",-24,0,0]);
    $rpc(mainid+":filter", [form.filter.value, serializeForm(bform)], null);   
  }
}

var submitBindingForm = function(form, mainid, suffix) {
  if (validateForm(form))
  {
    $tfn(xindi,this,[mainid+suffix+"bindingform",-24,0,0]);
    $rpc(mainid+":saveBinding", serializeForm(form), null);   
  }
}
        
function $tfn(fn, bind, args){
	try {
		return fn.apply(bind, $splat(args));
	} catch(e){
		return false;
	}
};

var FormatNumberSK = function(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	
	var rgx = /(\d+)(\d{3})/;
	if (window.wmslang == 'en')
	{
		x2 = x.length > 1 ? '.' + x[1] : '.00';
		while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	else
	{
		x2 = x.length > 1 ? ',' + x[1] : ',00';
		while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}	
	
	return x1 + x2;
}

var currencyControl = {
	formatEUR: function(x)
	{
		return FormatNumberSK(x) + ' &euro;';
	},
	
	formatSKK: function(x)
	{
		return FormatNumberSK(x) + ' Sk';
	},
	
	updateTitle: function(el)
	{
		el.title = currencyControl.formatSKK( (el.get('html').LToC() * 30.1260).toFixed(2));
	},
	
	augment: function()
	{
		var kurz = 30.1260;
		var currencyFields = $$('.currencyfield');
		var len = currencyFields.length;
		for(var i=0;i<len;i++)
		{
			currencyFields[i].title = currencyControl.formatSKK( (currencyFields[i].get('html').LToC() * kurz).toFixed(2));  
		}
	}
}
var findClosest = function(beginat, tagname) {
  var ul = beginat;
  
  while ($defined(ul) && ((ul.tagName && ul.tagName.toLowerCase() != tagname) || (!ul.tagName))) 
    ul = ul.parentNode;
      
  if ($defined(ul) && ul.tagName && (ul.tagName.toLowerCase()  == tagname)) 
    return ul;
  else
    return null;
}

var findParentMatch = function(beginat, selector) {
  var ul = $(beginat);
  
  while ($defined(ul) && !ul.match(selector)) 
    ul = $(ul.parentNode);
      
  if ($defined(ul)) 
    return ul;
  else
    return null;
}


var submitForm = function(el) {
  var form = findClosest(el, "form");
  if (form.onsubmit)
    form.onsubmit.apply(form);
  else
    form.submit.apply(form);
    
  return false;
}

var stdSubmitForm = function(form, rpcfnc) {
  form = $(form);
  if (validateForm(form)) {
    $tfn(xindi,this,[form,-20,0,0]);
    $rpc(rpcfnc, serializeForm(form), null);  
  }
}

var unvalSubmitForm = function(form, rpcfnc) {
  form = $(form);
  $tfn(xindi,this,[form,-20,0,0]);
  $rpc(rpcfnc, serializeForm(form), null);  
}


var stdCallProc = function(xpost, rpcfnc, args) {
  $tfn(xindi,this,[$(xpost),-20,0,0]);
  $rpc(rpcfnc, args, null);  
  return false;
}


var carGoTo = function(carplace, pageidx) {
  var cp = $(carplace);
  var wrapper = cp.getElement(".wrapper");
  var pages = cp.getElements(".carpage");
  if (pages.length <= pageidx) return;
  
  var page = pages[pageidx];
  var x = page.offsetLeft;
  //alert(x);
  wrapper.tween("margin-left", -x);
}

var onlyNumbers = function(event) {
  var event = new Event(event);
 
  if (event.key.length > 1 || event.control || event.alt || event.meta)
    return true;
    
  numcheck = /\d/;
  return numcheck.test(event.key);
}

var onlyDateChars = function(event) {
  var event = new Event(event);
 
  if (event.key.length > 1 || event.control || event.alt || event.meta)
    return true;
    
  // numcheck = /[\d\.]/;
  // return numcheck.test(event.key);
  return (event.code <= 31 || (event.code >= 48 && event.code <= 57))
}


var onlyPswChars = function(event) {
  var event = new Event(event);
 
  if (event.key.length > 1 || event.control || event.alt || event.meta)
    return true;
    
  numcheck = /\S/;
  return numcheck.test(event.key);
}

var validateDate = function(mm, dd, yyyy) {
  var dayobj = new Date(yyyy, mm-1, dd);
  
  if ((dayobj.getMonth()+1!=mm)||(dayobj.getDate()!=dd)||(dayobj.getFullYear()!=yyyy)) {
      alert("The date format is incorrect.");
      return false;
  }
  
  return true;
}
var xindiFunction = function(evt) {
  if (!$defined(this)) return;
    
  if (['string', 'element'].contains($type(evt)))
    var elem = $(evt);
  else {
    evt = evt || window.event;
    var elem = evt.target || evt.srcElement; 
  }
  
  if ((elem.nodeType) && (elem.nodeType == 3)) 
    elem = $(elem.parentNode);
  
  if (elem) {
    var relx = arguments.length > 1 ? arguments[1] : 16;
    var rely = arguments.length > 2 ? arguments[2] : 0;
    var ori = arguments.length > 3 ? arguments[3] : 0;
    
    var posit = elem.getPosition();
    posit.x += relx;
    posit.y += rely;
    
    this.setStyles({opacity: 0, display: 'block'});
    
    switch (ori) {
      case false:
      case 0: posit.x += elem.offsetWidth; break;
      case 1: posit.x -= this.offsetWidth; break;
      case 2: posit.y += elem.offsetHeight; break;
      case 3: posit.y -= this.offsetHeight; break;
      case 4: posit.x += ( (elem.scrollWidth-this.offsetWidth) / 2); break;
      default:;
    }
    
    this.setStyles({left: posit.x, top: posit.y});
    this.fade('in');
   }

  return true;
}

var augmentForm = function(form, c) {
  form = $(form);
  if (form.retrieve('augmented', false) && !c)
    return;
  
  var blurHandler = function(evt, input) {
     if (input.value == "") {
       input.addClass("editDefault");
       if (input.hasClass('psw')) input.type = "text";
       input.value = input.retrieve('defaultValue');
     }
  }
  
  var writeHandler = function(evt, input) {
    if (input.hasClass("editDefault")) {
      input.removeEvents("keypress");
      focusHandler(evt, input);
    }
  }
  
  var focusHandler = function(evt, input) {
    if (input.value == input.retrieve('defaultValue')) {
      input.value = "";
      if (input.hasClass('psw')) input.type = "password";
      input.removeClass("editDefault");
    }
  }
  
  form.addEvent('reset', 
    function() { 
      var inputs = form.getElements('input[type=text]');
      
      $each(inputs, function(input) {
        input.value = input.retrieve('defaultValue');
      });
    });
    
  $each(form.getElements('input[type=text]'), function(input) {
    if ($defined(input.retrieve('defaultValue')))
      return;
      
    input.store('defaultValue', input.value);
    
    input.addEvent('blur', blurHandler.bindWithEvent(this, input));
    if (Browser.Engine.trident)
      input.addEvent('keypress', writeHandler.bindWithEvent(this, input));
    
    input.addEvent('focus', focusHandler.bindWithEvent(this, input));
    
    
  }, this);
  
  form.store('augmented', true);
  // form.setAttribute("autocomplete", "off");
}

augmentForm.undefaultForm = function(form) {
  var inputs = form.getElements('input[type=text]');
  
  $each(inputs, function(input) {
    if (input.value == input.retrieve('defaultValue')) 
      input.value = "";
  }, this);
}

augmentForm.defaultForm = function(form) {
  var inputs = form.getElements('input[type=text]');
  
  $each(inputs, function(input) {
    if (input.value == "")
      input.value = input.retrieve('defaultValue');
  }, this);
}


var makeTableTrackableClickable = function(id) {
  var mytable = $(id);
  if ($type(mytable) == "element") {
    mytable.addEvent("mouseover", trackTableHightlight);
    mytable.addEvent("mouseout", trackTableHightlight);
    
    $each(mytable.getElements('tr'), function(tr) {
      var tda = tr.getElement('td a');
      if (tda) {
        tr.setStyle('cursor', 'pointer');    
        tr.addEvent('click', tda.onclick);
        tda.getParent().set('html', tda.innerHTML);
      }
    });
  }
}
 
var trackTableHightlight = function(event) {
  event.stop();
  
  var curhltr = $pick(this.currenthighlight, null);
  
  if (curhltr) 
      curhltr.removeClass('highlight');
    
  if (event.type == "mouseover") {
    var tr = $(event.target);
    while (tr && (tr != this) && ((tr.tagName && tr.tagName.toLowerCase() != 'tr') || (!tr.tagName)))
      tr = tr.getParent();
    
    if (tr && tr.tagName && (tr.tagName.toLowerCase() == 'tr')) {
      this.currenthighlight = tr;
          
      tr.addClass('highlight');
    }
    else
      this.currenthighlight = null;
  }
  else
    this.currenthighlight = null;
}
var closeDragWin = function (dw) {
  elem = $(dw);
  if (elem) {    
    elem.visfx = elem.visfx || new Fx.Tween(elem, {property: 'opacity', duration: 400, wait: false});
    elem.visfx.options.onComplete = $empty;
    elem.visfx.start(0)
  }          
}

var showDragWin = function (dw, width, height, pos, evt) {
  elem = $(dw);
  if (elem) {
    width = width ? width : 500;
    height = height ? height : 250; 
    if (pos==1) {
      var atop = (Window.getScrollTop() + ((Window.getHeight()-height)/2));
      var aleft = ((Window.getWidth()-width)/2);
    } else {
      evt = new Event(evt, Document.getWindow());
      var atop = evt.page.y;
      var aleft = evt.page.x;
      if (pos<0) aleft -= width;
      if (pos<=-2) atop -= height;  
    }      
    elem.setStyles( { 'width'  : width, 'height' : height,'top'    : atop,'left'   : aleft,'visibility' : 'visible','display' : 'block','opacity' : '1' }  );
  }
}

var setupDragWins = function () {
  var draggables = $$('div.dragwin');
  
  draggables.each(function(el) {
    var ar = el.getElements('.handle');
    if (ar && ar.length) el.makeDraggable({handle: ar[0]});
    ar=el.getElements('.resize');
    if (ar && ar.length) el.makeResizable({handle: ar[0]});
  });
}

var resizeHandler = function() {
  // vsetky veci co potrebuju menit velkost podla velkosti okna
  
  var o = $('globalOverlay');
  
  if ($defined(o)) {                                       
    var site = $('site');             
    if ($defined(document.body) && $defined(site)) {
      w = Math.max(Window.getScrollWidth(), document.body.scrollWidth, document.body.scrollWidth, site.scrollWidth);
      // h = Math.max(Window.getScrollHeight(), document.body.scrollHeight, site.scrollHeight);
      t = 0;
      l = 0;
    }
    else { 
      w = Window.getScrollWidth();
      // h = Window.getScrollHeight();
      t = Window.getScrollTop();
      l = Window.getScrollLeft(); 
    }
    
    o.setStyles({'top': t, 'left': l, 'width': w, 'height': Window.getScrollHeight()});
  }
}
                             
var globalBlock = function() {
  var o = $('globalOverlay');
  if (o) {
    resizeHandler();
    o.fx = o.fx || new Fx.Tween(o, {property: 'opacity', duration: 300})
    o.setStyle('opacity', '0');
    o.fx.start(0.9);
    
    o.setStyles({'display': 'block'});
  }
}

var globalUnblock = function() {
  var o = $('globalOverlay');
  if (o) {
    o.fx = o.fx || new Fx.Tween(o, {property: 'opacity', duration: 300})
    o.fx.start(0);
    
    (function() { o.setStyle('display', 'none') }).delay(270);
    
  }
}

function hackSH(el) {
  el = $(el);
  
  if (Browser.Engine.trident4) 
    return el.scrollHeight;
    
  var x=el.offsetHeight; 
  el.style.height='auto'; 

  var sH=el.scrollHeight; 
  el.style.height=x+'px';
  
  return sH;
}

var reenableForms = function(form)
{
  updateForm(form, false);
}

var completeHandler = function(kajax, problem) {
  if ($defined(global_xindi_elem))
    global_xindi_elem.fade('out');
    
  if (disabledForms.length)
  {
    disabledForms.forEach(reenableForms, window);
    disabledForms.clean();
  }
    
  if (problem) 
    alert('Server communication error! [js-cmn-ch]');
  else { 
  	currencyControl.augment();
  }
}     
var disabledForms = new Array();
var updateForm = function(form, disabled) {
  if (!form) return form;
  form = $(form);
  if (!form) return form;
  
  var toclear = updateForm.arguments.length > 2 && updateForm.arguments[2];
  var buttontext = updateForm.arguments.length > 3 && updateForm.arguments[3];
  if (disabled && updateForm.arguments.length > 4 && updateForm.arguments[4])
  {
    disabledForms.include(form.get("id"));
  }
  
  $(form).getElements('input, textarea, select, button, .formsubmitbutton').each(function(el) {
	  el = $(el);
    el.prevDisabled = $pick(el.prevDisabled, el.disabled);
	  el.disabled = el.prevDisabled || disabled;
	  
	  var tag = el.get('tag').toLowerCase();
	  if (tag =='input') {
	    if (el.type=='submit') {
        el.value = buttontext || (disabled ? 'počkajte...' : 'Poslať');
        el.setAttribute("autocomplete", "off");
        form.setAttribute("autocomplete", "off");
      }
      else if (toclear && el.type=='text')
        el.value = el.retrieve('defaultValue') || '';
    } 
    else if (toclear && tag=='textarea') {
      el.value = '';
    }
    else if (tag == 'button' && el.type=="submit")
    {
      el.setAttribute("autocomplete", "off");
      form.setAttribute("autocomplete", "off");
      if (disabled)
        el.store("oldvalue", el.get("html")).set("html", buttontext || 'počkajte...');
      else
        el.set("html", buttontext || el.retrieve("oldvalue", "Pokračovať"));
    }
    else if (tag == "a" && el.hasClass('formsubmitbutton'))
    {
      var span=el.getElement('span');      
      if (disabled)
      {
        el.store("oldvalue", span.get("html"));
        span.set("html", buttontext || 'počkajte...');
        el.addClass('isdisabled');
      }
      else
      {
      	span.set("html", buttontext || el.retrieve("oldvalue", "Pokračovať"));
      	el.removeClass('isdisabled');      	
      }
      form.setAttribute("autocomplete", "off");
    }
    
	});
	
	return form; 
}

var showFor = function(elem, time) {  
  elem = $(elem);
  if (elem)
  {
	  elem.setStyles({'opacity': 0, 'display': 'block'});
	  elem.fade('in', {duration:300});
	  (function() { elem.fade('out').get('tween').chain(elem.setStyle.pass(['display', 'none'], elem)); }).delay(time);
  }  
}

var serializeForm = function(form) {
  var obj = {};
  if (!form) return false;
  
	$(form).getElements('input, textarea, select').each(function(el){
		var name = el.name;        
    
    if (!name || el.disabled) return;                    
		
		if (name.substr(1,3) != "mce") {
		  var tag = el.tagName.toLowerCase();       
		  
      if ( (!el.disabled) && (tag == 'textarea') && (el.hasClass('wysiwyg')) && $defined(tinyMCE) ) {
        var editor = tinyMCE.getInstanceById(name);
        
        if ($defined(editor) && ($defined(editor.save))) {
          editor.save(obj);
        }
      }
      var value = null;
      
      if (tag == 'select') {  
        value = Element.getSelected(el).map(function(opt) { return opt.value; });
        if (!el.multiple && value && $type(value) == 'array' && value.length > 0)
          value = value[0]; 
      }
      else  
        value = ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
        	  	
  		if (value === null) return;
  		
  		if ((tag == 'input') && (name.substr(name.length-2, 2) == '[]')) {
        if (obj[name])
          obj[name].push(value);
        else
          obj[name] = new Array(value);
      } else {
        obj[name] = value;
      }
    }
	});
	
	return obj; 
}

customOrder = function(objname, ob) {
  $rpc(objname+':orderby', ob, null);
  return false;
}

var focusInput = function(elem) {
  if ($defined(elem))
    try {
      elem.focus();
      elem.select();
    
    } catch (e) {}
}

var rpcx = new Kajax(window.kjxoptions);             
var rpcxc = new Kajax(window.kjxoptions);
var rpcxs = new Kajax(window.kjxoptions);
rpcxs.options.url = String(window.kjxoptions.url).replace('http://', 'https://');
rpcxc.options.link = 'cancel'; 

rpcx.addEvent('onComplete', completeHandler);
rpcx.addEvent('onFailure', completeHandler);
rpcxc.addEvent('onComplete', completeHandler);

var $rpc = rpcx.rpc.bind(rpcx);
var $rpcc = rpcxc.rpc.bind(rpcxc);
var $rpcs = rpcxs.rpc.bind(rpcxs);

var DOMReadyHandler = function() { 
  global_xindi_elem = $("xindi");
  global_xindi_elem.set("tween", {duration: 200});

  xindi = xindiFunction.bind(global_xindi_elem);
  
  var site = $('site');
  if ($defined(site)) 
    site.addEvent('resize', resizeHandler);    
    
  currencyControl.augment();
}

window.addEvent('domready', DOMReadyHandler);
window.addEvent('resize', resizeHandler);


if (Browser.Engine.presto)
  Native.implement([Window, Document], { 
    getSize: function(){ return {x: window.innerWidth, y: window.innerHeight}; }  
  });




var savebtn = function(myuid, btn, back, supressValidate) {
  var form = $(myuid+'form');
  if (supressValidate || validateForm(form)) {
    $tfn(xindi,this,[myuid+'save'+btn,-20]);
    var obj = serializeForm(form);
    var pswfields = form.getElements("input[type=password]");
    if (pswfields.length > 0)
    {
      var key = form.getElement("input.keyfield").value.toLowerCase().trim();
      var origfield = form.getElement("input.origkey");
      
      var origkey = $defined(origfield) ? origfield.value.toLowerCase().trim() : false;
      
      for(var i=0; i<pswfields.length; i++) 
      {        
        var pswf = pswfields[i];
        
        if (obj[pswf.name].trim() != "")
        	obj[pswf.name] = hex_hmac_sha1(pswf.hasClass("useorigkey") ? origkey : key, obj[pswf.name]);
        else
        	obj[pswf.name] = "";
      }
    }
    
    $rpc(myuid+':save',[obj, back],null);
  }
  return false;
}

var togglebtn = function(myuid, tab) {
  var form = $(myuid+'form');
  var obj = {};
  
  if (form)
  {
    if (!validateForm(form)) return false;
       
    obj = serializeForm(form);
    var pswfields = form.getElements("input[type=password]");
    if (pswfields.length > 0)
    {
      var key = form.getElement("input.keyfield").value.toLowerCase().trim();
      var origfield = form.getElement("input.origkey");
      
      var origkey = $defined(origfield) ? origfield.value.toLowerCase().trim() : false;
      
      for(var i=0; i<pswfields.length; i++) 
      {
        var pswf = pswfields[i];
        if (obj[pswf.name].trim() != "")
        	obj[pswf.name] = hex_hmac_sha1(pswf.hasClass("useorigkey") ? origkey : key, obj[pswf.name]);
        else
        	obj[pswf.name] = "";
      }
    }  
  }
  
  $tfn(xindi,this,[myuid+'tabs',-20]); 
  $rpc(myuid+':tabToggle',[obj, tab],null);

  return false;
}

function makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse){
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	if (!steps)
	{
		scrollbar.setStyle('display', 'none');
	}
	else
		scrollbar.setStyle('display', 'block');
		
	var slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			// Scrolls the content element in x or y direction.
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	}).set(0);
	if( !(ignoreMouse) ){
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	}
	// Stops the handle dragging process when the mouse leaves the document body.
	$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}

Element.implement({
  customClone: function(contents, oldsuf, newsuf){
		switch ($type(this)){
			case 'element':
				var attributes = {};
				for (var j = 0, l = this.attributes.length; j < l; j++){
					var attribute = this.attributes[j], key = attribute.nodeName.toLowerCase();
					if (Browser.Engine.trident && (/input/i).test(this.tagName) && (/width|height/).test(key)) continue;
					var value = (key == 'style' && this.style) ? this.style.cssText : attribute.nodeValue;
					if (!$chk(value) || key == 'uid') continue;					
					if (value != 'inherit' && ['string', 'number'].contains($type(value))) 
          {
            if (key == 'id' || key == 'name' || key=='class')
            {
              attributes[key] = value.replace(oldsuf, newsuf);
            }
            else 
              attributes[key] = value;
          }
				}
				var tagname = this.nodeName.toLowerCase();
				var element = new Element(tagname, attributes);
				if (tagname == 'input' && element.hasClass("dateinput"))
				{
				  var oldcal = this.retrieve('calendar-obj');
				  if (oldcal)
				  {
				  
            new vlaDatePicker(element, { filePath: oldcal.filePath , prefillDate: oldcal.prefillDate, format: oldcal.format , separator: oldcal.separator});
          }
        }
				if (contents !== false){
					for (var i = 0, k = this.childNodes.length; i < k; i++){
						var child = Element.customClone(this.childNodes[i], true, oldsuf, newsuf);
						if (child) element.grab(child);
					}
				}
				return element;
			case 'textnode': return document.newTextNode(this.nodeValue);
		}
		return null;
	}

});

var cloneBlockRegroup = function(groups)
{
  var original = groups[0];
  var oldsuf = original.className.substr(original.className.lastIndexOf('--'));
  var newsuf = new String("--").concat($time());
  var clone = original.customClone(true, oldsuf, newsuf);
  clone.inject(groups[groups.length-1], 'after');
  var inputs = clone.getElements("input[type=text]");
  
  for(var i=0;i<inputs.length;i++)
  {
    inputs[i].set('value', '');
  }
}

var toggleCatContents = function(checkbox)
{
  var group = findParentMatch(checkbox, '.group');
  var contents = group.getElement('.catcontents');
  if (checkbox.get('checked'))
  {
    contents.removeClass('catoff');
    group.addClass('caton');
  }
  else {
    contents.addClass('catoff');
    group.removeClass('caton');
  }
}

var removeThisRow = function(el)
{
	var row = findClosest(el, 'tr');
	$(row).destroy();
	
	return false;
}

var addDom = function(uid)
{
	var table = $(uid);
	var pattern = table.getElement("tr.pattern");
	
	var newrow = pattern.clone().inject(table, 'bottom');
	newrow.removeClass("pattern");
	
	var serial = $time();
	newrow.getElement('input').set('name', 'domCislo(' + serial + ')');
	newrow.getElement('select').set('name', 'domDostupnost(' + serial + ')');
	
	return false;
}

var addOdpoved = function(uid)
{
	var table = $(uid);
	var pattern = table.getElement("tr.pattern");
	
	var newrow = pattern.clone().inject(table, 'bottom');
	newrow.removeClass("pattern");
	
	var serial = $time();
	newrow.getElement('input[type=hidden]').set('name', 'odpI(' + serial + ')').set('value', -1);
	newrow.getElement('input[type=text]').set('name', 'odpT(' + serial + ')');
	
	return false;
}

var showDomStatus = function(el, domstatus)
{
  el = $(el);
  var readies = el.retrieve('readies');  
  var status = 0;
  var idx = "d"+el.value.toInt().toString();
  if (readies.has(idx)) status = readies[idx];  
  else
  {
    idx = "d"+el.value;
    if (readies.has(idx)) status = readies[idx];    
  }
  
  var domstatuse = $(domstatus);  
  domstatuse.className = "domstatus" + status;
  
  if (status == domstatuse.retrieve("laststatus")) return;
    
  domstatuse.store("laststatus", status);
  
  var res = $(domstatus+'-result');
  
  /*if (status == 0)
    res.getElement('.wrapper').setStyle('height', 0);
  else*/
  {  
    res.getElement('.objednavka').setStyle('display', status == 0 ? 'none' : 'block');
    res.getElements('.ds').setStyle('display', 'none');
    res.getElement('.domstatus' + status).setStyle('display', 'block');
    var w = res.getElement('.wrapper'); 
    var sh = hackSH(w);
    var x = Math.min(-sh+w.getStyle('height').toInt(), 0);
    w.setStyle('margin-top', x);      
    w.morph({'height': sh, 'margin-top': 0});
  }
    
    
}

var clearDomStatus = function(domstatus)
{
  var res = $(domstatus+'-result');
  res.getElement('.wrapper').setStyle('height', 0);

  domstatus = $(domstatus);  
  domstatus.set("class", "");
  domstatus.store("laststatus", -1);  
}


var submitParentForm = function(el)
{
	var form = findClosest(el, 'form');	
	if (form)
	{
		form = $(form);
		if (form.onsubmit) form.onsubmit.run(null, form);		
		else form.submit();
	}
	
	return false;
}

var submitParentForm2 = function(el)
{
	var node = el.get('tag').toLowerCase() == 'a' ? el : findClosest(el, 'a');
	if (node.hasClass('isdisabled')) return false;
	
	var form = findClosest(el, 'form');	
	if (form)
	{
		form = $(form);
		if (form.onsubmit) form.onsubmit.run(null, form);		
		else form.submit.run(null, form);
	}
	
	return false;
}


var DostupnostSelectMesto = function(hsh, pid)
{
	/*var container = $('dostupmesto');
	var select = container.getElement('select');
	if (select)
	{
		var obj = $($(select).getElement('option[value='+pid+']')); 
		obj.set('selected', 1);
	}*/
}

var CmnLgc = {
	MUp: function(event, muid, idx) 
	{
		var event = new Event(event);
		event.stop();
		
		var el = $(event.target);
		if (el)	
		{
			var tr = el.getParent('tr');
			$tfn(xindi,this,[tr,4,0,0]);
		}
		$rpc(muid+':moveup', idx, 0);
		
		return false;	
	},
	
	MDn: function(event, muid, idx) 
	{
		var event = new Event(event);
		event.stop();
		
		var el = $(event.target);
		if (el)	
		{
			var tr = el.getParent('tr');
			$tfn(xindi,this,[tr,4,0,0]);
		}
		$rpc(muid+':movedown', idx, 0);
		
		return false;	
	}				
};




var valstrings_en = {
  notempty: "Please fill in the required field.", 
  number: "Enter only numbers into the field.",
  integer: "Enter only integer numbers into the field.",
  emailaddr: "Verify the email address format.",
  psw: "Passwords must be 6-30 characters in length.",
  phone: "Phone number format is incorrect"
};

var valstrings_sk = {
  notempty: "Položka je povinná. Prosím, vyplňte.", 
  number: "Zadaná hodnota je neplatná. Prosím, zadajte číslo.",
  integer: "Zadaná hodnota je neplatná. Prosím, zadajte celé číslo.",
  emailaddr: "Skontrolujte, prosím, formát emailovej adresy.",
  psw: "Heslo nemá správny formát. Zadajte slovo s dĺžkou 6-30 znakov.",
  phone: "Telefónne číslo nemá správny formát. Prosím, zadajte 10 číslic bez medzier, bodiek, pomlčiek alebo zátvoriek."
};
window.valstrings = valstrings_sk;

function isRadioChecked(elem, errorfunc, valstrings) {
  var numChecked = 0;
  
  for(var idx=0;idx<elem.length;idx++) {
    el = elem[idx]; 
    if (el.checked)
      numChecked++;
  }
  
  if (numChecked != 1) {
	if (errorfunc) errorfunc(elem, 'rc', valstrings.notempty);
    
    return false;
  } else {
    return true;
  }
}

// validates that the field value string has one or more characters in it
function isNotEmpty(elem, errorfunc, valstrings) {
	if (elem.get('tag') == "input" && elem.get('type') == "radio") {
		var name = elem.name; 
		var elems = $(elem.form).getElements('input[type=radio]').filter(function(item) { return item.name==name && item.checked; });
		if (elems.length) 
			return true;
		
		if (errorfunc) errorfunc(elem, 'ne', valstrings.notempty);
        return false;
	}
	else {
		var str = elem.value;		
	    var re = /.+/;
	    if(!str.match(re)) {
	        if (errorfunc) errorfunc(elem, 'ne', valstrings.notempty);
	        return false;
	    } else {
	        return true;
	    }
	}
}

// validates that the field value string has one or more characters in it
function isPsw(elem, errorfunc, valstrings) {
    var str = elem.value;
    var re = /\S+/;
    if(!str.match(re)) {
      if (errorfunc) errorfunc(elem, 'psw', valstrings.notempty);
      return false;
    } 
    
    var len = str.length;
    if (len < 6 || len > 30) {
      if (errorfunc) errorfunc(elem, 'psw', valstrings.psw);
      return false;
    }
    
    return true;
}



function isEmpty(elem) {
    var str = elem.value;
    var re = /.+/;
    return (!str.match(re));
}

   
//validates that the entry is a positive or negative number
function isNumber(elem, errorfunc, valstrings) {
    var str = elem.value;
    var re = /^\d*[\.,]?\d*$/;
    str = str.toString( );
    if (!str.match(re)) {
        if (errorfunc) errorfunc(elem, 'num', valstrings.number);
        return false;
    }
    return true;
}

function isInteger(elem, errorfunc, valstrings) {
    var str = elem.value;
    var re = /^\d*$/;
    str = str.toString( );
    if (!str.match(re)) {
        if (errorfunc) errorfunc(elem, 'int', valstrings.integer);
        return false;
    }
    return true;
}

function isTelefon(elem, errorfunc, valstrings) {
	var str = elem.value;
    var re = /^\d{10}$/;
    str = str.toString( );
    if (!str.match(re)) {
        if (errorfunc) errorfunc(elem, 'phone', valstrings.phone);
        return false;
    }
    return true;
}
   
// validates that the entry is formatted as an email address
function isEMailAddr(elem, errorfunc, valstrings) {
    var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        if (errorfunc) errorfunc(elem, 'email', valstrings.emailaddr);
        return false;
    } else {
        return true;
    }
}

function validateElem(elem, errorfunc, valstrings) {
  elem = $(elem);
  var typ = elem.getAttribute('datatype');
  if (!typ) {
    if (elem.hasClass("donotval"))
      return true;
        
    var bres = true;
        
    if (bres && elem.hasClass('number'))
      bres = bres && isNotEmpty(elem, errorfunc, valstrings) && isNumber(elem, errorfunc, valstrings);
      
    if (bres && elem.hasClass('integer'))
      bres = bres && isNotEmpty(elem, errorfunc, valstrings) && isInteger(elem, errorfunc, valstrings);
    
    if (bres && elem.hasClass('numberempty'))
      bres = bres && (isEmpty(elem) || isNumber(elem, errorfunc, valstrings));
    
    if (bres && elem.hasClass('integerempty'))
      bres = bres && (isEmpty(elem) || isInteger(elem, errorfunc, valstrings));
      
    if (bres && elem.hasClass('email'))
      bres = bres && isEMailAddr(elem, errorfunc, valstrings);
         
    if (bres && elem.hasClass('emailempty'))
      bres = bres && (isEmpty(elem) || isEMailAddr(elem, errorfunc, valstrings)); 

    if (bres && elem.hasClass('psw'))
      bres = bres && isNotEmpty(elem, errorfunc, valstrings) && isPsw(elem, errorfunc, valstrings);      
    
    if (bres && elem.hasClass('pswempty'))
      bres = bres && (isEmpty(elem) || isPsw(elem, errorfunc, valstrings));         
    
    if (bres && elem.hasClass('telefon'))
      bres = bres && isNotEmpty(elem, errorfunc, valstrings) && isTelefon(elem, errorfunc, valstrings);
    
    if (bres && elem.hasClass('notempty'))
      bres = bres && isNotEmpty(elem, errorfunc, valstrings);     
      
    return bres;
  } 
    
  typ = typ.toLowerCase()
  
  if (typ=="number")
    return isNotEmpty(elem, errorfunc, valstrings) && isNumber(elem, errorfunc, valstrings);
  else if (typ=="integer")
    return isNotEmpty(elem, errorfunc, valstrings) && isInteger(elem, errorfunc, valstrings);
  else if (typ=="email")
    return isEMailAddr(elem, errorfunc, valstrings);
  else if (typ=="notempty")
    return isNotEmpty(elem, errorfunc, valstrings);
  else 
    return true;   
}

function validateForm(form, af, customStrings) {
  var objForm = $(form);
  
  if (af) af.undefaultForm(form);
  
  var formElements = $(objForm).getElements('input, textarea, select');
  var result = true;
  var myAlert = function(el, kind, message)
  {
  	alert(message);
  }
  
  var strings = $merge(valstrings, customStrings || {});
  
  var i = 0;
  while ( result && (i < formElements.length) ) {
  	if (formElements[i].disabled && formElements[i].disabled == true) {
  		i++;
      continue;
  	}
  		
  	result = result && validateElem(formElements[i], myAlert, strings);
  	if (!result) {
  	  if (af) af.defaultForm(form);
  	  formElements[i].focus();
  	  formElements[i].select();
  	}
  	
    i++;	 
  }        
  
  return result;
}


var FormPreprocessor = {
	getIcon: function(elem)
	{
		var icon = elem.retrieve('valicon');
		if (!icon) {
			icon = new Element('span', {'class': 'valicon'}).inject(elem, 'after');
			elem.store('valicon', icon);
		}	
		
		return icon;
	},
	
	changeTtle: function(el, kind, title)
	{
		this.set('title', title);
	},
	
	onlineValElem: function(elem, li)
	{
		if (!elem.hasClass("nocheck"))
		{
			var icon = FormPreprocessor.getIcon(elem);
		
			if (validateElem(elem, FormPreprocessor.changeTtle.bind(icon), window.valstrings))
			{
				icon.addClass('valcheck');
				icon.removeClass('valcross');
			}
			else {
				icon.removeClass('valcheck');
				icon.addClass('valcross');
			}
		} 
	},
	
	RemoveIcons: function(formname)
	{
	  var form = $(formname);
	  
	  if (form) {
	  	var icons = form.getElements('span.valicon');
	  	for(var i=0;i<icons.length;i++)
	  	{
	  		var icon = $(icons[i]);
	  		icon.removeClass('valcross');
	  		icon.removeClass('valcheck');
	  	}
	  }
	
	},

	Augment: function(formname, onlineValidate) {
	  var form = $(formname);
	  
	  if (form) {
	              
	    var blurevent = function(event) {
	      var el = findClosest(event.target, 'li');
	      if (el) $(el).removeClass('active');
	      if (onlineValidate) FormPreprocessor.onlineValElem(this, el);
	    }
	    
	    var focusevent = function(event) {
	      var el = findClosest(event.target, 'li');
	      if (el) $(el).addClass('active');
	    }
	    
	    $each(form.getElements('input, textarea, select'), function(el) {
	      if (el.retrieve('augmentedVisual')) return; 
	      
	      el.addEvents({'blur': blurevent, 'focus': focusevent});
	      el.store('augmentedVisual', true);
	    });
	  }
}
	


};
var TvTips = new Class(
		{
			Extends :Tips,

			options : {
				onShow : function(tip) {
					tip.get("morph", {
						duration :150
					}).start( {
						'opacity' :1.00
					});
				},

				onHide : function(tip) {
					tip.get("morph", {
						duration :100
					}).start( {
						'opacity' :0.00
					});
				},

				loaderURL :''
			},

			elementEnter : function(event, element) {
				var text = element.retrieve('tip:text');
				if (!text) {
					element.store('tip:text',
						'<div class="inline-indicator">' + 
						(window.wmslang == 'en' ? 'The content is being loaded. Please wait.' 
						 : 'Obsah sa načitáva. Počkajte, prosím.') + '</div>');
					var tipRequest = new Request.HTML( {
						url :this.options.loaderURL,
						link :'cancel'
					}).get( {
						'param' :element.get('rev')
					}).addEvent(
							'onSuccess',
							( function(responseTree, responseElements,
									responseHTML) {
								element.store('tip:text', responseHTML);
								if (this.textElement)
									this.textElement.set('html', responseHTML);
							}).bind(this));
				}

				this.parent(event, element);
			}

		});

var FrontEffects = {
	works : {
		SetupHideAfter : function(selector) {
			var elem = $$(selector)[0];
			var size = elem.getSize();
			var wrapper = new Element('div').setStyles( {
				position :"relative",
				height :size.y,
				overflow :"hidden"
			});
			wrapper.wraps(elem);
			elem.setStyles( {
				position :"absolute",
				width :size.x,
				height :size.y,
				bottom :0
			});
			wrapper.morph( {
				opacity :0,
				height :0
			});
		}

	},

	SetupProduktAccordion : function(klass, menter, func) {
		var bloks = $$('.' + klass);

		var showidx = 0, hdr = $$(bloks.getElements('.header'));
		if (window.location.hash.length > 1) {
			var anch = $(window.location.hash.substr(1));
			if (anch)
				anch = anch.getElement('.header');

			if (anch) {
				var save = window.location.hash;
				window.location.hash = "#";
				showidx = hdr.indexOf(anch);

				if (showidx < 0)
					showidx = 0;

				( function() {
					window.location.hash = save;
				}).delay(100);
			}
		}

		var progAccordion = new Accordion(hdr, bloks.getElement('.wrapper'), {
			show :showidx,
			display :showidx,
			alwaysHide :true,
			opacity :false,
			duration :(Browser.Engine.gecko ? 150 : 150),
			fps :75
		});

		if (menter) {
			var len = progAccordion.togglers.length;
			for ( var i = 0; i < len; i++) {
				progAccordion.togglers[i].addEvent('mouseenter',
						( function(idx) {
							if (idx != progAccordion.previous) {
								progAccordion.display(idx);
							}
						}).bind(this, i));
			}
		} else {
			var len = progAccordion.togglers.length;
			for ( var i = 0; i < len; i++) {
				progAccordion.togglers[i].set("title",
				 window.wmslang == 'en' ? "Click to show or hide the detailed information" 
				 : "Kliknutím sa zobrazí alebo skryje detailná informácia...");
			}
		}

		progAccordion.addEvent('active', function(header) {
			var el = findParentMatch(header, '.' + klass);
			if (el) {
				changeHash(el.get('id'));
				if (func)
					func(el);
			}
		});

	},

	SetupHideAfter : function(selector, delay) {
		this.works.SetupHideAfter.delay(delay, this, selector);
	},

	HideNow : function(selector) {
		this.works.SetupHideAfter(selector);
	},

	Ticker : {
		Init : function(base) {
			base = $(base);
			if (!base)
				return;

			var m_el = base.getElement('.marquee');
			var m_data = m_el.getElement('ul');
			var msgs = m_data.getElements('li'), num_msgs = msgs.length, mar_width = m_el.offsetWidth;

			for ( var i = 0; i < num_msgs; i++) {
				var el = msgs[i];
				msgs[i].calculatedWidth = msgs[i].scrollWidth;
			}

			m_data.setStyle('display', 'none');

			var wrapper = new Element('div', {
				'class' :'wrapper'
			}).inject(m_el, 'bottom').setStyle('padding-left', mar_width);

			var current_index, current_boundary, oldtime;
			var setupMsg = function(idx) {
				if (wrapper) {
					wrapper.empty();
					m_el.scrollLeft = 0;
					var new_item = msgs[idx].clone(true, false).inject(wrapper);
					current_index = idx;
					current_boundary = msgs[idx].calculatedWidth + mar_width;
					oldtime = $time();
				}
			}
			var speed = 0.1;

			var animation = function() {
				if (m_el) {
					if (m_el.scrollLeft >= current_boundary) {
						setupMsg((current_index + 1) % num_msgs);

						return;
					}

					var ntime = $time(), delta = ntime - oldtime;

					m_el.scrollLeft = speed * delta;
				}
			}

			setupMsg(0);
			var intertime = $time();

			var timer = animation.periodical(10, this);
			m_el.addEvents( {
				mouseenter : function() {
					$clear(timer);
					intertime = $time();
				},
				mouseleave : function() {
					oldtime += $time() - intertime;
					timer = animation.periodical(10, this);
				}
			});
		}

	},

	LoadHomeCmpEffects : function() {
		var tpservices = $('tpservices');
		var tpscmps = tpservices.getElements('.tpscmp');
		tpscmps.addEvents( {
			mouseenter : function(el) {
				this.getElement('h3').get('morph', {
					'duration' :150
				}).start( {
					'font-size' :'32px',
					'margin-top' :-2
				});
			},
			mouseleave : function(el) {
				this.getElement('h3').get('morph', {
					'duration' :150
				}).start( {
					'font-size' :'24px',
					'margin-top' :0
				});
			}

		});

		this.Ticker.Init("tickerbar");
	},

	LoadGlobalEffects : function() {
		if (Browser.Engine.trident4) {
			var mis = $$('a.qbtn_std, a.qbtn_stdx');

			mis.addEvents( {
				mouseenter : function(event) {
					this.addClass('hover');
				},
				mouseleave : function(event) {
					this.removeClass('hover');
				}
			});

			var mis2 = $$('#tpponuka h5.item');
			mis2.addEvents( {
				mouseover : function(event) {
					this.addClass('hover');
				},
				mouseout : function(event) {
					this.removeClass('hover');
				}
			});

		}
		
		/*if (window.swfobject) swfobject.registerObject("mainbanner", "9.0.0");*/ 

		var pslogany = $('slogany');
		if (pslogany)
		{
  		var slogany = pslogany.getElements('div.slogan');
  		var idx, len = slogany.length;
  		for ( var idx = 0; idx < len; idx++)
  			if (slogany[idx].hasClass('active')) {
  				slogany[idx].removeClass('active').setStyles( {
  					'visibility' :'visible',
  					'opacity' :1.00
  				});
  				break;
  			}
  
  		idx = idx % len;
  
  		var turnSlogan = function() {
  			var nextidx = (idx + 1) % len;
  			/*
  			 * do { nextidx = $random(0, 1000) % len; } while (idx == nextidx);
  			 */
  			slogany[idx].fade('out');
  			slogany[nextidx].setStyles( {
  				'opacity' :0.00,
  				'visibility' :'visible'
  			}).fade('in');
  			idx = nextidx;
  		}
  
  		turnSlogan.periodical(5000);
  	}

		var bb = $('billboard-side');
		if (bb) {
			var tpmain = $('tpmain');
			var tpponuka = $('tpponuka');

			var bbimg = bb.getElement('img');
			var img = null, morphef = null, closeBtn = null;
			var stateOff = {
				left :12,
				top :48+55,
				width :240,
				height :116,
				'padding-bottom' :0
			};
			var stateOn = {
				left :262,
				top :105,
				width :730,
				height :352
			};
			stateOn['padding-bottom'] = tpmain.getSize().y - stateOn.height
					- tpponuka.getStyle('padding-top').toInt();

			var dly = 150;
			var toHide = false;
			var entered = false;
			var billCN = 'billboard-manually-closed';

			var closeImg = function() {
				closeBtn.fade('out');
				morphef.start(stateOff);
			}

			var closeImgTry = function(mode) {
				if (entered) {
					if (!mode)
						toHide = true;
					return;
				}

				if (toHide || !mode)
					closeImg();
			}

			var closeImgDefinite = function() {
				Cookie.write(billCN, '1', {
					duration :14
				});
				closeImg();
			}

			var openImg = function() {
				toHide = false;
				img.setStyle('display', 'block');
				morphef.start(stateOn);
			}

			var isOn = function() {
				return img.offsetWidth > 500;
			}

			var morphComplete = function() {
				if (!isOn())
					img.setStyle('display', 'none');
				else
					closeBtn.fade('in');
			}

			var loadFunc = function(el) {
				img = el;

				bbimg.setStyles( {
					opacity :0,
					visibility :'visible'
				});
				bbimg.set('tween', {
					property :'opacity',
					duration :dly
				});
				bbimg.tween(1.0);
				bbimg.addEvent('click', function() {
					if (isOn())
						closeImgTry();
					else
						openImg();
				});
				billCN += '-' + bbimg.get('rev');
				morphef = new Fx.Morph(img, {
					duration :250,
					transition :Fx.Transitions.Cubic.easeInOut
				}).addEvent('complete', morphComplete);

				img.addClass('billboard');
				img.setStyles(stateOff);
				img.addEvents( {
					mouseenter : function() {
						entered = true;
					},
					mouseleave : function() {
						entered = false;
						closeImgTry(1);
					}
				});
				img.set('title', window.wmslang == 'en' ? 'Click to close the billboard' : 'Kliknutím billboard zavriete');

				( function() {
					var cont = $('page_wrapper');
					img.inject(cont, 'bottom');
					closeBtn = new Element('div', {
						'class' :'billclose',
						'title' :img.get('title')
					}).setStyle('opacity', 0).inject(cont, 'bottom').set(
							'tween', {
								duration :100
							});
					if (Browser.Engine.trident4)
						new Element('div', {
							'class' :'wrp'
						}).inject(closeBtn, 'bottom');

					closeBtn.addEvent('click', closeImgDefinite);
					// set('html', 'zavri')
					img.addEvent('click', closeImgDefinite);

					if (Cookie.read(billCN) != '1') {
						openImg();
						closeImgTry.delay(5000);
					} else
						img.setStyle('display', 'none');
				}).delay(dly);
			}

			Asset.image(bbimg.src, {
				onload :loadFunc
			});
		}
	}
};

var FrontLogic = {
	objformuid :false,

	constructReqObj : function() {
		var base = $('vyber_produkt');
		var items = base.getElements('input[checked]');
		var obj = {
			produkt :null,
			instal :null,
			ext : []
		};

		for ( var i = 0; i < items.length; i++) {
			var item = items[i];
			if (item.hasClass("mainprodukt"))
				obj.produkt = item.get('value')
			else if (item.hasClass("instalacia"))
				obj.instal = item.get('value')
			else if (item.hasClass("ext") || item.hasClass("alt")) {
				if (item.hasClass("egt") || item.hasClass("agt"))
					obj.ext.push(item.get('value'));
				else
					obj.ext.push(item.name.substr(4));
			}
		}

		this.objednavkaPrepocitat(items);

		return obj;
	},

	vyberProdukt : function(el, cena, per) {
		el = $(el);
		var target = findParentMatch(el, 'div.base');
		if (target)
			$tfn(xindi, this, [ target, -20, 0, 0 ]);

		el.store('cena', cena);
		el.store('per', per);

		var obj = FrontLogic.constructReqObj();
		$rpcc(this.objformuid + ':produkt', obj, 0);
	},

	vyberAlt : function(el, cena, per) {
		el = $(el);
		var target = findParentMatch(el, 'div.base');
		if (target)
			$tfn(xindi, this, [ target, -20, 0, 0 ]);
		if (el.hasClass("agt")) {
			target.getElements('input.agt[name=' + el.get('name') + ']').each(function(e) { if (el != e) e.set('checked', false);});
		}

		el.store('cena', cena);
		el.store('per', per);

		var obj = FrontLogic.constructReqObj();
		$rpcc(this.objformuid + ':ext', obj, 0);
	},

	vyberExt : function(el, cena, per) {
		el = $(el);
		var target = findParentMatch(el, 'div.base');
		if (target)
			$tfn(xindi, this, [ target, -20, 0, 0 ]);

		if (el.hasClass("egt")) {
			var egts = target.getElements(
					'input.egt[name=' + el.get('name') + ']').each(
					function(e) {
						if (el != e)
							e.set('checked', false);
					});
		}

		/*
		 * var exts = [];
		 * target.getElements('input.ext[name^=ext_]').each(function(el){ if
		 * (el.checked) exts.push(el.name.substr(4)); });
		 * $rpc(this.objformuid+':ext',exts,0);
		 */
		el.store('cena', cena);
		el.store('per', per);

		var obj = FrontLogic.constructReqObj();
		$rpcc(this.objformuid + ':ext', obj, 0);
	},

	setupObjForm : function(uid, produkty) {
		this.objformuid = uid;
		if (!produkty)
			return;

		var base = $('vyber_produkt');
		if (base) {
			var len = produkty.length, elem;
			for ( var i = 0; i < len; i++) {
				var p = produkty[i];
				elem = base.getElement('#' + uid + 'p' + p[0]);
				if (elem) {
					elem.store('cena', p[1]);
					elem.store('per', p[2]);
				}
			}

		}
	},

	objednavkaPrepocitat : function(elms) {
		var base = $('vyber_produkt');
		if (base) {
			var elems = null;
			if (elms)
				elems = elms;
			else
				elems = base.getElements('input[checked]');
			var sum_j = 0.00, sum_m = 0.00;
			for ( var i = 0; i < elems.length; i++) {
				var per = elems[i].retrieve('per');
				var cena = elems[i].retrieve('cena');
				if (cena && cena > 0) {
					if (per == 0)
						sum_j += new Number(cena);
					else if (per == 1)
						sum_m += new Number(cena);
				}
			}
			var elems, str;

			str = currencyControl.formatEUR(sum_m ? sum_m.toFixed(2) : 0);
			elems = $$('.sumamesacna');
			for ( var i = 0; i < elems.length; i++) {
				var el = elems[i];
				try {
					el.set("html", str);
				} catch (e) {
					alert(sum_m);
				}
				currencyControl.updateTitle(el);
			}

			str = currencyControl.formatEUR(sum_j ? sum_j.toFixed(2) : 0);
			elems = $$('.sumajednorazova');
			for ( var i = 0; i < elems.length; i++) {
				var el = elems[i];
				el.set("html", str);
				currencyControl.updateTitle(el);
			}

			str = FormatNumberSK(sum_m ? (sum_m * 30.1260).toFixed(2) : 0);
			elems = $$('.sumamesacnaskk');
			for ( var i = 0; i < elems.length; i++) {
				var el = elems[i];
				try {
					el.set("html", str);
				} catch (e) {
					alert(sum_m);
				}
				currencyControl.updateTitle(el);
			}

			str = FormatNumberSK(sum_j ? (sum_j * 30.1260).toFixed(2) : 0);
			elems = $$('.sumajednorazovaskk');
			for ( var i = 0; i < elems.length; i++) {
				var el = elems[i];
				el.set("html", str);
				currencyControl.updateTitle(el);
			}

			// alert(sum_j+','+sum_m);
}
},

submitDruh : function(druh) {
$tfn(xindi, this, [ this.objformuid + "moduletitlef2", -20, 0, 0 ]);
var o = $(this.objformuid + "produkt");
o.empty();
$(this.objformuid + "ext").empty();
o.set('html', window.wmslang == 'en' ? 'Products are being loaded...' : 'Produkty sa načitávajú...');

$rpcc(this.objformuid + ':druh', druh, 0);
FrontLogic.objednavkaPrepocitat();
}

}

var ECKeyPress = function(event, target, rate) {
	var event = new Event(event);

	var me = $(event.target);
	var target = $(findClosest(me, 'table')).getElement(
			'input[name=' + target + ']');

	( function() {
		var num = new String(me.get('value')).LToC().toFloat() * rate;

		if (!isNaN(num)) {
			target.set('value', FormatNumberSK(num.toFixed(2)));
		}
	}).delay(30);

	return true;
}

window.addEvent('domready', FrontEffects.LoadGlobalEffects);
/*
 Slimbox v1.41 - The ultimate lightweight Lightbox clone
 by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
 Inspired by the original Lightbox v2 by Lokesh Dhakar.
 */

function detectMacXFF() {
	/*
	 * var userAgent = navigator.userAgent.toLowerCase(); if
	 * (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
	 * return true; }
	 */
	return Browser.Engine.gecko && Browser.Platform.mac;
}

var Lightbox = {
	init : function(options) {
		this.noNext = false;

		this.options = $extend( {
			resizeDuration :400,
			resizeTransition :false, // default transition
			initialWidth :250,
			initialHeight :250,
			defaultIframeWidth :800,
			defaultIframeHeight :500,
			animateCaption :true,
			showCounter :true,
			urlPrefix :'',
			thumbUrlPrefix :'',
			build :false,
			onShow :$empty,
			onClose :$empty,
			defaultTitle :false,
			galleryUrl :'',
			rpcMethod :''
		}, options || {});

		if (Browser.Engine.trident4 && document.compatMode == "BackCompat") {
			this.options.animateCaption = false;
		}

		this.anchors = [];
		if (this.options.build)
			this.build();

		this.eventKeyDown = this.keyboardListener.bind(this); // .bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		var stash = $('stash');
		// stash.setStyles({'width':Window.getScrollSize().x, 'top': 0, 'left':
		// 0});
		/*
		 * if (Browser.Engine.trident4) stash.setStyles({'overflow': 'visible',
		 * 'overflow-x': 'hidden', 'height': 1}); else
		 */
		stash.setStyles( {
			'overflow' :'visible',
			'height' :1
		});

		this.overlay = new Element('div', {
			'id' :'lbOverlay',
			'display' :'none',
			'opacity' :0
		}).inject(stash, 'bottom');

		this.center = new Element('div', {
			'id' :'lbCenter',
			'styles' : {
				'width' :this.options.initialWidth,
				'height' :this.options.initialHeight,
				'marginLeft' :-(this.options.initialWidth / 2),
				'display' :'none'
			}
		}).inject(stash, 'bottom');

		this.canvas = new Element('div', {
			'id' :'lbCanvas'
		}).inject(this.center, 'bottom');
		this.prevLink = new Element('a', {
			'id' :'lbPrevLink',
			'href' :'#',
			'styles' : {
				'display' :'none'
			}
		}).inject(this.canvas, 'bottom');
		this.nextLink = this.prevLink.clone().setProperty('id', 'lbNextLink')
				.inject(this.canvas, 'bottom');
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

		this.bottomContainer = new Element('div', {
			'id' :'lbBottomContainer',
			'styles' : {
				'display' :'none'
			}
		}).inject(stash, 'bottom');
		this.bottom = new Element('div', {
			'id' :'lbBottom',
			'class' :'clearfix'
		}).inject(this.bottomContainer, 'bottom');
		// 'href': '#'

		this.closebutton = new Element('a', {
			'id' :'lbCloseLink'
		}).inject(this.canvas, 'bottom');
		this.closebutton.onclick = this.overlay.onclick = this.close.bind(this);

		this.caption = new Element('div', {
			'id' :'lbCaption'
		}).inject(this.bottom, 'bottom');
		this.number = new Element('div', {
			'id' :'lbNumber'
		}).inject(this.bottom, 'bottom');
		new Element('div', {
			'styles' : {
				'clear' :'both'
			}
		}).inject(this.bottom, 'bottom');

		new Element('div').setStyle('clear', 'both').inject(this.bottom,
				'bottom');

		var nextEffect = this.nextEffect.bind(this);

		this.fx = {
			overlay :new Fx.Tween(this.overlay, {
				property :'opacity',
				duration :350
			}).addEvent('onComplete', ( function() {
				if (this.getStyle('opacity') == 0)
					this.setStyle('display', 'none');
			}).bind(this.overlay)).addEvent('onStart', ( function() {
				this.setStyle('display', 'block');
			}).bind(this.overlay)).set(0),
			resize :new Fx.Morph(this.center, $extend( {
				duration :this.options.resizeDuration,
				onComplete :nextEffect
			}, this.options.resizeTransition ? {
				transition :this.options.resizeTransition
			} : {})),
			image :new Fx.Tween(this.canvas, {
				property :'opacity',
				duration :500,
				onComplete :nextEffect
			}).addEvent('onComplete', ( function() {
				if (this.getStyle('opacity') == 0)
					this.setStyle('display', 'none');
			}).bind(this.canvas)).addEvent('onStart', ( function() {
				this.setStyle('display', 'block');
			}).bind(this.canvas)).set(0),
			bottom :new Fx.Tween(this.bottom, {
				property :'margin-top',
				duration :400,
				onComplete :nextEffect
			})
		};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
	},

	build : function(elems) {
		if (!elems)
			elems = $$('a[rel^=lightbox]');

		elems.each( function(el) {
			el.onclick = this.click.bind(this, el);
			this.anchors.push(el);
		}, this);

		return elems;
	},

	click : function(link) {
		link = $(link);

		if (link.rel.length == 8)
			return this.show(link.href, link.title, link.rev);

		var j, imageNum, images = [];

		this.anchors.each( function(el) {
			if (el.rel == link.rel) {
				for (j = 0; j < images.length; j++)
					if (images[j][0] == el.href)
						break;
				if (j == images.length) {
					images.push( [ el.href, el.title, el.rev ]);
					if (el.href == link.href)
						imageNum = j;
				}
			}
		}, this);

		res = this.open(images, imageNum);

		return res;
	},

	show : function(url, title, rev) {
		this.options.onShow();
		return this.open( [ [ url, title, rev ] ], 0);
	},

	getOffset : function() {
		var bch = this.bottomContainer.getStyle('height').toInt();

		if (!isFinite(bch) || (bch <= 0)) {
			bch = 44;
		}

		var size = Window.getSize();
		var ofs = size.y - (this.center.getStyle('height').toInt() + bch);

		// && this.step > 3
		if (isFinite(ofs) && (ofs > 0))
			return (ofs / 5);
		else
			return size.y / 25;
	},

	open : function(images, imageNum) {
		this.items = images;
		this.position();
		this.setup(true);
		this.fx.overlay.start(0.8);
		this.top = Document.getScroll().y + this.getOffset();
		this.center.setStyles( {
			top :this.top,
			display :''
		});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

	prepareImages : function(images) {
		this.items = images;
	},

	open2 : function(imageNum) {
		this.position();
		this.setup(true);
		this.top = Document.getScroll().y + this.getOffset();
		this.center.setStyles( {
			top :this.top,
			display :''
		});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

	position : function() {
		var stash = $('stash');
		this.overlay.setStyles( {
			width :0,
			height :0,
			display :'block'
		});
		stash.setStyles( {
			width :0,
			height :1,
			display :'block'
		});

		var winscrollsize = Window.getScrollSize();

		stash.setStyles( {
			'width' :winscrollsize.x,
			'top' :0,
			'left' :0
		});

		var size = Window.getSize();
		this.overlay.setStyles( {
			'display' :'block',
			'top' :0,
			'height' :0,
			'width' :winscrollsize.x,
			'height' :winscrollsize.y - 3
		});
			
		var cy = this.center.getSize().y;
		if (cy > 0 && (cy + this.bottomContainer.getSize().y) < size.y) {
			this.center.scrollfx = this.center.scrollfx
					|| new Fx.Tween(this.center, {
						property :'top',
						duration :100,
						link :"cancel"
					});
			this.bottomContainer.scrollfx = this.bottomContainer.scrollfx
					|| new Fx.Tween(this.bottomContainer, {
						property :'top',
						duration :100,
						link :"cancel"
					});

			
			this.top = Window.getScroll().y + this.getOffset();

			this.center.scrollfx.start(this.top);
			
			this.bottomContainer.scrollfx.start(this.top
					+ this.center.getSize().y);
		}

	},

	setup : function(open) {
		var elements = $A(document.getElementsByTagName('object'));

		elements.extend(document
				.getElementsByTagName(Browser.Engine.trident ? 'select'
						: 'embed'));
		elements.each( function(el) {
			if (open)
				el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});

		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition);
		window[fn]('mousewheel', this.eventPosition);
		window[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;

		if (!open) {
			this.canvas.setStyle('display', 'none');
			this.overlay.setStyle('display', 'none');
		}

		if (!open && detectMacXFF()) {
			( function() {
				var objs = $$('object');
				var d = new Element('div');
				for ( var i = 0, l = objs.length; i < l; i++) {
					var o = objs[i];
					var p = o.parentNode;
					o.style.display = "none";
					p.replaceChild(d, o);
					p.replaceChild(o, d);
					o.style.display = "";
				}
			}).delay(50);

		}
	},

	keyboardListener : function(event) {

		switch (event.code) {
		case 27:
			this.close();
			break;
		case 88:
		case 67:
			if (!this.inlelement)
				this.close();
			break;
		// case 80: this.previous(); break;
		// case 78: this.next();

		// case 27: /* case 88: case 67:*/ this.close(); break;
		// case 37: /* case 80:*/ this.previous(); break;
		// case 39: /* case 78:*/ this.next();
		}
	},

	previous : function() {
		return this.changeImage(this.activeItem - 1);
	},

	next : function() {
		return this.changeImage(this.activeItem + 1);
	},

	changeImage : function(imageNum) {
		if (this.step || (imageNum < 0) || (imageNum >= this.items.length))
			return false;
		this.step = 1;
		this.activeItem = imageNum;

		this.bottomContainer.style.display = this.prevLink.style.display = this.nextLink.style.display = 'none';
		this.noNext = true;
		this.fx.image.set(0);
		this.noNext = false;

		this.center.className = 'lbLoading';

		// discard previous content by clicking
		this.removeCurrentItem();

		// check item type
		var urlx = this.items[this.activeItem][0];
		var rev = this.items[this.activeItem][2];

		if ($type(urlx) == 'element') {
			this.preload = new Object(); // JavaScript native Object
			this.preload.datatype = 'element';
			this.preload.src = urlx;
			this.preload.w = this.matchOrDefault(rev, new RegExp(
					"width=(\\d+)", "i"), this.options.defaultIframeWidth);
			this.preload.h = this.matchOrDefault(rev, new RegExp(
					"height=(\\d+)", "i"), this.options.defaultIframeHeight);

			this.nextEffect();
		} else {
			var url = this.options.urlPrefix + urlx;

			var re_imageURL = /\.(jpe?g|png|gif|bmp)/i;
			if (url.match(re_imageURL)) {
				this.preload = new Image(); // JavaScript native Object
				this.preload.datatype = 'image';
				this.preload.w = this.matchOrDefault(rev, new RegExp(
						"width=(\\d+%?)", "i"), -1); // -1 if use original
														// size.
				this.preload.h = this.matchOrDefault(rev, new RegExp(
						"height=(\\d+%?)", "i"), -1);
				this.preload.onload = this.nextEffect.bind(this);
				this.preload.src = url;
			} else {
				this.preload = new Object(); // JavaScript native Object
				this.preload.datatype = 'iframe';
				this.preload.w = this.matchOrDefault(rev, new RegExp(
						"width=(\\d+)", "i"), this.options.defaultIframeWidth);
				this.preload.h = this
						.matchOrDefault(rev, new RegExp("height=(\\d+)", "i"),
								this.options.defaultIframeHeight);
				this.preload.src = url;
				this.nextEffect(); // asynchronous loading
			}
		}

		return false;
	},

	nextEffect : function() {
		if (this.noNext)
			return;

		switch (this.step++) {
		case 1:
			if (Browser.Engine.trident4)
			{
				this.center.setStyle('overflow', 'hidden');
				this.closebutton.setStyle('display', 'none');
			}
			
			this.center.className = '';
			// create HTML element
	if (this.preload.datatype == 'image') {
		var ws = (this.preload.w == -1) ? this.preload.width.toString()
				: this.preload.w.toString();
		var hs = (this.preload.h == -1) ? this.preload.height.toString()
				: this.preload.h.toString();
		this.p_width = (q = ws.match(/(\d+)%/)) ? q[1] * this.preload.width
				* 0.01 : ws;
		this.p_height = (q = hs.match(/(\d+)%/)) ? q[1] * this.preload.height
				* 0.01 : hs;
		new Element('img').setProperties( {
			id :'lbImage',
			src :this.preload.src,
			width :this.p_width,
			height :this.p_height
		}).inject(this.canvas, 'bottom');
		this.nextLink.style.right = '';
	} else {
		this.p_width = this.preload.w;
		this.p_height = this.preload.h;

		if (this.preload.datatype == 'iframe') {
			// Safari would not update iframe content that has static id.
			this.iframeId = "lbFrame_" + new Date().getTime();
			new Element('iframe').setProperties( {
				id :this.iframeId,
				width :this.p_width,
				height :this.p_height,
				frameBorder :0,
				scrolling :'auto',
				src :this.preload.src
			}).addClass('lbLoading').inject(this.canvas, 'bottom');
		} else {
			this.inlelement = this.preload.src;

			if (this.inlelement) {
				this.inlelement.store("originalParent",
						this.inlelement.parentNode);

				this.inlelement.setStyle('display', 'none').dispose().inject(
						this.canvas, 'bottom');
			}
		}

		this.nextLink.style.right = '25px';
	}
	this.canvas.setStyle('display', 'block');
	this.canvas.style.width = this.bottom.style.width = this.p_width + 'px';
	this.canvas.style.height = this.prevLink.style.height = this.nextLink.style.height = this.p_height + 'px';

	// this.canvas.style.backgroundImage =
	// 'url('+this.options.urlPrefix+this.items[this.activeItem][0]+')';
	// this.canvas.style.width = this.bottom.style.width =
	// this.preload.width+'px';
	// this.canvas.style.height = this.prevLink.style.height =
	// this.nextLink.style.height = this.preload.height+'px';

	this.caption.set('html', this.items[this.activeItem][1]
			|| this.options.defaultTitle || '');
	this.number.set('html',
			(!this.options.showCounter || (this.items.length == 1)) ? ''
					: 'Image ' + (this.activeItem + 1) + ' of '
							+ this.items.length);

	// this.closebutton.set('html', 'Close');

	if (this.activeItem)
		this.preloadPrev.src = this.options.urlPrefix
				+ this.items[this.activeItem - 1][0];
	if (this.activeItem != (this.items.length - 1))
		this.preloadNext.src = this.options.urlPrefix
				+ this.items[this.activeItem + 1][0];
	
	if ((this.center.getSize().y != this.canvas.offsetHeight)
			|| (this.center.getSize().x != this.canvas.offsetWidth)) {
		
		this.fx.resize.start( {
			'height' :this.canvas.offsetHeight,
			'width' :this.canvas.offsetWidth,
			'margin-left' :-this.canvas.offsetWidth / 2
		});
		break;
	}
	/*
	 * if { this.fx.resize.start(); break; }
	 */
	this.step++;
case 2:
	if (Browser.Engine.trident4)
	{
		this.center.setStyle('overflow', 'hidden');
		this.closebutton.setStyle('display', 'none');
	}
	this.step++;
case 3:
	this.bottomContainer.setStyles( {
		top :(this.top + this.center.getSize().y)+'px',
		height :'0',
		marginLeft :this.center.style.marginLeft,
		display :'block',
		position: 'absolute'
	});
	if (Browser.Engine.trident4)
	{
		this.center.setStyle('overflow', 'visible');
		this.closebutton.setStyle('display', 'block');
	}
	
	if (this.inlelement) {
		this.fx.image.set(1);
		this.inlelement.setStyle('display', 'block');
		this.nextEffect.delay(50, this);
	} else
		this.fx.image.start(1);
	break;
case 4:
	if (this.options.animateCaption) {
		this.bottom.setStyle('margin-top', -this.bottom.offsetHeight);
		this.bottomContainer.style.height = 'auto';
		this.fx.bottom.start(-this.bottom.offsetHeight, 0);
		break;
	}
	
	this.bottomContainer.style.height = 'auto';
case 5:
	if (this.activeItem)
		this.prevLink.style.display = '';
	if (this.activeItem != (this.items.length - 1))
		this.nextLink.style.display = '';
	this.step = 0;
}
},

close : function() {
if (this.step < 0)
	return;
this.step = -1;
this.removeCurrentItem(); // discard content
	for ( var f in this.fx)
		if (this.fx[f])
			this.fx[f].cancel();
	this.center.style.display = this.bottomContainer.style.display = 'none';
	this.fx.overlay.chain(this.setup.pass(false, this)).start(0);

	this.options.onClose();
	
	if (Browser.Engine.trident4)
	{
		this.center.setStyle('overflow', 'hidden');
		this.closebutton.setStyle('display', 'none');
	}

	return false;
},

removeCurrentItem : function() {
	if (this.preload) {
		if (this.preload.datatype == 'image') {
			this.preload.onload = $empty;
			var el = $('lbImage');
			el.destroy();
		} else if (this.preload.datatype == 'iframe') {
			var el = $(this.iframeId);
			el.destroy();
		} else {
			if (this.inlelement) {
				// 
	this.inlelement.setStyle('display', 'none').dispose()
			.inject(this.inlelement.retrieve("originalParent", document.body),
					'bottom');
}
}

this.inlelement = null;
this.preload = null;
}
},

matchOrDefault : function(str, re, val) {
var hasQuery = str.match(re);
return hasQuery ? hasQuery[1] : val;
}

};

/**
 * Observer - Observe formelements for changes
 *
 * - Additional code from clientside.cnet.com
 *
 * @version		1.1
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var Observer = new Class({

	Implements: [Options, Events],

	options: {
		periodical: false,
		delay: 1000
	},

	initialize: function(el, onFired, options){
		this.element = $(el) || $$(el);
		this.addEvent('onFired', onFired);
		this.setOptions(options);
		this.bound = this.changed.bind(this);
		this.resume();
	},

	changed: function() {
		var value = this.element.get('value');
		if ($equals(this.value, value)) return;
		this.clear();
		this.value = value;
		this.timeout = this.onFired.delay(this.options.delay, this);
	},

	setValue: function(value) {
		this.value = value;
		this.element.set('value', value);
		return this.clear();
	},

	onFired: function() {
		this.fireEvent('onFired', [this.value, this.element]);
	},

	clear: function() {
		$clear(this.timeout || null);
		return this;
	},

	pause: function(){
		if (this.timer) $clear(this.timer);
		else this.element.removeEvent('keyup', this.bound);
		return this.clear();
	},

	resume: function(){
		this.value = this.element.get('value');
		if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
		else this.element.addEvent('keyup', this.bound);
		return this;
	}

});

var $equals = function(obj1, obj2) {
	return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};

/**
 * Autocompleter
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var Autocompleter = new Class({

	Implements: [Options, Events],

	options: {/*
		onOver: $empty,
		onSelect: $empty,
		onSelection: $empty,
		onShow: $empty,
		onHide: $empty,
		onBlur: $empty,
		onFocus: $empty,*/
		minLength: 1,
		markQuery: true,
		width: 'inherit',
		maxChoices: 10,
		injectChoice: null,
		customChoices: null,
		emptyChoices: null,
		visibleChoices: true,
		className: 'autocompleter-choices',
		zIndex: 42,
		delay: 400,
		observerOptions: {},
		fxOptions: {},

		autoSubmit: false,
		overflow: false,
		overflowMargin: 25,
		selectFirst: false,
		filter: null,
		filterCase: false,
		filterSubset: false,
		forceSelect: false,
		selectMode: true,
		choicesMatch: null,

		multiple: false,
		separator: ', ',
		separatorSplit: /\s*[,;]\s*/,
		autoTrim: false,
		allowDupes: false,

		cache: true,
		relative: false
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.build();
		this.observer = new Observer(this.element, this.prefetch.bind(this), $merge({
			'delay': this.options.delay
		}, this.options.observerOptions));
		this.queryValue = null;
		if (this.options.filter) this.filter = this.options.filter.bind(this);
		var mode = this.options.selectMode;
		this.typeAhead = (mode == 'type-ahead');
		this.selectMode = (mode === true) ? 'selection' : mode;
		this.cached = [];
	},

	/**
	 * build - Initialize DOM
	 *
	 * Builds the html structure for choices and appends the events to the element.
	 * Override this function to modify the html generation.
	 */
	build: function() {
		if ($(this.options.customChoices)) {
			this.choices = this.options.customChoices;
		} else {
			this.choices = new Element('ul', {
				'class': this.options.className,
				'styles': {
					'zIndex': this.options.zIndex
				}
			}).inject($('footer'), 'before');
			this.relative = false;
			if (this.options.relative) {
				this.choices.inject(this.element, 'after');
				this.relative = this.element.getOffsetParent();
			}
			this.fix = new OverlayFix(this.choices);
		}
		if (!this.options.separator.test(this.options.separatorSplit)) {
			this.options.separatorSplit = this.options.separator;
		}
		this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, $merge({
			'property': 'opacity',
			'link': 'cancel',
			'duration': 200
		}, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
		this.element.setProperty('autocomplete', 'off')
			.addEvent((Browser.Engine.trident || Browser.Engine.webkit) ? 'keydown' : 'keypress', this.onCommand.bindWithEvent(this))
			.addEvent('click', this.onCommand.bind(this, [false]))
			.addEvent('focus', this.toggleFocus.create({bind: this, arguments: true, delay: 100}))
			.addEvent('blur', this.toggleFocus.create({bind: this, arguments: false, delay: 100}));
	},

	destroy: function() {
		if (this.fix) this.fix.destroy();
		this.choices = this.selected = this.choices.destroy();
	},
	
	doChange: function()
	{
	  if(!this.element.onchange) return;	  
	  // if (!Browser.Engine.trident && !Browser.Engine.webkit && !Browser.Engine.presto) return;	  
	  var value = this.element.retrieve("origvalue");
	  if (value != this.element.value)
	  {
      this.element.store('origvalue', this.element.value);
      // this.element.fireEvent('change');            
      this.element.onchange.run(false, this.element);
    }        
  },

	toggleFocus: function(state) {
    this.focussed = state;
		if (!state) {		  
      this.hideChoices(true);
       this.doChange();  
		}
		this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
		return true;
	},

	onCommand: function(e) {	  
		if (!e && this.focussed) return this.prefetch();
		if (e && e.key && !e.shift) {
			switch (e.key) {
				case 'enter':				  
					if (this.element.value != this.opted)
          {
            if (!!(this.options.autoSubmit)) this.doChange();
            return true;  
          } 
					 
					if (this.selected && this.visible) {
						this.choiceSelect(this.selected);
            if (!!(this.options.autoSubmit)) this.doChange();      				
					  return !!(this.options.autoSubmit);		            
					}										
					break;
				case 'up': case 'down':
					if (!this.prefetch() && this.queryValue !== null) {
						var up = (e.key == 'up');
						this.choiceOver((this.selected || this.choices)[
							(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')
						](this.options.choicesMatch), true);
					}
					return false;
				case 'esc': case 'tab':				  
					this.hideChoices(true);
					break;
			}
		}
		return true;
	},

	setSelection: function(finish) {
		var input = this.selected.inputValue, value = input;
		var start = this.queryValue.length, end = input.length;
		if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
		if (this.options.multiple) {
			var split = this.options.separatorSplit;
			value = this.element.value;
			start += this.queryIndex;
			end += this.queryIndex;
			var old = value.substr(this.queryIndex).split(split, 1)[0];
			value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
			if (finish) {
				var tokens = value.split(this.options.separatorSplit).filter(function(entry) {
					return this.test(entry);
				}, /[^\s,]+/);
				if (!this.options.allowDupes) tokens = [].combine(tokens);
				var sep = this.options.separator;
				value = tokens.join(sep) + sep;
				end = value.length;
			}
		}
		this.observer.setValue(value);
		this.opted = value;
		if (finish || this.selectMode == 'pick') start = end;
		this.element.selectRange(start, end);
		this.fireEvent('onSelection', [this.element, this.selected, value, input]);
	},

	showChoices: function() {
		var match = this.options.choicesMatch, first = this.choices.getFirst(match);
		this.selected = this.selectedValue = null;
		if (this.fix) {
			var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto';
			this.choices.setStyles({
				'left': pos.left,
				'top': pos.bottom,
				'width': (width === true || width == 'inherit') ? pos.width : width
			});
		}
		if (!first) return;
		if (!this.visible) {
			this.visible = true;
			this.choices.setStyle('display', '');
			if (this.fx) this.fx.start(0.9);
			this.fireEvent('onShow', [this.element, this.choices]);
		}
		if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
		var items = this.choices.getChildren(match), max = this.options.maxChoices;
		var styles = {'overflowY': 'hidden', 'height': ''};
		this.overflown = false;
		if (items.length > max) {
			var item = items[max - 1];
			styles.overflowY = 'scroll';
			styles.height = item.getCoordinates(this.choices).bottom;
			this.overflown = true;
		};
		this.choices.setStyles(styles);
		this.fix.show();
		if (this.options.visibleChoices) {
			var scroll = document.getScroll(),
			size = document.getSize(),
			coords = this.choices.getCoordinates();
			if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x;
			if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y;
			window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top));
		}
	},

	hideChoices: function(clear) {
		if (clear) {
			var value = this.element.value;
			if (this.options.forceSelect) value = this.opted;
			if (this.options.autoTrim) {
				value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator);
			}
			this.observer.setValue(value);
		}
		if (!this.visible) return;
		this.visible = false;
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.observer.clear();
		var hide = function(){
			this.choices.setStyle('display', 'none');
			this.fix.hide();
		}.bind(this);
		if (this.fx) this.fx.start(0).chain(hide);
		else hide();
		this.fireEvent('onHide', [this.element, this.choices]);
	},

	prefetch: function() {
		var value = this.element.value, query = value;
		if (this.options.multiple) {
			var split = this.options.separatorSplit;
			var values = value.split(split);
			var index = this.element.getSelectedRange().start;
			var toIndex = value.substr(0, index).split(split);
			var last = toIndex.length - 1;
			index -= toIndex[last].length;
			query = values[last];
		}
		if (query.length < this.options.minLength) {
			this.hideChoices();
		} else {
			if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
				if (this.visible) return false;
				this.showChoices();
			} else {
				this.queryValue = query;
				this.queryIndex = index;
				if (!this.fetchCached()) this.query();
			}
		}
		return true;
	},

	fetchCached: function() {
		return false;
		if (!this.options.cache
			|| !this.cached
			|| !this.cached.length
			|| this.cached.length >= this.options.maxChoices
			|| this.queryValue) return false;
		this.update(this.filter(this.cached));
		return true;
	},

	update: function(tokens) {
		this.choices.empty();
		this.cached = tokens;
		var type = tokens && $type(tokens);
		if (!type || (type == 'array' && !tokens.length) || (type == 'hash' && !tokens.getLength())) {
			(this.options.emptyChoices || this.hideChoices).call(this);
		} else {
			if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
			tokens.each(this.options.injectChoice || function(token){
				var choice = new Element('li', {'html': this.markQueryValue(token)});
				choice.inputValue = token;
				this.addChoiceEvents(choice).inject(this.choices);
			}, this);
			this.showChoices();
		}
	},

	choiceOver: function(choice, selection) {
		if (!choice || choice == this.selected) return;
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.selected = choice.addClass('autocompleter-selected');
		this.fireEvent('onSelect', [this.element, this.selected, selection]);
		if (!this.selectMode) this.opted = this.element.value;
		if (!selection) return;
		this.selectedValue = this.selected.inputValue;
		if (this.overflown) {
			var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin,
				top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height;
			if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
			else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
		}
		if (this.selectMode) this.setSelection();
	},

	choiceSelect: function(choice) {
		if (choice) this.choiceOver(choice);
		this.setSelection(true);
		this.queryValue = false;
		this.hideChoices();
	},

	filter: function(tokens) {
		return (tokens || this.tokens).filter(function(token) {
			return this.test(token);
		}, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
	},

	/**
	 * markQueryValue
	 *
	 * Marks the queried word in the given string with <span class="autocompleter-queried">*</span>
	 * Call this i.e. from your custom parseChoices, same for addChoiceEvents
	 *
	 * @param		{String} Text
	 * @return		{String} Text
	 */
	markQueryValue: function(str) {
		return (!this.options.markQuery || !this.queryValue) ? str
			: str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>');
	},

	/**
	 * addChoiceEvents
	 *
	 * Appends the needed event handlers for a choice-entry to the given element.
	 *
	 * @param		{Element} Choice entry
	 * @return		{Element} Choice entry
	 */
	addChoiceEvents: function(el) {
		return el.addEvents({
			'mouseover': this.choiceOver.bind(this, [el]),
			'click': this.choiceSelect.bind(this, [el])
		});
	}
});

var OverlayFix = new Class({

	initialize: function(el) {
		if (Browser.Engine.trident) {
			this.element = $(el);
			this.relative = this.element.getOffsetParent();
			this.fix = new Element('iframe', {
				'frameborder': '0',
				'scrolling': 'no',
				'src': 'javascript:false;',
				'styles': {
					'position': 'absolute',
					'border': 'none',
					'display': 'none',
					'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
				}
			}).inject(this.element, 'after');
		}
	},

	show: function() {
		if (this.fix) {
			var coords = this.element.getCoordinates(this.relative);
			delete coords.right;
			delete coords.bottom;
			this.fix.setStyles($extend(coords, {
				'display': '',
				'zIndex': (this.element.getStyle('zIndex') || 1) - 1
			}));
		}
		return this;
	},

	hide: function() {
		if (this.fix) this.fix.setStyle('display', 'none');
		return this;
	},

	destroy: function() {
		if (this.fix) this.fix = this.fix.destroy();
	}

});

Element.implement({

	getSelectedRange: function() {
		if (!Browser.Engine.trident) return {start: this.selectionStart, end: this.selectionEnd};
		var pos = {start: 0, end: 0};
		var range = this.getDocument().selection.createRange();
		if (!range || range.parentElement() != this) return pos;
		var dup = range.duplicate();
		if (this.type == 'text') {
			pos.start = 0 - dup.moveStart('character', -100000);
			pos.end = pos.start + range.text.length;
		} else {
			var value = this.value;
			var offset = value.length - value.match(/[\n\r]*$/)[0].length;
			dup.moveToElementText(this);
			dup.setEndPoint('StartToEnd', range);
			pos.end = offset - dup.text.length;
			dup.setEndPoint('StartToStart', range);
			pos.start = offset - dup.text.length;
		}
		return pos;
	},

	selectRange: function(start, end) {
		if (Browser.Engine.trident) {
			var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
			start = this.value.substr(0, start).replace(/\r/g, '').length;
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd('character', start + diff);
			range.moveStart('character', start);
			range.select();
		} else {
			this.focus();
			this.setSelectionRange(start, end);
		}
		return this;
	}

});

/* compatibility */

Autocompleter.Base = Autocompleter;

/**
 * Autocompleter.Local
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

Autocompleter.Local = new Class({

	Extends: Autocompleter,

	options: {
		minLength: 0,
		delay: 200
	},

	initialize: function(element, tokens, options) {
		this.parent(element, options);
		this.tokens = tokens;
	},

	query: function() {
		this.update(this.filter());
	}

});

var Search = new Class({
	
	Implements: [Events, Options],
	
	options: {
		label: null,
		restrict: null
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		if (google)
		{
			this.search = new google.search.WebSearch();
			if (this.options.label) this.search.setUserDefinedLabel(this.options.label);
			if (this.options.restrict) this.search.setSiteRestriction(this.options.restrict);
			this.search.setNoHtmlGeneration();
			this.search.setSearchCompleteCallback(this, this.complete);
		}
	},
	
	complete: function(){
		this.fireEvent('onComplete', [this.search.results]);
	},
	
	query: function(value){
		if (this.search)
			this.search.execute(value);
			
		return this;
	}
	
});

Search.Results = new Class({
	
	toElement: function(){
		return this.container;
	},
	
	initialize: function(){
		this.container = new Element('ul', {'class': 'results'});
	},
	
	fill: function(results){
		this.container.empty();
		
		for (var i = 0, l = results.length; i < l; i++){
			
			var li = this.parseResult(results[i]);
			
			this.container.adopt(li);
			
			if (i == results.length - 1) li.addClass('last');
		}
		
		if (results.length == 0){
			var empty = new Element('li', {'class': 'result-item first last'});
			var content = new Element('div', {'class': 'result-content', html: window.wmslang == 'en' ? 'empty search results' : 'výsledok vyhľadávania je prázdny'});
			empty.adopt(content);
			this.container.adopt(empty);
		}
	},
	
	parseResult: function(result){
		var li = new Element('li', {'class': 'result-item'});
		var title = new Element('a', {'class': 'result-title', html: result.title, href: result.url});
		var content = new Element('div', {'class': 'result-content', html: result.content});
		li.adopt(title, content);
		return li;
	}
	
});

Search.Input = new Class({
	
	Implements: [Events, Options],
	
	options: {
		results: 4,
		placeHolder: null,
		id: null,
		className: null
	},
	
	toElement: function(){
		return this.input;
	},
	
	initialize: function(options){
		
		this.setOptions(options);
		
		this.input = new Element('input', {type: Browser.Engine.webkit ? 'search' : 'text'});
		
		if (Browser.Engine.webkit) this.input.set('results', this.options.results);
		
		if (this.options.id) this.input.set('id', this.options.id);
		
		var placeHolder = this.options.placeHolder;
		
		if (placeHolder){
			
			if (Browser.Engine.webkit){
				this.input.set('placeholder', placeHolder);
			} else {
				this.input.addEvents({
					
					focus: function(){
						if (this.value == placeHolder) this.value = '';
						this.removeClass('place-holder');
					},
					
					blur: function(){
						if (!this.value.length){
							this.value = placeHolder;
							this.addClass('place-holder');
						}
					}
				});
				
				this.input.fireEvent('blur');
			}

		}
		
		this.input.addEvent('keydown', function(event){
			this.value = this.input.value;
			if (event.key == 'enter' && this.value.length) this.fireEvent('onSubmit');
		}.bind(this));
	}
	
});

if (google)
{
	google.load('search', '1', {nocss: true});
	
	window.addEvent('domready', function(){
		
		var webSearch = new Search({restrict: '005878271671231580550:nnxj4-sjlhi', label: 'MAX.sk'});
		
		var input = new Search.Input({id: "google-input", placeHolder: window.wmslang == 'en' ? 'search on MAX.sk' : 'vyhľadať na portáli'});
		$(input).inject('google-search');
		
		var list = new Search.Results();
		
		li = $(list);
		
		li.inject('google-search-results');
		
		li.setStyle('visibility', 'hidden');
		// , width: $(input).getWidth() -2
		input.addEvent('onSubmit', function(){					
			li.setStyles({			
				top: $(input).scrollHeight,
				left: $(input).offsetLeft
			});
			li.setStyle('visibility', 'visible').set('html', '<li class="first last">'+(window.wmslang == 'en' ? 'searching...' : 'hľadám...') + '</li>');
			webSearch.query(this.value);
		});
		
		webSearch.addEvent('onComplete', function(results){
			$(input).blur();
			list.fill(results);
			li.grabTop(new Element('li', {'class': 'first', id: 'powered-by-google', html: 'powered by <a onclick="return !window.open(this.href);" href="http://google.com">Google</a>'}));
		});
		
		document.addEvent('click', function(e){
			if (e.target != li && !li.hasChild(e.target)) li.setStyle('visibility', 'hidden');
		});
				
		
	});
}