/* -------------------------------------------------------------------------------------------------------------------------
	BOGIE CODE
   ------------------------------------------------------------------------------------------------------------------------ */

var trainKit = new Array();
trainKit[0] = "img/bogies/vbl.gif";
trainKit[1] = "img/bogies/vbdl.gif";
trainKit[2] = "img/bogies/vbg.gif";
trainKit[3] = "img/bogies/vbc.gif";
trainKit[4] = "img/bogies/vbc.gif";
trainKit[5] = "img/bogies/vbp.gif";
trainKit[6] = "img/bogies/vbdr.gif"
trainKit[7] = "img/bogies/vbr.gif";

var truckKit = new Array();
truckKit[0] = "img/bogies/tbl.gif";
truckKit[1] = "img/bogies/tbc.gif";
truckKit[2] = "img/bogies/tbr.gif";

function bogieSet(x,wc)
{
	wheelCount[wc] = parseInt(document.getElementById(x).value);
	var text = "set [" + wc + "]=" + wheelCount[wc];
	bogieChange("selBogie");
}

function showVehicle(id) {}
function tooltipVehicle(id) {}

function showBogie(id)
{
	if(id != null)
	{	
		Element.insert('train_form_container', 'show b id ' + id);
		var intParentId = $('train_parent_id').value;
		new Ajax.Updater(	'train_form_container', 
								'bw_process.php', 
									{	asynchronous:false, 
										parameters:'bw_action=bogie-edit&id='+id+'&parent_id='+intParentId
									}
							);
	}
}

function showWheel(id)
{
	//Element.insert('train_form_container', 'show w id ' + id);
}

function tooltipBogie(id)
{
	//Element.insert('train_form_container', 'tt B id ' + id);
}

function tooltipWheel(id)
{
	//Element.insert('train_form_container', 't W id ' + id);
}

/* -------------------------------------------------------------------------------------------------------------------------
	SEARCH FORM CODE
------------------------------------------------------------------------------------------------------------------------
*/

	function search_sort(col, dir, colfield, dirfield)
	{
		$(colfield).value = col;
		$(dirfield).value = dir;		
		search_submit();
	}
	
	function search_page(newpage, pagefield)
	{
		$(pagefield).value = newpage;
		search_submit();
	}
	
	function search_submit()
	{
		$('rv_searchform').submit();		
	}
	
	function advsearch_get_foreign_table(str)
	{
		var strTable = str.substring(0, str.indexOf("."));
		var strDirtyField = str.substring(str.indexOf(".") + 1);
	
		if(strDirtyField.indexOf("__") > 0) // if it has an identifier
		{
			strDirtyField = strDirtyField.substring(strDirtyField.indexOf("__") + 2);
		}

		return strDirtyField.substring(0, strDirtyField.indexOf("_id"));
	}
	
	function advsearch_change(elem, fieldnumber)
	{
		var strValue = $F(elem.id);
		var strSelectDiv = "advselectbox" + fieldnumber;
		var strInputDiv = "advinputbox" + fieldnumber;
		var strSelectId = 'sfm' + fieldnumber;
		
		if(strValue.indexOf("_id") > 0)		// it is a lookup column...so need to split and send the parameters
		{
			Element.hide(strInputDiv);
			
			var strTableName = advsearch_get_foreign_table(strValue);
			var strParams = "tablename=adv_search&table=" + strTableName + "&index=" + fieldnumber;
			

			new Ajax.Updater(	strSelectDiv, 
							'ajax_dispatch.php', 
								{	asynchronous:false, 
									parameters:strParams
								}
						);
			
			Element.show(strSelectDiv);
			
		} else
		{
			if($(strSelectId))
			{				
				Element.remove(strSelectId);
				Element.hide(strSelectDiv);
				Element.show(strInputDiv);
			}							
		}
	}


/* -------------------------------------------------------------------------------------------------------------------------
	INLINE EDIT CODE
   ------------------------------------------------------------------------------------------------------------------------ */
   
   function sh_save(tablename, savemessageel)
   {
	   var strEditFormId = savemessageel + "_editform";
	   var strConfigFieldId = savemessageel + "_shconfig";
	   var strSaveMessageId = savemessageel + '_savemessage';
	   
	   new Ajax.Updater(	strConfigFieldId,
	   						'sh_process.php',
							{parameters:Form.serialize(strEditFormId), asynchronous: false, 
								onSuccess: function () { 
									Element.show(strSaveMessageId);
									} 
							});
   }   
   
   function datagrid_refresh(tablename)
   {
	   var strParams = "mog_action=load-grid&mog_page=" + $(tablename + "_mog_page").value + "&mog_sort_dir=" + $(tablename + "_mog_sort_dir").value + "&mog_sort_col=" + $(tablename + "_mog_sort_col").value + "&mog_config=" + $(tablename + "_mog_config").value;
	   var strGridId = tablename + "_datagrid";
	  
	   new Ajax.Updater(	strGridId, 
							'mog_process.php', 
								{	asynchronous:false, 
									parameters:strParams,
									evalScripts: true
								}
						);
	   
	  datagrid_colourise(tablename);
   }
   
   function datagrid_sort(col, dir, colfield, dirfield, tablename)
	{
		$(colfield).value = col;
		$(dirfield).value = dir;		
		datagrid_refresh(tablename);
	}
	
	function datagrid_page(newpage, pagefield, tablename)
	{
		$(pagefield).value = newpage;
		datagrid_refresh(tablename);
	}
   
   function datagrid_toggle_new(tablename)
   {
	   $(tablename + '_newform').enable();
	   $(tablename + '_new').toggle();
   }
   
   function datagrid_block_changed(tablename)
   {
		$('vis_'+tablename).value = $('vis_'+tablename).value == 1 ? 0 : 1;
		
		if($('vis_'+tablename).value == 1)
		{
			Element.show('adb_'+tablename);
			$('symb_'+tablename).innerHTML = '-';
		
		} else
		{
			Element.hide('adb_'+tablename);
			$('symb_'+tablename).innerHTML = '+';
		}	
   }
   
   function datagrid_colourise(tablename)
   {
	   datagrid_colour_rows(tablename + '_rowcontainer');
	   
	   $$('tbody.'+tablename+'_colourable').each(function(value){
				datagrid_colour_rows(value.identify());
			});
   }
   
   function datagrid_colour_rows(tablebodyid)
   {
	   if($(tablebodyid))
	   {	   
			var arrTrElements = $(tablebodyid).childElements();
			var strClass = 'rowodd';
			
			for(ii = 0; ii < arrTrElements.length; ii++)
			{
				var elem = $(arrTrElements[ii].identify());
				
				if(!elem.hasClassName('newrecord'))
				{
					elem.removeClassName('rowodd');
					elem.removeClassName('roweven');
					elem.addClassName(strClass);
					strClass = strClass == 'roweven' ? 'rowodd': 'roweven';	 
				}
			}
	   }
   }
   
   function datagrid_process_form(tablename)
   {
	  if($('mog_edit_id'))
	  {
		  datagrid_update_row(tablename, $('mog_edit_id').value);	  
		  
	  } else
	  {
		  datagrid_save_new(tablename);
	  }
	   
   }
   
   function datagrid_save_new(tablename)
   {
	   	var strFormId = tablename + '_newform';
		var strNewTr = tablename + '_new';
		var strConfigElement = tablename + '_mog_config';
		var strParams = Form.serialize(strFormId) + "&mog_config=" + $(strConfigElement).value;
		var strDivId = 	   
		new Ajax.Updater(	strNewTr, 
							'mog_process.php', 
								{	asynchronous:false, 
									parameters:strParams,
									insertion:Insertion.After
								}
						);
		
		Form.reset(strFormId);
		$(strNewTr).toggle();
		datagrid_refresh(tablename);
		datagrid_colourise(tablename);
		
		return false;
   }
   
   function datagrid_edit(tablename, rowid)
   {	   
		datagrid_edit_cancel(tablename);
		
		$(tablename + '_new').hide();
		$(tablename + '_newform').disable();
		$('tr_' + tablename + '_' + rowid).hide();
		Element.addClassName('tr_' + tablename + '_' + rowid, 'mog_editing');
		
		new Ajax.Updater('tr_' + tablename + '_' + rowid, 
							'mog_process.php', 
								{	asynchronous:false, 
									evalScripts: true,
									parameters:("mog_action=edit&mog_id=" + rowid + "&mog_config=" + $(tablename + "_mog_config").value),
									insertion:Insertion.After
								}
						);
   }
   
   function datagrid_update_row(tablename, rowid)
   {
	   Element.remove('tr_' + tablename + '_' + rowid);
  
	   new Ajax.Updater(tablename + '_edit', 
							'mog_process.php', 
								{	asynchronous:false, 
									parameters:(Form.serialize(tablename + '_newform') + "mog_action=update&mog_id=" + rowid + "&mog_config=" + $(tablename + "_mog_config").value),
									insertion:Insertion.Before
								}
						);	   
	   
	   Element.remove(tablename + '_edit');
	   datagrid_colourise(tablename);
   }
   
   function datagrid_edit_cancel(tablename)
   {
	  	if($(tablename + '_edit'))		// remove editing on any other rows
		{			
			Element.remove(tablename + '_edit');
			$$('tr.mog_editing').each(function(value, index){
				value.show();
			});	
		}
		
		$(tablename + '_newform').enable();
   }
   
   function datagrid_confirm_delete(tablename, rowid)
   {
	   return confirm('Are you sure you want to delete this record?');
   }
   
   function datagrid_delete(tablename, rowid)
   {
	   if(datagrid_confirm_delete(tablename, rowid))
	   {
			 Element.remove('tr_' + tablename + '_' + rowid);
  
		   new Ajax.Updater('tr_' + tablename + '_' + rowid, 
								'mog_process.php', 
									{	asynchronous:false, 
										parameters:("mog_action=delete&mog_id=" + rowid + "&mog_config=" + $(tablename + "_mog_config").value),
										insertion:Insertion.Before
									}
							);	   
		   
		   datagrid_refresh(tablename);
		   datagrid_colourise(tablename);	   
	   }
   }

