
/*
** Evonux 2005-2007
** Evonux JavaScript Tools (EJST) - version 0.3
**
** tested: IE 6.0, Firefox 1.5, Safari 2.0, Konqueror
**         Mac OS X, Windows XP, Linux
**
** All rights reserved
*/

if (!Evonux)
  Evonux = {};

Evonux.debug = false;

Evonux.SITE_URL = window.location.hostname;
Evonux._include = new Array();
Evonux.trans = new Array();
Evonux.bufferid = 'buffer';
Evonux.loadingId = 'evonux_loading';
Evonux.PIC_DIR = Evonux.SITE_ROOT +'/pic';
Evonux.JS_DIR = Evonux.SITE_ROOT +'/js';
Evonux.mainWrapId = 'wrap';
Evonux.menuCornerRightId = 'menutop_rightcorner';
Evonux.menuCornerLeftId = 'menutop_leftcorner';

Evonux._calcPowerLevel = 0;
Evonux._browser = false;
Evonux._browserv = 0;
Evonux._os = false;
Evonux._id = 0;

Evonux._mouseX = 0;
Evonux._mouseY = 0;

Evonux.Local = {};

// ----------------------------------------------------------------------------
// Standard functions
Evonux.W = function(input)
{ // static
    document.write(input);
}
Evonux.$ = function(id)
{ // static
    if (typeof(id) == 'string')
      return document.getElementById(id);
    return id; // It may be object itself
}
Evonux.Exit = function(code) {throw (code ? code : 'evonux: Evonux.Exit() function called');}
/*
** Dynamically adds a JS script
*/
Evonux.Include = function(src, specialType)
{
    var objHead = document.getElementsByTagName('head')[0];
    if (!objHead) // No head found (should have been found!)
    {
	var objHtml = document.getElementsByTagName('html')[0],
	    objBody = document.getElementsByTagName('body')[0];
	if (objBody) // Else, document is definitely very badly made !
	{
	    objHead = document.createElement('head');
	    objBody.insertBefore(objHead, objBody);
	}
    }
    var objScript = document.createElement('script');
    objScript.type = (specialType ? specialType : 'text/javascript');
    objScript.src = src;
    objHead.appendChild(objScript);
}
/*
** Returns true if file is already included, false else
*/
Evonux.IncludeRegister = function(name)
{
    // Looks for file
    if (Evonux._include[name])
      return true;
    // Registers file
    Evonux._include[name] = true;
    return false;
}
/**
 * Same as Evonux.Include except it writes directly <script>...</script> declaration
 */
Evonux.Require = function(src, specialType)
{
    document.write('<script type="'+ (specialType ? specialType : 'text/javascript') +'" src="'+ src +'"><\/script>');
}
/*
** Returns unique id
*/
Evonux.GetId = function()
{
    return 'evonuxid'+ (Evonux._id++);
}
Evonux.TopParent = function()
{ // static
    docRef = document.getElementsByTagName('body')[0];
    while (docRef.parentNode != null)
      docRef = docRef.parentNode;
    return docRef;
}
Evonux.IsSSL = function()
{
    var re_https = new RegExp('^https', 'i');
    return re_https.test(window.location.href);
}
/*
** Programs an event
*/
if (document.addEventListener)
Evonux.AddEventListener = function(e, handler, obj, useCaption)
{ // static
    if (arguments.length < 4) useCaption = true;
    var _obj = (obj ? obj : window);
    return _obj.addEventListener(e, handler, useCaption);
}
else
Evonux.AddEventListener = function(e, handler, obj, useCaption)
{ // static
    if (arguments.length < 4) useCaption = true;
    if (obj) return obj.attachEvent('on'+ e, handler);
    window.attachEvent('on'+ e, handler);
}
/*
** Cancels an event
*/
if (document.removeEventListener)
Evonux.RemoveEventListener = function(e, handler, obj)
{ // static
    var _obj = (obj ? obj : window.document);
    _obj.removeEventListener(e, handler, true);
}
else
Evonux.RemoveEventListener = function(e, handler, obj)
{ // static
    var _obj = (obj ? obj : window.document);
    _obj.detachEvent('on'+ e, handler);
}
/*
** Stops event propagation
*/
Evonux.StopPropagation = function(e)
{
    e.cancelBubble = true;
    if (e.stopPropagation)
      e.stopPropagation();
}

/*
** Retrieves object that launched event
*/
Evonux.GetEventLauncher = function(e)
{
    var target;

    if (e.target)
      target =  e.target;
    else if (e.srcElement)
      target =  e.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
      target =  target.parentNode;
    return target;
}
Evonux.GetButton = function(e)
{
    var button;
    button = (e.button ? e.button : e.which);
    return button;
}
Evonux.GetKey = function(e)
{
    var key = e.keyCode;
    return key;
}

/*
** Records mouse position
*/
if (document.all)
{
Evonux.RecordMousePosition = function(e)
 { // static
     Evonux._mouseX = e.clientX + document.documentElement.scrollLeft;
     Evonux._mouseY = e.clientY + document.documentElement.scrollTop;
 }
Evonux.GetMouseCoord = function(e)
 { // static
     if (!e) var e = window.event;
     return new Array(e.clientX + document.documentElement.scrollLeft,
		      e.clientY + document.documentElement.scrollTop);
 }
}
else
{
Evonux.RecordMousePosition = function(e)
 { // static
     Evonux._mouseX = e.pageX;
     Evonux._mouseY = e.pageY;
}
Evonux.GetMouseCoord = function(e)
 { // static
     if (!e) var e = window.event;
     return new Array(e.pageX, e.pageY);
 }
}
/*
** Returns an array with size of obj : [width, height]
** Main window if no argument
*/
Evonux.GetObjSize = function(obj)
 {
     if (obj)
       return Array(obj.offsetWidth, obj.offsetHeight);
     var w = window, db = document.documentElement; // document.body
     if (w.innerWidth)
       return Array(w.innerWidth, w.innerHeight);
     return Array(db.offsetWidth, db.offsetHeight); // clientHeight / clientWidth
 }
/*
** Return actual style property for an object (JS, style="" or CSS)
*/
Evonux.GetStyleProp = function(obj, prop)
{
    // IE
    if (obj.currentStyle)
    {
	var re_dash2capital = /-([a-z]{1})/;
	for (k = 0; re_dash2capital.test(prop) && k < 10;k++)
	  prop = prop.replace(re_dash2capital, RegExp.$1.toUpperCase());

	return obj.currentStyle[prop];
    }
    // Gecko
    else if (window.getComputedStyle)
    {
	return document.defaultView.getComputedStyle(obj, null).getPropertyValue(prop);
    }
    // Safari
    else if (document.defaultView)
    {
	if (document.defaultView.getComputedStyle(obj, null))
	{
	  return document.defaultView.getComputedStyle(obj, null).getPropertyValue(prop);
	}
    }
    return false;
}

Evonux.GetOffsetLeftActual = function(obj)
{
    var offsetLeft = 0;
    for (; obj.offsetParent && obj.tagName.toLowerCase() != 'body'; obj = obj.offsetParent)
      offsetLeft += obj.offsetLeft;
    return offsetLeft;
}
Evonux.GetOffsetTopActual = function(obj)
{
    var offsetTop = 0;
    for (; obj.offsetParent && obj.tagName.toLowerCase() != 'body'; obj = obj.offsetParent)
      offsetTop += obj.offsetTop;
    return offsetTop;
}

Evonux.GetOS = function()
{
    if (Evonux._os)
      return Evonux._os;
    if (navigator.userAgent.toLowerCase().indexOf('linux') != -1)
      return (Evonux._os = 'linux');
    if (navigator.userAgent.toLowerCase().indexOf('mac') != -1)
      return (Evonux._os = 'mac');
    if (navigator.userAgent.toLowerCase().indexOf('win') != -1)
      return (Evonux._os = 'win');
    if (navigator.userAgent.toLowerCase().indexOf('bsd') != -1)
      return (Evonux._os = 'bsd');
    return (Evonux._os = 'undefined');
}
Evonux.GetBrowser = function()
{
    if (Evonux._browser)
      return Evonux._browser;
    var nav_name = navigator.userAgent.toLowerCase(),
        b = 'undefined';
    if (window.opera)    // opera
      b = 'opera';
    else if (/msie/.test(nav_name))    // internet explorer
      b = 'msie';
    else if (/firebird/.test(nav_name))    // firebird
      b = 'firebird';
    else if (/firefox/.test(nav_name) || /iceweasel/.test(nav_name))    // firefox
      b = 'firefox';
    else if (/netscape/.test(nav_name))    // netscape
      b = 'netscape';
    else if (/epiphany/.test(nav_name))    // epiphany
      b = 'epiphany';
    else if (/konqueror/.test(nav_name))    // konqueror
      b = 'konqueror';
    else if (/galeon/.test(nav_name))    // galeon
      b = 'galeon';
    else if (/safari|webkit/.test(nav_name))    // safari
      b = 'safari';
    else if (/mozilla/.test(nav_name))    // mozilla
      b = 'mozilla';
    Evonux._browser = b;
    return b;
}
Evonux.GetBrowserVersion = function()
{
    if (Evonux._browserv)
      return Evonux._browserv;
    var nav_name = navigator.userAgent.toLowerCase(),
        b = Evonux.GetBrowser();
    if (b == 'firefox') b = 'firefox|iceweasel';
    var re_version = new RegExp('('+ b +')'+'[\/ ]{1}([0-9\.]+)', 'i');
    re_version.exec(nav_name);
    return Evonux._browserv = RegExp.$2;
}

Evonux.IsIE6 = function ()
{
    return ((Evonux.GetBrowser() == 'msie') && (Evonux.GetBrowserVersion() == '6'));
}

Evonux.TypeOf = function(obj)
{
    var _type = typeof(obj);
    if ((_type == 'object') && obj.type)
      return obj.type;
    return _type;
}
// Calculates available calculation power
Evonux.AvailableCalcPower = function(recalc)
{
    if ((Evonux._calcPowerLevel > 0) && !recalc)
      return Evonux._calcPowerLevel;
    var now = new Date();
    nowMS0 = now.getTime();
    for (k = 1, i = 0; k < 1000; k++)
      i += eval('Math.sqrt(k) + Math.sin(k) + Math.cos(k)');
    now = new Date();
    nowMS = now.getTime() - nowMS0;

    // Fast calc availability : [50,100%]
    if (nowMS <= 150)
      Evonux._calcPowerLevel = Math.floor(100 - ((nowMS / 150) * 50));
    // Low calc availability  : [1,50%]
    else
    {
	if (nowMS > 2000)
	    nowMS = 2000;
	tmp = 50 - ((nowMS / 2000) * 50);
	Evonux._calcPowerLevel = (tmp > 0 ? Math.floor(tmp) : 1);
    }

    return Evonux._calcPowerLevel;
}

