
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);   
  }
}

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;
}


        
function $tfn(fn, bind, args){
	try {
		return fn.apply(bind, $splat(args));
	} catch(e){
		return false;
	}
};

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("Invalid Day, Month, or Year range detected. Please correct and submit again.");
      return false;
  }
  
  return true;
}

var openTab = function(me, xinditarget) { 
  var trgt = $(xinditarget).getElement(".content");
  trgt.empty();
  
  $tfn(xindis, this, [trgt, 0, 26, 4]);
  me = $(me);
   
  var ul = findClosest(me, 'ul');
  var li = findClosest(me, 'li');
  
  if ($defined(ul)) {
    var curactive = $(ul).getElement('li.active');
    
    if ($defined(curactive) && (curactive != li))
      curactive.removeClass('active');
  }
  
  if ($defined(li))
    $(li).addClass('active');
}

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 visiblePortion(elem) {
  var coords = elem.getCoordinates();
    
  var nd = $(elem.parentNode);
  while (nd && $type(nd)=='element' && nd.getStyle('overflow')!='hidden')
    nd = $(nd.parentNode); 
    
  if (nd && ($type(nd) == 'element')) {
    var pportion = visiblePortion(nd);
    
    coords.left = Math.max(coords.left, pportion.left);
    coords.top = Math.max(coords.top, pportion.top);
    coords.bottom = Math.min(coords.bottom, pportion.bottom);
    coords.right = Math.min(coords.right, pportion.right);
  }
  
  return coords;   
}

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 { 
  }
}     
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').each(function(el) {
	  el = $(el);
    el.prevDisabled = $pick(el.prevDisabled, el.disabled);
	  el.disabled = el.prevDisabled || disabled;
	  
	  var tag = el.get('tag');
	  if (tag =='input') {
	    if (el.type=='submit') {
        el.value = buttontext || (disabled ? 'Please wait...' : 'Submit');
        el.setAttribute("autocomplete", "off");
      }
      else if (toclear && el.type=='text')
        el.value = el.retrieve('defaultValue') || '';
    } 
    else if (toclear && el.get('tag')=='textarea') {
      el.value = '';
    }
    else if (tag == 'button' && el.type=="submit")
    {
      el.setAttribute("autocomplete", "off");
      if (disabled)
        el.store("oldvalue", el.get("html")).set("html", buttontext || 'sending');
      else
        el.set("html", buttontext || el.retrieve("oldvalue", "Submit"));
    }
	});
	
	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(window.tinyMCE) ) {        
        var editor = window.tinyMCE.getInstanceById(el.id);
        
        if ($defined(editor) && ($defined(editor.save))) {
          editor.execCommand('mceCleanup');
          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);
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 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);    
}

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 augmentFormVisual = function(formname) {
  var form = $(formname);
  
  if (form) {
              
    var blurevent = function(event) {
      var el = findClosest(event.target, 'li');
      if (el) $(el).removeClass('active');
    }
    
    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 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 generalRemoveTinyMCEeditors = function()
{
  if (!$defined(window.tinyMCE)) return;
  
	try 
	{ 
		var AR = $H(window.tinyMCE.editors); 
		
		$each(AR, function(e) { 
			try 
			{ 
				try 
				{ 
					e.remove();								
				} 
				catch(ex) {}
				
				window.tinyMCE.remove(e);
				
				delete e;
			} catch(ex) {} 
		}); 
	} 
	catch (ex) {}

  delete AR;
		
	for (n in window.tinyMCE.instances) 
  {
     window.tinyMCE.removeInstance(window.tinyMCE.instances[n]);
  }

}

window.kfm_for_tiny_mce = function(field_name, url, type, win){
  try
  {
  window.SetUrl=function(url,width,height,caption){
   win.document.forms[0].elements[field_name].value = url;
   if(caption){
    win.document.forms[0].elements["alt"].value=caption;
    win.document.forms[0].elements["title"].value=caption;
   }
  }
  window.open(window.wmsurl+'kfm/index.php?mode=selector&type='+type,'kfm','modal,width=800,height=600');
  } catch (exc) {}
}

var initTinyMCEFirst = function()
{
  if (!$defined(window.tinyMCE)) return;
  
	window.tinyMCE.init({
		add_unload_trigger: false,mode:"textareas",editor_selector : "wysiwyg",theme : "advanced",theme_advanced_disable: "styleselect",
		plugins : "paste,advlink,searchreplace,layer,xhtmlxtras,style,table",extended_valid_elements: "a[name|href|target|title|onclick|rel|class|rev|*]",
		theme_advanced_buttons1_add: "styleprops,tablecontrols", theme_advanced_buttons3_add : "paste,pastetext,pasteword,selectall,insertlayer,moveforward,movebackward,absolute",table_styles : "Header 1=header1;Header 2=header2;Header 3=header3",
		theme_advanced_buttons2_add: "cite,ins,del,abbr,acronym,attribs",
		table_cell_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Cell=tableCel1",
		table_row_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1",language : "en",
		add_form_submit_trigger : 0,submit_patch : 0,invalid_elements : "applet",fix_list_elements: true,fix_table_elements : true,paste_auto_cleanup_on_paste : true,paste_use_dialog: false,
		file_browser_callback : "kfm_for_tiny_mce",cleanup_on_startup : true, cleanup: true,debug : false,
		table_cell_limit : 150,table_row_limit : 50,table_col_limit : 5,verify_css_classes:false,strict_loading_mode:true,
    hidden_input:false});
}

var internalLoadTinyMCE = function()
{
/*	try
	{
		window.document.body.normalize();
	}
	catch (exc)
	{
	}*/
	if (!$defined(window.tinyMCE)) return;
	
	var elems = $$("textarea.wysiwyg");
	var len = elems.length;
	
	if (len > 0) 
	{	
		try 
		{ 
			var t = window.tinyMCE;
			if (!t.settings) 
      { 
        initTinyMCEFirst();
        internalLoadTinyMCE.delay(500);
      }
			else
			{				
				$each(elems, function(elem) 
				{
					elem = $(elem);
					if (!elem.id)
						elem.id = 'textarea' + $uid(elem);
					
					var exi = t.get(elem.id);					
					if (exi)
					{
						try 
						{ 
							try 
							{ 
								exi.remove();								
							} 
							catch(ex) {}							
							window.tinyMCE.remove(exi);							
							delete exi;
						} catch(ex) {} 
						exi = null;
					}
					
					ed = new tinymce.Editor(elem.id, t.settings);
					ed.render();	
					try { ed.focus(); } catch(exc) {}
                  							
				});
			
			}																
		} 
		catch (exc) 
		{ 
			alert(exc); 
		} 
		
	//	try { window.document.body.normalize(); } catch (exc) {}
  	
  	(function() {
  	//  try { window.document.body.normalize(); } catch (exc) {}
      var editors = $$(".mceEditor");
      $each(editors, function(e) { $(e).setStyle('display', 'none') } );
      
        (function() {
      //  try { window.document.body.normalize(); } catch (exc) {}
        var editors = $$(".mceEditor");
        $each(editors, function(e) { $(e).setStyle('display', 'block') } );
      
      }).delay(150);
    
    }).delay(150);
  	
	}
	
	return len;
}

var generalLoadTinyMCE = function()
{
  if (!$defined(window.tinyMCE)) return;
  
	generalRemoveTinyMCEeditors();
	
	(function() {
		if (!internalLoadTinyMCE())
			internalLoadTinyMCE.delay(200);	  
	}).delay(300);

}

var CommonLogic = {
		CheckBox_BillingSameHandler: function(chb)
		{
			var base = chb.getParent("form");
			var grp = base.getElement('.grp_d');
			var inputs = grp.getElements('input');
			for(var i=0;i<inputs.length;i++)
			{
				var inp = inputs[i];
				if (inp.get('name') == 'clientBillingZIP')
					chb.checked ? inp.removeClass("integer") : inp.addClass("integer");
				else
					chb.checked ? inp.removeClass("notempty") : inp.addClass("notempty");
					
				inp.set('disabled', chb.checked);
			}
			
			chb.checked ? grp.addClass('mh') : grp.removeClass('mh');
		},
		
		SetupClientStates: function(states)
		{			
			var clientState = document.getElement('input[name=clientState]');
			if (clientState)
			{				
				var acl_cs = new Autocompleter.Local(clientState, states, {forceSelect: true, selectMode: "type-ahead"});
			}
		}
		
};


/*********************************************************/
/*   vlaCalendar version 2.1 for mootools release 1.2    */
/*********************************************************/

var vlaCalendar = new Class({
	'limitDay' : 0,
	'slideDuration': 500,
	'fadeDuration': 500,
	'transition': Fx.Transitions.Quart.easeOut,
	'startMonday': false,
	'filePath': 'inc/',
	'defaultView': 'month',
	'style': '',
	
	initialize: function(_container, _options) {
		//Add the provided options to this object by extending
		if(_options) $extend(this, _options);
		
		this.loading = false;
		this.container = _container = $(_container);
				
    var _class = this;
		
		//Insert the base into the container and initialize elements
		var  pars = 'defaultView='+ this.defaultView;
		if(this.picker) {
			if($type(this.prefillDate) == 'object' && this.getInputDate(this.prefillDate)) pars += '&pickedDate='+ this.getInputDate(this.prefillDate);
			if(this.linkWithInput) pars += '&gotoPickedDate=1';
			if(this.limitDay) pars += '&limitDay='+this.limitDay;
		}
		
    this.u('base', pars, function() { 
			_class.mainLoader = _container.getElement('div[class=loaderA]');
			_class.tempLoader = _container.getElement('div[class=loaderB]');
			_class.label 	  = _container.getElement('span[class=label]');
			_class.arrowLeft  = _container.getElement('div[class=arrowLeft]');
			_class.arrowRight = _container.getElement('div[class=arrowRight]');				
			_class.initializeCalendarFunctions();
			
			//Prefill/load picker date elements
			if(_class.picker) {
				if($type(_class.prefillDate) == 'object' && _class.getInputDate(_class.prefillDate)) _class.pick(_class.prefillDate);
				else if(_class.prefillDate == true) _class.pick(JSON.decode(_class.label.getProperty('date')));
			}
		}, _container);
	},
	
	initializeCalendarFunctions: function() {
		this.resetArrows();
		
		//Retrieve data (label, timestamp etc) which are stored as a Json string in the table attribute summary
		var vars = JSON.decode(this.mainLoader.getElement('table').getProperty('summary'));
		var _class = this; 
		
		//Change the label
		this.label.removeClass('noHover').set('html', vars.label)
			.onclick = vars.parent ? function() { _class.u(vars.parent, 'limitDay=' + _class.limitDay + '&ts=' + vars.ts + '&parent=' + vars.current, function() { _class.fade() }) } : null;
			
		//Hide arrows if necessary and add arrow click events
		if(vars.hide_left_arrow) this.hideLeftArrow();
		else if(vars.hide_right_arrow) this.hideRightArrow();
		
		this.arrowLeft.onclick  = function() { _class.u(vars.current, 'limitDay=' + _class.limitDay + '&ts=' + vars.pr_ts, function() { _class.slideLeft() }) }
		this.arrowRight.onclick = function() { _class.u(vars.current, 'limitDay=' + _class.limitDay + '&ts=' + vars.nx_ts, function() { _class.slideRight() }) }		
		
		//Add cell click events
		var clickables = this.mainLoader.getElements('td');
		switch(vars.current) {
			case 'month':
				if(this.picker) {
					clickables.each(function(_clickable) {
						_clickable.onclick = function() {						
							if (!_class.limitDay || _clickable.hasClass("dued"))
							{
								if (_class.pick(JSON.decode(_clickable.getProperty('date'))))
								{							
									_class.mainLoader.getElements('td').each(function(_clickable) { _clickable.removeClass('selected') });
									this.addClass('selected');
								}
							} 
						}
					});
				}
				break;
			case 'year':
				clickables.each(function(_clickable) {
					_clickable.onclick = function() { _class.u('month', 'limitDay=' + _class.limitDay + '&ts=' + _clickable.getProperty('ts'), function() { _class.fade() }) }
				});
				break;
			case 'decade':
				this.label.addClass('noHover');
				clickables.each(function(_clickable) {
					_clickable.onclick = function() { _class.u('year', 'limitDay=' + _class.limitDay + '&ts=' + _clickable.getProperty('ts') + '&m_ts=' + _clickable.getProperty('m_ts'), function() { _class.fade() }) }
				});
				break;
		}
	},
	
	//Ajax updater function which handles all requests
	u: function(_url, _pars, _onComplete, _id) {
		if(!this.loading && !this.transitioning) {
			var _class = this;
			this.loading = true;
			var element = $(_id ? _id : this.tempLoader);
			_pars += '&picker=' + (this.picker ? 1 : 0) + '&startMonday=' + (this.startMonday ? 1 : 0) + '&style=' +  this.style;
			if(this.picker && this.getInputDate()) _pars += '&pickedDate='+ this.getInputDate();
			new Request({ method: 'post',
						  url: this.filePath + _url + '.php',
						  onComplete: function(data) { element.set('html', data); _onComplete(); _class.loading = false; }
						}).send(_pars);
		}
	},
	
	slideLeft: function() {
		var _class = this;
		this.transitioning = true;	
		this.tempLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition }).tween('margin-left', [-164, 0]);
		this.mainLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition, onComplete: function() { _class.transitioning = false } })
			.tween('margin-left', [0, 164]);
		this.switchLoaders();
	},
	
	slideRight: function() {
		var _class = this;
		this.transitioning = true;
		this.mainLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition }).tween('margin-left', [0, -164]);
		this.tempLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition, onComplete: function() { _class.transitioning = false } })
			.tween('margin-left', [164, 0]);
		this.switchLoaders();
	},
	
	fade: function(overRuleTrans) {
		var _class = this;
		this.transitioning = overRuleTrans ? false : true;
		this.tempLoader.setStyles({'opacity': 0, 'margin-left': 0});
		this.mainLoader.set('tween', { duration: this.fadeDuration, transition: this.transition}).fade('out');
		this.tempLoader.set('tween', { duration: this.fadeDuration, transition: this.transition, 
			onComplete: function() { 
					_class.tempLoader.setStyles({'opacity': 1, 'margin-left': -999});
					_class.transitioning = false;
				} 
			}).fade('in');
		this.switchLoaders();
	},
	
	switchLoaders: function() {
		this.mainLoader = this.mainLoader.className == 'loaderA' ? this.container.getElement('div[class=loaderB]') : this.container.getElement('div[class=loaderA]');
		this.tempLoader = this.tempLoader.className == 'loaderA' ? this.container.getElement('div[class=loaderB]') : this.container.getElement('div[class=loaderA]');
		this.initializeCalendarFunctions();
	},
	
	resetArrows: function() {
		this.arrowLeft.setStyle('visibility', 'visible');
		this.arrowRight.setStyle('visibility', 'visible');
	},
	
	hideLeftArrow: function() {
		this.arrowLeft.setStyle('visibility', 'hidden');
	},
	
	hideRightArrow: function() {
		this.arrowRight.setStyle('visibility', 'hidden');
	} 
});

