﻿$(document).ready(function() {
    $("input.cwhiddendialog").each(function(el) {
        document.dialogHash.setItem($(this).attr('name'), $(this).val());
    });
    $("span.opendialog").click(function(el) {
        var encoded = document.dialogHash.getItem($(this)[0].id);
        if (encoded) {
            $("#dialogarea").html(decodeURIComponent(encoded.replace(/\+/g, " ")));
            showDialog();
            //$("#dialog").dialog(); //{ position: 'left',position: 'top',show: 'slide' });
        }
    });
    $('.button').initButton();
    $('#navmenu').makeMenu({ fadeIn: 0, fadeOut: 300 });
    $('.dataform').initDataForm();
    $('#prodnav').initProdMenu();
    $('.firstfocus:first').focus().select();
    /*$('input[type=submit]').click(function() {
    document.body.style.cursor = "wait";
    $(this).attr('disabled', 'disabled');
    return true;
    });*/

    $('.formsubmit').click(function() {
        var form = $(this).parents('form:first');
        if (form.length) {
            document.body.style.cursor = "wait";
            recordHandler.prepeareForPostBack(form);
            form.submit();
            $('.formsubmit').attr('disabled', 'disabled');
        }
    });
    if (jQuery.fn.statusBarInit !== undefined)
        $('body').statusBarInit();
});
var debug = true;
var alerts = false;
var contextProviders = [];
var serverConnector = new CwServerConnector();
var recordHandler = new CwRecordHandler();
var attachedHash = new Hash();
var pageCache = new Hash();
var lastFieldHash = new Hash();
var saving = false;
var origHash = new Hash();

/* >> Session timout checking */
//To avoid in ajax state redirect in axapta because of session timeout
var timeinactive; //Clearing from AX
var timeinactiveallowed; //Setting from AX
var redirectUrl = window.location;
function sessionCheck() {
   if (redirectUrl && timeinactiveallowed) {
      timeinactive = timeinactive + (1000 * 60);
      if (timeinactive > timeinactiveallowed - 5)
         window.location = redirectUrl;
   }
   setTimeout('sessionCheck()', 1000 * 30); //Check every minute.
}
sessionCheck();
function sessionRestart(_timeinactiveallowed, _redirectUrl) {
   if (_redirectUrl)
      redirectUrl = _redirectUrl;
   if (_timeinactiveallowed)
      timeinactiveallowed = _timeinactiveallowed;
   timeinactive = 0;
}
/* << Session timout checking */
/* Dialog - start */
document.dialogHash = new Hash();
var removeOverlaysArray = new Array();
function showDialog() {
   var lastFieldId = recordHandler.fieldId();
   $("#dialog").dialog({
      close: function(event, ui) {
         //removeAllOverlays();//TODO: A litle week just to remove all overlays...
         var localLastFieldId = lastFieldId;
         if (localLastFieldId) {
            $('#' + localLastFieldId).focus();
            $('#' + localLastFieldId).select();
        }
         $('#dialog').dialog('destroy');
         $('#dialog').remove();
      },
      width: '500px',
      modal: true});
}
/* Dialog - end */
/* Various functions - start */
/*function addOverlay(selector,options){
if(typeof options == 'undefined')
options = {};
$(selector).showOverlay(options);      
removeOverlaysArray.push(selector);  
}
function removeAllOverlays(){
while(removeOverlaysArray.length > 0) {
$(removeOverlaysArray.pop()).hideOverlay();
}
}*/

