/*  Prototype JavaScript framework, version 1.5.0
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/


var Prototype = {
  Version: '1.5.0',
  BrowserFeatures: {
    XPath: !!document.evaluate
  },

  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

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;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
String.interpret = function(value){
  return value == null ? '' : String(value);
}

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var name = decodeURIComponent(pair[0]);
        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;

        if (hash[name] !== undefined) {
          if (hash[name].constructor != Array)
            hash[name] = [hash[name]];
          if (value) hash[name].push(value);
        }
        else hash[name] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if(window.opera){
  Array.prototype.concat = function(){
    var array = [];
    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for(var i = 0, length = arguments.length; i < length; i++) {
      if(arguments[i].constructor == Array) {
        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(obj) {
  Object.extend(this, obj || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];

	  this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;

      if (pair.value && pair.value.constructor == Array) {
        var values = pair.value.compact();
        if (values.length < 2) pair.value = values.reduce();
        else {
        	key = encodeURIComponent(pair.key);
          values.each(function(value) {
            value = value != undefined ? encodeURIComponent(value) : '';
            parts.push(key + '=' + encodeURIComponent(value));
          });
          return;
        }
      }
      if (pair.value == undefined) pair[1] = '';
      parts.push(pair.map(encodeURIComponent).join('='));
	  });

    return parts.join('&');
  }
});

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
});

function $H(object) {
  if (object && object.constructor == Hash) return object;
  return new Hash(object);
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

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.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.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')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = this.options.parameters;

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    params = Hash.toQueryString(params);
    if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='

    // when GET, append parameters to URL
    if (this.method == 'get' && params)
      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;

    try {
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      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();

      var body = this.method == 'post' ? (this.options.postBody || params) : null;

      this.transport.send(body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      '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';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  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, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.getHeader('Content-type') || 'text/javascript').strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? eval('(' + json + ')') : null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});


























// Transport part

scriptTransport = Class.create();
//modeled after XmlHttpRequest http://en.wikipedia.org/wiki/XMLHttpRequest
//functions open, send (setRequestHeader) - variable readyState, status
//
//    * 0 = uninitialized - open() has not yet been called.
//    * 1 = open - send() has not yet been called.
//    * 2 = sent - send() has been called, headers and status are available.
//    * 3 = receiving - Downloading, responseText holds partial data.
//    * 4 = loaded - Finished.

//TODO:
//Removal of <script> nodes?

//
//------------------------------ initialize, open and send ------------------------------------------------------
//

var _xsajax$transport_status = 200;

scriptTransport.prototype.initialize = function() {
    this.readyState = 0;
}

scriptTransport.prototype.open = function(method, url, asynchronous) {
    if (method != 'GET')
    alert('Method should be set to GET when using cross site ajax');
    this.readyState = 1;
    this.onreadystatechange();
    this.url = url;
    this.userAgent = navigator.userAgent.toLowerCase();
    this.setBrowser();
    this.prepareGetScriptXS();
}

scriptTransport.prototype.send = function(body) {
    this.readyState = 2;
    this.onreadystatechange();
    this.getScriptXS(this.url);
}

//
//------------------------------ actually do the request: setBrowser, prepareGetScriptXS, callback, getScriptXS ----------
//

scriptTransport.prototype.setBrowser = function(body) {
    scriptTransport.prototype.browser = {
        version: (this.userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        safari: /webkit/.test(this.userAgent),
        opera: /opera/.test(this.userAgent),
        msie: /msie/.test(this.userAgent) && !/opera/.test(this.userAgent),
        mozilla: /mozilla/.test(this.userAgent) && !/(compatible|webkit)/.test(this.userAgent),
        konqueror: this.userAgent.match(/konqueror/i)
        };
}

scriptTransport.prototype.prepareGetScriptXS = function() {
    if (this.browser.safari || this.browser.konqueror) {
        _xsajax$node = [];
        _xsajax$nodes = 0;
    }
}

scriptTransport.prototype.callback = function() {
    this.status = (_xsajax$transport_status) ? _xsajax$transport_status : 200;
    this.readyState = 4;
    this.onreadystatechange();
}

scriptTransport.prototype.getScriptXS = function() {

    /* determine arguments */
    var arg = {
        'url': null
    };
    arg.url = arguments[0];

    /* generate <script> node */
    this.node = document.createElement('SCRIPT');
    this.node.type = 'text/javascript';
    this.node.src = arg.url;

    /* optionally apply event handler to <script> node for
   garbage collecting <script> node after loading and/or
   calling a custom callback function */
    var node_helper = null;

    if (this.browser.msie) {

        function mybind(obj) {
            temp = function() {
                if (this.readyState == "complete" || this.readyState == "loaded") {
                    return obj.callback.call(obj);
                }
            };
            return temp;
        }
        /* MSIE doesn't support the "onload" event on
           <script> nodes, but it at least supports an
           "onreadystatechange" event instead. But notice:
           according to the MSDN documentation we would have
           to look for the state "complete", but in practice
           for <script> the state transitions from "loading"
           to "loaded". So, we check for both here... */
        this.node.onreadystatechange = mybind(this);

        } else if (this.browser.safari || this.browser.konqueror) {
        /* Safari/WebKit and Konqueror/KHTML do not emit
           _any_ events at all, but we can exploit the fact
           that dynamically generated <script> DOM nodes
           are executed in sequence (although the scripts
           theirself are still loaded in parallel) */
        _xsajax$nodes++;

        var helper = 'var ctx = _xsajax$node[' + _xsajax$nodes + '];' + 'ctx.callback.call(ctx.node);' + 'setTimeout(function () {' + '    ctx.node_helper.parentNode.removeChild(ctx.node_helper);' + '}, 100);';
        node_helper = document.createElement('SCRIPT');
        node_helper.type = 'text/javascript';
        node_helper.appendChild(document.createTextNode(helper));
        _xsajax$node[_xsajax$nodes] = {
            callback: this.callback.bind(this),
            node: this.node,
            node_helper: node_helper
        };
    } else {
        /* Firefox, Opera and other reasonable browsers can
           use the regular "onload" event... */
        this.node.onload = this.callback.bind(this);
    }

    /* inject <script> node into <head> of document */
    this.readyState = 3;
    this.onreadystatechange();
    var head = document.getElementsByTagName('HEAD')[0];
    head.appendChild(this.node);

    /* optionally inject helper <script> node into <head>
   (Notice: we have to use a strange indirection via
   setTimeout() to insert this second <script> node here or
   at least Konqueror (and perhaps also Safari) for unknown
   reasons will not execute the first <script> node at all) */
    if (node_helper !== null) {
        setTimeout(function() {
            var head = document.getElementsByTagName('HEAD')[0];
            head.appendChild(node_helper);
        }, 100);
    }

}

