﻿/* ********************************************************************
 **********************************************************************
 * HTML Virtual Keyboard Interface Script - v1.24
 *   Copyright (c) 2009 - GreyWyvern
 *
 *  - Licenced for free distribution under the BSDL
 *          http://www.opensource.org/licenses/bsd-license.php
 *
 * Add a script-driven keyboard interface to text fields, password
 * fields and textareas.
 *
 * See http://www.greywyvern.com/code/javascript/keyboard for examples
 * and usage instructions.
 *
 *This Version Modified for snap surveys, www.snapsurveys.com, starting from Version 1.24
 * Version 1.24 - May 12, 2009
 *   - Belarusian, Serbian Cyrillic and Serbian Latin keyboard layouts added (Evgeniy Titov)
 *   - Fix for maxlength attribute on textareas
 *
 *   See full changelog at:
 *     http://www.greywyvern.com/code/javascript/keyboard.changelog.txt
 *
 * Keyboard Credits
 *   - Belarusian, Serbian Cyrillic and Serbian Latin keyboard layouts by Evgeniy Titov
 *   - Bulgarian Phonetic keyboard layout by Samuil Gospodinov
 *   - Swedish keyboard layout by Håkan Sandberg
 *   - Romanian keyboard layout by Aurel
 *   - Farsi (Persian) keyboard layout by Kaveh Bakhtiyari (www.bakhtiyari.com)
 *   - Burmese keyboard layout by Cetanapa
 *   - Slovenian keyboard layout by Miran Zeljko
 *   - Hungarian keyboard layout by Antal Sall 'Hiromacu'
 *   - Arabic keyboard layout by Srinivas Reddy
 *   - Italian and Spanish (Spain) keyboard layouts by dictionarist.com
 *   - Lithuanian and Russian keyboard layouts by Ramunas
 *   - German keyboard layout by QuHno
 *   - French keyboard layout by Hidden Evil
 *   - Polish Programmers layout by moose
 *   - Turkish keyboard layouts by offcu
 *   - Dutch and US Int'l keyboard layouts by jerone
 *   - Portuguese keyboard layout by clisboa
 *
 */