function setWaitImg(element, center, img) {
   if (img == undefined || img == '')
      img = '/img/ajax-anim.gif';
   if (center) {
      //'/img/ajax-loader_indicator_big_redmond.gif'
      $(element).html('<div style="position:relative;text-align:center;width:100%;height:100%;display:block"><img style="position:absolute;top:45%;left:45%;" alt=""  src= "' + img + '" /></div>');
   }
   else {
      $(element).html('<img alt="" src= "' + img + '" />');
   }
}
/* Various functions - end */
/* Server connector - start */
function CwServerConnector() {
   this.optionMap = new Hash();
   this.callBacks = new Hash();
   this.loadHtml = function(options, sendContext, callback) {
      var defaults = {
         url: '/ajaxpages/AjaxGet.aspx',
         loadinto: '#deverror',
         classname: 'CwWPGenerator',
         methodname: 'execute',
         webpartid: 'OptionMissing.ax',
         imgurl: '/img/ajax-anim.gif',
         cache: false,
         overlay: '',
         cursor: '',
         statusbarshow: false,
         statusbartext:'',
         statusbartextcomplete: 'Complete',
         tooltippos:'default'
      };
      options = $.extend(defaults, options);
      if (sendContext) {
         options = $.extend(options, recordHandler.serialized());
      }
      var internalCallback = function(res, status) {
         var internalOptions = options;
         if (internalOptions.cache && status == "success" || status == "notmodified") {
            pageCache.setItem(internalOptions.url + JSON.stringify(internalOptions), res);
         }
         $(internalOptions.loadinto).unautocomplete();
         $(internalOptions.loadinto).unbind();
         $(internalOptions.loadinto).removeData('events');
         $(internalOptions.loadinto + ' .dataform').initDataForm();
         $(internalOptions.loadinto + ' .button').initButton();
         if (internalOptions.overlay)
            $(internalOptions.overlay).hideOverlay();

         if (callback)
            callback([res, status]);

         timeinactive = 0;
         //removeAllOverlays();
         document.body.style.cursor = 'default';
         if(options.statusbarshow)
            statusBarSetComplete(options.statusbartextcomplete);
      }
      if (options.cursor)
         document.body.style.cursor = options.cursor;

      if (options.overlay) {
         $(options.overlay).showOverlay({ opacity: 0.2, speed: 0 });
      } else if (options.imgurl) {
         setWaitImg($(options.loadinto), true, options.imgurl);
      }
      if(options.statusbarshow)
        statusBarShow(options.statusbartext);
      
      $(options.loadinto).cwload(options.url + (sendContext ? '' : '?classname=' + options.classname +
                                                                    '&methodname=' + options.methodname +
                                                                    '&webpartid=' + options.webpartid)
            , sendContext ? options : null
            , internalCallback
            , options.cache);
   }
   postingNow = {};
   this.post = function(options, sendContext, async, callback) {
      if (typeof async == 'undefined')
         async = true;

      var defaults = {
         recordHandler:null,
         recordaction: '',
         url: '/ajaxpages/AjaxUpdate.aspx',
         suppress: false,
         format: 'json',
         imgurl: '/img/ajax-anim.gif',
         classname: 'CwWebPart',
         methodname: 'action',
         overlay: '',
         callback: '',
         cursor: '',
         statusbartext:'Communicating with server'
      };
      options = $.extend(defaults, options);
      if (sendContext) {
         options = $.extend(options, recordHandler.serialized());
      }
      if(options.dataformid){
          statusBarShow(options.statusbartext);
      }
      if (options.classname == 'CwWebPart') {
         var webPartId = $('.webpartid', recordHandler.$currentDataForm).val();
         if (webPartId)
            options.classname = webPartId;
      }
      //Overriding callback not implemented yet, callback function needs to go in hash by id
      //Id has to be given back jsonObj.id to lookup hash an call function
      //should super be run() then, give parameter..?
      if (callback)
         callback = function(data) { return; };

      /* HACK START 
         This hack is to prevent multiple calls triggered by keydown event in grids. 
         Must be fixed so that multiple events are not triggered, unkown cause.
         Hack works by serializing the parameters for two objects and checking if
      */
      if(postingNow !== {} && JSON.stringify(postingNow) === JSON.stringify(options)){
        //$.log('Post canceled..');
        return;
      }
      postingNow = jQuery.extend(true, {}, options);
      /* HACK END */
      options.id = newGuid();

      if (options.cursor)
         document.body.style.cursor = options.cursor;

      if (options.overlay) {
         $(options.overlay).showOverlay({ opacity: 0.2, speed: 0 });
      } else if (options.imgurl && options.loadinto) {
         setWaitImg($(options.loadinto), true, options.imgurl);
      }
      $.cwPost(async, options.url, options,
            function(jsonObj) {
               var localOptions = options;
               jsonObj = $.extend({ 
                  success: false,
                  statusbarshow: false,
                  remove: '',
                  updateinfo: { updateelements: [], deleteelements: [] },
                  suppress: false,
                  dialog: '',
                  statustext: '',
                  tooltiptext: '',
                  loadinto: '',
                  html: '',
                  htmljson: {},
                  focuselement: '',
                  append: false,
                  callback:''
               }, jsonObj);
               postingNow = {};
               if (localOptions.callback) {
                  try {
                     eval(localOptions.callback);
                  }
                  catch (e) {
                     $.log(e);
                  }
               }
               if (jsonObj.success) {
                  jQuery.each(jsonObj.updateinfo.updateelements, function(i, kvp) {
                     var control = $(kvp.element);
                     if (control.length > 0) {
                        var value = kvp.value;
                        if (typeof value == 'string')
                           value = decodeURIComponent(value.replace(/\+/g, " "));
                        jQuery.nodeName(control[0], "input")
                                ? $(control).val(value)
                                : $(control).html(value);
                        
                        if(!jQuery.nodeName(control[0], "input")){
                            $('.dataform', control).initDataForm();
                            $('.button', control).initButton();
                        }
                     }
                  });
                  jQuery.each(jsonObj.updateinfo.deleteelements, function(i, idOrSelector) {
                     $(idOrSelector).remove();
                  });
               }
               else {
               }
               if (localOptions.recordid) {
                  var record = $('#' + localOptions.recordid);
                  if (!jsonObj.success) {
                     if (jQuery.nodeName(record[0], "tr"))
                        $(record).addClass('ui-state-error');
                     var fieldId = lastFieldHash.keyExists(localOptions.recordid) ? lastFieldHash.getItem(localOptions.recordid) : '';
                     if (fieldId) {
                        $('#' + fieldId, record).focus();
                        $('#' + fieldId, record).select();
                     }
                  }
                  else {
                     $(record).removeClass('ui-state-error');
                  }
               }
               if (jsonObj.loadinto) {
                  var $loadinto = $(jsonObj.loadinto);
                  if (!jsonObj.append) {
                     $('input', $loadinto).flushCache();
                     $('input', $loadinto).unautocomplete();
                     $('*', $loadinto).unbind();
                     $('*', $loadinto).removeData('events');
                     $loadinto.empty();
                  }
                  if (jsonObj.htmljson.hasOwnProperty("html")) {
                     $.log('json_to_html not implemented yet');
                     //injection code here
                     var html = function(json) { }; //transform to html here
                     $loadinto.html(html);
                     $('.dataform', $loadinto).initDataForm();
                  }
                  if (jsonObj.html) {
                     var encoded = jsonObj.html;
                     $loadinto.html(decodeURIComponent(encoded.replace(/\+/g, " ")));
                     $('.dataform', $loadinto).initDataForm();
                     $('.button', $loadinto).initButton();
                  }
               }
               if ((!jsonObj.success || !jsonObj.suppress) && jsonObj.dialog) {
                  var encoded = jsonObj.dialog;
                  var $dialogarea = $("#dialogarea");
                  $dialogarea.html(decodeURIComponent(encoded.replace(/\+/g, " ")));
                  $('.dataform',$dialogarea).initDataForm();
                  $('.button', $dialogarea).initButton();
                  showDialog();
               }
               if (jsonObj.statusbarshow) {
                  statusBarSetComplete(decodeURIComponent(jsonObj.statustext.replace(/\+/g, " ")),
                                       decodeURIComponent(jsonObj.tooltiptext.replace(/\+/g, " ")),
                                       jsonObj.success,
                                       localOptions.tooltippos);
               }else statusBarSetComplete('Complete','',jsonObj.success);
               if (localOptions.overlay) {
                  $(localOptions.overlay).hideOverlay();
               }

               if (saving && recordHandler.updateQueue.length == 0) {
                  saving = false;
               }
               if (jsonObj.updateinfo.focuselement)
                  $(jsonObj.updateinfo.focuselement).focus().select();
               document.body.style.cursor = 'default';
               timeinactive = 0;
            },
            options.format
        );
   }
}
/* Server connector - end */
/* Record handler - start */
function CwRecordHandler() {
   /*Private members... øø not so private any more..*/
   this.currentRecord = null;
   this.styledRecord = null;
   this.$currentRecord = [];
   this.currentField = null;
   this.$currentDataTable = [];
   this.currentSerialized = null;
   this.recordOrigHash = new Hash();
   this.recordFocusStack = new Array();
   this.updateQueue = [];
   this.$currentDataForm = [];
   this.hasFocus;
   this.inErrorModeStack = [];
   this.isPostBack = false;
   var self = this;
   this.restoreFromOrig = function() {

      return self;
   }
   this.autoSave = function() { return self.$currentRecord ? self.$currentRecord.hasClass('autosave') : false; }
   this.record = function() { return self.currentRecord; }
   this.recordId = function() { return self.currentRecord ? self.currentRecord.id : ''; }
   this.$dataForm = function() { return self.$currentDataForm }
   this.dataFormId = function() { return self.$currentDataForm.length > 0 ? self.$currentDataForm[0].id : ''; }
   this.dataTableId = function() { return self.$currentDataTable.length > 0 ? self.$currentDataTable[0].id : ''; }
   this.dataSourceName = function() {
      if (self.currentRecord) {
         var arr = self.currentRecord.id.split('_');
         if (arr.length >= 5) {
            return arr[4];
         }
      }
      return '';
   }
   this.field = function() { return self.currentField; }
   this.fieldId = function() { return self.currentField ? self.currentField.id : ''; }
   this.serialized = function() { serializeContext(); return self.currentSerialized; }
   this.fieldGotFocus = function(element) {
      var newRecord = this.findRecord(element);
      if (newRecord && newRecord == self.currentRecord) {
         hasFocus = true;
         self.currentField = element.id && element.id != self.currentRecord.id ? element : '';
         return self;
      }
      if (newRecord && newRecord.id) {
         self.currentRecord = newRecord;
         self.$currentRecord = $('#' + self.currentRecord.id);
         self.$currentDataForm = self.$currentRecord.parents('.dataform:first');
         self.currentField = element.id && element.id != self.currentRecord.id ? element : '';
         self.$currentDataTable = self.$currentRecord.parents('table.datagrid:first[id]');
         if (!self.recordOrigHash.keyExists(self.currentRecord.id)) {
            self.recordOrigHash.setItem(self.currentRecord.id, self.serializeRecord(self.currentRecord));
         }
         hasFocus = true;
         loadAttachedElements();
      }
      else {
         self.fieldLostFocus(element);
      }
      setStyles();
      return self;
   }
   function setStyles() {
      if (self.currentRecord != self.styledRecord) {
         var tmpArray = new Array;
         while (self.recordFocusStack.length > 0) {
            var id = self.recordFocusStack.pop();
            if ($("#" + id, self.$currentDataForm).length > 0) {
               $("#" + id, self.$currentDataForm).removeClass('highlight').find('.selectforupdate').removeClass('fieldactive');
            } else {
               tmpArray.push(id);
            }
         }
         self.recordFocusStack = tmpArray;
         if (self.currentRecord && jQuery.nodeName(self.currentRecord, "tr")) {
            self.recordFocusStack.push(self.currentRecord.id);
            self.$currentRecord.addClass('highlight')
                    .find('.selectforupdate').addClass('fieldactive');
         }
      }
   }
   this.save = function(async) {
      if (!self.currentRecord)
         return;
      var existsInSaveQueue = false;
      jQuery.each(self.updateQueue, function(i) {
         if (self.updateQueue[i] == self.currentRecord.id)
            existsInSaveQueue = true;
      });
      if (!existsInSaveQueue)
         self.updateQueue.push(self.currentRecord.id);
      serializeContext();
      self.recordOrigHash.setItem('m_' + self.currentRecord.id, self.currentSerialized);
      if (typeof async == 'undefined')
         async = false;
      self.saveRecords(true, async);
   }
   this.fieldLostFocus = function(element) {
      if (self.currentRecord) {
         lostFocus = true;
         if (self.autoSave()) {
            self.updateQueue.push(self.currentRecord.id);
            lastFieldHash.setItem(self.currentRecord.id, self.fieldId());
            serializeContext();
            self.recordOrigHash.setItem('m_' + self.currentRecord.id, self.currentSerialized)
            setTimeout('recordHandler.saveRecords(false)', 300);
         }
      }
      return self;
   }
   this.saveRecords = function(force, async) {
      jQuery.each(self.updateQueue, function(i) {
         var record = $('#' + self.updateQueue.pop(i))[0];
         if (record && record.id) {
            var serializedRecord = self.serializeRecord(record);
            var isChanged = JSON.stringify(self.recordOrigHash.getItem(record.id)) !== JSON.stringify(serializedRecord);
            if (isChanged && (force || !hasFocus || record.id != self.recordId())) {
               var options = $.extend({ recordaction: 10, suppress: $(record).hasClass('suppresinfo') }, self.recordOrigHash.getItem('m_' + record.id));
               if (typeof async == 'undefined')
                  async = false;
               serverConnector.post(options, false, !force);
               self.recordOrigHash.removeItem('m_' + record.id);
               self.recordOrigHash.removeItem(record.id);
               saving = true;
            }
         }
      });
   }
   this.findRecord = function(element) {
      var record = null;
      if ($(element).hasClass('datarecord')) {
         record = $(element)[0];
      }
      else {
         var records = $(element).parents('.datarecord:first');
         if (records.length > 0) {
            record = records[0];
         }
      }
      return record;
   }
   /*this.update = function(record) {
   updateRecord = record ? record : self.currentRecord;
   if (updateRecord) {
   }
   return self;
   }*/
   this.serializeRecord = function(record) {
      var s = '';
      if (record) {
         s = record.id;
         $('.selectforupdate', record).each(function() {
            var controlIdent = this.id != '' ? this.id : this.getAttribute("name");
            var $this = $(this);
            if (controlIdent != undefined && controlIdent != "") {
               if (jQuery.nodeName(this, "input") && /radio|checkbox/.test(this.type) && !this.checked)
                  return;
               s += ':' + controlIdent + '=' + (jQuery.nodeName(this, "input") ||
                                               jQuery.nodeName(this, "select") ||
                                               jQuery.nodeName(this, "option") ||
                                               jQuery.nodeName(this, "textarea")
                                               ? $this.val()
                                               : $this.html());
            }
         });
      }
      return s;
   }
   this.prepeareForPostBack = function(form) {
      self.isPostBack = true;
      serializeContext(form);
   }

   this.serializeRecord = function(record) {
       var s = '';
       if (record) {
           s = record.id;
           $('.selectforupdate', record).each(function() {
               var controlIdent = this.id != '' ? this.id : this.getAttribute("name");
               var $this = $(this);
               if (controlIdent != undefined && controlIdent != "") {
                   if (jQuery.nodeName(this, "input") && /radio|checkbox/.test(this.type) && !this.checked)
                       return;
                   s += ':' + controlIdent + '=' + (jQuery.nodeName(this, "input") ||
                                               jQuery.nodeName(this, "select") ||
                                               jQuery.nodeName(this, "option") ||
                                               jQuery.nodeName(this, "textarea")
                                               ? $this.val()
                                               : $this.html());
               }
           });
       }
       return s;
   }
   this.prepeareForPostBack = function(form) {
       self.isPostBack = true;
       serializeContext(form);
   }

   var serializeContext = function(form) {
       function addParam(param, value) {
           if (self.isPostBack && form) {
               if (!$('input[name=' + param + ']').length) {
                   form.append('<input name="' + param + '" type="hidden" value="' + value + '"/>');
               }
           }
           data[param] = value;
       }
       if (!self.currentRecord) {
           return self;
       }
       var data = {};
       addParam('dataformid', self.dataFormId());
       var controlArray = new Array();
       var controlGlobalArray = new Array();
       var idArray = self.currentRecord.id.split('_');

       if (idArray[0] == 'r') {
           addParam('tableid', idArray[1]);
           addParam('recid', idArray[2]);
           controlArray.push('recid');
           controlArray.push('tableid');
       }
       else {
           addParam('cid', self.currentRecord.id);
           controlArray.push('cid');
       }
       addParam('recordid', self.currentRecord.id);
       controlArray.push('recordid');
       addParam('contextproviders', contextProviders.join(':'));
       //add ismodified class to modified elements, only select values
       //create array of modified controls
       $('.selectforupdate', self.$currentRecord).each(function() {
           var controlIdent = this.id != '' ? this.id : this.getAttribute("name");
           var $this = $(this);
           if (controlIdent) {
               var tmpVal;
               if (jQuery.nodeName(this, "input") && /radio|checkbox/.test(this.type) && !this.checked)
                   return;

               addParam(controlIdent, jQuery.nodeName(this, "input") ||
                                      jQuery.nodeName(this, "select") ||
                                      jQuery.nodeName(this, "option") ||
                                      jQuery.nodeName(this, "textarea")
                                      ? $this.val()
                                      : $this.html());
               controlArray.push(controlIdent);
           }
       });
       addParam('controls', controlArray.join(':'));

       controlArray = new Array();
       $('.refresh[id]', self.$currentRecord).each(function() {
           controlArray.push(this.id);
       });
       $('.dorefresh[id]', self.$currentDataForm).each(function(idx) {
           controlArray.push(this.id);
           controlGlobalArray.push(this.id);
       });
       addParam('refreshfields', controlArray.join(':'));
       addParam('dorefreshfields', controlGlobalArray.join(':'));
       self.currentSerialized = data;
       return self;
   }

   function loadAttachedElements(loadinto) {
      if (self.currentRecord == null || !self.dataSourceName())
         return false;
      if (attachedHash.keyExists(self.dataSourceName())) {
         var hashArray = attachedHash.getItem(self.dataSourceName());
         jQuery.each(hashArray, function(i, options) {
            if (options.loadinto && (options.onchange == true || (loadinto && options.loadinto == loadinto))) {
               serverConnector.loadHtml(options, true);
            }
         });
      }
      return true;
   }
}
/* Record handler - end */
/* Hash table implementation - start */
function Hash() {
   this.length = 0;
   this.items = new Array();
   for (var i = 0; i < arguments.length; i += 2) {
      if (typeof (arguments[i + 1]) != 'undefined') {
         this.items[arguments[i]] = arguments[i + 1];
         this.length++;
      }
   }
   this.removeItem = function(in_key) {
      var tmp_previous;
      if (typeof (this.items[in_key]) != 'undefined') {
         this.length--;
         tmp_previous = this.items[in_key];
         delete this.items[in_key];
      }
      return tmp_previous;
   }
   this.getItem = function(in_key) {
      return this.items[in_key];
   }
   this.setItem = function(in_key, in_value) {
      var tmp_previous;
      if (typeof (in_value) != 'undefined') {
         if (typeof (this.items[in_key]) == 'undefined') {
            this.length++;
         }
         else {
            tmp_previous = this.items[in_key];
         }

         this.items[in_key] = in_value;
      }
      return tmp_previous;
   }
   this.keyExists = function(in_key) {
      return typeof (this.items[in_key]) != 'undefined';
   }
   this.clear = function() {
      for (var i in this.items) {
         delete this.items[i];
      }
      this.length = 0;
   }
}
/* Hash table implementation - end */
var KEY = {
   UP: 38,
   DOWN: 40,
   DEL: 46,
   TAB: 9,
   RETURN: 13,
   ESC: 27,
   COMMA: 188,
   PAGEUP: 33,
   PAGEDOWN: 34,
   BACKSPACE: 8
};
Array.prototype.find = function(searchStr) {
   var returnArray = false;
   for (i = 0; i < this.length; i++) {
      if (typeof (searchStr) == 'function') {
         if (searchStr.test(this[i])) {
            if (!returnArray) { returnArray = [] }
            returnArray.push(i);
         }
      } else {
         if (this[i] === searchStr) {
            if (!returnArray) { returnArray = [] }
            returnArray.push(i);
         }
      }
   }
   return returnArray;
}
function newGuid() {
   var result, i, j;
   result = '';
   for (j = 0; j < 32; j++) {
      if (j == 8 || j == 12 || j == 16 || j == 20)
         result = result + '-';
      i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
      result = result + i;
   }
   return result
}

