
if(typeof console === "undefined") {
    console = { log: function() { } };
}

/* --- http://test.unserdaheim.at/templates/daheim/scripts/wolfgang.js --- */
/**
 * @author wolfganghoeller
 */

function highlightEvent(id, url) {
	document.getElementById("event_row"+id).style.backgroundColor="#4d93b7";
	document.getElementById("event_clock"+id).style.width = "11px";
	document.getElementById("event_clock"+id).style.height = "11px";
	document.getElementById("event_clock"+id).style.display = "block";
	document.getElementById("event_clock"+id).style.backgroundImage ="url("+url+"images/clockIconSmallBlue.gif)";
	document.getElementById("event_date"+id).style.color = "#FFF";
	document.getElementById("event_time"+id).style.color = "#FFF";
	document.getElementById("event_term"+id).style.color = "#4d93b7";
}//function

function dehighlightEvent(id, url){
	document.getElementById("event_row"+id).style.backgroundColor="#FFF";
	document.getElementById("event_date"+id).style.color = "#696969";
	document.getElementById("event_time"+id).style.color = "#ACACAC";
	document.getElementById("event_clock"+id).style.backgroundImage ="url("+url+"images/clockIconSmall.gif)";
}//function

function SubmitForm() {
	document.getElementById("FormLogin").submit()
}//function


function addCompany(el) {
	myform = $(el).up('form').serialize();
	
	new Ajax.Request(
     '/add_company/',{
    	method: 'post',
		  parameters: myform,
		  onComplete: function(transport) {
		  	document.getElementById('company_details').innerHTML = transport.responseText;
		  }
		}
	);
	return false;	
}//function

function updateDD(value,id) {
	//alert("Subcat: "+value+' ID:'+id);
	new Ajax.Updater(id+'_div', '/register/update_dropdown', {
		method: 'post',
		parameters: {parent: value, what: id},
		onComplete: function() {
			if(id == "bundesland") {
				document.getElementById("bundesland_label").className ="label";
				document.register.bezirk.value ="Bitte ausw&auml;hlen";
				document.register.stadt.value = "Bitte ausw&auml;hlen";
		  	document.register.ort.value = "Bitte ausw&auml;hlen";
			}//if
			if (id == "bezirk") {
		  	document.register.stadt.value = "Bitte ausw&auml;hlen";
		  	document.register.ort.value = "Bitte ausw&auml;hlen";
	  }//if
		}
	});
} // function


function updateBezirk(value) {
	//alert("Subcat: "+value);
	new Ajax.Updater('bezirk_div', '/register/update_bezirk', {
		method: 'post',
		parameters: {parent: value},
		onComplete: function() {
		  //validateAddArticle(null);
		}
	});
} // function

function fillTextArea(obj,value){
  //alert(obj+','+value);
	new Ajax.Updater('regions', '/register/register_breadcrumbs', {
		method: 'post',
		parameters: {id: value},
		onComplete: function() {
		  //validateAddArticle(null);
		  //alert(id+'-'+value);
		  $('searchort').style.display = 'none';
		  document.register.ortsuche.value = '';
		}
	});
} // function

function funct(val) {
  new Ajax.Updater('searchort', '/register_citysearchlive', {
    method: 'post',
    parameters: { ortsuche: val},
    onComplete: function() {
      $('searchort').style.display = 'block';
    }
  });
} // function
/* --- /http://test.unserdaheim.at/templates/daheim/scripts/wolfgang.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/prototype.js --- */
/*  Prototype JavaScript framework, version 1.6.0.2
 *  (c) 2005-2008 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
 *--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.6.0.2',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      document.createElement('div').__proto__ &&
      document.createElement('div').__proto__ !==
        document.createElement('form').__proto__
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
};

if (Prototype.Browser.MobileSafari)
  Prototype.BrowserFeatures.SpecificElementExtensions = false;


/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if (!Object.keys({ toString: true }).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$super") {
        var method = value, value = Object.extend((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property).wrap(method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

var Abstract = { };

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.isUndefined(object)) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : String(object);
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }

    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (Object.isElement(object)) return;

    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (!Object.isUndefined(value))
        results.push(property.toJSON() + ': ' + value);
    }

    return '{' + results.join(', ') + '}';
  },

  toQueryString: function(object) {
    return $H(object).toQueryString();
  },

  toHTML: function(object) {
    return object && object.toHTML ? object.toHTML() : String.interpret(object);
  },

  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);
  },

  isElement: function(object) {
    return object && object.nodeType == 1;
  },

  isArray: function(object) {
    return object != null && typeof object == "object" &&
      'splice' in object && 'join' in object;
  },

  isHash: function(object) {
    return object instanceof Hash;
  },

  isFunction: function(object) {
    return typeof object == "function";
  },

  isString: function(object) {
    return typeof object == "string";
  },

  isNumber: function(object) {
    return typeof object == "number";
  },

  isUndefined: function(object) {
    return typeof object == "undefined";
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },

  bindAsEventListener: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = $A(arguments);
    return function() {
      return __method.apply(this, args.concat($A(arguments)));
    }
  },

  delay: function() {
    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    }
  },

  methodize: function() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      return __method.apply(null, [this].concat($A(arguments)));
    };
  }
});

Function.prototype.defer = Function.prototype.delay.curry(0.01);

Date.prototype.toJSON = function() {
  return '"' + this.getUTCFullYear() + '-' +
    (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
    this.getUTCDate().toPaddedString(2) + 'T' +
    this.getUTCHours().toPaddedString(2) + ':' +
    this.getUTCMinutes().toPaddedString(2) + ':' +
    this.getUTCSeconds().toPaddedString(2) + 'Z"';
};

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;
  }
};

RegExp.prototype.match = RegExp.prototype.test;

RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create({
  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);
  },

  execute: function() {
    this.callback(this);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

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 = Object.isUndefined(count) ? 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 String(this);
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = Object.isUndefined(truncation) ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : String(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 self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = new Element('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 key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = 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);
  },

  times: function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  },

  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.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  isJSON: function() {
    var str = this;
    if (str.blank()) return false;
    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  },

  interpolate: function(object, pattern) {
    return new Template(this, pattern).evaluate(object);
  }
});

if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (Object.isFunction(replacement)) return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
};

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create({
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    if (Object.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return '';

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3];
      var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
      match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    });
  }
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;

var $break = { };

var Enumerable = {
  each: function(iterator, context) {
    var index = 0;
    iterator = iterator.bind(context);
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.collect(iterator, context);
  },

  all: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = true;
    this.each(function(value, index) {
      result = result && !!iterator(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = false;
    this.each(function(value, index) {
      if (result = !!iterator(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function(iterator, context) {
    iterator = iterator.bind(context);
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(filter, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];

    if (Object.isString(filter))
      filter = new RegExp(filter);

    this.each(function(value, index) {
      if (filter.match(value))
        results.push(iterator(value, index));
    });
    return results;
  },

  include: function(object) {
    if (Object.isFunction(this.indexOf))
      if (this.indexOf(object) != -1) return true;

    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = Object.isUndefined(fillWith) ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator, context) {
    iterator = iterator.bind(context);
    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, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var trues = [], falses = [];
    this.each(function(value, index) {
      (iterator(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator, context) {
    iterator = iterator.bind(context);
    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 (Object.isFunction(args.last()))
      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,
  filter:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray,
  every:   Enumerable.all,
  some:    Enumerable.any
});
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

if (Prototype.Browser.WebKit) {
  $A = function(iterable) {
    if (!iterable) return [];
    if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
        iterable.toArray) return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  };
}

Array.from = $A;

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(Object.isArray(value) ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  intersect: function(array) {
    return this.uniq().findAll(function(item) {
      return array.detect(function(value) { return item === value });
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (!Object.isUndefined(value)) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
  Array.prototype._each = Array.prototype.forEach;

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
};

if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  var n = this.slice(0, i).reverse().indexOf(item);
  return (n < 0) ? n : i - n - 1;
};

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  if (!Object.isString(string)) return [];
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.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 (Object.isArray(arguments[i])) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  };
}
Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

$w('abs round ceil floor').each(function(method){
  Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
  return new Hash(object);
};

var Hash = Class.create(Enumerable, (function() {

  function toQueryPair(key, value) {
    if (Object.isUndefined(value)) return key;
    return key + '=' + encodeURIComponent(String.interpret(value));
  }

  return {
    initialize: function(object) {
      this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
    },

    _each: function(iterator) {
      for (var key in this._object) {
        var value = this._object[key], pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    },

    set: function(key, value) {
      return this._object[key] = value;
    },

    get: function(key) {
      return this._object[key];
    },

    unset: function(key) {
      var value = this._object[key];
      delete this._object[key];
      return value;
    },

    toObject: function() {
      return Object.clone(this._object);
    },

    keys: function() {
      return this.pluck('key');
    },

    values: function() {
      return this.pluck('value');
    },

    index: function(value) {
      var match = this.detect(function(pair) {
        return pair.value === value;
      });
      return match && match.key;
    },

    merge: function(object) {
      return this.clone().update(object);
    },

    update: function(object) {
      return new Hash(object).inject(this, function(result, pair) {
        result.set(pair.key, pair.value);
        return result;
      });
    },

    toQueryString: function() {
      return this.map(function(pair) {
        var key = encodeURIComponent(pair.key), values = pair.value;

        if (values && typeof values == 'object') {
          if (Object.isArray(values))
            return values.map(toQueryPair.curry(key)).join('&');
        }
        return toQueryPair(key, values);
      }).join('&');
    },

    inspect: function() {
      return '#<Hash:{' + this.map(function(pair) {
        return pair.map(Object.inspect).join(': ');
      }).join(', ') + '}>';
    },

    toJSON: function() {
      return Object.toJSON(this.toObject());
    },

    clone: function() {
      return new Hash(this);
    }
  }
})());

Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
  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 (Object.isFunction(responder[callback])) {
        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 = Class.create({
  initialize: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isString(this.options.parameters))
      this.options.parameters = this.options.parameters.toQueryParams();
    else if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

Ajax.Request = Class.create(Ajax.Base, {
  _complete: false,

  initialize: function($super, url, options) {
    $super(options);
    this.transport = Ajax.getTransport();
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    this.parameters = params;

    if (params = Object.toQueryString(params)) {
      // when GET, append parameters to URL
      if (this.method == 'get')
        this.url += (this.url.include('?') ? '&' : '?') + params;
      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
        params += '&_=';
    }

    try {
      var response = new Ajax.Response(this);
      if (this.options.onCreate) this.options.onCreate(response);
      Ajax.Responders.dispatch('onCreate', this, response);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.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 (Object.isFunction(extras.push))
        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() {
    var status = this.getStatus();
    return !status || (status >= 200 && status < 300);
  },

  getStatus: function() {
    try {
      return this.transport.status || 0;
    } catch (e) { return 0 }
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);

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

      var contentType = response.getHeader('Content-type');
      if (this.options.evalJS == 'force'
          || (this.options.evalJS && this.isSameOrigin() && contentType
          && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
        this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
      Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  isSameOrigin: function() {
    var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
    return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
      protocol: location.protocol,
      domain: document.domain,
      port: location.port ? ':' + location.port : ''
    }));
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name) || null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Response = Class.create({
  initialize: function(request){
    this.request = request;
    var transport  = this.transport  = request.transport,
        readyState = this.readyState = transport.readyState;

    if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
      this.status       = this.getStatus();
      this.statusText   = this.getStatusText();
      this.responseText = String.interpret(transport.responseText);
      this.headerJSON   = this._getHeaderJSON();
    }

    if(readyState == 4) {
      var xml = transport.responseXML;
      this.responseXML  = Object.isUndefined(xml) ? null : xml;
      this.responseJSON = this._getResponseJSON();
    }
  },

  status:      0,
  statusText: '',

  getStatus: Ajax.Request.prototype.getStatus,

  getStatusText: function() {
    try {
      return this.transport.statusText || '';
    } catch (e) { return '' }
  },

  getHeader: Ajax.Request.prototype.getHeader,

  getAllHeaders: function() {
    try {
      return this.getAllResponseHeaders();
    } catch (e) { return null }
  },

  getResponseHeader: function(name) {
    return this.transport.getResponseHeader(name);
  },

  getAllResponseHeaders: function() {
    return this.transport.getAllResponseHeaders();
  },

  _getHeaderJSON: function() {
    var json = this.getHeader('X-JSON');
    if (!json) return null;
    json = decodeURIComponent(escape(json));
    try {
      return json.evalJSON(this.request.options.sanitizeJSON ||
        !this.request.isSameOrigin());
    } catch (e) {
      this.request.dispatchException(e);
    }
  },

  _getResponseJSON: function() {
    var options = this.request.options;
    if (!options.evalJSON || (options.evalJSON != 'force' &&
      !(this.getHeader('Content-type') || '').include('application/json')) ||
        this.responseText.blank())
          return null;
    try {
      return this.responseText.evalJSON(options.sanitizeJSON ||
        !this.request.isSameOrigin());
    } catch (e) {
      this.request.dispatchException(e);
    }
  }
});

Ajax.Updater = Class.create(Ajax.Request, {
  initialize: function($super, container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    };

    options = Object.clone(options);
    var onComplete = options.onComplete;
    options.onComplete = (function(response, json) {
      this.updateContent(response.responseText);
      if (Object.isFunction(onComplete)) onComplete(response, json);
    }).bind(this);

    $super(url, options);
  },

  updateContent: function(responseText) {
    var receiver = this.container[this.success() ? 'success' : 'failure'],
        options = this.options;

    if (!options.evalScripts) responseText = responseText.stripScripts();

    if (receiver = $(receiver)) {
      if (options.insertion) {
        if (Object.isString(options.insertion)) {
          var insertion = { }; insertion[options.insertion] = responseText;
          receiver.insert(insertion);
        }
        else options.insertion(receiver, responseText);
      }
      else receiver.update(responseText);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  initialize: function($super, container, url, options) {
    $super(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(response) {
    if (this.options.decay) {
      this.decay = (response.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = response.responseText;
    }
    this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(Element.extend(query.snapshotItem(i)));
    return results;
  };
}

/*--------------------------------------------------------------------------*/

if (!window.Node) var Node = { };

if (!Node.ELEMENT_NODE) {
  // DOM level 2 ECMAScript Language Binding
  Object.extend(Node, {
    ELEMENT_NODE: 1,
    ATTRIBUTE_NODE: 2,
    TEXT_NODE: 3,
    CDATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8,
    DOCUMENT_NODE: 9,
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11,
    NOTATION_NODE: 12
  });
}

(function() {
  var element = this.Element;
  this.Element = function(tagName, attributes) {
    attributes = attributes || { };
    tagName = tagName.toLowerCase();
    var cache = Element.cache;
    if (Prototype.Browser.IE && attributes.name) {
      tagName = '<' + tagName + ' name="' + attributes.name + '">';
      delete attributes.name;
      return Element.writeAttribute(document.createElement(tagName), attributes);
    }
    if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
    return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  };
  Object.extend(this.Element, element || { });
}).call(window);

Element.cache = { };

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);
    content = Object.toHTML(content);
    element.innerHTML = content.stripScripts();
    content.evalScripts.bind(content).defer();
    return element;
  },

  replace: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    else if (!Object.isElement(content)) {
      content = Object.toHTML(content);
      var range = element.ownerDocument.createRange();
      range.selectNode(element);
      content.evalScripts.bind(content).defer();
      content = range.createContextualFragment(content.stripScripts());
    }
    element.parentNode.replaceChild(content, element);
    return element;
  },

  insert: function(element, insertions) {
    element = $(element);

    if (Object.isString(insertions) || Object.isNumber(insertions) ||
        Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
          insertions = {bottom:insertions};

    var content, insert, tagName, childNodes;

    for (var position in insertions) {
      content  = insertions[position];
      position = position.toLowerCase();
      insert = Element._insertionTranslations[position];

      if (content && content.toElement) content = content.toElement();
      if (Object.isElement(content)) {
        insert(element, content);
        continue;
      }

      content = Object.toHTML(content);

      tagName = ((position == 'before' || position == 'after')
        ? element.parentNode : element).tagName.toUpperCase();

      childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());

      if (position == 'top' || position == 'after') childNodes.reverse();
      childNodes.each(insert.curry(element));

      content.evalScripts.bind(content).defer();
    }

    return element;
  },

  wrap: function(element, wrapper, attributes) {
    element = $(element);
    if (Object.isElement(wrapper))
      $(wrapper).writeAttribute(attributes || { });
    else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
    else wrapper = new Element('div', wrapper);
    if (element.parentNode)
      element.parentNode.replaceChild(wrapper, element);
    wrapper.appendChild(element);
    return wrapper;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $(element).select("*");
  },

  firstDescendant: function(element) {
    element = $(element).firstChild;
    while (element && element.nodeType != 1) element = element.nextSibling;
    return $(element);
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (Object.isString(selector))
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(element.parentNode);
    var ancestors = element.ancestors();
    return Object.isNumber(expression) ? ancestors[expression] :
      Selector.findElement(ancestors, expression, index);
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    return Object.isNumber(expression) ? element.descendants()[expression] :
      element.select(expression)[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return Object.isNumber(expression) ? previousSiblings[expression] :
      Selector.findElement(previousSiblings, expression, index);
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return Object.isNumber(expression) ? nextSiblings[expression] :
      Selector.findElement(nextSiblings, expression, index);
  },

  select: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  adjacent: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element.parentNode, args).without(element);
  },

  identify: function(element) {
    element = $(element);
    var id = element.readAttribute('id'), self = arguments.callee;
    if (id) return id;
    do { id = 'anonymous_element_' + self.counter++ } while ($(id));
    element.writeAttribute('id', id);
    return id;
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      var t = Element._attributeTranslations.read;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name]) name = t.names[name];
      if (name.include(':')) {
        return (!element.attributes || !element.attributes[name]) ? null :
         element.attributes[name].value;
      }
    }
    return element.getAttribute(name);
  },

  writeAttribute: function(element, name, value) {
    element = $(element);
    var attributes = { }, t = Element._attributeTranslations.write;

    if (typeof name == 'object') attributes = name;
    else attributes[name] = Object.isUndefined(value) ? true : value;

    for (var attr in attributes) {
      name = t.names[attr] || attr;
      value = attributes[attr];
      if (t.values[attr]) name = t.values[attr](element, value);
      if (value === false || value === null)
        element.removeAttribute(name);
      else if (value === true)
        element.setAttribute(name, name);
      else element.setAttribute(name, value);
    }
    return element;
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    if (!element.hasClassName(className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    element.className = element.className.replace(
      new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    return element[element.hasClassName(className) ?
      'removeClassName' : 'addClassName'](className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.blank();
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    var originalAncestor = ancestor;

    if (element.compareDocumentPosition)
      return (element.compareDocumentPosition(ancestor) & 8) === 8;

    if (element.sourceIndex && !Prototype.Browser.Opera) {
      var e = element.sourceIndex, a = ancestor.sourceIndex,
       nextAncestor = ancestor.nextSibling;
      if (!nextAncestor) {
        do { ancestor = ancestor.parentNode; }
        while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
      }
      if (nextAncestor && nextAncestor.sourceIndex)
       return (e > a && e < nextAncestor.sourceIndex);
    }

    while (element = element.parentNode)
      if (element == originalAncestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = element.cumulativeOffset();
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    style = style == 'float' ? 'cssFloat' : style.camelize();
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

  getOpacity: function(element) {
    return $(element).getStyle('opacity');
  },

  setStyle: function(element, styles) {
    element = $(element);
    var elementStyle = element.style, match;
    if (Object.isString(styles)) {
      element.style.cssText += ';' + styles;
      return styles.include('opacity') ?
        element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
    }
    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property]);
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
            property] = styles[property];

    return element;
  },

  setOpacity: function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = Element.getStyle(element, 'overflow') || 'auto';
    if (element._overflow !== 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName == 'BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p !== 'static') break;
      }
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  absolutize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'absolute') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    var offsets = element.positionedOffset();
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
    return element;
  },

  relativize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'relative') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
    return element;
  },

  cumulativeScrollOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  getOffsetParent: function(element) {
    if (element.offsetParent) return $(element.offsetParent);
    if (element == document.body) return $(element);

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return $(element);

    return $(document.body);
  },

  viewportOffset: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body &&
        Element.getStyle(element, 'position') == 'absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element._returnOffset(valueL, valueT);
  },

  clonePosition: function(element, source) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || { });

    // find page position of source
    source = $(source);
    var p = source.viewportOffset();

    // find coordinate system to use
    element = $(element);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(element, 'position') == 'absolute') {
      parent = element.getOffsetParent();
      delta = parent.viewportOffset();
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if (options.setLeft)   element.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if (options.setTop)    element.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if (options.setWidth)  element.style.width = source.offsetWidth + 'px';
    if (options.setHeight) element.style.height = source.offsetHeight + 'px';
    return element;
  }
};

Element.Methods.identify.counter = 1;

Object.extend(Element.Methods, {
  getElementsBySelector: Element.Methods.select,
  childElements: Element.Methods.immediateDescendants
});

Element._attributeTranslations = {
  write: {
    names: {
      className: 'class',
      htmlFor:   'for'
    },
    values: { }
  }
};

if (Prototype.Browser.Opera) {
  Element.Methods.getStyle = Element.Methods.getStyle.wrap(
    function(proceed, element, style) {
      switch (style) {
        case 'left': case 'top': case 'right': case 'bottom':
          if (proceed(element, 'position') === 'static') return null;
        case 'height': case 'width':
          // returns '0px' for hidden elements; we want it to return null
          if (!Element.visible(element)) return null;

          // returns the border-box dimensions rather than the content-box
          // dimensions, so we subtract padding and borders from the value
          var dim = parseInt(proceed(element, style), 10);

          if (dim !== element['offset' + style.capitalize()])
            return dim + 'px';

          var properties;
          if (style === 'height') {
            properties = ['border-top-width', 'padding-top',
             'padding-bottom', 'border-bottom-width'];
          }
          else {
            properties = ['border-left-width', 'padding-left',
             'padding-right', 'border-right-width'];
          }
          return properties.inject(dim, function(memo, property) {
            var val = proceed(element, property);
            return val === null ? memo : memo - parseInt(val, 10);
          }) + 'px';
        default: return proceed(element, style);
      }
    }
  );

  Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
    function(proceed, element, attribute) {
      if (attribute === 'title') return element.title;
      return proceed(element, attribute);
    }
  );
}