var vlaDatePicker = new Class({
	Extends: vlaCalendar,
	
	'separateInput': false,
	'prefillDate': true,
	'linkWithInput': true,
	'leadingZero': true,
	'twoDigitYear': false,
	'separator': '/',
	'format': 'd/m/y',
	'openWith': null,
	'alignX': 'right',
	'alignY': 'inputTop',
	'offset': { 'x': 0, 'y': 0 },
	'style': '',
	'ieTransitionColor' : '#ffffff',
	'toggleDuration': 350,
	
	initialize: function(_element, _options) {
		//Add the provided options to this object by extending
		if(_options) $extend(this, _options);
		
		this.element = $(_element);
		if(!this.element) throw 'No (existing) element to create a datepicker for specified: new vlaDatePicker(ELEMENT, [options])';
		this.element.store("calendar-obj", this);
		//Check if the user wants multiple input
		if(this.separateInput) {
			this.element.day   = this.element.getElement('input[name='+ this.separateInput.day +']');
			this.element.month = this.element.getElement('input[name='+ this.separateInput.month +']');
			this.element.year  = this.element.getElement('input[name='+ this.separateInput.year +']');
		}
		
		//Create the picker and calendar and inject in in the body
		this.picker = new Element('div', { 'class': 'vlaCalendarPicker' + (this.style != '' ? ' ' + this.style : '') }).injectTop($(document.body));
		this.pickerContent = new Element('div', { 'class': 'pickerBackground' }).injectTop(this.picker);
		this.parent(this.pickerContent);
		
		//Add events for showing and hiding the picker
		var _class = this;
		(this.openWith ? $(this.openWith) : this.element)
			.addEvent('focus',  function() { _class.show(); })
			.addEvent('click',  function() { _class.openWith ? _class.toggle() : _class.show() })
			.addEvent('change', function() { _class.hide(); });
		
		//If the datepicker is visible an outside click makes it hide
		document.addEvent('mousedown', function(e) { if(_class.outsideHide && _class.outsideClick(e, _class.picker)) _class.hide() });
		
		//linkWithInput
		if(this.linkWithInput) {
			if(this.separateInput) {
				this.element.day.addEvent('keyup',  function() { _class.linkedUpdate() });
				this.element.month.addEvent('keyup',  function() { _class.linkedUpdate() });
				this.element.year.addEvent('keyup',  function() { _class.linkedUpdate() });
			} else {
				this.element.addEvent('keyup',  function() { _class.linkedUpdate() });
			}
		}
		
		this.visible = false;
		this.outsideHide = false;
	},
	
	//Position the picker
	position: function() {
		var top, left;
		
		switch(this.alignX) {
			case 'left':
				left = this.element.getLeft();
				break;
			case 'center':
				var pickerMiddle = this.pickerContent.getStyle('width').toInt() / 2;
				if(pickerMiddle == 0) pickerMiddle = 83;
				left = this.element.getLeft() + (this.element.getSize().x / 2) - pickerMiddle -
						((parseInt(this.pickerContent.getStyle('padding-left')) + parseInt(this.pickerContent.getStyle('padding-right'))) / 2);
				break;
			case 'right': default:
				left = this.element.getLeft() + this.element.getSize().x;
				break;
		}
		
		switch(this.alignY) {
			case 'bottom':
				top = this.getPos(this.element).y + this.element.getSize().y;
				break;
			case 'top': 
				top = this.getPos(this.element).y - parseInt(this.pickerContent.getStyle('height')) - 
					(parseInt(this.pickerContent.getStyle('padding-top')) + parseInt(this.pickerContent.getStyle('padding-bottom')));
				break;
			case 'inputTop': default:
				top = this.getPos(this.element).y;
		}
		
		if(this.isNumber(this.offset.x)) left += this.offset.x;
		if(this.isNumber(this.offset.y)) top += this.offset.y;
		
		this.picker.setStyles({ 'top': top, 'left': left });
	},
	
	show: function() {
		this.position();
		if(!this.visible) {
			this.visible = true;
			var _class = this;
			this.picker.setStyles({ 'opacity': 0, 'display': 'inline' });
			if(Browser.Engine.trident5) this.picker.setStyle('background-color', this.ieTransitionColor); //Ugly transition fix for IE7
			this.picker.set('tween', { onComplete: function() { 
					if(Browser.Engine.trident5) _class.picker.setStyle('background-color', 'transparent');
					_class.outsideHide = true; 
				}, duration: this.toggleDuration }).fade('in');
		}
	},
	
	hide: function() {
		if(this.visible) {
			this.visible = false;
			var _class = this;
			if(Browser.Engine.trident5) this.picker.setStyle('background-color', this.ieTransitionColor); //Ugly transition fix for IE7
			this.picker.set('tween', { onComplete: function() { _class.picker.setStyle('display', 'none'); _class.outsideHide = false; }, duration: this.toggleDuration }).fade('out');
		}
	},
	
	toggle: function() {
		if(this.visible) this.hide();
		else this.show();
	},
	
	pick: function(_date) {
		if(this.leadingZero) {
			if(_date.day < 10)   _date.day = '0' + Number(_date.day);
			if(_date.month < 10) _date.month = '0' + Number(_date.month);
		}
		if(this.twoDigitYear) _date.year = _date.year.toString().substring(2, 4);
		
		if(this.separateInput) {
			if(this.element.day)   this.element.day.set('value', _date.day);
			if(this.element.month) this.element.month.set('value', _date.month);
			if(this.element.year)  this.element.year.set('value', _date.year);
			this.hide();
		} else {
		  switch(this.format) {
				case "m/d/y": this.element.set('value', _date.month + this.separator + _date.day + this.separator + _date.year); break;
				case "y/m/d": this.element.set('value', _date.year + this.separator + _date.month + this.separator + _date.day); break;
				case "y/d/m": this.element.set('value', _date.year + this.separator +  _date.day + this.separator + _date.month); break;
				case "d/m/y": default: this.element.set('value', _date.day + this.separator + _date.month + this.separator + _date.year);
			}
			this.hide();
		}
		return true;
	},
	
	getInputDate: function(_date) {
		var day, month, year;
				
		if(_date) {	
			day = Number(_date.day);
			month = Number(_date.month);
			year = Number(_date.year);
		} else if(this.separateInput) {
			day = this.element.day.get('value').toInt();
			month = this.element.month.get('value').toInt();
			year = this.element.year.get('value').toInt();
		} else {
			var date = this.element.get('value').split(this.separator);
			
      if(date.length != 3) return null;
			switch(this.format) {
				case "m/d/y": day = date[1]; month = date[0]; year = date[2]; break;
				case "y/m/d": day = date[2]; month = date[1]; year = date[0]; break;
				case "y/d/m": day = date[1]; month = date[2]; year = date[0]; break;
				case "d/m/y": default: day = date[0]; month = date[1]; year = date[2];
			}
		}
		
		if( !this.isNumber(day) || !this.isNumber(month) || !this.isNumber(year) ||	day == 0 || month == 0 || year == '0' ||
		    (this.twoDigitYear && year > 99) || (!this.twoDigitYear && year < 1979) || (!this.twoDigitYear && year > 2030) || month > 12 || day > 31 ) return null;
		
		if(this.twoDigitYear && this.isNumber(year) && year < 100) {
			year = year.toInt();
			if(year < 10) year = '200'+  year;
			else if(year < 70) year = '20'+  year;
			else if(year > 69) year = '19'+  year;
			else year = new Date().getFullYear();
		}
		
		return day +'/'+ month +'/'+ year;
	},
	
	//This function is being called on keyup event if linkWithInput is set to true and when a date is picked
	//If the full date is inserted the picker will change itself to that specific date (month view)
	linkedUpdate: function() {
		var _class = this;
		var date = this.getInputDate();
		if(date && this.pickedDate != date) {
			this.u('month', 'limitDay=' + _class.limitDay + '&gotoPickedDate=1', function() { _class.fade(true) });
			this.pickedDate = date;
		}
		return true;
	},
	
	outsideClick: function(_event, _element) {
		var mousePos = this.getMousePos(_event);
		var elementData = _element.getCoordinates();
		return (mousePos.x > elementData.left && mousePos.x < (elementData.left + elementData.width)) &&
			   (mousePos.y > elementData.top  && mousePos.y < (elementData.top + elementData.height)) ? false : true;
	},
	
	getMousePos: function(_event) {
		if(document.all) {
			return { 'x': window.event.clientX + window.getScrollLeft(),
					 'y': window.event.clientY + window.getScrollTop() };
		} else {
			return { 'x': _event.page['x'],
					 'y': _event.page['y'] };
		}
	},
	
	isNumber: function(_number) {
		if(_number == '') return false;
		return (_number >= 0) || (_number < 0) ? true : false;
	},
	
	//Retrieving positition funtions (like getCoordinates, getTop etc) don't seem to return correct values in some situations in mootools 1.2; 
	//Opera returns wrong values, IE returns too small values. This function returns the correct coordinates.
	getPos: function(_element) { 
		var x, y = 0;
		if(_element.offsetParent) {
			do {
				x += _element.offsetLeft;
				y += _element.offsetTop;
			} while(_element = _element.offsetParent);
		} else if(_element.x) {
			x += _element.x;
			y += _element.y;
		}
		return { 'x': x, 'y': y };
	}
});