function checkDate(field) {
   var checkstr = "0123456789";
   var DateField = field;
   var Datevalue = "";
   var DateTemp = "";
   var seperator = ".";
   var day;
   var month;
   var year;
   var leap = 0;
   var err = 0;
   var i;
   err = 0;
   DateValue = DateField.value;
   /* Delete all chars except 0..9 */
   for (i = 0; i < DateValue.length; i++) {
      if (checkstr.indexOf(DateValue.substr(i, 1)) >= 0) {
         DateTemp = DateTemp + DateValue.substr(i, 1);
      }
   }
   DateValue = DateTemp;
   /* Always change date to 8 digits - string*/
   /* if year is entered as 2-digit / always assume 20xx */
   if (DateValue.length == 6) {
      DateValue = DateValue.substr(0, 4) + '20' + DateValue.substr(4, 2);
   }
   if (DateValue.length != 8) {
      err = 19;
   }
   /* year is wrong if year = 0000 */
   year = DateValue.substr(4, 4);
   if (year == 0) {
      err = 20;
   }
   /* Validation of month*/
   month = DateValue.substr(2, 2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* Validation of day*/
   day = DateValue.substr(0, 2);
   if (day < 1) {
      err = 22;
   }
   /* Validation leap-year / february / day */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* if 00 ist entered, no error, deleting the entry */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   if (err == 0) {
      DateField.value = day + seperator + month + seperator + year;
      $(DateField).removeClass('ui-text-error');
      $(DateField).removeClass('ui-state-error');
   }
   /* Error-message if err != 0 */
   else {
      //alert("Date is incorrect!");
      $(DateField).addClass('ui-text-error');
      $(DateField).addClass('ui-state-error');
      //DateField.select();
      //DateField.focus();
   }
   return err == 0 ? true : false;
}