//
//------------------------------ Don't complain when these are called: setRequestHeader and onreadystatechange ----------
//

scriptTransport.prototype.setRequestHeader = function() {
}
scriptTransport.prototype.onreadystatechange = function() {
}

//
//------------------------------- Extend prototype a bit -----------------------
//

Ajax.Request.prototype = Object.extend(Ajax.Request.prototype,{
    initialize: function(url, options) {
        this.setOptions(options);
        this.transport = (!this.options.crossSite) ? Ajax.getTransport() : new scriptTransport;
        this.request(url);
        }    
});


























//---------------------------------------------------------------------------



String.prototype.trim = function() { re = /[\s]+(.*?)[\s]+/gi; return this.replace(re, "$1"); }




function TimeRandFunction() {
var now;
now=new Date();
strng=now.getTime()+"_"+(Math.random()*999999);
return strng;
}



function Milliseconds() {
var now;
now=new Date();
return now.getTime();
}




function dynLoadCSS(addrs) {

 var styleSheet = document.createElement("link");
     styleSheet.setAttribute("href", addrs);
     styleSheet.setAttribute("rel", "stylesheet");
     styleSheet.setAttribute("type", "text/css");
     var head = document.getElementsByTagName("head");
     head[0].appendChild(styleSheet);

// alert(addrs);
}



















































//---------------------------------------------------------------------------



var errormsg = "";