else if (Prototype.Browser.IE) {
  // IE doesn't report offsets correctly for static elements, so we change them
  // to "relative" to get the values, then change them back.
  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
    function(proceed, element) {
      element = $(element);
      var position = element.getStyle('position');
      if (position !== 'static') return proceed(element);
      element.setStyle({ position: 'relative' });
      var value = proceed(element);
      element.setStyle({ position: position });
      return value;
    }
  );

  $w('positionedOffset viewportOffset').each(function(method) {
    Element.Methods[method] = Element.Methods[method].wrap(
      function(proceed, element) {
        element = $(element);
        var position = element.getStyle('position');
        if (position !== 'static') return proceed(element);
        // Trigger hasLayout on the offset parent so that IE6 reports
        // accurate offsetTop and offsetLeft values for position: fixed.
        var offsetParent = element.getOffsetParent();
        if (offsetParent && offsetParent.getStyle('position') === 'fixed')
          offsetParent.setStyle({ zoom: 1 });
        element.setStyle({ position: 'relative' });
        var value = proceed(element);
        element.setStyle({ position: position });
        return value;
      }
    );
  });

  Element.Methods.getStyle = function(element, style) {
    element = $(element);
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];

    if (style == 'opacity') {
      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }

    if (value == 'auto') {
      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
        return element['offset' + style.capitalize()] + 'px';
      return null;
    }
    return value;
  };

  Element.Methods.setOpacity = function(element, value) {
    function stripAlpha(filter){
      return filter.replace(/alpha\([^\)]*\)/gi,'');
    }
    element = $(element);
    var currentStyle = element.currentStyle;
    if ((currentStyle && !currentStyle.hasLayout) ||
      (!currentStyle && element.style.zoom == 'normal'))
        element.style.zoom = 1;

    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      (filter = stripAlpha(filter)) ?
        style.filter = filter : style.removeAttribute('filter');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = stripAlpha(filter) +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  Element._attributeTranslations = {
    read: {
      names: {
        'class': 'className',
        'for':   'htmlFor'
      },
      values: {
        _getAttr: function(element, attribute) {
          return element.getAttribute(attribute, 2);
        },
        _getAttrNode: function(element, attribute) {
          var node = element.getAttributeNode(attribute);
          return node ? node.value : "";
        },
        _getEv: function(element, attribute) {
          attribute = element.getAttribute(attribute);
          return attribute ? attribute.toString().slice(23, -2) : null;
        },
        _flag: function(element, attribute) {
          return $(element).hasAttribute(attribute) ? attribute : null;
        },
        style: function(element) {
          return element.style.cssText.toLowerCase();
        },
        title: function(element) {
          return element.title;
        }
      }
    }
  };

  Element._attributeTranslations.write = {
    names: Object.extend({
      cellpadding: 'cellPadding',
      cellspacing: 'cellSpacing'
    }, Element._attributeTranslations.read.names),
    values: {
      checked: function(element, value) {
        element.checked = !!value;
      },

      style: function(element, value) {
        element.style.cssText = value ? value : '';
      }
    }
  };

  Element._attributeTranslations.has = {};

  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
      'encType maxLength readOnly longDesc').each(function(attr) {
    Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
    Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  });

  (function(v) {
    Object.extend(v, {
      href:        v._getAttr,
      src:         v._getAttr,
      type:        v._getAttr,
      action:      v._getAttrNode,
      disabled:    v._flag,
      checked:     v._flag,
      readonly:    v._flag,
      multiple:    v._flag,
      onload:      v._getEv,
      onunload:    v._getEv,
      onclick:     v._getEv,
      ondblclick:  v._getEv,
      onmousedown: v._getEv,
      onmouseup:   v._getEv,
      onmouseover: v._getEv,
      onmousemove: v._getEv,
      onmouseout:  v._getEv,
      onfocus:     v._getEv,
      onblur:      v._getEv,
      onkeypress:  v._getEv,
      onkeydown:   v._getEv,
      onkeyup:     v._getEv,
      onsubmit:    v._getEv,
      onreset:     v._getEv,
      onselect:    v._getEv,
      onchange:    v._getEv
    });
  })(Element._attributeTranslations.read.values);
}

else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

else if (Prototype.Browser.WebKit) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;

    if (value == 1)
      if(element.tagName == 'IMG' && element.width) {
        element.width++; element.width--;
      } else try {
        var n = document.createTextNode(' ');
        element.appendChild(n);
        element.removeChild(n);
      } catch (e) { }

    return element;
  };

  // Safari returns margins on body which is incorrect if the child is absolutely
  // positioned.  For performance reasons, redefine Element#cumulativeOffset for
  // KHTML/WebKit only.
  Element.Methods.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return Element._returnOffset(valueL, valueT);
  };
}

if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  Element.Methods.update = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);

    content = Object.toHTML(content);
    var tagName = element.tagName.toUpperCase();

    if (tagName in Element._insertionTranslations.tags) {
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      Element._getContentFromAnonymousElement(tagName, content.stripScripts())
        .each(function(node) { element.appendChild(node) });
    }
    else element.innerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

if ('outerHTML' in document.createElement('div')) {
  Element.Methods.replace = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) {
      element.parentNode.replaceChild(content, element);
      return element;
    }

    content = Object.toHTML(content);
    var parent = element.parentNode, tagName = parent.tagName.toUpperCase();

    if (Element._insertionTranslations.tags[tagName]) {
      var nextSibling = element.next();
      var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
      parent.removeChild(element);
      if (nextSibling)
        fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
      else
        fragments.each(function(node) { parent.appendChild(node) });
    }
    else element.outerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

Element._returnOffset = function(l, t) {
  var result = [l, t];
  result.left = l;
  result.top = t;
  return result;
};

Element._getContentFromAnonymousElement = function(tagName, html) {
  var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  if (t) {
    div.innerHTML = t[0] + html + t[1];
    t[2].times(function() { div = div.firstChild });
  } else div.innerHTML = html;
  return $A(div.childNodes);
};

Element._insertionTranslations = {
  before: function(element, node) {
    element.parentNode.insertBefore(node, element);
  },
  top: function(element, node) {
    element.insertBefore(node, element.firstChild);
  },
  bottom: function(element, node) {
    element.appendChild(node);
  },
  after: function(element, node) {
    element.parentNode.insertBefore(node, element.nextSibling);
  },
  tags: {
    TABLE:  ['<table>',                '</table>',                   1],
    TBODY:  ['<table><tbody>',         '</tbody></table>',           2],
    TR:     ['<table><tbody><tr>',     '</tr></tbody></table>',      3],
    TD:     ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
    SELECT: ['<select>',               '</select>',                  1]
  }
};

(function() {
  Object.extend(this.tags, {
    THEAD: this.tags.TBODY,
    TFOOT: this.tags.TBODY,
    TH:    this.tags.TD
  });
}).call(Element._insertionTranslations);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    attribute = Element._attributeTranslations.has[attribute] || attribute;
    var node = $(element).getAttributeNode(attribute);
    return node && node.specified;
  }
};

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
    document.createElement('div').__proto__) {
  window.HTMLElement = { };
  window.HTMLElement.prototype = document.createElement('div').__proto__;
  Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.extend = (function() {
  if (Prototype.BrowserFeatures.SpecificElementExtensions)
    return Prototype.K;

  var Methods = { }, ByTag = Element.Methods.ByTag;

  var extend = Object.extend(function(element) {
    if (!element || element._extendedByPrototype ||
        element.nodeType != 1 || element == window) return element;

    var methods = Object.clone(Methods),
      tagName = element.tagName, property, value;

    // extend methods for specific tags
    if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

    for (property in methods) {
      value = methods[property];
      if (Object.isFunction(value) && !(property in element))
        element[property] = value.methodize();
    }

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

  }, {
    refresh: function() {
      // extend methods for all tags (Safari doesn't need this)
      if (!Prototype.BrowserFeatures.ElementExtensions) {
        Object.extend(Methods, Element.Methods);
        Object.extend(Methods, Element.Methods.Simulated);
      }
    }
  });

  extend.refresh();
  return extend;
})();

Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

  if (!methods) {
    Object.extend(Form, Form.Methods);
    Object.extend(Form.Element, Form.Element.Methods);
    Object.extend(Element.Methods.ByTag, {
      "FORM":     Object.clone(Form.Methods),
      "INPUT":    Object.clone(Form.Element.Methods),
      "SELECT":   Object.clone(Form.Element.Methods),
      "TEXTAREA": Object.clone(Form.Element.Methods)
    });
  }

  if (arguments.length == 2) {
    var tagName = methods;
    methods = arguments[1];
  }

  if (!tagName) Object.extend(Element.Methods, methods || { });
  else {
    if (Object.isArray(tagName)) tagName.each(extend);
    else extend(tagName);
  }

  function extend(tagName) {
    tagName = tagName.toUpperCase();
    if (!Element.Methods.ByTag[tagName])
      Element.Methods.ByTag[tagName] = { };
    Object.extend(Element.Methods.ByTag[tagName], methods);
  }

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    for (var property in methods) {
      var value = methods[property];
      if (!Object.isFunction(value)) continue;
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = value.methodize();
    }
  }

  function findDOMClass(tagName) {
    var klass;
    var trans = {
      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
      "FrameSet", "IFRAME": "IFrame"
    };
    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName.capitalize() + 'Element';
    if (window[klass]) return window[klass];

    window[klass] = { };
    window[klass].prototype = document.createElement(tagName).__proto__;
    return window[klass];
  }

  if (F.ElementExtensions) {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }

  if (F.SpecificElementExtensions) {
    for (var tag in Element.Methods.ByTag) {
      var klass = findDOMClass(tag);
      if (Object.isUndefined(klass)) continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;

  if (Element.extend.refresh) Element.extend.refresh();
  Element.cache = { };
};

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

  getWidth: function() {
    return this.getDimensions().width;
  },

  getHeight: function() {
    return this.getDimensions().height;
  },

  getScrollOffsets: function() {
    return Element._returnOffset(
      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
};
/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
 * license.  Please see http://www.yui-ext.com/ for more information. */

var Selector = Class.create({
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  shouldUseXPath: function() {
    if (!Prototype.BrowserFeatures.XPath) return false;

    var e = this.expression;

    // Safari 3 chokes on :*-of-type and :empty
    if (Prototype.Browser.WebKit &&
     (e.include("-of-type") || e.include(":empty")))
      return false;

    // XPath can't do namespaced attributes, nor can it read
    // the "checked" property from DOM nodes
    if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
      return false;

    return true;
  },

  compileMatcher: function() {
    if (this.shouldUseXPath())
      return this.compileXPathMatcher();

    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m;

    if (Selector._cache[e]) {
      this.matcher = Selector._cache[e];
      return;
    }

    this.matcher = ["this.matcher = function(root) {",
                    "var r = root, h = Selector.handlers, c = false, n;"];

    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
    	      new Template(c[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.matcher.push("return h.unique(n);\n}");
    eval(this.matcher.join('\n'));
    Selector._cache[this.expression] = this.matcher;
  },

  compileXPathMatcher: function() {
    var e = this.expression, ps = Selector.patterns,
        x = Selector.xpath, le, m;

    if (Selector._cache[e]) {
      this.xpath = Selector._cache[e]; return;
    }

    this.matcher = ['.//*'];
    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        if (m = e.match(ps[i])) {
          this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
            new Template(x[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.xpath = this.matcher.join('');
    Selector._cache[this.expression] = this.xpath;
  },

  findElements: function(root) {
    root = root || document;
    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
    return this.matcher(root);
  },

  match: function(element) {
    this.tokens = [];

    var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
    var le, p, m;

    while (e && le !== e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          // use the Selector.assertions methods unless the selector
          // is too complex.
          if (as[i]) {
            this.tokens.push([i, Object.clone(m)]);
            e = e.replace(m[0], '');
          } else {
            // reluctantly do a document-wide search
            // and look for a match in the array
            return this.findElements(document).include(element);
          }
        }
      }
    }

    var match = true, name, matches;
    for (var i = 0, token; token = this.tokens[i]; i++) {
      name = token[0], matches = token[1];
      if (!Selector.assertions[name](element, matches)) {
        match = false; break;
      }
    }

    return match;
  },

  toString: function() {
    return this.expression;
  },

  inspect: function() {
    return "#<Selector:" + this.expression.inspect() + ">";
  }
});

Object.extend(Selector, {
  _cache: { },

  xpath: {
    descendant:   "//*",
    child:        "/*",
    adjacent:     "/following-sibling::*[1]",
    laterSibling: '/following-sibling::*',
    tagName:      function(m) {
      if (m[1] == '*') return '';
      return "[local-name()='" + m[1].toLowerCase() +
             "' or local-name()='" + m[1].toUpperCase() + "']";
    },
    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
    id:           "[@id='#{1}']",
    attrPresence: function(m) {
      m[1] = m[1].toLowerCase();
      return new Template("[@#{1}]").evaluate(m);
    },
    attr: function(m) {
      m[1] = m[1].toLowerCase();
      m[3] = m[5] || m[6];
      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
    },
    pseudo: function(m) {
      var h = Selector.xpath.pseudos[m[1]];
      if (!h) return '';
      if (Object.isFunction(h)) return h(m);
      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
    },
    operators: {
      '=':  "[@#{1}='#{3}']",
      '!=': "[@#{1}!='#{3}']",
      '^=': "[starts-with(@#{1}, '#{3}')]",
      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
      '*=': "[contains(@#{1}, '#{3}')]",
      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
    },
    pseudos: {
      'first-child': '[not(preceding-sibling::*)]',
      'last-child':  '[not(following-sibling::*)]',
      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
      'checked':     "[@checked]",
      'disabled':    "[@disabled]",
      'enabled':     "[not(@disabled)]",
      'not': function(m) {
        var e = m[6], p = Selector.patterns,
            x = Selector.xpath, le, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
              e = e.replace(m[0], '');
              break;
            }
          }
        }
        return "[not(" + exclusion.join(" and ") + ")]";
      },
      'nth-child':      function(m) {
        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
      },
      'nth-last-child': function(m) {
        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
      },
      'nth-of-type':    function(m) {
        return Selector.xpath.pseudos.nth("position() ", m);
      },
      'nth-last-of-type': function(m) {
        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
      },
      'first-of-type':  function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
      },
      'last-of-type':   function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
      },
      'only-of-type':   function(m) {
        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
      },
      nth: function(fragment, m) {
        var mm, formula = m[6], predicate;
        if (formula == 'even') formula = '2n+0';
        if (formula == 'odd')  formula = '2n+1';
        if (mm = formula.match(/^(\d+)$/)) // digit only
          return '[' + fragment + "= " + mm[1] + ']';
        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
          if (mm[1] == "-") mm[1] = -1;
          var a = mm[1] ? Number(mm[1]) : 1;
          var b = mm[2] ? Number(mm[2]) : 0;
          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
          "((#{fragment} - #{b}) div #{a} >= 0)]";
          return new Template(predicate).evaluate({
            fragment: fragment, a: a, b: b });
        }
      }
    }
  },

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);      c = false;',
    className:    'n = h.className(n, r, "#{1}", c);    c = false;',
    id:           'n = h.id(n, r, "#{1}", c);           c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
    },
    pseudo: function(m) {
      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
    },
    descendant:   'c = "descendant";',
    child:        'c = "child";',
    adjacent:     'c = "adjacent";',
    laterSibling: 'c = "laterSibling";'
  },

  patterns: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

    // selectors follow
    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
    id:           /^#([\w\-\*]+)(\b|$)/,
    className:    /^\.([\w\-\*]+)(\b|$)/,
    pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
    attrPresence: /^\[([\w]+)\]/,
    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  },

  // for Selector.match and Element#match
  assertions: {
    tagName: function(element, matches) {
      return matches[1].toUpperCase() == element.tagName.toUpperCase();
    },

    className: function(element, matches) {
      return Element.hasClassName(element, matches[1]);
    },

    id: function(element, matches) {
      return element.id === matches[1];
    },

    attrPresence: function(element, matches) {
      return Element.hasAttribute(element, matches[1]);
    },

    attr: function(element, matches) {
      var nodeValue = Element.readAttribute(element, matches[1]);
      return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
    }
  },

  handlers: {
    // UTILITY FUNCTIONS
    // joins two collections
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        a.push(node);
      return a;
    },

    // marks an array of nodes for counting
    mark: function(nodes) {
      var _true = Prototype.emptyFunction;
      for (var i = 0, node; node = nodes[i]; i++)
        node._countedByPrototype = _true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._countedByPrototype = undefined;
      return nodes;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._countedByPrototype = Prototype.emptyFunction;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          var node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
      }
    },

    // filters out duplicates and extends all nodes
    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (!(n = nodes[i])._countedByPrototype) {
          n._countedByPrototype = Prototype.emptyFunction;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

    // COMBINATOR FUNCTIONS
    descendant: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, node.getElementsByTagName('*'));
      return results;
    },

    child: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        for (var j = 0, child; child = node.childNodes[j]; j++)
          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
      }
      return results;
    },

    adjacent: function(nodes) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        var next = this.nextElementSibling(node);
        if (next) results.push(next);
      }
      return results;
    },

    laterSibling: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, Element.nextSiblings(node));
      return results;
    },

    nextElementSibling: function(node) {
      while (node = node.nextSibling)
	      if (node.nodeType == 1) return node;
      return null;
    },

    previousElementSibling: function(node) {
      while (node = node.previousSibling)
        if (node.nodeType == 1) return node;
      return null;
    },

    // TOKEN FUNCTIONS
    tagName: function(nodes, root, tagName, combinator) {
      var uTagName = tagName.toUpperCase();
      var results = [], h = Selector.handlers;
      if (nodes) {
        if (combinator) {
          // fastlane for ordinary descendant combinators
          if (combinator == "descendant") {
            for (var i = 0, node; node = nodes[i]; i++)
              h.concat(results, node.getElementsByTagName(tagName));
            return results;
          } else nodes = this[combinator](nodes);
          if (tagName == "*") return nodes;
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName.toUpperCase() === uTagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!targetNode) return [];
      if (!nodes && root == document) return [targetNode];
      if (nodes) {
        if (combinator) {
          if (combinator == 'child') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (targetNode.parentNode == node) return [targetNode];
          } else if (combinator == 'descendant') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Element.descendantOf(targetNode, node)) return [targetNode];
          } else if (combinator == 'adjacent') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Selector.handlers.previousElementSibling(targetNode) == node)
                return [targetNode];
          } else nodes = h[combinator](nodes);
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node == targetNode) return [targetNode];
        return [];
      }
      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
    },

    className: function(nodes, root, className, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      return Selector.handlers.byClassName(nodes, root, className);
    },

    byClassName: function(nodes, root, className) {
      if (!nodes) nodes = Selector.handlers.descendant([root]);
      var needle = ' ' + className + ' ';
      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
        nodeClassName = node.className;
        if (nodeClassName.length == 0) continue;
        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
          results.push(node);
      }
      return results;
    },

    attrPresence: function(nodes, root, attr, combinator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      if (nodes && combinator) nodes = this[combinator](nodes);
      var results = [];
      for (var i = 0, node; node = nodes[i]; i++)
        if (Element.hasAttribute(node, attr)) results.push(node);
      return results;
    },

    attr: function(nodes, root, attr, value, operator, combinator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      if (nodes && combinator) nodes = this[combinator](nodes);
      var handler = Selector.operators[operator], results = [];
      for (var i = 0, node; node = nodes[i]; i++) {
        var nodeValue = Element.readAttribute(node, attr);
        if (nodeValue === null) continue;
        if (handler(nodeValue, value)) results.push(node);
      }
      return results;
    },

    pseudo: function(nodes, name, value, root, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      if (!nodes) nodes = root.getElementsByTagName("*");
      return Selector.pseudos[name](nodes, value, root);
    }
  },

  pseudos: {
    'first-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.previousElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'last-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.nextElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'only-child': function(nodes, value, root) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
          results.push(node);
      return results;
    },
    'nth-child':        function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root);
    },
    'nth-last-child':   function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true);
    },
    'nth-of-type':      function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, false, true);
    },
    'nth-last-of-type': function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true, true);
    },
    'first-of-type':    function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, false, true);
    },
    'last-of-type':     function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, true, true);
    },
    'only-of-type':     function(nodes, formula, root) {
      var p = Selector.pseudos;
      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
    },

    // handles the an+b logic
    getIndices: function(a, b, total) {
      if (a == 0) return b > 0 ? [b] : [];
      return $R(1, total).inject([], function(memo, i) {
        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
        return memo;
      });
    },

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._countedByPrototype) {
          h.index(node.parentNode, reverse, ofType);
          indexed.push(node.parentNode);
        }
      }
      if (formula.match(/^\d+$/)) { // just a number
        formula = Number(formula);
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.nodeIndex == formula) results.push(node);
      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
        if (m[1] == "-") m[1] = -1;
        var a = m[1] ? Number(m[1]) : 1;
        var b = m[2] ? Number(m[2]) : 0;
        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
          for (var j = 0; j < l; j++)
            if (node.nodeIndex == indices[j]) results.push(node);
        }
      }
      h.unmark(nodes);
      h.unmark(indexed);
      return results;
    },

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        // IE treats comments as element nodes
        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
        results.push(node);
      }
      return results;
    },

    'not': function(nodes, selector, root) {
      var h = Selector.handlers, selectorType, m;
      var exclusions = new Selector(selector).findElements(root);
      h.mark(exclusions);
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node._countedByPrototype) results.push(node);
      h.unmark(exclusions);
      return results;
    },

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled) results.push(node);
      return results;
    },

    'disabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.disabled) results.push(node);
      return results;
    },

    'checked': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.checked) results.push(node);
      return results;
    }
  },

  operators: {
    '=':  function(nv, v) { return nv == v; },
    '!=': function(nv, v) { return nv != v; },
    '^=': function(nv, v) { return nv.startsWith(v); },
    '$=': function(nv, v) { return nv.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  },

  split: function(expression) {
    var expressions = [];
    expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    return expressions;
  },

  matchElements: function(elements, expression) {
    var matches = $$(expression), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._countedByPrototype) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (Object.isNumber(expression)) {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    expressions = Selector.split(expressions.join(','));
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

if (Prototype.Browser.IE) {
  Object.extend(Selector.handlers, {
    // IE returns comment nodes on getElementsByTagName("*").
    // Filter them out.
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        if (node.tagName !== "!") a.push(node);
      return a;
    },

    // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node.removeAttribute('_countedByPrototype');
      return nodes;
    }
  });
}

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, options) {
    if (typeof options != 'object') options = { hash: !!options };
    else if (Object.isUndefined(options.hash)) options.hash = true;
    var key, value, submitted = false, submit = options.submit;

    var data = elements.inject({ }, function(result, element) {
      if (!element.disabled && element.name) {
        key = element.name; value = $(element).getValue();
        if (value != null && (element.type != 'submit' || (!submitted &&
            submit !== false && (!submit || key == submit) && (submitted = true)))) {
          if (key in result) {
            // a key is already present; construct an array of values
            if (!Object.isArray(result[key])) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return options.hash ? data : Object.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, options) {
    return Form.serializeElements(Form.getElements(form), options);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('disable');
    return form;
  },

  enable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('enable');
    return form;
  },

  findFirstElement: function(form) {
    var elements = $(form).getElements().findAll(function(element) {
      return 'hidden' != element.type && !element.disabled;
    });
    var firstByIndex = elements.findAll(function(element) {
      return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
    }).sortBy(function(element) { return element.tabIndex }).first();

    return firstByIndex ? firstByIndex : elements.find(function(element) {
      return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  },

  request: function(form, options) {
    form = $(form), options = Object.clone(options || { });

    var params = options.parameters, action = form.readAttribute('action') || '';
    if (action.blank()) action = window.location.href;
    options.parameters = form.serialize(true);

    if (params) {
      if (Object.isString(params)) params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(action, options);
  }
};

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
};

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = { };
        pair[element.name] = value;
        return Object.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  setValue: function(element, value) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    Form.Element.Serializers[method](element, value);
    return element;
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    try {
      element.focus();
      if (element.select && (element.tagName.toLowerCase() != 'input' ||
          !['button', 'reset', 'submit'].include(element.type)))
        element.select();
    } catch (e) { }
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.disabled = false;
    return element;
  }
};

/*--------------------------------------------------------------------------*/

var Field = Form.Element;
var $F = Form.Element.Methods.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element, value) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element, value);
      default:
        return Form.Element.Serializers.textarea(element, value);
    }
  },

  inputSelector: function(element, value) {
    if (Object.isUndefined(value)) return element.checked ? element.value : null;
    else element.checked = !!value;
  },

  textarea: function(element, value) {
    if (Object.isUndefined(value)) return element.value;
    else element.value = value;
  },

  select: function(element, index) {
    if (Object.isUndefined(index))
      return this[element.type == 'select-one' ?
        'selectOne' : 'selectMany'](element);
    else {
      var opt, value, single = !Object.isArray(index);
      for (var i = 0, length = element.length; i < length; i++) {
        opt = element.options[i];
        value = this.optionValue(opt);
        if (single) {
          if (value == index) {
            opt.selected = true;
            return;
          }
        }
        else opt.selected = index.include(value);
      }
    }
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
};

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  initialize: function($super, element, frequency, callback) {
    $super(callback, frequency);
    this.element   = $(element);
    this.lastValue = this.getValue();
  },

  execute: function() {
    var value = this.getValue();
    if (Object.isString(this.lastValue) && Object.isString(value) ?
        this.lastValue != value : String(this.lastValue) != String(value)) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
});

Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = Class.create({
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback, this);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
});

Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) var Event = { };

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,
  KEY_INSERT:   45,

  cache: { },

  relatedTarget: function(event) {
    var element;
    switch(event.type) {
      case 'mouseover': element = event.fromElement; break;
      case 'mouseout':  element = event.toElement;   break;
      default: return null;
    }
    return Element.extend(element);
  }
});