Evonux.Deselect = function()
{
    if (document.selection)
      document.selection.empty();
    else if (window.getSelection)
      window.getSelection().removeAllRanges();
}

Evonux.BlockRightClick = function(e)
{
    var b = Evonux.GetButton(e);
    if (b == 2 || b == 3)
      Evonux.StopPropagation(e);
    return false;
}

Evonux.popup = new Array();
Evonux.PopUp = function(url, name, option)
{
    if (arguments.length < 3) option = '';
    if (arguments.length < 2) name = 'popup';
    if (arguments.length < 1) url = 'http://www.evonux.com';
    Evonux.popup[name] = window.open(url, name, option);
    return false;
}
Evonux.GetPopUp = function(name)
{
    if (!name) return Evonux.popup['popup'];
    return Evonux.popup[name];
}

// Always refreshes mouse position record
//Evonux.AddEventListener('mousemove', Evonux.RecordMousePosition, window.document);

// ----------------------------------------------------------------------------
// Misc
Evonux.ObjProps = function(obj)
{
    var output = '';

    for (i in obj)
      output += i +', ';
    return output;
}

Evonux.CSSset = function(objId, prop, value)
{
    eval('Evonux.$(\''+ objId +'\').'+ prop +' = \''+ value +'\'');
    return value;
}

// ----------------------------------------------------------------------------
// Math functions
if (!Math.max)
Math.max = function()
{
    var argv = arguments;
    var argc = argv.length;
    var max = argv[0];
    for (r = 0; r < argc; r++)
      max = (argv[r] > max ? argv[r] : max);
    return max;
}
if (!Math.maxRank)
Math.maxRank = function()
{
    var argv = arguments;
    var argc = argv.length;
    var max = argv[0];
    var max_rank = 0;
    for (r = 0; r < argc; r++)
    if (argv[r] > max)
    {
	max = argv[r];
	max_rank = r;
    }
    return max_rank;
}
if (!Math.min)
Math.min = function()
{
    var argv = arguments;
    var argc = argv.length;
    var min = argv[0];
    for (r = 0; r < argc; r++)
      min = (argv[r] < min ? argv[r] : min);
    return min;
}
if (!Math.minRank)
Math.minRank = function()
{
    var argv = arguments;
    var argc = argv.length;
    var min = argv[0];
    var min_rank = 0;
    for (r = 0; r < argc; r++)
    {
	if (argv[r] < min)
	    {
		min = argv[r];
		min_rank = r;
	    }
    }
    return min_rank;
}
// Returns approximation of float : number of decimals are truncated
if (!Math.floatRound)
Math.floatRound = function(floatNb, decimalLg)
{
    var exp = Math.pow(10, decimalLg);
    return Math.floor(floatNb * exp) / exp;
}
if (!Math.floatMultiply)
Math.FloatMultiply = function(a, b)
{
    var a_int, b_int,
	a_exp, b_exp;
    for (a_exp = 1, a_int = a * a_exp; a_int % 1 > 0; a_exp *= 10, a_int *= 10)
    ;
    for (b_exp = 1, b_int = b * b_exp; b_int % 1 > 0; b_exp *= 10, b_int *= 10)
    ;
    return (a_int * b_int) / (a_exp * b_exp);
}


// ----------------------------------------------------------------------------
// String functions
if (!String.toNb)
String.prototype.toNb = function()
{
    return eval(this);
}

// TODO: recode to avoid using RegExp! It may kill outerscope RegExp results
if (!String.trim)
String.prototype.trim = function()
{
    return this.replace(RegExp('^[ \t\v\f\n\r]+', 'g'), '').replace(RegExp('[ \t\v\f\n\r]+$', 'g'), '');
}

if (!String.wordCount)
String.prototype.wordCount = function()
{
    ;
}

/**
 * Returns a Function object of a string that has form:
 * 'function (arg1 [, arg2 [,...]]) {...}'
 */