var ITConfig = { 
		CtrlURL: domain+"/controller.php",
		MemoryCache: 'on'
};



var Timer = null;
var Cache = [];
var AcceptMessage=true;
var userKey = "012345678901234567890123456789";
var globalSelectAjaxedClass = 'ajaxed_default';






// Short name of function
function $(divName) {
	return document.getElementById(divName);
}



function sp2pl(s) {
 if (s!=null) {
  return s.replace(" ","+");
 } else { return ""; }
}




function stripSlashes(content) {
		// Strip Slashes
		re = /\\\"/gi;
		content = content.replace(re, '"');
		re = /\\\'/gi;
		content = content.replace(re, "'");
		return content;
}




function getGSAC() {

 if (globalSelectAjaxedClass == undefined) {
  var gSAClass = "ajaxed_default";
 } else {
  var gSAClass = globalSelectAjaxedClass;
 }

 return gSAClass;

}







var lfuhandleSuccess = function(divName,htmlBody){

// alert(divName+" : "+htmlBody);

 $(divName).innerHTML = htmlBody;

};


var lfuhandleFailure = function(o){ alert("It seems as the script can not connect to the server. Please, check if controller exists by URL "+ITConfig.CtrlURL); };

var lfucallback =
{
  success:lfuhandleSuccess,
  failure:lfuhandleFailure,
  argument:['foo','bar']
};






function LoadHTML2Div(divName,url){

//      alert(ITConfig.CtrlURL+'?call=loadhtmlfromurl'+
//                      '&url='+encodeURIComponent(url.replace(/\//g,"#"))+
//                      '&timer='+TimeRandFunction());


        htmlBody = "<small>Error loading requested page...</small>";

	var request = new Ajax.Request(ITConfig.CtrlURL,
      {
          method: 'GET',
          crossSite: true,
          parameters: '?call=loadhtmlfromurl'+
                      '&url='+url+
                      '&timer='+TimeRandFunction(),
          onLoading: function()
          {
//           $(divName).innerHTML = " &nbsp;Loading data... Please wait...";
          },
          onSuccess: function(transport)
          {
           lfuhandleSuccess(divName, htmlBody, transport);
          },
          onFailure: function()
          {
           lfuhandleSuccess("");
          }
      });
}

























var gshandleSuccess = function(statesList, citiesList, n){

 if (n==null) {n='';}

 if (n!='') {
             statesList = statesList.replace('n_state ','n_state'+n+' ');
             statesList = statesList.replace('n_state ','n_state'+n+' ');
//             statesList = statesList.replace('GetCities()','GetCities('+n+')');
             statesList = statesList.replace('GetCities()','GetCities('+n+',1)');
             citiesList = citiesList.replace('n_city ','n_city'+n+' ');
             citiesList = citiesList.replace('n_city ','n_city'+n+' ');
             citiesList = citiesList.replace('SetCity()','SetCity('+n+')');
            }

 $("c_states_list"+n).innerHTML = statesList;
 $("c_cities_list"+n).innerHTML = citiesList;


 gSAClass = getGSAC();


 if (n!='') {
  $("n_state"+n).className = gSAClass;
  $("n_city"+n).className = gSAClass;
 } else {
  $("n_state").className = gSAClass;
  $("n_city").className = gSAClass;
 }

};


var gshandleFailure = function(o){ alert("It seems as the script can not connect to the server. Please, check if controller exists by URL "+ITConfig.CtrlURL); };

var gscallback =
{
  success:gshandleSuccess,
  failure:gshandleFailure,
  argument:['foo','bar']
};