/* -------------------------------------------------------------------------------------------------------------------------
	ASYNCHRONOUS UPLOAD CODE
   ------------------------------------------------------------------------------------------------------------------------ */
   
   function async_upload(upload_field, loaddiv, errorid, deleteid)
   {	
		document.getElementById(deleteid).value = "0";
		upload_field.form.submit();
		upload_field.disabled = true;
		document.getElementById(loaddiv).style.display = 'inline';
		document.getElementById(errorid).style.display = 'none';		
		return true;
	}
	
	function async_delete(formid, deleteid)
	{
		document.getElementById(deleteid).value = "1";
		document.getElementById(formid).submit();
		return true;
	}

/* -------------------------------------------------------------------------------------------------------------------------
	TOOLTIP CODE
   ------------------------------------------------------------------------------------------------------------------------ */


//  Copyright (c) 2007 Nick Stakenburg (http://www.nickstakenburg.com)
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//  More information on this project:
//  http://www.nickstakenburg.com/projects/prototip/

var Prototip = {
  Version: '1.2.0_pre1',

  REQUIRED_Prototype: '1.6.0',
  REQUIRED_Scriptaculous: '1.8.0',

  start: function() {
    this.require('Prototype');
    Tips.initialize();
    Element.observe(window, 'unload', this.unload);
  },

  require: function(library) {
    if ((typeof window[library] == 'undefined') ||
      (this.convertVersionString(window[library].Version) < this.convertVersionString(this['REQUIRED_' + library])))
      throw('Prototip requires ' + library + ' >= ' + this['REQUIRED_' + library]);
  },

  convertVersionString: function(versionString) {
    var r = versionString.split('.');
    return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
  },

  viewport: {
    getDimensions: function() {
      var dimensions = { };
      var B = Prototype.Browser;
      $w('width height').each(function(d) {
        var D = d.capitalize();
        dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
          (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
        });
      return dimensions;
    }
  },

  capture: function(func) {
    if (!Prototype.Browser.IE) {
      func = func.wrap(function(proceed, event) {
      var rel = event.relatedTarget, cur = event.currentTarget;
      if (rel && rel.nodeType == Node.TEXT_NODE) rel = rel.parentNode;
      if (rel && rel != cur && rel.descendantOf && !(rel.descendantOf(cur)))
        proceed(event);
      });
    }
    return func;
  },

  unload: function() { Tips.removeAll(); }
};

var Tips = {
  // Configuration
  closeButtons: false,
  zIndex: 1200,

  tips : [],
  visible : [],

  initialize: function() {
    this.zIndexTop = this.zIndex;
  },

  useEvent : (function(IE) { return {
    'mouseover': (IE ? 'mouseenter' : 'mouseover'),
    'mouseout': (IE ? 'mouseleave' : 'mouseout'),
    'mouseenter': (IE ? 'mouseenter' : 'mouseover'),
    'mouseleave': (IE ? 'mouseleave' : 'mouseout')
  };})(Prototype.Browser.IE),

  fixIE: (function(agent) {
    var version = new RegExp('MSIE ([\\d.]+)').exec(agent);
    return version ? (parseFloat(version[1]) <= 6) : false;
  })(navigator.userAgent),

  add: function(tip) {
    this.tips.push(tip);
  },

  remove: function(element) {
    var tip = this.tips.find(function(t){ return t.element == $(element); });
    if (tip) {
      tip.deactivate();
      if (tip.tooltip) {
        tip.wrapper.remove();
        if (Tips.fixIE) tip.iframeShim.remove();
      }
      this.tips = this.tips.without(tip);
    }
  },

  removeAll: function() {
    this.tips.each(function(tip) { this.remove(tip.element); }.bind(this));
  },

  raise: function(tip) {
    if (tip.highest) return;
    if (this.visible.length == 0) {
      this.zIndexTop = this.zIndex;
      for (var i=0;i<this.tips.length;i++) {
        this.tips[i].wrapper.style.zIndex = this.zIndex;
      }
    }
    tip.style.zIndex = this.zIndexTop++;
    for (var i=0;i<this.tips.length;i++) { this.tips[i].wrapper.highest = false; };
    tip.highest = true;
  },

  addVisibile: function(tip) {
    this.removeVisible(tip);
    this.visible.push(tip);
  },

  removeVisible: function(tip) {
    this.visible = this.visible.without(tip);
  }
};
Tips.initialize();

var Tip = Class.create({
  initialize: function(element, content) {
    this.element = $(element);
    Tips.remove(this.element);

    this.content = content;

    var isHooking = (arguments[2] && arguments[2].hook);
    var isShowOnClick = (arguments[2] && arguments[2].showOn == 'click');

    this.options = Object.extend({
      className: 'default',                 // see css, this will lead to .prototip .default
      closeButton: Tips.closeButtons,       // true, false
      delay: !isShowOnClick ? 0.2 : false,  // seconds before tooltip appears
      duration: 0.3,                        // duration of the effect
      effect: false,                        // false, 'appear' or 'blind'
      hideAfter: false,                     // second before hide after no hover/activity
      hideOn: 'mouseleave',                 // or any other event, false
      hook: false,                          // { element: topLeft|topRight|bottomLeft|bottomRight, tip: see element }
      offset: isHooking ? {x:0, y:0} : {x:16, y:16},
      fixed: isHooking ? true : false,      // follow the mouse if false
      showOn: 'mousemove',
      target: this.element,                 // or another element
      title: false,
      viewport: isHooking ? false : true    // keep within viewport if mouse is followed
    }, arguments[2] || {});

    this.target = $(this.options.target);

    this.setup();

    if (this.options.effect) {
      Prototip.require('Scriptaculous');
      this.queue = { position: 'end', limit: 1, scope: this.wrapper.identify() }
    }

    Tips.add(this);
    this.activate();
  },

  setup: function() {
    this.wrapper = new Element('div', { 'class' : 'prototip' }).setStyle({
      display: 'none', zIndex: Tips.zIndex });
    this.wrapper.identify();

    if (Tips.fixIE) {
      this.iframeShim = new Element('iframe', { 'class' : 'iframeShim', src: 'javascript:false;' }).setStyle({
        display: 'none', zIndex: Tips.zIndex - 1 });
    }

    this.tip = new Element('div', { 'class' : 'content' }).insert(this.content);
    this.tip.insert(new Element('div').setStyle({ clear: 'both' }));

    if (this.options.closeButton || (this.options.hideOn.element && this.options.hideOn.element == 'closeButton'))
      this.closeButton = new Element('a', { href: '#', 'class' : 'close' });
  },

  build: function() {
    if (Tips.fixIE) document.body.appendChild(this.iframeShim).setOpacity(0);

    // effects go smooth with extra wrapper
    var wrapper = 'wrapper';
    if (this.options.effect) {
      this.effectWrapper = this.wrapper.appendChild(new Element('div', { 'class' : 'effectWrapper' }));
      wrapper = 'effectWrapper';
    }

    this.tooltip = this[wrapper].appendChild(new Element('div', { 'class' : 'tooltip ' + this.options.className }));

    if (this.options.title || this.options.closeButton) {
      this.toolbar = this.tooltip.appendChild(new Element('div', { 'class' : 'toolbar' }));
      this.title = this.toolbar.appendChild(new Element('div', { 'class' : 'title' }).update(this.options.title || ' '));
    }

    this.tooltip.insert(this.tip);
    document.body.appendChild(this.wrapper);

    // fixate elements for better positioning and effects
    var fixate = (this.options.effect) ? [this.wrapper, this.effectWrapper]: [this.wrapper];
    if (Tips.fixIE) fixate.push(this.iframeShim);

    // fix width
    var fixedWidth = this.wrapper.getWidth();
    fixate.invoke('setStyle', { width: fixedWidth + 'px' });

    // make toolbar width fixed
    if(this.toolbar) {
      this.wrapper.setStyle({ visibility : 'hidden' }).show();
      this.toolbar.setStyle({ width: this.toolbar.getWidth() + 'px'});
      this.wrapper.hide().setStyle({ visibility : 'visible' });
    }

    // add close button
    if (this.closeButton)
      this.title.insert({ top: this.closeButton }).insert(new Element('div').setStyle({ clear: 'both' }));

    var fixedHeight = this.wrapper.getHeight();
    fixate.invoke('setStyle', { width: fixedWidth + 'px', height: fixedHeight + 'px' });

    this[this.options.effect ? wrapper : 'tooltip'].hide();
  },

  activate: function() {
    this.eventShow = this.showDelayed.bindAsEventListener(this);
    this.eventHide = this.hide.bindAsEventListener(this);

    // if fixed use mouseover instead of mousemove for less event calls
    if (this.options.fixed && this.options.showOn == 'mousemove') this.options.showOn = 'mouseover';

    if(this.options.showOn == this.options.hideOn) {
      this.eventToggle = this.toggle.bindAsEventListener(this);
      this.element.observe(this.options.showOn, this.eventToggle);
    }

    var hideOptions = {
      'element': this.eventToggle ? [] : [this.element],
      'target': this.eventToggle ? [] : [this.target],
      'tip': this.eventToggle ? [] : [this.wrapper],
      'closeButton': [],
      'none': []
    };
    var el = this.options.hideOn.element;
    this.hideElement = el || (!this.options.hideOn ? 'none' : 'element');
    this.hideTargets = hideOptions[this.hideElement];
    if (!this.hideTargets && el && Object.isString(el)) this.hideTargets = this.tip.select(el);

    var realEvent = {'mouseenter': 'mouseover', 'mouseleave': 'mouseout'};
    $w('show hide').each(function(e) {
      var E = e.capitalize();
      var event = (this.options[e + 'On'].event || this.options[e + 'On']);
      this[e + 'Action'] = event;
      if (['mouseenter', 'mouseleave', 'mouseover', 'mouseout'].include(event)) {
        this[e + 'Action'] = (Tips.useEvent[event] || event);
        this['event' + E] = Prototip.capture(this['event' + E]);
      }
    }.bind(this));

    if (!this.eventToggle) this.element.observe(this.options.showOn, this.eventShow);
    if (this.hideTargets) this.hideTargets.invoke('observe', this.hideAction, this.eventHide);

    // add postion observer to moving showOn click tips
    if (!this.options.fixed && this.options.showOn == 'click') {
      this.eventPosition = this.position.bindAsEventListener(this);
      this.element.observe('mousemove', this.eventPosition);
    }

    // close button
    this.buttonEvent = this.hide.wrap(function(proceed, event) {
      event.stop();
      proceed(event);
    }).bindAsEventListener(this);
    if (this.closeButton) this.closeButton.observe('click', this.buttonEvent);

    // delay timeout
    if (this.options.showOn != 'click' && (this.hideElement != 'element')) {
      this.eventCheckDelay = Prototip.capture(function() {
        this.clearTimer('show');
      }).bindAsEventListener(this);
      this.element.observe(Tips.useEvent['mouseout'], this.eventCheckDelay);
    }

    // activity (hideAfter, raise)
    var elements = [this.element, this.wrapper];
    this.activityEnter = Prototip.capture(function() {
      Tips.raise(this.wrapper);
      this.cancelHideAfter();
    }).bindAsEventListener(this);
    this.activityLeave = Prototip.capture(this.hideAfter).bindAsEventListener(this);
    elements.invoke('observe', Tips.useEvent['mouseover'], this.activityEnter);
    elements.invoke('observe', Tips.useEvent['mouseout'], this.activityLeave);
  },

  deactivate: function() {
    if(this.options.showOn == this.options.hideOn)
      this.element.stopObserving(this.options.showOn, this.eventToggle);
    else {
      this.element.stopObserving(this.options.showOn, this.eventShow);
      if (this.hideTargets) this.hideTargets.invoke('stopObserving');
    }

    if (this.eventPosition) this.element.stopObserving('mousemove', this.eventPosition);
    if (this.closeButton) this.closeButton.stopObserving();
    if (this.eventCheckDelay) this.element.stopObserving('mouseout', this.eventCheckDelay);
    this.wrapper.stopObserving();
    this.element.stopObserving(Tips.useEvent['mouseover'], this.activityEnter);
    this.element.stopObserving(Tips.useEvent['mouseout'], this.activityLeave);
  },

  showDelayed: function(event) {
    if (!this.tooltip) this.build();
    this.position(event); // follow mouse
    if (this.wrapper.visible()) return;

    this.clearTimer('show');
    this.showTimer = this.show.bind(this).delay(this.options.delay);
  },

  clearTimer: function(timer) {
    if (this[timer + 'Timer']) clearTimeout(this[timer + 'Timer']);
  },

  show: function() {
    if (this.wrapper.visible() && this.options.effect != 'appear') return;

    if (Tips.fixIE) this.iframeShim.show();
    Tips.addVisibile(this.wrapper);
    this.wrapper.show();

    if (!this.options.effect) this.tooltip.show();
    else {
      if (this.activeEffect) Effect.Queues.get(this.queue.scope).remove(this.activeEffect);
      this.activeEffect = Effect[Effect.PAIRS[this.options.effect][0]](this.effectWrapper,
        { duration: this.options.duration, queue: this.queue});
    }
  },

  hideAfter: function(event) {
    if (!this.options.hideAfter) return;
    this.cancelHideAfter();
    this.hideAfterTimer = this.hide.bind(this).delay(this.options.hideAfter);
  },

  cancelHideAfter: function() {
    if (this.options.hideAfter) this.clearTimer('hideAfter');
  },

  hide: function() {
    this.clearTimer('show');
    if(!this.wrapper.visible()) return;

    if (!this.options.effect) {
      if (Tips.fixIE) this.iframeShim.hide();
      this.tooltip.hide();
      this.wrapper.hide();
      Tips.removeVisible(this.wrapper);
    }
    else {
      if (this.activeEffect) Effect.Queues.get(this.queue.scope).remove(this.activeEffect);
      this.activeEffect = Effect[Effect.PAIRS[this.options.effect][1]](this.effectWrapper,
        { duration: this.options.duration, queue: this.queue, afterFinish: function() {
        if (Tips.fixIE) this.iframeShim.hide();
        this.wrapper.hide();
        Tips.removeVisible(this.wrapper);
      }.bind(this)});
    }
  },

  toggle: function(event) {
    if (this.wrapper && this.wrapper.visible()) this.hide(event);
    else this.showDelayed(event);
  },

  position: function(event) {
    Tips.raise(this.wrapper);

    var offset = {left: this.options.offset.x, top: this.options.offset.y};
    var targetPosition = Position.cumulativeOffset(this.target);
    var tipd = this.wrapper.getDimensions();
    var pos = { left: (this.options.fixed) ? targetPosition[0] : Event.pointerX(event),
      top: (this.options.fixed) ? targetPosition[1] : Event.pointerY(event) };

    // add offsets
    pos.left += offset.left;
    pos.top += offset.top;

    if (this.options.hook) {
      var dims = {target: this.target.getDimensions(), tip: tipd}
      var hooks = {target: Position.cumulativeOffset(this.target), tip: Position.cumulativeOffset(this.target)}

      for (var z in hooks) {
        switch (this.options.hook[z]) {
          case 'topRight':
            hooks[z][0] += dims[z].width;
            break;
          case 'topMiddle':
            hooks[z][0] += (dims[z].width / 2);
            break;
          case 'rightMiddle':
            hooks[z][0] += dims[z].width;
            hooks[z][1] += (dims[z].height / 2);
            break;
          case 'bottomLeft':
            hooks[z][1] += dims[z].height;
            break;
          case 'bottomRight':
            hooks[z][0] += dims[z].width;
            hooks[z][1] += dims[z].height;
            break;
          case 'bottomMiddle':
            hooks[z][0] += (dims[z].width / 2);
            hooks[z][1] += dims[z].height;
            break;
          case 'leftMiddle':
            hooks[z][1] += (dims[z].height / 2);
            break;
        }
      }

      // move based on hooks
      pos.left += -1*(hooks.tip[0] - hooks.target[0]);
      pos.top += -1*(hooks.tip[1] - hooks.target[1]);
    }

    // move tooltip when there is a different target
    if (!this.options.fixed && this.element !== this.target) {
      var elementPosition = Position.cumulativeOffset(this.element);
      pos.left += -1*(elementPosition[0] - targetPosition[0]);
      pos.top += -1*(elementPosition[1] - targetPosition[1]);
    }

    if (!this.options.fixed && this.options.viewport) {
      var scroll = document.viewport.getScrollOffsets();
      var viewport = Prototip.viewport.getDimensions();
      var pair = {left: 'width', top: 'height'};

      for(var z in pair) {
        if ((pos[z] + tipd[pair[z]] - scroll[z]) > viewport[pair[z]])
          pos[z] = pos[z] - tipd[pair[z]] - 2*offset[z];
      }
    }

    var setPos = { left: pos.left + 'px', top: pos.top + 'px' };
    this.wrapper.setStyle(setPos);
    if (Tips.fixIE) this.iframeShim.setStyle(setPos);
  }
});

Prototip.start();

/* -------------------------------------------------------------------------------------------------------------------------
	TAB CONTROL CODE FOR SEARCH VIEW
   ------------------------------------------------------------------------------------------------------------------------ */

function toggleSearchTab(num,numelems,opennum,animate) {
    if (($('searchTabContent'+num).style.display == 'none') || (!$('searchTabContent'+num).style.display)){
        for (var i=1;i<=numelems;i++){
            if ((opennum == null) || (opennum != i)){
                var temph = 'searchTabHeader'+i;
                var h = $(temph);
                if (!h){
                    var h = $('searchTabHeaderActive');
                    h.id = temph;
                }
                var tempc = 'searchTabContent'+i;
                var c = $(tempc);
                if(c.style.display != 'none'){
                    if (animate || typeof animate == 'undefined')
                        Effect.toggle(tempc,'appear',{duration:0.3, queue:{scope:'menus', limit: 3}});
                    else
                        toggleDisp(tempc);
                }
            }
        }
        var h = $('searchTabHeader'+num);
        if (h)
            h.id = 'searchTabHeaderActive';
        h.blur();
        var c = $('searchTabContent'+num);
        //c.style.marginTop = '2px';
        if (animate || typeof animate == 'undefined'){
            Effect.toggle('searchTabContent'+num,'appear',{duration:0.3, queue:{scope:'menus', position:'end', limit: 3}});
        } else {
            toggleDisp('searchTabContent'+num);
        }
    }
}


/* -------------------------------------------------------------------------------------------------------------------------
	TAB CONTROL CODE FOR MAIN VEHICLE VIEW
   ------------------------------------------------------------------------------------------------------------------------ */

/*-----------------------------------------------------------
    Toggles element's display value
    Input: any number of element id's
    Output: none 
    ---------------------------------------------------------*/
function toggleDisp() {
    for (var i=0;i<arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}

/*-----------------------------------------------------------
    Toggles tabs - Closes any open tabs, and then opens current tab
	Input:      1. The number of the current tab
				2. The number of tabs
				3. (optional)The number of the tab to leave 
					open
				4. (optional)Pass in true or false whether or 
					not to animate the open/close of the tabs
    Output: none 
    ---------------------------------------------------------*/
	
function toggleTab(num,numelems,opennum,animate) {
    if (($('tabContent'+num).style.display == 'none') || (!$('tabContent'+num).style.display)){
        for (var i=1;i<=numelems;i++){
            if ((opennum == null) || (opennum != i)){
                var temph = 'tabHeader'+i;
                var h = $(temph);
                if (!h){
                    var h = $('tabHeaderActive');
                    h.id = temph;
                }
                var tempc = 'tabContent'+i;
                var c = $(tempc);
                if(c.style.display != 'none'){
                    if (animate || typeof animate == 'undefined')
                        Effect.toggle(tempc,'appear',{duration:0.3, queue:{scope:'menus', limit: 3}});
                    else
                        toggleDisp(tempc);
                }
            }
        }
        var h = $('tabHeader'+num);
        if (h)
            h.id = 'tabHeaderActive';
        h.blur();
        var c = $('tabContent'+num);
        //c.style.marginTop = '2px';
        if (animate || typeof animate == 'undefined'){
            Effect.toggle('tabContent'+num,'appear',{duration:0.3, queue:{scope:'menus', position:'end', limit: 3}});
        }else{
            toggleDisp('tabContent'+num);
        }
    }
}

/* -------------------------------------------------------------------------------------------------------------------------
	DATE PICKER CODE
   ------------------------------------------------------------------------------------------------------------------------ */
   
   /**
 * DatePicker widget using Prototype and Scriptaculous.
 * (c) 2007 Mathieu Jondet <mathieu@eulerian.com>
 * Eulerian Technologies
 *
 * DatePicker is freely distributable under the same terms as Prototype.
 *
 */

/**
 * DatePickerFormatter class for matching and stringifying dates.
 *
 * By Arturas Slajus <x11@arturaz.net>.
 */
var DatePickerFormatter = Class.create();
DatePickerFormatter.prototype = {
    /**
     * Create a DatePickerFormatter.
     *
     * format: specify a format by passing 3 value array consisting of
     *   "yyyy", "mm", "dd". Default: ["yyyy", "mm", "dd"].
     *
     * separator: string for splitting the values. Default: "-".
     *
     * Use it like this:
     *   var df = new DatePickerFormatter(["dd", "mm", "yyyy"], "/");
     *   df.current_date();
     *   df.match("7/7/2007");
     */
    initialize: function(format, separator) {
        if (typeof(format) == "undefined") { format = ["yyyy", "mm", "dd"] }
        if (typeof(separator) == "undefined") { separator = "-" }

        this._format = format;
        this.separator = separator;
                
        this._format_year_index = format.indexOf("yyyy");
        this._format_month_index = format.indexOf("mm");
        this._format_day_index = format.indexOf("dd");
                
        this._year_regexp = /^\d{4}$/;
        this._month_regexp = /^0\d|1[012]|\d$/;
        this._day_regexp = /^0\d|[12]\d|3[01]|\d$/;
    },
    
    /**
     * Match a string against date format.
     * Returns: [year, month, day]
     */
    match: function(str) {
        d = str.split(this.separator);
        
        if (d.length < 3) {
            return false;
        }
        
        year = d[this._format_year_index].match(this._year_regexp);
        if (year) { year = year[0] } else { return false }
        month = d[this._format_month_index].match(this._month_regexp);
        if (month) { month = month[0] } else { return false }
        day = d[this._format_day_index].match(this._day_regexp);
        if (day) { day = day[0] } else { return false }
        
        return [year, month, day];
    },
    
    /**
     * Return current date according to format.
     */
    current_date: function() {
        var d = new Date;
        return this.date_to_string(
            d.getFullYear(),
            d.getMonth() + 1,
            d.getDay()
       );
    },
    
    /**
     * Return a stringified date accordint to format.
     */
    date_to_string: function(year, month, day, separator) {
        if (typeof(separator) == "undefined") { separator = this.separator }

        var a = [0, 0, 0];
        a[this._format_year_index] = year;
        a[this._format_month_index] = this.leftpad_with_zeroes(month, 2);
        a[this._format_day_index] = this.leftpad_with_zeroes(day, 2);
        
        return a.join(separator);
    },
    
    /**
     * Pad string from left with zeroes.
     *
     * Shameleslly stolen from http://www.eulerian.com/misc/datepicker/
     */
    leftpad_with_zeroes: function(str, padToLength) {
        var result	= '';
        for (var i = 0; i < (padToLength - String(str).length); i++)
            result	+= '0';
        return result + str;
    }
}; 


/**
 * DatePicker
 */

var DatePicker	= Class.create();

DatePicker.prototype	= {
 Version	: '0.9.3',
 _relative	: null,
 _div		: null,
 _zindex	: 1,
 _keepFieldEmpty: false,
 _daysInMonth	: [31,28,31,30,31,30,31,31,30,31,30,31],
 /* language */
 _language	: 'fr',
 _language_month	: $H({
  'fr'	: [ 'Janvier', 'F&#233;vrier', 'Mars', 'Avril', 'Mai', 'Juin', 
   'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'D&#233;cembre' ],
  'en'	: [ 'January', 'February', 'March', 'April', 'May',
   'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
  'sp'	: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 
   'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
  'it'	: [ 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
   'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre' ],
  'de'	: [ 'Januar', 'Februar', 'M&#228;rz', 'April', 'Mai', 'Juni',
   'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ],
  'pt'	: [ 'Janeiro', 'Fevereiro', 'Mar&#231;o', 'Abril', 'Maio', 'Junho',
   'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ],
  'hu'	: [ 'Janu&#225;r', 'Febru&#225;r', 'M&#225;rcius', '&#193;prilis', 
   'M&#225;jus', 'J&#250;nius', 'J&#250;lius', 'Augusztus', 'Szeptember', 
   'Okt&#243;ber', 'November', 'December' ],
  'lt'  : [ 'Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegu&#382;&#279;',
   'Bir&#382;elis', 'Liepa', 'Rugj&#363;tis', 'Rus&#279;jis', 'Spalis', 
   'Lapkritis', 'Gruodis' ],
  'nl'	: [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni',
   'juli', 'augustus', 'september', 'oktober', 'november', 'december' ],
  'dk'	: [ 'Januar', 'Februar', 'Marts', 'April', 'Maj',
   'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'December' ],
  'no'	: [ 'Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni',
   'Juli', 'August', 'September', 'Oktober', 'November', 'Desember' ]
 }),
 _language_day	: $H({
  'fr'	: [ 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim' ],
  'en'	: [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ],
  'sp'	: [ 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'S&#224;b', 'Dom' ],
  'it'	: [ 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom' ],
  'de'	: [ 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam', 'Son' ],
  'pt'	: [ 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'S&#225;', 'Dom' ],
  'hu'	: [ 'H&#233;', 'Ke', 'Sze', 'Cs&#252;', 'P&#233;', 'Szo', 'Vas' ],
  'lt'  : [ 'Pir', 'Ant', 'Tre', 'Ket', 'Pen', '&Scaron;e&scaron;', 'Sek' ],
  'nl'	: [ 'ma', 'di', 'wo', 'do', 'vr', 'za', 'zo' ],
  'dk'	: [ 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'L&#248;r', 'S&#248;n' ],
  'no'	: [ 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'L&#248;r', 'Sun' ]
 }),
 _language_close	: $H({
  'fr'	: 'fermer',
  'en'	: 'close',
  'sp'	: 'cierre',
  'it'	: 'fine',
  'de'	: 'schliessen',
  'pt'	: 'fim',
  'hu'	: 'bez&#225;r',
  'lt'  : 'udaryti',
  'nl'	: 'sluiten',
  'dk'	: 'luk',
  'no'	: 'lukk'
 }),
 _language_date_format : $H({
    'en': [ ["dd", "mm", "yyyy"], "/" ],
    'lt': [ ["yyyy", "mm", "dd"], "-" ],
    'fr': [ ["dd", "mm", "yyyy"], "/" ],
    'sp': [ ["dd", "mm", "yyyy"], "/" ],
    'it': [ ["dd", "mm", "yyyy"], "/" ],
    'de': [ ["dd", "mm", "yyyy"], "/" ],
    'pt': [ ["dd", "mm", "yyyy"], "/" ],
    'hu': [ ["dd", "mm", "yyyy"], "/" ],
    'nl': [ ["dd", "mm", "yyyy"], "-" ],
    'dk': [ ["dd", "mm", "yyyy"], "-" ],
    'no': [ ["dd", "mm", "yyyy"], "-" ]
 }),
 /* date manipulation */
 _todayDate	: new Date(),
 _current_date	: null,
 _clickCallback	: Prototype.emptyFunction,
 _cellCallback	: Prototype.emptyFunction,
 _id_datepicker	: null,
 /* positionning */
 _topOffset	: 30,
 _leftOffset	: 0,
 _isPositionned	: false,
 _relativePosition : true,
 _setPositionTop : 0,
 _setPositionLeft: 0,
 /* Effects Adjustment */
 _showEffect	: "appear", 
 _showDuration	: 0.3,
 _enableShowEffect : true,
 _closeEffect	: "fade", 
 _closeEffectDuration: 0.3,
 _enableCloseEffect : true,
 /* afterClose : called when the close function is executed */
 _afterClose	: Prototype.emptyFunction,
 /* return the name of current month in appropriate language */
 getMonthLocale	: function ( month ) {
  return	this._language_month.get(this._language)[month];
 },
 getLocaleClose	: function () {
  return	this._language_close.get(this._language);
 },
 _initCurrentDate : function () {
  /* Create the DateFormatter */
  this._df = new DatePickerFormatter(
   this._language_date_format.get(this._language)[0],
   this._language_date_format.get(this._language)[1]
  );
  /* check if value in field is proper, if not set to today */
  this._current_date = $F(this._relative);
  if (! this._df.match(this._current_date)) {
    this._current_date = this._df.current_date();
   /* set the field value ? */
   if (!this._keepFieldEmpty)
    $(this._relative).value = this._current_date;
  }
  var a_date = this._df.match(this._current_date);
  this._current_year 	= Number(a_date[0]);
  this._current_mon	= Number(a_date[1]) - 1;
  this._current_day	= Number(a_date[2]);
 },
 /* init */
 initialize	: function ( h_p ) {
  /* arguments */
  this._relative= h_p["relative"];
  if (h_p["language"])
   this._language = h_p["language"];
  this._zindex	= ( h_p["zindex"] ) ? parseInt(Number(h_p["zindex"])) : 1;
  if (!Object.isUndefined(h_p["keepFieldEmpty"]))
   this._keepFieldEmpty	= h_p["keepFieldEmpty"];
  if (Object.isFunction(h_p["clickCallback"])) 
   this._clickCallback	= h_p["clickCallback"];
  if (!Object.isUndefined(h_p["leftOffset"]))
   this._leftOffset	= parseInt(h_p["leftOffset"]);
  if (!Object.isUndefined(h_p["topOffset"]))
   this._topOffset	= parseInt(h_p["topOffset"]);
  if (!Object.isUndefined(h_p["relativePosition"]))
   this._relativePosition = h_p["relativePosition"];
  if (!Object.isUndefined(h_p["showEffect"]))
   this._showEffect 	= h_p["showEffect"];
  if (!Object.isUndefined(h_p["enableShowEffect"]))
   this._enableShowEffect	= h_p["enableShowEffect"];
  if (!Object.isUndefined(h_p["showDuration"]))
   this._showDuration 	= h_p["showDuration"];
  if (!Object.isUndefined(h_p["closeEffect"]))
   this._closeEffect 	= h_p["closeEffect"];
  if (!Object.isUndefined(h_p["enableCloseEffect"]))
   this._enableCloseEffect	= h_p["enableCloseEffect"];
  if (!Object.isUndefined(h_p["closeEffectDuration"]))
   this._closeEffectDuration = h_p["closeEffectDuration"];
  if (Object.isFunction(h_p["afterClose"]))
   this._afterClose	= h_p["afterClose"];
  if (!Object.isUndefined(h_p["externalControl"]))
   this._externalControl= h_p["externalControl"];
  if (Object.isFunction(h_p["cellCallback"]))
   this._cellCallback	= h_p["cellCallback"];
  this._setPositionTop	= ( h_p["setPositionTop"] ) ? parseInt(Number(h_p["setPositionTop"])) : 0;
  this._setPositionLeft	= ( h_p["setPositionLeft"] ) ? parseInt(Number(h_p["setPositionLeft"])) : 0;
  this._id_datepicker		= 'datepicker-'+this._relative;
  this._id_datepicker_prev	= this._id_datepicker+'-prev';
  this._id_datepicker_next	= this._id_datepicker+'-next';
  this._id_datepicker_hdr	= this._id_datepicker+'-header';
  this._id_datepicker_ftr	= this._id_datepicker+'-footer';

  /* build up calendar skel */
  this._div = Builder.node('div', { 
    id 		: this._id_datepicker,
    className	: 'datepicker',
    style	: 'display: none; z-index: '+this._zindex 
   }, [
      /* header */
      Builder.node('div', { className : 'datepicker-header' }, [
       Builder.node('span', { 
	id : this._id_datepicker_prev, style : 'cursor: pointer;' }, ' << '),
       Builder.node('span', { id : this._id_datepicker_hdr }),
       Builder.node('span', { 
	id : this._id_datepicker_next, style : 'cursor: pointer;' }, ' >> ')
      ]),
      /* calendar */
      Builder.node('div', { className : 'datepicker-calendar' }, [
       Builder.node('table', { id : this._id_datepicker+'-table' }) ]),
      /* footer */
      Builder.node('div', { 
       id 	: this._id_datepicker_ftr,
       className: 'datepicker-footer' })
  ]);
  /* finally declare the event listener on input field */
  if(!this._externalControl)
  {
  Event.observe(this._relative, 
    'click', this.click.bindAsEventListener(this), false);
  }
  /* need to append on body when doc is loaded for IE */
  document.observe('dom:loaded', this.load.bindAsEventListener(this), false);
 },
 /**
  * load	: called when document is fully-loaded to append datepicker
  *		  to main object.
  */
 load		: function () {
  /* if externalControl defined set the observer on it */
  if (this._externalControl) 
   Event.observe(this._externalControl, 'click',
    this.click.bindAsEventListener(this), false);
  /* append to page */
  if (this._relativePosition) {
   /* append to parnent node */
   if ($(this._relative).parentNode) 
    $(this._relative).parentNode.appendChild( this._div );
  } else {
   /* append to body */

   var body	= document.getElementsByTagName("body").item(0);
   if (body)
    body.appendChild( this._div);
   if (this._setPositionTop || this._setPositionLeft)
    this.setPosition(this._setPositionTop, this._setPositionLeft);
  }
  /* init the date in field if needed */
  this._initCurrentDate();
  /* set the close locale content */
  $(this._id_datepicker_ftr).innerHTML = this.getLocaleClose();
  /* declare the observers for UI control */
  Event.observe($(this._id_datepicker_prev), 
    'click', this.prevMonth.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_next), 
    'click', this.nextMonth.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_ftr), 
    'click', this.close.bindAsEventListener(this), false);
 },
 /**
  * visible	: return the visibility status of the datepicker.
  */
 visible	: function () {
  return	$(this._id_datepicker).visible();
 },
 /**
  * click	: called when input element is clicked
  */
 click		: function () {
  if (!this._isPositionned && this._relativePosition) {
   /* position the datepicker relatively to element */
   var a_lt = Position.positionedOffset($(this._relative));
   $(this._id_datepicker).setStyle({
    'left'	: Number(a_lt[0]+this._leftOffset)+'px',
    'top'	: Number(a_lt[1]+this._topOffset)+'px'
   });
   this._isPositionned	= true;
  }
  if (!this.visible()) {
   this._initCurrentDate();
   this._redrawCalendar();
  }
  /* eval the clickCallback function */
  eval(this._clickCallback());
  /* Effect toggle to fade-in / fade-out the datepicker */
  if ( this._enableShowEffect ) {
   new Effect.toggle(this._id_datepicker, 
     this._showEffect, { duration: this._showDuration });
  } else {
   $(this._id_datepicker).show();
  }
 },
 /**
  * close	: called when the datepicker is closed
  */
 close		: function () {
  if ( this._enableCloseEffect ) {
   switch(this._closeEffect) {
    case 'puff': 
     new Effect.Puff(this._id_datepicker, { 
      duration : this._closeEffectDuration });
     break;
    case 'blindUp': 
     new Effect.BlindUp(this._id_datepicker, { 
      duration : this._closeEffectDuration });
     break;
    case 'dropOut': 
     new Effect.DropOut(this._id_datepicker, { 
      duration : this._closeEffectDuration }); 
     break;
    case 'switchOff': 
     new Effect.SwitchOff(this._id_datepicker, { 
      duration : this._closeEffectDuration }); 
     break;
    case 'squish': 
     new Effect.Squish(this._id_datepicker, { 
      duration : this._closeEffectDuration });
     break;
    case 'fold': 
     new Effect.Fold(this._id_datepicker, { 
      duration : this._closeEffectDuration });
     break;
    case 'shrink': 
     new Effect.Shrink(this._id_datepicker, { 
      duration : this._closeEffectDuration });
     break;
    default: 
     new Effect.Fade(this._id_datepicker, { 
      duration : this._closeEffectDuration });
     break;
   };
  } else {
   $(this._id_datepicker).hide();
  }
  eval(this._afterClose());
 },
 /**
  * setPosition	: set the position of the datepicker.
  *  param : t=top | l=left
  */
 setPosition	: function ( t, l ) {
  var h_pos	= { 'top' : '0px', 'left' : '0px' };
  if (typeof(t) != 'undefined')
   h_pos['top']	= Number(t)+this._topOffset+'px';
  if (typeof(l) != 'undefined')
   h_pos['left']= Number(l)+this._leftOffset+'px';
  $(this._id_datepicker).setStyle(h_pos);
  this._isPositionned	= true;
 },
 /**
  * _leftpad_zero : pad the provided string to given number of 0
  */
  /** CHECK toPaddedString: from http://dev.rubyonrails.org/changeset/6363 */
 _leftpad_zero	: function ( str, padToLength ) {
  var result	= '';
  for ( var i = 0; i < (padToLength - String(str).length); i++)
   result	+= '0';
  return	result + str;
 },
 /**
  * _getMonthDays : given the year and month find the number of days.
  */
 _getMonthDays	: function ( year, month ) {
  if (((0 == (year%4)) && 
   ( (0 != (year%100)) || (0 == (year%400)))) && (month == 1))
   return 29;
  return this._daysInMonth[month];
 },
 /**
  * _buildCalendar	: draw the days array for current date
  */
 _buildCalendar		: function () {
  var _self	= this;
  var tbody	= document.createElement('tbody');
  /* generate day headers */
  var trDay	= document.createElement('tr');
  this._language_day.get(this._language).each( function ( item ) {
   var td	= document.createElement('td');
   td.innerHTML	= item;
   td.className	= 'wday';
   trDay.appendChild( td );
  });
  tbody.appendChild( trDay );
  /* generate the content of days */
  
  /* build-up days matrix */
  var a_d	= [
    [ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
  ];
  /* set date at beginning of month to display */
  var d		= new Date(this._current_year, this._current_mon, 1, 12);
  /* start the day list on monday */
  var startIndex	= ( !d.getDay() ) ? 6 : d.getDay() - 1;
  var nbDaysInMonth	= this._getMonthDays(
    this._current_year, this._current_mon);
  var daysIndex		= 1;
  for ( var j = startIndex; j < 7; j++ ) {
   a_d[0][j]	= { 
     d : daysIndex
    ,m : this._current_mon
    ,y : this._current_year 
   };
   daysIndex++;
  }
  var a_prevMY	= this._prevMonthYear();
  var nbDaysInMonthPrev	= this._getMonthDays(a_prevMY[1], a_prevMY[0]);
  for ( var j = 0; j < startIndex; j++ ) {
   a_d[0][j]	= { 
     d : Number(nbDaysInMonthPrev - startIndex + j + 1) 
    ,m : Number(a_prevMY[0])
    ,y : a_prevMY[1]
    ,c : 'outbound'
   };
  }
  var switchNextMonth	= false;
  var currentMonth	= this._current_mon;
  var currentYear	= this._current_year;
  for ( var i = 1; i < 6; i++ ) {
   for ( var j = 0; j < 7; j++ ) {
    a_d[i][j]	= { 
      d : daysIndex
     ,m : currentMonth
     ,y : currentYear
     ,c : ( switchNextMonth ) ? 'outbound' : ( 
      ((daysIndex == this._todayDate.getDate()) &&
        (this._current_mon  == this._todayDate.getMonth()) &&
        (this._current_year == this._todayDate.getFullYear())) ? 'today' : null)
    };
    daysIndex++;
    /* if at the end of the month : reset counter */
    if (daysIndex > nbDaysInMonth ) {
     daysIndex	= 1;
     switchNextMonth = true;
     if (this._current_mon + 1 > 11 ) {
      currentMonth = 0;
      currentYear += 1;
     } else {
      currentMonth += 1;
     }
    }
   }
  }

  /* generate days for current date */
  for ( var i = 0; i < 6; i++ ) {
   var tr	= document.createElement('tr');
   for ( var j = 0; j < 7; j++ ) {
    var h_ij	= a_d[i][j];
    var td	= document.createElement('td');
    /* id is : datepicker-day-mon-year or depending on language other way */
    /* don't forget to add 1 on month for proper formmatting */
    var id	= $A([
     this._relative,
     this._df.date_to_string(h_ij["y"], h_ij["m"]+1, h_ij["d"], '-')
    ]).join('-');
    /* set id and classname for cell if exists */
    td.setAttribute('id', id);
    if (h_ij["c"])
     td.className	= h_ij["c"];
    /* on onclick : rebuild date value from id of current cell */
    td.onclick	= function () { 
     $(_self._relative).value = String($(this).readAttribute('id')
        ).replace(_self._relative+'-','').replace(/-/g, _self._df.separator);
     /* if we have a cellCallback defined call it and pass it the cell */
     if (_self._cellCallback)
       _self._cellCallback(this);
     _self.close(); 
    };
    td.innerHTML= h_ij["d"];
    tr.appendChild( td );
   }
   tbody.appendChild( tr );
  }
  return	tbody;
 },
 /**
  * nextMonth	: redraw the calendar content for next month.
  */
 _nextMonthYear	: function () {
  var c_mon	= this._current_mon;
  var c_year	= this._current_year;
  if (c_mon + 1 > 11) {
   c_mon	= 0;
   c_year	+= 1;
  } else {
   c_mon	+= 1;
  }
  return	[ c_mon, c_year ];
 },
 nextMonth	: function () {
  var a_next		= this._nextMonthYear();
  this._current_mon	= a_next[0];
  this._current_year 	= a_next[1];
  this._redrawCalendar();
 },
 /**
  * prevMonth	: redraw the calendar content for previous month.
  */
 _prevMonthYear	: function () {
  var c_mon	= this._current_mon;
  var c_year	= this._current_year;
  if (c_mon - 1 < 0) {
   c_mon	= 11;
   c_year	-= 1;
  } else {
   c_mon	-= 1;
  }
  return	[ c_mon, c_year ];
 },
 prevMonth	: function () {
  var a_prev		= this._prevMonthYear();
  this._current_mon	= a_prev[0];
  this._current_year 	= a_prev[1];
  this._redrawCalendar();
 },
 _redrawCalendar	: function () {
  this._setLocaleHdr();
  var table	= $(this._id_datepicker+'-table');
  try {
   while ( table.hasChildNodes() )
    table.removeChild(table.childNodes[0]);
  } catch ( e ) {};
  table.appendChild( this._buildCalendar() );
 },
 _setLocaleHdr	: function () {
  /* next link */
  var a_next	= this._nextMonthYear();
  $(this._id_datepicker_next).setAttribute('title',
   this.getMonthLocale(a_next[0])+' '+a_next[1]);
  /* prev link */
  var a_prev	= this._prevMonthYear();
  $(this._id_datepicker_prev).setAttribute('title',
   this.getMonthLocale(a_prev[0])+' '+a_prev[1]);
  /* header */
  $(this._id_datepicker_hdr).update('&nbsp;&nbsp;&nbsp;'+this.getMonthLocale(this._current_mon)+'&nbsp;'+this._current_year+'&nbsp;&nbsp;&nbsp;');
 }
};


/* -------------------------------------------------------------------------------------------------------------------------
	CODE FOR MODAL BOX AND KT DOCUMENT LINKER
   ------------------------------------------------------------------------------------------------------------------------ */

if (!window.Modalbox)
	var Modalbox = new Object();

Modalbox.Methods = {
	overrideAlert: false, // Override standard browser alert message with ModalBox
	focusableElements: new Array,
	options: {
		title: "ModalBox Window", // Title of the ModalBox window
		overlayClose: true, // Close modal box by clicking on overlay
		width: 500, // Default width in px
		height: 90, // Default height in px
		overlayOpacity: .75, // Default overlay opacity
		overlayDuration: .25, // Default overlay fade in/out duration in seconds
		slideDownDuration: .5, // Default Modalbox appear slide down effect in seconds
		slideUpDuration: .15, // Default Modalbox hiding slide up effect in seconds
		resizeDuration: .2, // Default resize duration seconds
		inactiveFade: true, // Fades MB window on inactive state
		transitions: true, // Toggles transition effects. Transitions are enabled by default
		loadingString: "Please wait. Loading...", // Default loading string message
		closeString: "Close window", // Default title attribute for close window link
		params: {},
		method: 'get' // Default Ajax request method
	},
	_options: new Object,
	
	setOptions: function(options) {
		Object.extend(this.options, options || {});
	},
	
	_init: function(options) {
		// Setting up original options with default options
		Object.extend(this._options, this.options);
		this.setOptions(options);
		//Create the overlay
		this.MBoverlay = Builder.node("div", { id: "MB_overlay", opacity: "0" });
		//Create the window
		this.MBwindow = Builder.node("div", {id: "MB_window", style: "display: none"}, [
			this.MBframe = Builder.node("div", {id: "MB_frame"}, [
				this.MBheader = Builder.node("div", {id: "MB_header"}, [
					this.MBcaption = Builder.node("div", {id: "MB_caption"}),
					this.MBclose = Builder.node("a", {id: "MB_close", title: this.options.closeString, href: "#"}, [
						Builder.build("<span>&times;</span>"),
					]),
				]),
				this.MBcontent = Builder.node("div", {id: "MB_content"}, [
					this.MBloading = Builder.node("div", {id: "MB_loading"}, this.options.loadingString),
				]),
			]),
		]);
		
		// If title isn't given, the header will not displayed 
		if(!this.options.title) this.MBheader.hide();
		
		// Inserting into DOM
		document.body.insertBefore(this.MBwindow, document.body.childNodes[0]);
		document.body.insertBefore(this.MBoverlay, document.body.childNodes[0]);
		
		// Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
		this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
		this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		
		//Adding event observers
		this.hide = this.hide.bindAsEventListener(this);
		this.close = this._hide.bindAsEventListener(this);
		this.kbdHandler = this.kbdHandler.bindAsEventListener(this);
		this._initObservers();

		this.initialized = true; // Mark as initialized
		this.active = true; // Mark as active
		this.currFocused = 0;
	},
	
	show: function(content, options) {
		if(!this.initialized) this._init(options); // Check for is already initialized
		
		this.content = content;
		this.setOptions(options);
		
		Element.update(this.MBcaption, this.options.title); // Updating title of the MB
		
		if(this.MBwindow.style.display == "none") { // First modal box appearing
			this._appear();
			this.event("onShow"); // Passing onShow callback
		}
		else { // If MB already on the screen, update it
			this._update();
			this.event("onUpdate"); // Passing onUpdate callback
		} 
	},
	
	hide: function(options) { // External hide method to use from external HTML and JS
		if(this.initialized) {
			if(options) Object.extend(this.options, options); // Passing callbacks
			if(this.options.transitions)
				Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, afterFinish: this._deinit.bind(this) } );
			else {
				Element.hide(this.MBwindow);
				this._deinit();
			}
		} else throw("Modalbox isn't initialized");
	},
	
	alert: function(message){
		var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
		Modalbox.show(html, {title: 'Alert: ' + document.title, width: 300});
	},
		
	_hide: function(event) { // Internal hide method to use inside MB class
		if(event) Event.stop(event);
		this.hide();
	},
	
	_appear: function() { // First appearing of MB
		if(navigator.appVersion.match(/\bMSIE\b/))
			this._toggleSelects();
		this._setOverlay();
		this._setWidth();
		this._setPosition();
		if(this.options.transitions) {
			Element.setStyle(this.MBoverlay, {opacity: 0});
			new Effect.Fade(this.MBoverlay, {
					from: 0, 
					to: this.options.overlayOpacity, 
					duration: this.options.overlayDuration, 
					afterFinish: function() {
						new Effect.SlideDown(this.MBwindow, {
							duration: this.options.slideDownDuration, 
							afterFinish: function(){ 
								this._setPosition(); 
								this.loadContent();
							}.bind(this)
						});
					}.bind(this)
			});
		} else {
			Element.setStyle(this.MBoverlay, {opacity: this.options.overlayOpacity});
			Element.show(this.MBwindow);
			this._setPosition(); 
			this.loadContent();
		}
		this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
		Event.observe(window, "resize", this._setWidthAndPosition);
	},
	
	resize: function(byWidth, byHeight, options) { // Change size of MB without loading content
		var wHeight = Element.getHeight(this.MBwindow);
		var wWidth = Element.getWidth(this.MBwindow);
		var hHeight = Element.getHeight(this.MBheader);
		var cHeight = Element.getHeight(this.MBcontent);
		var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight - wHeight) : byHeight;
		this.setOptions(options); // Passing callbacks
		if(this.options.transitions) {
			new Effect.ScaleBy(this.MBwindow, byWidth, newHeight, {
					duration: this.options.resizeDuration, 
				  	afterFinish: function() { 
						this.event("_afterResize"); // Passing internal callback
						this.event("afterResize"); // Passing callback
					}.bind(this)
				});
		} else {
			this.MBwindow.setStyle({width: wWidth + byWidth + "px", height: wHeight + newHeight + "px"});
			setTimeout(function() {
				this.event("_afterResize"); // Passing internal callback
				this.event("afterResize"); // Passing callback
			}.bind(this), 1);
			
		}
		
	},
	
	_update: function() { // Updating MB in case of wizards
		Element.update(this.MBcontent, "");
		this.MBcontent.appendChild(this.MBloading);
		Element.update(this.MBloading, this.options.loadingString);
		this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];
		Modalbox.resize((this.options.width - this.currentDims[0]), (this.options.height - this.currentDims[1]), {_afterResize: this._loadAfterResize.bind(this) });
	},
	
	loadContent: function () {
		if(this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
			if(typeof this.content == 'string') {
				
				var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
				if(htmlRegExp.test(this.content)) { // Plain HTML given as a parameter
					this._insertContent(this.content);
					this._putContent();
				} else 
					new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params, 
						onComplete: function(transport) {
							var response = new String(transport.responseText);
							this._insertContent(transport.responseText.stripScripts());
							response.extractScripts().map(function(script) { 
								return eval(script.replace("<!--", "").replace("// -->", ""));
							}.bind(window));
							this._putContent();
						}.bind(this)
					});
					
			} else if (typeof this.content == 'object') {// HTML Object is given
				this._insertContent(this.content);
				this._putContent();
			} else {
				Modalbox.hide();
				throw('Please specify correct URL or HTML element (plain HTML or object)');
			}
		}
	},
	
	_insertContent: function(content){
		Element.extend(this.MBcontent);
		this.MBcontent.update("");
		if(typeof content == 'string')
			this.MBcontent.hide().update(content);
		else if (typeof this.content == 'object') { // HTML Object is given
			var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
			// If clonable element has ID attribute defined, modifying it to prevent duplicates
			if(this.content.id) this.content.id = "MB_" + this.content.id;
			/* Add prefix for IDs on all elements inside the DOM node */
			this.content.getElementsBySelector('*[id]').each(function(el){ el.id = "MB_" + el.id });
			this.MBcontent.hide().appendChild(_htmlObj);
			this.MBcontent.down().show(); // Toggle visibility for hidden nodes
			if(navigator.appVersion.match(/\bMSIE\b/)) // Toggling back visibility for hidden selects in IE
				$$("#MB_content select").invoke('setStyle', {'visibility': ''});
		}
	},
	
	_putContent: function(){
		// Prepare and resize modal box for content
		if(this.options.height == this._options.height)
			Modalbox.resize(0, this.MBcontent.getHeight() - Element.getHeight(this.MBwindow) + Element.getHeight(this.MBheader), {
				afterResize: function(){
					this.MBcontent.show();
					this.focusableElements = this._findFocusableElements();
					this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
					this.event("afterLoad"); // Passing callback
				}.bind(this)
			});
		else { // Height is defined. Creating a scrollable window
			this._setWidth();
			this.MBcontent.setStyle({overflow: 'auto', height: Element.getHeight(this.MBwindow) - Element.getHeight(this.MBheader) - 13 + 'px'});
			this.MBcontent.show();
			this.focusableElements = this._findFocusableElements();
			this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
			this.event("afterLoad"); // Passing callback
		}
	},
	
	activate: function(options){
		this.setOptions(options);
		this.active = true;
		Event.observe(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
		Element.show(this.MBclose);
		if(this.options.transitions && this.options.inactiveFade) new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
	},
	
	deactivate: function(options) {
		this.setOptions(options);
		this.active = false;
		Event.stopObserving(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
		Element.hide(this.MBclose);
		if(this.options.transitions && this.options.inactiveFade) new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
	},
	
	_initObservers: function(){
		Event.observe(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
		Event.observe(document, "keypress", Modalbox.kbdHandler );
	},
	
	_removeObservers: function(){
		Event.stopObserving(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
		Event.stopObserving(document, "keypress", Modalbox.kbdHandler );
	},
	
	_loadAfterResize: function() {
		this._setWidth();
		this._setPosition();
		this.loadContent();
	},
	
	_setFocus: function() { // Setting focus to be looped inside current MB
		if(this.focusableElements.length > 0) {
			var i = 0;
			var firstEl = this.focusableElements.find(function (el){
				i++;
				return el.tabIndex == 1;
			}) || this.focusableElements.first();
			this.currFocused = (i == this.focusableElements.length - 1) ? (i-1) : 0;
			firstEl.focus(); // Focus on first focusable element except close button
		} else
			$("MB_close").focus(); // If no focusable elements exist focus on close button
	},
	
	_findFocusableElements: function(){ // Collect form elements or links from MB content
		var els = this.MBcontent.getElementsBySelector('input:not([type~=hidden]), select, textarea, button, a[href]');
		els.invoke('addClassName', 'MB_focusable');
		return this.MBcontent.getElementsByClassName('MB_focusable');
	},
	
	kbdHandler: function(e) {
		var node = Event.element(e);
		switch(e.keyCode) {
			case Event.KEY_TAB:
				Event.stop(e);
				if(!e.shiftKey) { //Focusing in direct order
					if(this.currFocused == this.focusableElements.length - 1) {
						this.focusableElements.first().focus();
						this.currFocused = 0;
					} else {
						this.currFocused++;
						this.focusableElements[this.currFocused].focus();
					}
				} else { // Shift key is pressed. Focusing in reverse order
					if(this.currFocused == 0) {
						this.focusableElements.last().focus();
						this.currFocused = this.focusableElements.length - 1;
					} else {
						this.currFocused--;
						this.focusableElements[this.currFocused].focus();
					}
				}
				break;			
			case Event.KEY_ESC:
				if(this.active) this._hide(e);
				break;
			case 32:
				this._preventScroll(e);
				break;
			case 0: // For Gecko browsers compatibility
				if(e.which == 32) this._preventScroll(e);
				break;
			case Event.KEY_UP:
			case Event.KEY_DOWN:
			case Event.KEY_PAGEDOWN:
			case Event.KEY_PAGEUP:
			case Event.KEY_HOME:
			case Event.KEY_END:
				// Safari operates in slightly different way. This realization is still buggy in Safari.
				if(/Safari|KHTML/.test(navigator.userAgent) && !["textarea", "select"].include(node.tagName.toLowerCase()))
					Event.stop(e);
				else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
					Event.stop(e);
				break;
		}
	},
	
	_preventScroll: function(event) { // Disabling scrolling by "space" key
		if(!["input", "textarea", "select", "button"].include(Event.element(event).tagName.toLowerCase())) 
			Event.stop(event);
	},
	
	_deinit: function()
	{	
		this._removeObservers();
		Event.stopObserving(window, "resize", this._setWidthAndPosition );
		if(this.options.transitions) {
			Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
		} else {
			this.MBoverlay.hide();
			this._removeElements();
		}
		Element.setStyle(this.MBcontent, {overflow: '', height: ''});
	},
	
	_removeElements: function () {
		if(navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
			window.scrollTo(this.initScrollX, this.initScrollY);
		}
		Element.remove(this.MBoverlay);
		Element.remove(this.MBwindow);
		
		/* Replacing prefixes 'MB_' in IDs for the original content */
		if(typeof this.content == 'object' && this.content.id && this.content.id.match(/MB_/)) {
			this.content.getElementsBySelector('*[id]').each(function(el){ el.id = el.id.replace(/MB_/, ""); });
			this.content.id = this.content.id.replace(/MB_/, "");
		}
		/* Initialized will be set to false */
		this.initialized = false;
		
		if(navigator.appVersion.match(/\bMSIE\b/))
			this._toggleSelects(); // Toggle back 'select' elements in IE
		this.event("afterHide"); // Passing afterHide callback
		this.setOptions(this._options); //Settings options object into intial state
	},
	
	_setOverlay: function () {
		if(navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("100%", "hidden");
			if (!navigator.appVersion.match(/\b7.0\b/)) window.scrollTo(0,0); // Disable scrolling on top for IE7
		}
	},
	
	_setWidth: function () { //Set size
		Element.setStyle(this.MBwindow, {width: this.options.width + "px", height: this.options.height + "px"});
	},
	
	_setPosition: function () {
		Element.setStyle(this.MBwindow, {left: Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2 ) + "px"});
	},
	
	_setWidthAndPosition: function () {
		Element.setStyle(this.MBwindow, {width: this.options.width + "px"});
		this._setPosition();
	},
	
	_getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop)
			theTop = document.documentElement.scrollTop;
		else if (document.body)
			theTop = document.body.scrollTop;
		return theTop;
	},
	// For IE browsers -- IE requires height to 100% and overflow hidden (taken from lightbox)
	_prepareIE: function(height, overflow){
		var body = document.getElementsByTagName('body')[0];
		body.style.height = height;
		body.style.overflow = overflow;
  
		var html = document.getElementsByTagName('html')[0];
		html.style.height = height;
		html.style.overflow = overflow; 
	},
	// For IE browsers -- hiding all SELECT elements
	_toggleSelects: function() {
		var selects = $$("select");
		if(this.initialized) {
			selects.invoke('setStyle', {'visibility': 'hidden'});
		} else {
			selects.invoke('setStyle', {'visibility': ''});
		}
			
	},
	event: function(eventName) {
		if(this.options[eventName]) {
			var returnValue = this.options[eventName](); // Executing callback
			this.options[eventName] = null; // Removing callback after execution
			if(returnValue != undefined) 
				return returnValue;
			else 
				return true;
		}
		return true;
	}
}

Object.extend(Modalbox, Modalbox.Methods);

if(Modalbox.overrideAlert) window.alert = Modalbox.alert;

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
  initialize: function(element, byWidth, byHeight, options) {
    this.element = $(element)
    var options = Object.extend({
	  scaleFromTop: true,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleByWidth: byWidth,
	  scaleByHeight: byHeight
    }, arguments[3] || {});
    this.start(options);
  },
  setup: function() {
    this.elementPositioning = this.element.getStyle('position');
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
	
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
	 if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
	  
	this.deltaY = this.options.scaleByHeight;
	this.deltaX = this.options.scaleByWidth;
  },
  update: function(position) {
    var currentHeight = this.dims[0] + (this.deltaY * position);
	var currentWidth = this.dims[1] + (this.deltaX * position);
	
	currentHeight = (currentHeight > 0) ? currentHeight : 0;
	currentWidth = (currentWidth > 0) ? currentWidth : 0;
	
    this.setDimensions(currentHeight, currentWidth);
  },

  setDimensions: function(height, width) {
    var d = {};
    d.width = width + 'px';
    d.height = height + 'px';
    
	var topd  = Math.round((height - this.dims[0])/2);
	var leftd = Math.round((width  - this.dims[1])/2);
	if(this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
		if(!this.options.scaleFromTop) d.top = this.originalTop-topd + 'px';
		d.left = this.originalLeft-leftd + 'px';
	} else {
		if(!this.options.scaleFromTop) d.top = -topd + 'px';
		d.left = -leftd + 'px';
	}
    this.element.setStyle(d);
  }
});

// JavaScript Document

	function fireFilesUpdate(strFolderId)
	{
		var strVs = $('fbcviewstate').value;
		var reqUrl = '/kt/doclink/ajax_files.php?action=list-folder&folder=' + strFolderId + '&fbcviewstate=' + strVs;
		$('docLoadIndicator').style.display = 'inline';
		
		new Ajax.Updater('filebrowser', reqUrl, 
						 {	onComplete:function() {$('docLoadIndicator').style.display = 'none';},
						 	asynchronous:true
						 });
	}
	
	function changeDoc()
	{
		new Effect.BlindDown('filebrowser', {duration: 0.5, queue: 'front'});
		new Effect.SlideUp('vinfo', {duration: 0.5, queue: 'end'});		
	}
	
	function selectDoc(docId, docTitle)
	{
		// called when a document is selected, uses scriptaculous effects
		
		// update hidden fields		
			$('ktDocumentId').value = docId;
		
		// update visual bits so user sees document is selected
			$('docInfo').update(docTitle);
			
		// un-hide info box but hide the file browser
			new Effect.BlindDown('vinfo', {duration: 0.3, queue: 'front'});
			new Effect.SlideUp('filebrowser', {duration: 0.3, queue: 'end'});
			
			newInfoNode = document.createElement('div');
	}
	
	function switchForms()
	{
		var value = $('destination').options[$('destination').selectedIndex].value;
		
		$('KTForm').style.display = value == '1' ? 'block' : 'none';
		$('CCMSForm').style.display = value != '1' ? 'block' : 'none';		
	}