Event.Methods = (function() {
  var isButton;

  if (Prototype.Browser.IE) {
    var buttonMap = { 0: 1, 1: 4, 2: 2 };
    isButton = function(event, code) {
      return event.button == buttonMap[code];
    };

  } else if (Prototype.Browser.WebKit) {
    isButton = function(event, code) {
      switch (code) {
        case 0: return event.which == 1 && !event.metaKey;
        case 1: return event.which == 1 && event.metaKey;
        default: return false;
      }
    };

  } else {
    isButton = function(event, code) {
      return event.which ? (event.which === code + 1) : (event.button === code);
    };
  }

  return {
    isLeftClick:   function(event) { return isButton(event, 0) },
    isMiddleClick: function(event) { return isButton(event, 1) },
    isRightClick:  function(event) { return isButton(event, 2) },

    element: function(event) {
      var node = Event.extend(event).target;
      return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
    },

    findElement: function(event, expression) {
      var element = Event.element(event);
      if (!expression) return element;
      var elements = [element].concat(element.ancestors());
      return Selector.findElement(elements, expression, 0);
    },

    pointer: function(event) {
      return {
        x: event.pageX || (event.clientX +
          (document.documentElement.scrollLeft || document.body.scrollLeft)),
        y: event.pageY || (event.clientY +
          (document.documentElement.scrollTop || document.body.scrollTop))
      };
    },

    pointerX: function(event) { return Event.pointer(event).x },
    pointerY: function(event) { return Event.pointer(event).y },

    stop: function(event) {
      Event.extend(event);
      event.preventDefault();
      event.stopPropagation();
      event.stopped = true;
    }
  };
})();

Event.extend = (function() {
  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
    m[name] = Event.Methods[name].methodize();
    return m;
  });

  if (Prototype.Browser.IE) {
    Object.extend(methods, {
      stopPropagation: function() { this.cancelBubble = true },
      preventDefault:  function() { this.returnValue = false },
      inspect: function() { return "[object Event]" }
    });

    return function(event) {
      if (!event) return false;
      if (event._extendedByPrototype) return event;

      event._extendedByPrototype = Prototype.emptyFunction;
      var pointer = Event.pointer(event);
      Object.extend(event, {
        target: event.srcElement,
        relatedTarget: Event.relatedTarget(event),
        pageX:  pointer.x,
        pageY:  pointer.y
      });
      return Object.extend(event, methods);
    };

  } else {
    Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
    Object.extend(Event.prototype, methods);
    return Prototype.K;
  }
})();

Object.extend(Event, (function() {
  var cache = Event.cache;

  function getEventID(element) {
    if (element._prototypeEventID) return element._prototypeEventID[0];
    arguments.callee.id = arguments.callee.id || 1;
    return element._prototypeEventID = [++arguments.callee.id];
  }

  function getDOMEventName(eventName) {
    if (eventName && eventName.include(':')) return "dataavailable";
    return eventName;
  }

  function getCacheForID(id) {
    return cache[id] = cache[id] || { };
  }

  function getWrappersForEventName(id, eventName) {
    var c = getCacheForID(id);
    return c[eventName] = c[eventName] || [];
  }

  function createWrapper(element, eventName, handler) {
    var id = getEventID(element);
    var c = getWrappersForEventName(id, eventName);
    if (c.pluck("handler").include(handler)) return false;

    var wrapper = function(event) {
      if (!Event || !Event.extend ||
        (event.eventName && event.eventName != eventName))
          return false;

      Event.extend(event);
      handler.call(element, event);
    };

    wrapper.handler = handler;
    c.push(wrapper);
    return wrapper;
  }

  function findWrapper(id, eventName, handler) {
    var c = getWrappersForEventName(id, eventName);
    return c.find(function(wrapper) { return wrapper.handler == handler });
  }

  function destroyWrapper(id, eventName, handler) {
    var c = getCacheForID(id);
    if (!c[eventName]) return false;
    c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  }

  function destroyCache() {
    for (var id in cache)
      for (var eventName in cache[id])
        cache[id][eventName] = null;
  }

  if (window.attachEvent) {
    window.attachEvent("onunload", destroyCache);
  }

  return {
    observe: function(element, eventName, handler) {
      element = $(element);
      var name = getDOMEventName(eventName);

      var wrapper = createWrapper(element, eventName, handler);
      if (!wrapper) return element;

      if (element.addEventListener) {
        element.addEventListener(name, wrapper, false);
      } else {
        element.attachEvent("on" + name, wrapper);
      }

      return element;
    },

    stopObserving: function(element, eventName, handler) {
      element = $(element);
      var id = getEventID(element), name = getDOMEventName(eventName);

      if (!handler && eventName) {
        getWrappersForEventName(id, eventName).each(function(wrapper) {
          element.stopObserving(eventName, wrapper.handler);
        });
        return element;

      } else if (!eventName) {
        Object.keys(getCacheForID(id)).each(function(eventName) {
          element.stopObserving(eventName);
        });
        return element;
      }

      var wrapper = findWrapper(id, eventName, handler);
      if (!wrapper) return element;

      if (element.removeEventListener) {
        element.removeEventListener(name, wrapper, false);
      } else {
        element.detachEvent("on" + name, wrapper);
      }

      destroyWrapper(id, eventName, handler);

      return element;
    },

    fire: function(element, eventName, memo) {
      element = $(element);
      if (element == document && document.createEvent && !element.dispatchEvent)
        element = document.documentElement;

      var event;
      if (document.createEvent) {
        event = document.createEvent("HTMLEvents");
        event.initEvent("dataavailable", true, true);
      } else {
        event = document.createEventObject();
        event.eventType = "ondataavailable";
      }

      event.eventName = eventName;
      event.memo = memo || { };

      if (document.createEvent) {
        element.dispatchEvent(event);
      } else {
        element.fireEvent(event.eventType, event);
      }

      return Event.extend(event);
    }
  };
})());

Object.extend(Event, Event.Methods);

Element.addMethods({
  fire:          Event.fire,
  observe:       Event.observe,
  stopObserving: Event.stopObserving
});

Object.extend(document, {
  fire:          Element.Methods.fire.methodize(),
  observe:       Element.Methods.observe.methodize(),
  stopObserving: Element.Methods.stopObserving.methodize(),
  loaded:        false
});

(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards and John Resig. */

  var timer;

  function fireContentLoadedEvent() {
    if (document.loaded) return;
    if (timer) window.clearInterval(timer);
    document.fire("dom:loaded");
    document.loaded = true;
  }

  if (document.addEventListener) {
    if (Prototype.Browser.WebKit) {
      timer = window.setInterval(function() {
        if (/loaded|complete/.test(document.readyState))
          fireContentLoadedEvent();
      }, 0);

      Event.observe(window, "load", fireContentLoadedEvent);

    } else {
      document.addEventListener("DOMContentLoaded",
        fireContentLoadedEvent, false);
    }

  } else {
    document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
    $("__onDOMContentLoaded").onreadystatechange = function() {
      if (this.readyState == "complete") {
        this.onreadystatechange = null;
        fireContentLoadedEvent();
      }
    };
  }
})();
/*------------------------------- DEPRECATED -------------------------------*/

Hash.toQueryString = Object.toQueryString;

var Toggle = { display: Element.toggle };

Element.Methods.childOf = Element.Methods.descendantOf;

var Insertion = {
  Before: function(element, content) {
    return Element.insert(element, {before:content});
  },

  Top: function(element, content) {
    return Element.insert(element, {top:content});
  },

  Bottom: function(element, content) {
    return Element.insert(element, {bottom:content});
  },

  After: function(element, content) {
    return Element.insert(element, {after:content});
  }
};

var $continue = new Error('"throw $continue" is deprecated, use "return" instead');

// This should be moved to script.aculo.us; notice the deprecated methods
// further below, that map to the newer Element methods.
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = Element.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = Element.cumulativeScrollOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = Element.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  // Deprecation layer -- use newer Element methods now (1.5.2).

  cumulativeOffset: Element.Methods.cumulativeOffset,

  positionedOffset: Element.Methods.positionedOffset,

  absolutize: function(element) {
    Position.prepare();
    return Element.absolutize(element);
  },

  relativize: function(element) {
    Position.prepare();
    return Element.relativize(element);
  },

  realOffset: Element.Methods.cumulativeScrollOffset,

  offsetParent: Element.Methods.getOffsetParent,

  page: Element.Methods.viewportOffset,

  clone: function(source, target, options) {
    options = options || { };
    return Element.clonePosition(target, source, options);
  }
};

/*--------------------------------------------------------------------------*/

if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  function iter(name) {
    return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  }

  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  function(element, className) {
    className = className.toString().strip();
    var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
    return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  } : function(element, className) {
    className = className.toString().strip();
    var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
    if (!classNames && !className) return elements;

    var nodes = $(element).getElementsByTagName('*');
    className = ' ' + className + ' ';

    for (var i = 0, child, cn; child = nodes[i]; i++) {
      if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
          (classNames && classNames.all(function(name) {
            return !name.toString().blank() && cn.include(' ' + name + ' ');
          }))))
        elements.push(Element.extend(child));
    }
    return elements;
  };

  return function(className, parentElement) {
    return $(parentElement || document.body).getElementsByClassName(className);
  };
}(Element.Methods);

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);

/*--------------------------------------------------------------------------*/

Element.addMethods();
/* --- /http://test.unserdaheim.at/templates/daheim/scripts/prototype.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/friend.js --- */
function confirmFriend(fid, url) {

	var text = document.getElementById('t_short').value;
	var subject = $('subject').value;
	var fsname = $('fsname').value;
	var uname = $('uname').value;
	var uurl = $('uurl').value;
	var email = $('email').value;
	var roles = $('roles').value;
	
	new Ajax.Request('/benutzer_profil/meinekontakte/confirm/', {
			method: 'post',
			parameters: {fid:fid, text:text, subject:subject, fsname: fsname, uname:uname, uurl:uurl, email:email, roles:roles},
			onComplete: function(e) {
				if (!url) {
					window.location.reload();
				} else {
					window.location.href = url;
				}
				
				}
		});
}

function deleteFriend(fid, url, mail) {
	if($('t_short')){
		var text = document.getElementById('t_short').value;
	}
	new Ajax.Request('/benutzer_profil/meinekontakte/delete/', {

			method: 'post',
			parameters: {fid:fid, mail:mail, text:text},
			onComplete: function(e) {
				
				if (!url) {
				window.location.reload();
				} else {
				window.location.href = url;
				}
			}
		});
}

/* --- /http://test.unserdaheim.at/templates/daheim/scripts/friend.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/btn.js --- */
var btn = {
    init : function() {
        if (!document.getElementById || !document.createElement || !document.appendChild) return false;
        as = btn.getElementsByClassName('btn(.*)');
        for (i=0; i<as.length; i++) {
            if ( as[i].tagName == "INPUT" && ( as[i].type.toLowerCase() == "submit" || as[i].type.toLowerCase() == "button" ) ) {
                var a1 = document.createElement("a");
                a1.appendChild(document.createTextNode(as[i].value));
                a1.className = as[i].className;
                a1.id = as[i].id;
                as[i] = as[i].parentNode.replaceChild(a1, as[i]);
                as[i] = a1;
                as[i].style.cursor = "pointer";
            }
            else if (as[i].tagName == "A") {
                var tt = as[i].childNodes;
            }
            else { return false };
            var i1 = document.createElement('i');
            var i2 = document.createElement('i');
            var s1 = document.createElement('span');
            var s2 = document.createElement('span');
            s1.appendChild(i1);
            s1.appendChild(s2);
            while (as[i].firstChild) {
              s1.appendChild(as[i].firstChild);
            }
            as[i].appendChild(s1);
            as[i] = as[i].insertBefore(i2, s1);
        }
        // The following lines submits the form if the button id is "submit_btn"
		
var submit_buttons = $$('a[id^=submit_btn]');
for (j = 0; j<submit_buttons.length; j++) {
	btn.addEvent(submit_buttons[j],'click',function() { /*alert("hit");*/ this.up('form').submit(); });
}
    },
    findForm : function(f) {
        while(f.tagName != "FORM") {
            f = f.parentNode;
        }
        return f;
    },
    addEvent : function(obj, type, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(type, fn, false);
        }
        else if (obj.attachEvent) {
            obj["e"+type+fn] = fn;
            obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
            obj.attachEvent("on"+type, obj[type+fn]);
        }
    },
    getElementsByClassName : function(className, tag, elm) {
        var testClass = new RegExp("(^|\s)" + className + "(\s|$)");
        var tag = tag || "*";
        var elm = elm || document;
        var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
        var returnElements = [];
        var current;
        var length = elements.length;
        for(var i=0; i<length; i++){
            current = elements[i];
            if(testClass.test(current.className)){
                returnElements.push(current);
            }
        }
        return returnElements;
    }
}
btn.addEvent(window,'load', function() { btn.init();} );

/* --- /http://test.unserdaheim.at/templates/daheim/scripts/btn.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/window.js --- */

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

var Window = Class.create();

Window.keepMultiModalWindow = false;
Window.hasEffectLib = (typeof Effect != 'undefined');
Window.resizeEffectDuration = 0.1;

Window.prototype = {
// Constructor
// Available parameters : className, blurClassName, title, minWidth, minHeight, maxWidth, maxHeight, width, height, top, left, bottom, right, resizable, zIndex, opacity, recenterAuto, wiredDrag
//                        hideEffect, showEffect, showEffectOptions, hideEffectOptions, effectOptions, url, draggable, closable, minimizable, maximizable, parent, onload
//                        add all callbacks (if you do not use an observer)
//                        onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose

initialize: function() {
 var id;
 var optionIndex = 0;
 // For backward compatibility like win= new Window("id", {...}) instead of win = new Window({id: "id", ...})
 if (arguments.length > 0) {
   if (typeof arguments[0] == "string" ) {
     id = arguments[0];
     optionIndex = 1;
   }
   else
     id = arguments[0] ? arguments[0].id : null;
 }
 
 // Generate unique ID if not specified
 if (!id)
   id = "window_" + new Date().getTime();
   
 if ($(id))
   alert("Window " + id + " is already registered in the DOM! Make sure you use setDestroyOnClose() or destroyOnClose: true in the constructor");

 this.options = Object.extend({
   className:         "dialog",
   blurClassName:     null,
   minWidth:          100, 
   minHeight:         20,
   resizable:         true,
   closable:          true,
   minimizable:       true,
   maximizable:       true,
   draggable:         true,
   userData:          null,
   showEffect:        (Window.hasEffectLib ? Effect.Appear : Element.show),
   hideEffect:        (Window.hasEffectLib ? Effect.Fade : Element.hide),
   showEffectOptions: {},
   hideEffectOptions: {},
   effectOptions:     null,
   parent:            document.body,
   title:             "&nbsp;",
   url:               null,
   onload:            Prototype.emptyFunction,
   width:             200,
   height:            300,
   opacity:           1,
   recenterAuto:      true,
   wiredDrag:         false,
   closeCallback:     null,
   destroyOnClose:    false,
   gridX:             1, 
   gridY:             1      
 }, arguments[optionIndex] || {});
 if (this.options.blurClassName)
   this.options.focusClassName = this.options.className;
   
 if (typeof this.options.top == "undefined" &&  typeof this.options.bottom ==  "undefined") 
   this.options.top = this._round(Math.random()*500, this.options.gridY);
 if (typeof this.options.left == "undefined" &&  typeof this.options.right ==  "undefined") 
   this.options.left = this._round(Math.random()*500, this.options.gridX);

 if (this.options.effectOptions) {
   Object.extend(this.options.hideEffectOptions, this.options.effectOptions);
   Object.extend(this.options.showEffectOptions, this.options.effectOptions);
   if (this.options.showEffect == Element.Appear)
     this.options.showEffectOptions.to = this.options.opacity;
 }
 if (Window.hasEffectLib) {
   if (this.options.showEffect == Effect.Appear)
     this.options.showEffectOptions.to = this.options.opacity;
 
   if (this.options.hideEffect == Effect.Fade)
     this.options.hideEffectOptions.from = this.options.opacity;
 }
 if (this.options.hideEffect == Element.hide)
   this.options.hideEffect = function(){ Element.hide(this.element); if (this.options.destroyOnClose) this.destroy(); }.bind(this)
 
 if (this.options.parent != document.body)  
   this.options.parent = $(this.options.parent);
   
 this.element = this._createWindow(id);       
 this.element.win = this;
 
 // Bind event listener
 this.eventMouseDown = this._initDrag.bindAsEventListener(this);
 this.eventMouseUp   = this._endDrag.bindAsEventListener(this);
 this.eventMouseMove = this._updateDrag.bindAsEventListener(this);
 this.eventOnLoad    = this._getWindowBorderSize.bindAsEventListener(this);
 this.eventMouseDownContent = this.toFront.bindAsEventListener(this);
 this.eventResize = this._recenter.bindAsEventListener(this);

 this.topbar = $(this.element.id + "_top");
 this.bottombar = $(this.element.id + "_bottom");
 this.content = $(this.element.id + "_content");
 
 Event.observe(this.topbar, "mousedown", this.eventMouseDown);
 Event.observe(this.bottombar, "mousedown", this.eventMouseDown);
 Event.observe(this.content, "mousedown", this.eventMouseDownContent);
 Event.observe(window, "load", this.eventOnLoad);
 Event.observe(window, "resize", this.eventResize);
 Event.observe(window, "scroll", this.eventResize);
 Event.observe(this.options.parent, "scroll", this.eventResize);
 
 if (this.options.draggable)  {
   var that = this;
   [this.topbar, this.topbar.up().previous(), this.topbar.up().next()].each(function(element) {
     element.observe("mousedown", that.eventMouseDown);
     element.addClassName("top_draggable");
   });
   [this.bottombar.up(), this.bottombar.up().previous(), this.bottombar.up().next()].each(function(element) {
     element.observe("mousedown", that.eventMouseDown);
     element.addClassName("bottom_draggable");
   });
   
 }    
 
 if (this.options.resizable) {
   this.sizer = $(this.element.id + "_sizer");
   Event.observe(this.sizer, "mousedown", this.eventMouseDown);
 }  
 
 this.useLeft = null;
 this.useTop = null;
 if (typeof this.options.left != "undefined") {
   this.element.setStyle({left: parseFloat(this.options.left) + 'px'});
   this.useLeft = true;
 }
 else {
   this.element.setStyle({right: parseFloat(this.options.right) + 'px'});
   this.useLeft = false;
 }
 
 if (typeof this.options.top != "undefined") {
   this.element.setStyle({top: parseFloat(this.options.top) + 'px'});
   this.useTop = true;
 }
 else {
   this.element.setStyle({bottom: parseFloat(this.options.bottom) + 'px'});      
   this.useTop = false;
 }
   
 this.storedLocation = null;
 
 this.setOpacity(this.options.opacity);
 if (this.options.zIndex)
   this.setZIndex(this.options.zIndex)

 if (this.options.destroyOnClose)
   this.setDestroyOnClose(true);

 this._getWindowBorderSize();
 this.width = this.options.width;
 this.height = this.options.height;
 this.visible = false;
 
 this.constraint = false;
 this.constraintPad = {top: 0, left:0, bottom:0, right:0};
 
 if (this.width && this.height)
   this.setSize(this.options.width, this.options.height);
 this.setTitle(this.options.title)
 Windows.register(this);      
},

// Destructor
destroy: function() {
 this._notify("onDestroy");
 Event.stopObserving(this.topbar, "mousedown", this.eventMouseDown);
 Event.stopObserving(this.bottombar, "mousedown", this.eventMouseDown);
 Event.stopObserving(this.content, "mousedown", this.eventMouseDownContent);
 
 Event.stopObserving(window, "load", this.eventOnLoad);
 Event.stopObserving(window, "resize", this.eventResize);
 Event.stopObserving(window, "scroll", this.eventResize);
 
 Event.stopObserving(this.content, "load", this.options.onload);

 if (this._oldParent) {
   var content = this.getContent();
   var originalContent = null;
   for(var i = 0; i < content.childNodes.length; i++) {
     originalContent = content.childNodes[i];
     if (originalContent.nodeType == 1) 
       break;
     originalContent = null;
   }
   if (originalContent)
     this._oldParent.appendChild(originalContent);
   this._oldParent = null;
 }

 if (this.sizer)
     Event.stopObserving(this.sizer, "mousedown", this.eventMouseDown);

 if (this.options.url) 
   this.content.src = null

  if(this.iefix) 
   Element.remove(this.iefix);

 Element.remove(this.element);
 Windows.unregister(this);      
},
 
// Sets close callback, if it sets, it should return true to be able to close the window.
setCloseCallback: function(callback) {
 this.options.closeCallback = callback;
},

// Gets window content
getContent: function () {
 return this.content;
},

// Sets the content with an element id
setContent: function(id, autoresize, autoposition) {
 var element = $(id);
 if (null == element) throw "Unable to find element '" + id + "' in DOM";
 this._oldParent = element.parentNode;

 var d = null;
 var p = null;

 if (autoresize) 
   d = Element.getDimensions(element);
 if (autoposition) 
   p = Position.cumulativeOffset(element);

 var content = this.getContent();
 // Clear HTML (and even iframe)
 this.setHTMLContent("");
 content = this.getContent();
 
 content.appendChild(element);
 element.show();
 if (autoresize) 
   this.setSize(d.width, d.height);
 if (autoposition) 
   this.setLocation(p[1] - this.heightN, p[0] - this.widthW);    
},

setHTMLContent: function(html) {
 // It was an url (iframe), recreate a div content instead of iframe content
 if (this.options.url) {
   this.content.src = null;
   this.options.url = null;
   
	  var content ="<div id=\"" + this.getId() + "_content\" class=\"" + this.options.className + "_content\"> </div>";
   $(this.getId() +"_table_content").innerHTML = content;
   
   this.content = $(this.element.id + "_content");
 }
   
 this.getContent().innerHTML = html;
},

setAjaxContent: function(url, options, showCentered, showModal) {
 this.showFunction = showCentered ? "showCenter" : "show";
 this.showModal = showModal || false;

 options = options || {};

 // Clear HTML (and even iframe)
 this.setHTMLContent("");

 this.onComplete = options.onComplete;
 if (! this._onCompleteHandler)
   this._onCompleteHandler = this._setAjaxContent.bind(this);
 options.onComplete = this._onCompleteHandler;

 new Ajax.Request(url, options);    
 options.onComplete = this.onComplete;
},

_setAjaxContent: function(originalRequest) {
 Element.update(this.getContent(), originalRequest.responseText);
 if (this.onComplete)
   this.onComplete(originalRequest);
 this.onComplete = null;
 this[this.showFunction](this.showModal)
},

setURL: function(url) {
 // Not an url content, change div to iframe
 if (this.options.url) 
   this.content.src = null;
 this.options.url = url;
 var content= "<iframe frameborder='0' name='" + this.getId() + "_content'  id='" + this.getId() + "_content' src='" + url + "' width='" + this.width + "' height='" + this.height + "'> </iframe>";
 $(this.getId() +"_table_content").innerHTML = content;
 
 this.content = $(this.element.id + "_content");
},

getURL: function() {
	return this.options.url ? this.options.url : null;
},

refresh: function() {
 if (this.options.url)
	    $(this.element.getAttribute('id') + '_content').src = this.options.url;
},

// Stores position/size in a cookie, by default named with window id
setCookie: function(name, expires, path, domain, secure) {
 name = name || this.element.id;
 this.cookie = [name, expires, path, domain, secure];
 
 // Get cookie
 var value = WindowUtilities.getCookie(name)
 // If exists
 if (value) {
   var values = value.split(',');
   var x = values[0].split(':');
   var y = values[1].split(':');

   var w = parseFloat(values[2]), h = parseFloat(values[3]);
   var mini = values[4];
   var maxi = values[5];

   this.setSize(w, h);
   if (mini == "true")
     this.doMinimize = true; // Minimize will be done at onload window event
   else if (maxi == "true")
     this.doMaximize = true; // Maximize will be done at onload window event

   this.useLeft = x[0] == "l";
   this.useTop = y[0] == "t";

   this.element.setStyle(this.useLeft ? {left: x[1]} : {right: x[1]});
   this.element.setStyle(this.useTop ? {top: y[1]} : {bottom: y[1]});
 }
},

// Gets window ID
getId: function() {
 return this.element.id;
},

// Detroys itself when closing 
setDestroyOnClose: function() {
 this.options.destroyOnClose = true;
},

setConstraint: function(bool, padding) {
 this.constraint = bool;
 this.constraintPad = Object.extend(this.constraintPad, padding || {});
 // Reset location to apply constraint
 if (this.useTop && this.useLeft)
   this.setLocation(parseFloat(this.element.style.top), parseFloat(this.element.style.left));
},

// initDrag event

_initDrag: function(event) {
 // No resize on minimized window
 if (Event.element(event) == this.sizer && this.isMinimized())
   return;

 // No move on maximzed window
 if (Event.element(event) != this.sizer && this.isMaximized())
   return;
   
 if (Prototype.Browser.IE && this.heightN == 0)
   this._getWindowBorderSize();
 
 // Get pointer X,Y
 this.pointer = [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)];
 if (this.options.wiredDrag) 
   this.currentDrag = this._createWiredElement();
 else
   this.currentDrag = this.element;
   
 // Resize
 if (Event.element(event) == this.sizer) {
   this.doResize = true;
   this.widthOrg = this.width;
   this.heightOrg = this.height;
   this.bottomOrg = parseFloat(this.element.getStyle('bottom'));
   this.rightOrg = parseFloat(this.element.getStyle('right'));
   this._notify("onStartResize");
 }
 else {
   this.doResize = false;

   // Check if click on close button, 
   var closeButton = $(this.getId() + '_close');
   if (closeButton && Position.within(closeButton, this.pointer[0], this.pointer[1])) {
     this.currentDrag = null;
     return;
   }

   this.toFront();

   if (! this.options.draggable) 
     return;
   this._notify("onStartMove");
 }    
 // Register global event to capture mouseUp and mouseMove
 Event.observe(document, "mouseup", this.eventMouseUp, false);
 Event.observe(document, "mousemove", this.eventMouseMove, false);
 
 // Add an invisible div to keep catching mouse event over iframes
 WindowUtilities.disableScreen('__invisible__', '__invisible__', this.overlayOpacity);

 // Stop selection while dragging
 document.body.ondrag = function () { return false; };
 document.body.onselectstart = function () { return false; };
 
 this.currentDrag.show();
 Event.stop(event);
},