function GetStates(n,wpo){

      if (n==null) {n='';}

//      $("c_cities_list").innerHTML = "Pleae select state, and only then city...";
      $("c_state_fld"+n).value = "";
      $("c_city_fld"+n).value = "";
      $("c_state_fld_control"+n).value = "";
      $("c_city_fld_control"+n).value = "";


      gc = 'getstates';

      if (wpo!=null && wpo==1) {gc= gc + '_wpo';}

	var request = new Ajax.Request(ITConfig.CtrlURL,
      {
          method: 'GET',
          crossSite: true,
          parameters: '&call='+gc+ //getcities'+
//	var request = new Ajax.Request(ITConfig.CtrlURL,
//      {
//          method: 'GET',
//          crossSite: true,
//          parameters: '&call=getstates'+
                      '&country='+$("c_country"+n).value+
                      '&SessID='+userKey+
                      '&timer='+TimeRandFunction(),
          onLoading: function()
          {
           $("c_states_list"+n).innerHTML = " &nbsp;Loading states list... Wait please...";
           $("c_cities_list"+n).innerHTML = " &nbsp;Loading cities list... Wait please...";
          },
          onSuccess: function(transport)
          {
           gshandleSuccess(statesList, citiesList, n, transport);
          },
          onFailure: function()
          {
           gshandleSuccess("");
          }
      });
}

















var goshandleSuccess = function(statesList,n){

 if (n==null) {n='';}


 if (n!='') {
             statesList = statesList.replace('n_state ','n_state'+n+' ');
             statesList = statesList.replace('n_state ','n_state'+n+' ');
//             statesList = statesList.replace('GetCities()','GetCities('+n+')');
             statesList = statesList.replace('GetCities()','GetCities('+n+',1)');
            }

 $("c_states_list"+n).innerHTML = statesList;

 gSAClass = getGSAC();

 if (n!='') {
  $("n_state"+n).className = gSAClass;
 } else {
  $("n_state").className = gSAClass;
 }

 $("c_cities_list"+n).innerHTML = " &nbsp;You have to select state first...";
 $("c_resorts_list"+n).innerHTML = " &nbsp;You have to select state first...";

};


var goshandleFailure = function(o){ alert("It seems as the script can not connect to the server. Please, check if controller exists by URL "+ITConfig.CtrlURL); };

var goscallback =
{
  success:goshandleSuccess,
  failure:goshandleFailure,
  argument:['foo','bar']
};






function GetOnlyStates(n,wpo){

      if (n==null) {n='';}

      gc = 'getonlystates';

      if (wpo!=null && wpo==1) {gc= gc + '_wpo';}

	var request = new Ajax.Request(ITConfig.CtrlURL,
      {
          method: 'GET',
          crossSite: true,
          parameters: '&call='+gc+ //getcities'+

//	var request = new Ajax.Request(ITConfig.CtrlURL,
//      {
//          method: 'GET',
//          crossSite: true,
//          parameters: '&call=getonlystates'+
                      '&country='+$("c_country"+n).value+
                      '&SessID='+userKey+
                      '&timer='+TimeRandFunction(),
          onLoading: function()
          {
           $("c_states_list"+n).innerHTML = " &nbsp;Loading states list... Wait please...";
           $("c_cities_list"+n).innerHTML = " &nbsp;Loading cities list... Wait please...";
          },
          onSuccess: function(transport)
          {
           goshandleSuccess(statesList, n, transport);
          },
          onFailure: function()
          {
           goshandleSuccess("");
          }
      });
}


























var gchandleSuccess = function(citiesList,n){

 if (n==null) {n='';}

 if (n!='') {
             citiesList = citiesList.replace('n_city ','n_city'+n+' ');
             citiesList = citiesList.replace('n_city ','n_city'+n+' ');
             citiesList = citiesList.replace('SetCity()','SetCity('+n+')');
            }

 $("c_cities_list"+n).innerHTML = citiesList;

 gSAClass = getGSAC();

 if (n!='') {
  $("n_city"+n).className = gSAClass;
 } else {
  $("n_city").className = gSAClass;
 }


};


var gchandleFailure = function(o){ alert("It seems as the script can not connect to the server. Please, check if controller exists by URL "+ITConfig.CtrlURL); };

var gccallback =
{
  success:gchandleSuccess,
  failure:gchandleFailure,
  argument:['foo','bar']
};