var fromtoCalendar = new Class({	
	Extends: vlaCalendar,
	
	'separateInput': false,
	'prefillDate': false,
	'linkWithInput': true,
	'leadingZero': true,
	'twoDigitYear': false,
	'separator': '/',
	'format': 'd/m/y',
	'openWith': null,
	'alignX': 'right',
	'alignY': 'inputTop',
	'offset': { 'x': 0, 'y': 0 },
	'style': '',
	'ieTransitionColor' : '#ffffff',
	'toggleDuration': 350,
	'startMonday': true,
	greaterThen: null,
	lowerThen: null,
		
	initialize: function(_element, _options) {
		//Add the provided options to this object by extending
		if(_options) $extend(this, _options);
		
		this.element = $(_element);
		if(!this.element) throw 'No (existing) element to create a datepicker for specified: new vlaDatePicker(ELEMENT, [options])';
		this.element.store('calendar', this);
		
		if(this.greaterThen) this.greaterThen = $(this.greaterThen);
		if(this.lowerThen) this.lowerThen = $(this.lowerThen); 
		
		//Check if the user wants multiple input
		if(this.separateInput) {
			this.element.day   = this.element.getElement('input[name='+ this.separateInput.day +']');			
			this.element.month = this.element.getElement('input[name='+ this.separateInput.month +']');
			this.element.year  = this.element.getElement('input[name='+ this.separateInput.year +']');
		}
		
		//Create the picker and calendar and inject in in the body
		this.picker = new Element('div', { 'class': 'inplace vlaCalendarPicker' + (this.style != '' ? ' ' + this.style : '') }).inject(this.element, 'bottom');
		this.pickerContent = new Element('div', { 'class': 'pickerBackground' }).inject(this.picker, 'top');
		this.parent(this.pickerContent);
		
		//Add events for showing and hiding the picker
		var _class = this;
			
		//linkWithInput
		if(this.linkWithInput) {
			if(this.separateInput) {
				this.element.day.addEvent('keyup',  function() { _class.linkedUpdate() });
				this.element.month.addEvent('keyup',  function() { _class.linkedUpdate() });
				this.element.year.addEvent('keyup',  function() { _class.linkedUpdate() });
			} else {
				this.element.addEvent('keyup',  function() { _class.linkedUpdate() });
			}
		}
		
		this.picker.setStyles({ 'opacity': 0, 'display': 'block', 'visibility': 'visible', 'opacity' : 1 });
		
		this.visible = true;
		this.outsideHide = false;
	},
	
	isNumber: function(_number) {
		if(_number == '') return false;
		return (_number >= 0) || (_number < 0) ? true : false;
	},
	
	hide: function() {},
	

	pick: function(_date) {
		if (this.greaterThen)
		{
			var cal = this.greaterThen.retrieve('calendar');
			var dta = cal.getInputDateObj();
			var ts1 = Number(dta.y)*10000 + Number(dta.m) * 100 + Number(dta.d);			
			var ts2 = Number(_date.year)*10000 + Number(_date.month) * 100 + Number(_date.day);
			if (ts1 > ts2)
			{
				alert("Dátum ukončenia musí nasledovať po dátume začiatku.");
				return false;
			} 			
		}
		
		if (this.lowerThen)
		{
			var cal = this.lowerThen.retrieve('calendar');
			var dta = cal.getInputDateObj();
			var ts1 = Number(dta.y)*10000 + Number(dta.m) * 100 + Number(dta.d);			
			var ts2 = Number(_date.year)*10000 + Number(_date.month) * 100 + Number(_date.day);
			
			if (ts1 < ts2)
			{
				// alert("Dátum začiatku nemôže nasledovať po dátume ukončenia.");				
				var odate = new Date();
				
				odate.setUTCFullYear(_date.year);
				odate.setUTCMonth(Number(_date.month)-1);
				odate.setUTCDate(_date.day);
				var x = Number(odate.getTime());
				odate.setTime(x + 518400000);
				
				var dt = {day: odate.getUTCDate(), month: odate.getUTCMonth()+1, year: odate.getUTCFullYear()};
										
				cal.pickedDate = dta.day + '/' + dta.month + '/' + dta.year;		
				cal.pick.run(dt, cal);				
				cal.linkedUpdate.run(null, cal);
				return true;
			} 			
		}
		
		if(this.leadingZero) {
			if(_date.day < 10)   _date.day = '0' + Number(_date.day);
			if(_date.month < 10) _date.month = '0' + Number(_date.month);
		}
		if(this.twoDigitYear) _date.year = _date.year.toString().substring(2, 4);
		
		if(this.separateInput) {
			if(this.element.day)   this.element.day.set('value', _date.day);
			if(this.element.month) this.element.month.set('value', _date.month);
			if(this.element.year)  this.element.year.set('value', _date.year);				
		} else {
		  switch(this.format) {
				case "m/d/y": this.element.set('value', _date.month + this.separator + _date.day + this.separator + _date.year); break;
				case "y/m/d": this.element.set('value', _date.year + this.separator + _date.month + this.separator + _date.day); break;
				case "y/d/m": this.element.set('value', _date.year + this.separator +  _date.day + this.separator + _date.month); break;
				case "d/m/y": default: this.element.set('value', _date.day + this.separator + _date.month + this.separator + _date.year);
			}
		}
		
		return true;
	},
	
	getInputDate: function(_date) {
		var o = this.getInputDateObj(_date);
		return o.d +'/'+ o.m +'/'+ o.y;
	},
	
	getInputDateObj: function(_date) {
		var day, month, year;
				
		if(_date) {	
			day = Number(_date.day);
			month = Number(_date.month);
			year = Number(_date.year);
		} else if(this.separateInput) {
			day = this.element.day.get('value').toInt();
			month = this.element.month.get('value').toInt();
			year = this.element.year.get('value').toInt();
		} else {
			var date = this.element.get('value').split(this.separator);
			
      if(date.length != 3) return null;
			switch(this.format) {
				case "m/d/y": day = date[1]; month = date[0]; year = date[2]; break;
				case "y/m/d": day = date[2]; month = date[1]; year = date[0]; break;
				case "y/d/m": day = date[1]; month = date[2]; year = date[0]; break;
				case "d/m/y": default: day = date[0]; month = date[1]; year = date[2];
			}
		}
		
		if( !this.isNumber(day) || !this.isNumber(month) || !this.isNumber(year) ||	day == 0 || month == 0 || year == '0' ||
		    (this.twoDigitYear && year > 99) || (!this.twoDigitYear && year < 1979) || (!this.twoDigitYear && year > 2030) || month > 12 || day > 31 ) return null;
		
		if(this.twoDigitYear && this.isNumber(year) && year < 100) {
			year = year.toInt();
			if(year < 10) year = '200'+  year;
			else if(year < 70) year = '20'+  year;
			else if(year > 69) year = '19'+  year;
			else year = new Date().getFullYear();
		}
		
		return {d: day, m: month, y: year};
	},
	
	//This function is being called on keyup event if linkWithInput is set to true and when a date is picked
	//If the full date is inserted the picker will change itself to that specific date (month view)
	linkedUpdate: function() {
		var _class = this;
		var date = this.getInputDate();
		if(date && this.pickedDate != date) {
			this.u('month', 'gotoPickedDate=1&limitDay='+this.limitDay, function() { _class.fade(true) });
			this.pickedDate = date;
		}
		return true;
	}
		
		
});