_round: function(val, round) {
 return round == 1 ? val  : val = Math.floor(val / round) * round;
},

// updateDrag event
_updateDrag: function(event) {
 var pointer =  [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)];  
 var dx = pointer[0] - this.pointer[0];
 var dy = pointer[1] - this.pointer[1];
 
 // Resize case, update width/height
 if (this.doResize) {
   var w = this.widthOrg + dx;
   var h = this.heightOrg + dy;
   
   dx = this.width - this.widthOrg
   dy = this.height - this.heightOrg
   
   // Check if it's a right position, update it to keep upper-left corner at the same position
   if (this.useLeft) 
     w = this._updateWidthConstraint(w)
   else 
     this.currentDrag.setStyle({right: (this.rightOrg -dx) + 'px'});
   // Check if it's a bottom position, update it to keep upper-left corner at the same position
   if (this.useTop) 
     h = this._updateHeightConstraint(h)
   else
     this.currentDrag.setStyle({bottom: (this.bottomOrg -dy) + 'px'});
     
   this.setSize(w , h);
   this._notify("onResize");
 }
 // Move case, update top/left
 else {
   this.pointer = pointer;
   
   if (this.useLeft) {
     var left =  parseFloat(this.currentDrag.getStyle('left')) + dx;
     var newLeft = this._updateLeftConstraint(left);
     // Keep mouse pointer correct
     this.pointer[0] += newLeft-left;
     this.currentDrag.setStyle({left: newLeft + 'px'});
   }
   else 
     this.currentDrag.setStyle({right: parseFloat(this.currentDrag.getStyle('right')) - dx + 'px'});
   
   if (this.useTop) {
     var top =  parseFloat(this.currentDrag.getStyle('top')) + dy;
     var newTop = this._updateTopConstraint(top);
     // Keep mouse pointer correct
     this.pointer[1] += newTop - top;
     this.currentDrag.setStyle({top: newTop + 'px'});
   }
   else 
     this.currentDrag.setStyle({bottom: parseFloat(this.currentDrag.getStyle('bottom')) - dy + 'px'});

   this._notify("onMove");
 }
 if (this.iefix) 
   this._fixIEOverlapping(); 
   
 this._removeStoreLocation();
 Event.stop(event);
},

// endDrag callback
_endDrag: function(event) {
 // Remove temporary div over iframes
  WindowUtilities.enableScreen('__invisible__');
 
 if (this.doResize)
   this._notify("onEndResize");
 else
   this._notify("onEndMove");
 
 // Release event observing
 Event.stopObserving(document, "mouseup", this.eventMouseUp,false);
 Event.stopObserving(document, "mousemove", this.eventMouseMove, false);

 Event.stop(event);
 
 this._hideWiredElement();

 // Store new location/size if need be
 this._saveCookie()
   
 // Restore selection
 document.body.ondrag = null;
 document.body.onselectstart = null;
},

_updateLeftConstraint: function(left) {
 if (this.constraint && this.useLeft && this.useTop) {
   var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;

   if (left < this.constraintPad.left)
     left = this.constraintPad.left;
   if (left + this.width + this.widthE + this.widthW > width - this.constraintPad.right) 
     left = width - this.constraintPad.right - this.width - this.widthE - this.widthW;
 }
 return left;
},

_updateTopConstraint: function(top) {
 if (this.constraint && this.useLeft && this.useTop) {        
   var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
   
   var h = this.height + this.heightN + this.heightS;

   if (top < this.constraintPad.top)
     top = this.constraintPad.top;
   if (top + h > height - this.constraintPad.bottom) 
     top = height - this.constraintPad.bottom - h;
 }
 return top;
},

_updateWidthConstraint: function(w) {
 if (this.constraint && this.useLeft && this.useTop) {
   var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;
   var left =  parseFloat(this.element.getStyle("left"));

   if (left + w + this.widthE + this.widthW > width - this.constraintPad.right) 
     w = width - this.constraintPad.right - left - this.widthE - this.widthW;
 }
 return w;
},

_updateHeightConstraint: function(h) {
 if (this.constraint && this.useLeft && this.useTop) {
   var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
   var top =  parseFloat(this.element.getStyle("top"));

   if (top + h + this.heightN + this.heightS > height - this.constraintPad.bottom) 
     h = height - this.constraintPad.bottom - top - this.heightN - this.heightS;
 }
 return h;
},


// Creates HTML window code
_createWindow: function(id) {
 var className = this.options.className;
 var win = document.createElement("div");
 win.setAttribute('id', id);
 win.className = "dialog";

 var content;
 if (this.options.url)
   content= "<iframe frameborder=\"0\" name=\"" + id + "_content\"  id=\"" + id + "_content\" src=\"" + this.options.url + "\"> </iframe>";
 else
   content ="<div id=\"" + id + "_content\" class=\"" +className + "_content\"> </div>";

 var closeDiv = this.options.closable ? "<div class='"+ className +"_close' id='"+ id +"_close' onclick='Windows.close(\""+ id +"\", event)'> </div>" : "";
 var minDiv = this.options.minimizable ? "<div class='"+ className + "_minimize' id='"+ id +"_minimize' onclick='Windows.minimize(\""+ id +"\", event)'> </div>" : "";
 var maxDiv = this.options.maximizable ? "<div class='"+ className + "_maximize' id='"+ id +"_maximize' onclick='Windows.maximize(\""+ id +"\", event)'> </div>" : "";
 var seAttributes = this.options.resizable ? "class='" + className + "_sizer' id='" + id + "_sizer'" : "class='"  + className + "_se'";
 var blank = "../themes/default/blank.gif";
 
 win.innerHTML = closeDiv + minDiv + maxDiv + "\
   <table id='"+ id +"_row1' class=\"top table_window\">\
     <tr>\
       <td class='"+ className +"_nw'></td>\
       <td class='"+ className +"_n'><div id='"+ id +"_top' class='"+ className +"_title title_window'>"+ this.options.title +"</div></td>\
       <td class='"+ className +"_ne'></td>\
     </tr>\
   </table>\
   <table id='"+ id +"_row2' class=\"mid table_window\">\
     <tr>\
       <td class='"+ className +"_w'></td>\
         <td id='"+ id +"_table_content' class='"+ className +"_content' valign='top'>" + content + "</td>\
       <td class='"+ className +"_e'></td>\
     </tr>\
   </table>\
     <table id='"+ id +"_row3' class=\"bot table_window\">\
     <tr>\
       <td class='"+ className +"_sw'></td>\
         <td class='"+ className +"_s'><div id='"+ id +"_bottom' class='status_bar'><span style='float:left; width:1px; height:1px'></span></div></td>\
         <td " + seAttributes + "></td>\
     </tr>\
   </table>\
 ";
 Element.hide(win);
 this.options.parent.insertBefore(win, this.options.parent.firstChild);
 Event.observe($(id + "_content"), "load", this.options.onload);
 return win;
},


changeClassName: function(newClassName) {    
 var className = this.options.className;
 var id = this.getId();
 $A(["_close", "_minimize", "_maximize", "_sizer", "_content"]).each(function(value) { this._toggleClassName($(id + value), className + value, newClassName + value) }.bind(this));
 this._toggleClassName($(id + "_top"), className + "_title", newClassName + "_title");
 $$("#" + id + " td").each(function(td) {td.className = td.className.sub(className,newClassName); });
 this.options.className = newClassName;
},

_toggleClassName: function(element, oldClassName, newClassName) { 
 if (element) {
   element.removeClassName(oldClassName);
   element.addClassName(newClassName);
 }
},

// Sets window location
setLocation: function(top, left) {
 top = this._updateTopConstraint(top);
 left = this._updateLeftConstraint(left);

 var e = this.currentDrag || this.element;
 e.setStyle({top: top + 'px'});
 e.setStyle({left: left + 'px'});

 this.useLeft = true;
 this.useTop = true;
},
 
getLocation: function() {
 var location = {};
 if (this.useTop)
   location = Object.extend(location, {top: this.element.getStyle("top")});
 else
   location = Object.extend(location, {bottom: this.element.getStyle("bottom")});
 if (this.useLeft)
   location = Object.extend(location, {left: this.element.getStyle("left")});
 else
   location = Object.extend(location, {right: this.element.getStyle("right")});
 
 return location;
},

// Gets window size
getSize: function() {
 return {width: this.width, height: this.height};
},
 
// Sets window size
setSize: function(width, height, useEffect) {    
 width = parseFloat(width);
 height = parseFloat(height);
 
 // Check min and max size
 if (!this.minimized && width < this.options.minWidth)
   width = this.options.minWidth;

 if (!this.minimized && height < this.options.minHeight)
   height = this.options.minHeight;
   
 if (this.options. maxHeight && height > this.options. maxHeight)
   height = this.options. maxHeight;

 if (this.options. maxWidth && width > this.options. maxWidth)
   width = this.options. maxWidth;

 
 if (this.useTop && this.useLeft && Window.hasEffectLib && Effect.ResizeWindow && useEffect) {
   new Effect.ResizeWindow(this, null, null, width, height, {duration: Window.resizeEffectDuration});
 } else {
   this.width = width;
   this.height = height;
   var e = this.currentDrag ? this.currentDrag : this.element;

   e.setStyle({width: width + this.widthW + this.widthE + "px"})
   e.setStyle({height: height  + this.heightN + this.heightS + "px"})

   // Update content size
   if (!this.currentDrag || this.currentDrag == this.element) {
     var content = $(this.element.id + '_content');
     content.setStyle({height: height  + 'px'});
     content.setStyle({width: width  + 'px'});
   }
 }
},

updateHeight: function() {
 this.setSize(this.width, this.content.scrollHeight, true);
},

updateWidth: function() {
 this.setSize(this.content.scrollWidth, this.height, true);
},

// Brings window to front
toFront: function() {
 if (this.element.style.zIndex < Windows.maxZIndex)  
   this.setZIndex(Windows.maxZIndex + 1);
 if (this.iefix) 
   this._fixIEOverlapping(); 
},

getBounds: function(insideOnly) {
 if (! this.width || !this.height || !this.visible)  
   this.computeBounds();
 var w = this.width;
 var h = this.height;

 if (!insideOnly) {
   w += this.widthW + this.widthE;
   h += this.heightN + this.heightS;
 }
 var bounds = Object.extend(this.getLocation(), {width: w + "px", height: h + "px"});
 return bounds;
},
   
computeBounds: function() {
  if (! this.width || !this.height) {
   var size = WindowUtilities._computeSize(this.content.innerHTML, this.content.id, this.width, this.height, 0, this.options.className)
   if (this.height)
     this.width = size + 5
   else
     this.height = size + 5
 }

 this.setSize(this.width, this.height);
 if (this.centered)
   this._center(this.centerTop, this.centerLeft);    
},

// Displays window modal state or not
show: function(modal) {
 this.visible = true;
 if (modal) {
   // Hack for Safari !!
   if (typeof this.overlayOpacity == "undefined") {
     var that = this;
     setTimeout(function() {that.show(modal)}, 10);
     return;
   }
   Windows.addModalWindow(this);
   
   this.modal = true;      
   this.setZIndex(Windows.maxZIndex + 1);
   Windows.unsetOverflow(this);
 }
 else    
   if (!this.element.style.zIndex) 
     this.setZIndex(Windows.maxZIndex + 1);        
   
 // To restore overflow if need be
 if (this.oldStyle)
   this.getContent().setStyle({overflow: this.oldStyle});
   
 this.computeBounds();
 
 this._notify("onBeforeShow");   
 if (this.options.showEffect != Element.show && this.options.showEffectOptions)
   this.options.showEffect(this.element, this.options.showEffectOptions);  
 else
   this.options.showEffect(this.element);  
   
 this._checkIEOverlapping();
 WindowUtilities.focusedWindow = this
 this._notify("onShow");   
},

// Displays window modal state or not at the center of the page
showCenter: function(modal, top, left) {
 this.centered = true;
 this.centerTop = top;
 this.centerLeft = left;

 this.show(modal);
},

isVisible: function() {
 return this.visible;
},

_center: function(top, left) {    
 var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);    
 var pageSize = WindowUtilities.getPageSize(this.options.parent);    
 if (typeof top == "undefined")
   top = (pageSize.windowHeight - (this.height + this.heightN + this.heightS))/2;
 top += windowScroll.top
 
 if (typeof left == "undefined")
   left = (pageSize.windowWidth - (this.width + this.widthW + this.widthE))/2;
 left += windowScroll.left      
 this.setLocation(top, left);
 this.toFront();
},

_recenter: function(event) {     
 if (this.centered) {
   var pageSize = WindowUtilities.getPageSize(this.options.parent);
   var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);    

   // Check for this stupid IE that sends dumb events
   if (this.pageSize && this.pageSize.windowWidth == pageSize.windowWidth && this.pageSize.windowHeight == pageSize.windowHeight && 
       this.windowScroll.left == windowScroll.left && this.windowScroll.top == windowScroll.top) 
     return;
   this.pageSize = pageSize;
   this.windowScroll = windowScroll;
   // set height of Overlay to take up whole page and show
   if ($('overlay_modal')) 
     $('overlay_modal').setStyle({height: (pageSize.pageHeight + 'px')});
   
   if (this.options.recenterAuto)
     this._center(this.centerTop, this.centerLeft);    
 }
},

// Hides window
hide: function() {
 this.visible = false;
 if (this.modal) {
   Windows.removeModalWindow(this);
   Windows.resetOverflow();
 }
 // To avoid bug on scrolling bar
 this.oldStyle = this.getContent().getStyle('overflow') || "auto"
 this.getContent().setStyle({overflow: "hidden"});

 this.options.hideEffect(this.element, this.options.hideEffectOptions);  

  if(this.iefix) 
   this.iefix.hide();

 if (!this.doNotNotifyHide)
   this._notify("onHide");
},

close: function() {
 // Asks closeCallback if exists
 if (this.visible) {
   if (this.options.closeCallback && ! this.options.closeCallback(this)) 
     return;

   if (this.options.destroyOnClose) {
     var destroyFunc = this.destroy.bind(this);
     if (this.options.hideEffectOptions.afterFinish) {
       var func = this.options.hideEffectOptions.afterFinish;
       this.options.hideEffectOptions.afterFinish = function() {func();destroyFunc() }
     }
     else 
       this.options.hideEffectOptions.afterFinish = function() {destroyFunc() }
   }
   Windows.updateFocusedWindow();
   
   this.doNotNotifyHide = true;
   this.hide();
   this.doNotNotifyHide = false;
   this._notify("onClose");
 }
},

minimize: function() {
 if (this.resizing)
   return;
 
 var r2 = $(this.getId() + "_row2");
 
 if (!this.minimized) {
   this.minimized = true;

   var dh = r2.getDimensions().height;
   this.r2Height = dh;
   var h  = this.element.getHeight() - dh;

   if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
     new Effect.ResizeWindow(this, null, null, null, this.height -dh, {duration: Window.resizeEffectDuration});
   } else  {
     this.height -= dh;
     this.element.setStyle({height: h + "px"});
     r2.hide();
   }

   if (! this.useTop) {
     var bottom = parseFloat(this.element.getStyle('bottom'));
     this.element.setStyle({bottom: (bottom + dh) + 'px'});
   }
 } 
 else {      
   this.minimized = false;
   
   var dh = this.r2Height;
   this.r2Height = null;
   if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
     new Effect.ResizeWindow(this, null, null, null, this.height + dh, {duration: Window.resizeEffectDuration});
   }
   else {
     var h  = this.element.getHeight() + dh;
     this.height += dh;
     this.element.setStyle({height: h + "px"})
     r2.show();
   }
   if (! this.useTop) {
     var bottom = parseFloat(this.element.getStyle('bottom'));
     this.element.setStyle({bottom: (bottom - dh) + 'px'});
   }
   this.toFront();
 }
 this._notify("onMinimize");
 
 // Store new location/size if need be
 this._saveCookie()
},

maximize: function() {
 if (this.isMinimized() || this.resizing)
   return;

 if (Prototype.Browser.IE && this.heightN == 0)
   this._getWindowBorderSize();
   
 if (this.storedLocation != null) {
   this._restoreLocation();
   if(this.iefix) 
     this.iefix.hide();
 }
 else {
   this._storeLocation();
   Windows.unsetOverflow(this);
   
   var windowScroll = WindowUtilities.getWindowScroll(this.options.parent);
   var pageSize = WindowUtilities.getPageSize(this.options.parent);    
   var left = windowScroll.left;
   var top = windowScroll.top;
   
   if (this.options.parent != document.body) {
     windowScroll =  {top:0, left:0, bottom:0, right:0};
     var dim = this.options.parent.getDimensions();
     pageSize.windowWidth = dim.width;
     pageSize.windowHeight = dim.height;
     top = 0; 
     left = 0;
   }
   
   if (this.constraint) {
     pageSize.windowWidth -= Math.max(0, this.constraintPad.left) + Math.max(0, this.constraintPad.right);
     pageSize.windowHeight -= Math.max(0, this.constraintPad.top) + Math.max(0, this.constraintPad.bottom);
     left +=  Math.max(0, this.constraintPad.left);
     top +=  Math.max(0, this.constraintPad.top);
   }
   
   var width = pageSize.windowWidth - this.widthW - this.widthE;
   var height= pageSize.windowHeight - this.heightN - this.heightS;

   if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) {
     new Effect.ResizeWindow(this, top, left, width, height, {duration: Window.resizeEffectDuration});
   }
   else {
     this.setSize(width, height);
     this.element.setStyle(this.useLeft ? {left: left} : {right: left});
     this.element.setStyle(this.useTop ? {top: top} : {bottom: top});
   }
     
   this.toFront();
   if (this.iefix) 
     this._fixIEOverlapping(); 
 }
 this._notify("onMaximize");

 // Store new location/size if need be
 this._saveCookie()
},

isMinimized: function() {
 return this.minimized;
},

isMaximized: function() {
 return (this.storedLocation != null);
},

setOpacity: function(opacity) {
 if (Element.setOpacity)
   Element.setOpacity(this.element, opacity);
},

setZIndex: function(zindex) {
 this.element.setStyle({zIndex: zindex});
 Windows.updateZindex(zindex, this);
},

setTitle: function(newTitle) {
 if (!newTitle || newTitle == "") 
   newTitle = "&nbsp;";
   
 Element.update(this.element.id + '_top', newTitle);
},

getTitle: function() {
 return $(this.element.id + '_top').innerHTML;
},

setStatusBar: function(element) {
 var statusBar = $(this.getId() + "_bottom");

 if (typeof(element) == "object") {
   if (this.bottombar.firstChild)
     this.bottombar.replaceChild(element, this.bottombar.firstChild);
   else
     this.bottombar.appendChild(element);
 }
 else
   this.bottombar.innerHTML = element;
},