function GetCities(n,wpo){

      if (n==null) {n='';}

      if ($("n_state"+n).selectedIndex>0) {
       $("c_state_fld"+n).value = $("n_state"+n).options[$("n_state"+n).selectedIndex].label;
       $("c_state_fld_control"+n).value = $("n_state"+n).options[$("n_state"+n).selectedIndex].label;
      } else {
       $("c_state_fld"+n).value = ""; //$("n_state"+n).options[$("n_state"+n).selectedIndex].label;
       $("c_state_fld_control"+n).value = ""; //$("n_state"+n).options[$("n_state"+n).selectedIndex].label;
      }

      $("c_city_fld"+n).value = "";
      $("c_city_fld_control"+n).value = "";

      gc = 'getcities';

      if (wpo!=null && wpo==1) {gc= gc + '_wpo';}

//       alert(ITConfig.CtrlURL+
//             '?call='+gc+ //getcities'+
//                      '&country='+$("c_country"+n).value+
//                      '&state='+$("n_state"+n).value+
//                      '&SessID='+userKey+
//                      '&timer='+TimeRandFunction()
//            );

	var request = new Ajax.Request(ITConfig.CtrlURL,
      {
          method: 'GET',
          crossSite: true,
          parameters: '&call='+gc+ //getcities'+
                      '&country='+$("c_country"+n).value+
                      '&state='+$("n_state"+n).value+
                      '&SessID='+userKey+
                      '&timer='+TimeRandFunction(),
          onLoading: function()
          {
           $("c_cities_list"+n).innerHTML = " &nbsp;Loading cities list... Wait please...";
          },
          onSuccess: function(transport)
          {
           gchandleSuccess(citiesList,n,transport);
          },
          onFailure: function()
          {
           gchandleSuccess("");
          }
      });
}






function SetResort(n) {

}



function SetCity(n) {

      if (n==null) {n='';}

      if ($("n_city"+n).selectedIndex>0) {
       $("c_city_fld"+n).value = $("n_city"+n).options[$("n_city"+n).selectedIndex].label;
       $("c_city_fld_control"+n).value = $("n_city"+n).options[$("n_city"+n).selectedIndex].label;
      } else {
       $("c_city_fld"+n).value = ""; //$("n_city"+n).options[$("n_city"+n).selectedIndex].label;
       $("c_city_fld_control"+n).value = ""; //$("n_city"+n).options[$("n_city"+n).selectedIndex].label;
      }

}





//getresortsbycs










var grhandleSuccess = function(resortsList,n){

 $("c_resorts_list").innerHTML = resortsList;

 gSAClass = getGSAC();

 $("n_resort_id").className = gSAClass;

};


var grhandleFailure = function(o){ alert("It seems as the script can not connect to the server. Please, check if controller exists by URL "+ITConfig.CtrlURL); };

var grcallback =
{
  success:grhandleSuccess,
  failure:grhandleFailure,
  argument:['foo','bar']
};






function GetResorts(n,wpo){

      if (n==null) {n='';}

      if ($("n_state"+n)== null) {
       n_state = 0;
      } else {
       n_state = $("n_state"+n).value;
      }

      if ($("n_city"+n)== null) {
       n_city = 0;
      } else {
       n_city = $("n_city"+n).value;
      }

      gc = 'getresortsbycs';

      if (wpo!=null && wpo==1) {gc= gc + '_wpo';}

/*
alert(
ITConfig.CtrlURL+ '&call='+gc+
                      '&country='+$("c_country"+n).value+
                      '&state='+n_state+
                      '&city='+n_city+
                      '&SessID='+userKey+
                      '&timer='+TimeRandFunction()
);

*/



	var request = new Ajax.Request(ITConfig.CtrlURL,
      {
          method: 'GET',
          crossSite: true,
          parameters: '&call='+gc+ //getresortsbycs'+
                      '&country='+$("c_country"+n).value+
                      '&state='+n_state+
                      '&city='+n_city+
                      '&SessID='+userKey+
                      '&timer='+TimeRandFunction(),
          onLoading: function()
          {
           $("c_resorts_list"+n).innerHTML = " &nbsp;Loading resorts list... Wait please...";
          },
          onSuccess: function(transport)
          {
           grhandleSuccess(resortsList,n,transport);
          },
          onFailure: function()
          {
           grhandleSuccess("");
          }
      });
}




dynLoadCSS(domain+"/tpl/img/css/selects.css");