if (!String.toFunction)
String.prototype.toFunction = function()
{
    if (this.length < 12) // 12 is length of 'function(){}' (smallest possible function)
      return null;
    if (!window.opera)
    {
      eval('var f = '+ this);
      return f;
    }
    // Opera bugfix
    var str = this.trim(),
        re_function = /^function[ ]*\(([ a-zA-Z0-9_\-,]+)\)[ ]*{[ ]*(.*)[ ]*}$/;
    re_function.exec(str);
    var argv = RegExp.$1.trim().split(','),
        func_body = RegExp.$2;
    // Builds list of arguments
    for (var k = 0; k < argv.length; k++)
      argv[k] = '"'+ argv[k].trim() +'"';

    return eval('new Function('+ argv.join(',') + (argv.length > 0 ? ',' : '') +'"'+ func_body.replace(/"/g, '\"')/*"*/ +'")');
}


/**
 * Calculates strings similarity
 * 0 = equal, the higher is result, the more strings are different
 */
String.prototype.LevenshteinDistance = function (s, t)
{
    var dG = new Array();

    var i; // iterates through s
    var j; // iterates through t
    var s_i; // ith character of s
    var t_j; // jth character of t
    var cost; // cost
    
    // Step 1
    var n = s.length; // length of s
    var m = t.length; // length of t
    if (n == 0)
	return m;
    if (m == 0)
	return n;
    
    // Construct a matrix containing 0..m rows and 0..n columns
    var d = new Array();

    // Step 2
    // Initialize the first row to 0..n.
    // Initialize the first column to 0..m
    for (i = 0; i <= n; i++)
    {
	d[i] = new Array();
	d[i][0] = i;
    }
    
    for (j = 0; j <= m; j++)
	d[0][j] = j;

    // Step 3
    // Examine each character of s (i from 1 to n)
    // Step 4
    // Examine each character of t (j from 1 to m)
    // Step 5
    // Determine cost
    // Step 6
    // Set cell d[i,j] of the matrix equal to the minimum of:
    // a. The cell immediately above plus 1: d[i-1,j] + 1.
    // b. The cell immediately to the left plus 1: d[i,j-1] + 1.
    // c. The cell diagonally above and to the left plus the cost: d[i-1,j-1] + cost

    // Does it ! :
    for (i = 1; i <= n; i++)
    {
	for (j = 1; j <= m; j++)
	    {
		s_i = s.charAt(i - 1);
		t_j = t.charAt(j - 1);
		cost = (s_i == t_j ? 0 : 1);

		d[i][j] = Evonux.Math.Min(d[i-1][j]   + 1,
					  d[i][j-1]   + 1,
					  d[i-1][j-1] + cost);
	    }
    }

    // Step 7
    return d[n][m];
}

if (!String.toSize)
String.prototype.toSize = function()
{
    var size = this.toNb();
    if (size > 1000000000000) // > 1TB
      return Math.floatRound(size / 1000000000000, 2) + 'TB';
    if (size > 1000000000) // > 1GB
      return Math.floatRound(size / 1000000000, 2) + 'GB';
    if (size > 1000000) // > 1MB
      return Math.floatRound(size / 1000000, 2) + 'MB';
    if (size > 1000) // > 1kB
      return Math.floatRound(size / 1000, 2) + 'kB';
    return size + 'B';
}

if (!String.urlencode)
String.prototype.urlencode = function ()
{
    var SAFECHARS = "0123456789" + // Numeric
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
    "abcdefghijklmnopqrstuvwxyz" +
    "-_.!~*'()"; // RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
    
    var plaintext = this;
    var encoded = "";
    for (var i = 0; i < plaintext.length; i++ )
    {
	var ch = plaintext.charAt(i);
	if (ch == " ")
	  encoded += "+";
	else if (SAFECHARS.indexOf(ch) != -1)
	  encoded += ch;
	else
	{
	  var charCode = ch.charCodeAt(0);
	  if (charCode > 255)
	    encoded += "+";
	  else
	  {
	    encoded += "%";
	    encoded += HEX.charAt((charCode >> 4) & 0xF);
	    encoded += HEX.charAt(charCode & 0xF);
	  }
	}
    }
    return encoded;
};

// ----------------------------------------------------------------------------
// RegExp

// Tests if compile function exists
var __re = new RegExp('a', 'i');
if (!__re.compile)
{
	RegExp.prototype.compile = function(source, options)
	{
		var re_g = new RegExp('g', 'i');
		var re_i = new RegExp('i', 'i');
		//this = new RegExp(source, options);
		this.source = source;
		this.ignoreCase = (re_i.test(options));
		this.global = (re_g.test(options));
	}
}

// ----------------------------------------------------------------------------
// Array functions
if (!Array.push)
Array.prototype.push = function()
{
    var argv = Array.prototype.push.arguments,
        argc = argv.length;
    for (var c = 0; c < argc; c++)
      this[this.length] = argv[c];
}
// Overrides useless concat base method
Array.prototype.concat2 = function()
{
    var argv = Array.prototype.concat2.arguments,
        argc = argv.length,
	a = this;
    for (var c = 0; c < argc; c++) // for each Array to concat
      for (var n = 0, lg_n = argv[c].length; n < lg_n; n++) // for each cell in this Array
        a.push(argv[c][n]);
    return a;
}
Array.concat2 = function()
{ // static
    var argv = Array.concat2.arguments,
	argc = argv.length,
	a = new Array();
    for (var c = 0; c < argc; c++)
      a = a.concat2(argv[c]);
    return a;
}
if (!Array.prototype.del)
Array.prototype.del = function(rank, length)
{
    if (arguments.length < 2) length = 1;
    if (rank == 'last') rank = this.length - 1;
    this.splice(rank, length);
    return this.length;
}

// ------------------------------------------------------------
// List tables
Evonux.List = {};

Evonux.List.Highlight = function(obj, display)
{
    if (display)
    {
      obj.style.backgroundColor = 'rgb(255,255,200)';
      obj.style.color = 'rgb(255,255,255)';
    }
    else
    {
      obj.style.backgroundColor = '';
      obj.style.color = '';
    }
}

// ------------------------------------------------------------
// List tables
Evonux.Text = {};

Evonux.Text._fontSizeMin = 10; // px
Evonux.Text._fontSizeMax = 16; // px
Evonux.Text._fontSizeDefault = 14; // px
Evonux.Text._fontSizeStep = 1; // px

// Returns size in pixels
Evonux.Text.GetSize = function()
{
    if (!document.body.style.fontSize)
      document.body.style.fontSize = Evonux.Text._fontSizeDefault +'px';
    return parseInt(document.body.style.fontSize);
}
Evonux.Text.SetSize = function(size, obj) // px
{
    var re_classTextSize = new RegExp('textsize_button', 'i');

    // Sets size
    document.body.style.fontSize = size +'px';
    

    with (Evonux)
    {
	Server.Get('/textsize.php?size='+ size);
	if (obj)
	    {
		var o = obj.parentNode.getElementsByTagName('div');
		for (var k = 0, lg_k = o.length; k < lg_k; k++)
		    {
			if (re_classTextSize.test(o[k].className))
			    o[k].style.backgroundColor = '';
		    }
		obj.style.backgroundColor = 'rgb(0,166,236)';
	    }
    }
}
Evonux.Text.DecreaseSize = function()
{
    var curTextSize = Evonux.Text.GetSize();
    if (curTextSize > Evonux.Text._fontSizeMin)
      Evonux.Text.SetSize(curTextSize - Evonux.Text._fontSizeStep);
}
Evonux.Text.IncreaseSize = function()
{
    var curTextSize = Evonux.Text.GetSize();
    if (curTextSize < Evonux.Text._fontSizeMax)
      Evonux.Text.SetSize(curTextSize + Evonux.Text._fontSizeStep);
}

// ------------------------------------------------------------
// "Loading..." message

Evonux.Loading = {};

Evonux.Loading = function(on, parentId)
{
    var parentObj = (parentId ? Evonux.$(parentId) : document.getElementsByTagName('body')[0]);

    if (Evonux.Loading.arguments.length == 0) on = true;
    else if (!on) on = false;
    with (Evonux)
    {
	var LObj = $(loadingId);

	if (!on && LObj)
	    {
		LObj.parentNode.removeChild(LObj);
		delete LObj;
		return;
	    }
	// Constructs object
	if (!LObj)
	{
	    LObj = document.createElement('div');
	    if (!parentId)
		{
		    LObj.style.position = 'absolute';
		    LObj.style.top = 0;
		    LObj.style.left = 0;
		}
	    LObj.style.padding = 0;
	    LObj.style.margin = 0;
	    LObj.id = loadingId;
	    LObj.innerHTML = '<img src="/picture/pic_loading.gif" alt="" />';
	}
	LObj.style.display = 'block';
	// Position or placement
	parentObj.appendChild(LObj);
	if (!parentId)
	    {
		var pageOffsetY = (window.pageYOffset ? window.pageYOffset : document.body.scrollTop),
		    size = Evonux.GetObjSize();
		LObj.style.top = pageOffsetY +'px';
		LObj.style.left = size[1] +'px';
	    }
    }
}


Evonux.LoadData = function (server, target, effect)
{
    if (server.GetReadyState() == 4)
    {
      var t = $(target);
      t.hide();
      t.innerHTML = server.GetResponseText();
      Evonux.Text.HeadersToImg(t, 7);
      // Loads calendars
      var cal = document.getElementsByClassName('date', t);
      for (var k = 0; k < cal.length; k++)
      {
	new Evonux.Calendar({parent:cal[k], display:false, hiddenTimestamp:true});
	Evonux.AddEventListener('click', function (e) {Evonux.StopPropagation(e); Evonux.GetEventLauncher(e).calendar.ToggleShow();}, cal[k]);
	//	Event.observe(cal[k], 'click', function (e) {Evonux.StopPropagation(e); Event.element(e).calendar.ToggleShow();});
      }

      if (arguments.length > 2 && effect)
        Effect.Appear(target);
      else
        $(target).show();
    }
}


// ------------------------------------------------------------
// Forms
/*
** Returns selected value of a select from its id (not name !)
*/
Evonux.GetSelectedValue = function(sel_id)
{
    var sel = Evonux.$(sel_id);
    if (!sel)
      return false;
    return sel.options[sel.selectedIndex].value;
}

// ------------------------------------------------------------
// INCLUDES
/*
with (Evonux)
{
  Require(JS_DIR +'/evonux/dom.js');
  Require(JS_DIR +'/evonux/xml.js');
  Require(JS_DIR +'/evonux/date.js');
  Require(JS_DIR +'/evonux/xhr.js');
  Require(JS_DIR +'/evonux/text.js');
  Require(JS_DIR +'/evonux/menu.js');

  Require(JS_DIR +'/evonux/sign.js');
  Require(JS_DIR +'/evonux/search.js');
  Require(JS_DIR +'/evonux/this.js');
}
*/
/*
** Evonux 2005-2006
** Evonux JavaScript Tools (EJST) - version 0.3
**
** tested: IE 6.0, Firefox 1.5, Safari 2.0, Konqueror
**         Mac OS X, Windows 2000/XP, Linux
**
** All rights reserved
*/

if (Evonux && Evonux.IncludeRegister('DOM'))
  Evonux.Exit();
if (!Evonux) Evonux = {};
Evonux.Dom = {};

Evonux.Dom.EmptyNode = function(node)
{
    if((node != undefined) && (node != null))
      return;
    while (node.hasChildNodes())
      node.removeChild(node.firstChild);
}

// HTML syntax highlighting
Evonux.Dom.HighlightHTML = function (node)
{
    var node = Evonux.$(node);
    if (node.evonux_highlighted)
      return;

    var tagRE = new RegExp('&lt;([/a-z]+)([^&]*)&gt;', 'g'),
        attrRE = new RegExp('\\b([a-zA-Z]+)="([^"]+)"', 'g'),
        content = node.innerHTML;
    node.innerHTML = content.replace(tagRE, function(text, tagname, rest)
	{
	    /* This function gets a tag and must work out how to highlight it */
	    // First highlight any attributes in 'rest'
	    rest = rest.replace(attrRE, '<span class="dom_att">$1=</span><span class="dom_val">"$2"</span>');
	    return '<span class="dom_tag">&lt;'+tagname+'</span>'+rest+'<span class="dom_tag">&gt;</span>';
	});
    node.evonux_highlighted = true;
}

// CSS syntax highlighting
Evonux.Dom.HighlightCSS = function (node)
{
    var node = Evonux.$(node);
    if (node.evonux_highlighted)
      return;


    var ruleRE = new RegExp('([^\\{]+)\\{([^\\}]+)\\}', 'g'),
        idselectorRE = new RegExp('(#[a-zA-Z0-9]+)\\b', 'g'),
        classselectorRE = new RegExp('(\\.[a-zA-Z0-9]+)\\b', 'g'),
        pairRE = new RegExp('([a-zA-Z-]+):([^;]+);', 'g'),
        content = node.innerHTML, body, selector;

    node.innerHTML = content.replace(ruleRE, function(text, selector, body)
	{
	    selector = selector.replace(idselectorRE, '<span class="idselector">$1</span>');
	    selector = selector.replace(classselectorRE, '<span class="classselector">$1</span>');
	    body = body.replace(pairRE, '<span class="property">$1</span>:<span class="value">$2</span>;');
	});

    node.evonux_highlighted = true;
}

// Reveals PNG transparency for this oldish IE 6-
Evonux.Dom.PngTransparency = function(e, node)
{
   var re_msie_version = /MSIE[ ]+([0-9\.]+)/i;
   if (!re_msie_version.test(navigator.appVersion) || window.opera) return false;
   var msie_v = parseInt(RegExp.$1);
   if (msie_v < 5.5 || msie_v >= 7) return false;

   var img = (arguments.length > 1 ? node.getElementsByTagName('img') : document.getElementsByTagName('img'));

   if (document.body.filters)
   {
      for(var i = 0; i < img.length; i++)
      {
	var o = img[i];
	if (!o.src || !o.src.length)
	    continue;
	if (o.pngfilterok || o.src.substring(o.src.length-3, o.src.length).toLowerCase() != "png")
	  continue;

	o.style.width = o.offsetWidth +'px';
	o.style.height = o.offsetHeight +'px';
	o.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + o.getAttribute('src') + "',sizingMethod='scale')"; // sizingMethod='image'
	o.setAttribute('src', Evonux.PIC_DIR +'/blank2x2.gif');
	o.pngfilterok = true;
      }
   }
}
Evonux.AddEventListener('load', Evonux.Dom.PngTransparency);

// Returns scroll length [width,height]
Evonux.Dom.PageOffset = function()
{
    alert(window.pageYOffset ? window.pageYOffset : document.body.scrollTop);

    return ([window.pageXOffset ? window.pageXOffset : document.body.scrollLeft,
	     window.pageYOffset ? window.pageYOffset : document.body.scrollTop]);
}

// Returns words space-separated without any tag from an XML tree
Evonux.Dom.RemoveTags = function(inputNode)
{ // static
    if (inputNode.nodeType == 3)
      return inputNode.nodeValue;

    var output = '',
	node = (inputNode.childNodes.length > 0 ? inputNode.childNodes.item(0) : null),
	pnode = inputNode;
    while (node != null)
    {
	if (node.nodeType == 3) // Text content
	    output += ' '+ node.nodeValue;
	// Node (1) - NB. attribute = 2
	if (node.childNodes.length > 0)
	    node = node.childNodes.item(0);
	else
	    {
		if (node.nextSibling != null)
		    node = node.nextSibling;
		else
		    {
			while ((node.parentNode.nextSibling == null) && (node.parentNode != pnode))
			    node = node.parentNode;
			node = (node.parentNode != pnode ? node.parentNode.nextSibling : node.nextSibling);
		    }
	    }
    }
    return output;
}

/**
 * Adds a rule for one or more objects into CSS stylesheets
 */
if (document.styleSheets)
{
var tmp = document.styleSheets[0];
if (tmp.insertRule) // deleteRule(index)
Evonux.Dom.AddCssRules = function(rules, index) // Array of rules: ['tag {style}' [, ...}]
{
    if (arguments.length <= 0) return '';
    if (typeof rules == 'string') rules = new Array(rules);
    var index_set = (arguments.length > 1),
        css = document.styleSheets[0];
    for (var k = 0; k < rules.length; k++)
      css.insertRule(rules[k], (index_set ? index : css.cssRules.length));
    return '';
}
else if (tmp.addRule)// removeRule(index)
Evonux.Dom.AddCssRules = function(rules, index)
{
    if (arguments.length <= 0) return '';
    if (typeof rules == 'string') rules = new Array(rules);
    var index_set = (arguments.length > 1),
        css = document.styleSheets[0],
        re_rule = /^[ \n\r]*([^{]+)[ \n\r]*{([^}]+)}[ \n\r]*$/,
        sel, style;
    for (var k = 0; k < rules.length; k++)
    {
      re_rule.exec(rules[k]);
      sel = RegExp.$1;
      style = RegExp.$2;
      // addRule accepts only one declaration at once (eg. 'b {z-index:1}' is ok but 'b, strong {z-index:1}' is not
      sel = sel.split(',');
      for (var s = 0; s < sel.length; s++)
        css.addRule(sel[s].trim(), style.trim(), -1);
    }
    return '';
}
else
Evonux.Dom.AddCssRules = function(rules, index)
{
    document.getElementByTagName('body')[0].innerHTML += '<style type="text/css">'+ rules.join('\n') +'</style>';
}
delete tmp;
}
else
Evonux.Dom.AddCssRules = function(rules, index)
{
    document.getElementByTagName('body')[0].innerHTML += '<style type="text/css">'+ rules.join('\n') +'</style>';
}

/**
 * Transforms a <select> into a simple displayed <div>
 * IMPORTANT: Consider that <select> is 'inline' element while <div> is 'block' element.
 */
Evonux.Dom.HTMLSelect = Class.create();
Evonux.Dom.HTMLSelect.prototype = {
    initialize: function(node, option)
    {
	this.target = node;
	this.option = option;
	this.MakeNewNode();
    },

    MakeNewNode: function()
    {
	var div = document.createElement('div'),
	    cur = document.createElement('span'),
	    img = document.createElement('img'),
	    t = this.target,
	    sp = Evonux.GetStyleProp;
	Element.setStyle(div, {backgroundColor:sp(t, 'background-color'), color:sp(t, 'color'),
			       width:(t.offsetWidth - 4) +'px', height:t.offsetHeight +'px',
			       paddingTop:Math.floor((t.offsetHeight - parseInt(sp(t, 'font-size'))) / 2) +'px', paddingLeft:'4px',
			       marginLeft:sp(t, 'margin-left'), marginRight:sp(t, 'margin-right'), marginTop:sp(t, 'margin-top'), marginBottom:sp(t, 'margin-bottom'),
			       opacity:'0.75'});
	img.src = Evonux.PIC_DIR +'/pic_arrow-down-white.png';
	// TOTO FOR SAFARI:
	//Element.setStyle(img, {float:'right', marginLeft:'6px', marginRight:'6px', marginTop:Math.floor((t.offsetHeight - 14) / 2) +'px'});
	cur.innerHTML = t.options[t.selectedIndex].text;
	div.appendChild(img);
	div.appendChild(cur);
	t.parentNode.insertBefore(div, t);
	t.style.display = 'none';
    }
}

Evonux.Dom.HTMLSelect.Init = function()
{
    var evonux = document.getElementsByClassName('evonux'),
        node;
    for (var n = 0; n < evonux.length; n++)
    {
      node = evonux[n];
      if (node.tagName == 'SELECT')
        new Evonux.Dom.HTMLSelect(node);
    }
}
Evonux.AddEventListener('load', Evonux.Dom.HTMLSelect.Init);

/*
function transform(xml, xsl, id)
{
  try {
    // navigateur basé sur Gecko
    if (window.XSLTProcessor)
    {
      var fragment;
      var xsltProcessor = new XSLTProcessor();
    	
      xsltProcessor.importStylesheet(xsl);
      fragment = xsltProcessor.transformToFragment(xml, document);
      var target = document.getElementById(id);
      target.appendChild(fragment);
      document.appendChild(target);
      // ActiveX pour Internet Explorer
    } else if (window.ActiveXObject) {
      var target = document.getElementById(id);
      target.innerHTML = xml.transformNode(xsl);
    }
  } catch (e) {
    return e;
  }
}

function loadXML(url)
{
  var xmlDoc;

  // chargement du fichier XML
  try {
    // navigateur basé sur Gecko
    if (document.implementation && document.implementation.createDocument)
    {
      xmlDoc = document.implementation.createDocument('', '', null);
      xmlDoc.load(url);
    // ActiveX pour Internet Explorer
    } else if (window.ActiveXObject) {
      try {
        xmlDoc = new ActiveXObject('Msxml2.XMLDOM');
      } catch (e) {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
      }
      xmlDoc.async = false;
      xmlDoc.load(url);
    // à l'aide de lobjet XMLHTTPRequest
    } else if (window.XMLHttpRequest) {
      xmlDoc = new XMLHttpRequest();
      xmlDoc.overrideMimeType('text/xml'); 
      xmlDoc.open('GET', url, false);
      xmlDoc.send(null);
      if (this.xmlDoc.readyState == 4) xmlDoc = xmlDoc.responseXML;
    }
  } catch (e) {
    return e;
  }
  return xmlDoc;
}
*/
/*
** Evonux 2005-2007
** Evonux JavaScript Tools (EJST) - version 0.3
**
** tested: IE 6.0, Firefox 1.5/2.0, Safari 2.0, Konqueror
**         Mac OS X, Windows XP, Linux
**
** All rights reserved
*/

if (Evonux && Evonux.IncludeRegister('XML'))
  Evonux.Exit();
if (!Evonux) Evonux = {};

Evonux.XML = Class.create();
Evonux.XML.prototype = {
    initialize: function(xmldoc, options)
    {
	if (arguments.length < 2)
	  this.root = xmldoc.documentElement;
	else if (options && options.subxml)
	  this.root = xmldoc;
	else
	  return false;
	if (!this.root) return false;
    },

    GetTag: function(tagname)
    {
        var l = this.root.getElementsByTagName(tagname);
	return (l.length && l[0]
		? l[0]
		: '');
    },
    GetTags: function(tagname)
    {
        return this.root.getElementsByTagName(tagname);
    },
    GetTagData: function() // arguments: tagname1, [tagname2 [, ...]]
    {
	var argv = arguments, argc = argv.length;
	// One tag is asked
	if (argc == 1 && typeof(argv[0]) == 'string')
	  return this.__gettagdata(argv[0]);
	// Several tags are asked
	var tag = new Array();
	for (var k = 0; k < argc; k++)
	{
	  if (typeof(argv[k]) == 'string')
	    tag[argv[k]] = this.__gettagdata(argv[k]);
	  else
	    for (var i = 0; i < argv[k].length; i++)
	      tag[argv[k][i]] = this.__gettagdata(argv[k][i]);
	}
	return tag;
    },
    __gettagdata: function(tagname)
    {
	var l = this.root.getElementsByTagName(tagname);
	return (l.length && l[0] && l[0].firstChild
		? l[0].firstChild.data
		: '');
    },
    GetXML: function(tagname)
    {
	var tag = this.GetTag(tagname);
	if (tag)
	  return new Evonux.XML(tag, {subxml:true});
	return false;
    },
    GetArray: function(xmltree, subtree)
    {
	if (arguments.length < 1) xmltree = this.root;
	if (arguments.length < 2) subtree = 0;

	var a = new Array();
	try
	{
	  var node = xmltree.childNodes, nodeName = xmltree.nodeName,
	      n /* current node */, c /* node content */, tN /* current node's tag name */;

	  for (var k = 0; k < node.length; k++)
	  {
	    n = node[k]; tN = n.nodeName; c = (a[tN] ? true : false);
	    if (n.nodeType == 1)
	    {
	      // Methods can badly interact with this function
	      if (c && typeof a[tN] == 'function')
	      {
		delete a[tN]; // Removes method (why the hell is it here anyway?)
		c = false; // Forces to reset content of node
	      }
	      // Checks whether node is empty or not, filled with Array or String
	      if (!c) // Node has to be initialized
		a[tN] = new Array();
	      if (n.childNodes.length > 1) // Subtree
		a[tN].push(this.GetArray(n, subtree + 1));
	      else // #text
		a[tN].push((n.firstChild ? n.firstChild.data : ''));
	    }
	  }
	  return a;
	} catch (e) {return null;}
    }
}
/*
** Evonux 2005-2007
** Evonux JavaScript Tools (EJST) - version 0.3
**
** tested: IE 6.0, Firefox 1.5, Safari 2.0, Konqueror
**         Mac OS X, Windows XP, Linux
**
** All rights reserved
*/

if (Evonux && Evonux.IncludeRegister('DATE'))
  Evonux.Exit();
if (!Evonux) Evonux = {};


/**
 * Returns timestamp corresponding to date object.
 * If a timestamp if given as t, object is updated with t.
 * Timestamp is like: 20070225125201 (YYYYMMDDHHmmss)
 */
Date.prototype.timestamp = function(t)
{
    if (t && t.length == 14)
    {
      this.setFullYear(t.substr(0, 4));
      this.setMonth(eval(t.substr(4, 2)) - 1);
      this.setDate(t.substr(6, 2));
      this.setHours(t.substr(8, 2));
      this.setMinutes(t.substr(10, 2));
      this.setSeconds(t.substr(12, 2));
      return t;
    }
    var year = this.getFullYear(),
        month = this.getMonth() + 1,
        date = this.getDate(),
        hours = this.getHours(),
        minutes = this.getMinutes(),
        seconds = this.getSeconds();
    return year +''+
           (month < 10 ? '0' : '') + month +''+
           (date < 10 ? '0' : '') + date +''+
           (hours < 10 ? '0' : '') + hours +''+
           (minutes < 10 ? '0' : '') + minutes +''+
           (seconds < 10 ? '0' : '') + seconds;
}
Date.timestamp = function(t)
{
    var d = new Date();
    return d.timestamp(t);
}

Date.prototype.getShortDate = function()
{
    var d = this.getDate(),
        m = this.getMonth() + 1,
        y = this.getFullYear();
    if (d < 10) d = '0'+ d;
    if (m < 10) m = '0'+ m;
    return d +'/'+ m +'/'+ y;
}

/**
 * Transforms all inputs with class 'date' into easy to use
 * calendars. Values of these inputs will be timestamp with
 * 14 digits.
 */
if (!Date.activateInputs)
Date.activateInputs = function()
{
    ;
}

Evonux.Calendar = Class.create();
Evonux.Calendar.prototype = {
    short_day_lg: 3,
    month_name: (Evonux.LANG == 'fr'
		 ? ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
		 : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']),
    day_name: (Evonux.LANG == 'fr'
	       ? ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi']
	       : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']),

    /**
     * option: parent: attached node
     *         display: true - false (default)
     *         month: 1 to 12
     *         year: 1900 to ...
     *         magnify: true (default) / false : gives better looking to input
     */
    initialize: function(option)
    {
	this.id = Evonux.GetId();
	this.option = (option ? option : new Array());

	// Inits
	//  - display
	if (option && option.parent) this.option.parent = $(option.parent);
	//  - default month/year
	var d = new Date();
	if (!option.month) this.option.month = d.getMonth() + 1;
	if (!option.year) this.option.year = d.getFullYear();
	//  - clickable days
	if (!option || !option.days) this.option.days = new Array();
	//  - transforms timestamp to readable date
	var ts = '00000000000000', d = new Date();
	if (option.parent)
	for (var f = 0; f < 2; f++)
	{
	  switch (option.parent.tagName)
	  {
	  case 'INPUT':
	  case 'TEXTAREA':
	      if (f == 0)
		ts = option.parent.value;
	      else
		this.option.parent.value = d.getShortDate();
	      break;
	  default:
	      if (f == 0)
	        ts = option.parent.innerHTML;
	      else
		this.option.parent.innerHTML = d.getShortDate();;
	      break;
	  }
	  if (f == 0)
	    this.cur_timestamp = d.timestamp(ts);
	  else
	  {
	    this.option.year = d.getFullYear();
	    this.option.month = d.getMonth() + 1;
	  }
	}
	
	//  - hidden timestamp input field:
	//    if user add option.hiddenTimestamp, an input with same name as option.parent
	//    is created and contains date with a timestamp (14 digits)
	if (this.option.parent && this.option.hiddenTimestamp)
	{
	  var hts = document.createElement('input');
	  hts.name = (option.parent.id ? option.parent.id : option.parent.name) +'_timestamp';
	  hts.type = 'hidden';
	  hts.value = this.cur_timestamp;
	  this.option.parent.parentNode.insertBefore(hts, this.option.parent);
	  this.option.hts = hts;
	}
	// Registers this calendar
	Evonux.Calendar.Register(this);

	this.InitDisplay();
    },

    InitDisplay: function()
    {
	var div = document.createElement('div');
	div.id = this.id;
	// Style
	//  - calendar
	Element.setStyle(div, {backgroundColor:'rgb(202,202,202)', backgroundImage:'url('+ Evonux.PIC_DIR +'/bg_calendar-mini.png)',
			       backgroundPosition:'left top', backgroundRepeat:'repeat-x',
						   textAlign:'center', padding:'0px', margin:'0px', border:'solid 1px rgb(200,200,200)',
						   zIndex:'9000'});
	//  - parent element
	if (this.option.parent && this.option.parent.tagName == 'INPUT')
	Element.setStyle(this.option.parent, {cursor:'pointer',
					      backgroundColor:'rgb(255,255,255)',
					      backgroundPosition:'right center', backgroundRepeat:'no-repeat'});
	// Display
	if (!this.option.display)
	  Element.setStyle(div, {display:'none'});
	if (this.option.parent)
	{
	  Element.setStyle(div, {position:'absolute'});
	  this.option.parent.calendar = this;
	}
	// Event
	Element.observe(div, 'click', function (e) {Evonux.StopPropagation(e);});
	// Adds object into DOM
	document.getElementsByTagName('body')[0].appendChild(div);

	this.SetOutput();
    },

    Show: function()
    {
	Evonux.Calendar.HideAll(false, this); // Hides all other calendar entries
	var n = $(this.id);
	n.style.display = '';
	if (this.option.parent)
	{
	  var p = Position.cumulativeOffset(this.option.parent);
	  n.style.top = (p[1] + this.option.parent.offsetHeight) +'px';
	  n.style.left = (p[0]) +'px';
	}
	//$(this.id).setStyle('opacity', '1');
    },

    Hide: function()
    {
	//Effect.Fade(this.id);
	$(this.id).style.display = 'none';
    },

    ToggleShow: function()
    {
	var n = $(this.id);
	if (n.style.display == 'none')
	  this.Show();
	else
	  this.Hide();
    },

    SetOutput: function()
    {
	var d = new Date(), m = this.option.month - 1, y = this.option.year,
            output = '', cur = 0, cur_m, cur_d,
        SUNDAY = 0, SATURDAY = 6, cur_filled = 0, cur_is_filled;
	d.setFullYear(y, m, 1);
	for (; d.getDay() > SUNDAY;)
	  d.setDate(d.getDate() - 1);
	for (k = 0; (d.getMonth() <= m || d.getDay() != SATURDAY) && k < 50; k++)
	{
	  cur_m = d.getMonth() + 1;
	  cur_d = d.getDate();
	  cur = d.getFullYear() + (cur_m < 10 ? '0' : '') + cur_m + (cur_d < 10 ? '0' : '') + cur_d;
	  
	  cur_is_filled = false;
	  // Checks that day is filled
	  if (this.option.days[cur_filled] && this.option.days[cur_filled] == cur)
	  {
	    cur_filled++;
	    cur_is_filled = true;
	  }
	  output += (d.getDay() == SUNDAY ? '<tr class="days">' : '');
	  if (d.getMonth() != m)
	    output += '<td></td>';
	  else
	    output += '<td'+ (cur_is_filled ? ' style="color:red;"' : '') + (this.option.parent ? ' onclick="Evonux.Calendar.Get(\''+ this.id +'\').ValidateDate(\''+ cur +'000000\');"' : '') +'>'+ d.getDate() +'</td>';
	  output += (d.getDay() == SATURDAY ? '</tr>' : '');
	  d.setDate(d.getDate() + 1);
	}
	// Years for fast browsing
	var years = '';
	for (var y = this.option.year - 2; y <= this.option.year + 2; y++)
	  years += '<span onclick="Evonux.Calendar.Get(\''+ this.id +'\').Update({year:'+ y +'});">'+ y +'</span>';
	// CSS
	if (!Evonux.Calendar.css_set && document.styleSheets && document.styleSheets.length)
	{
	  Evonux.Dom.AddCssRules(['table.evonux_calendar {cursor:default;}',
				  'table.evonux_calendar tr.days td {cursor:pointer; text-align:right;}',
				  'table.evonux_calendar td.arrowleft, table.evonux_calendar td.arrowright {background-repeat:no-repeat; cursor:pointer; text-align:center; width:13px;}',
				  'table.evonux_calendar td.arrowleft {background-image:url('+ Evonux.PIC_DIR +'/bg_calendar-mini-arrow-left.png); background-position:left top; padding-right:7px;}',
				  'table.evonux_calendar td.arrowright {background-image:url('+ Evonux.PIC_DIR +'/bg_calendar-mini-arrow-right.png);background-position:right top; padding-left:8px;}',
				  'table.evonux_calendar td.years {text-align:center; height:15px;}',
				  'table.evonux_calendar td.years span {cursor:pointer; color:rgb(80,80,80); font-size:9px; padding-left:6px; padding-right:6px;}']);
	  Evonux.Calendar.css_set = true;
	}

	$(this.id).innerHTML = '\
<table cellpadding="0" cellspacing="0" class="evonux_calendar">\
<tr>\
<td class="arrowleft" onclick="Evonux.Calendar.Get(\''+ this.id +'\').Update({month:'+ (this.option.month > 1 ? this.option.month - 1 : 12) +',year:'+ (this.option.month > 1 ? this.option.year : this.option.year - 1) +'});"><img src="'+ Evonux.PIC_DIR +'/pic_calendar-mini-arrow-left.png?a=1" alt="&lt;" /></td>\
<td style="padding-top:3px;">\
  <img src="'+ Evonux.PIC_DIR +'/ico16_close.png?a=1" alt="[X]" style="float:right; font-size:9px; width:16px; height:16px;" onclick="Evonux.Calendar.Get(\''+ this.id +'\').Hide();" />\
  <strong style="text-transform:uppercase;">'+ this.month_name[this.option.month - 1] +' '+ this.option.year +'</strong>\
  <table align="center">\
  <!-- Header -->\
  <tr><td>'+ this.GetDayShort(0) +'</td><td>'+ this.GetDayShort(1) +'</td><td>'+ this.GetDayShort(2) +'</td><td>'+ this.GetDayShort(3) +'</td><td>'+ this.GetDayShort(4) +'</td><td>'+ this.GetDayShort(5) +'</td><td>'+ this.GetDayShort(6) +'</td></tr>\
  '+ output +'\
  </table>\
</td>\
<td class="arrowright" onclick="Evonux.Calendar.Get(\''+ this.id +'\').Update({month:'+ (this.option.month < 12 ? this.option.month + 1 : 1) +',year:'+ (this.option.month < 12 ? this.option.year : this.option.year + 1) +'});"><img src="'+ Evonux.PIC_DIR +'/pic_calendar-mini-arrow-right.png?a=1" alt="&gt;" /></td>\
</tr>\
<tr>\
<td class="years" colspan="3">'+ years +'</td>\
</tr>\
</table>';
	// PNG transparency hack
	if (Evonux.Dom && Evonux.Dom.PngTransparency)
	  Evonux.Dom.PngTransparency($(this.id));
    },

    /**
     * option: month, year, days
     */
    Update: function(option)
    {
	if (option.month) this.option.month = option.month;
	if (option.year) this.option.year = option.year;
	if (option.days) this.option.days = option.days;
	this.SetOutput();
    },

    ValidateDate: function(timestamp)
    {
	this.cur_timestamp = timestamp;
	if (this.option.hts)
	  this.option.hts.value = timestamp;
	if (!this.option.parent)
	  return false;
	var n = this.option.parent, d = new Date();
	d.timestamp(timestamp);
	switch (n.tagName)
	{
	case 'INPUT':
	case 'TEXTAREA':
	    n.value = d.getShortDate();
	    break;
	default:
	    n.innerHTML = d.getShortDate();
	    break;
	}
	this.Hide();
	return true;
    },

    GetDayShort: function (daynb)
    {
	return this.day_name[daynb].substr(0, this.short_day_lg);
    }
}

Evonux.Calendar.item = new Array();
Evonux.Calendar.item_id = new Array();
Evonux.Calendar.css_set = false;
Evonux.Calendar.Get = function(id)
{
    return Evonux.Calendar.item[id];
}
Evonux.Calendar.Register = function(item)
{
    Evonux.Calendar.item[item.id] = item;
    Evonux.Calendar.item_id.push(item.id);
    return item.id;
}
Evonux.Calendar.Delete = function(item)
{
    if (!Evonux.Calendar.item[item.id])
      return false;

    // Deletes calendar entry from parent obj
    if (item.option.parent)
      item.option.parent.calendar = null;
    // Deletes calendar from DOM
    var node = $(item.id);
    node.parentNode.removeChild(node);
    // TODO: remove style from parent
    // Clears entry from local arrays
    for (var i = 0; i < Evonux.Calendar.item_id.length; i++)
      if (Evonux.Calendar.item_id[i] == item.id)
      {
	Evonux.Calendar.item_id.splice(i, 1);
	break;
      }
    delete Evonux.Calendar.item[item.id];

    return true;
}
Evonux.Calendar.HideAll = function(e, obj)
{
    if (Evonux.Calendar.item_id.length)
    for (var id = 0; id < Evonux.Calendar.item_id.length; id++)
    {
      var o = Evonux.Calendar.Get(Evonux.Calendar.item_id[id]);
      if (o != obj)
        Evonux.Calendar.Get(Evonux.Calendar.item_id[id]).Hide();
    }
    return true;
}
/**
 * Removes all Evonux.Calendar objects whose parents are inside parent_obj
 */
Evonux.Calendar.ClearAllInside = function(parent_obj)
{
    var p, // parent of Evonux.Calendar object
        c, // Evonux.Calendar object
        o, // DOM node
        item_id = Evonux.Calendar.item_id.clone();

    if (Evonux.Calendar.item_id.length)
    for (var id = 0; id < item_id.length; id++)
    {
      c = Evonux.Calendar.Get(item_id[id]);
      p = c.option.parent;

      if (!p) continue; // No parent = object is managed independantly
      // Deletes Evonux.Calendar object
      for (o = p; o.tagName != 'BODY'; o = o.parentNode)
	if (o.parentNode == parent_obj)
	  Evonux.Calendar.Delete(c);
    }
}
Element.observe(window, 'click', Evonux.Calendar.HideAll);
/*
** Evonux 2005-2006
** Evonux JavaScript Tools (EJST) - version 0.3
**
** tested: IE 6.0, Firefox 1.5, Safari 2.0, Konqueror
**         Mac OS X, Windows XP, Linux
**
** All rights reserved
*/

if (Evonux && Evonux.IncludeRegister('XHR'))
  Evonux.Exit();
if (!Evonux) Evonux = {};

// ------------------------------------------------------------
// Client/Server exchanges
 Evonux.Server = {};

Evonux.Server = function()
{
    this.obj = this.GetHTTPObject();
    // Builds url prefix
    // e.g. http://hostname.com
    this.url_prefix = window.location.protocol +'//'+ window.location.hostname;
}

Evonux.Server._translationURL = Evonux.SITE_ROOT +'/translationof.php';

Evonux.Server.prototype.GetHTTPObject = function()
{
    var xmlhttp;
    /*@cc_on
	@if (@_jscript_version >= 5)
	    try
		{
		    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
	    catch (e)
		{
		    try
			{
			    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		    catch (E)
			{
			    xmlhttp = false;
			}
		}
	@else
	    xmlhttp = false;
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	try
	    {
		xmlhttp = new XMLHttpRequest();
	    }
	catch (e)
	    {
		xmlhttp = false;
	    }
    }
    return xmlhttp;
}
// - GET method
Evonux.Server.prototype.Get = function(url, __handler, asynchronous)
{
    if (!__handler) __handler = false;
    asynchronous = (Evonux.Server.prototype.Get.arguments.length < 3 ? true : asynchronous);
    if (this.obj)
    {
	var re_http = new RegExp('^http', 'i'),
	    debugid = Evonux.GetId(), debugidtitle = Evonux.GetId(), s = this;

	this.obj.open('GET', (!re_http.test(url) ? this.url_prefix : '') + url, asynchronous);
	if (__handler)
	{
	  if (Evonux.debug && Evonux.DebugMsg)
	    this.obj.onreadystatechange = function () {__handler(s); if (s.GetReadyState() == 4) {$(debugid).innerHTML = s.GetResponseText().escapeHTML().replace(/\n\r/, '<br/>'); if (s.GetResponseText().length > 0) $(debugidtitle).getElementsByTagName('strong')[0].innerHTML += ' +'; $(debugidtitle).getElementsByTagName('strong')[0].style.color = 'rgb(255,0,0)';} else $(debugid).innerHTML = 'loading... ('+ s.GetReadyState() +')';};
	  else
	    this.obj.onreadystatechange = __handler;
	}

	// JS debug
	if (Evonux.debug && Evonux.DebugMsg)
	{
	  var re_parseurl = /^(.*)(\?.*)$/i;
	  re_parseurl.exec((!re_http.test(url) ? this.url_prefix : '') + url);
	  Evonux.DebugMsg('<div id="'+ debugidtitle +'" onclick="Effect.toggle($(\''+ debugid +'\'), \'appear\', {duration:0.3})" style="cursor:pointer; background-color:rgb(220,220,220); padding:2px; border-bottom: solid 1px rgb(180,180,180);"><strong>GET</strong> '+ RegExp.$1 +'<strong>'+ RegExp.$2 +'</strong></div><div id="'+ debugid +'" style="overflow:hidden; display:none;"></div>', true);
	}

	this.obj.send(null);
	if (asynchronous)
	    return true;
	else
	    return this;
    }
    return false;
}
/**
 * Any handler used with this static method
 * must be of the form function handler([Server obj])
 */
Evonux.Server.Get = function(url, __handler, asynchronous)
{ // static
    var server = new Evonux.Server();
    return server.Get(url, function()
		           {
			       if (__handler)
				 __handler(server);
			       if (asynchronous)
			         delete server;
			   },
    		      (Evonux.Server.Get.arguments.length < 3 ? true : asynchronous));
}
// - POST method (absolute)
Evonux.Server.prototype.Post = function(url, param, __handler)
{
    if (!__handler) __handler = false;
    if (this.obj)
    {  
	var re_http = new RegExp('^http', 'i'),
	    debugid = Evonux.GetId(), debugidtitle = Evonux.GetId(), s = this;

       	//this.obj.setOption(3) = ""; // patch to enable secure communication
	this.obj.open('POST', (!re_http.test(url) ? this.url_prefix : '') + url, true);

	if (__handler)
	{
	  if (Evonux.debug && Evonux.DebugMsg)
	    this.obj.onreadystatechange = function () {__handler(s); if (s.GetReadyState() == 4) {$(debugid).innerHTML = s.GetResponseText().escapeHTML().replace(/\n\r/, '<br/>'); if (s.GetResponseText().length > 0) $(debugidtitle).getElementsByTagName('strong')[0].innerHTML += ' +'; $(debugidtitle).getElementsByTagName('strong')[0].style.color = 'rgb(255,0,0)';} else $(debugid).innerHTML = 'loading... ('+ s.GetReadyState() +')';};
	  else
	    this.obj.onreadystatechange = __handler;
	}

	// JS debug
	if (Evonux.debug && Evonux.DebugMsg)
	Evonux.DebugMsg('<div id="'+ debugidtitle +'" onclick="Effect.toggle($(\''+ debugid +'\'), \'appear\', {duration:0.3})" style="cursor:pointer; background-color:rgb(220,220,220); padding:2px; border-bottom: solid 1px rgb(180,180,180);"><strong>POST</strong> '+ (!re_http.test(url) ? this.url_prefix : '') + url +' - <strong>'+ param +'</strong></div><div id="'+ debugid +'" style="overflow:hidden; display:none;"></div>', true);

	this.obj.send(param);
	return true;
    }
    return false;
}
/**
 * Any handler used with this static method
 * must be of the form function handler([Server obj])
 */
Evonux.Server.Post = function(url, __handler)
{ // static
    var server = new Evonux.Server();
    server.Post(url, function()
    {
			if (__handler)
			    __handler(server);
			delete server;
		    });
}
// - POST method (from form)
Evonux.Server.prototype.PostForm = function(formName, __handler, urlencode)
{
    if (!__handler) __handler = false;
    if (arguments.length < 3) urlencode = false;
    
    if (this.obj)
    {
	var re_http = new RegExp('^http', 'i'),
	    boundary = '&'; // delimiter
	
	// Collects form info
	var formObj = document.forms[formName];
	if (!formObj)
	  return false;
	var formAction = formObj.getAttribute('action'); //formObj.action;

	// Lists and prepare data to be sent
	var form_item = new Array(),
	    name;
	// - input: text, password, checkbox, radio...
	var input = formObj.getElementsByTagName('input'),
	    found;
	for (var k = 0, lg_k = input.length; k < lg_k; k++)
	    {
		name = (input[k].name ? input[k].name : (input[k].id ? input[k].id : ''));
		switch (input[k].type.toLowerCase())
		    {
		    case 'submit':
		    case 'image':
		    case 'button':
		    case 'reset':
			// No data to be transmitted
			break;
		    case 'checkbox': // TODO: Do it better: comma cannot be used :(
			if (name && input[k].checked)
			    {
				found = false;
				for (var i = 0, lg_i = form_item.length; i < lg_i; i++)
				    {
					if (form_item[i][0] == name)
					    {
						form_item[i][1] += ','+ input[k].value;
						found = true;
					    }
				    }
				if (!found)
				    form_item.push([name, input[k].value, 'checkbox']);
			    }
			break;
		    case 'radio':
			if (name && (input[k].checked))
			    form_item.push([name, input[k].value, 'radio']);
			break;
		    case '':
		    case 'hidden':
		    case 'text':
		    case 'password':
			if (name)
			    form_item.push([input[k].name, input[k].value, 'text']);
		    default:
		    }
	    }
	// - textarea
	var textarea = formObj.getElementsByTagName('textarea');
	for (var k = 0, lg_k = textarea.length; k < lg_k; k++)
	    {
		name = (textarea[k].name ? textarea[k].name : (textarea[k].id ? textarea[k].id : ''));
		if (name && textarea[k].value)
		    form_item.push([textarea[k].name, textarea[k].value, 'textarea']); // Some HTML RTE may transform text to escaped HTML
	    }
	// - select: normal, multiple
	var select = formObj.getElementsByTagName('select'),
	    values;
	for (var k = 0, lg_k = select.length; k < lg_k; k++)
	    {
		name = (select[k].name ? select[k].name : (select[k].id ? select[k].id : ''));
		if (name)
		    {
			if (select[k].multiple)
			    {
				values = '';
				for (var i = 0, lg_i = select[k].options.length; i < lg_i; i++)
				    {
					// Multiple <select> with name "test[]" is transmitted like : test=1&test=3&...
					// So : '&'+ name +'='
					if (select[k].options[i].selected)
					    values += (values.length > 0 ? boundary + name +'=' : '') + (urlencode && select[k].options[i].value.urlencode
												   ? select[k].options[i].value.urlencode()
												   : select[k].options[i].value);
				    }
				if (values.length > 0)
				    form_item.push([name, values, 'select-multiple']);
			    }
			else
			    form_item.push([select[k].name, select[k].options[select[k].selectedIndex].value, 'select']);
		    }
	    }
	// Constructs string to be sent
	var sendStr = '';
	for (var i = 0, lg_i = form_item.length; i < lg_i; i++)
	  if (form_item[i][0].length > 0)
	      sendStr += (i > 0 ? boundary : '') + form_item[i][0] +'='+ (urlencode && form_item[i][1].urlencode && !(form_item[i][2] == 'select-multiple')
								   ? form_item[i][1].urlencode()
								   : form_item[i][1]).replace(/[\n\r]+/g,'');

	// Launches request
	//this.obj.setOption(3) = ""; // patch to enable secure communication

	//var sendStr = Form.serialize(formName);
	this.obj.open('POST', (!re_http.test(formAction) ? this.url_prefix : '') + formAction, true);

	var debugid = Evonux.GetId(), debugidtitle = Evonux.GetId(), s = this;
	if (__handler)
	{
	  if (Evonux.debug && Evonux.DebugMsg)
	    this.obj.onreadystatechange = function () {__handler(s); if (s.GetReadyState() == 4) {$(debugid).innerHTML = s.GetResponseText().escapeHTML().replace(/\n\r/, '<br/>'); if (s.GetResponseText().length > 0) $(debugidtitle).getElementsByTagName('strong')[0].innerHTML += ' +'; $(debugidtitle).getElementsByTagName('strong')[0].style.color = 'rgb(255,0,0)';} else $(debugid).innerHTML = 'loading... ('+ s.GetReadyState() +')';};
	  else
	    this.obj.onreadystatechange = __handler;
	}

	// JS debug
	if (Evonux.debug && Evonux.DebugMsg)
	Evonux.DebugMsg('<div id="'+ debugidtitle +'" onclick="Effect.toggle($(\''+ debugid +'\'), \'appear\', {duration:0.3})" style="cursor:pointer; background-color:rgb(220,220,220); padding:2px; border-bottom: solid 1px rgb(180,180,180);"><strong>POST FORM</strong> '+ ((!re_http.test(formAction) ? this.url_prefix : '') + formAction) +' - <strong>'+ sendStr +'</strong></div><div id="'+ debugid +'" style="overflow:hidden; display:none;"></div>', true);

	this.obj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	this.obj.setRequestHeader('Content-length', sendStr.length);

	// Response is converted to XML if needed
	//this.obj.overrideMimeType('text/xml; charset=UTF-8'); // ISO-8859-1

	this.obj.send(sendStr);
	return true;
    }
    return false;
}
/**
 * Any handler used with this static method
 * must be of the form function handler([Server obj])
 */
Evonux.Server.PostForm = function(formName, __handler, urlencode)
{ // static
    var server = new Evonux.Server();
    return server.PostForm(formName, function()
			   {
			       __handler(server);
			       delete server;
			   }, urlencode);
}

// ------------------------------------------------------------
// Translation

Evonux.Server.translation = new Array();

/**
 * Returns translation for given word
 *
 * WARNING: this method is synchrone!!!
 */
Evonux.Server.prototype.T = function(ref)
{
    if (Evonux.Server.translation[ref])
      return Evonux.Server.translation[ref];

    var url = Evonux.Server._translationURL +'?ref='+ ref;
    var dateStart = new Date(), dateCurrent;

    if (this.obj)
    {
     	//this.obj.setOption(3) = ""; // patch to enable secure communication
	this.obj.open('GET', url, false);
	this.obj.send(null);

	if (!Evonux.Server.translation[ref])
	  Evonux.Server.translation[ref] = this.GetResponseText();

	return this.GetResponseText();
    }
    return '?';
}
Evonux.Server.T = function(ref)
{ // static
    var server = new Evonux.Server();
    return server.T(ref);
}
Evonux.Server.Tu = function(ref)
{ // static
    var server = new Evonux.Server(),
	trans = server.T(ref);
    trans = trans.charAt(0).toUpperCase() + trans.substr(1);

    return trans;
}
T = Evonux.Server.T;
Tu = Evonux.Server.Tu;

Evonux.Server.prototype.GetResponseText = function()
{
    return (this.obj ? this.obj.responseText : false)
}
Evonux.Server.prototype.GetResponseXML = function()
{
    return (this.obj ? this.obj.responseXML : false)
}
Evonux.Server.prototype.GetReadyState = function()
{
    return (this.obj ? this.obj.readyState : 0)
}



Evonux.Server.innerCodeExec = function (divid)
{
    // Catches <script> tags contents
    var scriptNode = $(divid).getElementsByTagName('script');
    // Loads or executes scripts/actions
    for (var k = 0; k < scriptNode.length; k++)
	{
	    if (scriptNode[k].src.length > 0) // Loads a script
		Evonux.Require(scriptNode[k].src);
	    else // Executes content
		{
		    eval(scriptNode[k].innerHTML);
		}
	}
}


Evonux.Server.Display = function(divid, url)
{
    Evonux.Server.Get(url, function (Server) {Evonux.Server.DisplayDo(Server, divid);})
}
    
Evonux.Server.DisplayDo = function(Server, divid)
{
    if (Server.GetReadyState() == 4)
	{
	    Evonux.$(divid).innerHTML = Server.GetResponseText();
	    Evonux.Server.innerCodeExec(divid);
	}
}
/*
** Evonux 2005-2006
** Evonux JavaScript Tools (EJST) - version 0.3
**
** tested: IE 6.0/7.0, Firefox 2.0, Safari 2.0, Konqueror
**         Mac OS X, Windows XP, Linux
**
** All rights reserved
*/

if (Evonux && Evonux.IncludeRegister('TEXT'))
  Evonux.Exit();

if (!Evonux) Evonux = {};

Evonux.Text = {};

Evonux.Text.ToImg = function(node, font, options)
{
    if (typeof(node) == 'string') node = new Array(node);
    if (arguments.length < 2) font = 0;
    with (Evonux)
    {
      var re_rgba = /rgba/i,
	  _node,
	  _node_original_display, _node_display_ok;
      for (var k = 0; k < node.length; k++)
      {
	_node = $(node[k]);
	if (_node.evonux_toimg || Element.hasClassName(_node, 'locked'))
	  continue;
	// _node has to be displayed temporaryly because some browsers can't access non-displayed objects
	if ((/Konqueror|Safari|KHTML/.test(navigator.userAgent)) || _node.style.display == 'none')
	{
	  _node_display_ok = false;
	  _node_original_display = _node.style.display;
	  _node.style.display = '';
	}
	else
	  _node_display_ok = true;

        var text = _node.innerHTML.replace(/(<br\/?>)/, '\n').replace(/<!--(.|\s)*?-->/g, ''), // removes comments, replaces <br/>s, URL encodes (when calling)
            original_text = _node.innerHTML,
            fontSize = GetStyleProp(_node, 'font-size'),
	    fontWeight = GetStyleProp(_node, 'font-weight'),
            color = GetStyleProp(_node, 'color'),
            bgcolor = GetStyleProp(_node, 'background-color'),
	    width = _node.offsetWidth,
	    nowrap = (GetStyleProp(_node, 'white-space') == 'nowrap' ? 1 : 0),
	    uppercase = (GetStyleProp(_node, 'text-transform') == 'uppercase' ? 1 : 0),
	    lowercase = (GetStyleProp(_node, 'text-transform') == 'lowercase' ? 1 : 0);

	// fontSize may not be correct
	if (parseInt(fontSize) < 50 && RegExp('%', 'i').test(fontSize))
	  fontSize = 0; //GetStyleProp(_node, 'font-size');

	// Sometimes width is null
	if (isNaN(width) || (width <= 0))
	{
	  if (isNaN(width)) width = 0;
	  for (var n = _node; width <= 0 && n.parentNode != n; )
	  {
	    width = n.offsetWidth;

	    if (isNaN(width) || width <= 0)
	    {
	      width = parseInt(GetStyleProp(n, 'width'));
	      if (!isNaN(width) && width > 0)
	        break;
	      else
		width = 0;
	    }
	    n = n.parentNode;
	  }
	}
	// Color may be #XXXXXX instead of rgb(...)
	if (color && color.charAt(0) == '#')
	{ // So it is translated into rgb(...)
	  color = 'rgb('+ parseInt(color.substr(1,2), 16) +','+ parseInt(color.substr(3,2), 16) +','+ parseInt(color.substr(5,2), 16) +')';
	}
	// Background-Color may be #XXXXXX instead of rgb(...)
	if (bgcolor && bgcolor.charAt(0) == '#')
	  bgcolor = 'rgb('+ parseInt(bgcolor.substr(1,2), 16) +','+ parseInt(bgcolor.substr(3,2), 16) +','+ parseInt(bgcolor.substr(5,2), 16) +')';
	// or transparent
	for (var n = _node; (re_rgba.test(bgcolor) || bgcolor == 'transparent') && (n.parentNode != n);)
	{ // re_rgba.test(bgcolor) : Safari considers transparent as 'rgba(0,0,0,0)'
	  n = n.parentNode;
	  bgcolor = (GetStyleProp(n, 'background-color'));
	  if (bgcolor.charAt(0) == '#')
	    bgcolor = 'rgb('+ parseInt(bgcolor.substr(1,2), 16) +','+ parseInt(bgcolor.substr(3,2), 16) +','+ parseInt(bgcolor.substr(5,2), 16) +')';
	}
	// Asks for image
	if (fontSize && color && width)
	{
	  _node.innerHTML = '<img src="'+ SITE_ROOT +'/getimgtext?text='+ text.urlencode() +'&font-size='+ fontSize +'&font-weight='+ fontWeight +'&color='+ color +'&bgcolor='+ bgcolor +'&width='+ width +'&font='+ font +'&nowrap='+ nowrap +'&uppercase='+ uppercase +'&lowercase='+ lowercase +'" alt="'+ text.unescapeHTML().escapeHTML().replace(/\"/g, '\'\'') +'" />';
	  _node.evonux_toimg = true;
	}
	// Resets _node's display property
	if (!_node_display_ok)
	  _node.style.display = _node_original_display;
      }
      if (options && options.afterFinish)
	options.afterFinish(node);
    }
}

Evonux.Text.HeadersToImg = function(node, font)
{
    // Converts titles to font images
    for (var h = 1; h < 3; h++)
      Evonux.Text.ToImg(node.getElementsByTagName('h'+ h), font);
    for (var h = 1; h < 3; h++)
      // Some other tags may be implied
      Evonux.Text.ToImg(document.getElementsByClassName('h'+ h), font);
}

Evonux.Text.MenusToImg = function(node, font)
{
    var paddingtop = 1,
        paddingbottom = 3;
    var a = $('menu-main').getElementsByTagName('a'),
        re_high = /[t]/,
        re_low = /[gjpqy]/,
        a_html = '';
    for (var k = 0; k < a.length; k++)
    {
      a_html = Evonux.Dom.RemoveTags(a[k]);
      a[k].style.paddingTop = ((re_high.test(a_html) && !re_low.test(a_html) ? paddingtop : 0) +
			       (re_low.test(a_html) ? paddingbottom : 0)) +'px';
    }

    //Evonux.Text.ToImg(node.getElementsByTagName('li'), font);
    // Main menu
    var o;
    if (o = $('menu-main'))
    {
      o.style.backgroundColor = 'rgb(141,182,231)';
      Evonux.Text.ToImg(o.getElementsByTagName('a'), font);

      o.style.backgroundColor = '';
    }
    // Local menu
}


Evonux.Text.LimitSize = function(node, max_chars)
{
    switch (node.tagName)
    {
      case 'TEXTAREA':
      case 'INPUT':
        if (node.value.length > max_chars)
	  node.value = node.value.substr(0, max_chars);
	break;
    }
}


if (Evonux && Evonux.IncludeRegister('BOOKING'))
  Evonux.Exit();
if (!Evonux) Evonux = {};

Evonux.SendContactForm = function()
{
    if (Evonux.Booking.CheckForm())
	Evonux.Server.PostForm ("contact", Evonux.SendContactFormDo, true);
}
    
    
Evonux.SendContactFormDo = function (server)
{
    if (server.GetReadyState() == 4)
	$('contact_form').innerHTML = server.GetResponseText();
}

Evonux.DisplayCGV = function(urln)
{
window.open(urln, 'open_window', 'directories, status, scrollbars, resizable, dependent, width=400, height=300, left=0, top=0');
	  
}

Evonux.RateDisplay = function(obj)
{
    if (obj == 'shared')
	{
	    $('private').style.display = 'none';
	    $('shared_title').style.background = 'yellow';
	    $('private_title').style.background = 'none';
	    $('private_title').parentNode.removeClassName('selected');
	    $('shared_title').parentNode.addClassName('selected');
	}
    else
	{
	    $('shared').style.display = 'none';
	    $('shared_title').parentNode.removeClassName('selected');
	    $('shared_title').style.background = 'none';
	    $('private_title').style.background = 'yellow';
	    $('private_title').parentNode.addClassName('selected');
	}
    Evonux.Dom.PngTransparency();
    $(obj).style.display = 'block';
}


/*
** STD
*/
Evonux.AddEventListener('load', function () {
    //Evonux.Text.ToImg($('menu').getElementsByTagName('a'), 0);
    Evonux.HomeLinksActivate();
    //Evonux.Text.HeadersToImg($('body'));
    Evonux.CheckBodyHeight();
    Evonux.BannerInit();
});

Evonux.HomeLinksActivate = function()
{
    var homelinks_ul = $('subbody').getElementsByClassName('home-links');
    if (homelinks_ul.length <= 0) return;
    var homelinks_li = homelinks_ul[0].getElementsByTagName('li'),
        img;
    if (homelinks_li.length <= 0) return;
    for (var k = 0; k < homelinks_li.length; k++)
    {
	img = homelinks_li[k].getElementsByTagName('img')[0];
	Event.observe(img, 'mouseover', function () {
	    this.morph({height:'244px'}, {duration:0.2, afterFinish: function () {
		this.morph({height:'260px'}, {duration:0.2})
	    }.bindAsEventListener(this)})
	}.bindAsEventListener(img));
	Event.observe(img, 'mouseout', function () {this.morph({height:'288px'}, {duration:0.3})}.bindAsEventListener(img));
    }
}

Evonux.CheckBodyHeight = function ()
{
    var bheight = $('subbody').offsetHeight, mheight = $('left').offsetHeight, 
        bpaddingbottom = parseInt($('subbody').getStyle('padding-bottom'));

    if (mheight < 700)
    	$('subbody').setStyle('subbody', {'padding-bottom': (bpaddingbottom + 700 - bheight) +'px'});
//	$('body').style.paddingBottom = (bpaddingbottom + 700 - bheight) +'px';
    else if (bheight + bpaddingbottom < 320)
    	$('subbody').setStyle('subbody', {'padding-bottom': (bpaddingbottom + 320 - bheight) +'px'});
//	$('body').style.paddingBottom = (bpaddingbottom + 320 - bheight) +'px';
}



/*
** Top Banner
*/


Evonux.banner_cpt = 0;
Evonux.BannerInit = function()
{
    if (banner_top && banner_top[0])
	{
	    Evonux.banner_cpt = 1;
	    $('banner_top_img').src = banner_top[0];
	}
    for (var k = 0; k < banner_top.length; k++)
    {
      var img = new Image();
      img.src = banner_top[k];
    }
    setTimeout(Evonux.BannerGo, 8000);
}

Evonux.BannerGo = function()
{
    Effect.Fade('banner_top_img', {duration:0.3,
    afterFinish: function () {
	$('banner_top_img').src = banner_top[Evonux.banner_cpt];
	Effect.Appear('banner_top_img');
	Evonux.banner_cpt++;
	if (Evonux.banner_cpt > banner_top.length - 1)
	Evonux.banner_cpt = 0;
    }})
    setTimeout(Evonux.BannerGo, 8000);
}





/*
** Booking
*/
Evonux.Booking = {};


Evonux.Booking.Move = function (step)
{
    if (!step) step = 1;
    $('required_step').value = step;
    $('booking').submit();
}

Evonux.Booking.SwitchChildrens = function(obj)
{
    var s = $$('.shared_only');
    if (obj.value == 1)
	for (var i = 0; i <= s.length; i++)
	    s[i].hide();
    else
	for (var i = 0; i <= s.length; i++)
	    s[i].show();
}

Evonux.Booking.SwitchPassengers = function (obj)
{
    var s = $$('.shuttle_only');
    var p = $$('.private_only');
    if (obj.value == 1)
	{
	    for (var i = 0; i <= s.length; i++)
		if (s[i]) s[i].hide();
	    for (var i = 0; i <= p.length; i++)
		if (p[i]) p[i].show();
	}
    else
	{
	    for (var i = 0; i <= s.length; i++)
		if (s[i]) s[i].show();
	    for (var i = 0; i <= p.length; i++)
		if (p[i]) p[i].hide();
	}
}

Evonux.Booking.AddressForm = function(obj, prefix)
{
    Evonux.Server.Get(Evonux.SITE_ROOT+'/dynbooking.php?call_action=getaddressform&place_id='+obj.value+'&prefix='+prefix, function (server) {Evonux.Booking.AddressFormDisplay(server, prefix)});
}

Evonux.Booking.AddressFormDisplay = function(server, prefix)
{
    if (server.GetReadyState() == 4)
	{
	    var s = $$('.'+prefix+'info');
	    if (s.length)
		{
		    var t = s[0].parentNode;
		    for (var i = 0; i < s.length; i++)
			s[i].remove();
		}
	    
	    var owdelay = false;
	    var rwdelay = false;
	    var change = false;
	    var owtime = false;
	    var rwtime = false;
	    var tchange = false;

	    eval(server.GetResponseText());
	    if (append)
		{
		    for (var i = 0; append[i]; i++)
			{
			    var tr = document.createElement('tr');
			    tr.className =  ' '+prefix+'info ';
			    var title = document.createElement('td');
			    if (append[i][0] == '1')
				title.className = ' needed ';
			    title.className = ' title ';
			    var data = document.createElement('td');
			    title.innerHTML = append[i][1];
			    data.innerHTML = append[i][2];
			    tr.appendChild(title);
			    tr.appendChild(data);
			    t.appendChild(tr);
			}
		}
	    if (change)
		{
		    if (owdelay && prefix == 'o_a_')
			$('owdelay').style.display = 'block';
		    if (!owdelay && prefix == 'o_a_')
			$('owdelay').style.display = 'none';
		    if (rwdelay && prefix == 'r_a_')
			$('rwdelay').style.display = 'block';
		    if (!rwdelay && prefix == 'r_a_')
			$('rwdelay').style.display = 'none';
		}
	    if (tchange)
		{
		    if (owtime)
			$('owtime').innerHTML = owtime;
		    if (rwtime)
			$('rwtime').innerHTML = rwtime;
		}
	}
}

Evonux.Booking.Check = function ()
{
    var o = $$('.important');
    for (var k = 0; k < o.length; k++)
	{
	    if (!o[k].value)
		{
		    $('error').innerHTML = T('please_fill_all_required_fields');
		    return false;
		}
	}
    var o = $$('.numeric');
    for (var k = 0; k < o.length; k++)
	{
	    if (isNaN(o[k].value))
		{
		    o[k].style.border = 'solid 1px red';
		    $('error').innerHTML = T('please_fill_properly_required_fields');
		    return false;
		}
	}

    if (Evonux.Booking.CheckTime())
	$('booking').submit();
}

Evonux.Booking.CheckTime = function ()
{
    var hm = document.getElementsByClassName('time');
    for (var k=0; k < hm.length; k++)
	{
	    hm[k].value = hm[k].value.replace(/[ ]*/,'');
	    var re_h = /^([0-9]{1,2})[h:]([0-9]{1,2})$/i;
	    re_h.exec(hm[k].value);
	    var h = parseInt(RegExp.$1);
	    var m = parseInt(RegExp.$2);
	    if (!re_h.test(hm[k].value) || !((h >= 0) && (h < 24)) || !((m >= 0) && (m < 60)))
		{
		    alert (T('invalid_hour'));
		    return false;
		}
	}
    return true;
}

Evonux.Booking.CheckForm = function()
{
    var o = document.getElementsByClassName('important');
    for (var k = 0; k < o.length; k++)
	{
	    if (!o[k].value)
		{
		    alert(T('please_fill_all_required_fields'));
		    return false;
		}
	}
    return true;
}


Evonux.Booking.CashInfo = function(obj)
{
    if (obj.value == 1)
    	{
	$('cb_info').style.display = 'none';
	$('cash_info').style.display = '';
	}
    else
    	{
	$('cash_info').style.display = 'none';
	$('cb_info').style.display = '';
	}
}


Evonux.SwitchTrip = function(obj)
{
    if (obj.value == 0)
	{
	    var l = '.citytour';
	    var u = '.shuttle';
	}
    else
	{
	    var l = '.shuttle';
	    var u = '.citytour';
	}
    var all = $$(l);
    for (var k = 0; k < all.length; k++)
	all[k].disabled=true;
    var all = $$(u);
    for (var k = 0; k < all.length; k++)
	all[k].disabled=false;
}

Evonux.Booking.CopyInfo = function ()
{
    var elts = ['ihotel', 'iaddress', 'iaddress_comp', 'izipcode', 'icity', 'iairline'];

    var ai = false;
    var ao = false;
    
    for (k=0; k < elts.length; k++)
	{
	    ai = $('ow_arr').getElementsByClassName(elts[k]);
	    if (ai && ai.length)
		{
		    ao = $('rw_dep').getElementsByClassName(elts[k]);
		    if (ao && ao.length)
			ao[0].value=ai[0].value;
		}
	}

    ai = false;
    ao = false;
    
    for (k=0; k < elts.length; k++)
	{
	    ai = $('ow_dep').getElementsByClassName(elts[k]);
	    if (ai && ai.length)
		{
		    ao = $('rw_arr').getElementsByClassName(elts[k]);
		    if (ao && ao.length)
			ao[0].value=ai[0].value;
		}
	}
}