_checkIEOverlapping: function() {
 //if(!this.iefix && (navigator.appVersion.indexOf('MSIE')>0) && (navigator.userAgent.indexOf('Opera')<0) && (this.element.getStyle('position')=='absolute')) {
   if(!this.iefix && (Prototype.Browser.IE) && this.element.getStyle('position') == 'absolute' && this.element.id == 'overlay_modal') {
     new Insertion.After(this.element.id, '<iframe id="' + this.element.id + '_iefix" '+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' + 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
     this.iefix = $(this.element.id+'_iefix');
 }
 if(this.iefix) 
   setTimeout(this._fixIEOverlapping.bind(this), 50);
},

_fixIEOverlapping: function() {
   Position.clone(this.element, this.iefix);
   this.iefix.style.zIndex = this.element.style.zIndex - 1;
   this.iefix.show();
},

_getWindowBorderSize: function(event) {
 // Hack to get real window border size!!
 var div = this._createHiddenDiv(this.options.className + "_n")
 this.heightN = Element.getDimensions(div).height;    
 div.parentNode.removeChild(div)

 var div = this._createHiddenDiv(this.options.className + "_s")
 this.heightS = Element.getDimensions(div).height;    
 div.parentNode.removeChild(div)

 var div = this._createHiddenDiv(this.options.className + "_e")
 this.widthE = Element.getDimensions(div).width;    
 div.parentNode.removeChild(div)

 var div = this._createHiddenDiv(this.options.className + "_w")
 this.widthW = Element.getDimensions(div).width;
 div.parentNode.removeChild(div);
 
 var div = document.createElement("div");
 div.className = "overlay_" + this.options.className ;
 document.body.appendChild(div);
 //alert("no timeout:\nopacity: " + div.getStyle("opacity") + "\nwidth: " + document.defaultView.getComputedStyle(div, null).width);
 var that = this;
 
 // Workaround for Safari!!
 setTimeout(function() {that.overlayOpacity = ($(div).getStyle("opacity")); div.parentNode.removeChild(div);}, 10);
 
 // Workaround for IE!!
 if (Prototype.Browser.IE) {
   this.heightS = $(this.getId() +"_row3").getDimensions().height;
   this.heightN = $(this.getId() +"_row1").getDimensions().height;
 }

 // Safari size fix
 if (Prototype.Browser.WebKit && Prototype.Browser.WebKitVersion < 420)
   this.setSize(this.width, this.height);
 if (this.doMaximize)
   this.maximize();
 if (this.doMinimize)
   this.minimize();
},

_createHiddenDiv: function(className) {
 var objBody = document.body;
 var win = document.createElement("div");
 win.setAttribute('id', this.element.id+ "_tmp");
 win.className = className;
 win.style.display = 'none';
 win.innerHTML = '';
 objBody.insertBefore(win, objBody.firstChild);
 return win;
},

_storeLocation: function() {
 if (this.storedLocation == null) {
   this.storedLocation = {useTop: this.useTop, useLeft: this.useLeft, 
                          top: this.element.getStyle('top'), bottom: this.element.getStyle('bottom'),
                          left: this.element.getStyle('left'), right: this.element.getStyle('right'),
                          width: this.width, height: this.height };
 }
},

_restoreLocation: function() {
 if (this.storedLocation != null) {
   this.useLeft = this.storedLocation.useLeft;
   this.useTop = this.storedLocation.useTop;
   
   if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow)
     new Effect.ResizeWindow(this, this.storedLocation.top, this.storedLocation.left, this.storedLocation.width, this.storedLocation.height, {duration: Window.resizeEffectDuration});
   else {
     this.element.setStyle(this.useLeft ? {left: this.storedLocation.left} : {right: this.storedLocation.right});
     this.element.setStyle(this.useTop ? {top: this.storedLocation.top} : {bottom: this.storedLocation.bottom});
     this.setSize(this.storedLocation.width, this.storedLocation.height);
   }
   
   Windows.resetOverflow();
   this._removeStoreLocation();
 }
},

_removeStoreLocation: function() {
 this.storedLocation = null;
},

_saveCookie: function() {
 if (this.cookie) {
   var value = "";
   if (this.useLeft)
     value += "l:" +  (this.storedLocation ? this.storedLocation.left : this.element.getStyle('left'))
   else
     value += "r:" + (this.storedLocation ? this.storedLocation.right : this.element.getStyle('right'))
   if (this.useTop)
     value += ",t:" + (this.storedLocation ? this.storedLocation.top : this.element.getStyle('top'))
   else
     value += ",b:" + (this.storedLocation ? this.storedLocation.bottom :this.element.getStyle('bottom'))
     
   value += "," + (this.storedLocation ? this.storedLocation.width : this.width);
   value += "," + (this.storedLocation ? this.storedLocation.height : this.height);
   value += "," + this.isMinimized();
   value += "," + this.isMaximized();
   WindowUtilities.setCookie(value, this.cookie)
 }
},

_createWiredElement: function() {
 if (! this.wiredElement) {
   if (Prototype.Browser.IE)
     this._getWindowBorderSize();
   var div = document.createElement("div");
   div.className = "wired_frame " + this.options.className + "_wired_frame";
   
   div.style.position = 'absolute';
   this.options.parent.insertBefore(div, this.options.parent.firstChild);
   this.wiredElement = $(div);
 }
 if (this.useLeft) 
   this.wiredElement.setStyle({left: this.element.getStyle('left')});
 else 
   this.wiredElement.setStyle({right: this.element.getStyle('right')});
   
 if (this.useTop) 
   this.wiredElement.setStyle({top: this.element.getStyle('top')});
 else 
   this.wiredElement.setStyle({bottom: this.element.getStyle('bottom')});

 var dim = this.element.getDimensions();
 this.wiredElement.setStyle({width: dim.width + "px", height: dim.height +"px"});

 this.wiredElement.setStyle({zIndex: Windows.maxZIndex+30});
 return this.wiredElement;
},

_hideWiredElement: function() {
 if (! this.wiredElement || ! this.currentDrag)
   return;
 if (this.currentDrag == this.element) 
   this.currentDrag = null;
 else {
   if (this.useLeft) 
     this.element.setStyle({left: this.currentDrag.getStyle('left')});
   else 
     this.element.setStyle({right: this.currentDrag.getStyle('right')});

   if (this.useTop) 
     this.element.setStyle({top: this.currentDrag.getStyle('top')});
   else 
     this.element.setStyle({bottom: this.currentDrag.getStyle('bottom')});

   this.currentDrag.hide();
   this.currentDrag = null;
   if (this.doResize)
     this.setSize(this.width, this.height);
 } 
},

_notify: function(eventName) {
 if (this.options[eventName])
   this.options[eventName](this);
 else
   Windows.notify(eventName, this);
}
};

//Windows containers, register all page windows
var Windows = {
windows: [],
modalWindows: [],
observers: [],
focusedWindow: null,
maxZIndex: 0,
overlayShowEffectOptions: {duration: 0.1},
overlayHideEffectOptions: {duration: 0.1},

addObserver: function(observer) {
 this.removeObserver(observer);
 this.observers.push(observer);
},

removeObserver: function(observer) {  
 this.observers = this.observers.reject( function(o) { return o==observer });
},

// onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose
notify: function(eventName, win) {  
 this.observers.each( function(o) {if(o[eventName]) o[eventName](eventName, win);});
},

// Gets window from its id
getWindow: function(id) {
 return this.windows.detect(function(d) { return d.getId() ==id });
},

// Gets the last focused window
getFocusedWindow: function() {
 return this.focusedWindow;
},

updateFocusedWindow: function() {
 this.focusedWindow = this.windows.length >=2 ? this.windows[this.windows.length-2] : null;    
},

// Registers a new window (called by Windows constructor)
register: function(win) {
 this.windows.push(win);
},
 
// Add a modal window in the stack
addModalWindow: function(win) {
 // Disable screen if first modal window
 if (this.modalWindows.length == 0) {
   WindowUtilities.disableScreen(win.options.className, 'overlay_modal', win.overlayOpacity, win.getId(), win.options.parent);
 }
 else {
   // Move overlay over all windows
   if (Window.keepMultiModalWindow) {
     $('overlay_modal').style.zIndex = Windows.maxZIndex + 1;
     Windows.maxZIndex += 1;
     WindowUtilities._hideSelect(this.modalWindows.last().getId());
   }
   // Hide current modal window
   else
     this.modalWindows.last().element.hide();
   // Fucking IE select issue
   WindowUtilities._showSelect(win.getId());
 }      
 this.modalWindows.push(win);    
},

removeModalWindow: function(win) {
 this.modalWindows.pop();
 
 // No more modal windows
 if (this.modalWindows.length == 0)
   WindowUtilities.enableScreen();     
 else {
   if (Window.keepMultiModalWindow) {
     this.modalWindows.last().toFront();
     WindowUtilities._showSelect(this.modalWindows.last().getId());        
   }
   else
     this.modalWindows.last().element.show();
 }
},

// Registers a new window (called by Windows constructor)
register: function(win) {
 this.windows.push(win);
},

// Unregisters a window (called by Windows destructor)
unregister: function(win) {
 this.windows = this.windows.reject(function(d) { return d==win });
}, 

// Closes all windows
closeAll: function() {  
 this.windows.each( function(w) {Windows.close(w.getId())} );
},

closeAllModalWindows: function() {
 WindowUtilities.enableScreen();     
 this.modalWindows.each( function(win) {if (win) win.close()});    
},

// Minimizes a window with its id
minimize: function(id, event) {
 var win = this.getWindow(id)
 if (win && win.visible)
   win.minimize();
 Event.stop(event);
},

// Maximizes a window with its id
maximize: function(id, event) {
 var win = this.getWindow(id)
 if (win && win.visible)
   win.maximize();
 Event.stop(event);
},

// Closes a window with its id
close: function(id, event) {
 var win = this.getWindow(id);
 if (win) 
   win.close();
 if (event)
   Event.stop(event);
},

blur: function(id) {
 var win = this.getWindow(id);  
 if (!win)
   return;
 if (win.options.blurClassName)
   win.changeClassName(win.options.blurClassName);
 if (this.focusedWindow == win)  
   this.focusedWindow = null;
 win._notify("onBlur");  
},

focus: function(id) {
 var win = this.getWindow(id);  
 if (!win)
   return;       
 if (this.focusedWindow)
   this.blur(this.focusedWindow.getId())

 if (win.options.focusClassName)
   win.changeClassName(win.options.focusClassName);  
 this.focusedWindow = win;
 win._notify("onFocus");
},

unsetOverflow: function(except) {    
 this.windows.each(function(d) { d.oldOverflow = d.getContent().getStyle("overflow") || "auto" ; d.getContent().setStyle({overflow: "hidden"}) });
 if (except && except.oldOverflow)
   except.getContent().setStyle({overflow: except.oldOverflow});
},

resetOverflow: function() {
 this.windows.each(function(d) { if (d.oldOverflow) d.getContent().setStyle({overflow: d.oldOverflow}) });
},

updateZindex: function(zindex, win) { 
 if (zindex > this.maxZIndex) {   
   this.maxZIndex = zindex;    
   if (this.focusedWindow) 
     this.blur(this.focusedWindow.getId())
 }
 this.focusedWindow = win;
 if (this.focusedWindow) 
   this.focus(this.focusedWindow.getId())
}
};

var Dialog = {
dialogId: null,
onCompleteFunc: null,
callFunc: null, 
parameters: null, 
 
confirm: function(content, parameters) {
 // Get Ajax return before
 if (content && typeof content != "string") {
   Dialog._runAjaxRequest(content, parameters, Dialog.confirm);
   return 
 }
 content = content || "";
 
 parameters = parameters || {};
 var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";
 var cancelLabel = parameters.cancelLabel ? parameters.cancelLabel : "Cancel";

 // Backward compatibility
 parameters = Object.extend(parameters, parameters.windowParameters || {});
 parameters.windowParameters = parameters.windowParameters || {};

 parameters.className = parameters.className || "alert";

 var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
 var cancelButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " cancel_button'" 
 var content = "\
   <div class='_message'>" + content  + "</div>\
     <div class='" + parameters.className + "_buttons'>\
       <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
       <input type='button' value='" + cancelLabel + "' onclick='Dialog.cancelCallback()' " + cancelButtonClass + "/>\
     </div>\
 ";
 return this._openDialog(content, parameters)
},

alert: function(content, parameters) {
 // Get Ajax return before
 if (content && typeof content != "string") {
   Dialog._runAjaxRequest(content, parameters, Dialog.alert);
   return 
 }
 content = content || "";
 
 parameters = parameters || {};
 var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";

 // Backward compatibility    
 parameters = Object.extend(parameters, parameters.windowParameters || {});
 parameters.windowParameters = parameters.windowParameters || {};
 
 parameters.className = parameters.className || "alert";
 
 var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
 var content = "\
   <div class='" + parameters.className + "_message'>" + content  + "</div>\
     <div class='" + parameters.className + "_buttons'>\
       <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
     </div>";                  
 return this._openDialog(content, parameters)
},

info: function(content, parameters) {   
 // Get Ajax return before
 if (content && typeof content != "string") {
   Dialog._runAjaxRequest(content, parameters, Dialog.info);
   return 
 }
 content = content || "";
  
 // Backward compatibility
 parameters = parameters || {};
 parameters = Object.extend(parameters, parameters.windowParameters || {});
 parameters.windowParameters = parameters.windowParameters || {};
 
 parameters.className = parameters.className || "alert";
 
 var content = "<div id='modal_dialog_message' class='" + parameters.className + "_message'>" + content  + "</div>";
 if (parameters.showProgress)
   content += "<div id='modal_dialog_progress' class='" + parameters.className + "_progress'>  </div>";

 parameters.ok = null;
 parameters.cancel = null;
 
 return this._openDialog(content, parameters)
},

setInfoMessage: function(message) {
 $('modal_dialog_message').update(message);
},

closeInfo: function() {
 Windows.close(this.dialogId);
},

_openDialog: function(content, parameters) {
 var className = parameters.className;
 
 if (! parameters.height && ! parameters.width) {
   parameters.width = WindowUtilities.getPageSize(parameters.options.parent || document.body).pageWidth / 2;
 }
 if (parameters.id)
   this.dialogId = parameters.id;
 else { 
   var t = new Date();
   this.dialogId = 'modal_dialog_' + t.getTime();
   parameters.id = this.dialogId;
 }

 // compute height or width if need be
 if (! parameters.height || ! parameters.width) {
   var size = WindowUtilities._computeSize(content, this.dialogId, parameters.width, parameters.height, 5, className)
   if (parameters.height)
     parameters.width = size + 5
   else
     parameters.height = size + 5
 }
 parameters.effectOptions = parameters.effectOptions ;
 parameters.resizable   = parameters.resizable || false;
 parameters.minimizable = parameters.minimizable || false;
 parameters.maximizable = parameters.maximizable ||  false;
 parameters.draggable   = parameters.draggable || false;
 parameters.closable    = parameters.closable || false;
 
 var win = new Window(parameters);
 win.getContent().innerHTML = content;
 
 win.showCenter(true, parameters.top, parameters.left);  
 win.setDestroyOnClose();
 
 win.cancelCallback = parameters.onCancel || parameters.cancel; 
 win.okCallback = parameters.onOk || parameters.ok;
 
 return win;    
},

_getAjaxContent: function(originalRequest)  {
   Dialog.callFunc(originalRequest.responseText, Dialog.parameters)
},

_runAjaxRequest: function(message, parameters, callFunc) {
 if (message.options == null)
   message.options = {}  
 Dialog.onCompleteFunc = message.options.onComplete;
 Dialog.parameters = parameters;
 Dialog.callFunc = callFunc;
 
 message.options.onComplete = Dialog._getAjaxContent;
 new Ajax.Request(message.url, message.options);
},

okCallback: function() {
 var win = Windows.focusedWindow;
 if (!win.okCallback || win.okCallback(win)) {
   // Remove onclick on button
   $$("#" + win.getId()+" input").each(function(element) {element.onclick=null;})
   win.close();
 }
},

cancelCallback: function() {
 var win = Windows.focusedWindow;
 // Remove onclick on button
 $$("#" + win.getId()+" input").each(function(element) {element.onclick=null})
 win.close();
 if (win.cancelCallback)
   win.cancelCallback(win);
}
}
/*
Based on Lightbox JS: Fullsize Image Overlays 
by Lokesh Dhakar - http://www.huddletogether.com

For more information on this script, visit:
http://huddletogether.com/projects/lightbox/

Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
(basically, do anything you want, just leave my name and link)
*/

if (Prototype.Browser.WebKit) {
var array = navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/));
Prototype.Browser.WebKitVersion = parseFloat(array[1]);
}

var WindowUtilities = {  
// From dragdrop.js
getWindowScroll: function(parent) {
 var T, L, W, H;
 parent = parent || document.body;              
 if (parent != document.body) {
   T = parent.scrollTop;
   L = parent.scrollLeft;
   W = parent.scrollWidth;
   H = parent.scrollHeight;
 } 
 else {
   var w = window;
   with (w.document) {
     if (w.document.documentElement && documentElement.scrollTop) {
       T = documentElement.scrollTop;
       L = documentElement.scrollLeft;
     } else if (w.document.body) {
       T = body.scrollTop;
       L = body.scrollLeft;
     }
     if (w.innerWidth) {
       W = w.innerWidth;
       H = w.innerHeight;
     } else if (w.document.documentElement && documentElement.clientWidth) {
       W = documentElement.clientWidth;
       H = documentElement.clientHeight;
     } else {
       W = body.offsetWidth;
       H = body.offsetHeight
     }
   }
 }
 return { top: T, left: L, width: W, height: H };
}, 
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
getPageSize: function(parent){
 parent = parent || document.body;              
 var windowWidth, windowHeight;
 var pageHeight, pageWidth;
 if (parent != document.body) {
   windowWidth = parent.getWidth();
   windowHeight = parent.getHeight();                                
   pageWidth = parent.scrollWidth;
   pageHeight = parent.scrollHeight;                                
 } 
 else {
   var xScroll, yScroll;

   if (window.innerHeight && window.scrollMaxY) {  
     xScroll = document.body.scrollWidth;
     yScroll = window.innerHeight + window.scrollMaxY;
   } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
     xScroll = document.body.scrollWidth;
     yScroll = document.body.scrollHeight;
   } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
     xScroll = document.body.offsetWidth;
     yScroll = document.body.offsetHeight;
   }


   if (self.innerHeight) {  // all except Explorer
     windowWidth = self.innerWidth;
     windowHeight = self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
     windowWidth = document.documentElement.clientWidth;
     windowHeight = document.documentElement.clientHeight;
   } else if (document.body) { // other Explorers
     windowWidth = document.body.clientWidth;
     windowHeight = document.body.clientHeight;
   }  

   // for small pages with total height less then height of the viewport
   if(yScroll < windowHeight){
     pageHeight = windowHeight;
   } else { 
     pageHeight = yScroll;
   }

   // for small pages with total width less then width of the viewport
   if(xScroll < windowWidth){  
     pageWidth = windowWidth;
   } else {
     pageWidth = xScroll;
   }
 }             
 return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
},

disableScreen: function(className, overlayId, overlayOpacity, contentId, parent) {
 WindowUtilities.initLightbox(overlayId, className, function() {this._disableScreen(className, overlayId, overlayOpacity, contentId)}.bind(this), parent || document.body);
},

_disableScreen: function(className, overlayId, overlayOpacity, contentId) {
 // prep objects
 var objOverlay = $(overlayId);

 var pageSize = WindowUtilities.getPageSize(objOverlay.parentNode);

 // Hide select boxes as they will 'peek' through the image in IE, store old value
 if (contentId && Prototype.Browser.IE) {
   WindowUtilities._hideSelect();
   WindowUtilities._showSelect(contentId);
 }  

 // set height of Overlay to take up whole page and show
 objOverlay.style.height = (pageSize.pageHeight + 'px');
 objOverlay.style.display = 'none'; 
 if (overlayId == "overlay_modal" && Window.hasEffectLib && Windows.overlayShowEffectOptions) {
   objOverlay.overlayOpacity = overlayOpacity;
   new Effect.Appear(objOverlay, Object.extend({from: 0, to: overlayOpacity}, Windows.overlayShowEffectOptions));
 }
 else
   objOverlay.style.display = "block";
},

enableScreen: function(id) {
 id = id || 'overlay_modal';
 var objOverlay =  $(id);
 if (objOverlay) {
   // hide lightbox and overlay
   if (id == "overlay_modal" && Window.hasEffectLib && Windows.overlayHideEffectOptions)
     new Effect.Fade(objOverlay, Object.extend({from: objOverlay.overlayOpacity, to:0}, Windows.overlayHideEffectOptions));
   else {
     objOverlay.style.display = 'none';
     objOverlay.parentNode.removeChild(objOverlay);
   }
   
   // make select boxes visible using old value
   if (id != "__invisible__") 
     WindowUtilities._showSelect();
 }
},

_hideSelect: function(id) {
 if (Prototype.Browser.IE) {
   id = id ==  null ? "" : "#" + id + " ";
   $$(id + 'select').each(function(element) {
     if (! WindowUtilities.isDefined(element.oldVisibility)) {
       element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
       element.style.visibility = "hidden";
     }
   });
 }
},

_showSelect: function(id) {
 if (Prototype.Browser.IE) {
   id = id ==  null ? "" : "#" + id + " ";
   $$(id + 'select').each(function(element) {
     if (WindowUtilities.isDefined(element.oldVisibility)) {
       // Why?? Ask IE
       try {
         element.style.visibility = element.oldVisibility;
       } catch(e) {
         element.style.visibility = "visible";
       }
       element.oldVisibility = null;
     }
     else {
       if (element.style.visibility)
         element.style.visibility = "visible";
     }
   });
 }
},

isDefined: function(object) {
 return typeof(object) != "undefined" && object != null;
},

// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
initLightbox: function(id, className, doneHandler, parent) {
 // Already done, just update zIndex
 if ($(id)) {
   Element.setStyle(id, {zIndex: Windows.maxZIndex + 1});
   Windows.maxZIndex++;
   doneHandler();
 }
 // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
 else {
   var objOverlay = document.createElement("div");
   objOverlay.setAttribute('id', id);
   objOverlay.className = "overlay_" + className
   objOverlay.style.display = 'none';
   objOverlay.style.position = 'absolute';
   objOverlay.style.top = '0';
   objOverlay.style.left = '0';
   objOverlay.style.zIndex = Windows.maxZIndex + 1;
   Windows.maxZIndex++;
   objOverlay.style.width = '100%';
   parent.insertBefore(objOverlay, parent.firstChild);
   if (Prototype.Browser.WebKit && id == "overlay_modal") {
     setTimeout(function() {doneHandler()}, 10);
   }
   else
     doneHandler();
 }    
},

setCookie: function(value, parameters) {
 document.cookie= parameters[0] + "=" + escape(value) +
   ((parameters[1]) ? "; expires=" + parameters[1].toGMTString() : "") +
   ((parameters[2]) ? "; path=" + parameters[2] : "") +
   ((parameters[3]) ? "; domain=" + parameters[3] : "") +
   ((parameters[4]) ? "; secure" : "");
},

getCookie: function(name) {
 var dc = document.cookie;
 var prefix = name + "=";
 var begin = dc.indexOf("; " + prefix);
 if (begin == -1) {
   begin = dc.indexOf(prefix);
   if (begin != 0) return null;
 } else {
   begin += 2;
 }
 var end = document.cookie.indexOf(";", begin);
 if (end == -1) {
   end = dc.length;
 }
 return unescape(dc.substring(begin + prefix.length, end));
},
 
_computeSize: function(content, id, width, height, margin, className) {
 var objBody = document.body;
 var tmpObj = document.createElement("div");
 tmpObj.setAttribute('id', id);
 tmpObj.className = className + "_content";

 if (height)
   tmpObj.style.height = height + "px"
 else
   tmpObj.style.width = width + "px"

 tmpObj.style.position = 'absolute';
 tmpObj.style.top = '0';
 tmpObj.style.left = '0';
 tmpObj.style.display = 'none';

 tmpObj.innerHTML = content;
 objBody.insertBefore(tmpObj, objBody.firstChild);

 var size;
 if (height)
   size = $(tmpObj).getDimensions().width + margin;
 else
   size = $(tmpObj).getDimensions().height + margin;
 objBody.removeChild(tmpObj);
 return size;
}  
}

/* --- /http://test.unserdaheim.at/templates/daheim/scripts/window.js --- */



/* --- http://test.unserdaheim.at/templates/daheim/scripts/daheim.js --- */
function ichKommen(oid,uid,action){
	//alert(oid+'~'+uid);
		new Ajax.Request('/veranstaltung/ich_kommen/'+action, {
			method: 'post',
			parameters: {oid: oid, uid: uid},
			onComplete: function(transport) {
				//alert(param2+'~'+transport.responseText);
				$('iwannajoin').innerHTML = 'Danke!';
				location.reload();
			}
		});	
}