/**
 * 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(document.body);
			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;
            return !!(this.options.autoSubmit);  
          }                               
					 
					if (this.selected && this.visible) {
						this.choiceSelect(this.selected);
            if (!!(this.options.autoSubmit)) this.doChange();      				
					  return !!(this.options.autoSubmit);		            
					}	
					else {                    
            this.fireEvent('onPressedEnter', [this.element, this.selected, this.opted, this.opted]);
            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, key){
				var choice = new Element('li', {'html': this.markQueryValue(token)});
				choice.inputValue = token;
				choice.inputKey = key;
				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());
	}

});

/**
 * SqueezeBox - Expandable Lightbox
 *
 * Allows to open various content as modal,
 * centered and animated box.
 *
 * Dependencies: MooTools 1.2
 *
 * Inspired by
 *  ... Lokesh Dhakar	- The original Lightbox v2
 *
 * @version		1.1 rc4
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var SqueezeBox = {

	presets: {
		onOpen: $empty,
		onClose: $empty,
		onUpdate: $empty,
		onResize: $empty,
		onMove: $empty,
		onShow: $empty,
		onHide: $empty,
		size: {x: 600, y: 450},
		sizeLoading: {x: 200, y: 150},
		marginInner: {x: 20, y: 20},
		marginImage: {x: 50, y: 75},
		handler: false,
		target: null,
		closable: true,
		closeBtn: true,
		zIndex: 65555,
		overlayOpacity: 0.7,
		classWindow: '',
		classOverlay: '',
		overlayFx: {},
		resizeFx: {},
		contentFx: {},
		parse: false, // 'rel'
		parseSecure: false,
		shadow: true,
		document: null,
		ajaxOptions: {}
	},

	initialize: function(presets) {
		if (this.options) return this;

		this.presets = $merge(this.presets, presets);
		this.doc = this.presets.document || document;
		this.options = {};
		this.setOptions(this.presets).build();
		this.bound = {
			window: this.reposition.bind(this, [null]),
			scroll: this.checkTarget.bind(this),
			close: this.close.bind(this),
			key: this.onKey.bind(this)
		};
		this.isOpen = this.isLoading = false;
		return this;
	},

	build: function() {
		this.overlay = new Element('div', {
			id: 'sbox-overlay',
			styles: {display: 'none', zIndex: this.options.zIndex}
		});
		this.win = new Element('div', {
			id: 'sbox-window',
			styles: {display: 'none', zIndex: this.options.zIndex + 2}
		});
		if (this.options.shadow) {
			if (Browser.Engine.webkit420) {
				this.win.setStyle('-webkit-box-shadow', '0 0 10px rgba(0, 0, 0, 0.7)');
			} else if (!Browser.Engine.trident4) {
				var shadow = new Element('div', {'class': 'sbox-bg-wrap'}).inject(this.win);
				var relay = function(e) {
					this.overlay.fireEvent('click', [e]);
				}.bind(this);
				['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
					new Element('div', {'class': 'sbox-bg sbox-bg-' + dir}).inject(shadow).addEvent('click', relay);
				});
			}
		}
		this.content = new Element('div', {id: 'sbox-content'}).inject(this.win);
		this.closeBtn = new Element('a', {id: 'sbox-btn-close', href: '#'}).inject(this.win);
		this.fx = {
			overlay: new Fx.Tween(this.overlay, $merge({
				property: 'opacity',
				onStart: Events.prototype.clearChain,
				duration: 250,
				link: 'cancel'
			}, this.options.overlayFx)).set(0),
			win: new Fx.Morph(this.win, $merge({
				onStart: Events.prototype.clearChain,
				unit: 'px',
				duration: 750,
				transition: Fx.Transitions.Quint.easeOut,
				link: 'cancel',
				unit: 'px'
			}, this.options.resizeFx)),
			content: new Fx.Tween(this.content, $merge({
				property: 'opacity',
				duration: 250,
				link: 'cancel'
			}, this.options.contentFx)).set(0)
		};
		$(this.doc.body).adopt(this.overlay, this.win);
	},

	assign: function(to, options) {
		return ($(to) || $$(to)).addEvent('click', function() {
			return !SqueezeBox.fromElement(this, options);
		});
	},
	
	open: function(subject, options) {
		this.initialize();

		if (this.element != null) this.trash();
		this.element = $(subject) || false;
		
		this.setOptions($merge(this.presets, options || {}));
		
		if (this.element && this.options.parse) {
			var obj = this.element.getProperty(this.options.parse);
			if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
		}
		this.url = ((this.element) ? (this.element.get('href')) : subject) || this.options.url || '';

		this.assignOptions();
		
		var handler = handler || this.options.handler;
		if (handler) return this.setContent(handler, this.parsers[handler].call(this, true));
		var ret = false;
		return this.parsers.some(function(parser, key) {
			var content = parser.call(this);
			if (content) {
				ret = this.setContent(key, content);
				return true;
			}
			return false;
		}, this);
	},
	
	fromElement: function(from, options) {
		return this.open(from, options);
	},

	assignOptions: function() {
		this.overlay.set('class', this.options.classOverlay);
		this.win.set('class', this.options.classWindow);
		if (Browser.Engine.trident4) this.win.addClass('sbox-window-ie6');
	},

	close: function(e) {
		var stoppable = ($type(e) == 'event');
		if (stoppable) e.stop();
		if (!this.isOpen || (stoppable && !$lambda(this.options.closable).call(this, e))) return this;
		this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this));
		this.win.setStyle('display', 'none');
		this.fireEvent('onClose', [this.content]);
		this.trash();
		this.toggleListeners();
		this.isOpen = false;
		return this;
	},

	trash: function() {
		this.element = this.asset = null;
		this.content.empty();
		this.options = {};
		this.removeEvents().setOptions(this.presets).callChain();
	},

	onError: function() {
		this.asset = null;
		this.setContent('string', this.options.errorMsg || 'An error occurred');
	},

	setContent: function(handler, content) {
		if (!this.handlers[handler]) return false;
		this.content.className = 'sbox-content-' + handler;
		this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content));
		if (this.overlay.retrieve('opacity')) return this;
		this.toggleOverlay(true);
		this.fx.overlay.start(this.options.overlayOpacity);
		return this.reposition();
	},

	applyContent: function(content, size) {
		if (!this.isOpen && !this.applyTimer) return;
		this.applyTimer = $clear(this.applyTimer);
		this.hideContent();
		if (!content) {
			this.toggleLoading(true);
		} else {
			if (this.isLoading) this.toggleLoading(false);
			this.fireEvent('onUpdate', [this.content], 20);
		}
		if (content) {
			if (['string', 'array'].contains($type(content))) this.content.set('html', content);
			else if (!this.content.hasChild(content)) this.content.adopt(content);
		}
		this.callChain();
		if (!this.isOpen) {
			this.toggleListeners(true);
			this.resize(size, true);
			this.isOpen = true;
			this.fireEvent('onOpen', [this.content]);
		} else {
			this.resize(size);
		}
	},

	resize: function(size, instantly) {
		this.showTimer = $clear(this.showTimer || null);
		var box = this.doc.getSize(), scroll = this.doc.getScroll();
		this.size = $merge((this.isLoading) ? this.options.sizeLoading : this.options.size, size);
		var to = {
			width: this.size.x,
			height: this.size.y,
			left: (scroll.x + (box.x - this.size.x - this.options.marginInner.x) / 2).toInt(),
			top: (scroll.y + (box.y - this.size.y - this.options.marginInner.y) / 2).toInt()
		};
		this.hideContent();
		if (!instantly) {
			this.fx.win.start(to).chain(this.showContent.bind(this));
		} else {
			this.win.setStyles(to).setStyle('display', '');
			this.showTimer = this.showContent.delay(50, this);
		}
		return this.reposition();
	},

	toggleListeners: function(state) {
		var fn = (state) ? 'addEvent' : 'removeEvent';
		this.closeBtn[fn]('click', this.bound.close);
		this.overlay[fn]('click', this.bound.close);
		this.doc[fn]('keydown', this.bound.key)[fn]('mousewheel', this.bound.scroll);
		this.doc.getWindow()[fn]('resize', this.bound.window)[fn]('scroll', this.bound.window);
	},

	toggleLoading: function(state) {
		this.isLoading = state;
		this.win[(state) ? 'addClass' : 'removeClass']('sbox-loading');
		if (state) this.fireEvent('onLoading', [this.win]);
	},

	toggleOverlay: function(state) {
		var full = this.doc.getSize().x;
		this.overlay.setStyle('display', (state) ? '' : 'none');
		this.doc.body[(state) ? 'addClass' : 'removeClass']('body-overlayed');
		if (state) {
			this.scrollOffset = this.doc.getWindow().getSize().x - full;
			this.doc.body.setStyle('margin-right', this.scrollOffset);
		} else {
			this.doc.body.setStyle('margin-right', '');
		}
	},

	showContent: function() {
		if (this.content.get('opacity')) this.fireEvent('onShow', [this.win]);
		this.fx.content.start(1);
	},

	hideContent: function() {
		if (!this.content.get('opacity')) this.fireEvent('onHide', [this.win]);
		this.fx.content.cancel().set(0);
	},

	onKey: function(e) {
		switch (e.key) {
			case 'esc': this.close(e);
			case 'up': case 'down': return false;
		}
	},

	checkTarget: function(e) {
		return this.content.hasChild(e.target);
	},

	reposition: function() {
		var size = this.doc.getSize(), scroll = this.doc.getScroll(), ssize = this.doc.getScrollSize();
		this.overlay.setStyles({
			width: ssize.x + 'px',
			height: ssize.y + 'px'
		});
		this.win.setStyles({
			left: (scroll.x + (size.x - this.win.offsetWidth) / 2 - this.scrollOffset).toInt() + 'px',
			top: (scroll.y + (size.y - this.win.offsetHeight) / 2).toInt() + 'px'
		});
		return this.fireEvent('onMove', [this.overlay, this.win]);
	},

	removeEvents: function(type){
		if (!this.$events) return this;
		if (!type) this.$events = null;
		else if (this.$events[type]) this.$events[type] = null;
		return this;
	},

	extend: function(properties) {
		return $extend(this, properties);
	},

	handlers: new Hash(),

	parsers: new Hash()

};

SqueezeBox.extend(new Events($empty)).extend(new Options($empty)).extend(new Chain($empty));

SqueezeBox.parsers.extend({

	image: function(preset) {
		return (preset || (/\.(?:jpg|png|gif)$/i).test(this.url)) ? this.url : false;
	},

	clone: function(preset) {
		if ($(this.options.target)) return $(this.options.target);
		if (this.element && !this.element.parentNode) return this.element;
		var bits = this.url.match(/#([\w-]+)$/);
		return (bits) ? $(bits[1]) : (preset ? this.element : false);
	},

	ajax: function(preset) {
		return (preset || (this.url && !(/^(?:javascript|#)/i).test(this.url))) ? this.url : false;
	},

	iframe: function(preset) {
		return (preset || this.url) ? this.url : false;
	},

	string: function(preset) {
		return true;
	}
});

SqueezeBox.handlers.extend({

	image: function(url) {
		var size, tmp = new Image();
		this.asset = null;
		tmp.onload = tmp.onabort = tmp.onerror = (function() {
			tmp.onload = tmp.onabort = tmp.onerror = null;
			if (!tmp.width) {
				this.onError.delay(10, this);
				return;
			}
			var box = this.doc.getSize();
			box.x -= this.options.marginImage.x;
			box.y -= this.options.marginImage.y;
			size = {x: tmp.width, y: tmp.height};
			for (var i = 2; i--;) {
				if (size.x > box.x) {
					size.y *= box.x / size.x;
					size.x = box.x;
				} else if (size.y > box.y) {
					size.x *= box.y / size.y;
					size.y = box.y;
				}
			}
			size.x = size.x.toInt();
			size.y = size.y.toInt();
			this.asset = $(tmp);
			tmp = null;
			this.asset.width = size.x;
			this.asset.height = size.y;
			this.applyContent(this.asset, size);
		}).bind(this);
		tmp.src = url;
		if (tmp && tmp.onload && tmp.complete) tmp.onload();
		return (this.asset) ? [this.asset, size] : null;
	},

	clone: function(el) {
		if (el) return el.clone();
		return this.onError();
	},

	adopt: function(el) {
		if (el) return el;
		return this.onError();
	},

	ajax: function(url) {		
		var options = this.options.ajaxOptions || {};
		this.asset = new Request.HTML($merge({
			method: 'get',
			evalScripts: false
		}, this.options.ajaxOptions)).addEvents({
			onSuccess: function(resp) {
				this.applyContent(resp);
				if (options.evalScripts !== null && !options.evalScripts) $exec(this.asset.response.javascript);
				this.fireEvent('onAjax', [resp, this.asset]);
				this.asset = null;
			}.bind(this),
			onFailure: this.onError.bind(this)
		});
		this.asset.send.delay(10, this.asset, [{url: url}]);
	},

	iframe: function(url) {		
		this.asset = new Element('iframe', $merge({
			src: url,
			frameBorder: 0,
			width: this.options.size.x,
			height: this.options.size.y
		}, this.options.iframeOptions));
		if (this.options.iframePreload) {
			this.asset.addEvent('load', function() {
				this.applyContent(this.asset.setStyle('display', ''));
			}.bind(this));
			this.asset.setStyle('display', 'none').inject(this.content);
			return false;
		}
		return this.asset;
	},

	string: function(str) {
		return str;
	}

});

SqueezeBox.handlers.url = SqueezeBox.handlers.ajax;
SqueezeBox.parsers.url = SqueezeBox.parsers.ajax;
SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone;

var valstrings = {
  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"
};

function isRadioChecked(elem, errorfunc, state) {
  var numChecked = 0;
  
  for(var idx=0;idx<elem.length;idx++) {
    el = elem[idx]; 
    if (el.checked)
    {
      if (el.value == "#other#")
      {
      	var inp = el.form.getElement("input[name=" + el.name + "_OTHER]");
      	if (inp)
      	{
      	  if (isNotEmpty(inp, errorfunc))
      	  {
      	  	numChecked++;      	  	
      	  }   
      	  else 
      	  {
      	    if (state)
      	    	state[el.name] = inp;
      	    return false;
      	  }
      	}
      }
      else
        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) {
    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) {
    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) {
    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) {
    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) {
	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) {
    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, state) {
  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) && isNumber(elem, errorfunc);
      
    if (bres && elem.hasClass('integer'))
      bres = bres && isNotEmpty(elem, errorfunc) && isInteger(elem, errorfunc);
    
    if (bres && elem.hasClass('numberempty'))
      bres = bres && (isEmpty(elem) || isNumber(elem, errorfunc));
    
    if (bres && elem.hasClass('integerempty'))
      bres = bres && (isEmpty(elem) || isInteger(elem, errorfunc));
      
    if (bres && elem.hasClass('email'))
      bres = bres && isEMailAddr(elem, errorfunc);
         
    if (bres && elem.hasClass('emailempty'))
      bres = bres && (isEmpty(elem) || isEMailAddr(elem, errorfunc)); 

    if (bres && elem.hasClass('psw'))
      bres = bres && isNotEmpty(elem, errorfunc) && isPsw(elem, errorfunc);      
    
    if (bres && elem.hasClass('pswempty'))
      bres = bres && (isEmpty(elem) || isPsw(elem, errorfunc));         
    
    if (bres && elem.hasClass('telefon'))
      bres = bres && isNotEmpty(elem, errorfunc) && isTelefon(elem, errorfunc);
    
    if (bres && elem.hasClass('notempty'))
      bres = bres && isNotEmpty(elem, errorfunc); 
      
    if (bres && elem.hasClass('radionotempty'))
    {      
      if (!state[elem.name])
	  {      
      	state[elem.name] = elem;
        bres = bres && isRadioChecked(elem.form.getElements('input[name='+elem.name+']'), errorfunc, state);
      }
    }
             
    return bres;
  } 
    
  typ = typ.toLowerCase()
  
  if (typ=="number")
    return isNotEmpty(elem, errorfunc) && isNumber(elem, errorfunc);
  else if (typ=="integer")
    return isNotEmpty(elem, errorfunc) && isInteger(elem, errorfunc);
  else if (typ=="email")
    return isEMailAddr(elem, errorfunc);
  else if (typ=="notempty")
    return isNotEmpty(elem, errorfunc);
  else 
    return true;   
}

function validateForm(form, af) {
  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 i = 0;
  while ( result && (i < formElements.length) ) {
    var elem = formElements[i];
  	if (elem.disabled && elem.disabled == true) {
  		i++;
      continue;
  	}
  		
  	state = {};
  		
  		
  	result = result && validateElem(elem, myAlert, state);
  	if (!result) {
  	  if (af) af.defaultForm(form);
  	  if (state[elem.name]) elem = state[elem.name]; 
  	  elem.focus();
  	  elem.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)))
			{
				icon.addClass('valcheck');
				icon.removeClass('valcross');
			}
			else {
				icon.removeClass('valcheck');
				icon.addClass('valcross');
			}
		} 
	},

	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 FrontLogic = {
		__initloginetc_accordion: null,
		InitLoginEtc: function(uid)
		{
			var base = $(uid);
			FrontLogic.__initloginetc_accordion = new Fx.Accordion(base.getElements('.hoverpad'), base.getElements('.wrapper'),
					{trigger: 'click', opacity: false, initialDisplayFx: false, duration: 200});
	
		},
		
		TBD: function()
		{
			alert('Feature not implemented, yet.');
			return false;
		},
		
		_pm_uid : '',
		
		InitDSections: function(uid)
		{
			this._pm_uid = uid;
			var anch =  null;
			if (window.location.hash.length > 1) anch = $(window.location.hash.substr(1));
			if (!anch) anch = $(uid + 'blog').getElement('a.tab');
				
			if (anch) 
			{				
				var key = anch.get('rev');
				FrontLogic.LoadDSection(anch, key);	
			}							
		},
		
		_def_box_options: {
				'0': {}, '4': {}, '3': {},
				'1': { size: { x: 300 , y: 25 }, handler: 'iframe' },
				'2': { size: { x: 640 , y: 400 }, handler: 'iframe' }
		},
		
		InitPreviews: function(uid)
		{
			var base = $(uid);
			SqueezeBox.assign(base.getElements('a[rel=boxed(1)]'), FrontLogic._def_box_options[1]);
			SqueezeBox.assign(base.getElements('a[rel=boxed(2)]'), FrontLogic._def_box_options[2]);			
		},
		
		ShowDSection: function(key) {							
			SqueezeBox.assign(document.getElement('#'+FrontLogic._pm_uid + 'moduletitle').getElements('a[rel^=boxed]'), FrontLogic._def_box_options[key]);
			return false;
		},

		LoadDSection: function(anchor, kind)
		{
			var ael = $(anchor);
			changeHash(ael.get('id'));
			
			$tfn(xindi, this, [ FrontLogic._pm_uid + 'moduletitle', -20, 10, 0 ]);
			$rpc(FrontLogic._pm_uid + ':loadSection', kind, null);
			
			return false;
		},		
		
		ShowEventMedia: function(anchor, key)
		{			
			var base = $(anchor).getParent('div.event');
			if (base) $tfn(xindi, this, [ base.getElement('h4'), -20, 0, 0 ]);
			$rpc(FrontLogic._pm_uid + ':loadMedia', key, null);			
			
			return false;
			
		},
		
		ShowMedia: function(key)
		{
			var div = document.getElementById(FrontLogic._pm_uid + 'media_' + key);					
			var base = div.getParent('div.event');
			// var mediablocks = base.getParent('div.events').getElements('div.eventmedia');
			
			var anchor = base.getElement('a[rel=togglemedia]');
			if (anchor) anchor.hide();
			
			( function() {			
			if (div.hasClass('mh'))
			{
				div.slide('hide');			
				div.removeClass('mh');
				div.slide('in');
				FrontLogic.InitPreviews(div);
			}	
			}).delay(25);
			
			
		},

		SubmitNLSform: function(form, uid) {
			if (validateForm(form)) 
			{
				var em = form.getElement('input[name=email]'), emval = form.getElement('input[name=email_val]');
				if (em.get('value').toLowerCase() != emval.get('value').toLowerCase())
				{
					alert('Check the email address please');
					emval.focus();
					return false;
				}          	
		
				var serialized = serializeForm(form);
				updateForm(form,true);
				$tfn(xindi,this,[uid+'submit',8,8]);
				$rpc(uid+':submit',serialized,null);
			}
		  
			return false;
	    },
		
		InitHomeCar: function(uid)
		{
			var base = document.getElement('#carcomponent');
			
			var current = -1;
			var timer = null;
			var pause = 10000;
						
			var Activate = function(idx, manual) 
			{												
				$clear(timer);
				if (current == idx) 
				{
					if (!manual)
						timer = Activate.delay(pause, this, [(current % 3) + 1, false]);
					return;			
				}
								
				if (current != -1)
				{
					var tab = base.getElement('#cartab'+current);
					var page = base.getElement('#carpage'+current);
					tab.removeClass('active');
					page.fade('out');
					base.getElement('#carpage'+idx).fade('in');
				}
								
				current = idx;
				
				var tab = base.getElement('#cartab'+idx);
				tab.addClass('active');	
				
				if (!manual)
					timer = Activate.delay(pause, this, [(idx % 3)+1, false]);
			}
			
			for(var i=2;i<=3;i++)
			{				
				base.getElement('#carpage'+i).setStyle('opacity', 0);
			}
			
			for(var i=1;i<=3;i++)
			{				
				var tab = base.getElement('#cartab'+i);
				tab.addEvent('mouseenter', Activate.bind(this, [i, true]));
				tab.addEvent('mouseleave', function() { 
					$clear(timer); 
					timer = Activate.delay(pause, this, [(current % 3) + 1, false]);} );
			}
			
			Activate(1);
			
			
		}
		
		
};