var DTI_attach, DTI_close;
  function DTI_buildKeyboardInputs(inputElems) {
    var self = this;

    this.DTI_version = "1.24";
    this.DTI_target = this.DTI_visible = false;
    this.DTI_shift = this.DTI_capslock = this.DTI_alternate = this.DTI_dead = false;
    this.DTI_deadkeysOn = false;
    this.DTI_kt = "US Int'l";  // Default keyboard layout
    this.DTI_clearPasswords = false;  // Clear password fields on focus
    this.DTI_showVersion = false;
    this.DTI_clickless = false;
    this.DTI_clicklessDelay = 500;
    this.DTI_keyCenter = 3;

    this.DTI_isIE = /*@cc_on!@*/false;    
    this.DTI_useIFrame = /MSIE 6/i.test(navigator.userAgent);
    this.DTI_isIElt8 = /*@if(@_jscript_version < 5.8)!@end@*/false;
    this.DTI_isMoz = (navigator.product == "Gecko");
    this.DTI_isWebKit = RegExp("KHTML").test(navigator.userAgent);
	this.DTI_date = new Date();


    /* ***** Create keyboards ************************************** */
    this.DTI_layout = {};
    this.DTI_layoutDDK = {};

    // - Lay out each keyboard in rows of sub-arrays.  Each sub-array
    //   represents one key.
    //
    // - Each sub-array consists of four slots described as follows:
    //     example: ["a", "A", "\u00e1", "\u00c1"]
    //
    //          a) Normal character
    //          A) Character + Shift or Caps
    //     \u00e1) Character + Alt or AltGr
    //     \u00c1) Character + Shift or Caps + Alt or AltGr
    //
    //   You may include sub-arrays which are fewer than four slots.
    //   In these cases, the missing slots will be blanked when the
    //   corresponding modifier key (Shift or AltGr) is pressed.
    //
    // - If the second slot of a sub-array matches one of the following
    //   strings:
    //       "Tab", "Caps", "Shift", "Enter", "Bksp", "Alt" OR "AltGr"
    //   then the function of the key will be the following,
    //   respectively:
    //     - Insert a tab
    //     - Toggle Caps Lock (technically a Shift Lock)
    //     - Next entered character will be the shifted character
    //     - Insert a newline (textarea), or close the keyboard
    //     - Delete the previous character
    //     - Next entered character will be the alternate character
    //
    //   The first slot of this sub-array will be the text to display
    //   on the corresponding key.  This allows for easy localisation
    //   of key names.
    //
    // - Layout dead keys (diacritic + letter) should be added as
    //   arrays of two item arrays with hash keys equal to the
    //   diacritic.  See the "this.DTI_deadkey" object below the layout
    //   definitions.  In  each two item child array, the second item
    //   is what the diacritic would change the first item to.
    //
    // - To disable dead keys for a layout, simply assign true to the
    //   this.DTI_layoutDDK (DDK = disable dead keys) object of the
    //   same name as the layout.  See the Numpad layout below for an
    //   example.
    //
    // - Note that any characters beyond the normal ASCII set should be
    //   entered in escaped Unicode format.  (eg \u00a3 = Pound symbol)
    //   You can find Unicode values for characters here:
    //     http://unicode.org/charts/
    //
    // - To remove a keyboard, just delete it, or comment it out of the
    //   source code

   this.DTI_layout.Numpad = [ // Number pad
      [["$"], ["\u00a3"], ["\u20ac"], ["\u00a5"], ["/"], ["^"], ["Bksp", "Bksp"]],
      [["."], ["7"], ["8"], ["9"], ["*"], ["<"], ["("], ["["]],
      [["="], ["4"], ["5"], ["6"], ["-"], [">"], [")"], ["]"]],
      [["0"], ["1"], ["2"], ["3"], ["+"], ["Enter", "Enter"]],
      [[" "]]
    ];
    this.DTI_layoutDDK.Numpad = true;


    /* ***** Define Dead Keys ************************************** */
    this.DTI_deadkey = {};

    // - Lay out each dead key set in one row of sub-arrays.  The rows
    //   below are wrapped so uppercase letters are below their
    //   lowercase equivalents.
    //
    // - The first letter in each sub-array is the letter pressed after
    //   the diacritic.  The second letter is the letter this key-combo
    //   will generate.
    //
    // - Note that if you have created a new keyboard layout and want
    //   it included in the distributed script, PLEASE TELL ME if you
    //   have added additional dead keys to the ones below.

    this.DTI_deadkey['"'] = this.DTI_deadkey['\u00a8'] = [ // Umlaut / Diaeresis / Greek Dialytika
      ["a", "\u00e4"], ["e", "\u00eb"], ["i", "\u00ef"], ["o", "\u00f6"], ["u", "\u00fc"], ["y", "\u00ff"], ["\u03b9", "\u03ca"], ["\u03c5", "\u03cb"],
      ["A", "\u00c4"], ["E", "\u00cb"], ["I", "\u00cf"], ["O", "\u00d6"], ["U", "\u00dc"], ["Y", "\u0178"], ["\u0399", "\u03aa"], ["\u03a5", "\u03ab"]
    ];
    this.DTI_deadkey['~'] = [ // Tilde
      ["a", "\u00e3"], ["o", "\u00f5"], ["n", "\u00f1"],
      ["A", "\u00c3"], ["O", "\u00d5"], ["N", "\u00d1"]
    ];
    this.DTI_deadkey['^'] = [ // Circumflex
      ["a", "\u00e2"], ["e", "\u00ea"], ["i", "\u00ee"], ["o", "\u00f4"], ["u", "\u00fb"], ["w", "\u0175"], ["y", "\u0177"],
      ["A", "\u00c2"], ["E", "\u00ca"], ["I", "\u00ce"], ["O", "\u00d4"], ["U", "\u00db"], ["W", "\u0174"], ["Y", "\u0176"]
    ];
    this.DTI_deadkey['\u02c7'] = [ // Baltic caron
      ["c", "\u010D"], ["s", "\u0161"], ["z", "\u017E"], ["r", "\u0159"], ["d", "\u010f"], ["t", "\u0165"], ["n", "\u0148"], ["l", "\u013e"], ["e", "\u011b"],
      ["C", "\u010C"], ["S", "\u0160"], ["Z", "\u017D"], ["R", "\u0158"], ["D", "\u010e"], ["T", "\u0164"], ["N", "\u0147"], ["L", "\u013d"], ["E", "\u011a"]
    ];
    this.DTI_deadkey['\u02d8'] = [ // Romanian and Turkish breve
      ["a", "\u0103"], ["g", "\u011f"],
      ["A", "\u0102"], ["G", "\u011e"]
    ];
    this.DTI_deadkey['`'] = [ // Grave
      ["a", "\u00e0"], ["e", "\u00e8"], ["i", "\u00ec"], ["o", "\u00f2"], ["u", "\u00f9"],
      ["A", "\u00c0"], ["E", "\u00c8"], ["I", "\u00cc"], ["O", "\u00d2"], ["U", "\u00d9"]
    ];
    this.DTI_deadkey["'"] = this.DTI_deadkey['\u00b4'] = this.DTI_deadkey['\u0384'] = [ // Acute / Greek Tonos
      ["a", "\u00e1"], ["e", "\u00e9"], ["i", "\u00ed"], ["o", "\u00f3"], ["u", "\u00fa"], ["y", "\u00fd"], ["\u03b1", "\u03ac"], ["\u03b5", "\u03ad"], ["\u03b7", "\u03ae"], ["\u03b9", "\u03af"], ["\u03bf", "\u03cc"], ["\u03c5", "\u03cd"], ["\u03c9", "\u03ce"],
      ["A", "\u00c1"], ["E", "\u00c9"], ["I", "\u00cd"], ["O", "\u00d3"], ["U", "\u00da"], ["Y", "\u00dd"], ["\u0391", "\u0386"], ["\u0395", "\u0388"], ["\u0397", "\u0389"], ["\u0399", "\u038a"], ["\u039f", "\u038c"], ["\u03a5", "\u038e"], ["\u03a9", "\u038f"]
    ];
    this.DTI_deadkey['\u02dd'] = [ // Hungarian Double Acute Accent
      ["o", "\u0151"], ["u", "\u0171"],
      ["O", "\u0150"], ["U", "\u0170"]
    ];
    this.DTI_deadkey['\u0385'] = [ // Greek Dialytika + Tonos
      ["\u03b9", "\u0390"], ["\u03c5", "\u03b0"]
    ];
    this.DTI_deadkey['\u00b0'] = this.DTI_deadkey['\u00ba'] = [ // Ring
      ["a", "\u00e5"], ["u", "\u016f"],
      ["A", "\u00c5"], ["U", "\u016e"]
    ];
    this.DTI_deadkey['\u02DB'] = [ // Ogonek
      ["a", "\u0106"], ["e", "\u0119"], ["i", "\u012f"], ["o", "\u01eb"], ["u", "\u0173"], ["y", "\u0177"],
      ["A", "\u0105"], ["E", "\u0118"], ["I", "\u012e"], ["O", "\u01ea"], ["U", "\u0172"], ["Y", "\u0176"]
    ];
    this.DTI_deadkey['\u02D9'] = [ // Dot-above
      ["c", "\u010B"], ["e", "\u0117"], ["g", "\u0121"], ["z", "\u017C"],
      ["C", "\u010A"], ["E", "\u0116"], ["G", "\u0120"], ["Z", "\u017B"]
    ];
    this.DTI_deadkey['\u00B8'] = this.DTI_deadkey['\u201a'] = [ // Cedilla
      ["c", "\u00e7"], ["s", "\u015F"],
      ["C", "\u00c7"], ["S", "\u015E"]
    ];
    this.DTI_deadkey[','] = [ // Comma
      ["s", (this.DTI_isIElt8) ? "\u015F" : "\u0219"], ["t", (this.DTI_isIElt8) ? "\u0163" : "\u021B"],
      ["S", (this.DTI_isIElt8) ? "\u015E" : "\u0218"], ["T", (this.DTI_isIElt8) ? "\u0162" : "\u021A"]
    ];



    /* ****************************************************************
     * Attach the keyboard to an element
     *
     */
    this.DTI_attachKeyboard = DTI_attach = function(elem, styleName) {
      if (elem.DTI_attached) return false;
      var keybut = document.createElement('img');
		keybut.src = pickerIconName(styleName, "calendar.gif");
		var size = pickerIconSize(styleName);
		if (0 < size) keybut.height = keybut.width = size;
      keybut.alt = "Date picker";
      keybut.className = "keyboardInputInitiator";
      keybut.title = "Show date picker";
      keybut.elem = elem;
      keybut.keyStyle = pickerStyle(styleName);
      keybut.onclick = function() { self.DTI_show(this.elem, this.keyStyle); };
      elem.DTI_attached = true;
      elem.parentNode.insertBefore(keybut, elem);
      if (this.DTI_isIE) {
        elem.onclick = elem.onselect = elem.onkeyup = function(e) {
          if ((e || event).type != "keyup" || !this.readOnly)
            this.range = document.selection.createRange();
        };
      }
    };


    var DTI_ClickAway=function(){self.DTI_close(true);};
    /* ***** Find tagged input & textarea elements ***************** */
    for (var x = 0, elem; elem = inputElems[x++];)
      for (var y = 0, ex; ex = elem[y++];)
      {
        if ((ex.nodeName == "TEXTAREA" || ex.type == "text" || ex.type == "password") && ex.className.indexOf("dateInput") > -1)
          this.DTI_attachKeyboard(ex, ex.className);
        else if (ex.attachEvent)
		  {	ex.attachEvent("onfocus", DTI_ClickAway);
		  } else if (ex.addEventListener)
		  {	ex.addEventListener("focus", DTI_ClickAway, true);
		  }
      }


    /* ***** Build the keyboard interface ************************** */
    this.DTI_keyboard = document.createElement('table');
    this.DTI_keyboard.className = "keyboardInputMaster keyboardInputMedium";
    this.DTI_keyboard.dir = "ltr";
    this.DTI_keyboard.cellSpacing = this.DTI_keyboard.border = "0";

    var thead = document.createElement('thead');
	
      var tr = document.createElement('tr');
        var th = document.createElement('th');
          tr.appendChild(th);
		  
        var td = document.createElement('td');
          var clearer = document.createElement('span');
              clearer.id = "dateInputClear";
              clearer.appendChild(document.createTextNode("Clear"));
              clearer.title = "Clear this input";
              clearer.onmousedown = function() { this.className = "pressed"; };
              clearer.onmouseup = function() { this.className = ""; };
              clearer.onclick = function() {
                self.DTI_target.value = "";
                self.DTI_target.focus();
                return false;
              };
            td.appendChild(clearer);

          var closer = document.createElement('span');
              closer.id = "dateInputClose";
              closer.appendChild(document.createTextNode('Close'));
              closer.title = "Close this window";
              closer.onmousedown = function() { this.className = "pressed"; };
              closer.onmouseup = function() { this.className = ""; };
              closer.onclick = function() { self.DTI_close(); };
            td.appendChild(closer);

          tr.appendChild(td);
        thead.appendChild(tr);
    this.DTI_keyboard.appendChild(thead);

    var tbody = document.createElement('tbody');
	
      var tr = document.createElement('tr');
        var td = document.createElement('td');
            td.colSpan = "2";
          var div = document.createElement('div');
              div.className = "keyboardInputLayout";
            td.appendChild(div);
          if (this.DTI_showVersion) {
            var div = document.createElement('div');
              var ver = document.createElement('var');
                  ver.appendChild(document.createTextNode("v" + this.DTI_version));
                div.appendChild(ver);
              td.appendChild(div);
          }
          tr.appendChild(td);
        tbody.appendChild(tr);
		
    this.DTI_keyboard.appendChild(tbody);

    if (this.DTI_useIFrame) {
      this.DTI_iframe = document.createElement('iframe');
      this.DTI_iframe.style.position = "absolute";
      this.DTI_iframe.style.border = "0px none";
      this.DTI_iframe.style.filter = "mask()";
      this.DTI_iframe.style.zIndex = "999999";
    }

this.DTI_startingMonth = function(year, month)
{
  var thisDay = new Date();
 
  if ((month >= 0) && (year > 0))
  {
    thisDay = new Date(year, month, 1);
  } else
  {
    //day = thisDay.getDate();
    thisDay.setDate(1);
  }
  return thisDay;
};
/*
this.DTI_startingMonth = function(dateVal)
{
  var thisDay = new Date();
	if(dateVal)
		thisDay = dateVal;
 
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
  return thisDay;
};
*/
this.DTI_getButtonCode = function(container, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  while (newMonth < 0)
  {
    newMonth += 12;
    newYear += -1;
  }
  //var bt=document.createElement('button');
  var bt=container;
  bt.onclick = function()
  {
	//refreshDatePicker(\"" + datePickerDivID + "\",\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
	//self.DTI_show(this.elem);
	self.DTI_date.setMonth(newMonth);
	self.DTI_date.setYear(newYear);
	self.DTI_buildKeys();
  };
	bt.onmouseover = function() {
	this.className += " hover";
	};
	bt.onmouseout = function() {
	this.className = this.className.replace(/ ?(hover|pressed)/g, "");
	};
	bt.onmousedown = function() {
	this.className += " pressed";
	};
	bt.onmouseup = function() {
	this.className = this.className.replace(/ ?pressed/g, "");
	};
  bt.ondblclick = function()
  {
	//refreshDatePicker(\"" + datePickerDivID + "\",\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
	//self.DTI_show(this.elem);
	self.DTI_date.setMonth(newMonth);
	self.DTI_date.setYear(newYear);
	self.DTI_buildKeys();
  };
  bt.appendChild(document.createTextNode(label));
  //container.appendChild(bt);
};

    /* ****************************************************************
     * Build or rebuild the keyboard keys
     *
     */
    this.DTI_buildKeys = function() {
      this.DTI_shift = this.DTI_capslock = this.DTI_alternate = this.DTI_dead = false;
	  this.DTI_deadkeysOn=false;
      //this.DTI_deadkeysOn = (this.DTI_layoutDDK[this.DTI_kt]) ? false : this.DTI_keyboard.getElementsByTagName('label')[0].getElementsByTagName('input')[0].checked;

      var container = this.DTI_keyboard.tBodies[0].getElementsByTagName('div')[0];
      while (container.firstChild) 
         container.removeChild(container.firstChild);

      {
		   //var thisDay = this.DTI_startingMonth(new Date());
		   var thisDay=this.DTI_date;
		   thisDay.setDate(1);
		   var year=thisDay.getFullYear();
		   var month=thisDay.getMonth();
		   //alert(thisDay);

	      var targetDate=stringToDate(this.DTI_target.value);
	      if(targetDate==null)
		      targetDate=new Date();
   		
		   var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
		   //var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
		   var monthArrayLong = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
   				
		   var table = document.createElement('table');
		   var tbody = document.createElement('tbody');
		   table.className = "keyboardInputCenter";
		   table.cellSpacing = table.border = "1";
		   {
			   var tr = document.createElement('tr');
			   {
				   var td = document.createElement('td');
				   this.DTI_getButtonCode(td,thisDay,-12,'<<');
				   tr.appendChild(td);
			   }
			   {
				   var td = document.createElement('td');
				   this.DTI_getButtonCode(td,thisDay,-1,'<');
				   tr.appendChild(td);
			   }
			   {
				   var td = document.createElement('td');
				   td.colSpan=3;
				   td.appendChild(document.createTextNode(monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear()));
				   tr.appendChild(td);
			   }
			   {
				   var td = document.createElement('td');
				   this.DTI_getButtonCode(td,thisDay,1,'>');
				   tr.appendChild(td);
			   }
			   {
				   var td = document.createElement('td');
				   this.DTI_getButtonCode(td,thisDay,12,'>>');
				   tr.appendChild(td);
			   }
			   tbody.appendChild(tr);
		   }
		   {
			   var tr = document.createElement('tr');
			   for(i = 0; i < dayArrayShort.length; i++)
			   {
				   var td = document.createElement('td');
				   td.appendChild(document.createTextNode(dayArrayShort[i]));
				   tr.appendChild(td);
			   }
			   tbody.appendChild(tr);
			   var dayOffset=thisDay.getDay();
			   var calendarComplete=false;
			   for(j=0;j<6 && !calendarComplete;++j)
			   {
				   var tr = document.createElement('tr');
				   for(i = 0; i < dayArrayShort.length; ++i)
				   {
					   var d=1+i+j*dayArrayShort.length-dayOffset;
					   var td = document.createElement('td');
					   if(d>=1 && !calendarComplete)
					   {
						   if(d==targetDate.getDate() && month==targetDate.getMonth() && year==targetDate.getFullYear())
							   td.className="hl";
						   td.appendChild(document.createTextNode(d));
   						
						   td.onclick = function()
						   {
							   var thisDate=new Date();
							   thisDate.setDate(this.firstChild.nodeValue);
							   thisDate.setMonth(month);
							   thisDate.setYear(year);
							   self.DTI_target.value=dateToString(thisDate);
							   self.DTI_close();
						   };
					   td.onmouseover = function() {
						   this.className += " hover";
					   };
					   td.onmouseout = function() {
						   this.className = this.className.replace(/ ?(hover|pressed)/g, "");
					   };
					   td.onmousedown = function() {
						   if (this.firstChild.nodeValue != "\xa0") this.className += " pressed";
					   };
					   td.onmouseup = function() {
						   this.className = this.className.replace(/ ?pressed/g, "");
					   };
					   td.ondblclick = function() { return false; };

						   thisDay.setDate(thisDay.getDate() + 1);
						   calendarComplete=(thisDay.getDate()==1);
					   }
					   tr.appendChild(td);
				   }
				   tbody.appendChild(tr);
			   }
			   table.appendChild(tbody);
		   }
		
		container.appendChild(table);
   }
      //this.DTI_deadkeysElem.style.display = (!this.DTI_layoutDDK[this.DTI_kt] && hasDeadKey) ? "inline" : "none";
  };

    this.DTI_buildKeys();
    DTI_disableSelection(this.DTI_keyboard);


    /* ****************************************************************
     * Controls modifier keys
     *
     */
    this.DTI_modify = function(type) {
      switch (type) {
        case "Alt":
        case "AltGr": this.DTI_alternate = !this.DTI_alternate; break;
        case "Caps": this.DTI_capslock = !this.DTI_capslock; break;
        case "Shift": this.DTI_shift = !this.DTI_shift; break;
      } var vchar = 0;
      if (!this.DTI_shift != !this.DTI_capslock) vchar += 1;

      var tables = this.DTI_keyboard.getElementsByTagName('table');
      for (var x = 0; x < tables.length; x++) {
        var tds = tables[x].getElementsByTagName('td');
        for (var y = 0; y < tds.length; y++) {
          var className = [];
          var lkey = this.DTI_layout[this.DTI_kt][x][y];

          if (tds[y].className.indexOf('hover') > -1) className.push("hover");

          switch (lkey[1]) {
            case "Alt":
            case "AltGr":
              if (this.DTI_alternate) className.push("dead");
              break;
            case "Shift":
              if (this.DTI_shift) className.push("dead");
              break;
            case "Caps":
              if (this.DTI_capslock) className.push("dead");
              break;
            case "Tab": case "Enter": case "Bksp": break;
            default:
              if (type) tds[y].firstChild.nodeValue = lkey[vchar + ((this.DTI_alternate && lkey.length == 4) ? 2 : 0)];
              if (this.DTI_deadkeysOn) {
                var char = tds[y].firstChild.nodeValue;
                if (this.DTI_dead) {
                  if (char == this.DTI_dead) className.push("dead");
                  for (var z = 0; z < this.DTI_deadkey[this.DTI_dead].length; z++) {
                    if (char == this.DTI_deadkey[this.DTI_dead][z][0]) {
                      className.push("target");
                      break;
                    }
                  }
                }
                for (key in this.DTI_deadkey)
                  if (key === char) { className.push("alive"); break; }
              }
          }

          if (y == tds.length - 1 && tds.length > this.DTI_keyCenter) className.push("last");
          if (lkey[0] == " ") className.push("space");
          tds[y].className = className.join(" ");
        }
      }
    };


    /* ****************************************************************
     * Insert text at the cursor
     *
     */
    this.DTI_insert = function(text) {
      this.DTI_target.focus();
      if (this.DTI_target.maxLength) this.DTI_target.maxlength = this.DTI_target.maxLength;
      if (typeof this.DTI_target.maxlength == "undefined" ||
          this.DTI_target.maxlength < 0 ||
          this.DTI_target.value.length < this.DTI_target.maxlength) {
        if (this.DTI_target.setSelectionRange) {
          if (this.DTI_target.readOnly && this.DTI_isWebKit) {
            var rng = [this.DTI_target.selStart || 0, this.DTI_target.selEnd || 0];
          } else var rng = [this.DTI_target.selectionStart, this.DTI_target.selectionEnd];
          this.DTI_target.value = this.DTI_target.value.substr(0, rng[0]) + text + this.DTI_target.value.substr(rng[1]);
          if (text == "\n" && window.opera) rng[0]++;
          this.DTI_target.setSelectionRange(rng[0] + text.length, rng[0] + text.length);
          if (this.DTI_target.readOnly && this.DTI_isWebKit) {
            var range = window.getSelection().getRangeAt(0);
            this.DTI_target.selStart = range.startOffset;
            this.DTI_target.selEnd = range.endOffset;
          }
        } else if (this.DTI_target.createTextRange) {
          try {
            this.DTI_target.range.select();
          } catch(e) { this.DTI_target.range = document.selection.createRange(); }
          this.DTI_target.range.text = text;
          this.DTI_target.range.collapse(true);
          this.DTI_target.range.select();
        } else this.DTI_target.value += text;
        if (this.DTI_shift) this.DTI_modify("Shift");
        if (this.DTI_alternate) this.DTI_modify("AltGr");
        this.DTI_target.focus();
      } else if (this.DTI_target.createTextRange && this.DTI_target.range)
        this.DTI_target.range.select();
    };


    /* ****************************************************************
     * Show the keyboard interface
     *
     */
    this.DTI_show = function(elem, style) {
      if (style != null) this.DTI_keyboard.className = style;
      if (this.DTI_target = elem) {
        if (this.DTI_visible != elem) {
          if (this.DTI_isIE) {
            if (!this.DTI_target.range) {
              this.DTI_target.range = this.DTI_target.createTextRange();
              this.DTI_target.range.moveStart('character', this.DTI_target.value.length);
            } this.DTI_target.range.select();
          }
          try { this.DTI_keyboard.parentNode.removeChild(this.DTI_keyboard); } catch (e) {}
          if (this.DTI_clearPasswords && this.DTI_target.type == "password") this.DTI_target.value = "";
		  
		  this.DTI_date=stringToDate(this.DTI_target.value);
		  if(this.DTI_date==null)
			this.DTI_date=new Date();
		  //if(this.DTI_target.type == "password")

          var elem = this.DTI_target;
          this.DTI_target.keyboardPosition = "absolute";
          do {
            if (DTI_getStyle(elem, "position") == "fixed") {
              this.DTI_target.keyboardPosition = "fixed";
              break;
            }
          } while (elem = elem.offsetParent);

          if (this.DTI_useIFrame) document.body.appendChild(this.DTI_iframe);
          document.body.appendChild(this.DTI_keyboard);
          this.DTI_keyboard.style.top = this.DTI_keyboard.style.right = this.DTI_keyboard.style.bottom = this.DTI_keyboard.style.left = "auto";
          this.DTI_keyboard.style.position = this.DTI_target.keyboardPosition;

          this.DTI_visible = this.DTI_target;
		  this.DTI_buildKeys();
          this.DTI_position();
          this.DTI_target.focus();
        } else this.DTI_close();
      }
    };


    /* ****************************************************************
     * Position the keyboard
     *
     */
    this.DTI_position = function() {
      if (self.DTI_visible) {
        var inputElemPos = DTI_findPos(self.DTI_target);
        self.DTI_keyboard.style.top = inputElemPos[1] - ((self.DTI_target.keyboardPosition == "fixed" && !self.DTI_isIE && !self.DTI_isMoz) ? DTI_scrollDist()[1] : 0) + self.DTI_target.offsetHeight + 3 + "px";
        self.DTI_keyboard.style.left = Math.min(DTI_innerDimensions()[0] - self.DTI_keyboard.offsetWidth - 15, inputElemPos[0]) + "px";
        if (self.DTI_useIFrame) {
          self.DTI_iframe.style.width = self.DTI_keyboard.offsetWidth + "px";
          self.DTI_iframe.style.height = self.DTI_keyboard.offsetHeight + "px";
          self.DTI_iframe.style.top = self.DTI_keyboard.style.top;
          self.DTI_iframe.style.left = self.DTI_keyboard.style.left;
        }
      }
    };


    if (window.addEventListener) {
      window.addEventListener('resize', this.DTI_position, false);
    } else if (window.attachEvent)
      window.attachEvent('onresize', this.DTI_position);


    /* ****************************************************************
     * Close the keyboard interface
     *
     */
    this.DTI_close = DTI_close = function(stopFocus) {
      if (this.DTI_visible) {
        try {
          this.DTI_keyboard.parentNode.removeChild(this.DTI_keyboard);
          if (this.DTI_useIFrame) this.DTI_iframe.parentNode.removeChild(this.DTI_iframe);
        } catch (e) {}
        if (!stopFocus) this.DTI_target.focus();
        this.DTI_target = this.DTI_visible = false;
      }
    };
  };

  function DTI_findPos(obj) {
    var curleft = curtop = 0;
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curleft, curtop];
  }

  function DTI_innerDimensions() {
    if (self.innerHeight) {
      return [self.innerWidth, self.innerHeight];
    } else if (document.documentElement && document.documentElement.clientHeight) {
      return [document.documentElement.clientWidth, document.documentElement.clientHeight];
    } else if (document.body)
      return [document.body.clientWidth, document.body.clientHeight];
    return [0, 0];
  }

  function DTI_scrollDist() {
    var html = document.getElementsByTagName('html')[0];
    if (html.scrollTop && document.documentElement.scrollTop) {
      return [html.scrollLeft, html.scrollTop];
    } else if (html.scrollTop || document.documentElement.scrollTop)
      return [html.scrollLeft + document.documentElement.scrollLeft, html.scrollTop + document.documentElement.scrollTop];
    return [0, 0];
  }

  function DTI_getStyle(obj, styleProp) {
    if (obj.currentStyle) {
      var y = obj.currentStyle[styleProp];
    } else if (window.getComputedStyle)
      var y = window.getComputedStyle(obj, null)[styleProp];
    return y;
  }

  function DTI_disableSelection(elem) {
    elem.onselectstart = function() { return false; };
    elem.unselectable = "on";
    elem.style.MozUserSelect = "none";
    elem.style.cursor = "default";
    if (window.opera) elem.onmousedown = function() { return false; };
  }

   function stringToDate(indate)
   {
	   if(indate==null || indate.length==0)
		   return null;
	   var punct;
	   if(indate.indexOf(".")!=-1)
		   punct=".";
	   else if(indate.indexOf("-")!=-1)
		   punct="-";
	   else
		   punct="/";
	   var day;
	   var month;
	   var year;
	   if (snapIsUk())//true=uk,false=usa
	   {	day=indate.substring(0,indate.indexOf(punct));
		   month=indate.substring(indate.indexOf(punct)+1,indate.lastIndexOf(punct));
	   } else
	   {	month=indate.substring(0,indate.indexOf(punct));
		   day=indate.substring(indate.indexOf(punct)+1,indate.lastIndexOf(punct));
	   }
	   year=indate.substring(indate.lastIndexOf(punct)+1,indate.length);
	   month = getMonthName(month-1);
	   if (year.length == 2)
	   {	if (30 > parseInt(year, 10))
		   {	year = "20"+year;
		   } else
		   {	year = "19"+year;
		   }
	   }
	   if (month=="" || year.length != 4 || parseInt(day, 10) > 31)
	   {
		   return null;
	   }
	   if (day.length == 1)
		   day = "0" + day;
	   var varDate = new Date(Date.parse(month + " " + day + ", " + year));
	   var cmpDate1 = day + "/" + month + "/" + year;
	   var month2 = getMonthName(varDate.getMonth());
	   day = varDate.getDate();
	   if (day.toString().length == 1)
	   {	day = "0" + day;
	   }
	   var cmpDate2 = day + "/" + month2 + "/" + varDate.getFullYear();
	   if (cmpDate1 != cmpDate2)
	   {
		   return null;
	   }
	   return varDate;
   }
   // Validation
   function dateToString(inDate)
   {
	   if (snapIsUk())//true=uk,false=usa
		   return ""+inDate.getDate()+"/"+(inDate.getMonth()+1)+"/"+inDate.getFullYear();
	   else
		   return ""+(inDate.getMonth()+1)+"/"+inDate.getDate()+"/"+inDate.getFullYear();
   }