/* ----- Functions for CityLiveSearch ----- */
function KCheckForm(myfield, e, param) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if ((keycode==38) || (keycode==40) || (keycode==13)) {
  }	    
  else funcForm(document.getElementById('ortsucheForm').value);
}//function

function funcForm(val) {
	//alert(val);
	if(val.length >= 3){
	  new Ajax.Updater('citysearchlive2', '/citysearchlive_articles', {
	    method: 'post',
	    parameters: { ortsuche: val},
	    onLoading: function(e) {
	    	$("OrtSucheAjaxLoader").innerHTML = "<img src='{$TEMPLATE_URL}images/ajax-loader.gif\'>";
	    },
	    onComplete: function(e) {
	    	//alert(e.responseText);
 	    	$('citysearchlive2').style.display = 'block';
	      $("OrtSucheAjaxLoader").innerHTML="";
	    }//onComplete
	  });
	}
}//function

function closeBoxForm() {
	document.getElementById('citysearchlive2').style.display='none';
	if($('hideFriends')){
		document.getElementById('hideFriends').style.visibility = "visible";
	}
}//function

function hideFriends() {
	if( window.clipboardData && document.compatMode ) {
	document.getElementById('hideFriends').style.visibility = "hidden";
	}
}

function showElement(id) {
	$(id).show();
}//function


/* ----- Functions for CityLiveSearch ----- */


/* ----- Functions for Repository ----- */


function getFolderContent(oid,param2) {
	if(oid) {
		new Ajax.Updater('files', '/repository/get_folder_content', {
			method: 'post',
			parameters: {oid: oid},
			onComplete: function(transport) {
			  //location . reload();
			  //alert("Done!");
			}			
		});
	} // if
} // function

/* ------------------------------------ */

function deleteObject(oid,pid) {
	if(oid) {
		//new Ajax.Updater('files', '/repository/delete_object', {
		new Ajax.Request('/repository/delete_object', {
			method: 'post',
			parameters: {oid: oid, pid: pid},
			onComplete: function(transport) {
			  getFolderContent(pid, 0);
			}			
		});
	} // if
} // function

/* ------------------------------------ */

function createRepositoryFolder(parent_oid, name, param2) {
  if(name == null) {
	  name = $F("newfolder");
  } // if
	
	if(name) {
		new Ajax.Request('/repository/create_new_folder/'+param2, {
			method: 'post',
			parameters: {parent_oid: parent_oid, name: name},
			onComplete: function(transport) {
				//alert(param2+'~'+transport.responseText);
			  //go.addVariable("extFolderId", "transport.responseText");
			  //var obj = swfobject.getObjectById("uploader");
			  //obj.SetVariable("extFolderId", transport.responseText);
			  getFolderContent(parent_oid, param2);
			  //location. reload();
			}
		});
		
		return false;
	} // if
} // function


/* ------------------------------------ */

function showHide(elementS, elementH) {
	
	if($(elementS).style.display == 'none') {
		$(elementS+'Arrow').addClassName('open');
		$(elementH+'Arrow').removeClassName('open');
		$(elementS).style.display = 'block';
		$(elementH).style.display = 'none';			
	} else {
		$(elementH+'Arrow').removeClassName('open');
		$(elementS+'Arrow').addClassName('open');
		$(elementH).style.display = 'none';	
		$(elementS).style.display = 'block';
	} // if
} // function

/* ------------------------------------ */

function showHideDiv(element) {
	if($(element).style.display == 'none') {
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';
	} // if	
} // function

/* ------------------------------------ */


//Reload for Flash Uploader
function flashReload() {
	window.setTimeout("window.location.reload()", 100);
}

/* ----- END Functions for Repository ----- */



//Change page location
function changeURL(url) {
	window.location = url;
}
/* ------------------------------------ */

// retrieves the bezirke according to a bundesland
// and sets the current selection of the bundesland
function getBezirke(bl_ref, bl_name) {
  new Ajax.Updater('listBezirke',
                   '/get_bezirke',
                   {
                     method: 'post',
                     parameters: {
                       bl_ref: bl_ref
                     }
                   });
  $('bl_sel').innerHTML = bl_name;
} // function


// retrieves the gemeinden according to a bezirk
function getGemeinden(bez_ref, bez_name) {
  new Ajax.Updater('listGemeinden',
                   '/get_gemeinden',
                   {
                     method: 'post',
                     parameters: {
                       bez_ref: bez_ref
                     }
                   });
  $('bez_sel').innerHTML = bez_name;
} // function


var curr_add_article_tab = 'newFilesTab';
var curr_add_article_area = 'tab_NeueDateien';

function toggleAddArticleArea(area, tab) {
	
  if(curr_add_article_area) {
    $(curr_add_article_area).style.display = 'none';
    $(curr_add_article_tab).className = 'levelQuarterDeact';
  } // if
  
  $(area).style.display = 'block';
  $(tab).className = 'levelQuarterAct';
  
  curr_add_article_area = area;
  curr_add_article_tab = tab;
} // function


function toggleAddArticleArea2(area, tab) {

var curr_add_article_tab = area;
var curr_add_article_area = tab;
	
	
  if($(curr_add_article_area).style.display == 'none') {
    $(curr_add_article_area).style.display = 'block';
    $(curr_add_article_tab).className = 'levelQuarterAct';
  } else { 
    $(area).style.display = 'none';
    $(tab).className = 'levelQuarterDeact';
	}// if
  curr_add_article_area = area;
  curr_add_article_tab = tab;  
} // function


function setObjectperm(oid, object_perm) {

	new Ajax.Request('/benutzer_profil/setobjectperm', {
			method: 'post',
			parameters: {oid: oid, object_perm: object_perm},
			onComplete: function(transport) {
				window.location.reload();
			}
		});
	
}

var win = null;
var index = 1;
	function openDialog(id, url) {
		if(url) {
			writeCommonLogin(url);
		} // if
	  Dialog.alert($(id).innerHTML, {className: "alphacube",  width:218,showEffect:Element.show, hideEffect:Element.hide , id: "d" + index})
	  index++;
}

function openDialog2(id, url) {
	if(url) {
			writeCommonLogin(url);
		} // if
	  Dialog.alert($(id).innerHTML, {className: "alphacube2",  width:273,showEffect:Element.show, hideEffect:Element.hide , id: "d" + index})
	  index++;
}

function openDialog3(id, url) {
	if(url) {
			writeCommonLogin(url);
		} // if
	  Dialog.alert($(id).innerHTML, {className: "alphacube3",  width:273,showEffect:Element.show, hideEffect:Element.hide , id: "d" + index})
	  index++;
}

  function openDialog4(id, url) {
	if(url) {
			writeCommonLogin(url);
		} // if
	  Dialog.alert($(id).innerHTML, {className: "alphacube4",  width:218,showEffect:Element.show, hideEffect:Element.hide , id: "d" + index})
	  index++;
}

function closeAllModalWindows() {
  Windows.closeAllModalWindows();
  return true;
}

function writeCommonLogin(url) {
	new Ajax.Request('/write_commonlogin', {
		method: 'post',
		parameters: { url: url }
	});
}



function openDialogSetSessionVar(variable, value) {
  new Ajax.Request(
      '/setsessionvar/', {
        method: 'post',
        parameters: {variable: variable, value: value},
        onComplete: function(transport) {
          openDialog('content');
        }
      }
    );
} // function


