/* UltraLight Prototype */

function $(name) { return document.getElementById(name) }
emptyFunction=function(){};
  
Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    return __method.apply(object);
  }
}

var Try = {
  these: function() {
    var returnValue;
    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    return returnValue;
  }
}

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}     

Object.clone=function(object) {
  return Object.extend({}, object);
}
             
var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },
  activeRequestCount: 0
}                   

Ajax.Request = function(url, options) {  
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
};      
                  
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      if (this.options.parameters != '')
        this.options.parameters = this.options.parameters.toQueryParams();
  },   
  
  dispatchException: function(exception) {
    (this.options.onException || emptyFunction)(this, exception);
  },
     
  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },  
              
  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },
  
  respondToReadyState: function(readyState) {   
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport;

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || emptyFunction)(transport);
      } catch (e) {
        this.dispatchException(e);
      }
    }

    try {               
      (this.options['on' + state] || emptyFunction)(transport);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = emptyFunction;
    }
  },       
  
  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }
    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },  
  
  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);
    params['_method'] = this.method;
    this.method = 'post';    
    this.parameters = params;  
    try {
      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();
       
      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send();
       
      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();
    }
    catch (e) {
      this.dispatchException(e);
    }
  }
};

function loadModellInfo(dontDisplayAll) {
  var label = $('label').value;
  $('loader').style.visibility = 'visible';
  new Ajax.Request('carmodell?'+label, {
   onComplete: function(transport) {
     $('loader').style.visibility = 'hidden';  
     var select = $('modell');
     var defVal = select.getAttribute('defVal');
     select.innerHTML = '';
     if (!dontDisplayAll) {
       var opt = document.createElement('option');
       opt.setAttribute('value', -1);
       opt.innerHTML = 'beliebig';
       select.appendChild(opt);
     }
     eval('data='+transport.responseText);
     for (var i=0;i<data.length;i++) {
       var opt = document.createElement('option');
       opt.setAttribute('value', data[i].id);
       opt.innerHTML = data[i].name;
       if (data[i].id == defVal)
         opt.setAttribute('selected', 'true');
       select.appendChild(opt);
     }   
   }
  });
  
};

function DOMIsLoaded() {
  if (!$('loader')) 
    return;
  $('loader').style.visibility = 'hidden';
  if ($('modell').innerHTML == '')
    loadModellInfo();
}

if (document.addEventListener) {  
  document.addEventListener("DOMContentLoaded", DOMIsLoaded, false);
} else
  window.onload=DOMIsLoaded;