function openDialogArticleComments() {
	new Ajax.Request(
		'/artikel/comments_check_login', {
			method: 'post',
			parameters: {subject: $F('subject_0'), text: $F('text_0')},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function

function openDialogGalleryComments() {
	new Ajax.Request(
		'/gallery/comments_check_login', {
			method: 'post',
			parameters: {subject: $F('subject_0'), text: $F('text_0')},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function

function openDialogVideoComments() {
	new Ajax.Request(
		'/video/comments_check_login', {
			method: 'post',
			parameters: {subject: $F('subject_0'), text: $F('text_0')},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function



function openDialogWriteArticle() {
	new Ajax.Request(
		'/add_article/add_article_check_login', {
			method: 'post',
			parameters: {doit: 1},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function
function addGeoBookmark2(id) {
	new Ajax.Updater('meineOrte', '/GeoBookmark/add2', {
			method: 'post',
			parameters: {id: id},
			onComplete: function(transport) {
			  
			}			
		});
} // function
function delGeoBookmark2(id) {
	new Ajax.Updater('meineOrte', '/GeoBookmark/del2', {
			method: 'post',
			parameters: {id:id},
			onComplete: function(transport) {
			  //window.location.reload();
			}			
		});
} // function
function addStartpage2(id) {
	new Ajax.Updater('meineOrte', '/GeoBookmark/startpage2', {
			method: 'post',
			parameters: {id:id},
			onComplete: function(transport) {
			  //window.location.reload();
			}			
		});
} // function

function addGeoBookmark(id) {
	new Ajax.Updater('ladeMeineOrte', '/GeoBookmark/add', {
			method: 'post',
			parameters: {id: id},
			onComplete: function(transport) {
			  
			}			
		});
} // function
function editGeoBookmark() {
	new Ajax.Updater('ladeMeineOrte2', '/GeoBookmark/edit', {
			method: 'post',
			parameters: {},
			onComplete: function(transport) {
			  
			}			
		});
} // function

function closeGeoBookmark() {
	new Ajax.Updater('ladeMeineOrte', '/GeoBookmark/close', {
			method: 'post',
			parameters: {},
			onComplete: function(transport) {
			  
			}			
		});
} // function

function delGeoBookmark(id) {
	new Ajax.Updater('ladeMeineOrte2', '/GeoBookmark/del', {
			method: 'post',
			parameters: {id:id},
			onComplete: function(transport) {
			  window.location.reload();
			}			
		});
} // function

function addStartpage(id) {
	new Ajax.Updater('ladeMeineOrte2', '/GeoBookmark/startpage', {
			method: 'post',
			parameters: {id:id},
			onComplete: function(transport) {
			  window.location.reload();
			}			
		});
} // function

function setDistance() {
	if ($('jumpMenu').value == '-1')
		return; 
	new Ajax.Request('/setdistance', {
			method: 'post',
			parameters: $('setdistform').serialize(true),
			onComplete: function(transport) {
			  window.location.reload();
			}			
		});
}// function



function validatePostalCode( strValue ) {
	var objRegExp  = /(^\d{4}$)|(^A-\d{4}$)/i;
	
	  //check for valid Austrian Postal Code A-XXXX | XXXX
	  return objRegExp.test(strValue);
}

function validateNumeric( strValue ) {
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function validateEmail( strValue) {
	var objRegExp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;

  //check for valid email
  return objRegExp.test(strValue);
}


function checkByClassName(classname, id) {
	
		var status = $(id).checked;
		
		var ceckboxes = $$('.'+classname);

		ceckboxes.each(function(cb) {

			if(cb.checked != status && cb.id != id) {
				$(cb).checked = status;
			}

		});	
	
}


























































//return content of FCK editor ~ don't delete
function getFCKcontent(eleid) {
	if (document.getElementById(eleid+'___Frame')) {
		var fck_frame = document.getElementById(eleid+'___Frame');
		var iFrame = (fck_frame.contentWindow || fck_frame.contentDocument);
		
		if (iFrame.document) {
			iFrame = iFrame.document;
			
			if (iFrame.getElementsByTagName('iframe')[0]) {
				var fck_textframe = iFrame.getElementsByTagName('iframe')[0];
				var textFrame = (fck_textframe.contentWindow || fck_textframe.contentDocument);
				
				if (textFrame.document) {
					textFrame = textFrame.document;function ichKommen(oid,uid,action){
	//alert(oid+'~'+uid);
		new Ajax.Request('/veranstaltung/ich_kommen/'+action, {
			method: 'post',
			parameters: {oid: oid, uid: uid},
			onComplete: function(transport) {
				//alert(param2+'~'+transport.responseText);
				$('iwannajoin').innerHTML = 'Danke!';
				location.reload();
			}
		});	
}

/* ----- Functions for CityLiveSearch ----- */
function KCheckForm(myfield, e, param) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if ((keycode==38) || (keycode==40) || (keycode==13)) {
  }	    
  else funcForm(document.getElementById('ortsucheForm').value);
}//function

function funcForm(val) {
	//alert(val);
	if(val.length >= 3){
	  new Ajax.Updater('citysearchlive2', '/citysearchlive_articles', {
	    method: 'post',
	    parameters: { ortsuche: val},
	    onLoading: function(e) {
	    	$("OrtSucheAjaxLoader").innerHTML = "<img src='{$TEMPLATE_URL}images/ajax-loader.gif\'>";
	    },
	    onComplete: function(e) {
	    	//alert(e.responseText);
	      $('citysearchlive2').style.display = 'block';
	      $("OrtSucheAjaxLoader").innerHTML="";
	    }//onComplete
	  });
	}
}//function

function closeBoxForm() {
	document.getElementById('citysearchlive2').style.display='none';
	if($('hideFriends')){
		document.getElementById('hideFriends').style.visibility = "visible";
	}
}//function

function hideFriends() {
	if( window.clipboardData && document.compatMode ) {
	document.getElementById('hideFriends').style.visibility = "hidden";
	}
}

function showElement(id) {
	$(id).show();
}//function


/* ----- Functions for CityLiveSearch ----- */


/* ----- Functions for Repository ----- */


function getFolderContent(oid,param2) {
	if(oid) {
		new Ajax.Updater('files', '/repository/get_folder_content', {
			method: 'post',
			parameters: {oid: oid},
			onComplete: function(transport) {
			  //location . reload();
			  //alert("Done!");
			}			
		});
	} // if
} // function

/* ------------------------------------ */

function deleteObject(oid,pid) {
	if(oid) {
		//new Ajax.Updater('files', '/repository/delete_object', {
		new Ajax.Request('/repository/delete_object', {
			method: 'post',
			parameters: {oid: oid, pid: pid},
			onComplete: function(transport) {
			  getFolderContent(pid, 0);
			}			
		});
	} // if
} // function

/* ------------------------------------ */

function createRepositoryFolder(parent_oid, name, param2) {
  if(name == null) {
	  name = $F("newfolder");
  } // if
	
	if(name) {
		new Ajax.Request('/repository/create_new_folder/'+param2, {
			method: 'post',
			parameters: {parent_oid: parent_oid, name: name},
			onComplete: function(transport) {
				//alert(param2+'~'+transport.responseText);
			  //go.addVariable("extFolderId", "transport.responseText");
			  //var obj = swfobject.getObjectById("uploader");
			  //obj.SetVariable("extFolderId", transport.responseText);
			  getFolderContent(parent_oid, param2);
			  // location. reload();
			}
		});
		
		return false;
	} // if
} // function


/* ------------------------------------ */

function showHide(elementS, elementH) {
	
	if($(elementS).style.display == 'none') {
		$(elementS+'Arrow').addClassName('open');
		$(elementH+'Arrow').removeClassName('open');
		$(elementS).style.display = 'block';
		$(elementH).style.display = 'none';			
	} else {
		$(elementH+'Arrow').removeClassName('open');
		$(elementS+'Arrow').addClassName('open');
		$(elementH).style.display = 'none';	
		$(elementS).style.display = 'block';
	} // if
} // function

/* ------------------------------------ */

function showHideDiv(element) {
	if($(element).style.display == 'none') {
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';
	} // if	
} // function

/* ------------------------------------ */


//Reload for Flash Uploader
function flashReload() {
	window.setTimeout("window.location.reload()", 100);
}

/* ----- END Functions for Repository ----- */



//Change page location
function changeURL(url) {
	window.location = url;
}
/* ------------------------------------ */

// retrieves the bezirke according to a bundesland
// and sets the current selection of the bundesland
function getBezirke(bl_ref, bl_name) {
  new Ajax.Updater('listBezirke',
                   '/get_bezirke',
                   {
                     method: 'post',
                     parameters: {
                       bl_ref: bl_ref
                     }
                   });
  $('bl_sel').innerHTML = bl_name;
} // function


// retrieves the gemeinden according to a bezirk
function getGemeinden(bez_ref, bez_name) {
  new Ajax.Updater('listGemeinden',
                   '/get_gemeinden',
                   {
                     method: 'post',
                     parameters: {
                       bez_ref: bez_ref
                     }
                   });
  $('bez_sel').innerHTML = bez_name;
} // function


var curr_add_article_tab = 'newFilesTab';
var curr_add_article_area = 'tab_NeueDateien';

function toggleAddArticleArea(area, tab) {
	
  if(curr_add_article_area) {
    $(curr_add_article_area).style.display = 'none';
    $(curr_add_article_tab).className = 'levelQuarterDeact';
  } // if
  
  $(area).style.display = 'block';
  $(tab).className = 'levelQuarterAct';
  
  curr_add_article_area = area;
  curr_add_article_tab = tab;
} // function


function toggleAddArticleArea2(area, tab) {

var curr_add_article_tab = area;
var curr_add_article_area = tab;
	
	
  if($(curr_add_article_area).style.display == 'none') {
    $(curr_add_article_area).style.display = 'block';
    $(curr_add_article_tab).className = 'levelQuarterAct';
  } else { 
    $(area).style.display = 'none';
    $(tab).className = 'levelQuarterDeact';
	}// if
  curr_add_article_area = area;
  curr_add_article_tab = tab;  
} // function


function setObjectperm(oid, object_perm) {

	new Ajax.Request('/benutzer_profil/setobjectperm', {
			method: 'post',
			parameters: {oid: oid, object_perm: object_perm},
			onComplete: function(transport) {
				window.location.reload();
			}
		});
	
}





function openDialogArticleComments() {
	new Ajax.Request(
		'/artikel/comments_check_login', {
			method: 'post',
			parameters: {subject: $F('subject_0'), text: $F('text_0')},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function

function openDialogGalleryComments() {
	new Ajax.Request(
		'/gallery/comments_check_login', {
			method: 'post',
			parameters: {subject: $F('subject_0'), text: $F('text_0')},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function

function openDialogVideoComments() {
	new Ajax.Request(
		'/video/comments_check_login', {
			method: 'post',
			parameters: {subject: $F('subject_0'), text: $F('text_0')},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function



function openDialogWriteArticle() {
	new Ajax.Request(
		'/add_article/add_article_check_login', {
			method: 'post',
			parameters: {doit: 1},
			onComplete: function(transport) {
				openDialog('content');
			}
		}
	);
} // function

function addGeoBookmark(id) {
	new Ajax.Updater('ladeMeineOrte', '/GeoBookmark/add', {
			method: 'post',
			parameters: {id: id},
			onComplete: function(transport) {
			  
			}			
		});
} // function
function editGeoBookmark() {
	new Ajax.Updater('ladeMeineOrte2', '/GeoBookmark/edit', {
			method: 'post',
			parameters: {},
			onComplete: function(transport) {
			  
			}			
		});
} // function

function closeGeoBookmark() {
	new Ajax.Updater('ladeMeineOrte', '/GeoBookmark/close', {
			method: 'post',
			parameters: {},
			onComplete: function(transport) {
			  
			}			
		});
} // function

function delGeoBookmark(id) {
	new Ajax.Updater('ladeMeineOrte2', '/GeoBookmark/del', {
			method: 'post',
			parameters: {id:id},
			onComplete: function(transport) {
			  window.location.reload();
			}			
		});
} // function

function addStartpage(id) {
	new Ajax.Updater('ladeMeineOrte2', '/GeoBookmark/startpage', {
			method: 'post',
			parameters: {id:id},
			onComplete: function(transport) {
			  window.location.reload();
			}			
		});
} // function













































































//return content of FCK editor ~ don't delete
function getFCKcontent(eleid) {
	if (document.getElementById(eleid+'___Frame')) {
		var fck_frame = document.getElementById(eleid+'___Frame');
		var iFrame = (fck_frame.contentWindow || fck_frame.contentDocument);
		
		if (iFrame.document) {
			iFrame = iFrame.document;
			
			if (iFrame.getElementsByTagName('iframe')[0]) {
				var fck_textframe = iFrame.getElementsByTagName('iframe')[0];
				var textFrame = (fck_textframe.contentWindow || fck_textframe.contentDocument);
				
				if (textFrame.document) {
					textFrame = textFrame.document;
					var orig_text = document.getElementById(eleid).value.replace(/[\n\r]/g, "");
					var current_text = textFrame.getElementsByTagName('body')[0].innerHTML;
					current_text = current_text.replace(/[\n\r]/g, "").replace(/;"/g, '"').replace(/<b>/, "<strong>").replace(/<\/b>/, "</strong>");
          var orig_tags = orig_text.match(/(<\/?.*?>)/g);
              
              if (orig_tags) {
                for (var i = 0; i < orig_tags.length; ++i) {
                  orig_text = orig_text.replace(orig_tags[i], orig_tags[i].toLowerCase());
                }
              } // if
              
              var current_tags = current_text.match(/(<\s?\/?\s?[A-Z]+.*?>)/g);
              
              if (current_tags) {
                for (var i = 0; i < current_tags.length; ++i) {
                  current_text = current_text.replace(current_tags[i], current_tags[i].toLowerCase());
                } // for
              } // if
              
              if(current_text == "<br>") current_text = "";
               
             // alert ("Orig: "+orig_text+"\n\nCurrent: "+current_text);
              
             //if (orig_text == current_text) {
             if (current_text=="") {
                return false;
              } else {
                return current_text;
              } // if              
         } // if         
        } // if        
      } // if      
    } // if      
}//function getFCKcontent

					var orig_text = document.getElementById(eleid).value.replace(/[\n\r]/g, "");
					var current_text = textFrame.getElementsByTagName('body')[0].innerHTML;
					current_text = current_text.replace(/[\n\r]/g, "").replace(/;"/g, '"').replace(/<b>/, "<strong>").replace(/<\/b>/, "</strong>");
          var orig_tags = orig_text.match(/(<\/?.*?>)/g);
              
              if (orig_tags) {
                for (var i = 0; i < orig_tags.length; ++i) {
                  orig_text = orig_text.replace(orig_tags[i], orig_tags[i].toLowerCase());
                }
              } // if
              
              var current_tags = current_text.match(/(<\s?\/?\s?[A-Z]+.*?>)/g);
              
              if (current_tags) {
                for (var i = 0; i < current_tags.length; ++i) {
                  current_text = current_text.replace(current_tags[i], current_tags[i].toLowerCase());
                } // for
              } // if
              
              if(current_text == "<br>") current_text = "";
               
             // alert ("Orig: "+orig_text+"\n\nCurrent: "+current_text);
              
             //if (orig_text == current_text) {
             if (current_text=="") {
                return false;
              } else {
                return current_text;
              } // if              
         } // if         
        } // if        
      } // if      
    } // if      
}//function getFCKcontent



function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/

function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getnewcaptcha() {
    $('captchaimg').src = "/getcaptcha/?rand="+Math.random(0, 1000);
    return false;
}
/* --- /http://test.unserdaheim.at/templates/daheim/scripts/daheim.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/send.js --- */
/*  Send.js
 *  Benjamin Sernji
 *	SEND, FLAG  ARTILE,PHOTOS,EVENTS - FLAG COMMENTS
 *--------------------------------------------------------------------------*/




// SEND ARTICLE
function shSendArticle(element) {
	if($(element).style.display == 'none') {
		if($('send_article_success').style.display == 'block'){
		$('send_article_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function sendArticle(value) {

	$('textid').removeClassName('error');
	var email = $F('avemail');
	var isEmail = validateEmail(email);
	
	if(isEmail) {
		$('sendArticle').request();
		$('send_article').style.display = 'none';
		$('send_article_success').style.display = 'block';
		$('sendArticle').reset();
	}else{
		$('textid').addClassName('error');
		return false;
	}//if-else
	
}// function

// SEND PHOTOS
function shSendPhotos(element) {
	if($(element).style.display == 'none') {
		if($('send_photos_success').style.display == 'block'){
		$('send_photos_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function sendPhotos(value) {
	var email = $F('pvemail');
	var isEmail = validateEmail(email);
	
	if(isEmail) {
		$('sendPhotos').request();
		$('send_photos').style.display = 'none';
		$('send_photos_success').style.display = 'block';
		$('sendPhotos').reset();
	}else{
		$('textid').addClassName('error');
		return false;
	}//if-else		

}// function


// SEND VIDEOS
function shSendVideos(element) {
	if($(element).style.display == 'none') {
		if($('send_videos_success').style.display == 'block'){
		$('send_videos_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function sendVideos(value) {	
	var email = $F('vvemail');
	var isEmail = validateEmail(email);
	
	if(isEmail) {
		$('sendVideos').request();
		$('send_videos').style.display = 'none';
		$('send_videos_success').style.display = 'block';
		$('sendVideos').reset();
	}else{
		$('textid').addClassName('error');
		return false;
	}//if-else	
	
}// function

// SEND EVENTS
function shSendEvents(element) {
	if($(element).style.display == 'none') {
		if($('send_events_success').style.display == 'block'){
		$('send_events_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function sendEvents(value) {	
	
	$('textid').removeClassName('error');
	var email = $F('evemail');
	var isEmail = validateEmail(email);
	
	if(isEmail) {
		$('sendEvents').request();
		$('send_events').style.display = 'none';
		$('send_events_success').style.display = 'block';
		$('sendEvents').reset();
	}else{
		$('textid').addClassName('error');
		return false;
	}//if-else
	

}// function





// FLAG ARTICLE

function shFlagArticle(element) {
	if($(element).style.display == 'none') {
		if($('flag_article_success').style.display == 'block'){
		$('flag_article_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function flagArticle(value) {
	
	
	$('flagArticle').request();
	$('flag_article').style.display = 'none';
	$('flag_article_success').style.display = 'block';
	$('flagArticle').reset();
}// function


// FLAG PHOTOS
function shFlagPhotos(element) {
	if($(element).style.display == 'none') {
		if($('flag_photos_success').style.display == 'block'){
		$('flag_photos_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function flagPhotos(value) {
	
	
	$('flagPhotos').request();
	$('flag_photos').style.display = 'none';
	$('flag_photos_success').style.display = 'block';
	$('flagPhotos').reset();
}// function


// FLAG VIDEOS
function shFlagVideos(element) {
	if($(element).style.display == 'none') {
		if($('flag_videos_success').style.display == 'block'){
		$('flag_videos_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function flagVideos(value) {
	
	
	$('flagVideos').request();
	$('flag_videos').style.display = 'none';
	$('flag_videos_success').style.display = 'block';
	$('flagVideos').reset();
}// function


// FLAG EVENTS
function shFlagEvents(element) {
	if($(element).style.display == 'none') {
		if($('flag_events_success').style.display == 'block'){
		$('flag_events_success').style.display = 'none';
		}
		$(element).style.display = 'block';
	} else {
		$(element).style.display = 'none';	
	} // if	
} // function


function flagEvents(value) {
	
	
	$('flagEvents').request();
	$('flag_events').style.display = 'none';
	$('flag_events_success').style.display = 'block';
	$('flagEvents').reset();
}// function



// FLAG COMMENT
function flagComment(value) {
	$(value).request();
	$(value).style.display = 'none';
  $(value+'Success').style.display = 'block';
}// function


/* --- /http://test.unserdaheim.at/templates/daheim/scripts/send.js --- */


/* --- http://test.unserdaheim.at/templates/daheim/scripts/common.js --- */
function autoSelect(selectTarget) {
	 	if(selectTarget != null && ((selectTarget.childNodes.length == 1
	      && selectTarget.childNodes[0].nodeName == "#text") || (selectTarget.tagName == "INPUT"
	      && selectTarget.type == "text"))) {
	  		if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
	  			 selectTarget.select();
	  		} else if(window.getSelection) { // FF, Safari, Opera
	   			var sel = window.getSelection();
	   			var range = document.createRange();
	   			range.selectNode(selectTarget.firstChild);
	   			sel.removeAllRanges();
	   			sel.addRange(range);
	  		} else { // IE
	   			document.selection.empty();
	   			var range = document.body.createTextRange();
	   			range.moveToElementText(selectTarget);
	   			range.select();
	  		}
	 	}
	}

function toggle_visibility(id) {
      //var e = $(id);
      var e = document.getElementById(id);

      if(e.style.display == 'block'){
         e.style.display = 'none';
      }else{
         e.style.display = 'block';
      }
   }

function toggle_visibilityOC(open, close) {
      var a = $(open);
      if (close) {
		var b = $(close);
	  }

       if(a.style.display == 'block' || a.style.display == ''){
         a.style.display = 'none';
         if(b) {
        	 b.style.display = 'block';
         }
       } else {
         a.style.display = 'block';
          if(b){
        	  b.style.display = 'none';
          }
       }
   }


function suchfelder (autosv, plh, res, sid) {
	var autosave = autosv;
	var placeholder = plh;
	var results = res;
	var search_el = document.getElementById(sid);
	//search_el.style.color = "#666";
	function setSafariSearch(element) {
	   element.setAttribute("type", "search");
	   element.setAttribute("autosave", autosave);
	   element.setAttribute("placeholder", placeholder);
	   element.setAttribute("results", results);
	}
	function setNormalSearch(element) {
	  if (typeof(element) == 'undefined') return;
		if (element.value == '') {
	   		element.value = placeholder;
		}
	   element.onfocus = function() {
		  if (element.value == placeholder) {
		    element.value = "";
		    //element.style.color = "#000";
		  };
	   }
	   element.onblur = function() {
		  if (!element.value) {
		    element.value = placeholder;
			//element.style.color = "#666";
		  };
	   }
	}
	if (navigator.userAgent.indexOf("AppleWebKit") != -1) {
	   /*setSafariSearch(search_el);*/
	   setNormalSearch(search_el);
	} else {
	   setNormalSearch(search_el);
	}
}

// SWITCH NAV STYLE //
var selLevel = 0;
function switchStyle(level) {
	if(selLevel != level) {
	  selLevel = level;
	  var option=['l1','l2'];
	  for (var i=0; i<option.length; i++) {
	    obj=document.getElementById(option[i]);
		if (obj != selLevel) {
	    	obj.style.display=(option[i]==selLevel) && !(obj.style.display=="block")? "block" : "none";
		}
	  }
    }
}

// TOGGLE SITE SEARCH //
/*
"gsuche"
"textsuche"

"udSearch"
"webSearch"
*/
function switchSearch(sobj,field1,field2,displayswitch1,displayswitch2) {
  var wsVal = document.getElementById(field1).value;
  var usVal = document.getElementById(field2).value;

  if (sobj == "sopt1") {
	 //alert("sopt1");
	if (wsVal != 'Google Suche...' || wsVal == '' || (wsVal != usVal && usVal != 'Suchbegriff...')) {
	  //alert("1");
	  document.getElementById(field1).value = wsVal;
    }
	document.getElementById(displayswitch1).style.display="block";
	document.getElementById(displayswitch2).style.display="none";
  } else {
	//alert("not sopt1");
	if (usVal != 'Suchbegriff...' || usVal == '' || (wsVal != usVal && wsVal != 'Google Suche...')) {
	  //alert("2");
	  document.getElementById(field2).value = usVal;
    }
	document.getElementById(displayswitch1).style.display="none";
	document.getElementById(displayswitch2).style.display="block";
  }
}

function switchSearchV2(sobj,field1,field2,displayswitch1,displayswitch2) {
  var wsVal = document.getElementById("gsuche").value;
  var usVal = document.getElementById("textsuche").value;
  if (wsVal == "Google Suche...") {
	  wsVal = '';
  }
  if (usVal == "Suchbegriff...") {
	  usVal = '';
  }
  //alert(wsVal);
  //alert(usVal);

  if (sobj == "sopt1") {
	if (wsVal != '') {
		//alert("1");
		document.getElementById(field1).value = wsVal;
	}
	document.getElementById(displayswitch1).style.display="block";
	document.getElementById(displayswitch2).style.display="none";
  } else {
	if (usVal != '') {
		//alert("2");
		document.getElementById(field2).value = usVal;
	}
	document.getElementById(displayswitch1).style.display="none";
	document.getElementById(displayswitch2).style.display="block";
  }
}

// TOGGLE MEINE ORTE //
function switchMeineOrte() {
	obj=document.getElementById("meineOrteEdit");
	obj.style.display=!(obj.style.display=="block")? "block" : "none";
	obj=document.getElementById("meineOrte");
	obj.style.display=!(obj.style.display=="block")? "block" : "none";
}

// TOGGLE MEINE REGION //
function switchMeineRegion() {
	obj=document.getElementById("btRegionOpen");
	obj.style.display=!(obj.style.display=="block")? "block" : "none";
	obj=document.getElementById("btRegionClosed");
	obj.style.display=!(obj.style.display=="block")? "block" : "none";
}

// TOGGLE LOCATIONSELECTOR //
var selLocation = 0;
var selState = 0;
function switchSlider(slider, state) {
	var sliders=['listBundesland','listBezirke','listGemeinden'];
	var states=['btBundeslandClosed','btBundeslandOpen','btBezirkClosed','btBezirkOpen','btGemeindeOpen','btGemeindeClosed'];
	if (selLocation == slider) {
		obj=document.getElementById(slider);
		obj.style.display=!(obj.style.display=="block")? "block" : "none";
	}
	if (selLocation != slider) {
	  selLocation = slider;
	  for (var i=0; i<sliders.length; i++) {
	    obj=document.getElementById(sliders[i]);
	    obj.style.display=(sliders[i]==selLocation) && !(obj.style.display=="block")? "block" : "none";
	  }
    }
	if (state == 'btBundeslandClosed') {
		obj=document.getElementById('btBundeslandOpen');
		obj.style.display="block";
		obj=document.getElementById('btBundeslandClosed');
		obj.style.display="none";
		obj=document.getElementById('btBezirkOpen');
		obj.style.display="none";
		obj=document.getElementById('btBezirkClosed');
		obj.style.display="block";
		obj=document.getElementById('btGemeindeOpen');
		obj.style.display="none";
		obj=document.getElementById('btGemeindeClosed');
		obj.style.display="block";
	} else if (state == 'btBundeslandOpen') {
		obj=document.getElementById('btBundeslandOpen');
		obj.style.display="none";
		obj=document.getElementById('btBundeslandClosed');
		obj.style.display="block";
		obj=document.getElementById('btBezirkOpen');
		obj.style.display="none";
		obj=document.getElementById('btBezirkClosed');
		obj.style.display="block";
		obj=document.getElementById('btGemeindeOpen');
		obj.style.display="none";
		obj=document.getElementById('btGemeindeClosed');
		obj.style.display="block";
	}
	if (state == 'btBezirkClosed') {
		obj=document.getElementById('btBundeslandOpen');
		obj.style.display="none";
		obj=document.getElementById('btBundeslandClosed');
		obj.style.display="block";
		obj=document.getElementById('btBezirkOpen');
		obj.style.display="block";
		obj=document.getElementById('btBezirkClosed');
		obj.style.display="none";
		obj=document.getElementById('btGemeindeOpen');
		obj.style.display="none";
		obj=document.getElementById('btGemeindeClosed');
		obj.style.display="block";
	} else if (state == 'btBezirkOpen') {
		obj=document.getElementById('btBundeslandOpen');
		obj.style.display="none";
		obj=document.getElementById('btBundeslandClosed');
		obj.style.display="block";
		obj=document.getElementById('btBezirkOpen');
		obj.style.display="none";
		obj=document.getElementById('btBezirkClosed');
		obj.style.display="block";
		obj=document.getElementById('btGemeindeOpen');
		obj.style.display="none";
		obj=document.getElementById('btGemeindeClosed');
		obj.style.display="block";
	}
	if (state == 'btGemeindeClosed') {
		obj=document.getElementById('btBundeslandOpen');
		obj.style.display="none";
		obj=document.getElementById('btBundeslandClosed');
		obj.style.display="block";
		obj=document.getElementById('btBezirkOpen');
		obj.style.display="none";
		obj=document.getElementById('btBezirkClosed');
		obj.style.display="block";
		obj=document.getElementById('btGemeindeOpen');
		obj.style.display="block";
		obj=document.getElementById('btGemeindeClosed');
		obj.style.display="none";
	} else if (state == 'btGemeindeOpen') {
		obj=document.getElementById('btBundeslandOpen');
		obj.style.display="none";
		obj=document.getElementById('btBundeslandClosed');
		obj.style.display="block";
		obj=document.getElementById('btBezirkOpen');
		obj.style.display="none";
		obj=document.getElementById('btBezirkClosed');
		obj.style.display="block";
		obj=document.getElementById('btGemeindeOpen');
		obj.style.display="none";
		obj=document.getElementById('btGemeindeClosed');
		obj.style.display="block";
	}
}

function textlimit(textareaID, counterID, divID, limitNum) {
	var tID = document.getElementById(textareaID);
	var cID = document.getElementById(counterID);
	var dID = document.getElementById(divID);
	var bal = limitNum - tID.value.length;
	if (bal < 0) {
		var bal = 0;
	}
	cID.innerHTML = bal;
	if (tID.value.length > limitNum) {
		tID.value = tID.value.substring(0, limitNum);
		dID.style.color = "#f00";
	} else if (bal != 0) {
		dID.style.color = "#000";
	}
}

function P7_Snap() { //v10 by Marek (snap_to_id, snap_what_id, relative_left, relative_top)
  var snap_to_offset, args=P7_Snap.arguments;
  for (k=0; k<(args.length-3); k+=4) {
	try {
		snap_to_offset = $(args[k]).cumulativeOffset();
		$(args[k+1]).setStyle({left: (snap_to_offset.left + parseInt(args[k+2])) + 'px', top: (snap_to_offset.top + parseInt(args[k+3])) + 'px' });
		//console.log("setStyle({left: " + (snap_to_offset.left + parseInt(args[k+2])) + 'px, top: ' + (snap_to_offset.top + parseInt(args[k+3])) + 'px' + ")}");
	} catch(e) { /*console.log(e)*/ }
  }
}

function loadAds(sname, path, gid_dmu, gid_dr, gid_lmu, gid_lr, gid_s1, gid_s2) {
	if (gid_dmu && document.getElementById('detailmitteunten')) {
	  document.getElementById('detailmitteunten').src = (sname+path+'google/adsense_detail_mitteunten.html?gid='+gid_dmu);
	}
	if (gid_dr && document.getElementById('detailrechts')) {
	  document.getElementById('detailrechts').src = (sname+path+'google/adsense_detail_rechts.html?gid='+gid_dr);
	}
	if (gid_lmu && document.getElementById('listemitteunten')) {
	  document.getElementById('listemitteunten').src = (sname+path+'google/adsense_liste_mitteunten.html?gid='+gid_lmu);
	}
	if (gid_lr && document.getElementById('listerechts')) {
	  document.getElementById('listerechts').src = (sname+path+'google/adsense_liste_rechts.html?gid='+gid_lr);
	}
	if (gid_s2 && document.getElementById('googleStartseite2')) {
	 /* document.getElementById('googleStartseite1').src = (sname+path+'google/adsense_startseite.html?gid='+gid_s1);*/
	  document.getElementById('googleStartseite2').src = (sname+path+'google/adsense_startseite.html?gid='+gid_s2);
	}
}

// DREAMWEAVER FUNCTIONS //
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_showHideLayers() { //v9.0 //modified by Martin Huber 25/03/2009
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3)
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'block':(v=='hide')?'none':v; }
    obj.display=v; }
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function positionBanners() {
	var c = $('container');
	var col = c.cumulativeOffset()['left'];
	$$('.footerBox').invoke('setStyle', {marginLeft: col + 'px'});
	var l = col + c.getWidth() + 2;
	var a = $('a577d8b3');
	if(!a) return;
	var w = a.getWidth();
    a.setStyle({left: (l) + 'px'});
    var dw = document.viewport.getDimensions()['width'];
    
    $('footerBG').setStyle({width: Math.max(w + l, dw) + 'px'});
}

Event.observe(window, 'load', positionBanners);
Event.observe(window, 'resize', positionBanners);

/* --- /http://test.unserdaheim.at/templates/daheim/scripts/common.js --- */



/* --- http://test.unserdaheim.at/templates/daheim/scripts/selectbox.js --- */
function createBoxElement(prefix,text) {

	var thisDiv = prefix+'Div';
	var thisVal = prefix+'Value';
	//alert(thisDiv+'-'+thisVal);
	var ni = document.getElementById(thisDiv);
	var numi = document.getElementById(thisVal);
	var num = (document.getElementById(thisVal).value -1)+ 2;
	numi.value = num;
	var divIdName = prefix+''+num+"Div";
	var newdiv = document.createElement('div');
	newdiv.setAttribute("id",divIdName);
	newdiv.innerHTML = text;
	ni.appendChild(newdiv);
}//function

function removeBoxElement(prefix,divNum) {
	var thisDiv = prefix+'Div';
	var thisVal = prefix+'Value';

	var d = document.getElementById(thisDiv);
	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);
	var numi = document.getElementById(thisVal);
	var num = (document.getElementById(thisVal).value -1);
	numi.value = num;
}//function

function selectAll(selectBox,selectAll) {

	//<input type="button" name="Button" value="All" onclick="selectAll('select1',true)" />
	//<input type="button" name="Button" value="None" onclick="selectAll('select1',false)" />
	// have we been passed an ID
	if (typeof selectBox == "string") {
		selectBox = document.getElementById(selectBox);
	}
	// is the select box a multiple select box?
	if (selectBox.type == "select-multiple") {
		for (var i = 0; i < selectBox.options.length; i++) {
			selectBox.options[i].selected = selectAll;
		}
	}
}


// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//      http://www.mattkruse.com/javascript/selectbox/index.html
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// April 20, 2005: Fixed the removeSelectedOptions() function to
//                 correctly handle single selects
// June 12, 2003: Modified up and down functions to support more than
//                one selected option
/*
DESCRIPTION: These are general functions to deal with and manipulate
select boxes. Also see the OptionTransfer library to more easily
handle transferring options between two lists

COMPATABILITY: These are fairly basic functions - they should work on
all browsers that support Javascript.
*/


// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
		}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
		}
		else {
			return;
		}
		var re = new RegExp(regex);
		if (!hasOptions(obj)) { return; }
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
			}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
				}
			}
		}
	}
}

// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in.
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
}

// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
	}
	if (o.length==0) { return; }
	o = o.sort(
	function(a,b) {
		if ((a.text+"") < (b.text+"")) { return -1; }
		if ((a.text+"") > (b.text+"")) { return 1; }
		return 0;
	}
	);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	}
}

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
	}
}

// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
		}
	}
	// Move them over
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
			to.options[index] = new Option( o.text, o.value, false, false);
		}
	}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
		}
	}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
	}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
	var options = new Object();
	if (hasOptions(to)) {
		for (var i=0; i<to.options.length; i++) {
			options[to.options[i].value] = to.options[i].text;
		}
	}
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
				if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
				to.options[index] = new Option( o.text, o.value, false, false);
			}
		}
	}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(to);
	}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
	}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
	}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
	}
}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		copySelectedOptions(from,to);
	}
	else if (arguments.length==3) {
		copySelectedOptions(from,to,arguments[2]);
	}
}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
}

// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
			}
		}
	}
}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
			}
		}
	}
}

// -------------------------------------------------------------------
// removeSelectedOptions(select_object)
//  Remove all selected options from a list
//  (Thanks to Gene Ninestein)
// -------------------------------------------------------------------
function removeSelectedOptions(from) {
	if (!hasOptions(from)) { return; }
	if (from.type=="select-one") {
		from.options[from.selectedIndex] = null;
	}
	else {
		for (var i=(from.options.length-1); i>=0; i--) {
			var o=from.options[i];
			if (o.selected) {
				from.options[i] = null;
			}
		}
	}
	from.selectedIndex = -1;
}

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
function removeAllOptions(from) {
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) {
		from.options[i] = null;
	}
	from.selectedIndex = -1;
}

// -------------------------------------------------------------------
// addOption(select_object,display_text,value,selected)
//  Add an option to a list
// -------------------------------------------------------------------
function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
	}
}
/* --- /http://test.unserdaheim.at/templates/daheim/scripts/selectbox.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/validation.js --- */
function validateAddComment(id,submit){

	var formname = 'addcomment_'+id;
	var title    = $F('subject_'+id);
	var text     = $F('text_'+id);

	if(!title){
		$('subject_label_'+id).className = 'label labelTop error';
	}else{
		$('subject_label_'+id).className = 'label labelTop';
	}//if-else

	if(!text){
		$('text_label_'+id).className = 'label labelTop error';
	}else{
		$('text_label_'+id).className = 'label labelTop';
	}//if-else

	if(title && text && submit == 's') {
		document.forms[formname].submit();
	}//if

}//function


function isValidURL(url) {
	var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
	if(RegExp.test(url)) {
		return true;
	} else{
		return false;
	} // if-else
} // function

function checkIfSpaceIsInBeginningOfString(str) {
	var isspace = str.indexOf(" ");
	if(isspace == 0) {
		return false;
	} else {
		return true;
	} // if-else
} // if

function isValidName(str) {
	var search = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZß 1234567890äüöÄÜÖ';
	var error = 0;
	for (i=0; i<=str.length-1; i++) {
		zeichen = str.charAt(i);
		if (search.indexOf(zeichen)==-1) { // we found a special char
 		  error = 1;
		} // if
	} // for	
	
	if(error == 0) {
		return true;
	} else {
		return false;
	} // if-else

} // function

 
function validatereg() {
	var Errors="";
	var fname = false;
	var sname = false;
	var gender = false;
	var email = false;
	var password = false;
	var password1 = false;
	var bundesland = false;
	var bezirk = false;
	var stadt = false;
	var ort = false;
	var read = false;
	var captcha = false;

	apos=document.register.email.value.indexOf("@");
	dotpos=document.register.email.value.lastIndexOf(".")
	if(document.register.fname.value =="" || checkIfSpaceIsInBeginningOfString(document.register.fname.value) == false || isValidName(document.register.fname.value) == false) {
		document.getElementById('fname_label').className='label error';
		Errors += "- Es wurde kein Vorname eingegeben oder  dieser enth&auml;lt nicht erlaubte Sonderzeichen<br />";
		fname = false;
	} else {
		document.getElementById('fname_label').className='label';
		fname = true;
	} // if

	if(document.register.sname.value =="" || checkIfSpaceIsInBeginningOfString(document.register.sname.value) == false || isValidName(document.register.sname.value) == false) {
		document.getElementById('sname_label').className='label error';
		Errors += "- Es wurde kein Nachname eingegeben oder dieser enth&auml;lt nicht erlaubte Sonderzeichen<br />";
		sname = false;
	} else {
		document.getElementById('sname_label').className='label';
		sname = true;
	} // if

	if(document.register.gender.value =="") {
		document.getElementById('gender_label').className='label error';
		Errors += "- Es wurde kein Geschlecht angegeben <br />";
		gender = false;
	} else {
		document.getElementById('gender_label').className='label';
		gender = true;
	} // if

	if (document.register.email.value == "" || apos<1 || dotpos-apos<2)	{
		document.getElementById('email_label').className='label error';
		Errors += "- E-Mail Adresse wurde falsch eingegeben <br />";
		email = false;
	} else {
		document.getElementById('email_label').className='label';
		email = true;
	}
	if(document.register.password.value =="") {
		document.getElementById('Pass_label').className='label error';
		Errors += "- Es wurde kein Passwort eingegeben <br />";
		password = false;
	} else {
		document.getElementById('Pass_label').className='label';
		password = true;
	} // if

	if(document.register.password1.value != document.register.password.value || document.register.password1.value=="") {
		document.getElementById('PassRep_label').className='label error';
		Errors += "- Die Passwörter stimmen nicht überein <br />";
		password1 = false;
	} else {
		document.getElementById('PassRep_label').className='label';
		password1 = true;
	} // if

	if(document.register.bundesland.value =="" || document.register.bundesland.options[document.register.bundesland.options.selectedIndex].value == -1 || document.register.bundesland.options[document.register.bundesland.options.selectedIndex].value == "Bitte auswählen") {
		document.getElementById('bundesland_label').className='label error';
		Errors += "- Es wurde kein Bundesland ausgewählt <br />";
		bundesland = false;
	} else {
		document.getElementById('bundesland_label').className='label';
		bundesland = true;
	} // if

	if(document.register.bezirk.value =="" || document.register.bezirk.options[document.register.bezirk.options.selectedIndex].value == "Bitte auswählen" || document.register.bezirk.options[document.register.bezirk.options.selectedIndex].value == -1) {
		document.getElementById('bezirk_label').className='label error';
		Errors += "- Es wurde kein Bezirk ausgewählt <br />";
		bezirk = false;
	} else {
		document.getElementById('bezirk_label').className='label';
		bezirk = true;
	} // if

	if(document.register.gemeinde.value =="" || document.register.gemeinde.options[document.register.gemeinde.options.selectedIndex].value == "Bitte auswählen" || document.register.gemeinde.options[document.register.gemeinde.options.selectedIndex].value == -1) {
		document.getElementById('gemeinde_label').className='label error';
		Errors += "- Es wurde keine Gemeinde/Stadt ausgewählt <br />";
		stadt = false;
	} else {
		document.getElementById('gemeinde_label').className='label';
		stadt = true;
	} // if

	if(document.register.ort.value =="" || document.register.ort.options[document.register.ort.options.selectedIndex].value == "Bitte auswählen" || document.register.ort.options[document.register.ort.options.selectedIndex].value == -1) {
		document.getElementById('ort_label').className='label error';
		Errors += "- Es wurde kein Ort ausgewählt <br />";
		ort = false;
	} else {
		document.getElementById('ort_label').className='label';
		ort = true;
	} // if

	if(document.register.zustimmung.checked ==false) {
		document.getElementById('zustimmung_label').className='labelNoWidth error';
		Errors += "- Sie m&uuml;ssen den Zugangsbestimmungen zustimmen <br />";
		read = false;
	} else {
		document.getElementById('zustimmung_label').className='labelNoWidth';
		read = true;
	} // if-else


	if (document.register.captcha.value == "") {
		document.getElementById('captcha_label').className = 'labelNoWidth error';
		Errors += "- Es wurde kein Wort eingegeben <br />";
		captcha = false;
	}
	else {
		captcha = false;
		/*
		new Ajax.Request('/register/check/', {
		method: 'post',
		parameters: {
		id: document.register.captcha.value
		},
		onSuccess: function(transport){
		if (transport.responseText == "true") {
		document.getElementById('captcha_label').className = 'label';
		document.register.captca.value = transport.responseText;
		}
		else {
		document.getElementById('captcha_label').className = 'label error';
		}
		}
		});
		*/
	}
	if(document.register.captca.value == "true") {
		captcha = true;
	} // if

	if (fname && sname && gender && email && password && password1 && bundesland && stadt && ort && captcha && read) {
		return true;
	} else {
		document.getElementById('ErrorBox').style.display = "block";
		document.getElementById('Errors').innerHTML = Errors;
		return false;
	}//-if-else
}//function


function validateCaptcha(value){
	//alert ("validateCaptcha: "+value);
	new Ajax.Request('/register/check/', {
		method: 'post',
		parameters: {
			//id: document.register.captcha.value
			id: value
		},
		onSuccess: function(transport){
			if (transport.responseText == "true") {
				document.getElementById('captcha_label').className = 'labelNoWidth';
				document.register.captca.value = transport.responseText;
			}
			else {
				document.getElementById('captcha_label').className = 'labelNoWidth error';
			}
		}
	});
}

function validateCaptcha2(value,form){
	//alert ("validateCaptcha: "+value);
	new Ajax.Request('/register/check/', {
		method: 'post',
		parameters: {
			//id: document.register.captcha.value
			id: value
		},
		onSuccess: function(transport){
			if (transport.responseText == "true") {
				document.getElementById('captcha_label').className = 'label';
				form.captca.value = transport.responseText;
			}
			else {
				document.getElementById('captcha_label').className = 'label error';
				form.captca.value = 'false';
			}
		}
	});
}


function validateEmailAddress(email) {

	var AtPos = email.indexOf("@")
	var StopPos = email.lastIndexOf(".")

	var invalidChars = "\/'\\ \";:?!()[]\{\}^|#";
	for (i=0; i<invalidChars.length; i++) {
		if (email.indexOf(invalidChars.charAt(i),0) > -1) {
			return false;
		}//if
	}	//for

	if (email == "") {
		return false;
	}//if

	if (AtPos == -1 || StopPos == -1) {
		return false;
	}//if

	if (StopPos < AtPos) {
		return false;
	}//if

	if (StopPos - AtPos == 1) {
		return false;
	}//if

	return true;
}//function

function validateEinladungSenden(theform){
	if(validateEmailAddress(theform.einladungsenden_email.value)) {
		$('einladungsenden_subject_label').className = 'label labelTop pflichtfeld';
		var isemail = true;
	}else{
		$('einladungsenden_subject_label').className = 'label labelTop pflichtfeld error';
	}

	if(theform.einladungsenden_text.value != "") {
		$('einladungsenden_text_label').className = 'label labelTop pflichtfeld';
		var istext = true;
	}else{
		$('einladungsenden_text_label').className = 'label labelTop pflichtfeld error';
	}

	if(isemail && istext) {
		theform.submit();
	}


}


function validateFeedback(form) {

	var error = 0;

	if(form.name.value == '') {
		$('ihr_name_label').className = 'label labelTop pflichtfeld error';
		error = 1;
	} else {
		$('ihr_name_label').className = 'label labelTop pflichtfeld';
	} // if-else

	if(validateEmailAddress(form.email.value)) {
		$('ihre_email_label').className = 'label labelTop pflichtfeld';
	} else{
		$('ihre_email_label').className = 'label labelTop pflichtfeld error';
		error = 2;
	} // if-else

	if(form.subject.value != '') {
		$('betreff_label').className = 'label labelTop pflichtfeld';
	} else {
		$('betreff_label').className = 'label labelTop pflichtfeld error';
		error = 3;
	} // if-else

	if(form.wurstsemmel.value != '') {
		$('wurstsemmel_label').className = 'label labelTop pflichtfeld';
	} else {
		$('wurstsemmel_label').className = 'label labelTop pflichtfeld error';
		error = 4;
	} // if-else

	if(form.captca.value != 'true'){
		$('captcha_label').className = 'label error';
		error = 5;
	} else {
		$('captcha_label').className = 'label';
	} // if-else


	if(error == 0) {
		form.submit();
	} // if
}

function validate(value,id){
	//alert("here");
	// extract id of element
	var myID = id.substring(3, id.indexOf("-not_empty"));
	//alert(value+" : "+id+"= "+myID);
	//validateAddArticle('nosubmit'); //this give error "Microsoft JScript runtime error: Object expected"
	// commented by Radu Bighiu, why do we need validateAddArticle???
} // function validate


function validateNachrichtSchreiben(submit){
	//&& $('subject-not_empty').value != ""
	if( $('jumpMenu').value != "" && $('text-not_empty').value != "" && submit == 'submit' ) {
		if($('subject-not_empty').value == ""){
			$('subject-not_empty').value = 'Kein Betreff';
		}
		document.form_nachricht_schreiben.submit();

	}else{
		if($('jumpMenu').value == ""){
			$('jumpMenu_label').addClassName = 'error';
		}else{
			$('jumpMenu_label').removeClassName = 'error';
		}//if-else
		if($('subject-not_empty').value == "" && submit == 'submit'){
			$('subject-not_empty').value = 'Kein Betreff';
		}

		/*
		if($('subject-not_empty').value == ""){
		$('subject-not_empty_label').className = 'label labelTop pflichtfeld error';
		}else{
		$('subject-not_empty_label').className = 'label labelTop pflichtfeld';
		}//if-else
		*/
		if($('text-not_empty').value == ""){
			$('text-not_empty_label').className = 'label labelTop pflichtfeld error';
		}else{
			$('text-not_empty_label').className = 'label labelTop pflichtfeld';
		}//if-else

	}//if-else
}//function


function validateFriendmail(id){
		if($F(id) != "" && validateEmail($F(id)) == false) {
			$(id).style.color = 'red';
			$(id).style.borderColor="red";
			return false;
		}else{
			$(id).style.color = '';
			$(id).style.borderColor='';
			$('list2').style.borderColor='';
			return true;
		}	
}

function validateAllEmailFields(id) {
	
	if (!$(id)) return true;
	
	var inputs = $$('#'+id+' input');
	if (!inputs || inputs.length == 0) return true;
	
	myreturn = true;
	for(i=0;i<inputs.length;i++) {
		if (inputs[i].id == 'emailValue') continue;
		checkresult = validateFriendmail(inputs[i].id);
		if (!checkresult) myreturn = false;
	}
	return myreturn;
	
} // function

function validateVNachrichtSchreiben(submit){

	//alert($F('text-not_empty')+'\n'+submit);
	
	if(!$F('subject-not_empty')){
		$('subject-not_empty').value = 'Kein Betreff';
	}//if

	if( $F('text-not_empty') ) {

		$('text-not_empty_label').className = 'label labelTop pflichtfeld';
		if ($$('.friendmail'))
		var emails = $$('.friendmail');
		var validfriendmail = 'true';

		emails.each(function(w) {

			if(validateEmail(w.value) == false) {
				$(w.id).style.color = 'red';
				validfriendmail = 'false';
				//alert(w.value);
			}else{
				$(w.id).style.color = '';
				validfriendmail = 'true';
			}

		});

			
		if($F('list2')) {
			selectAll('list2', true);
			if($('friendmail0'))
			$('friendmail0').style.borderColor='';
			$('list2').style.borderColor='';			
		}
		
		if(validfriendmail && submit == 'submit' && ($F('list2') || emails[0].value != '')) {
			
			//$('form_nachricht_schreiben_id').action = '/organisation/Radio_KB/postfach/nachrichtschreiben/sendmail';
			$('form_nachricht_schreiben_id').submit();
			return true;
			
		}else if(!$F('list2') && emails[0].value == ''){
			$('list2').style.borderColor='red';
			$('friendmail0').style.borderColor='red';
		}

	}else{

		$('text-not_empty_label').className = 'label labelTop pflichtfeld error';

	}


	/*
	if($('subject-not_empty').value == ""){
	$('subject-not_empty_label').className = 'label labelTop pflichtfeld error';
	}else{
	$('subject-not_empty_label').className = 'label labelTop pflichtfeld';
	}//if-else
	*/



	//}//if-else
}//function

function validateVideo(value,id){
	// extract id of element
	var myID = id.substring(3, id.indexOf("-not_empty"));
	//alert(value+" : "+id+"= "+myID);
	validateAddVideo('nosubmit');
} // function validate

function validateFCK(eleid) {
	if (document.getElementById(eleid+'___Frame')) {
		var fck_frame = document.getElementById(eleid+'___Frame');
		var iFrame = (fck_frame.contentWindow || fck_frame.contentDocument);

		if (iFrame.document) {
			iFrame = iFrame.document;

			if (iFrame.getElementsByTagName('iframe')[0]) {
				var fck_textframe = iFrame.getElementsByTagName('iframe')[0];
				var textFrame = (fck_textframe.contentWindow || fck_textframe.contentDocument);

				if (textFrame.document) {
					textFrame = textFrame.document;
					var orig_text = document.getElementById(eleid).value.replace(/[\n\r]/g, "");
					var current_text = textFrame.getElementsByTagName('body')[0].innerHTML;
					current_text = current_text.replace(/[\n\r]/g, "").replace(/;"/g, '"').replace(/<b>/, "<strong>").replace(/<\/b>/, "</strong>");
          var orig_tags = orig_text.match(/(<\/?.*?>)/g);
              
              if (orig_tags) {
                for (var i = 0; i < orig_tags.length; ++i) {
                  orig_text = orig_text.replace(orig_tags[i], orig_tags[i].toLowerCase());
                }
              } // if
              
              var current_tags = current_text.match(/(<\s?\/?\s?[A-Z]+.*?>)/g);
              
              if (current_tags) {
                for (var i = 0; i < current_tags.length; ++i) {
                  current_text = current_text.replace(current_tags[i], current_tags[i].toLowerCase());
                } // for
              } // if
              
              //remove HTML tags for Mozilla
              current_text = current_text.replace(/(<([^>]+)>)/ig,""); 
              //remove HTML Entities and empty strings for IE
              current_text = current_text.replace(/(&\w+;)|(\s+)/ig,""); 
              //alert ("Orig: "+orig_text+"\n\nCurrent: "+current_text);
              
             //if (orig_text == current_text) {
             if (current_text == "" || current_text == "&nbsp;") {
            	 //alert ("Empty? : "+current_text);
                return false;
              } else {
                return true;
              } // if              
         } // if         
        } // if        
      } // if      
    } // if      
}//function


// validates if the comments are not empty
function validateComments() {
	var error = 0;
	
	if($('subject').value == '') {
		$('subject_label').className = 'label error';
		error = 1;
	} else {
		$('subject_label').className = 'label labelTop';
	} // if-else
	
	if($('text').value == '') {
		$('text_label').className = 'label error';
		error = 1;
	} else {
		$('text_label').className = 'label labelTop';
	} // if-else
	
	if(error == 1) {
		return 0;
	} // if
	
	return 1;
} // function

/* --- /http://test.unserdaheim.at/templates/daheim/scripts/validation.js --- */

/* --- http://test.unserdaheim.at/templates/daheim/scripts/validateMyForm.js --- */
/*
Validierungsmethoden (check_n):

Wert	Kurzform	Beschreibung
e	empty	 	das Element darf nicht leer sein
n	number		das Element muss eine Zahl sein
m	mail		eine E-Mail-Adresse muss formal richtig sein
r	regexp		der Wert soll ein bestimmtes Muster haben
p	price		der Wert soll in der Form "10,00" sein (mit Komma)
p.	price_dot	der Wert soll in der Form "10.00" sein (mit Punkt)
c	capitalize	Namen sollen korrigiert werden
x   crosscheck  Übereinstimmung von z.B. Passwörtern prüfen
s	spamcheck	Captcha Überprüfung
g	geodaten	Überprüft Daten einer Geoauswahl
a	rAdiobutton	Überprüft, ob ein Radiobutton ausgewählt wurde


WICHTIGE HINWEISE:

Um die Labels eindeutig identifizieren zu können, muss sich die ID eines Labels aus der Variable "labelPrefix" und dem "name" des zu validierenden Objekts zusammensetzen. Also z.B. var labelPrefix = "label_" und <input type="text" name="vorname" id="vorname"/> ergibt <label for="vorname" id="label_vorname">

Die zu validierenden Objekte sind im jeweiligen Template zu definieren.

Für den Crosscheck muss der Name des Kontrollfeldes gleich lauten wie das Eingabefeld und um eine Stelle erweitert werden. Z.B. "passwort" -> "passwort1" oder "passwortX"
*/


function validateMyForm(sender,myarray,err_hd){

// Werte nach eigenem Bedarf anpassen
var listDeco = "- "
var errorDiv = 'ErrorBox';
var errorList = 'Errors';
var labelPrefix = 'label_';

var error = false;
var err_msg = !err_hd?new Array(''):new Array(err_hd);

for (i=0;i<myarray.length;i++){
  field = document.forms[sender.name].elements[myarray[i][0]];
  fieldID = [myarray[i][0]];

/* Block 1 überprüft Felder, die ausgefüllt sein müssen */
  if (myarray[i][1].indexOf('e')>-1){
    if (!field.value || (field.type == 'checkbox' && field.checked == false)){
      error = true;
	  $(labelPrefix+fieldID).addClassName('error');
      err_msg.push(myarray[i][2]);
    } else {
	  $(labelPrefix+fieldID).removeClassName('error');
	}
  } // Block

/* Block 2 überprüft, ob die E-Mailadresse formal richtig ist */
  else if (myarray[i][1].indexOf('m')>-1) {
    if (field.value) {
      var usr = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
      var domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
      var regex = "^"+usr+"\@"+domain+"$";
      var myrxp = new RegExp(regex);
      var check = (myrxp.test(field.value));
        if (check!=true) {
          error=true;
		  $(labelPrefix+fieldID).addClassName('error');
          err_msg.push(field.value+" "+myarray[i][2]);
        } else {
		  $(labelPrefix+fieldID).removeClassName('error');
		}
      }
    } // Block

/* Block 3 überprüft Felder, deren Wert eine Zahl sein muss */
  else if (myarray[i][1].indexOf('n')>-1) {
    var num_error = false;
    if(field.value) {
      var myvalue = field.value;
      var num = myvalue.match(/[^0-9,\.]/gi)
      var dot = myvalue.match(/\./g);
      var com = myvalue.match(/,/g);
        if (num!=null) {
          num_error = true;
        }
        else if ((dot!=null)&&(dot.length>1)) {
          num_error = true;
        }
        else if ((com!=null)&&(com.length>1)) {
          num_error = true;
        }
        else if ((com!=null)&&(dot!=null)) {
          num_error = true;
        }
    }
    if (num_error==true) {
        error = true;
        err_msg.push(myvalue+" "+myarray[i][2]);
    }
  } // Block

/* Block 4 überprüft Wert anhand eines regulären Audrucks auf bestimmte Muster */
  else if (myarray[i][1].indexOf('r')>-1) {
    var regexp = myarray[i][3];
    if (field.value) {
      if (!regexp.test(field.value)) {
        error = true;
        err_msg.push(field.value+" "+myarray[i][2]);
      }
    }
  } // Block

/* Block 5 überprüft Felder, die als Preis formatiert sein müssen, ändert die Formatierung */
  else if (myarray[i][1].indexOf('p')>-1) {
    var myvalue = field.value;
    var reg = /,-{1,}|\.-{1,}/;
    var nantest_value = myvalue.replace(reg,"");
    var num = nantest_value.match(/[^0-9,\.]/gi)
    sep = myarray[i][1].substr(1,1)?myarray[i][1].substr(1,1):',';
    if (field.value) {
      var myvalue = field.value.replace(/\./,',');
      if (myvalue.indexOf(',')==-1) {
        field.value = myvalue+sep+'00';
      }
      else if (myvalue.indexOf(",--")>-1) {
        field.value = myvalue.replace(/,--/,sep+'00');
      }
      else if (myvalue.indexOf(",-")>-1) {
        field.value = myvalue.replace(/,-/,sep+'00');
      }
      else if (!myvalue.substring(myvalue.indexOf(',') + 2)) {
        error=true;
        err_msg.push(field.value+" "+myarray[i][2]);
      }
      else if (myvalue.substring(myvalue.indexOf(',') + 3)!='') {
        error=true;
        err_msg.push(field.value+" "+myarray[i][2]);
      }
      else if (num!=null) {
        error=true;
        err_msg.push(field.value+" "+myarray[i][2]);
      }
    }
  } // Block

/* Block 6 überprüft Namensfelder und korrigiert evtl. die Groß-/Kleinschreibung */
  else if (myarray[i][1].indexOf('c')>-1) {
    var noble = new Array("de","von","van","der","d","la","da","of");
    var newvalue='';
    var myvalue = field.value.split(/\b/);
	//alert(myvalue);
    for (k=0;k<myvalue.length;k++) {
      newvalue+= myvalue[k].substr(0,1).toUpperCase()+myvalue[k].substring(1);
    }
    for(k=0;k<noble.length;k++){
      var reg = new RegExp ("\\b"+noble[k]+"\\b","gi");
      newvalue = newvalue.replace(reg,noble[k]);
    }
    field.value = newvalue;
  } // Block

/* Block 7 überprüft die Übereinstimmung z.B. von Passwörtern */
  else if (myarray[i][1].indexOf('x')>-1) {
	var pfieldID = String(fieldID).substring(0,String(fieldID).length-1);
	if (field.value != $(pfieldID).value || field.value==''){
      error = true;
	  $(labelPrefix+fieldID).addClassName('error');
      err_msg.push(myarray[i][2]);
    } else {
	  $(labelPrefix+fieldID).removeClassName('error');
	}
  } // Block

/* Block 8 überprüft Captchas; benötigt den Wert captchaError der Funktion getMyCaptcha */
  else if (myarray[i][1].indexOf('s')>-1) {
	var value = field.value;
	if (captchaError == true || value == "") {
	  error = true;
	  $(labelPrefix+fieldID).addClassName('error');
	  err_msg.push(myarray[i][2]);
	} else {
	  $(labelPrefix+fieldID).removeClassName('error');
	}
  } // Block


/* Block 9 überprüft, ob die Geodaten korrekt ausgewählt wurden. */
  else if (myarray[i][1].indexOf('g')>-1) {
if(field.value =="" || field.options[field.options.selectedIndex].value == -1 || field.options[field.options.selectedIndex].value == "Bitte auswählen") {
		$(fieldID+"_label").addClassName('error');
		err_msg.push(myarray[i][2]);
		error = true;
	} else {
		$(fieldID+"_label").removeClassName('error');
	} // if
  } // Block
  
/* Block 10 überprüft, ob ein Radiobutton ausgwählt wurde. */

  else if (myarray[i][1].indexOf('a')>-1) {
  		
		// Radio Button Validation
		// copyright Stephen Chapman, 15th Nov 2004,14th Sep 2005
		// you may copy this function but please keep the copyright notice with it
		function valButton(rbt) {
		var cnt = -1;
		for (var i=rbt.length-1; i > -1; i--) {
			if (rbt[i].checked) {
				cnt = i; i = -1;
			}
		}
		if (cnt > -1) {
			return rbt[cnt].value;
		} else {
			return null;
		}
		}
		var rbt = valButton(field);

		if (rbt == null) {
			$(labelPrefix+fieldID).addClassName('error');
			err_msg.push(myarray[i][2]);
			error = true;
		} else {
			$(labelPrefix+fieldID).removeClassName('error');
		}
  } // Block
  
} // Ende for-Schleife

/* Gesammelte Ausgabe der Fehlermeldungen und Absenden des Formulars */
if (error) {
  if (errorDiv) {
	$(errorDiv).style.display="block";
    err_msg = err_msg.join(listDeco);
	if ($(errorList)) {
	  $(errorList).innerHTML = err_msg;
	}
  }
  return false;
} else {
  if (errorDiv) {
	$(errorDiv).style.display="none";
  }
  document.forms[sender.id].submit();
  return true;
}
}

var captchaError;
function getMyCaptcha(){
	new Ajax.Request('/register/check/', {
		method: 'post',
		parameters: {
			id: document.register.captcha.value
		},
		onSuccess: function(transport) {
			if (transport.responseText == "true") {
				captchaError = false;
				//document.register.captca.value = transport.responseText;
			} else {
				captchaError = true;
			}
		}
	});
}
/* --- /http://test.unserdaheim.at/templates/daheim/scripts/validateMyForm.js --- */

/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();

