

/*../vendor/carousel/lib/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();

/*common.js*/

/** 
 * @fileoverview This javascript file contains the common functions. 
 * @author Hardik Shah
 * @author Pankit Bhanushali
 * @version 0.1 
 */
var goToMap = false;
var imgThmPath = "../../wt/"+bkTheme+"/images/";
var isIE = document.all?1:0;
var isIE6 = (window.XMLHttpRequest)?0:1;
var usrAgt = navigator.userAgent.toLowerCase();
var isFF = (usrAgt.indexOf('firefox')!=-1)?1:0;
var isOpera = (usrAgt.indexOf('opera')!=-1)?1:0;
var isSafari = ((usrAgt.indexOf('safari')!=-1)&&(usrAgt.indexOf('mac')!=-1))?1:0;
//enables background image cache for internet explorer 6
if (isIE6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};
// Global Variables
//var leadEmailDlg1;
var maindivid	= 'middle';
var url			= '';
var queryString	= '';
var lastToggled	;
var sessid	= '';
var YAHOO;
var jsPath = '../../';
var totalImgs;
var latLong = '';
var isCountySearchEnabled = "0";
//lmsre specific
var lmsreDshbrdBitz= '{"mortgagerates" : "50","mcalc":"24","equity":"57","weather":"19","climate":"19","demographics" : "28","localnews" : "20","marketsnapshot":"46","crimestats":"49","valuehome":"58","afford":"51","localSearch":"39","crimestats":"49"}';
//var leadEmailDlg1;
/*metrospecific*/
var agtOffDlgBox = "";
var clientTime = new Date();
var ClientTimezoneOffset = (clientTime.getTimezoneOffset() / 60);
var month = clientTime.getMonth() + 1;
var day = clientTime.getDate();
var year = clientTime.getFullYear();
var hours = clientTime.getHours();
var min = clientTime.getMinutes();
var sec = clientTime.getSeconds();
var localTime = year + "-" + month + "-" + day+" "+hours+ ":" + min+ ":" + sec;

/**
 * set new session id
 *
 */
function setSessid()
{
	var queryString  = "PHPSESSID="+sessid;
	var url = jsPath+"../classes/sessionSwitch.php";
	ajaxRequest(url,queryString,setID);
};

function setID(originalRequest)
{
	sessid = originalRequest.responseText;
};
function pageReload(originalRequest)
{
	if(originalRequest==null)originalRequest="";
	window.location.href = window.location.pathname+window.location.search;
};
/**
 * This is the Ajax function that requests the url and loads the HT response to particular Div/container
 * @param {String} url The url called by the Ajax request
 * @param {String} queryString The parameter String passed to the url 
 * @param {String} inDiv The Div/Container in which the response to be set
 * @param {String} callbackfn The callback function name
 */
 
function loadToDiv(url,queryString,inDiv,callbackfn,classNm)
{

	if(classNm==null)
		classNm = false;
		
	inDiv = typeof(inDiv) != 'undefined' ? inDiv : maindivid; 
	if(queryString=='')
	{
		queryString = "PHPSESSID="+sessid;
	}
	else
	{
		queryString = "PHPSESSID="+sessid+"&"+queryString;
	}
	/*
	var callbackfn = function(myAjaxObjext)
	{
		alert(inDiv+" :: "+$(inDiv)+" :: "+$(inDiv).innerHTML);
		alert(myAjaxObjext.responseText);
	}
	*/ 
	if(callbackfn==null)
	{
		var objAjax = new Ajax.Updater({success: inDiv},url, {method: 'post', parameters: queryString, onFailure: showError,onlyLatestOfClass:classNm,evalScripts: true});
	}
	else
	{
		var objAjax = new Ajax.Updater({success: inDiv},url, {method: 'post', parameters: queryString, onFailure: showError,onlyLatestOfClass:classNm,onSuccess: callbackfn, evalScripts: true});
	}
};

/**
 * This is the Ajax function that request the particular url 
 * @param {String} url The url called by the Ajax request
 * @param {String} queryString The parameter String passed to the url 
 * @param {String} callbackfn The callback function name
 * @param {boolean} requestType The type of the request to be made should synchronous or asynchronous(default)
 */
 
function ajaxRequest(url,queryString,callbackfn,requestType,classNm)
{

	if(classNm==null)
		classNm = false;
		
	if(requestType==null)
	{
		requestType=true;
	}

	if(queryString=='')
	{
		queryString = "PHPSESSID="+sessid;
	}
	else
	{
		queryString = "PHPSESSID="+sessid+"&"+queryString;
	}
	if(typeof(callbackfn) == 'undefined')
	{
		var objAjaxReq = new Ajax.Request(url, {method: 'post',asynchronous:requestType, parameters: queryString, onlyLatestOfClass:classNm, onFailure: showError, evalScripts: true});
	}
	else
	{
		var objAjaxReq = new Ajax.Request(url, {method: 'post',asynchronous:requestType, parameters: queryString, onlyLatestOfClass:classNm, onFailure: showError, onSuccess: callbackfn, evalScripts: true});
	}
};

/**
 * Display the Error message when the Ajax request fails 
 * @param {String} originalRequest the request object
 */
function showError(originalRequest)
{
	if (originalRequest.status == 999)
	{
		window.location.href = "../auth/sessionExpire.php";
	}
	else
	{
		var response = originalRequest.responseText;
		$(maindivid).innerHTML = response;
		alert(response);
	}
};


/***********************General Section********************/

/**
 * Includes the single javaScript file dynamically
 * @param {String} jsFile the javscript filename
 */

function includeJS(jsFile, callBack)
{
	var fileName = jsFile.substr(eval(jsFile.lastIndexOf('/')+1),eval(jsFile.lastIndexOf('\.')-eval(jsFile.lastIndexOf('/')+1)));
	var myScript = $(fileName+"Script");
	if(fileName+"Script" == "mlsSrc.searchPs.template.jsScript")
	{
		myScript = null;
	}	
	if(myScript==null)
	{
		var myScr = document.createElement('script');
		myScr.id= fileName+"Script";
		myScr.src = jsFile;
		myScr.type = "text/javascript";
								
		if(typeof(callBack) != "undefined" && typeof(callBack) == "function")
		{
			myScr.onload = myScr.onreadystatechange = function(){
				if(this.readyState)
				{
					if(this.readyState == "loaded")
						callBack();
				}
				else
					callBack();
			}
		}
		document.getElementsByTagName('head')[0].appendChild(myScr);						
	}
};
/**
 * Includes the single css file dynamically
 * @param {String} cssFile the css filename
 */

function includeCSS(cssFile)
{
	var fileName = cssFile.substr(eval(cssFile.lastIndexOf('/')+1),eval(cssFile.lastIndexOf('\.')-eval(cssFile.lastIndexOf('/')+1)));
	var myStyle = $(fileName+"Css");
	
	if(myStyle==null)
	{
		var myCss = document.createElement('link');
		myCss.id= fileName+"Css";
		myCss.href = cssFile;
		myCss.rel = "stylesheet";
		myCss.type = "text/css";
		document.getElementsByTagName('head')[0].appendChild(myCss);
	}
};
/**
 * Includes the multiple css files dynamically
 * @param {Array} cssFileArr the array of css filenames
 */
function includeMultiCSS(cssFileArr)
{
	var insrtCssFileArr = $A(cssFileArr);
	insrtCssFileArr.each(function(node) {
		includeCSS(node);
	});
};

/**
 * Function for flipping images on mouse over
 * (Normal images should be with suffix '_n' and hoverimages should be with suffix '_h')
 * @requires changeImgOnHover The changeImgOnHover function
 */

function revealThumbnail()
{
	imgsrc = this.src;
	newimgsrc=(imgsrc.replace("_n","_h"));
	this.src=newimgsrc;
};

/**
 * Function for flipping images on mouse out
 * (Normal images should be with suffix '_n' and hoverimages should be with suffix '_h')
 * @requires changeImgOnHover The changeImgOnHover function
 */	
function hideThumbnail()
{
	imgsrc = this.src;
	newimgsrc=(imgsrc.replace("_h","_n"));
	this.src=newimgsrc;
};
/**
 * Function for Toggle Divs using Effect for showing details
 * @param {id} id current Div id to be opened
 */
var sameFlag = false;
function menuToggle(id)
{
    if (lastToggled == null || $(lastToggled) == null) 
	{
		//Effect.toggle(id,'blind',{duration:0.2});
		lastToggled = id;
		//Element.Toggle(id);
		$(id).style.display = "block";
    }
    else if (lastToggled == id) 
	{     		       
		//Effect.toggle(id,'blind',{duration:0.2});	
		//Element.Toggle(id);
		if(sameFlag==false)
		{
			$(id).style.display = "none";
			sameFlag = true;
		}
		else
		{
			$(id).style.display = "block";
			sameFlag = false;
		}
    }  
    else
	{
	   $(lastToggled).style.display = "none";
       lastToggled = id;
       $(id).style.display = "block";
    }
    
};


/**
 * InPlace Editor function for Textbox
 * @param {TextBox Id} elementId The current element ID
 * @param {Button Id}  edtBtn The button id
 * @param {fileToCommunicate} The file that is call on click of edit button
 */
function createInplaceEditorText(elementId,fileToCommunicate,fieldName,tableName,condition,edtBtn,validation,size)
{
	
	if(elementId==null || fileToCommunicate == null || fieldName==null || tableName == null || condition == null)
	{
		alert("Parameters missing: elementId, fileToCommunicate, fieldName, tableName, and condition are mandatory");	
	}
	else
	{
		
		if(validation==null){validation="";}
		
		if(edtBtn==null){edtBtn="";}
		
		if(size==null)
			var inplaceEditorTxt =new Ajax.InPlaceEditor(elementId, fileToCommunicate,{ clickToEditText : "You can Edit this by clicking on it.", callback: function(form, value) { return 'value=' + escape(value)+'&fieldName='+escape(fieldName)+'&tableName='+escape(tableName)+'&condition='+escape(condition) },validate:validation,externalControl:edtBtn,highlightcolor:'#74AACF'});
		else
			var inplaceEditorTxt =new Ajax.InPlaceEditor(elementId, fileToCommunicate,{ clickToEditText : "You can Edit this by clicking on it.", size:size, callback: function(form, value) { return 'value=' + escape(value)+'&fieldName='+escape(fieldName)+'&tableName='+escape(tableName)+'&condition='+escape(condition) },validate:validation,externalControl:edtBtn,highlightcolor:'#74AACF'});
	
		return inplaceEditorTxt;
	}
};

/**
 * InPlace Editor function for TextArea
 * @param {TextArea Id} elementId The current element ID
 * @param {Button Id}  edtBtn The button id
 * @param {fileToCommunicate} The file that is call on click of edit button
 */
function createInplaceEditorTextArea(elementId,fileToCommunicate,fieldName,tableName,condition,edtBtn)
{
	if(elementId==null || fileToCommunicate == null || fieldName==null || tableName == null || condition == null)
	{
		alert("Parameters missing: elementId, fileToCommunicate, fieldName, tableName, and condition are mandatory");	
	}
	else
	{
		if(Ajax.InPlaceEditor == null)
		{
			alert("Please include Scriptaculous.js from vendor folder for using inplace Editor");
		}
		else
		{
			if(edtBtn==null){edtBtn="";}
			var inplaceEditorTA = new Ajax.InPlaceEditor(elementId, fileToCommunicate, { clickToEditText : "You can Edit this by clicking on it.", callback: function(form, value) { return 'value=' + escape(value)+'&fieldName='+escape(fieldName)+'&tableName='+escape(tableName)+'&condition='+escape(condition) },externalControl:edtBtn,rows:4,cols:60,highlightcolor:'#74AACF'});
			return inplaceEditorTA;
		}
	}
};

/**
 * InPlace Editor function for ComboBox
 * @param {ComboBox Id} elementId The current element ID
 * @param {Button Id}  edtBtn The button id
 * @param {fileToCommunicate} The file that is call on click of edit button
 */
function createInplaceEditorCombo(elementId,fileToCommunicate,optionArray,fieldName,tableName,condition,edtBtn)
{
	if(elementId==null || fileToCommunicate == null || fieldName==null || tableName == null || condition == null)
	{
		alert("Parameters missing: elementId, fileToCommunicate, fieldName, tableName, and condition are mendatory");	
	}
	else
	{
		if(Ajax.InPlaceEditor == null)
		{
			alert("Please include Scriptaculous.js from vendor folder for using inplace Editor");
		}
		else
		{
			var queryString = '&combo=1&fieldName='+escape(fieldName)+'&tableName='+escape(tableName)+'&condition='+escape(condition);
			if(edtBtn==null){edtBtn=""}
			var inplaceEditorTA = new Ajax.InPlaceCollectionEditor (elementId,fileToCommunicate,{collection:optionArray, ajaxOptions: {parameters: queryString },externalControl:edtBtn,highlightcolor:'#74AACF'} );
			return inplaceEditorTA;
		}
	}
};

function StringBuffer() { this.buffer = []; }
StringBuffer.prototype.append = function(string)
{
	this.buffer.push(string);
	return this;
}

StringBuffer.prototype.toString = function()
{
	return this.buffer.join("");
}

// YUI Related Functions 
/**
 * Create the YAHOO Panel dynamically
 * @param {id} elid The div id of the Yahoo Panel
 * @return Panel object
 */
 function setDlgPos(elid)
{
	
	if(elid=="initWithMe")
		return;
	if($(elid))
	{
		var f_cw = f_clientWidth();
		var f_ch = f_clientHeight();
		var el_H = $(elid).getHeight();
		var el_W = $(elid).getWidth();
		$(elid).style.position = "static";
		$(elid).style.top = eval(Math.abs(f_ch/2) - Math.abs(el_H/2))+"px";
		$(elid).style.left = eval(Math.abs(f_cw/2) - Math.abs(el_W/2))+"px";
		var myObj = document.getElementsByClassName('underlay');
		if(myObj != null)
		{
			var myLen = myObj.length;
			for(var i=0;i<myLen;i++)
			{
				myObj[i].removeClassName('underlay');
			}
		}			
	}	
}
function createDialog(elid)
{
	var useShim;
	var ua = navigator.userAgent.toLowerCase();
	if (isIE){
		useShim = true;
	}else{
		useShim = false;
		setDlgPos(elid);
	}
	if(YAHOO==null)
	{
		alert("Please include yahoo.js");
	}
	else
	{			
		dlgBox = new YAHOO.widget.Panel(elid, {modal:true, visible:false, fixedcenter:true, constraintoviewport:true, shim:useShim, draggable:false} );
		dlgBox.render();
		if (!isIE6)
			dlgBox.beforeShowEvent.subscribe(function(){setDlgPos(elid);}, this);					
		return dlgBox;
	}
};

/**
 * Create the YAHOO TabView dynamically
 * @param {id} parentDiv The div id that will contain the Tabs
 * @param {Array} keyValArr the Key:Value paired array of Labels:Urls
 * @param {String} orientation the Tab Orientation ie. left,right,top or bottom
 * @return TabView object
 */
function loadTabs(parentDiv,keyValArr,orientation,noOfTabs)
{
	if(noOfTabs!=null)
	{
		loadTabsDynamically(parentDiv,keyValArr,orientation,noOfTabs);
		return;
	}
	orientation = typeof(orientation) != 'undefined' ? orientation : 'top';

	var hashArrLabels = $A($H(keyValArr).keys());
	var hashArrURLs   = $A($H(keyValArr).values());

    var tabView = new YAHOO.widget.TabView({id: parentDiv , orientation: orientation});
    var activate = false;
	for(i=0;i<hashArrLabels.length;i++)
	{
		if(i==0)
			activate = true;
		else
			activate = false;

		if(hashArrURLs[i]==null || hashArrURLs[i]=="")
		{
			dataSource = hashArrURLs[i];
		}
		else
		{
			if(hashArrURLs[i].search(/\?/)<0)
			{
				dataSource = hashArrURLs[i]+"?PHPSESSID="+sessid;
			}
			else
			{
				dataSource = hashArrURLs[i]+"&PHPSESSID="+sessid;
			}
		}
		tabView.addTab(new YAHOO.widget.Tab({
			label: hashArrLabels[i],
			dataSrc: dataSource,
			active: activate,
			cacheData: false /******************To be kept true in production *************/
	 	 }));
	}
    
    YAHOO.util.Event.onContentReady(parentDiv, function() {
        tabView.appendTo(parentDiv);
    });
    
  	for(i=0;i<$A($H(keyValArr)).length;i++)
	{
		tabView.getTab(i).addListener('contentChange',function (){
				this.get('content').evalScripts();
			});
	}
	return tabView;
};

var start = 1;
function addTabs(tabElem,keyValArr,enableArr)
{
	var hashArrLabels = $A($H(keyValArr).keys());
	var hashArrURLs   = $A($H(keyValArr).values());

	for(i=0;i<hashArrLabels.length;i++)
	{

		tabElem.addTab(new YAHOO.widget.Tab({
			label: hashArrLabels[i],
			dataSrc: hashArrURLs[i],
			active: true,
			disabled : enableArr[i],
			cacheData: false /******************To be kept true in production *************/
	    }));
	}
	var noOfTabs = 0;
	while(tabElem.getTab(noOfTabs))
	{
		noOfTabs = noOfTabs + 1;
	}
	for(i=1;i<noOfTabs;i++)
	{
		tabElem.getTab(i).addListener('contentChange',function (){
					this.get('content').evalScripts();
			});

	}
	return tabElem;
};
/************************************************************************/
/**
* Create Custom Confirm Dialog Box
*/
		var popupMessageBoxForm;
    function popupMessageBox (title, message, icon, buttons,wth,hgt) 
    {
    		if(!wth || wth == null)
    			wth = "300px";
    		if(!hgt || hgt == null)
    			hgt = "100px";
        // our container must exist for this to work				
        if (!YAHOO.util.Dom.inDocument('popupMessageBoxContainer'))
					return;
				
        // create the confirm dialog
        var ybuttons = [];
        for (var i=0; i<buttons.length; i++) 
        {
            ybuttons[i] = { text:buttons[i].label, handler:buttons[i].func, isDefault:(i==0?true:false) };
        }

	    	popupMessageBoxForm = new YAHOO.widget.SimpleDialog("popupMessageBoxContainer1", 
				{
	            modal: true,
	     			  width: wth+"px",
	     			  height:hgt+"px",
	            fixedcenter: true,
	            visible: false,
	            draggable: false,
	            close: true,
	            text: message,
	            icon: icon,
	            constraintoviewport: true,
	            buttons: ybuttons
	           
	      });
		    popupMessageBoxForm.setHeader(title);
		    popupMessageBoxForm.render("popupMessageBoxContainer");     
		    popupMessageBoxForm.show();

    }

    function popupMessageBoxHide() 
    {
        popupMessageBoxForm.hide();
    }

    function YAlert (title, msg, icon,button,wth,hgt) 
    {
        if (icon === undefined) icon = YAHOO.widget.SimpleDialog.ICON_ALARM;
        popupMessageBox (title, msg, icon,[{label:button,func:popupMessageBoxHide}],wth,hgt);        
    }

    function YConfirm (msg, yeshandler,nohandler,button1,button2,wth,hgt) 
    {
        popupMessageBox('Please Confirm...', msg,YAHOO.widget.SimpleDialog.ICON_HELP, [{label:button1,func:function(){popupMessageBoxHide();yeshandler();}},{label:button2,func:function(){popupMessageBoxHide();nohandler();}}],wth,hgt);
    } 
/************************************************************************/    
/** 
 * Function that returns the string in particular Language
 * @param {String} str The string to be converted in the selected language
 * @return String of the language currently set. 
 */

function getText(str) /* Returns Related Language from Language Array String */
{
	//below line, which uses Localisation variable, is commented by pratik as hardik removed line for loading of individual Language.JS file in code clean up
	//if (Localisation[str]) str = Localisation[str];
	return str;
};

/**************************Added Without Comments *******************/
function _alert(str) 
{
	alert(getText(str));
};
function _confirm(str)
{
	return confirm(getText(str));
};

/*************************Added Functions ************************/
/**
 * @author Shah Pratik
 * @date 31/01/2007
 * @param {String | Int} search string or integer
 * @return {boolean} return index of needle if needle is found in array else return false
 */
Array.prototype.in_array = function ( needle ) 
{
	var len = this.length;
	for ( var x = 0 ; x <= len ; x++ ) 
	{
		if ( this[x] == needle ) 
		{
			return x;
		}
	}
	return false;
};

/**
 * Function that sets the cookie.
 * @author Sanjev Dutta
 * @date 31/01/2007
 * @param {String} name of the cookie
 * @param {String} value of the cookie
 * @param {String} expires expiry time for the cookie
 * @param {String} path path
 * @param {String} domain domain
 * @param {String} secure Secure cookie (SSL)
 */
function setCookie(name, value, expires, path, domain, secure)
{
	//alert(name+" "+value);
	if (name == "msgboxCK" || name == "msgboxCKSignin" || name == "msgboxtutorialcook" || name == "rememberIdPassword" || name == "Cpanel_rememberIdPassword" || name == "pv" || name == "strWidgetCookie")
	{
		if (expires)
		{
			expires = expires.toGMTString();
		}
	}
	else
		expires = null;

  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires : "") +
      ((path) ? "; path=" + path : "; path=/") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
};

/**
 * Function that gets the cookie value for given name.
 * @author Sanjev Dutta
 * @date 31/01/2007
 * @param {String} name of the cookie
 * @return (String) returns the value for the given cookie name.
 */
function getCookie(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;
	var returnCookie = unescape(dc.substring(begin + prefix.length, end));
	if((returnCookie == null) || (returnCookie == 'null'))
	{
		returnCookie = "";
	}

	return returnCookie;
	
};

/**
 * Function that deletes the cookie.
 * @author Sanjev Dutta
 * @date 31/01/2007
 * @param {String} name of the cookie
 * @param {String} path path
 * @param {String} domain domain
 * @return (void)
 */
function deleteCookie(name, path, domain)
{
	if (getCookie(name))
	{
		document.cookie = name + "=" + ((path) ? "; path=" + path : "path=/") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
};
/********in place editor code******/


/******************************** Thanks To Scriptaculaus****************************/
// script.aculo.us effects.js v1.7.0_beta2, Mon Dec 18 23:38:56 CET 2006

// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

/************************** Ajax Inplace Editor ********************************/	
Ajax.InPlaceEditor = Class.create();
Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlaceEditor.prototype = {
  initialize: function(element, url, options) {
    this.url = url;
    this.element = $(element);

    this.options = Object.extend({
      paramName: "value",
      okButton: true,
      okText: "Save",
      cancelLink: true,
      cancelText: "Cancel",
      savingText: "Saving...",
      clickToEditText: "Click to edit",
      rows: 1,
      onComplete: function(transport, element) {
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      },
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      handleLineBreaks: true,
      loadingText: 'Loading...',
      savingClassName: 'inplaceeditor-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'inplaceeditor-form',
      highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
      highlightendcolor: "#E2E2DF",
      externalControl: null,
      submitOnBlur: false,
      ajaxOptions: {},
      evalScripts: false
    }, options || {});

    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplaceeditor";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }
    
    if (this.options.externalControl) {
      this.options.externalControl = $(this.options.externalControl);
    }
    
    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }
    
    this.element.title = this.options.clickToEditText;
    
    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'click', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    if (this.options.externalControl) {
      Element.hide(this.options.externalControl);
    }
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    // stop the event to avoid a page refresh in Safari
    
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    var uid = this.options.formId;
	var arrid = uid.split('-');    
    var txtid = arrid[0];
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this,txtid);

    this.createEditField();

    if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }

    if (this.options.okButton) {
      okButton = document.createElement("a");
      //okButton.type = "#";
	  okButton.href = "#";
	  okButton.appendChild(document.createTextNode(this.options.okText));
	  okButton.onclick = this.onSubmit.bind(this);	  
      okButton.value = this.options.okText;
      okButton.className = 'editor_ok_button';
	  okButton.style.fontSize  = '13px';
	  //okButton.style.height ='17px';
	  //okButton.style.paddingTop = '0px' ;
	  this.form.appendChild(okButton);
    }
    if (this.options.cancelLink) {
      cancelLink = document.createElement("a");
      cancelLink.href = "#";
      cancelLink.appendChild(document.createTextNode(this.options.cancelText));
      cancelLink.onclick = this.onclickCancel.bind(this);
      cancelLink.style.fontSize  = '13px';
	  cancelLink.style.fontWeight  = 'normal';
	  cancelLink.className = 'editor_cancel';      
	  this.form.appendChild(cancelLink);
    }
  },
  hasHTMLLineBreaks: function(string) {
    if (!this.options.handleLineBreaks) return false;
    return string.match(/<br/i) || string.match(/<p>/i);
  },
  convertHTMLLineBreaks: function(string) {
    return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
  },
  createEditField: function() {
    var text;
    if(this.options.loadTextURL) {
      text = this.options.loadingText;
    } else {
    	if(this.getText()=="none")
    	 	text="";
    	else
      		text = this.getText();
    }

    var obj = this;
    
    if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
      this.options.textarea = false;
      var textField = document.createElement("input");
      textField.obj = this;
      textField.type = "text";
      textField.name = this.options.paramName;
      textField.value = text;
      textField.style.backgroundColor = this.options.highlightcolor;
      textField.className = 'editor_field';
      textField.style.backgroundColor = 'white';
      var size = this.options.size || this.options.cols || 0;
      if (size != 0) textField.size = size;
      if (this.options.submitOnBlur)
        textField.onblur = this.onSubmit.bind(this);
      this.editField = textField;
    } else {
      this.options.textarea = true;
      var textArea = document.createElement("textarea");
      textArea.obj = this;
      textArea.name = this.options.paramName;
      textArea.value = this.convertHTMLLineBreaks(text);
      textArea.rows = this.options.rows;
      textArea.cols = this.options.cols || 40;
      textArea.className = 'editor_field_ta';   
      textArea.style.backgroundColor = 'white';   
      if (this.options.submitOnBlur)
        textArea.onblur = this.onSubmit.bind(this);
      this.editField = textArea;
    }
    
    if(this.options.loadTextURL) {
      this.loadExternalText();
    }
    this.form.appendChild(this.editField);
  },
  getText: function() {
    return this.element.innerHTML;
  },
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onLoadedExternalText: function(transport) {
    Element.removeClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = false;
    this.editField.value = transport.responseText.stripTags();
    Field.scrollFreeActivate(this.editField);
  },
  onclickCancel: function() {
  	var erArr = document.getElementsByClassName("errMsg")
	$A(erArr).each(function(node){
			node.innerHTML="&nbsp;";
	});
  	if(this.editField.value=="")
  	{
  		this.editField.value=="none"
  	}
  	if ($('selTag'))
  	{
	  	if($('selTag').options[$('selTag').selectedIndex].value=="A" && $('divOH')!=null)
	  		$('divOH').style.display = "none";
  	}  	
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  onSubmit: function(id,id2) {
	var erArr;
  	if(!this.validate(id))
  	{
  		if(navigator.appName=="Microsoft Internet Explorer")
		  	this.editField.className = "textboxRedIn";
		 else
		 	this.editField.style.border = "1px solid red";
  		
  		erArr = document.getElementsByClassName("errMsg")
  		$A(erArr).each(function(node){
				node.innerHTML=alertErrorMsg;
  		});
  		
  		return false;
  	}
  	else
  	{
  		erArr = document.getElementsByClassName("errMsg")
  		$A(erArr).each(function(node){
				node.innerHTML="&nbsp;";
  		});
	    // onLoading resets these so we need to save them away for the Ajax call
	    var form = this.form;
	    var value = this.editField.value;
	    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
	    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
	    // to be displayed indefinitely
	    this.onLoading();
	    if (this.options.evalScripts) {
	    	this.options.ajaxOptions.parameters = this.options.callback(form, value);
	      new Ajax.Request(
	        this.url, Object.extend({
	          parameters: this.options.callback(form, value),
	          onComplete: this.onComplete.bind(this),
	          onFailure: this.onFailure.bind(this),
	          asynchronous:true, 
	          evalScripts:true
	        }, this.options.ajaxOptions));
	    } else  {
    	 this.options.ajaxOptions.parameters = this.options.callback(form, value);
	      new Ajax.Updater(
	        { success: this.element,
	          // don't update on failure (this could be an option)
	          failure: null }, 
	        this.url, Object.extend({
	          parameters: this.options.callback(form, value),
	          onComplete: this.onComplete.bind(this),
	          onFailure: this.onFailure.bind(this)
	        }, this.options.ajaxOptions));
	    }
	    // stop the event to avoid a page refresh in Safari
	    if (arguments.length > 1) {
	      Event.stop(arguments[0]);
	    }
	    return false;
  	}
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    this.element.style.backgroundColor = this.options.highlightcolor;
    if (this.effect) {
      this.effect.cancel();
    }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    if (this.options.backgroundColor) {
      this.element.style.backgroundColor = this.oldBackground;
    }
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
    this.effect = new Effect.Highlight(this.element, {
      startcolor: this.options.highlightcolor,
      endcolor: this.options.highlightendcolor,
      restorecolor: this.originalBackground
    });
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
    if (this.options.externalControl) {
      Element.show(this.options.externalControl);
    }
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
    this.onLeaveEditMode();
  },
  onComplete: function(transport) {
    this.leaveEditMode();
    this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {
  		onLeaveEditMd = window.onLeaveEditMd || false;
  	    if(onLeaveEditMd==false)
  	    	return;
  	    else
	    	onLeaveEditMd();
  },
  
  validate:function(id)
  {
	    validArg=this.options.validate;
		if(validArg!="" && typeof(validArg)!="undefined" && validArg!=null)
			id=validArg;
		
		switch(id)
		{
			case "ufname" : 
				return this.editField;
				break; 

			case "umname" : 
				return this.editField;
				break; 

			case "ulname" : 
				return this.editField;
				break; 

			case "name" : 
				return (isBlank(this.editField,"value"))
				break; 
				
			case "uemail":
			case "email":
				return emailIsValid(this.editField);
				break;

			case "ualtemail":
				return chkOnlyEmailIsValid(this.editField);
				break;

			case "uMobile":
			case "cell":
				return (mobileIsValid(this.editField,"Number"));
				break;

			case "uPhone":
			case "phone":
				return (phoneIsValid(this.editField,"Number"));
				break;

			case "uFax":
			case "fax":
				return (faxIsValid(this.editField,"Number"));
				break;
			case "site":
				return isValidURL(this.editField);
				break;
				
			case "uZip":
			case "zip":
				return zipIsValid(this.editField,"msg");
				break;
			
			case "uCity":
				//return isOfLength(this.editField,2);
				return albhabetIsValid(this.editField,"Only alphabets allowed.","City ");
				break;

			case "uState":
			case "state":
				//return isOfLength(this.editField,2);
				return albhabetIsValid(this.editField,"Only alphabets allowed.","State ",2,2);
				break;
			case "year":
				return isYear(this.editField);
				break;
			case "room":
				return (isOfLength(this.editField,3,"max") && numberIsValid(this.editField,"Enter valid Number",""));
				break;
			case "sqft":
				return isSqft(this.editField);
				break;
			default:
				return true;
		}
  	},  
 
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    Event.stopObserving(this.element, 'click', this.onclickListener);
    Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};


/************************** Ajax Inplace Editor Ends ********************************/	
/***************************Ajax Inplace collectin Editor*******************************/

Ajax.InPlaceCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
createEditField: function() {
if (!this.cached_selectTag) {
var selectTag = document.createElement("select");
selectTag.id = "selTag";
var collection = this.options.collection || [];
var optionTag;
collection.each(function(e,i) {
optionTag = document.createElement("option");
optionTag.value = (e instanceof Array) ? e[0] : e;
if((typeof this.options.value == 'undefined') &&
((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
if(this.options.value==optionTag.value) optionTag.selected = true;
optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
selectTag.appendChild(optionTag);
}.bind(this));
this.cached_selectTag = selectTag;
}
this.editField = this.cached_selectTag;
if(this.options.loadTextURL) this.loadExternalText();
this.form.appendChild(this.editField);

value2 = this.options.ajaxOptions.parameters;
//alert(value2);
this.options.callback = function(form, value) {
	if(value2.indexOf('value=')>=0)
	{
		value2 = value2.substr(value2.indexOf('&'),eval(value2.length-value2.indexOf('&')))
	}
	newVal = "value=" + encodeURIComponent(value)+value2;
//alert(newVal);	
	//this.options.ajaxOptions.parameters = "value=" + encodeURIComponent(value)+value2;
return newVal;
}
}
});


/*******************************Ajax Inplace collectin Editor Ends********************************/
/************************** Basic Effect For Inplace Editor *********************************/
String.prototype.parseColor = function() {  
  var color = '#';
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
};

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

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
  return element;
};

Element.getOpacity = function(element){
  return $(element).getStyle('opacity');
};

Element.setOpacity = function(element, value){
  return $(element).setStyle({opacity:value});
} ; 
 
Element.getInlineOpacity = function(element){  
  return $(element).style.opacity || '';
};

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

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

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
};

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

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  tagifyText: function(element) {
    if(typeof Builder == 'undefined')
      throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
      
    var tagifyStyle = 'position:relative';
    if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || {});
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;

    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    if(!this.interval) 
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    this.effects.invoke('loop', timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  duration:   1.0,   // seconds
  fps:        60.0,  // max. 60fps due to Effect.Queue implementation
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
};



Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  start: function(options) {
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn + (this.options.duration*1000);
    this.event('beforeStart');
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
  	  	
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
      var frame = Math.round(pos * this.options.fps * this.options.duration);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  render: function(pos) {
    if(this.state == 'idle') {
      this.state = 'running';
      this.event('beforeSetup');
      if(this.setup) this.setup();
      this.event('afterSetup');
    }
    if(this.state == 'running') {
      if(this.options.transition) pos = this.options.transition(pos);
      pos *= (this.options.to-this.options.from);
      pos += this.options.from;
      this.position = pos;
      this.event('beforeUpdate');
      if(this.update) this.update(pos);
      this.event('afterUpdate');
    }
  },
  cancel: function() {
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
};

/************************** Basic Effect For Inplace Editor Ends *********************************/

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
  	if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = Math.round(width) + 'px';
    if(this.options.scaleY) d.height = Math.round(height) + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});


Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {
      backgroundImage: this.element.getStyle('background-image') };
    this.element.setStyle({backgroundImage: 'none'});
    if(!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});



Effect.BlindUp = function(element) {
	
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || {})
  );
};

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: false,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
      if(effect.element.id=="toggleDiv" && isIE)
      	setTimeout(function(){effect.element.style.display="block";},200);
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || {}));
};


Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || {})
  );
};

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
      effect.element.down().undoPositioned();
    }
   }, arguments[1] || {})
  );
};



/************************************Slide Show Related *****************************************/



	var displayWaitMessage=true;	// Display a please wait message while images are loading?
	var activeImage = false;
	var imageGalleryLeftPos = false;
	var imageGalleryWidth = false;
	var imageGalleryObj = false;
	var maxGalleryXPos = false;
	var slideSpeed = 0;
	var imageGalleryCaptions = new Array();
	function startSlide(e)
	{
		//alert('start slide');
		slideSpeed = 0;
		if(document.all)e = event;
		var id = this.id;
		if(this.getElementsByTagName('IMG')[0].src.indexOf('Over')<0)
			this.getElementsByTagName('IMG')[0].src = this.getElementsByTagName('IMG')[0].src.replace('.gif','Over.gif');
		if(this.id=='arrowRight'){
			slideSpeed = -4;
		}else{
			slideSpeed = 6;
		}
	};
	
	function releaseSlide()
	{
		var id = this.id;
		
		this.getElementsByTagName('IMG')[0].src = this.getElementsByTagName('IMG')[0].src.replace('Over','')			
		slideSpeed=0;
	};
	function fastSlide(event)
	{

		var arrow = Event.element(event).parentNode.id;
		imageGalleryWidth = $('galleryContainer').offsetWidth - 80;
		if(arrow.search('Left') != -1)
		{
			var leftPos = imageGalleryObj.offsetLeft;
				leftPos = leftPos + imageGalleryWidth;
			if(leftPos>maxGalleryXPos)
			{				
				leftPos = maxGalleryXPos;
			}
			if(leftPos<minGalleryXPos)
			{
				leftPos = minGalleryXPos;
			}
			
			imageGalleryObj.style.left = leftPos + 'px';
		}
		else
		{
			
			var leftPos = imageGalleryObj.offsetLeft;
				leftPos = leftPos - imageGalleryWidth;
			if(leftPos>maxGalleryXPos)
			{
				leftPos = maxGalleryXPos;
			}
			if(leftPos<minGalleryXPos)
			{
				leftPos = minGalleryXPos;
			}
			imageGalleryObj.style.left = leftPos + 'px';
		}
	}
	function gallerySlide()
	{
		
		if(slideSpeed!=0){
			var leftPos = imageGalleryObj.offsetLeft;
				
			leftPos = eval(leftPos + slideSpeed);
			
			if(leftPos>maxGalleryXPos){
				
				leftPos = maxGalleryXPos;
				slideSpeed = 0;
			}
			if(leftPos<minGalleryXPos){
				leftPos = minGalleryXPos;
				slideSpeed=0;
				//alert("here else");
			}
			
			imageGalleryObj.style.left = leftPos + 'px';
		}
		setTimeout('gallerySlide()',20);
		
	};
	
	function initSlideShow()
	{
		if($('arrowLeft')&& $('arrowRight'))
		{
			
			$('arrowLeft').onmousemove = startSlide;
			$('arrowLeft').onmouseout = releaseSlide;
			$('arrowRight').onmousemove = startSlide;
			$('arrowRight').onmouseout = releaseSlide;
			
			Event.observe($('arrowLeft'), 'click', function(event) {
				fastSlide(event);
			});
			Event.observe($('arrowRight'), 'click', function(event) {
				fastSlide(event);
			});
		}
		totalImgs = $A(document.getElementsByClassName('dashIconsDrag')).length;
		imageGalleryObj = $('theImages');
		imageGalleryLeftPos = imageGalleryObj.offsetLeft;
		imageGalleryWidth = $('galleryContainer').offsetWidth - 80;
		
		maxGalleryXPos = imageGalleryObj.offsetLeft; 
		minGalleryXPos = imageGalleryWidth - $('slideEnd').offsetLeft;		
		
		if(isIE)
		{
		
			var arrAllIcons = $('divIconCollect').getElementsByTagName('img');
			var lenAllIcons = arrAllIcons.length;
			//alert(lenAllIcons);
			var widthImages = 0;
			for(var i =0;i<lenAllIcons;i++)
			{
				var divWidth = $(arrAllIcons[i].id.replace('img','divImg')).style.width.replace('px','');
				divWidth = (isNaN(parseInt(divWidth)))?0:parseInt(divWidth); 
				widthImages = widthImages + divWidth;
			}
					//alert("widthImages : " + widthImages);	
			minGalleryXPos = imageGalleryWidth - widthImages;
			maxGalleryXPos = imageGalleryObj.offsetLeft;
			//minGalleryXPos += 1550;
		}
		
		var slideshowImages = imageGalleryObj.getElementsByTagName('IMG');
		for(var no=0;no<slideshowImages.length;no++){
			slideshowImages[no].onmouseover = revealThumbnail;
			slideshowImages[no].onmouseout = hideThumbnail;
		}
		gallerySlide();
	};
	
/***********************************************End Slide Show*********************************/







function selectAll(parentdiv,all,myObj)
{
	if(all==null)
		all = true;

	if(myObj!=null && myObj.checked)
		all = true;
	else
		all = false;
		
	chkbxArr = $A($(parentdiv).getElementsByTagName("input"));
	chkbxArr.each(
		function(node)
		{
			if(node.type=="checkbox")
				node.checked=all;
		});
};

/******************Number To Money Format******************/
function num2money(n_value,prefix,elementId,dec,retval)
{
	
	dec = (dec)?dec:false;
	retval = (retval)?true:false;
	oNval = n_value.toString();
	if(typeof(n_value) == "string")
	{
		n_value = money2num(n_value);
	}
	if(n_value=="")
	{
		if(elementId!=null)
		{
			if($(elementId).type == "text")
			{
				if(retval)
				{
					$(elementId).value = "";
				}
				else
				{
					$(elementId).value = prefix+"0";
				}
			}
		else
			$(elementId).innerHTML = prefix+"0";
		}
		return;
	}
	var pre = (!prefix)?"$":prefix;
	
	if (isNaN(Number(n_value)))
	return 'ERROR';

	var b_negative = Boolean(n_value < 0);
	n_value = Math.abs(n_value);
	
	// round to 1/100 precision, add ending zeroes if needed
	if(dec && dec>2)
	{
		dec = parseInt(oNval.substr(oNval.indexOf('.')).length-1);
		divd = parseInt(eval('1e'+dec));
		var roundPt = (Math.round(n_value*divd)%divd>9)?(Math.round(n_value*divd)%divd):('0'+Math.round(n_value*divd)%divd);
	}
	else
		var roundPt = (Math.round(n_value*1e2)%1e2>9)?(Math.round(n_value*1e2)%1e2):('0'+Math.round(n_value*1e2)%1e2);
	var s_result = String(roundPt + '00').substring(0,dec);
	// separate all orders
	var b_first = true;
	var s_subresult;
	while (n_value >= 1) 
	{
		s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value%1e3);
		s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
		b_first = false;
		n_value = n_value/1e3;
	}
	
	// add at least one integer digit
	if (b_first)
	s_result = '0.' + s_result;

	// apply formatting and return
	if(!dec)
	{
		s_result = s_result.substring(0,s_result.indexOf("."));
	}
	if(elementId!=null)
	{
		if($(elementId).type == "text")
			$(elementId).value = b_negative ? '-'+pre + s_result + '' : pre + s_result;
		else
			$(elementId).innerHTML = b_negative ? '-'+pre + s_result + '' : pre + s_result;
	}
	
	return b_negative
	? '-'+pre + s_result + ''
	: pre + s_result;
};
/******************* String To number************/

function money2num(strMoney) 
{
	var strArr = strMoney.toArray();
	var newnum = "";
	strArr.each(function(i) {
		if(i=="-"||i=="1"||i=="2"||i=="3"||i=="4"||i=="5"||i=="6"||i=="7"||i=="8"||i=="9"||i=="0"||i==".")
		{
			newnum += i;
		}
	});
	newnum = parseFloat(newnum);
	if(!isNaN(newnum))
		return(newnum);
	else
		return "";
};
function numTotal(strMoney)
{
	var strArr = strMoney.toArray();
	var newnum = "";
	strArr.each(function(i) {
		if(i=="1"||i=="2"||i=="3"||i=="4"||i=="5"||i=="6"||i=="7"||i=="8"||i=="9"||i=="0")
		{
			newnum += i;
		}
	});
	newnum = parseFloat(newnum);
	if(!isNaN(newnum))
		return(newnum);
	else
		return "";
}
/**
 * Function For Changing inplace Edit Link
 */
function trim(str)
{ 
	if((str == null) || ( str != null && str.length == 0))
		return "";
	else if (typeof(str) != "string")
		return "";

	return(str.replace(/^\s+|\s+$/g, ''));
};



if(typeof(tabType) == 'undefined' || tabType != 'dashboard')
{
	//This function is commented by Saloni to solve c21award dashboard tab
	Array.prototype.find = function(searchStr, from, strict) 
	{
		 if(from == undefined || from >= this.length) from = 0;
		   strict = strict == undefined ? false : strict;

		  var returnArray = false;
		  for (i=from; i<this.length; i++) 
		{
			if (typeof(searchStr) == 'function') 
			{
			  if (searchStr.test(this[i]))
				{
					if (!returnArray)
						{ returnArray = [] }
					returnArray.push(i);
				}
			} 
			else
			{
				if(strict)
				{
						if (this[i]===searchStr) 
						{
								if (!returnArray) 
									{ returnArray = [] }
								returnArray.push(i);
						}
				}
				else
				{
					if (this[i]==searchStr) 
					{
						if (!returnArray) 
							{ returnArray = [] }
						returnArray.push(i);
					}
				 }
			}
			
		  }
		  return returnArray;
	};
}
/*
a = ["0",1,2,3,4,5,'',7,"0",1,"1",1,"1",1]
	result1 = a.find ("1"); // return 1,9,10,11,12,13
	result2 = a.find ("1",3);//return 9,10,11,12,13
	result3 = a.find ("1",3,true);//return 10,12
	*/
	
function toggleSlider()
{
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	Element.toggle('toggleDiv');
	if($('after')&&$('before'))
    {
		Element.toggle('after');
		Element.toggle('before');	
    }
    var menuDivArr = document.getElementsByClassName("widgetMenuDiv");
	$A(menuDivArr).each(function(node){
		$(node).style.display = "none";
		oldidMenu = null;
	});
	if($("tabArrow") && $("tabArrow").className.include("_up"))
	{
		$("tabArrow").className ="dashboard_tab_arrow_down";
		document.getElementsByClassName("tabCss").each(function(node){
			node.className = "tabCssCl";
		});
		if($("divSuperParent"))
			$("divSuperParent").addClassName("divSuperParentCl");
	}
	else if($("tabArrow") && $("tabArrow").className.include("_down"))
	{
		$("tabArrow").className ="dashboard_tab_arrow_up";
		document.getElementsByClassName("tabCssCl").each(function(node){
			node.className = "tabCss";
		});
		if($("divSuperParent"))
			$("divSuperParent").removeClassName("divSuperParentCl");
	}
};


function chooseChecked(parentDiv,chkd)
{
	var selectedArr = new Array();
	var selectArr = new Array();
	if($(parentDiv)==null)
	{
		return false;
	}
	parentDiv = $(parentDiv);
	chkbxArr = $A(parentDiv.getElementsByTagName("input"));
	var i=0;
	var j = 0;
	chkbxArr.each(
		function(node)
		{
			if(node.type=="checkbox" && node.id!="sel")
			{
				selectedArr[i]=node.value;
				if(chkd!=null && node.checked)
				{
					selectArr[j] = node.value;
					j++;
				}
				i++;
			}
		});
		if(chkd!=null)
			return selectArr;
		else
			return selectedArr;	
};
function getPositionLeft(element)
{
     var el = $(element);
	 var pL = 0;
     while(el)
     {
           pL += el.offsetLeft;
           el = el.offsetParent;
     }
     return pL;
};
// To find the top position, add this snippet to your code:
function getPositionTop(element)
{
     var el = $(element);var pT = 0;
     while(el)
     {
        pT += el.offsetTop;
        el = el.offsetParent;
     }
     return pT;
};
function showTooltip(tipStr,evnt,xpos)
{
	var e = evnt;
	var xpos = (xpos==null || xpos == "undefined")?50:xpos;
	var element = Event.element(e);
	var leftpos = e.clientX-xpos;
	var toppos = getPositionTop(element)+20;
	if(tipStr!=null || tipStr!="")
	{
		toppos = getPositionTop(element)+5;
		if($("titleInner"))
			$("titleInner").innerHTML = tipStr;
	}
	else
	{
		if($("titleInner"))
			$("titleInner").innerHTML = $("titleInner").title;
	}
	if($("titleDiv"))
	{
		$("titleDiv").style.width = "50px";
		$("titleDiv").style.left = leftpos+"px";
		$("titleDiv").style.top = eval(toppos+50)+"px";
		$("titleDiv").style.display = "inline";
	}
};
function hideTooltip()
{
	if($("titleDiv"))
	{
		$("titleDiv").style.display = "none";
		$("titleDiv").style.left = "0px";
		$("titleDiv").style.top = "0px";
	}
};


function getGeoAdd(lat,lng,city,state,zip,page,action,otherArgs)
{
	//alert(page);
		//alert("4"+zip);
		var myState = '';
		if(state.indexOf('|')>-1)
		{
			var arrState = state.split('|');
			myState = arrState[0];	
		}
		
		if(city.indexOf('|')>-1)
		{
			var arrCity = city.split('|');
			city = arrCity[0];	
		}
		
		var geoCodeResp = function(geoResponse)//response function for ajax call from getGeoAdd
		{
			var geoArr = eval('('+geoResponse.responseText+')');
			var geoStatus = geoArr[0].status;
			if(geoStatus!=0)
			{
				var geoCity = "";
				var geoState = "";
				var geoZip = "";
				//alert(lat+","+lng+","+city+","+state+","+zip+","+page+","+action);
				//alert('Sorry, We couldn\'t find a location for "' + geoArr[0].originaladdress + '"');
				switch(action)
				{
					case 'start':
						//alert('startNo');
						getGeoAdd(lat,lng,city,state,zip,page,'zip');
					break;
					case 'zip':
						//alert('zipNo');
						getGeoAdd(lat,lng,city,state,zip,page,'end');
					break;
				}
				return;
			}
			else
			{
				//alert('bye');
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoAddress = geoArr[0].address;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				if(geoCity=="" && geoZip=="")
				{
					alert('Please specify City or Zip');
					return;
				}
				else if((geoLat == "0" && geoLong == "0") || (geoLat == 0 && geoLong == 0))
				{
					//alert('else if');
					switch(action)
					{
						case 'start':
							//alert('startNo');
							getGeoAdd(lat,lng,city,state,zip,page,'zip');
						break;
						case 'zip':
							//alert('zipNo');
							getGeoAdd(lat,lng,city,state,zip,page,'end');
						break;
					}
					return;	
				}
				
				if(geoState == "")
					geoState = state;
				setSearchCookie("searchAddress",geoAddress);
				/*setSearchCookie("city",geoCity);
				setSearchCookie("state",geoState);
				setSearchCookie("zip",geoZip);*/
				//var cszFromCookie = setCSZValue (getSearchCookie("city"), state, getSearchCookie("zip"));
				/*if($("searchCSZ") && page != "ListMyHome")
					$("searchCSZ").value = cszFromCookie;*/
				
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				var latLongStr = "[{'lat':'"+geoLat+"','lng':'"+geoLong+"'}]";
				var now = new Date();
				now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
				setCookie("latLongCk",latLongStr,now);
				latLong = eval(getCookie("latLongCk"))[0];
			}
			
			setSearchCookie("city",listAllCity);
			setSearchCookie("state",state);
			
			if(page.include("METRO"))
			{
				var strFromWhere = page.split("|");
				var mapit=strFromWhere[1];
				var widgetName =strFromWhere[2]; 
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				var url;
				if(isZip)
				{	
					if(geoZip == "")
						geoZip = zip;
				}
				else
					geoZip = '';
				//alert(state);
				//return;
				if(mapit=="mapitAddr")
				{
					var geoAddress = geoArr[0].address;
					if(listAllCity != false)
					{
						var tempArr = listAllCity.split('|');
						//alert(tempArr.length);
						if(tempArr.length != 1) 
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+listAllCity+","+state+",,,,,"+geoLat+","+geoLong;
						else
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+listAllCity+","+state+","+geoZip+",,,,"+geoLat+","+geoLong;
					}
					else
					 	url = "app/listing/singlePropertyLanding.php?PHPSESSID=&status=EXP&address="+geoAddress+","+geoCity+","+state+","+geoZip+",,,,"+geoLat+","+geoLong;
					 //url = "app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;
				}
				else if(mapit=="mapit")
				{						
					 if(listAllCity != false)
					 {
						var tempArr = listAllCity.split('|');
						//alert(tempArr.length);
						if(tempArr.length != 1)
						 {
							url = "Search/"+state+"/"+geoCity;
							 if(zip != "")
								url += "/"+geoZip;
							//url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+",,,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;
						 }
						else
						 {
							url = "Search/"+state+"/"+geoCity;
							 if(zip != "")
								url += "/"+geoZip;
							//url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;
						 }
					 }
					 else
					{
						 url = "Search/"+state+"/"+geoCity;
						 if(zip != "")
							url += "/"+geoZip;
					 	//url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+state+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;//+",jbfeaturedlistings";
					}
				}
				else if(mapit=="multicity")
				{
					setSearchCookie("city",listAllCity);
					setSearchCookie("state",state);
					//cszFromCookie = setCSZValue (getSearchCookie("city"), myState);
					
					 if(listAllCity != false)
					 {
						var tempArr = listAllCity.split('|');
						//alert(tempArr.length);
						if(tempArr.length != 1) 
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+",,,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;
						else
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;
					 }
					 else
					 	url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+state+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;//+",jbfeaturedlistings";
				}
				//alert(url);
				if(otherArgs!= null)
					url = url + otherArgs;
				location.href = url;
				return;
			}
			else if(page.include("LMSRE"))
			{
				var address="";
				//alert(geoArr);
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				if(geoState == "")
					geoState = state;
				
				var geoZip = geoArr[0].zip;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				var url;
				if(Exclusiveflag==1)
					url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+address+","+listAllCity+","+state+",,,,,"+geoLat+","+geoLong+"&widgetnames=exclusivelisting";
				else
					url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+address+","+listAllCity+","+state+",,,,,"+geoLat+","+geoLong+"&widgetnames=mlsCountySearch";

				if(otherArgs!= null)
					url = url + otherArgs;
				location.href = url;
				return;			
			}	
		}
		
		if(lat != "0" || lng != "0")
		{
			//alert(lat+","+lng)
			if(page.include("METRO"))
			{
				var strFromWhere = page.split("|");
				var mapit=strFromWhere[1];
				var widgetName =strFromWhere[2];
				var url;

				var latLongStr = "[{'lat':'"+lat+"','lng':'"+lng+"'}]";
				var now = new Date();
				now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
				setCookie("latLongCk",latLongStr,now);
				if(!isZip)
					zip = '';
				
				setSearchCookie("city",listAllCity);
				setSearchCookie("state",state);
				//var	cszFromCookie = setCSZValue (getSearchCookie("city"), state);
				if(mapit=="mapitAddr")
				{
					var geoAddress;
					
					
					if($("txtAddress"))
						geoAddress = $("txtAddress").value;
					else
						geoAddress="";
						
					if(listAllCity != false)
					{
						var tempArr = listAllCity.split('|');
						//alert(tempArr.length);
						if(tempArr.length != 1) 
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+listAllCity+","+state+",,,,,"+lat+","+lng;
						else
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+listAllCity+","+state+","+zip+",,,,"+lat+","+lng;
					}
					else
						url = "app/listing/singlePropertyLanding.php?PHPSESSID=&status=EXP&address="+geoAddress+","+city+","+state+","+zip+",,,,"+lat+","+lng;
				
				}
				else if(mapit=="mapit")
				{					
					removeSearchCookie("city");
					removeSearchCookie("state");
					 //alert("2"+ zip+" , "+isZip);					
					 url = "Search/"+state+"/"+city;
	    			 if(zip != "")
						url += "/"+zip;
					 /*if(listAllCity != false)
					 {
						var tempArr = listAllCity.split('|');
						//alert(tempArr.length);
						if(tempArr.length != 1) 
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames="+widgetName;
						else
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+","+zip+",,,,"+lat+","+lng+"&widgetnames="+widgetName;
					 }
					 else
					 	//url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+city+","+state+","+zip+",,,,"+lat+","+lng+"&widgetnames="+widgetName;//+",jbfeaturedlistings";*/
				}
				else if(mapit=="multicity")
				{
					 if(listAllCity != false)
					 {
						var tempArr = listAllCity.split('|');
						//alert(tempArr.length);
						if(tempArr.length != 1) 
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames="+widgetName;
						else
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+","+zip+",,,,"+lat+","+lng+"&widgetnames="+widgetName;
					 }
					 else
					 	url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+city+","+state+","+zip+",,,,"+lat+","+lng+"&widgetnames="+widgetName;//+",jbfeaturedlistings";
				}
				//if(otherArgs!= null)
				//	url = url + otherArgs;
				location.href = url;
			}
			else if(page.include("LMSRE"))
			{
				var address="";
				var url;
//				alert("LMSRE : "+lat+","+lng);
				if(Exclusiveflag==1)
					url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+address+","+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames=exclusivelisting";
				else
					url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+address+","+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames=mlsCountySearch";
				
				setSearchCookie("city",listAllCity);
				setSearchCookie("state",state);
				var latLongStr = "[{'lat':'"+lat+"','lng':'"+lng+"'}]";
				var now = new Date();
				now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
				setCookie("latLongCk",latLongStr,now);
				if(otherArgs!= null)
					url = url + otherArgs;
				location.href = url;
				//return;			
			}	
		}
		else
		{
			//alert('else');
			var geoAddress;
			var geoUrl = "/classes/getCSZ.php";
			
			if($("txtAddress"))
				geoAddress = $("txtAddress").value;
			else
				geoAddress="";
			
			var geoQueryString;
			switch(action)
			{
				case 'start':
					geoQueryString = "csz="+city+","+myState+"&address="+geoAddress;	
					//alert('start');
					ajaxRequest(geoUrl,geoQueryString,geoCodeResp);
				break;
				case 'zip':
					geoQueryString = "csz="+city+","+myState+","+zip+"&address="+geoAddress;	
					//alert('zip');
					ajaxRequest(geoUrl,geoQueryString,geoCodeResp);
				break;
				case 'end':
					//alert('Ends');
					if(page.include("METRO"))
					{
						var strFromWhere = page.split("|");
						var mapit=strFromWhere[1];
						var widgetName =strFromWhere[2];
						var url;
						if(!isZip)
							zip = '';
						if(mapit=="mapitAddr")
						{
							var geoAddress;
							if($("txtAddress"))
								geoAddress = $("txtAddress").value;
							else
								geoAddress="";
								
							 if(listAllCity != false)
							 {
								var tempArr = listAllCity.split('|');
								//alert(tempArr.length);
								if(tempArr.length != 1) 
									url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+listAllCity+","+state+",,,,,"+lat+","+lng;
								else
									url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+listAllCity+","+state+","+zip+",,,,"+lat+","+lng;
							 }
							 else
								 url = "app/listing/singlePropertyLanding.php?PHPSESSID=&status=EXP&address="+geoAddress+","+city+","+state+","+zip+",,,,"+lat+","+lng;
						}
						else if(mapit=="mapit")
						{
							 //alert("3"+ zip+" , "+isZip);
							 if(listAllCity != false)
							 {
								var tempArr = listAllCity.split('|');
								//alert(tempArr.length);
								if(tempArr.length != 1)
								{
									//alert('e');
									url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames="+widgetName;
								}
								else
								{
									//alert('d');
									url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address=,"+listAllCity+","+state+","+zip+",,,,"+lat+","+lng+"&widgetnames="+widgetName;
								}
							 }
							 else
							 url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+city+","+state+","+zip+",,,,"+lat+","+lng+"&widgetnames="+widgetName;//+",jbfeaturedlistings";
						}
						if(otherArgs!= null)
							url = url + otherArgs;
						location.href = url;
					}
					else if(page.include("LMSRE"))
					{
						var address="";
						if(Exclusiveflag==1)
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+address+","+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames=exclusivelisting";
						else
							url ="../../../app/listing/singlePropertyLanding.php?status=EXP&address="+address+","+listAllCity+","+state+",,,,,"+lat+","+lng+"&widgetnames=mlsCountySearch";
						//alert(url);
						if(otherArgs!= null)
							url = url + otherArgs;
						location.href = url;
					}
				break;
			}
			//var geoQueryString = "csz="+city+","+state+","+zip+"&address="+geoAddress;
		}
}


function getGeocodeAddress(csz,page)
{
		var geoCbFn = function(geoResponse)
		{
			var geoArr = eval('('+geoResponse.responseText+')');
			var geoStatus = geoArr[0].status;
			if(geoStatus!=0)
			{
				var geoCity = "";
				var geoState = "";
				var geoZip = "";
				alert('Sorry, We couldn\'t find a location for "' + geoArr[0].originaladdress + '"');
				if (page=="ValueMyHome")
				{
					$('btnSearchEstimateAddress').style.display = "";
					$('statusMsg').style.display = "none";
				}
				
				return;
			}
			else
			{

				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoAddress = geoArr[0].address;
				if(geoCity=="" && geoZip=="")
				{
					alert('Please specify City or Zip');
					return;
				}
				if($("searchCity"))
					$("searchCity").value = geoCity;
				if($("searchState"))
					$("searchState").value = geoState;
				if($("searchZip"))
					$("searchZip").value = geoZip;
				if($("searchAddress")  && page != "ListMyHome")
					$("searchAddress").value = geoAddress;
					
				
				setSearchCookie("searchAddress",geoAddress);
				setSearchCookie("city",geoCity);
				setSearchCookie("state",geoState);
				setSearchCookie("zip",geoZip);
				setSearchCookie("county","");
				
				var cszFromCookie = setCSZValue (getSearchCookie("city"), getSearchCookie("state"), getSearchCookie("zip"));
				if($("searchCSZ") && page != "ListMyHome")
					$("searchCSZ").value = cszFromCookie;
				
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				var latLongStr = "[{'lat':'"+geoLat+"','lng':'"+geoLong+"'}]";
				var now = new Date();
				now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
				setCookie("latLongCk",latLongStr,now);
				latLong = eval(getCookie("latLongCk"))[0];
				
				
			}
			//alert(page);
			if(page != "campaign" && page != "landing" && page != "ListMyHome" && page != "snapShot" && page != "VOH" && page != "BST" && page != "FAH" && page != "FAO" && page != "VH" && !(page.include("LMSRE")) && page != "LMSRE_SmartWin" && page != "METRO_AssOff" &&!(page.include("METRO")))
			{
				if(trim($('searchAddress').value) == "")$('searchAddress').value = "optional";	

				if(document.cookie=="")
					pageReload();
			}
			if(page=="dashboard")
			{
				funQckUpdateWidgets();		
			}
			else if(page=="singleProp")
			{
				funExploreOnMapit();//alert("Please add your function call for MapIt in common.js");
			}
			else if(page=="landing")
			{
				window.location.href = './app/dashboard/dashboardIndex.php';
			}
			else if(page == "dashboardbitz")
			{
				window.location.href = '../../app/dashboard/dashboardIndex.php?setDsh=1';
			}
			else if(page=="campaign")
			{

				lat = latLong.lat;
				lng = latLong.lng;

				if (geoArr[0].city !="")
					var geoCityStr = geoArr[0].city;
				if (geoArr[0].state !="")
					geoCityStr += ", "+geoArr[0].state;
				if (geoArr[0].zip !="")
					geoCityStr += ", "+geoArr[0].zip;
				//return geoCityStr;
				if(trim(geoCityStr)=="") 
					alert("Please refine your search criteria");
				else
					sendDashboard(geoCity,geoState,geoZip,lat,lng);
			}
			else if(page=="ValueMyHome")
			{
				var url = "../feed/homeEstimate.php?pid=&address="+geoAddress+","+geoCity+","+geoState+","+geoZip;
				window.open(url,"_blank");
				$('btnSearchEstimateAddress').style.display = "";
				$('statusMsg').style.display = "none";
			}
			
			else if(page=="ExploreNeighborhood")
			{
				
				var url = './dshbrdExplore.php';
				var qryStr = 'geoAddress=1&exploreAddress='+geoAddress+'&exploreCity='+geoCity+'&exploreState='+geoState+'&exploreZip='+geoZip;
				ajaxRequest(url,qryStr,function(respObj)
				{
					if (respObj.responseText=="0")
					{
						alert("Sorry, Not Able To Resolve Address");
						$('btnSearchExplore').style.display = "";
						$('expStatusMsg').style.display = "none";
					}
					else
					{
						var url = respObj.responseText;
						window.open(url,"_blank");
						$('btnSearchExplore').style.display = "";
						$('expStatusMsg').style.display = "none";
					}
				});
			}
			
			else if(page=="ListMyHome")
			{
				$('btnGetBids').style.display = "none";
				$('statusMsgListHome').style.display = "";

				var url = './dshbrdLMH.php';
				var qryStr = 'validateAddress=1&address='+geoAddress+'&city='+geoCity+'&state='+geoState+'&zip='+geoZip+'&expt='+exptdSales+'&name='+names+'&email='+email+'&timel='+timeLine;
				var divid = $('listHome').id;
				loadToDiv(url,qryStr,divid);			
			}
			else if(page=="snapShot")
			{
				getListingSnapshots();
			}
			else if(page=="FAH")
			{
				var url = "app/dashboard/dashboardIndex.php";
				location.href = url;
			}
			else if(page=="BST")
			{
				var url = "app/dashboard/dashboardIndex.php";
				location.href = url;
			}
			else if(page=="VOH")
			{
				var url = "app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong;
				location.href = url;
			}
			else if (page=="VH")
			{
				var csz = geoCity+","+geoState+","+geoZip;
				var url = "app/feed/homeEstimate.php?pid=&address="+escape(geoAddress)+","+escape(csz);
				location.href = url; 				
			}
			else if(page=="FAO")
			{
				var url = "app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong;
				location.href = url;
			}
			else if(page=="METRO_AssOff")
			{
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				
				var url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames=brokeragents,brokeroffices";
				location.href = url;
			}
			else if(page=="METRO_AssAgtOff")
			{
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				var qs = "";
				var wdNm = "brokeragents";
				var isOthSet = false;
				if(isBlank('txtFname','First Name'))
				{
					qs += "&fname="+$F('txtFname');
					isOthSet= true;
				}
				
				if(isBlank('txtLname','Last Name'))
				{
					qs += "&lname="+$F('txtLname');
					isOthSet= true;
				}
				
				if(isBlank('txtCityName','City'))
				{
					qs += "&cityName="+escape($F('txtCityName'));
					wdNm = wdNm + ",officeLocation";
					isOthSet= true;
				}
				
				if($F('txtOffice') != "")
				{
					//qs += "&office="+escape($F('txtOffice'));
					qs += "&office="+escape($("txtOffice").options[$("txtOffice").selectedIndex].value);
					wdNm = wdNm + ",brokeroffices";
					isOthSet= true;
				}
				
				if($F('txtOfficeLoc') != "")
				{
					//qs += "&office="+escape($F('txtOffice'));
					qs += "&officeLoc="+escape($("txtOfficeLoc").options[$("txtOfficeLoc").selectedIndex].value);
					//alert($F('txtOfficeLoc'));return;
					/*if(isOthSet)
						wdNm = wdNm + ",officeLocation";
					else
						wdNm = "officeLocation";*//*old*/
					
					if(!wdNm.include("officeLocation"))
						wdNm = wdNm + ",officeLocation";/*new*/	
				}				
				var showDialog="";
				if(wdNm != "officeLocation")
					showDialog = "&showAgentDialog=some";
				else
					showDialog = "&showAgentDialog=";
				var url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+wdNm+showDialog+qs;
				
				//var url = "./app/listing/singlePropertyLanding.php?status=EXP&address=,denver,CO,,,,,39.755092,-104.988123&widgetnames=brokeragents,brokeroffices&showAgentDialog=1";
				//alert(url);
				location.href = url;
			}
			else if(page=="LMSRE_SmartWin")
			{
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				sendAddressFldsToLMSRE(geoCity,geoState,geoLat,geoLong);
			}
			else if(page.include("LMSRE"))
			{
				var strFromWhere = page.split("|");
				var mapit=strFromWhere[1];
				var widgetName =strFromWhere[2]; 
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				var url;
				var moreWidgets="";
				moreWidgets = getCookie("strMapitCK");
				if(widgetName=="terabitzMap")
				{
					url = "/app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames=";
				}
				else if(mapit=="mapit")
				{
					var ps = "";
					if(typeof(powerSearch) != 'undefined' && powerSearch == '1' && (uRole == 'EA' || uRole == 'A'))
						var ps = "&ps=1";

					if(moreWidgets == "" || moreWidgets == null)
					{
						url = "/app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName+ps;
					}
					else
					{
						url = "/app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName+","+moreWidgets+ps;
					}
					if(uid != "")
						setCookie("strMapitCK","");
				}
				else if(mapit=="fromMapIt")
				{
					if(moreWidgets == "" || moreWidgets == null)
					{
						url = "/app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName;
					}
					else
					{
						url = "/app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName+","+moreWidgets;
					}
				}
				else if(mapit=="dashboard")
				{
					//url = "/app/dashboard/dashboardIndex.php?loadnow=1&code=searchAddress=:::city="+geoCity+":::state="+geoState+":::county=:::neighborhood=:::minPrice=:::maxPrice=:::searchBeds=:::minSize=:::maxSize=:::searchBaths=:::searchType=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::zip=&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;
					url = "/app/dashboard/dashboardIndex.php";
				}
				else if(mapit=="dashboardindex")
				{
					eval("var hashDshbrdBitz="+lmsreDshbrdBitz); 
					if(eval("hashDshbrdBitz['"+widgetName+"']")!=null)
	 				{	
	 					hashVal = eval("hashDshbrdBitz['"+widgetName+"']");
	 					url = "/app/dashboard/dashboardIndex.php?loadnow=1&code=searchAddress=:::city="+geoCity+":::state="+geoState+":::county=:::neighborhood=:::minPrice=:::maxPrice=:::searchBeds=:::minSize=:::maxSize=:::searchBaths=:::searchType=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::zip=&id=:::"+hashVal+",1,2&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;
 					}
	 			}
				location.href = url;
			}
			else if(page.include("METRO"))
			{
				var strFromWhere = page.split("|");
				var mapit=strFromWhere[1];
				var widgetName =strFromWhere[2]; 
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				if(geoState!="CO")
				{
					alert("Sorry, we do not support any other state then CO.");
					return;
				}
				var url;
				var extra = "";
				if(widgetName == "exclusivecol")
				{
					extra = "&mapZoomLevel=9";
					var now = new Date();
					now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
					setCookie("mapSearchSelect","1",now);
				}

				if(mapit=="mapitAddr")
				{
					var geoAddress = geoArr[0].address;
					 widgetName = 'mlsaddrsearch';
					 url = "app/listing/singlePropertyLanding.php?status=EXP&address="+geoAddress+","+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName+extra;
				}
				else if(mapit=="mapit")
				{
					//alert(3);
					var dist = "";
					var distStr = "";
					if($("distanceChk").checked)
					{
						dist = $F("distance");
						distStr = "&mapZoomLevel=" + dist;//"&distance="+dist;
					}

					if(widgetName == "exclusivecol")
					{
						distStr = "&mapZoomLevel=9";
					}

					//url = "app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName+distStr;//+",jbfeaturedlistings";
					url = "Search/"+geoState+"/"+geoCity;
					if(geoZip != "")
						url += "/"+geoZip;
					
					removeSearchCookie("city");
					removeSearchCookie("state");
				}
				else if(mapit=="fromMapIt")
				{
					url = "/app/listing/singlePropertyLanding.php?status=EXP&address=,"+geoCity+","+geoState+","+geoZip+",,,,"+geoLat+","+geoLong+"&widgetnames="+widgetName+extra;
				}
				else if(mapit=="dashboard")
				{
					url = "/app/dashboard/dashboardIndex.php?loadnow=1&code=searchAddress=:::city="+geoCity+":::state="+geoState+":::county=:::neighborhood=:::minPrice=:::maxPrice=:::searchBeds=:::minSize=:::maxSize=:::searchBaths=:::searchType=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::zip=&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;
				}
				else if(mapit=="dashboardindex")
				{
					if(widgetName=="demographics")
						url = "app/dashboard/dashboardIndex.php?loadnow=1&code=searchAddress=:::city="+geoCity+":::state="+geoState+":::county=:::neighborhood=:::minPrice=:::maxPrice=:::searchBeds=:::minSize=:::maxSize=:::searchBaths=:::searchType=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::zip=&id=28,1,1:::&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;
					if(widgetName=="climate")
						url = "app/dashboard/dashboardIndex.php?loadnow=1&code=searchAddress=:::city="+geoCity+":::state="+geoState+":::county=:::neighborhood=:::minPrice=:::maxPrice=:::searchBeds=:::minSize=:::maxSize=:::searchBaths=:::searchType=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::zip=&id=19,1,1:::&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;
					if(widgetName=="mortgage rates")
						url = "app/dashboard/dashboardIndex.php?loadnow=1&code=city="+geoCity+":::state="+geoState+":::county=:::minsqft=:::maxsqft=:::minSize=:::maxSize=:::searchType=:::searchAddress=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::minPrice=:::maxPrice=:::searchBeds=:::searchBaths=:::zip=&id=50,1,1:::&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;;
					if(widgetName=="mcalc")
						url = "app/dashboard/dashboardIndex.php?loadnow=1&code=city="+geoCity+":::state="+geoState+":::county=:::minsqft=:::maxsqft=:::minSize=:::maxSize=:::searchType=:::searchAddress=:::searchSortType=ph:::ckLFDate=:::ckLTDate=:::minPrice=:::maxPrice=:::searchBeds=:::searchBaths=:::zip=&id=24,1,1:::&fe=&f=1&propLatitude="+geoLat+"&propLongitude="+geoLong;
				}
				location.href = url;
			}
			else if(page == "METRO_GOTLL")
			{
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoZip = geoArr[0].zip;
				sendAddressForLatLong(geoCity,geoState,geoZip);
			}
			else if(page=="METRO_SmartWin")
			{
				var geoCity = geoArr[0].city;
				var geoState = geoArr[0].state;
				var geoLat = geoArr[0].latitude;
				var geoLong = geoArr[0].longitude;
				sendAddressFldsToMETRO(geoCity,geoState,geoLat,geoLong);
			}
			else
			{
				submitSearchForm();
			}
		}
		
		if (page == 'ValueMyHome')
		{
			var geoAddress = $("valueHomeAddress").value;
		}
		else if (page == 'ExploreNeighborhood')
		{
			var geoAddress = $("exploreAddress").value;
		}
		else if (page == 'ListMyHome')
		{
			var geoAddress = $("listHomeAddress").value;
			var exptdSales = $("expectedSale").value;
			var names = $("listHomeName").value;
			var email = $("listHomeEmail").value;						
			var timeLine = $("timeLine").value;									
		}
		else if (page == 'landing')
		{
			if ($('searchAddress').value == "optional")
			{
				var geoAddress = "";
			}
			else
			{
				var geoAddress = $("searchAddress").value;
			}

			if  ($('searchCSZ').value == "required")
			{
				alert ('Please enter a location.');
				return;
			}
		}
		else if(page == 'campaign')
		{
			var geoAddress ="";
		}
		else if(page == "FAH" || page == "BST" || page == "VOH" || page == "VH" || page == "FAO")
		{
			if ($('searchAddress').value == "optional")
			{
				var geoAddress = "";
			}
			else
			{
				var geoAddress = $("searchAddress").value;
			}
		}
		else if(page.include("LMSRE") || page=="LMSRE_SmartWin" || page.include("METRO") || page=="METRO_SmartWin" || page == 'Metro')
		{
			var geoAddress; 
			if($("txtAddress"))
				geoAddress = $("txtAddress").value;
			else
				geoAddress="";
		}
		else
		{
			var geoAddress = $("searchAddress").value;
		}
		
	
		var geoUrl = "/classes/getCSZ.php";
		var geoQueryString = "csz="+csz+"&address="+geoAddress;
		if (page == 'METRO')
		{
			ajaxRequest(geoUrl,geoQueryString,geoCbFn,false);
		}
		else
		{
			ajaxRequest(geoUrl,geoQueryString,geoCbFn);
		}

}

//--------------------------- Search Funtions -----------------------------//
function isNumeric(strValue)
{
	var objRegExp  = /(^-?\d\d*$)/;
	return objRegExp.test(strValue);
};

function submitSearchForm()
{
	if (($F('searchCity') == "") && ($F('searchZip') == ""))
	{
		alert ("Atleast one of 'City' or 'Zip' is requied");
		return false;
	}

	if(!zipValid('searchZip'))
	{
		alert("Zip is invalid");
		return false;
	}
	if(!numberIsValid('yearFrom',"Please enter valid year value","Year From",null,null))
	{
		alert ("Please enter valid year value");
		return false;
	}
	else
	{
		 if($('yearFrom').value!="" && $('yearFrom').value!=" ")
		 {
			 if($('yearFrom').value.length < 4)
			 {
				alert ("Year From should be 4 charcters long.");
				return false;
			 }
		}
	}
	
	if(!numberIsValid('yearTo',"Please enter valid year value","Year To",null,null))
	{
		alert ("Please enter valid year value");
		return false;
	}
	else
	{
		if($('yearTo').value!="" && $('yearTo').value!=" ")
		{
			 if($('yearTo').value.length < 4)
			 {
				alert ("Year To should be 4 charcters long.");
				return false;
			 }
		}
	}
	var contextArray = new Array("onSale","openHouse","newHomes","allHomes");
	var searchAddress = $F('searchAddress');
	if($('srchPopInDiv'))
		Element.toggle('srchPopInDiv');

	var saleable = "3";
	var userContext = "allHomes";
	var queryString = "address=" + escape(searchAddress);
		queryString = queryString + "&city=" + escape(trim($F("searchCity")));
		queryString = queryString + "&state=" + escape(trim($F("searchState")));
		queryString = queryString + "&zip=" + escape(trim($F("searchZip")));
		queryString = queryString + "&minprice=" + escape(money2num($F("minPrice")));
		queryString = queryString + "&maxprice=" + escape(money2num($F("maxPrice")));
		queryString = queryString + "&minsqft=" + escape($F("minSize"));
		queryString = queryString + "&maxsqft=" + escape($F("maxSize"));
		queryString = queryString + "&beds=" + escape($F("searchBeds"));
		queryString = queryString + "&baths=" + escape($F("searchBaths"));
		queryString = queryString + "&searchType=" + escape($F("searchType"));
		queryString = queryString + "&saleable=" + escape(saleable);
		queryString = queryString + "&usercontext=" + escape(userContext);
		setCookie("checkedType",saleable,now);
		
	//-------------------setting client side cookies--------------------//
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	setAllToCookie();
	url = "../listing/checkRecords.php";
	if ($('signInDiv')) Element.toggle('signInDiv');
	if ($('srchDiv')) Element.toggle('srchDiv');
	ajaxRequest(url,queryString,evalResponce);	
};

function evalResponce(originalRequest)
{
	var recCount = parseInt(originalRequest.responseText);
	if (recCount < 0)
	{
		if ($('srchDiv')) Element.toggle('srchDiv');
		if ($('signInDiv')) Element.toggle('signInDiv');
		alert("Sorry cannot connect to server");
	}	
	else if (recCount == 0)
	{
		if ($('srchDiv')) Element.toggle('srchDiv');
		if ($('signInDiv')) Element.toggle('signInDiv');
		alert("Sorry no records found");
		if($('srchPopInDiv'))
			Element.toggle('srchPopInDiv');
	}	
	else
	{
		window.location.href = "../listing/searchResult.php?PHPSESSID="+sessid;
	}
};

//--------------------------- Search Funtions -----------------------------//
function contactUs(type)
{
	alert ("For technical issues, please contact us at support@terabitz.com"+'\n'+"Broker-Agents contact us at brokeragentsupport@terabitz.com"+'\n'+"For all other inquiries, please contact us at info@terabitz.com");
}
/*********************************************************************************
 * Getting window size and scroll bars position in JavaScript/DHTML
 * http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
 * author : Hi Pratik!
 * Date	: 15th May 2007
 * 
 ********************************************************************************** 
 */

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function Querystring(qs) { 
	this.qs = qs;
	this.params = new Object();
	this.get=Querystring_get;
	this.set = Querystring_set;
	if (this.qs == null)
		this.qs=location.search.substring(1,location.search.length)

	if (this.qs.length == 0) return

	this.qs = this.qs.replace(/\+/g, ' ')
	var args = this.qs.split('&') // parse out name/value pairs separated via &
	
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0]);
        if(i==0)
		{
			name = name.substr(eval(name.indexOf('?')+1),name.length);
		}
		if (pair.length == 2)
			value = unescape(pair[1]);
		else
			value = name;
		this.params[name] = value;
	}
}

function Querystring_get(key, default_) 
{
	if (default_ == null) default_ = null;
	
	var value=this.params[key];
	if (value==null) value=default_;
	return value;
}
function Querystring_set(key,value)
{
	if(key == null)
		return;
	if(value == null)
		value = "";	
	this.params[key] = unescape(value);
	var paramKeys = Object.keys(this.params);
	var myQS = "";
	for(var i=0;i<paramKeys.length;i++)
	{
		myQS = myQS + "&" + paramKeys[i] + "=" + escape(this.params[paramKeys[i]]);
	}
	myQS = myQS.substr(1,myQS.length);
	this.qs = myQS;
}
Element.addMethods({
  hasAttributeValue: function(element, attrName, attrVal, separator) {
    element = $(element);
    attrName = trim(attrName);
    separator = (separator)?(separator):" ";
    var attr = element.readAttribute(attrName);
    if(attr==null || attr =="")
    	return false;
    attrVal = trim(attrVal);
    if(attr!="" || trim(attr)!="")
    {
    	attr = attr.replace (/^\s+/g, "").replace (/\s+$/g, "").replace (/\s+/g, " ");
    	var attrArr = attr.split(separator);
    	var retVal = attrArr.find(attrVal);
    	if(retVal===false)
    		return false;
    	else
    		return true;
    }
    return false;
  }
});
  
document.getElementsByAttributeVal = function(attrName,attrVal, parentElement) {
  if (Prototype.BrowserFeatures.XPath) {
    var q = ".//*[contains(concat(' ', @"+ attrName +", ' '), ' " + attrVal + " ')]";
    return document._getElementsByXPath(q, parentElement);
  } else {
    var children = ($(parentElement) || document.body).getElementsByTagName('*');
    var elements = [], child;
    for (var i = 0, length = children.length; i < length; i++) {
      child = children[i];
      if ($(child).hasAttributeValue(attrName, attrVal))
      {
        elements.push(Element.extend(child));
      }
    }
    return elements;
  }
};
//("groupid","3","galleryContainer")
var lastArrow = false;
function searchAddressFormat(event,defaultText)
{
	if(typeof(event)!="string")
	{
		var element = Event.element(event);
			if(event.type=="blur")
	{
		var srchVal = element.value.replace (/^\s+/g, '').replace (/\s+$/g, '').replace (/\s+/g, ' ');
		if(srchVal == '')
		{
			element.value=defaultText;
			element.className = element.className.gsub("N","");
		}
		else
		{
			element.value=srchVal;
			if(element.className.indexOf("N")==-1)
				element.className = String(element.className+"N");
		}
	}
	if(event.type=="focus")
	{
		if(element.value==defaultText)
		{
			element.value='';
			if(element.className.indexOf("N")==-1)
				element.className = String(element.className+"N");
		}
	}
		
	}
	else
	{
		var element = $(event);
		var srchVal = element.value.replace (/^\s+/g, '').replace (/\s+$/g, '').replace (/\s+/g, ' ');
		if(srchVal == '')
		{
			element.value=defaultText;
			element.className = element.className.gsub("N","");
		}
		else
		{
			element.value=srchVal;
			if(element.className.indexOf("N")==-1)
				element.className = String(element.className+"N");
		}
	}	
}
function findBitFormat()
{
	if(trim($("findBitTxt").value) == "")
	{
		$("findBitTxt").value = "Find Bit";
		$("findBitTxt").className = "textboxstyle";
	}
	else if(trim($("findBitTxt").value) == "Find Bit")
	{
		$("findBitTxt").value = "";
		$("findBitTxt").className = "textboxstyleN";
	}
	else
	{
		$("findBitTxt").className = "textboxstyleN";
		findBit();
	}
}
var arrLoadedTabs = new Array();
function showWidgetGrp(gid)
{
	if(gid==null || typeof(gid)=='undefined')
		return;
	if($("toggleDiv").style.display=="none")
	{
		toggleSlider();
	}
	
	$A(document.getElementsByClassName("dashIconsDrag","galleryContainer")).each(Element.hide);
	if(gid=="All")
	{
		var gidArr = document.getElementsByClassName("dashIconsDrag","galleryContainer");
		gidArr.each(function(nd)
		{
			$(nd).style.display = "inline";
		});
		$('theImages').style.left = 25 + 'px';
		if($("arrowLeft"))
		{
			$("arrowLeft").show();
			$("arrowRight").show();
			$("arrowLeftDis").hide();
			$("arrowRightDis").hide();
		}
		initSlideShow();
		return;
	}
	gid = gid.toString();
	var gidArr = document.getElementsByAttributeVal("groupid",gid,"galleryContainer");
	var len = gidArr.length;
	for(var i=0;i<len;i++)
	{
		if((arrLoadedTabs.in_array(gid) === false) && ($(gidArr[i]) != null))
		{
			var divImgId = $(gidArr[i]).id;
			var widgetName = divImgId.gsub('divImg_','');
			var imgId =  'img_'+widgetName;
			$(imgId).src = $(imgId).src.gsub('spacer.gif',eval('widgetsData.'+widgetName+'.img_n'));
		}	
		if($(gidArr[i]))
			$(gidArr[i]).style.display = "inline";
	}
	if(arrLoadedTabs.in_array(gid) === false)
		arrLoadedTabs[arrLoadedTabs.length] = parseInt(gid);
	
	if(len>=9)
	{
		lastArrow = true;
		if($("arrowLeft"))
		{
			$("arrowLeft").show();
			$("arrowRight").show();
			$("arrowLeftDis").hide();
			$("arrowRightDis").hide();
		}
	}
	else
	{
		lastArrow = false;
		if($("arrowLeft"))
		{
			$("arrowLeft").hide();
			$("arrowRight").hide();
			$("arrowLeftDis").style.display = "inline";
			$("arrowRightDis").style.display = "inline";
		}
	}
	$('theImages').style.left = 25 + 'px';
	if(!isIE)
		initSlideShow();
}

function findHash(myObjFind,key)
{
	var h  = $H(myObjFind);
	var arrKeys = h.keys().sort();
	
	key = trim(key).toLowerCase();
	var keyLen = key.length;
	
	var arrRes = Array();
	for(var i=0;i<arrKeys.length;i++)
	{
		//if(key==((arrKeys[i].toLowerCase().substring(0,keyLen)).toLowerCase()))
		if((arrKeys[i].toLowerCase()).include(key))
			arrRes.push(h[arrKeys[i]]);
	}
	return arrRes;
}
function findBit()
{
	var gidArr = document.getElementsByClassName("dashIconsDrag","galleryContainer");
	var key=$("findBitTxt").value;
	if(trim(key)!="")
	{
		gidArr.each(function(nd)
		{
			$(nd).style.display = "none";
		});
		var findArr = findHash(myObjFind[0],key);
		$A(findArr).each(
			function(node)
			{
				if($("divImg_"+node) && node!="mapit")
					$("divImg_"+node).show();
			}
		);
	}
	else
	{
		gidArr.each(function(nd)
		{
			if(nd!="divImg_mapit")
				$(nd).style.display = "inline";
		});
	}
}

function changeTabCls(type,event)
{
	var gidArr = document.getElementsByClassName("tabTdCls",event);
	if(type=="over")
	{
		gidArr.each(function(nd)
		{
			if(!(nd.className.include("_blue_h")))
				nd.className = nd.className.gsub("_blue_n","_blue_h");
		});
	}
	else if(type=="out")
	{
		gidArr.each(function(nd)
		{
			if((nd.className.include("_blue_h")))
				nd.className = nd.className.gsub("_blue_h","_blue_n");
		});
	}
	else
	{
		var gidArrAll = document.getElementsByClassName("tabTdCls","grpDiv");
		gidArrAll.each(function(nd)
		{
			if((nd.className.include("_blue_cl")))
			{
				nd.className = nd.className.gsub("_blue_cl","_blue_n");
			}
		});
		gidArr.each(function(nd)
		{
			if(!(nd.className.include("_blue_cl")))
			{
				nd.className = nd.className.gsub("_blue_h","_blue_cl");
				nd.className = nd.className.gsub("_blue_n","_blue_cl");
			}
		});
	}
	
}

function trimToRect(w, h, str, strApp, strClass, bTrimToWords, bAlwaysAppend,id)
{
	h=parseInt(h);
	str=str.replace(/<=>/g,"'");
	str=str.replace(/<==>/g,'"');
// element with id "ruler" must exist in the document, e.g.:
// <div id=ruler style="position:absolute; left:-5000px;"><!-- --></div>
	elR = document.getElementById(id);
	elR.className = strClass;
	elR.style.width = w;
	
	if(bAlwaysAppend)
		strResult = str + strApp;
	else
		strResult = str;

	// fits already? opt out early
	elR.innerHTML = strResult;
	if(elR.clientHeight <= h)
		return strResult;

	with(Math) position = nextOffset = pow(2,floor(log(str.length) / LN2));

	do
	{
		nextOffset = nextOffset / 2;
		elR.innerHTML = str.substr(0, position) + strApp;
		position = position + (elR.clientHeight > h? -nextOffset:nextOffset);
	} while(nextOffset!= 1);

	elR.innerHTML = str.substr(0, position) + strApp;
	if(elR.clientHeight > h)
		position--;

	if(bTrimToWords)
		while(str.substr(--position, 1)!= " ");

	return str.substr(0, position) + strApp;
}

function highlightMapTypeBtn(maparg)
{
	if (maparg)
		mapType = maparg.getCurrentMapType().getName(true);
	if(mapType=="Map")
	{
		document.getElementById("btnMap").className="mapTypeButtonSelect";
		document.getElementById("btnSat").className="mapTypeButton";
//		document.getElementById("btnHyb").className="mapTypeButton";
		document.getElementById("btnTer").className="mapTypeButton";
	}
	else if(mapType=="Sat")
	{
		document.getElementById("btnMap").className="mapTypeButton";
		document.getElementById("btnSat").className="mapTypeButtonSelect";
//		document.getElementById("btnHyb").className="mapTypeButton";
		document.getElementById("btnTer").className="mapTypeButton";
	}
/*	else if(mapType=="Hyb")
	{
		document.getElementById("btnMap").className="mapTypeButton";
		document.getElementById("btnSat").className="mapTypeButton";
		document.getElementById("btnHyb").className="mapTypeButtonSelect";
		document.getElementById("btnTer").className="mapTypeButton";
	}
*/
	else if(mapType=="Ter")
	{
		document.getElementById("btnMap").className="mapTypeButton";
		document.getElementById("btnSat").className="mapTypeButton";
//		document.getElementById("btnHyb").className="mapTypeButton";
		document.getElementById("btnTer").className="mapTypeButtonSelect";
	};
}
//Funtions for getting the all the MapIT bits that are currently loaded on the dashboard

function getMapItBitsLoadedOnDashboard(expURL,uid)
{
	if (typeof(uid) != "undefined")
	{
		var url = "/app/dashboard/dshbrdProcess.php";
		var qryStr = "fetchdata=1";
		ajaxRequest(url,qryStr,function(objRequest){

			var response = trim(objRequest.responseText);
			if(response == '{}')
			{
				return;
			}
			else
			{
				var responseArr = eval(response);
				widgetNames = '';
				for(var i=0;i<responseArr.length;i++)
				{
					var rowNo = responseArr[i].rowNo;
					var colNo = responseArr[i].colNo;
					var widgetName = responseArr[i].widgetName;
					var divChildId = "divChild"+rowNo+"X"+colNo; 
					widgetNames = widgetNames + widgetName + ',';	
				}
				widgetNames = widgetNames.substr(0, widgetNames.length - 1);
				window.open(expURL+"&widgetnames=" + widgetNames,"_self");
			}
		});
	}
	else
	{
		widgetNames = '';
		for (var i=1 ; i<=3 ; i++)
		{
			for (var j=1 ; j<=3 ; j++)
			{
				if(getCookie("widget"+i+"X"+j))
				{
					var widgetName;
					widgetName = getCookie("widget"+i+"X"+j).split(':::')[0];
					if (widgetName != "undefined")
					{
						widgetNames = widgetNames + widgetName + ',';
					}
				}
				
			}
		}		
		widgetNames = widgetNames.substr(0, widgetNames.length - 1);
		window.open(expURL+"&widgetnames=" + widgetNames,"_self");
	}
}

function getMapItBits(objRequest,expURL)
{
	var MapitBitzName = trim(objRequest.responseText);
	MapitBitzName = MapitBitzName.substr(0, MapitBitzName.length - 1);
	window.open(expURL+"&widgetnames=" + MapitBitzName,"_self");
}

var timeDiff  =  {
    setStartTime:function (){
        d = new Date();
        time  = d.getTime();
    },

    getDiff:function (){
        d = new Date();
        return (d.getTime()-time);
    }
}
var bitzTabPrev="";
var bitzTabNew="";
function changeTabImg(newTabVal)
{
	if(bitzTabNew!="")
	{
		bitzTabPrev = bitzTabNew;
		bitzTabNew = newTabVal;
	}
	else
	{
		var dgidArrAll = document.getElementsByClassName("tabSelected","tabDiv");
		dgidArrAll.each(function(nd)
		{
		   bitzTabPrev = nd.id;
		});
		bitzTabNew = newTabVal;
	}
	if($(bitzTabPrev)) 
	{
		$(bitzTabPrev).className = "tabs";	
		$(bitzTabNew).className = "tabSelected";
	}
	/*
		var dgidArrAll = document.getElementsByClassName("tabSelected");
		dgidArrAll.each(function(nd)
		{
				$(nd.id).className = "tabs";
			
		});
		var gidArrAll = document.getElementsByClassName("tabs");
		gidArrAll.each(function(nd)
		{
			if((nd.id==event))
			{
				$(nd.id).className = "tabSelected";
			}
		});
	*/ 
}
function funMakeChatWindow(userType,toChatType)
{
	if(typeof(flagB)!=='undefined' && flagB)
		document.getElementById('tooltipMainB').style.display = 'none';
	if(typeof(flag)!=='undefined' && flag)
		document.getElementById('tooltipMain').style.display = 'none';
	initResizePanel("widgetPanel");
	$('widgetPanel_h').style.display='none';
	if(typeof(initResizePanel)!='undefined')
	{
		/*if(userType=="C")
		{
			$('msgerDiv').style.display="none";
			$('loginDiv').style.display="none";
			$('registerDiv').style.display="block";
		}
		else*/ if(userType=="SP")
		{
			location.href = "../../app/ajaxim/support.php";
		}
		else
		{
			pingTimer = setInterval(ping, pingFrequency);
			$('msgerDiv').style.display="block";
			/*$('loginDiv').style.display="none";
			$('registerDiv').style.display="none";*/
		}
	}
	else
	{
		alert("include Chat Window");
	}
		
}


//function for searching by mlsno from index page header//
function funReloadAdvertise()
{
	//if(window.frames['iframeAdvertise'])
	//{
	//	window.frames['iframeAdvertise'].location.href = "/getAdvertise.php";
	//}
}

function setSearchCookie(ckName,ckValue)
{
	var strSearchCookie = getCookie("strSearchCookie");
	var arrSearchCookie = new Array();
	if(strSearchCookie != null && strSearchCookie != "")
	{
		arrSearchCookie = strSearchCookie.split(':::');
	}
	var arrNameSearchCookie = new Array();
	var arrValueSearchCookie = new Array();
	
	if(arrSearchCookie.length > 0)
	{
		for(var i=0;i<arrSearchCookie.length;i++)
		{
			var arrKeyVal = arrSearchCookie[i].split('=');
			arrNameSearchCookie[arrNameSearchCookie.length] = trim(arrKeyVal[0]);
			arrValueSearchCookie[arrValueSearchCookie.length] = trim(arrKeyVal[1]);
		}	
	}
	if(arrNameSearchCookie.find(ckName) !== false )
	{
		var ckIndex = arrNameSearchCookie.find(trim(ckName));
		arrValueSearchCookie[ckIndex] = escape(ckValue);
	}	
	else
	{
		arrNameSearchCookie[arrNameSearchCookie.length] = trim(ckName);
		arrValueSearchCookie[arrValueSearchCookie.length] = trim(escape(ckValue));
	}
	
	var strSearchCookie = "";
	for(var j=0;j<arrNameSearchCookie.length;j++)
	{
		if(j==0)
			strSearchCookie = strSearchCookie + trim(arrNameSearchCookie[j]) + '=' + trim(arrValueSearchCookie[j]); 
		else
			strSearchCookie = strSearchCookie + ':::' + trim(arrNameSearchCookie[j]) + '=' + trim(arrValueSearchCookie[j]);
	}
	
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	
	setCookie("strSearchCookie",strSearchCookie,now);
}

function getSearchCookie(ckName)
{
	var strSearchCookie = getCookie("strSearchCookie");
	var arrSearchCookie = new Array();
	if(strSearchCookie != null && strSearchCookie != "")
	{
		arrSearchCookie = strSearchCookie.split(':::');
	}
	var arrNameSearchCookie = new Array();
	var arrValueSearchCookie = new Array();
	
	if(arrSearchCookie.length > 0)
	{
		for(var i=0;i<arrSearchCookie.length;i++)
		{
			var arrKeyVal = arrSearchCookie[i].split('=');
			arrNameSearchCookie[arrNameSearchCookie.length] = trim(arrKeyVal[0]);
			arrValueSearchCookie[arrValueSearchCookie.length] = trim(arrKeyVal[1]);
		}	
	}
	
	var returnCKValue = "";
	if(arrNameSearchCookie.find(trim(ckName)) !== false)
	{
		var ckIndex = arrNameSearchCookie.find(ckName);
		returnCKValue = trim(unescape(arrValueSearchCookie[ckIndex]));
	}
	return returnCKValue;
	
}

function removeSearchCookie(ckName)
{
	var strSearchCookie = getCookie("strSearchCookie");
	var arrSearchCookie = new Array();
	if(strSearchCookie != null && strSearchCookie != "")
	{
		arrSearchCookie = strSearchCookie.split(':::');
	}
	
	var arrNameSearchCookie = new Array();
	var arrValueSearchCookie = new Array();
	
	if(arrSearchCookie.length > 0)
	{
		for(var i=0;i<arrSearchCookie.length;i++)
		{
			var arrKeyVal = arrSearchCookie[i].split('=');
			if(arrKeyVal[0] != ckName)
			{
				arrNameSearchCookie[arrNameSearchCookie.length] = trim(arrKeyVal[0]);
				arrValueSearchCookie[arrValueSearchCookie.length] = trim(arrKeyVal[1]);
			}	
		}
		var strSearchCookie = "";
		for(var j=0;j<arrNameSearchCookie.length;j++)
		{
			if(j==0)
				strSearchCookie = strSearchCookie + trim(arrNameSearchCookie[j]) + '=' + trim(arrValueSearchCookie[j]); 
			else
				strSearchCookie = strSearchCookie + ':::' + trim(arrNameSearchCookie[j]) + '=' + trim(arrValueSearchCookie[j]);
		}
	
		var now = new Date();
		now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
		setCookie("strSearchCookie",strSearchCookie,now);
	}
}
function funClrQckLocSrchCookies()
{
	removeSearchCookie("searchAddress");
	removeSearchCookie("city");
	removeSearchCookie("state");
	removeSearchCookie("zip");
	removeSearchCookie("county");
	removeSearchCookie("neighborhood");
}
function funClrQckSrchCookies()
{
	// CLEAR COOKIE RELATED TO MLSSource 
	if(typeof(clr_MLSSRC_Cookie) == 'function')	
		clr_MLSSRC_Cookie();
	if(typeof(clr_MLSSRC_Html) == 'function')	
		clr_MLSSRC_Html();	
	//UI Template Related Code
	if(typeof(clearSearchTemplateParam) == 'function' )
		clearSearchTemplateParam();
	
	removeSearchCookie('Garage');
	removeSearchCookie('Stories');
	removeSearchCookie('YearBuilt');
	removeSearchCookie('Pool');
	removeSearchCookie('Photo');
	removeSearchCookie('FirePlace');
	removeSearchCookie('searchCriteria');
	removeSearchCookie("listType");

	removeSearchCookie("spanHTML");
	removeSearchCookie("spanStyleHTML");
	removeSearchCookie("searchAddress");
	removeSearchCookie("city");
 	removeSearchCookie("state");
	removeSearchCookie("zip");
	removeSearchCookie("county");
	removeSearchCookie("neighborhood");
	removeSearchCookie("minPrice");
	removeSearchCookie("maxPrice");
	removeSearchCookie("searchBeds");
	removeSearchCookie("minSize");
	removeSearchCookie("maxSize");
	removeSearchCookie("searchBaths");
	removeSearchCookie("searchType");
	removeSearchCookie("searchSortType");
	removeSearchCookie("ckLFDate");
	removeSearchCookie("ckLTDate");
	removeSearchCookie("propStyle");
	removeSearchCookie("neighborhood");
	//removeSearchCookie("parkingType");
	
	// for power search
	removeSearchCookie("mlsSource");
	removeSearchCookie("propType");
	removeSearchCookie("propStatus");
	removeSearchCookie("area");
	removeSearchCookie("polygon");
	removeSearchCookie("salePriceFrom");
	removeSearchCookie("salePriceTo");
	removeSearchCookie("minPSize");
	removeSearchCookie("maxPSize");
	removeSearchCookie("ckPLFDate");
	removeSearchCookie("ckPLTDate");
	removeSearchCookie("listAgentFnm");
	removeSearchCookie("listAgentLnm");
	removeSearchCookie("minLotSize");
	removeSearchCookie("maxLotSize");
	removeSearchCookie("fromAge");
	removeSearchCookie("toAge");
	removeSearchCookie("fromYear");
	removeSearchCookie("toYear");
	removeSearchCookie("marketDaysFrom");
	removeSearchCookie("marketDaysTo");
	removeSearchCookie("garage");
	removeSearchCookie("stories");
	removeSearchCookie("eleSchool");
	removeSearchCookie("midSchool");
	removeSearchCookie("highSchool");
	removeSearchCookie("saleDateFrom");
	removeSearchCookie("saleDateTo");
	removeSearchCookie("saleAgentFnm");
	removeSearchCookie("saleAgentLnm");
	removeSearchCookie("salePriceFrom");
	removeSearchCookie("salePriceTo");
	removeSearchCookie("powerradial");
	removeSearchCookie("listagtid");
	removeSearchCookie("saleagtid");
	removeSearchCookie("listoff");
	removeSearchCookie("saleoff");
	removeSearchCookie("fire");
	removeSearchCookie("pool");
	removeSearchCookie("roof");
	
	setAllCookieValue("mlssource");
	setAllCookieValue("proptype");
	setAllCookieValue("propstatus");
	setAllCookieValue("sqftp");
	setAllCookieValue("listdatep");
	setAllCookieValue("listagent");
	setAllCookieValue("lotsize");
	setAllCookieValue("age");
	setAllCookieValue("yearbuilt");
	setAllCookieValue("daysonmarket");
	setAllCookieValue("garage");
	setAllCookieValue("stories");
	setAllCookieValue("eleschool");
	setAllCookieValue("midschool");
	setAllCookieValue("highschool");
	setAllCookieValue("saledate");
	setAllCookieValue("saleprice");
	setAllCookieValue("saleagent");
	setAllCookieValue("area");
	setAllCookieValue("polygon");
	setAllCookieValue("listagtid");
	setAllCookieValue("listoff");
	setAllCookieValue("saleagtid");
	setAllCookieValue("saleoff");
	setAllCookieValue("roof");
	setAllCookieValue("fire");
	setAllCookieValue("pool");
	//---------------------------------

	setAllCookieValue(null);
	headerContent(null);
	funCloseAdvanceSearch();
	
	removeSearchCookie("spanStyleHTML");
	removeSearchCookie("propStyle")
	if($('prpStyleText')) $('prpStyleText').innerHTML = "";

	if(typeof(srTabs) != "undefined" && srTabs.getTab(0).get("active"))
	{
		srTabs.set('activeTab',srTabs.getTab(0),true);
		srTabs.getTab(0).refresh();
	}
}

/**
 * add and remove the MapIt cookie
 * @param bitzNm = BitName
 * @param oprn = 'add' to add cookie 'del' to remove cookie 
 */
function setMapItCookie(bitzNm,oprn)
{
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	var strMapitCK = getCookie("strMapitCK");
	var ckAr = new Array();
	if(strMapitCK == null || trim(strMapitCK) == "")
	{
		strMapitCK = "";
		ckAr.length = 0;
	}
	else
	{
		ckAr = strMapitCK.split(',').compact();
	}
	if(oprn == "add")
	{
		var isBitz = ckAr.in_array(bitzNm);
		if(isBitz === false)
		{
			ckAr[ckAr.length] = bitzNm;
			strMapitCK = "";
			for(var i=0;i<ckAr.length;i++)
			{
				if(strMapitCK != "")
				{
					strMapitCK = strMapitCK + ',';
				}
				strMapitCK = strMapitCK + ckAr[i]; 
			}		
			setCookie("strMapitCK",strMapitCK,now);
		}
	}
	else if (oprn == "del")
	{
		var isBitz = ckAr.in_array(bitzNm);
		if(isBitz === false)
		{
			return;
		}
		else
		{
			ckAr.splice(isBitz,1);
		}
		strMapitCK = "";
		for(var i=0;i<ckAr.length;i++)
		{
			if(strMapitCK != "")
			{
				strMapitCK = strMapitCK + ',';
			}
			strMapitCK = strMapitCK + ckAr[i]; 
		}
		setCookie("strMapitCK",strMapitCK,now);
	}
}

/**
 * returns all the mapable bits in form of an array
 */
function getAllMapItCookie()
{
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	var strMapitCK = getCookie("strMapitCK");
	var ckAr = new Array();
	if(strMapitCK == null || trim(strMapitCK) == "")
	{
		strMapitCK = "";
		ckAr.length = 0;
	}
	else
	{
		ckAr = strMapitCK.split(',').compact();
	}
	return ckAr;
}

/**
 * set the mapit cookie to the list of mapable bits passed as an array
 */
function setAllMapItCookie(mapitBitsArray)
{
	for(i=0;i<mapitBitsArray.length;i++)
		setMapItCookie(mapitBitsArray[i],"add");
}

/**
 * set the mapit cookie to the list of mapable bits passed as an array
 */
function removeAllMapItCookie()
{
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	var strMapitCK = "";
	setCookie("strMapitCK",strMapitCK,now);
}


function setCSZValue(city, state, zip)
{
	var geoCSZStr = "";
	var multiCity = false;
	if ((city  == null) || (city =="") || (city  =="undefined"))
	{
		// Do nothing
	}
	else
	{
		if (city.indexOf('|') != -1)
			multiCity = true;
	}

	if (!multiCity && (zip  == null) || (zip =="") || (zip  =="undefined"))
	{
		// Do nothing
	}
	else
	{
		if (zip.indexOf('|') != -1)
			multiCity = true;
	}
	
	if (multiCity)
	{
		var cityArr = new Array();
		var stateArr = new Array();
		var zipArr = new Array();
		if ((city  == null) || (city =="") || (city  =="undefined"))
		{}
		else
		{
			cityArr = city.split('|');
		}
		if (state  =="" || state  =="undefined" || state  == null)
		{}
		else
		{
			stateArr = state.split('|');
		}
		if (zip =="" || zip  =="undefined" || zip  == null)
		{}
		else
		{
			zipArr = zip.split('|');
		}
		
		for (var i=0; i<cityArr.length; i++)
		{
			var currentCsz = "";
			if (cityArr[i]  == null || cityArr[i] == "")
			{}
			else
			{
				currentCsz += cityArr[i] + ", ";
			}
			if (stateArr[i]  == null || stateArr[i] == "")
			{}
			else
			{
				currentCsz += stateArr[i] + " ";
			}
			if (zipArr[i]  == null || zipArr[i] == "")
			{}
			else
			{
				currentCsz += zipArr[i];
			}
			
			if (currentCsz != "")
				geoCSZStr += trim(currentCsz) + ";";
				
			var geoCity 	= cityArr[i];
			var geoState 	= stateArr[i];
			var geoZip 		= zipArr[i];
			var geoCSZ 		= setCSZValue(geoCity, geoState,geoZip);
			var idTxtObj = 'searchCSZ'+ eval(i+1);
			if($(idTxtObj) != null)
				$(idTxtObj).value = trim(geoCSZ).replace (/^\s+/g, "").replace (/\s+$/g, "").replace (/\s+/g, " ");
		}
		if (geoCSZStr != "")
			geoCSZStr = geoCSZStr.substr(0, geoCSZStr.length-1);
	}
	else
	{
	 	if(city!=null)
	 	{
			if ((city  == null) || (city =="") || (city  =="undefined"))
			{
				
			}
			else
			{
				geoCSZStr = city + ", ";
			}
	 	}
	 	if(state!=null)
	 	{
			if (state  =="" || state  =="undefined" || state  == null)
			{
				
			}
			else
			{
				geoCSZStr += state +" ";
			}
	 	}
	 	if(zip!=null)
	 	{
			if (zip =="" || zip  =="undefined" || zip  == null)
			{
				
			}
			else
			{
				geoCSZStr += zip;
			}
	 	}
	}
	
 	if(trim(geoCSZStr) == "" )
 	{
 		geoCSZStr = "Neighborhood, City or ZIP code";
 	}
 	return trim(geoCSZStr);
}
function funWrapText(str,len)
{
	if(str.length > len)
	{
		str = str.substr(0,len)+' ...';
	}
	return str;
}

function explore(page)
{	

	/* */
	// IF NEW LISTING THEN LAST 15 DAYS DATE DURATION WOULD BE SET
	if($('bit_select_box') && $F('bit_select_box') == 'newListing')
	{
		$("RStxtLFDate").value = listDate1;
		$("RStxtLTDate").value = listDate2;
		setSearchCookie("listType",$F('bit_select_box'));
	}
	else if($('bit_select_box') && $F('bit_select_box') != 'newListing')
	{
		lfDate = ''; ltDate = '';
		$("RStxtLFDate").value = '';
		$("RStxtLTDate").value = '';
		setSearchCookie("listType",$F('bit_select_box'));
	}
	setSearchCookie("ckLFDate",($("RStxtLFDate"))?($F("RStxtLFDate")):"");
	setSearchCookie("ckLTDate",($("RStxtLTDate"))?($F("RStxtLTDate")):"");



	if (countySearchEnabled == "0" && checkMultiCity() == false && trim(getSearchCookie("neighborhood")) != "")
	{
		setSearchCookie("county", "");
	}
	if ( bkTheme != "terabitz" && trim($("searchMLS").value) != "")
	{
		var allBitz = getAllMapItCookie().toString();
		allBitz = allBitz.split(",");

		if(allBitz.length >= 10)
		{	
			alert("Please close atleast one bit, then enter MLS Number.");
			return;
		}

		if (page=="agentSiteListing")
			searchByMlsNoAgentSite();
		else if(page == "singlePropPower")
		{
			if(typeof(powerSearch) != 'undefined' && powerSearch == "1" && (uRole == "EA" || uRole == "A"))
			{
				var mlsurl = "../../app/dashboard/mlsSearch.php";
			    var mlsstr = "mlsno="+trim($("searchMLS").value)+ "&forAlert=1&mlsSource="+getSearchCookie('mlsSource')+"&ignorestatus=1&theme="+bkTheme+"&aid="+uid;
				
				ajaxRequest(mlsurl,mlsstr,function(r){
					response = trim(r.responseText);
					if(response == '0')	           
					{
						alert('MLS NO. not found.');
						return;
					}
					else
					{
						dataArr = response.split("&")[1].split("=")[1].split(",");
						var city = dataArr[1];
						var state = dataArr[2];
						var zip = dataArr[3];
						var lat = dataArr[7];
						var lng = dataArr[8];

						setSearchCookie("city",city);
						setSearchCookie("state",state);
						setSearchCookie("zip",zip);

						var latLongStr = "[{'lat':'"+lat+"','lng':'"+lng+"'}]";
						var now = new Date();
						now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
						setCookie("latLongCk",latLongStr,now);

						setSearchCookie("mlsno",trim($("searchMLS").value));
						setSearchCookie("area","");
						setSearchCookie("polygon","");
						funExplorePowerSearch();
					}
				});
			}
		}
		else
			searchByMlsNo();
		return;
	}
	else if($("searchMLS").value != "" && ($("searchCSZ").value == "" || $F("searchCSZ").toLowerCase() == "required"))
	{
		alert("Please enter City or Zip along with MLS Number.");
		return;
	}
	else if($("searchMLS").value != "")
	{
		var myStatus = funCheckContradict();
		if(myStatus != null && myStatus != 0)
		{
			if (page=="agentSiteListing")
				searchByMlsNoAgentSite();
			else
				searchByMlsNo();
		}
		return;
	}
	var csz = $("searchCSZ").value.replace (/^\s+/g, '').replace (/\s+$/g, '').replace (/\s+/g, ' ');
	var addr= $("searchAddress").value.replace (/^\s+/g, '').replace (/\s+$/g, '').replace (/\s+/g, ' ');
	/*if (trim(csz) == "")
	{
		alert ("Please specify either City or Zip");
		return false;
	}
	else */
	if (trim(csz) == "" || trim(csz).toLowerCase() == "required")
	{
		if(page == "singlePropPower")
		{
			if($("txtArea") && $("txtArea").value == "")
			{
				alert ("Please specify either City or Zip");
				return false;
			}
			else
			{				
				var status = funSaveAdvanceSearch("power","singlePropPower");
				
				if(status == true)
				{
					if(getSearchCookie("mlsno") && getSearchCookie("mlsno") != "")
						setSearchCookie("mlsno","");
					funExplorePowerSearch();
				}
			}
		}
		else
		{
			alert ("Please specify either City or Zip");
			return false;
		}
	}
	else if ( addr!="optional" && addr!="")
	{
		var contradict = funCheckContradict();
		if(contradict != null && contradict != 0)
		{
			var contradict = funReloadAdvertise();

			if(typeof(powerSearch) != 'undefined' && powerSearch == "1" && (uRole == "EA" || uRole == "A"))
			{		
				/*
				[{"status":"0","originaladdress":"4214 E Arch Rd, Stockton, CA ","statuscode":"200","country":"US","accuracy":"8","address":"4214 E Arch Rd","state":"CA","city":"Stockton","zip":"95215","latitude":"37.905234","longitude":"-121.214809"}]
				*/
				var url = "../../classes/getCSZ.php";
			    var qs = "csz="+trim($("searchCSZ").value)+"&address="+addr;
				
				ajaxRequest(url,qs,function(r){
					response = eval('(' + trim(r.responseText) + ')');

					if(response[0].status == "0")
					{
						var addr = response[0].address;
						var city = response[0].city;
						var state = response[0].state;
						var zip = response[0].zip;
						var lat = response[0].latitude;
						var lng = response[0].longitude;

						setSearchCookie("searchAddress",addr);
						setSearchCookie("city",city);
						setSearchCookie("state",state);
						setSearchCookie("zip",zip);

						var latLongStr = "[{'lat':'"+lat+"','lng':'"+lng+"'}]";
						var now = new Date();
						now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
						setCookie("latLongCk",latLongStr,now);
							
						funExplorePowerSearch();
					}
				});
			}
			else
			{
				var allBitz = getAllMapItCookie().toString();
				allBitz = allBitz.split(",");

				if(allBitz.length >= 10)
				{	
					alert("Please close atleast one bit, then enter Address.");
					return;
				}
				funExploreMlsAddrMap();
			}
			
			return;
		}
	}
	else
	{
		var cszFromCk = setCSZValue(getSearchCookie("city"), getSearchCookie("state"), getSearchCookie("zip"));
		var contradict = funCheckContradict();
		if(contradict != null && contradict != 0)
		{
			var contradict = funReloadAdvertise();
			if(page == "index")
			{
				gotoDashBrd();
			}	
			else if(page=="dashboard")
			{
				funQckUpdateWidgets();		
			}
			else if(page=="singleProp")
			{
				funExploreOnMapit();
			}
			else if(page=="singlePropPower")
			{
				var status = funSaveAdvanceSearch("power","singlePropPower");
				
				if(status == true)
				{
					if(getSearchCookie("mlsno") && getSearchCookie("mlsno") != "" && $("searchCSZ").value != "")
					{
						setSearchCookie("mlsno","");
					}
					else
					{
						if($('searchCSZ') != null)
						{
							$('searchCSZ').value = $('searchCSZ').value.replace (/^\s+/g, "").replace (/\s+$/g, "").replace (/\s+/g, " ");
							if (trim(cszFromCk).toUpperCase() != trim($('searchCSZ').value).toUpperCase())
							{
								if(getSearchCookie("area") && getSearchCookie("area") == $("txtArea").value)
								{
									setSearchCookie("area","");
									setSearchCookie("polygon","");
								}
							}
						}	
					}
					funExplorePowerSearch();
				} 
			}
			else if(page=="agentSiteListing")
			{
				funAgentSiteSearch();
			}
		}	
	}	
}
function funAgentSiteSearch(page,valOrderBy,typeOrderBy,searchByMlsNo)
{
	var cbfnAgentSite = function(reqObj)
	{
		var response = trim(reqObj.responseText);
		var arrResponseCount = response.split('|==|');
		var responseCount = arrResponseCount[0];
		var responseHTML = arrResponseCount[1];
		$('listDiv').innerHTML = responseHTML;
		if(parseInt(responseCount) > 0)
		{
			$('propSortBar').style.display = 'block';
		}
	}
	var url = "./getListing.php";
	var qs = funGetSearchQueryString();

	var objQS = new Querystring();
	var aid = objQS.get('aid');
	
	qs = qs + "&aid="+aid;

	if(page != null)
	{
		qs = qs + "&page="+page;
	}
	else
	{
		qs = qs + "&page=1";
	}
	if(valOrderBy != null)
	{
		qs = qs + "&valOrderBy="+valOrderBy;
	}
	else
	{
		qs = qs + "&valOrderBy=price";
	}
	if(typeOrderBy != null)
	{
		qs = qs + "&typeOrderBy="+typeOrderBy;
	}
	else
	{
		qs = qs + "&typeOrderBy=asc";
	}
	if(searchByMlsNo != null)
	{
		qs = qs + "&MlsSearch="+searchByMlsNo;
	}
	else
	{
		qs = qs + "&MlsSearch=0";
	}
	$('listDiv').innerHTML = '';
	ajaxRequest(url,qs,cbfnAgentSite);
}

function searchByMlsNoAgentSite()
{
	var cbfnAgentSite = function(reqObj)
	{
		var response = trim(reqObj.responseText);
		var arrResponseCount = response.split('|==|');
		var responseCount = arrResponseCount[0];
		var responseHTML = arrResponseCount[1];
		$('listDiv').innerHTML = responseHTML;
		if(parseInt(responseCount) > 0)
		{
			$('propSortBar').style.display = 'block';
		}
	}
	var url = "./getListing.php";
	var qs = "";
        var objQS = new Querystring();
        var aid = objQS.get('aid');
        qs = qs + "&aid="+aid;


	var mlsNo = objQS.get('mlsno');
	if(mlsNo!=null && mlsNo!='')
	{
		qs = qs + "&MlsSearch="+mlsNo;
	}
	else
	{
		qs = qs + "&MlsSearch="+trim($("searchMLS").value);
	}

	//qs = qs + "&MlsSearch=1";
    qs = qs + "&valOrderBy=price";
    qs = qs + "&typeOrderBy=asc";

	$('listDiv').innerHTML = '';
	ajaxRequest(url,qs,cbfnAgentSite);
}

var	recordDialogBox = "";
var	agtOffDlgBox = "";
function searchByMlsNo()
{
	if ($("searchMLS").value == "")
	{
		alert("Please input MLS number to search.");
		$("searchMLS").value = "";
		$("searchMLS").focus();
		return;
	}
	var mlsno = trim($("searchMLS").value);
	var qStr = "mlsno="+escape(mlsno);
	qStr += "&city="	+ trim(getSearchCookie("city"));
	qStr += "&state="	+ trim(getSearchCookie("state"));
	qStr += "&zip="		+ trim(getSearchCookie("zip"));
	var myQs = new Querystring();
	var frm = myQs.get("frm");
	var aid = myQs.get("aid");
	
	if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
	{
		if(typeof(strAgtMlsSrc) != 'undefined' && strAgtMlsSrc != null && strAgtMlsSrc.length > 0)
			qStr = qStr + "&mlsSource="	+ 	escape((trim(strAgtMlsSrc)));
		else
			qStr = qStr + "&mlsSource=";
		qStr = qStr + "&aid="+	escape((trim(aid)));

		//agentsite statistics
		var city = getSearchCookie("city");
		var ad = getSearchCookie("searchAddress");
		var beds = getSearchCookie("searchBeds");
		var baths = getSearchCookie("searchBaths");
		var type = getSearchCookie("searchType");
		var minprice = getSearchCookie("minPrice");
		var maxprice = getSearchCookie("maxPrice");

		var url = "../../classes/emailStats.php";
		var qs = "from=search&aid="+aid+"&city="+city+"&type="+type+"&beds="+beds+"&baths="+baths+"&price="+minprice+"-"+maxprice+"&addr="+ad+"&mlsno="+mlsno;

		ajaxRequest(url,qs);
		//statistics done
	}	
	var url  = "/app/dashboard/mlsSearch.php";
	ajaxRequest(url,qStr,cbfnSearchByMlsNo);
}

function funRedirectToMLS(urlMLS)
{
	funClrQckLocSrchCookies();
	removeAllMapItCookie();	
	var myQs = new Querystring();
	var frm = myQs.get("frm");
	var aid = myQs.get("aid");
	
	if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
	{
		urlMLS = urlMLS + '&frm=agt&aid='+aid;
	}	
	window.location.href = unescape(urlMLS);
}

function cbfnSearchByMlsNo(originalRequest)
{
	var response = originalRequest.responseText;
	if (response == 0)
	{
		alert("MLS Number Not found.");
		$("searchMLS").value = "";
		$("searchMLS").focus();
		return;
	}
	else
	{
		if(response.include("|^|"))
		{
			var arrResponse = response.split("|^|");
			var strIH = new StringBuffer();
			strIH.append(' <div id="divMLSConfirmBox" style="background-color:#B0B0B0;display: none;border: 0px solid rgb(0, 0, 0); padding: 20px; height: 150px; width: 530px; position: fixed; top: 225px; left: 255px; visibility: inherit;" >');
			strIH.append(' 	<table cellspacing="0" cellpadding="0" bordercolor="red" border="0" style="width: 100%; height: 100%;">');
			strIH.append(' 		<tr style="height: 8px;">');
			strIH.append(' 			<td valign="bottom" class="crvTopLeft"></td>');
			strIH.append(' 			<td valign="bottom" class="crvTopMid" style="width: 500px;"></td>');
			strIH.append(' 			<td valign="bottom" class="crvTopRight"></td>');
			strIH.append(' 		</tr>');
			strIH.append(' 		<tr style="height: 90%;width:520px;">');
			strIH.append(' 			<td style="background-color: rgb(255, 255, 255);" class="crvLeftMid"></td>');
			strIH.append(' 			<td style="background-color: rgb(255, 255, 255);">');

			strIH.append('<table style="width:100%;height:100%">');
			strIH.append('<tr>');
			strIH.append('<td>');
			strIH.append('<img src="../../wt/'+bkTheme+'/images/common/imgConfirm.gif" alt="conform" />');
			strIH.append('</td>');
			strIH.append('<td  class="moduleDescText">');
			strIH.append('<div style="position: relative;font-size:11px;width: 79%;float: left;display: inline;padding-left: 5px;height:100%;vertical-align: middle;" align="left" id="divMLSConfirmMessageText">');
			strIH.append('&nbsp;');
			strIH.append('</div>');
			strIH.append('</td>');
			strIH.append('<tr>');
			strIH.append('<td colspan="2" align="center" valign="top">');
			strIH.append('<button style="width:50px;" onclick="javascript:myPopup();" class="lang" type="button" name="btnOK" id="btnOK">Yes</button>');
			strIH.append('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button class="lang" type="button" name="btnCancel" id="btnCancel" onclick="dlgMLSConfirmBox.hide();" style="width:50px;">No</button>');
			strIH.append('</td>');
			strIH.append('</tr>');
			strIH.append('</table>');

			strIH.append(' 			</td>');
			strIH.append(' 			<td style="background-color: rgb(255, 255, 255);" class="crvRightMid"></td>');
			strIH.append(' 		</tr>');
			strIH.append(' 		<tr style="height: 8px;">');
			strIH.append(' 			<td class="crvBotLeft"></td>');
			strIH.append(' 			<td class="crvBotMid"></td>');
			strIH.append(' 			<td class="crvBotRight"></td>');
			strIH.append(' 		</tr>');
			strIH.append(' 	</table>');
			strIH.append(' </div><style type="text/css">.closeMy{background-image:url(../../wt/'+bkTheme+'/images/common/close_dlgLog.gif);}</style>');
			
			myPopup = function()
			{
				response = arrResponse[1];
				dlgMLSConfirmBox.hide();
				loadMlsNumberProp(response);
				
			}

			function funRedirectToOther()
			{
				response = arrResponse[1];
				loadMlsNumberProp(response);
			}

			function funCnfrmRedirectToOther()
			{
				var closeBox = document.getElementsByClassName("close","divMLSConfirmBox")[0];
				if(closeBox)
				{
					closeBox.removeClassName("nonsecure");
					closeBox.addClassName("closeMy");
				}
				$('divMLSConfirmMessageText').innerHTML = "Redirecting to our Partners Site: <b>"+arrResponse[0]+"</b>";
				$("divMLSConfirmBox").style.display="block";	
				dlgMLSConfirmBox.show();
			}
			if($("divMLSConfirmBox") == null)
			{
				var myIH = strIH.toString();var myDiv = document.createElement("div");myDiv.innerHTML = myIH;document.body.appendChild(myDiv);							
				dlgMLSConfirmBox = createDialog('divMLSConfirmBox');
				
			}
			//funCnfrmRedirectToOther();				
			funRedirectToOther();
			//alert("Redirecting to our Partner's site '" + arrResponse[0] +"'");
			
		}
		else
		{
			loadMlsNumberProp(response);
		}
	}
}

function loadMlsNumberProp(response)
{
	var arrMlsRecords = new Array();	
	var arrRecords = new Array();	
	arrMlsRecords = response.split('\n');

	if(arrMlsRecords.length == 1)
	{
		arrRecords = arrMlsRecords[0].split('|');
		funRedirectToMLS(arrRecords[8]);
	}
	else
	{
		var mlsNumber;
		var detailRecords="";
		var startRecords;
		var recLen = arrMlsRecords.length;
		// Build table for div
		
		for(var i=0;i<recLen;i++)
		{
			arrRecords = arrMlsRecords[i].split('|');
			mlsNumber  = arrRecords[0];
			detailRecords += "<tr style=\"height:25px\"><td width=\"60%\" class=\"mlsLightBoxDescText\" align=\"left\" valign=\"top\">&nbsp;<a class=\"mlsHeadDis\" href=\"javascript:void(0);\" onclick=\"javascript:funRedirectToMLS(\'"+arrRecords[8]+"\');\"><b><span class=\"crsr\">"+arrRecords[1]+", "+arrRecords[2]+", "+arrRecords[3]+", "+arrRecords[4]+"</span></b></a></td><td width=\"15%\" class=\"mlsLightBoxDescText\" valign=\"top\">&nbsp;<a class=\"mlsHeadDis\" href=\"javascript:void(0);\" onclick=\"javascript:funRedirectToMLS(\'"+arrRecords[8]+"\');\"><b><span class=\"crsr\">"+num2money(arrRecords[5])+"</span></b></a></td><td width=\"15%\" class=\"mlsLightBoxDescText\" valign=\"top\">&nbsp;<a class=\"mlsHeadDis\" href=\"javascript:void(0);\" onclick=\"javascript:funRedirectToMLS(\'"+arrRecords[8]+"\');\"><b><span class=\"crsr\">"+arrRecords[6]+"-Br/"+arrRecords[7]+"-Ba</span></b></a></td></tr>";
		}			
		
		startRecords = "<table width=\"100%\" height=\"98%\" class=\"mlsLightBoxLableText\">";
		startRecords += "<tr style=\"height:25px\"><td class=\"mlsLightBoxTopLableText\" colspan=\"3\" align=\"left\" style=\"height:20px\">Total "+recLen+" listings were found. For more details, click on below link.</td></tr>";
		startRecords += "<tr><td height=\"5px\" colspan=\"3\"></td></tr>";
		startRecords = startRecords+detailRecords;
		startRecords += "</table>";
		
		if(typeof(recordDialogBox) == "string")
		{
			recordDialogBox = createDialog("recordsDialog");	
		}
		
		var ht = (recLen+1)*25;
		if(recLen>3)
			ht = "100%";
		else
		{
			if(isIE)
				ht = "85%";//ht+"px";
			else
				ht = "80%";//ht+"px";
		}
		$("recordsDialog").getElementsByClassName("bd")[0].style.height = ht;
		$("recordsDialog").getElementsByClassName("bd")[0].innerHTML = startRecords;
		$("recordsDialog").getElementsByClassName("hd")[0].innerHTML = "Listing Of MLS Number : "+mlsNumber;			
		$("recordsDialog").style.display="block";
		recordDialogBox.show();			
	}
}
function setAllToCookie(srchcrt,from)
{
	if(srchcrt == null)
	{
		if ($F("searchAddress").toLowerCase() == "optional" || $F("searchAddress") == "undefined" || $F("searchAddress") == null)
		{
			setSearchCookie("searchAddress","");
		}
		else
		{
			setSearchCookie("searchAddress",($("searchAddress"))?$F("searchAddress"):"");
		}
	}
	if(srchcrt == "neighborhood")
	{			
		if(typeof(from)!="undefined")
		{
			divId = "divNHood";
			chkAllId = "chbRSNHAll";
		}
		else
		{
			divId = "divSHDataNeighborHood";
			chkAllId = "chbSHNHAll";
		}
		if($(divId))
		{
			var arrChkBox = $(divId).getElementsByTagName("input");
			var lenArrChkBox = arrChkBox.length;
			var strCKNH = "";
			for(var i=0;i<lenArrChkBox;i++)
			{
				if(arrChkBox[i].id == chkAllId && arrChkBox[i].checked == true)
				{
					strCKNH = 'all';
					break;
				}
				if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
				{
					var valChkBox = arrChkBox[i].value;
					strCKNH = strCKNH + valChkBox + ",";  	
				}
			}
			if(strCKNH.charAt(strCKNH.length-1) == ',')
			{
				strCKNH = strCKNH.substr(0,eval(strCKNH.length-1));
			}
			setSearchCookie("neighborhood",strCKNH);
			if(srchcrt != null)
			{
				return;
			}
		}
	}
	if(srchcrt == "county")
	{		
		var dv = "";
		if(typeof(from) != "undefined")
			dv = "divRSCounty";
		else
			dv = "divSHDataCounty";

		if($(dv))
		{
			var arrChkBox = $(dv).getElementsByTagName("input");
			var lenArrChkBox = arrChkBox.length;
			var strCKCounty = "";
			for(var i=0;i<lenArrChkBox;i++)
			{
				if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
				{
					var valChkBox = arrChkBox[i].value;
					strCKCounty = strCKCounty + valChkBox + ",";  	
				}
			}
			
			if(strCKCounty.charAt(strCKCounty.length-1) == ',')
			{
				strCKCounty = strCKCounty.substr(0,eval(strCKCounty.length-1));
			}

			if(trim(strCKCounty) != "")
			{
				setSearchCookie("county",strCKCounty);
				removeSearchCookie("neighborhood");
				headerContent("neighborhood");
			}
			else
			{
				// If no County selected then just remove county from cookie
				removeSearchCookie("county");
			}
		}
		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "price")
	{			
		setSearchCookie("minPrice",($("minPrice"))?(money2num($F("minPrice"))):"");
		setSearchCookie("maxPrice",($("maxPrice"))?(money2num($F("maxPrice"))):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "beds")
	{			
		var srchBds = "";
		var minBeds = trim($("searchBedsMin").value);
		if(minBeds == "0") minBeds = "";
		if(minBeds != "" && minBeds.indexOf(".") == (minBeds.length-1)) minBeds = minBeds+"0";
		if(minBeds != "" && minBeds.indexOf(".") == 0) minBeds = "0"+minBeds;

		var maxBeds = trim($("searchBedsMax").value)
		if(maxBeds == "0") maxBeds = "";
		if(maxBeds != "" && maxBeds.indexOf(".") == (maxBeds.length-1)) maxBeds = maxBeds+"0";
		if(maxBeds != "" && maxBeds.indexOf(".") == 0) maxBeds = "0"+maxBeds;

		srchBds = minBeds+"-"+maxBeds;
		if(trim(srchBds) == "-")
			srchBds = "";
		setSearchCookie("searchBeds",srchBds);

		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "sqft")
	{			
		setSearchCookie("minSize",($("minSize"))?$F("minSize")==0?"":$F("minSize"):"");
		setSearchCookie("maxSize",($("maxSize"))?$F("maxSize")==0?"":$F("maxSize"):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "baths")
	{			
		var srchBths = "";
		var minBath = trim($("searchBathsMin").value);
		if(minBath == "0") minBath = "";
		if(minBath != "" && minBath.indexOf(".") == (minBath.length-1)) minBath = minBath+"0";
		if(minBath != "" && minBath.indexOf(".") == 0) minBath = "0"+minBath;

		var maxBath = trim($("searchBathsMax").value);
		if(maxBath == "0") maxBath = "";
		if(maxBath != "" && maxBath.indexOf(".") == (maxBath.length-1)) maxBath = maxBath+"0";
		if(maxBath != "" && maxBath.indexOf(".") == 0) maxBath = "0"+maxBath;

		srchBths = minBath+"-"+maxBath;
		if(trim(srchBths) == "-")
			srchBths = "";
		setSearchCookie("searchBaths",srchBths);

		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "type")
	{
		if(typeof(from)!="undefined")
		{
			divId = "divRSType";
			chkAllId = "RSchbSHTypeAll";
		}
		else
		{
			divId = "divPopUpSHType";
			chkAllId = "chbSHTypeAll";
		}
		var arrChkBox = $(divId).getElementsByTagName("input");
		var lenChkBox = arrChkBox.length;		
		var strChkBox = "";
		var allChked = true;		
		for(var i=0;i<lenChkBox;i++)
		{			
	    	if(arrChkBox[i].id == chkAllId)
	    	{
	    		continue;
	    	}
	    	if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
	    	{
	    	    var valChkBox = arrChkBox[i].value;
	    	    strChkBox = strChkBox + valChkBox + ':';				
	    	}
	    	else if(arrChkBox[i].type == "checkbox")
	    	{
	    	    allChked = false;    
	    	}
		}
		if(allChked == true)
		{
	    	strChkBox = "";
		}
		else if(strChkBox.charAt(strChkBox.length-1) == ':')
		{
			strChkBox = strChkBox.substr(0,eval(strChkBox.length-1));
		}		
		setSearchCookie("searchType",strChkBox);		
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "sortby")
	{			
		setSearchCookie("searchSortType",($("searchSortType"))?$F("searchSortType"):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "listdate")
	{			
		setSearchCookie("ckLFDate",($("txtLFDate"))?($F("txtLFDate")):"");
		setSearchCookie("ckLTDate",($("txtLTDate"))?($F("txtLTDate")):"");
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "mlssource")
	{
		setSearchCookie("mlsSource",($("mlsSource"))?($F("mlsSource")):"");
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "proptype" && $("divPType"))
	{			
		//setSearchCookie("propType",($("propTypes"))?($F("propTypes")):"");			
		var arrChkBox = $("divPType").getElementsByTagName("input");
		var strChkd = "";

		for(i=0;i<arrChkBox.length;i++)
		{
			if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
	    	{
				strChkd += arrChkBox[i].value + ':';
			}
		}
		
		if(strChkd.charAt(strChkd.length-1) == ':')
			strChkd = strChkd.substr(0,eval(strChkd.length-1));

		setSearchCookie("propType",strChkd);

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "propstatus" && $("divPStatus"))
	{
		/*setSearchCookie("propStatus",($("propStatus"))?($F("propStatus")):"");
		if(srchcrt != null)
		{
			return;
		}*/

		var arrChkBox = $("divPStatus").getElementsByTagName("input");
		var strChkd = "";

		for(i=0;i<arrChkBox.length;i++)
		{
			if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
	    	{
				strChkd += arrChkBox[i].value + ':';
			}
		}
		
		if(strChkd.charAt(strChkd.length-1) == ':')
			strChkd = strChkd.substr(0,eval(strChkd.length-1));

		setSearchCookie("propStatus",strChkd);

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "sqftp")
	{
		setSearchCookie("minPSize",($("minPSize"))?$F("minPSize")==0?"":$F("minPSize"):"");
		setSearchCookie("maxPSize",($("maxPSize"))?$F("maxPSize")==0?"":$F("maxPSize"):"");
		if(srchcrt != null)
		{
			return;
		}		
	}
	if(srchcrt != null && srchcrt == "listagent")
	{
		if($('txtAgtFName').value != 'First Name')
			setSearchCookie("listAgentFnm",($("txtAgtFName"))?($F("txtAgtFName")):"");
		else
			setSearchCookie("listAgentFnm","");

		if($('txtAgtLName').value != 'Last Name')				
			setSearchCookie("listAgentLnm",($("txtAgtLName"))?($F("txtAgtLName")):"");
		else
			setSearchCookie("listAgentLnm","");

		if(srchcrt != null)
		{
			return;
		}		
	}
	if(srchcrt != null && srchcrt == "listdatep")
	{			
		setSearchCookie("ckPLFDate",($("txtPLFDate"))?($F("txtPLFDate")):"");
		setSearchCookie("ckPLTDate",($("txtPLTDate"))?($F("txtPLTDate")):"");
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "lotsize")
	{
		setSearchCookie("minLotSize",($("minLotSize"))?$F("minLotSize")==0?"":$F("minLotSize"):"");
		setSearchCookie("maxLotSize",($("maxLotSize"))?$F("maxLotSize")==0?"":$F("maxLotSize"):"");
		if(srchcrt != null)
		{
			return;
		}		
	}
	if(srchcrt != null && srchcrt == "age")
	{			
		setSearchCookie("fromAge",($("txtAgeFrom"))?(money2num($F("txtAgeFrom"))):"");
		setSearchCookie("toAge",($("txtAgeTo"))?(money2num($F("txtAgeTo"))):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt != null && srchcrt == "yearbuilt")
	{			
		setSearchCookie("fromYear",($("txtYearBuiltFrom"))?(money2num($F("txtYearBuiltFrom"))):"");
		setSearchCookie("toYear",($("txtYearBuiltTo"))?(money2num($F("txtYearBuiltTo"))):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt != null && srchcrt == "daysonmarket")
	{			
		setSearchCookie("marketDaysFrom",($("txtDaysMarketFrom"))?(money2num($F("txtDaysMarketFrom"))):"");
		setSearchCookie("marketDaysTo",($("txtDaysMarketTo"))?(money2num($F("txtDaysMarketTo"))):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt != null && srchcrt == "garage")
	{			
		if(typeof(from)!="undefined")
			var cmbId = "RScmbGarage";
		else
			var cmbId = "cmbGarage";

		setSearchCookie("garage",($(cmbId))?$F(cmbId)==0?"":$F(cmbId):"");

		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt != null && srchcrt == "stories")
	{			
		setSearchCookie("stories",($("txtStories"))?($F("txtStories")):"");		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "bankowned")
	{			
		setSearchCookie("bankowned",$("chkBankOwned").value);
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "shortsales")
	{			
		setSearchCookie("shortsales",$("chkShortSales").value);
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "schooldist")
	{			
		setSearchCookie("schooldist",($("txtSchoolDist"))?($F("txtSchoolDist")):"");		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "eleschool")
	{			
		setSearchCookie("eleSchool",($("txtEleSchool"))?($F("txtEleSchool")):"");		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "midschool")
	{			
		setSearchCookie("midSchool",($("txtMidSchool"))?($F("txtMidSchool")):"");		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "highschool")
	{			
		setSearchCookie("highSchool",($("txtHighSchool"))?($F("txtHighSchool")):"");		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saledate")
	{			
		setSearchCookie("saleDateFrom",($("txtSFDate"))?($F("txtSFDate")):"");
		setSearchCookie("saleDateTo",($("txtSTDate"))?($F("txtSTDate")):"");
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saleprice")
	{			
		setSearchCookie("salePriceFrom",($("txtSalePriceFrom"))?(money2num($F("txtSalePriceFrom"))):"");
		setSearchCookie("salePriceTo",($("txtSalePriceTo"))?(money2num($F("txtSalePriceTo"))):"");
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt != null && srchcrt == "saleagent")
	{
		if($('txtSaleAgentFname').value != 'First Name')
			setSearchCookie("saleAgentFnm",($("txtSaleAgentFname"))?($F("txtSaleAgentFname")):"");
		else
			setSearchCookie("saleAgentFnm","");

		if($('txtSaleAgentLname').value != 'Last Name')				
			setSearchCookie("saleAgentLnm",($("txtSaleAgentLname"))?($F("txtSaleAgentLname")):"");
		else
			setSearchCookie("saleAgentLnm","");

		if(srchcrt != null)
		{
			return;
		}		
	}
	if(srchcrt != null && srchcrt == "area")
	{			
		setSearchCookie("area",($("txtArea"))?($F("txtArea")):"");		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "polygon")
	{			
		setSearchCookie("polygon",($("txtPolygon"))?($F("txtPolygon")):"");		
		//alert(getSearchCookie("polygon"))
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "powerradial")
	{			
		setSearchCookie("powerradial",$F("cmbradial"));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "listagtid")
	{			
		setSearchCookie("listagtid",trim($F("txtListAgtId")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "listoff")
	{			
		setSearchCookie("listoff",trim($F("txtListOff")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saleagtid")
	{			
		setSearchCookie("saleagtid",trim($F("txtSaleAgtId")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saleoff")
	{			
		setSearchCookie("saleoff",trim($F("txtSaleOff")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "roof")
	{			
		setSearchCookie("roof",trim($F("txtRoof")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "fire")
	{			
		setSearchCookie("fire",trim($F("cmbFire")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "pool")
	{			
		setSearchCookie("pool",trim($F("cmbPool")));

		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "propstyle")
	{		
		if(typeof(from)!="undefined")
		{
			divId = "RSpropStyleDv";
			chkAllId = "RSchkStyleAll";
		}
		else
		{
			divId = "propStyleDv";
			chkAllId = "chkStyleAll";
		}

		if($(divId))
		{
			var arrChkBox = $(divId).getElementsByTagName("input");
			var lenChkBox = arrChkBox.length;
			var strChkBox = "";
			var allChked = true;
			for(var i=0;i<lenChkBox;i++)
			{
				if(arrChkBox[i].id == chkAllId)
				{
					continue;
				}
				if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
				{
					var valChkBox = arrChkBox[i].value;
					strChkBox = strChkBox + valChkBox + ':';
				}
				else if(arrChkBox[i].type == "checkbox")
				{
					allChked = false;    
				}
			}
			if(allChked == true)
			{
				strChkBox = "";
			}
			else if(strChkBox.charAt(strChkBox.length-1) == ':')
			{
				strChkBox = strChkBox.substr(0,eval(strChkBox.length-1));
			}
			setSearchCookie("propStyle",strChkBox);
		}
		else
			setSearchCookie("propStyle","");

		if(srchcrt != null)
		{
			return;
		}
	}
	/*if(srchcrt == null || srchcrt == "parkingtype")
	{
		if($("parkingStyleDv"))
		{
			var arrChkBox = $("parkingStyleDv").getElementsByTagName("input");
			var lenChkBox = arrChkBox.length;
			var strChkBox = "";
			var allChked = true;
			for(var i=0;i<lenChkBox;i++)
			{
				if(arrChkBox[i].id == "chkParkingStyleAll")
				{
					continue;
				}
				if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
				{
					var valChkBox = arrChkBox[i].value;
					strChkBox = strChkBox + valChkBox + ':';
				}
				else if(arrChkBox[i].type == "checkbox")
				{
					allChked = false;    
				}
			}
			if(allChked == true)
			{
				strChkBox = "";
			}
			else if(strChkBox.charAt(strChkBox.length-1) == ':')
			{
				strChkBox = strChkBox.substr(0,eval(strChkBox.length-1));
			}
			setSearchCookie("parkingType",strChkBox);
		}
		else
			setSearchCookie("parkingType","");

		if(srchcrt != null)
		{
			return;
		}
	}*/
}
function setAllCookieValue(srchcrt)
{
	
	if(srchcrt == null)
	{
		if($("searchAddress"))
		{
			
			$("searchAddress").value = (trim(getSearchCookie("searchAddress")) == "")?"optional":trim(getSearchCookie("searchAddress"));
			$("searchAddress").className = "textboxDashHdN";
		}
		if($('searchCSZ'))
		{
			var cszFromCookie = setCSZValue(getSearchCookie("city"), getSearchCookie("state"), getSearchCookie("zip"));
			$('searchCSZ').value = trim(cszFromCookie).replace (/^\s+/g, "").replace (/\s+$/g, "").replace (/\s+/g, " ");
			if(trim(getSearchCookie('city')) == "" && trim(getSearchCookie('zip')) == "")
			{
				for(var i=0;i<20;i++)
				{
					var idTxtObj = 'searchCSZ'+ eval(i+1);
					if($(idTxtObj) != null)
						$(idTxtObj).value = "";
				}
			}	
		}
		if($('searchMLS'))
		{
			$('searchMLS').value = "";
		}
	}	
	if(srchcrt == null || srchcrt == "price")
	{
		if($("minPrice"))
		{
			if(getSearchCookie("minPrice") != 0)
				$("minPrice").value = addCommas(getSearchCookie("minPrice"));
			else 
				$("minPrice").value = '';
		}
		if($("maxPrice"))
		{
			if(getSearchCookie("maxPrice") != 0)
				$("maxPrice").value = addCommas(getSearchCookie("maxPrice"));
			else 
				$("maxPrice").value = '';
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "beds")
	{
		if(getSearchCookie("searchBeds") && $("searchBedsMin") && $("searchBedsMax"))
		{
			var beds = getSearchCookie("searchBeds");
			if(trim(beds) == "")
			{
				$("searchBedsMin").value = "";
				$("searchBedsMax").value = "";
			}
			else
			{
				var bdArr = beds.split("-");
				$("searchBedsMin").value = bdArr[0];
				$("searchBedsMax").value = bdArr[1];
			}
		}
		else
		{
			if($("searchBedsMin") && $("searchBedsMax"))
			{
				$("searchBedsMin").value = "";
				$("searchBedsMax").value = "";
			}
		}		
		
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "sqft")
	{
		if(getSearchCookie("minSize") && $("minSize"))
		{
			$("minSize").value = getSearchCookie("minSize");
		}
		else if($("minSize"))
		{
			$("minSize").selectedIndex = 0;
		}
		if(getSearchCookie("maxSize") && $("maxSize"))
		{
			$("maxSize").value = getSearchCookie("maxSize");
		}
		else if($("maxSize"))
		{
			$("maxSize").selectedIndex = 0;
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "baths")
	{
		if(getSearchCookie("searchBaths") && $("searchBathsMin") && $("searchBathsMax"))
		{
			var baths = getSearchCookie("searchBaths");
			if(trim(baths) == "")
			{
				$("searchBathsMin").value = "";
				$("searchBathsMax").value = "";
			}
			else
			{
				var bthArr = baths.split("-");
				$("searchBathsMin").value = bthArr[0];
				$("searchBathsMax").value = bthArr[1];
			}
		}
		else
		{
			if($("searchBathsMin") && $("searchBathsMax"))
			{
				$("searchBathsMin").value = "";
				$("searchBathsMax").value = "";
			}
		}

		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "type")
	{
		if(getSearchCookie("searchType") || trim(getSearchCookie("searchType")) == "")
		{
			if($("divPopUpSHType"))
			{
				var arrChkBox = $("divPopUpSHType").getElementsByTagName("input");
				var lenChkBox = arrChkBox.length;
				var strChkBox = getSearchCookie("searchType");
				if(trim(strChkBox) == "")
				{
					
					for(var i=0;i<lenChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chbSHTypeAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == false)
		    			{
		    				arrChkBox[i].checked = true;
		    			}
					}	
				}
				else
				{
					var arrStrChkBox = strChkBox.split(":");
					for(var i=0;i<lenChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chbSHTypeAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox")
		    			{
		    				var valChkBox = arrChkBox[i].value;
		    				if(arrStrChkBox.in_array(valChkBox) !== false)
		    				{
		    					arrChkBox[i].checked = true;
		    				}
							else
							{
								arrChkBox[i].checked = false;
							}
		    			}
					}	
				}
			}
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "sortby")
	{
		if(getSearchCookie("searchSortType") && $("searchSortType"))
		{
			$("searchSortType").value = getSearchCookie("searchSortType");
		}
		else if($("searchSortType"))
		{
			$("searchSortType").selectedIndex = 0;
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "listdate")
	{
		if(getSearchCookie("ckLFDate") && $("txtLFDate"))
		{
			$("txtLFDate").value = getSearchCookie("ckLFDate");
		}
		else if($("txtLFDate"))
		{
			$("txtLFDate").value = '';
		}
		if(getSearchCookie("ckLTDate") && $("txtLTDate"))
		{
			$("txtLTDate").value = getSearchCookie("ckLTDate");
		}
		else if($("txtLTDate"))
		{
			$("txtLTDate").value = '';
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "propstyle")
	{
		if(getSearchCookie("propStyle") || trim(getSearchCookie("propStyle")) == "")
		{
			if($("propStyleDv"))
			{
				var arrChkBox = $("propStyleDv").getElementsByTagName("input");
				var lenChkBox = arrChkBox.length;
				var strChkBox = getSearchCookie("propStyle");
				if(trim(strChkBox) == "")
				{					
					for(var i=0;i<lenChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chkStyleAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == false)
		    			{
		    				arrChkBox[i].checked = true;
		    			}
					}	
				}
				else
				{
					var arrStrChkBox = strChkBox.split(":");
					for(var i=0;i<lenChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chkStyleAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox")
		    			{
		    				var valChkBox = arrChkBox[i].value;
		    				if((arrStrChkBox.in_array(valChkBox) !== false) && (arrChkBox[i].checked == false))
		    				{
		    					arrChkBox[i].checked = true;
		    				}
		    			}
					}	
				}
			}
		}

		if(srchcrt != null)
		{
			return;
		}
	}
	/*if(srchcrt == null || srchcrt == "parkingtype")
	{
		if(getSearchCookie("parkingType") || trim(getSearchCookie("parkingType")) == "")
		{
			if($("parkingStyleDv"))
			{
				var arrChkBox = $("parkingStyleDv").getElementsByTagName("input");
				var lenChkBox = arrChkBox.length;
				var strChkBox = getSearchCookie("parkingType");
				if(trim(strChkBox) == "")
				{					
					for(var i=0;i<lenChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chkParkingStyleAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == false)
		    			{
		    				arrChkBox[i].checked = true;
		    			}
					}	
				}
				else
				{
					var arrStrChkBox = strChkBox.split(":");
					for(var i=0;i<lenChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chkParkingStyleAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox")
		    			{
		    				var valChkBox = arrChkBox[i].value;
		    				if((arrStrChkBox.in_array(valChkBox) !== false) && (arrChkBox[i].checked == false))
		    				{
		    					arrChkBox[i].checked = true;
		    				}
		    			}
					}	
				}
			}
		}

		if(srchcrt != null)
		{
			return;
		}
	}*/
	
	if(srchcrt != null && srchcrt == "mlssource")
	{
		if(getSearchCookie("mlsSource") && $("mlsSource"))
		{
			$("mlsSource").value = getSearchCookie("mlsSource").replace(/[+]/g, ' ');
		}
		else if($("mlsSource"))
		{
			$("mlsSource").selectedIndex = 0;
		}
		if(srchcrt != null)
		{
			return;
		}
	}

	if(srchcrt != null && srchcrt == "propstatus")
	{
		/*if(getSearchCookie("propStatus") && $("propStatus"))
		{
			$("propStatus").value = getSearchCookie("propStatus");
		}
		else if($("propStatus"))
		{
			//$("propStatus").selectedIndex = 0;
			len = $("propStatus").options.length;
			var j;
			var status = 0;
			var defaultStatus = "";
			if(len>0)
			{
				for(j=0;j<len;j++)
				{
					if($("propStatus").options[j].value == 'Active')
					{
						defaultStatus = $("propStatus").options[j].value;
						status = 1;
					}
					else if(status==0)
					{
						defaultStatus = $("propStatus").options[0].value;
					}
				}
			}
			$("propStatus").value = defaultStatus;
		}
		if(srchcrt != null)
		{
			return;
		}*/

		var status = getSearchCookie("propStatus");

		if(status != '')
		{
			if($('divPStatus'))
			{				
				var dataArr = status.split(":");
				chkbxArr = $A($('divPStatus').getElementsByTagName("input"));
				chkbxArr.each(
					function(node)
					{				
						if(node.type == "checkbox" && node.checked == true)
							node.checked = false;

						if(node.type == "checkbox" && dataArr.indexOf(node.value) != -1)
							node.checked = true;
					});			
			}
		}
		else
		{
			if($('divPStatus'))
			{
				var stat = 0;
				chkbxArr = $A($('divPStatus').getElementsByTagName("input"));
				chkbxArr.each(
					function(node)
					{
						if(node.type=="checkbox" && (node.id == 'Active'))
						{
							node.checked = true;
							stat = 1;
						}
						else
							node.checked = false;
					});
					
				if(stat == 0)
				{
					var unstat = 0;
					$A($('divPStatus').getElementsByTagName("input")).each(function(node)
					{
						if(node.type=="checkbox" && unstat == 0)
						{
							node.checked = true;
							unstat = 1;
						}
					});
				}
			}
		}

		if(srchcrt != null)
		{
			return;
		}
	}
	
	if(srchcrt != null && srchcrt == "proptype")
	{		
		var types = getSearchCookie("propType");	

		if(types != '')
		{
			if($('divPType'))
			{
				var dataArr = types.split(":");
				chkbxArr = $A($('divPType').getElementsByTagName("input"));
				chkbxArr.each(
					function(node)
					{				
						if(node.type == "checkbox" && node.checked == true)
							node.checked = false;

						if(node.type == "checkbox" && dataArr.indexOf(node.value) != -1)
							node.checked = true;
					});			
			}
		}
		else
		{
			if($('divPType'))
			{
				chkbxArr = $A($('divPType').getElementsByTagName("input"));
				chkbxArr.each(
					function(node)
					{
						if(node.type=="checkbox" && (node.id == 'Single Family Residential' || node.id == 'Residential' || node.id == 'Single Family' || node.id == 'Single Family Homes'))
							node.checked = true;
						else
							node.checked = false;
					});			
			}
		}

		if(srchcrt != null)
		{
			return;
		}
	}
	
	if(srchcrt != null && srchcrt == "sqftp")
	{
		if(getSearchCookie("minPSize") && $("minPSize"))
		{
			$("minPSize").value = getSearchCookie("minPSize");
		}
		else if($("minPSize"))
		{
			$("minPSize").value = "";
		}
		if(getSearchCookie("maxPSize") && $("maxPSize"))
		{
			$("maxPSize").value = getSearchCookie("maxPSize");
		}
		else if($("maxPSize"))
		{
			$("maxPSize").value = "";
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	
	if(srchcrt != null && srchcrt == "listdatep")
	{
		if(getSearchCookie("ckPLFDate") && $("txtPLFDate"))
		{
			$("txtPLFDate").value = getSearchCookie("ckPLFDate");
		}
		else if($("txtPLFDate"))
		{
			$("txtPLFDate").value = '';
		}
		if(getSearchCookie("ckPLTDate") && $("txtPLTDate"))
		{
			$("txtPLTDate").value = getSearchCookie("ckPLTDate");
		}
		else if($("txtPLTDate"))
		{
			$("txtPLTDate").value = '';
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	
	if(srchcrt != null && srchcrt == "listagent")
	{
		if(getSearchCookie("listAgentFnm") && $("txtAgtFName"))
		{
			$("txtAgtFName").value = getSearchCookie("listAgentFnm");
		}
		else if($("txtAgtFName"))
		{
			$("txtAgtFName").value = 'First Name';
		}
		
		if(getSearchCookie("listAgentLnm") && $("txtAgtLName"))
		{
			$("txtAgtLName").value = getSearchCookie("listAgentLnm");
		}
		else if($("txtAgtLName"))
		{
			$("txtAgtLName").value = 'Last Name';
		}
		if(srchcrt != null)
		{
			return;
		}		
	}	
	
	if(srchcrt != null && srchcrt == "lotsize")
	{
		if(getSearchCookie("minLotSize") && $("minLotSize"))
		{
			$("minLotSize").value = getSearchCookie("minLotSize");
		}
		else if($("minLotSize"))
		{
			$("minLotSize").value = "";
		}
		
		if(getSearchCookie("maxLotSize") && $("maxLotSize"))
		{
			$("maxLotSize").value = getSearchCookie("maxLotSize");
		}
		else if($("maxLotSize"))
		{
			$("maxLotSize").value = "";
		}
		
		if(srchcrt != null)
		{
			return;
		}		
	}
	
	if(srchcrt != null && srchcrt == "age")
	{			
		if(getSearchCookie("fromAge") && $("txtAgeFrom"))
		{
			$("txtAgeFrom").value = getSearchCookie("fromAge");
		}
		else if($("txtAgeFrom"))
		{
			$("txtAgeFrom").value = '';
		}
		
		if(getSearchCookie("toAge") && $("txtAgeTo"))
		{
			$("txtAgeTo").value = getSearchCookie("toAge");
		}
		else if($("txtAgeTo"))
		{
			$("txtAgeTo").value = '';
		}
		
		if(srchcrt != null)
		{
			return;
		}
	}
	
	if(srchcrt != null && srchcrt == "yearbuilt")
	{			
		if(getSearchCookie("fromYear") && $("txtYearBuiltFrom"))
		{
			$("txtYearBuiltFrom").value = getSearchCookie("fromYear");
		}
		else if($("txtYearBuiltFrom"))
		{
			$("txtYearBuiltFrom").value = '';
		}
		
		if(getSearchCookie("toYear") && $("txtYearBuiltTo"))
		{
			$("txtYearBuiltTo").value = getSearchCookie("toYear");
		}
		else if($("txtYearBuiltTo"))
		{
			$("txtYearBuiltTo").value = '';
		}
		
		if(srchcrt != null)
		{
			return;
		}
	}	
	
	if(srchcrt != null && srchcrt == "daysonmarket")
	{			
		if(getSearchCookie("marketDaysFrom") && $("txtDaysMarketFrom"))
		{
			$("txtDaysMarketFrom").value = getSearchCookie("marketDaysFrom");
		}
		else if($("txtDaysMarketFrom"))
		{
			$("txtDaysMarketFrom").value = '';
		}
		if(getSearchCookie("marketDaysTo") && $("txtDaysMarketTo"))
		{
			$("txtDaysMarketTo").value = getSearchCookie("marketDaysTo");
		}
		else if($("txtDaysMarketTo"))
		{
			$("txtDaysMarketTo").value = '';
		}
		
		if(srchcrt != null)
		{
			return;
		}
	}
			
	if(srchcrt != null && srchcrt == "garage")
	{	
		if(getSearchCookie("garage") && $("cmbGarage"))
		{
			$("cmbGarage").value = getSearchCookie("garage").replace(/[+]/g, ' ');
		}
		else if($("cmbGarage"))
		{
			$("cmbGarage").selectedIndex = 0;
		}
		
		if(srchcrt != null)
		{
			return;
		}		
	}	

	if(srchcrt != null && srchcrt == "stories")
	{			
		if(getSearchCookie("stories") && $("txtStories"))
		{
			$("txtStories").value = getSearchCookie("stories");
		}
		else if($("txtStories"))
		{
			$("txtStories").value = '';
		}	
		if(srchcrt != null)
		{
			return;
		}
	}
	
	if(srchcrt != null && srchcrt == "schooldist")
	{			
		if(getSearchCookie("schooldist") && $("txtSchoolDist"))
		{
			$("txtSchoolDist").value = getSearchCookie("schooldist").replace(/[+]/g, ' ');
		}
		else if($("txtSchoolDist"))
		{
			$("txtSchoolDist").value = '';	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "eleschool")
	{			
		if(getSearchCookie("eleSchool") && $("txtEleSchool"))
		{
			$("txtEleSchool").value = getSearchCookie("eleSchool").replace(/[+]/g, ' ');
		}
		else if($("txtEleSchool"))
		{
			$("txtEleSchool").value = '';	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "midschool")
	{			
		if(getSearchCookie("midSchool") && $("txtMidSchool"))
		{
			$("txtMidSchool").value = getSearchCookie("midSchool").replace(/[+]/g, ' ');
		}
		else if($("txtMidSchool"))
		{
			$("txtMidSchool").value = '';	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "highschool")
	{			
		if(getSearchCookie("highSchool") && $("txtHighSchool"))
		{
			$("txtHighSchool").value = getSearchCookie("highSchool").replace(/[+]/g, ' ');
		}
		else if($("txtHighSchool"))
		{
			$("txtHighSchool").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}

	if(srchcrt != null && srchcrt == "bankowned")
	{			
		if(getSearchCookie("bankowned") && $("chkBankOwned"))
		{
			/*if(getSearchCookie("bankowned") == "true")
				$("chkBankOwned").checked = true;
			else
				$("chkBankOwned").checked = false;*/

			$("chkBankOwned").value = getSearchCookie("bankowned");
		}
		else if($("chkBankOwned"))
		{
			//$("chkBankOwned").checked = false;	
			$("chkBankOwned").selectedIndex = 0;
		}		
		if(srchcrt != null)
		{
			return;
		}
	}

	if(srchcrt != null && srchcrt == "shortsales")
	{			
		if(getSearchCookie("shortsales") && $("chkShortSales"))
		{
			/*if(getSearchCookie("shortsales") == "true")
				$("chkShortSales").checked = true;
			else
				$("chkShortSales").checked = false;*/

			$("chkShortSales").value = getSearchCookie("shortsales");
		}
		else if($("chkShortSales"))
		{
			//$("chkShortSales").checked = false;	
			$("chkShortSales").selectedIndex = 0;
		}		
		if(srchcrt != null)
		{
			return;
		}
	}

	if(srchcrt != null && srchcrt == "listagtid")
	{			
		if(getSearchCookie("listagtid") && $("txtListAgtId"))
		{
			$("txtListAgtId").value = getSearchCookie("listagtid");
		}
		else if($("txtListAgtId"))
		{
			$("txtListAgtId").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "listoff")
	{			
		if(getSearchCookie("listoff") && $("txtListOff"))
		{
			$("txtListOff").value = getSearchCookie("listoff").replace(/[+]/g, ' ').replace("__",'#');
		}
		else if($("txtListOff"))
		{
			$("txtListOff").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saleagtid")
	{			
		if(getSearchCookie("saleagtid") && $("txtSaleAgtId"))
		{
			$("txtSaleAgtId").value = getSearchCookie("saleagtid");
		}
		else if($("txtSaleAgtId"))
		{
			$("txtSaleAgtId").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saleoff")
	{			
		if(getSearchCookie("saleoff") && $("txtSaleOff"))
		{
			$("txtSaleOff").value = getSearchCookie("saleoff").replace(/[+]/g, ' ');
		}
		else if($("txtSaleOff"))
		{
			$("txtSaleOff").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "roof")
	{			
		if(getSearchCookie("roof") && $("txtRoof"))
		{
			$("txtRoof").value = getSearchCookie("roof").replace(/[+]/g, ' ');
		}
		else if($("txtRoof"))
		{
			$("txtRoof").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "fire")
	{	
		if(getSearchCookie("fire") && $("cmbFire"))
		{
			$("cmbFire").value = getSearchCookie("fire");
		}
		else if($("cmbFire"))
		{
			$("cmbFire").selectedIndex = 0;
		}
		
		if(srchcrt != null)
		{
			return;
		}		
	}
	if(srchcrt != null && srchcrt == "pool")
	{	
		if(getSearchCookie("pool") && $("cmbPool"))
		{
			$("cmbPool").value = getSearchCookie("pool");
		}
		else if($("cmbPool"))
		{
			$("cmbPool").selectedIndex = 0;
		}
		
		if(srchcrt != null)
		{
			return;
		}		
	}
	
	if(srchcrt != null && srchcrt == "saledate")
	{			
		if(getSearchCookie("saleDateFrom") && $("txtSFDate"))
		{
			$("txtSFDate").value = getSearchCookie("saleDateFrom");
		}
		else if($("txtSFDate"))
		{
			$("txtSFDate").value = '';
		}
		if(getSearchCookie("saleDateTo") && $("txtSTDate"))
		{
			$("txtSTDate").value = getSearchCookie("saleDateTo");
		}
		else if($("txtSTDate"))
		{
			$("txtSTDate").value = '';
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "saleprice")
	{			
		if(getSearchCookie("salePriceFrom") && $("txtSalePriceFrom"))
		{
			$("txtSalePriceFrom").value = getSearchCookie("salePriceFrom");
		}
		else if($("txtSalePriceFrom"))
		{
			$("txtSalePriceFrom").value = '';
		}
		if(getSearchCookie("salePriceTo") && $("txtSalePriceTo"))
		{
			$("txtSalePriceTo").value = getSearchCookie("salePriceTo");
		}
		else if($("txtSalePriceTo"))
		{
			$("txtSalePriceTo").value = '';
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt != null && srchcrt == "saleagent")
	{
		if(getSearchCookie("saleAgentFnm") && $("txtSaleAgentFname"))
		{
			$("txtSaleAgentFname").value = getSearchCookie("saleAgentFnm");
		}
		else if($("txtSaleAgentFname"))
		{
			$("txtSaleAgentFname").value = 'First Name';
		}
		if(getSearchCookie("saleAgentLnm") && $("txtSaleAgentLname"))
		{
			$("txtSaleAgentLname").value = getSearchCookie("saleAgentLnm");
		}
		else if($("txtSaleAgentLname"))
		{
			$("txtSaleAgentLname").value = 'Last Name';
		}
		if(srchcrt != null)
		{
			return;
		}		
	}
	if(srchcrt != null && srchcrt == "area")
	{			
		if(getSearchCookie("area") && $("txtArea"))
		{
			$("txtArea").value = getSearchCookie("area");
		}
		else if($("txtArea"))
		{
			$("txtArea").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt != null && srchcrt == "polygon")
	{			
		if(getSearchCookie("polygon") && $("txtPolygon"))
		{
			$("txtPolygon").value = getSearchCookie("polygon").replace(/\+/g, " ");
		}
		else if($("txtPolygon"))
		{
			$("txtPolygon").value = '';	
		}		
		if(srchcrt != null)
		{
			return;
		}
	}

	if(srchcrt != null && srchcrt == "powerradial")
	{	
		if(getSearchCookie("powerradial") && $("cmbradial"))
		{
			$("cmbradial").value = getSearchCookie("powerradial");
		}
		else if($("cmbradial"))
		{
			$("cmbradial").selectedIndex = 0;
		}
		
		if(srchcrt != null)
		{
			return;
		}		
	}
}

function funGetSearchQueryString()
{
	var lfDate = "";
	var ltDate = "";

	var tempDate = escape(trim(getSearchCookie("ckLFDate")));
	if (tempDate != "")
	{
		var arrTempDate = tempDate.split ("-");
		lfDate = arrTempDate[2] + "-" + arrTempDate[0] + "-" + arrTempDate[1];
	}

	var tempDate = escape(trim(getSearchCookie("ckLTDate")));
	if (tempDate != "")
	{
		var arrTempDate = tempDate.split ("-");
		ltDate = arrTempDate[2] + "-" + arrTempDate[0] + "-" + arrTempDate[1];
	}

	searchQueryString = "";
	searchQueryString = searchQueryString + "qckWidgetUpdate=1";
	searchQueryString = searchQueryString + "&address=" 		+ 	escape(getSearchCookie("searchAddress"));
	if(getSearchCookie("city") && getSearchCookie("city") != "")
	{
		searchQueryString = searchQueryString + "&city=" 			+ 	escape(getSearchCookie("city"));
	}
	if(getSearchCookie("state") && getSearchCookie("state") != "")
	{
		searchQueryString = searchQueryString + "&state=" 			+ 	escape(getSearchCookie("state"));
	}
	if(getSearchCookie("zip") && getSearchCookie("zip") != "")
	{
		searchQueryString = searchQueryString + "&zip=" 			+ 	escape(getSearchCookie("zip"));
	}
	searchQueryString = searchQueryString + "&minprice=" 		+ 	escape(money2num(getSearchCookie("minPrice")));
	searchQueryString = searchQueryString + "&maxprice=" 		+ 	escape(money2num(getSearchCookie("maxPrice")));
	searchQueryString = searchQueryString + "&beds=" 			+ 	escape(getSearchCookie("searchBeds"));
	searchQueryString = searchQueryString + "&minsqft=" 		+ 	escape(getSearchCookie("minSize"));
	searchQueryString = searchQueryString + "&maxsqft=" 		+ 	escape(getSearchCookie("maxSize"));
	searchQueryString = searchQueryString + "&baths=" 			+ 	escape(getSearchCookie("searchBaths"));
	searchQueryString = searchQueryString + "&searchType=" 		+ 	escape(getSearchCookie("searchType"));
	searchQueryString = searchQueryString + "&searchSortType=" 	+ 	escape(trim(getSearchCookie("searchSortType"))==""?"ph":trim(getSearchCookie("searchSortType")));
	searchQueryString = searchQueryString + "&lfDate="			+ 	escape(lfDate);
	searchQueryString = searchQueryString + "&ltDate="			+ 	escape(ltDate);
	searchQueryString = searchQueryString + "&county="			+ 	escape(trim(getSearchCookie("county")));
	
	var setPropStyle  = getSearchCookie("propStyle");
	setPropStyle 	  = setPropStyle.replace(":",",");
	searchQueryString = searchQueryString + "&propStyle="		+ 	escape(trim(setPropStyle));
	
	if(trim(getSearchCookie("garage")) == 'All')
		searchQueryString = searchQueryString + "&garage=";
	else
		searchQueryString = searchQueryString + "&garage="		+ 	escape(trim(getSearchCookie("garage")));
		
	if(trim(getSearchCookie("neighborhood")) == 'all')
		searchQueryString = searchQueryString + "&neighborhood=";
	else
		searchQueryString = searchQueryString + "&neighborhood="	+ 	escape((trim(getSearchCookie("neighborhood"))));
	
	var myQs = new Querystring();
	var frm = myQs.get("frm");
	var aid = myQs.get("aid");

	if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
	{
		if(typeof(strAgtMlsSrc) != 'undefined' && strAgtMlsSrc != null && strAgtMlsSrc.length > 0)
			searchQueryString = searchQueryString + "&mlsSource="	+ 	escape((trim(strAgtMlsSrc)));
		else
			searchQueryString = searchQueryString + "&mlsSource=";
		searchQueryString = searchQueryString + "&aid="			+ 	escape((trim(aid)));
	}	
	if(latLong)
		searchQueryString = searchQueryString+"&propLatitude="+latLong.lat+"&propLongitude="+latLong.lng;
	return searchQueryString;
}

function funGetAdvSearchQueryString()
{
	var lfDate = "";
	var ltDate = "";

	var tempDate = escape(trim(getSearchCookie("ckLFDate")));
	if (tempDate != "")
	{
		var arrTempDate = tempDate.split ("-");
		lfDate = arrTempDate[2] + "-" + arrTempDate[0] + "-" + arrTempDate[1];
	}

	var tempDate = escape(trim(getSearchCookie("ckLTDate")));
	if (tempDate != "")
	{
		var arrTempDate = tempDate.split ("-");
		ltDate = arrTempDate[2] + "-" + arrTempDate[0] + "-" + arrTempDate[1];
	}

	searchQueryString = new StringBuffer();
	searchQueryString.append("qckWidgetUpdate=1");
	searchQueryString.append("&minprice=" 		+ 	escape(money2num(getSearchCookie("minPrice"))));
	searchQueryString.append("&maxprice=" 		+ 	escape(money2num(getSearchCookie("maxPrice"))));
	searchQueryString.append("&beds=" 			+ 	escape(getSearchCookie("searchBeds")));
	searchQueryString.append("&minsqft=" 		+ 	escape(getSearchCookie("minSize")));
	searchQueryString.append("&maxsqft=" 		+ 	escape(getSearchCookie("maxSize")));
	searchQueryString.append("&baths=" 			+ 	escape(getSearchCookie("searchBaths")));
	searchQueryString.append("&searchType=" 		+ 	escape(getSearchCookie("searchType")));
	searchQueryString.append("&searchSortType=" 	+ 	escape(trim(getSearchCookie("searchSortType"))==""?"ph":trim(getSearchCookie("searchSortType"))));
	searchQueryString.append("&lfDate="			+ 	escape(lfDate));
	searchQueryString.append("&ltDate="			+ 	escape(ltDate));
	searchQueryString.append("&county="			+ 	escape(trim(getSearchCookie("county"))));
		
	if(trim(getSearchCookie("neighborhood")) == 'all')
		searchQueryString.append("&neighborhood=");
	else
		searchQueryString.append("&neighborhood="	+ 	escape((trim(getSearchCookie("neighborhood")))));

	var myQs = new Querystring();
	var frm = myQs.get("frm");
	var aid = myQs.get("aid");	
	if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
	{
		if(typeof(strAgtMlsSrc) != 'undefined' && strAgtMlsSrc != null && strAgtMlsSrc.length > 0)
			searchQueryString.append("&mlsSource="	+ 	escape((trim(strAgtMlsSrc))));
		else
			searchQueryString.append("&mlsSource=");
		searchQueryString.append("&aid="			+ 	escape((trim(aid))));
	}	
	return searchQueryString.toString();
}

function funCompareSearchCookie()
{
	if($('searchCSZ') != null)
	{
		var cszFromCookie = setCSZValue(getSearchCookie("city"), getSearchCookie("state"), getSearchCookie("zip"));
		$('searchCSZ').value = $('searchCSZ').value.replace (/^\s+/g, "").replace (/\s+$/g, "").replace (/\s+/g, " ");
		if (trim(cszFromCookie).toUpperCase() != trim($('searchCSZ').value).toUpperCase())
		{
			return 1;		
		}
	}		
	if(($("searchAddress") != null) && (getSearchCookie("searchAddress") != $F("searchAddress").replace('optional','')))
	{
		return 1;
	}
	if($("minPrice") && (getSearchCookie("minPrice") != money2num($F("minPrice"))))
	{
		return true;
	}
	if($("maxPrice") && (getSearchCookie("maxPrice") != money2num($F("maxPrice"))))
	{
		return true;
	}
	if($("searchBedsMin") && $("searchBedsMax") && trim(getSearchCookie("searchBeds")) != "" && (trim(getSearchCookie("searchBeds")) != trim($F("searchBedsMin"))+"-"+trim($F("searchBedsMax"))))
	{
		return true;
	}
	if($("minSize") && ((trim(getSearchCookie("minSize")) == "" && $F("minSize") != 0) || ((trim(getSearchCookie("minSize")) != "") && (trim(getSearchCookie("minSize")) != $F("minSize")))))
	{
		return true;
	}
	if($("maxSize") && ((trim(getSearchCookie("maxSize")) == "" && $F("maxSize") != 0) || ((trim(getSearchCookie("maxSize")) != "") && (trim(getSearchCookie("maxSize")) != $F("maxSize")))))
	{
		return true;
	}
	if($("searchBathsMin") && $("searchBathsMax") && trim(getSearchCookie("searchBaths")) != "" && (trim(getSearchCookie("searchBaths")) != trim($F("searchBathsMin"))+"-"+trim($F("searchBathsMax"))))
	{
		return true;
	}
	if($("divPopUpSHType") != null)
	{
		var arrChkBox = $("divPopUpSHType").getElementsByTagName("input");
		var lenChkBox = arrChkBox.length;
		var strChkBox = getSearchCookie("searchType");
		if(trim(strChkBox) == "")
		{
			for(var i=0;i<lenChkBox;i++)
			{
		    	if(arrChkBox[i].id == "chbSHTypeAll")
		    	{
		    		continue;
		    	}
		    	if((arrChkBox[i].type == "checkbox") && (arrChkBox[i].checked === false))
		    	{
		    		return true;
		    	}
			}	
		}
		else
		{
			var arrStrChkBox = strChkBox.split(":");
			for(var i=0;i<lenChkBox;i++)
			{
		    	if(arrChkBox[i].type == "checkbox")
		    	{
		    		var valChkBox = arrChkBox[i].value;
		    		if(arrStrChkBox.in_array(valChkBox) != false && arrChkBox[i].checked == false)
		    		{
		    			return true;
		    		}
		    	}
			}	
		}
	}
	if($("searchSortType") && (((trim(getSearchCookie("searchSortType"))!= "") && (getSearchCookie("searchSortType") !== $F("searchSortType"))) || (((trim(getSearchCookie("searchSortType")) == "") && ($F("searchSortType") != "ph")))))
	{
		return true;
	}
	return false;
}

function funCheckContradict()
{
	var retValue;
	var geoCbFn = function(reqObj)
	{
		for(var i=0;i<20;i++)
		{
			var idTxtObj = 'searchCSZ'+ eval(i+1);
			if($(idTxtObj) != null)
				$(idTxtObj).value = "";
		}
		var geoResponse = reqObj.responseText;
		var allCity = "";
		var allState = "";
		var allZip = "";
		var geoArrResponse = eval(geoResponse);
		var boolGetSingleCity = false;
		for(var i=0;i<geoArrResponse.length;i++)
		{
			if(geoArrResponse[i].status == 0)
			{	
				boolGetSingleCity = true;
				var geoCity = geoArrResponse[i].city;
				allCity += geoCity + '|';
				var geoState = geoArrResponse[i].state;
				allState += geoState + '|';
				var geoZip = geoArrResponse[i].zip;
				allZip += geoZip + '|';
				var geoAddress = geoArrResponse[i].address;
				setSearchCookie("searchAddress",geoAddress);
				$("searchAddress").value = geoAddress;
				
				
				setSearchCookie("county","");
				setSearchCookie("neighborhood","");
				arrDataCounty.length = 0;
				arrDataNeighborHood.length = 0;
				headerContent("county");
				headerContent("neighborhood");
				
				var now = new Date();
				now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
				var latLongStr = "[{'lat':'"+geoArrResponse[i].latitude+"','lng':'"+geoArrResponse[i].longitude+"'}]";
				setCookie("latLongCk",latLongStr,now);
				latLong = eval(getCookie("latLongCk"))[0];
				if(trim(getCookie("lpid")) != "" && isContradict === 1)
				{
					setCookie("lpid","");
					if(window.location.pathname.indexOf("dashboard") > 0)
					{
						funCloseWidget("divChild1X2");
						funCloseWidget("divChild1X3");
						funCloseWidget("divChild2X1");
						funCloseWidget("divChild2X2");
						funCloseWidget("divChild2X3");
						funCloseWidget("divChild3X1");
						funCloseWidget("divChild3X2");
						funCloseWidget("divChild3X3");
					}	
				}
			}
		}
		if(boolGetSingleCity == false)
		{			
			if(geoArrResponse.length > 1)
			{
				alert('Sorry, We couldn\'t find any location from "' + $('searchCSZ').value + '"');
			}
			else
			{				
				alert('Sorry, We couldn\'t find a location for "' + geoArrResponse[0].originaladdress + '"');
				setSearchCookie("searchAddress","");
				if($("searchAddress")) $("searchAddress").value = "optional";
				if(typeof(srTabs) != "undefined" && srTabs.getTab(0).get("active"))
				{
					srTabs.set('activeTab',srTabs.getTab(0),true);
					srTabs.getTab(0).refresh();
				}
			}
			retValue = "0";
			return;
		}
		else
		{
			if (allCity != "")
			{
				setSearchCookie ("city", allCity.substr(0, allCity.length-1));			
			}
			if (allState != "")
			{
				setSearchCookie ("state", allState.substr(0, allState.length-1));			
			}
			if (allZip != "")
			{
				setSearchCookie ("zip", allZip.substr(0, allZip.length-1));			
			}
			$('searchCSZ').value = setCSZValue(getSearchCookie('city'),getSearchCookie('state'),getSearchCookie('zip'));
			retValue = "2";
			return;
		}	
	}
	var isContradict = funCompareSearchCookie();
	if(isContradict === 1)
	{
		var geoUrl = "/classes/getCSZ.php";
		var geoAddress = "";
		if((trim($("searchAddress").value).toLowerCase() != "optional") && (trim($('searchCSZ').value).search(';') === -1))
		{
			geoAddress = $("searchAddress").value;
		}
		var geoQueryString = "csz="+escape($('searchCSZ').value)+"&address="+escape(geoAddress);
		ajaxRequest(geoUrl,geoQueryString,geoCbFn,false);
		return retValue;
	}
	else
	{
		return "1";
	}	
}

function CompareMinMax(srchcrt)
{
	if(srchcrt == null || srchcrt == "price")
	{
		var minP = Number(money2num($('minPrice').value));	
		var maxP = Number(money2num($('maxPrice').value));	
	
		if(minP<0 || maxP<0)
		{
			alert("Please enter valid price range");
			$('minPrice').value = '';
			$('maxPrice').value = '';
			return false;
		}
		if((minP>maxP) && (minP != "" && maxP != ""))
		{
			alert("Please enter valid price range");
			$('minPrice').value = '';
			$('maxPrice').value = '';
			return false;
		}
		if(srchcrt != null)
		{
			return;
		}
	}

	if(srchcrt == null || srchcrt == "beds")
	{
		var minbd = trim($('searchBedsMin').value);
		var maxbd = trim($('searchBedsMax').value);

		if(isNaN(minbd))
		{
			alert("Please enter numeric value for min beds");
			$('searchBedsMin').value = '';
			return false;
		}

		if(isNaN(maxbd))
		{
			alert("Please enter numeric value for max beds");
			$('searchBedsMax').value = '';
			return false;
		}

		if(minbd.include("."))
		{
			var ptLen = minbd.substr(minbd.indexOf(".")+1,minbd.length).length;
			if(ptLen>2)
			{
				alert("Only 2 digits allowed after decimal point for min beds");
				$('searchBedsMin').value = '';
				return false;
			}
		}

		if(maxbd.include("."))
		{
			var ptLen = maxbd.substr(maxbd.indexOf(".")+1,maxbd.length).length;
			if(ptLen>2)
			{
				alert("Only 2 digits allowed after decimal point for max beds");
				$('searchBedsMax').value = '';
				return false;
			}
		}

		minbd = Number(minbd);
		maxbd = Number(maxbd);

		if(minbd<0 || maxbd<0)
		{
			alert("Please enter valid beds range");
			$('searchBedsMin').value = '';
			$('searchBedsMax').value = '';
			return false;
		}
		if((minbd>maxbd) && (minbd != "" && maxbd != ""))
		{
			alert("Please enter valid beds range");
			$('searchBedsMin').value = '';
			$('searchBedsMax').value = '';
			return false;
		}
	}

	if(srchcrt == null || srchcrt == "baths")
	{
		var minbth = trim($('searchBathsMin').value);
		var maxbth = trim($('searchBathsMax').value);

		if(isNaN(minbth))
		{
			alert("Please enter numeric value for min baths");
			$('searchBathsMin').value = '';
			return false;
		}

		if(isNaN(maxbth))
		{
			alert("Please enter numeric value for max baths");
			$('searchBathsMax').value = '';
			return false;
		}

		if(minbth.include("."))
		{
			var ptLen = minbth.substr(minbth.indexOf(".")+1,minbth.length).length;
			if(ptLen>2)
			{
				alert("Only 2 digits allowed after decimal point for min baths");
				$('searchBathsMin').value = '';
				return false;
			}
		}

		if(maxbth.include("."))
		{
			var ptLen = maxbth.substr(maxbth.indexOf(".")+1,maxbth.length).length;
			if(ptLen>2)
			{
				alert("Only 2 digits allowed after decimal point for max baths");
				$('searchBathsMax').value = '';
				return false;
			}
		}

		minbth = Number(minbth);
		maxbth = Number(maxbth);

		if(minbth<0 || maxbth<0)
		{
			alert("Please enter valid baths range");
			$('searchBathsMin').value = '';
			$('searchBathsMax').value = '';
			return false;
		}
		if((minbth>maxbth) && (minbth != "" && maxbth != ""))
		{
			alert("Please enter valid baths range");
			$('searchBathsMin').value = '';
			$('searchBathsMax').value = '';
			return false;
		}
	}

	if(srchcrt == null || srchcrt == "sqft")	
	{
		var sqftMin = Number($("minSize").value);
		var sqftMax = Number($("maxSize").value);
		if(sqftMin>sqftMax && sqftMax != 0)
		{
			alert("Please select valid range for square feet");
			return false;
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "listdate")
	{
		if(trim($("txtLFDate").value) != "" && trim($("txtLTDate").value) != "")
		{
			var valLFDate = $("txtLFDate").value;
			var arrLFDate = valLFDate.split("-");		
			var objLFDate = new Date();
			objLFDate.setYear(arrLFDate[2]);
			objLFDate.setMonth(arrLFDate[0]);
			objLFDate.setDate(arrLFDate[1]);
			var tsLFDate = objLFDate.getTime()
			var valLTDate = $("txtLTDate").value;
			var arrLTDate = valLTDate.split("-");		
			var objLTDate = new Date();
			objLTDate.setYear(arrLTDate[2]);
			objLTDate.setMonth(arrLTDate[0]);
			objLTDate.setDate(arrLTDate[1]);
			var tsLTDate = objLTDate.getTime()
			if(tsLFDate > tsLTDate)
			{
				alert("To date should not be less than From date.");
				$('txtLFDate').value = '';
				$('txtLTDate').value = '';
				return false;
			}
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	return true;
}

function headerContent(srchcrt)
{
	if(srchcrt != null && srchcrt == "mls")
	{
		var ihMLSLabel = "MLS # ";
		var ihMLSValue = "";
		if(trim(getSearchCookie('mlsno')) != "")
		{
			var ihMLSValue = getSearchCookie('mlsno'); 
		}
		if($("divSHMLS") != null)
		{
			if($("divSHMLS").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHMLS").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihMLSLabel;
				}
				var objSpanValue = $("divSHMLS").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihMLSValue) != ""))
				{
					objSpanValue.innerHTML = ihMLSValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "county")
	{
		var ihCountyLabel = "County: ";
		var ihCountyValue = "";
		if((getSearchCookie("county") != null) && (trim(getSearchCookie("county")) != ""))
		{
			ihCountyValue = getSearchCookie("county"); 
		}
		else
		{
			ihCountyValue = 'any';
		}
		if($("divSHCounty") != null)
		{
			if($("divSHCounty").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHCounty").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihCountyLabel;
				}
				var objSpanValue = $("divSHCounty").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihCountyValue) != ""))
				{
					objSpanValue.innerHTML = funWrapText(ihCountyValue,20);
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "neighborhood")
	{
		var ihNeighborhoodLabel = "Neighborhood: ";
		var ihNeighborhoodValue = new StringBuffer();
		if((getSearchCookie("neighborhood") != null) && (trim(getSearchCookie("neighborhood")) != ""))
		{
			var strCKNH = getSearchCookie("neighborhood");
			var arrCKNH = strCKNH.split(',');
			var lenArrCKNH = arrCKNH.length;
			for(var i=0;i<lenArrCKNH;i++)
			{
				ihNeighborhoodValue.append(arrCKNH[i] + ',');
			}
			ihNeighborhoodValue = ihNeighborhoodValue.toString();
			if(ihNeighborhoodValue.charAt(ihNeighborhoodValue.length-1) == ',')
			{
				ihNeighborhoodValue = ihNeighborhoodValue.substr(0,eval(ihNeighborhoodValue.length-1));
			}
		}
		else
		{
			ihNeighborhoodValue =  ihNeighborhoodValue + 'any';
		}
		if($("divSHNeighborHood") != null)
		{
			if($("divSHNeighborHood").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHNeighborHood").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihNeighborhoodLabel;
				}
				var objSpanValue = $("divSHNeighborHood").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihNeighborhoodValue) != ""))
				{
					objSpanValue.innerHTML = funWrapText(ihNeighborhoodValue,15);
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if((srchcrt == null || srchcrt == "price") && $('minPrice') && $('maxPrice'))
	{	
		var ihPriceLabel = "Price: ";
		var ihPriceValue = "";
		var minP = Number(money2num(getSearchCookie("minPrice")));
		var maxP = Number(money2num(getSearchCookie("maxPrice")));	
		if(minP != 0 || maxP != 0)
		{
			if(minP != 0)
			{
				minP = num2money($('minPrice').value,'$','minPrice',false);
				ihPriceValue = ihPriceValue + minP+" to ";
			}
			else
			{
				ihPriceValue = ihPriceValue + "No Min to ";
			}
			if(maxP != 0)
			{
				maxP = num2money($('maxPrice').value,'$','maxPrice',false);
				ihPriceValue = ihPriceValue + maxP;
			}
			else
			{
				ihPriceValue = ihPriceValue + "No Max";
			}
		}
		else
		{
			ihPriceValue = ihPriceValue + "any";
		}
		if($("divSHPrice") != null)
		{
			if($("divSHPrice").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHPrice").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihPriceLabel;
				}
				var objSpanValue = $("divSHPrice").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihPriceValue) != ""))
				{
					objSpanValue.innerHTML = ihPriceValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}
	if(srchcrt == null || srchcrt == "beds")
	{
		var ihBedsLabel = "Beds: ";
		var ihBedsValue = "";
		var searchBeds = getSearchCookie("searchBeds");
		if(trim(searchBeds) == "")
			ihBedsValue = ihBedsValue + "any";
		else
		{
			var bdArr = searchBeds.split("-");

			if(bdArr[0] != "" && bdArr[1] != "")
				ihBedsValue = bdArr[0] + " to " + bdArr[1];
			else if(bdArr[0] != "")
				ihBedsValue = bdArr[0] + " to No Max";
			else
				ihBedsValue = "No Min to " + bdArr[1];
		}
		if($("divSHBeds") != null)
		{
			if($("divSHBeds").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHBeds").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihBedsLabel;
				}
				var objSpanValue = $("divSHBeds").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihBedsValue) != ""))
				{
					objSpanValue.innerHTML = ihBedsValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}		
	if(srchcrt == null || srchcrt == "baths")
	{
		var ihBathsLabel = "Baths: ";
		var ihBathsValue = "";
		var searchBaths = getSearchCookie("searchBaths");
		if(trim(searchBaths) == "")
			ihBathsValue = ihBathsValue + "any";
		else
		{
			var bthArr = searchBaths.split("-");

			if(bthArr[0] != "" && bthArr[1] != "")
				ihBathsValue = bthArr[0] + " to " + bthArr[1];
			else if(bthArr[0] != "")
				ihBathsValue = bthArr[0] + " to No Max";
			else
				ihBathsValue = "No Min to " + bthArr[1];
		}

		if($("divSHBaths") != null)
		{
			if($("divSHBaths").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHBaths").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihBathsLabel;
				}
				var objSpanValue = $("divSHBaths").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihBathsValue) != ""))
				{
					objSpanValue.innerHTML = ihBathsValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "sqft")
	{
		var ihSqftLabel = "Sqft: ";
		var ihSqftValue = "";
		var sqftMin = Number(getSearchCookie("minSize"));
		var sqftMax = Number(getSearchCookie("maxSize"));
		if((sqftMax != "0") || (sqftMin > 0 && sqftMax == 0))
		{
			if (sqftMin > 0 || (sqftMax > 0 && sqftMin == 0))
				ihSqftValue = ihSqftValue + sqftMin + ' - ';
			if (sqftMax > 0)
				ihSqftValue = ihSqftValue + sqftMax;
			if (sqftMax == 0)
				ihSqftValue = ihSqftValue + 'No Max';
		}
		else
		{
			ihSqftValue = ihSqftValue +  "any";
		}
		if($("divSHSqft") != null)
		{
			if($("divSHSqft").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHSqft").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihSqftLabel;
				}
				var objSpanValue = $("divSHSqft").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihSqftValue) != ""))
				{
					objSpanValue.innerHTML = ihSqftValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "listdate")
	{
		var ihListDateLabel = "List Date: ";
		var ihListDateValue = "";
		var valLFDate = getSearchCookie("ckLFDate");
		var valLTDate = getSearchCookie("ckLTDate");
		if(trim(valLFDate) != "" || trim(valLTDate) != "")
		{
			if(trim(valLFDate) != "")
			{
				ihListDateValue = ihListDateValue + "From "+valLFDate;
			}
			if(trim(valLFDate) != "" && trim(valLTDate) != "")
			{
				ihListDateValue = ihListDateValue + " To "+valLTDate;
			}
			else if(trim(valLTDate) != "")
			{
				ihListDateValue = ihListDateValue + " : UpTo "+valLTDate;
			}
		}
		else
		{
			ihListDateValue = ihListDateValue + "any";
		}
		if($("divSHListDate") != null)
		{
			if($("divSHListDate").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHListDate").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihListDateLabel;
				}
				var objSpanValue = $("divSHListDate").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihListDateValue) != ""))
				{
					objSpanValue.innerHTML = ihListDateValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "type")
	{
		var ihTypeLabel = "Type: ";
		var ihTypeValue = "";
		var valSearchType = getSearchCookie("searchType");
		if(trim(valSearchType) != "")
		{
			var arrValSearchType = valSearchType.split(':');
			var lenValSearchType = arrValSearchType.length;
			for(var i=0;i<lenValSearchType;i++)
			{
				var keySearchTypeVal = arrValSearchType[i];
				if(trim(keySearchTypeVal) != "")
				{
					ihTypeValue = ihTypeValue + arrValSearchType[keySearchTypeVal]+',';
				}	
			}
			if(ihTypeValue.charAt(ihTypeValue.length-1) == ',')
			{
				ihTypeValue = ihTypeValue.substr(0,eval(ihTypeValue.length-1));
			}
		}
		else
		{
			ihTypeValue = ihTypeValue + "all";
		}
		if($("divSHType") != null)
		{
			if($("divSHType").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHType").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihTypeLabel;
				}
				var objSpanValue = $("divSHType").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihTypeValue) != ""))
				{
					objSpanValue.innerHTML = funWrapText(ihTypeValue,15);
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}	
	if(srchcrt == null || srchcrt == "sortby")
	{
		var ihSortTypeLabel = "Sort By: ";
		var ihSortTypeValue = "";
		var sortType = getSearchCookie("searchSortType");
		if(trim(sortType) == "" || sortType == "ph")
		{ 
			ihSortTypeValue = ihSortTypeValue + "Price High to Low";
		}		
		else if(sortType == "pl")
		{ 
			ihSortTypeValue = ihSortTypeValue + "Price Low to High";
		}	
		else if(sortType == "brh")
		{ 
			ihSortTypeValue = ihSortTypeValue + "Beds High to Low";
		}		
		if(sortType == "brl")
		{ 
			ihSortTypeValue = ihSortTypeValue + "Beds Low to High";
		}	
		else if(sortType == "bah")
		{ 
			ihSortTypeValue = ihSortTypeValue + "Baths High to Low";
		}		
		else if(sortType == "bal")
		{ 
			ihSortTypeValue = ihSortTypeValue + "Baths Low to High";
		}
		if($("divSHSortBy") != null)
		{
			if($("divSHSortBy").getElementsByTagName('a')[0] != null)
			{
				var objSpanLabel = $("divSHSortBy").getElementsByTagName('a')[0].getElementsByTagName('span')[0];
				if(objSpanLabel != null)
				{
					objSpanLabel.innerHTML = ihSortTypeLabel;
				}
				var objSpanValue = $("divSHSortBy").getElementsByTagName('a')[0].getElementsByTagName('span')[1];
				if((objSpanValue != null) && (trim(ihSortTypeValue) != ""))
				{
					objSpanValue.innerHTML = ihSortTypeValue;
				}
			}	
		}
		if(srchcrt != null)
		{
			return;
		}
	}		
}
function funUnchkAllChkBox(objChkBox) 
{
	if(($('chbSHNHAll').checked == true) && (objChkBox.checked == false))
	{
		$('chbSHNHAll').checked = false;
	}
}
function funSetSHNHAll(from)
{
	if(typeof(from)!="undefined")
	{
		divId = "divNHood";
		chkAllId = "chbRSNHAll";
	}
	else
	{
		divId = "divSHDataNeighborHood";
		chkAllId = "chbSHNHAll";
	}
	var arrChkBox = $(divId).getElementsByTagName("input");
	var lenChkBox = arrChkBox.length;
	for(var i=0;i<lenChkBox;i++)
	{
		if(arrChkBox[i].id == chkAllId)
		{
		 	continue;
		}
	    if(($(chkAllId).checked == true) && (arrChkBox[i].type == "checkbox"))
	    {
	    	arrChkBox[i].checked = true;
	    }
	    else if(arrChkBox[i].type == "checkbox")
	    {
    		arrChkBox[i].checked = false;
	    }
	}
}
function funSetSHTypeAll(type)
{
	if(typeof(type)!="undefined")
	{
		divId = "divRSType";
		chkAllId = "RSchbSHTypeAll";
	}
	else
	{
		divId = "divPopUpSHType";
		chkAllId = "chbSHTypeAll";
	}
	if($(divId))
	{
		var	arrChkBox  = $(divId).getElementsByTagName("input");
		var lenChkBox = arrChkBox.length;
		for(var i=0;i<lenChkBox;i++)
		{
			if(arrChkBox[i].id == chkAllId)
			{
				continue;
			}
			if(($(chkAllId).checked == true) && (arrChkBox[i].type == "checkbox"))
			{
				arrChkBox[i].checked = true;
			}
			else if(($(chkAllId).checked == false) && (arrChkBox[i].type == "checkbox"))
			{
				arrChkBox[i].checked = false;
			}
		}
	}
}

function funCloseAdvanceSearch(srchcrt,page)
{	
	if($("divSHCounty")==null)
	{
		return;
	}
	
	Element.removeClassName($("divSHCounty").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
	Element.addClassName($("divSHCounty").getElementsByTagName('a')[0],'linkAdvanceSearch');
	$("divPopUpSHCounty").style.display = "none";

	Element.removeClassName($("divSHNeighborHood").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
	Element.addClassName($("divSHNeighborHood").getElementsByTagName('a')[0],'linkAdvanceSearch');
	$("divPopUpSHNeighborHood").style.display 	= "none";
	
	if($("divPopUpSHPrice"))
	{
		Element.removeClassName($("divSHPrice").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSHPrice").getElementsByTagName('a')[0],'linkAdvanceSearch');
		$("divPopUpSHPrice").style.display = "none";
	}

	if($("divSHMultiCity") != null)
	{
		Element.removeClassName($("divSHMultiCity").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSHMultiCity").getElementsByTagName('a')[0],'linkAdvanceSearch');
		$("divPopUpSHMultiCity").style.display = "none";
	}
	
	if($("divPopUpSHBeds"))
	{
		Element.removeClassName($("divSHBeds").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSHBeds").getElementsByTagName('a')[0],'linkAdvanceSearch');
		$("divPopUpSHBeds").style.display = "none";
	}
	
	if($("divPopUpSHBaths"))
	{
		Element.removeClassName($("divSHBaths").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSHBaths").getElementsByTagName('a')[0],'linkAdvanceSearch');
		$("divPopUpSHBaths").style.display = "none";
	}
	
	if($("divPopUpSHSqft"))
	{
		Element.removeClassName($("divSHSqft").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSHSqft").getElementsByTagName('a')[0],'linkAdvanceSearch');
		$("divPopUpSHSqft").style.display = "none";
	}
	
	Element.removeClassName($("divSHListDate").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
	Element.addClassName($("divSHListDate").getElementsByTagName('a')[0],'linkAdvanceSearch');
	$("divPopUpSHListDate").style.display = "none";
	
	Element.removeClassName($("divSHType").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
	Element.addClassName($("divSHType").getElementsByTagName('a')[0],'linkAdvanceSearch');
	$("divPopUpSHType").style.display = "none";
	
	Element.removeClassName($("divSHMLS").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
	Element.addClassName($("divSHMLS").getElementsByTagName('a')[0],'linkAdvanceSearch');
	$("divPopUpSHMLS").style.display = "none";
	
	Element.removeClassName($("divSHSortBy").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
	Element.addClassName($("divSHSortBy").getElementsByTagName('a')[0],'linkAdvanceSearch');
	$("divPopUpSHSortBy").style.display = "none";

	if($("divSaveSearch"))
	{
		Element.removeClassName($("divSaveSearch").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSaveSearch").getElementsByTagName('a')[0],'linkAdvanceSearch');
		$("divSaveSearch").style.display = "none";
	}

	if($("divSHPowerSortBy"))
	{
		Element.removeClassName($("divSHPowerSortBy").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
		Element.addClassName($("divSHPowerSortBy").getElementsByTagName('a')[0],'linkAdvanceSearch');
	}
	
	if($("divPopUpSHPower"))
		$("divPopUpSHPower").style.display = "none";
	
	if($("divPopUpSHPropStyle")) $("divPopUpSHPropStyle").style.display = "none";
	if($("divPopUpSHGarage")) $("divPopUpSHGarage").style.display = "none";
	
	$("divPopUpSHMLSInfo").style.visibility = "hidden";
	$("divPopUpSHControls").style.display = "none";
	
	$("divContainerAdvanceSearch").style.display = "none";
	$("divContainerAdvanceSearch").style.left = "-100px";
	$("divContainerAdvanceSearch").style.top = "-100px";
	
	if(srchcrt != null)
	{
		setAllCookieValue(srchcrt);
	}
}
function funSaveAdvanceSearch(srchcrt,page)
{
	if(srchcrt == "multicity")
	{
		var boolAllCityBlank = true;
		for(var i=0;i<20;i++)
		{
			var idTxtObj = 'searchCSZ'+ eval(i+1);
			if(trim($(idTxtObj).value) != "")
			{
				boolAllCityBlank = false;
				break;
			}
		}
		if (boolAllCityBlank == true)
		{
			alert("Please specify either City & State or Zip for atleast one.");
			return false;
		}
		var allCSZ = "";
		for(var i=0;i<20;i++)
		{
			var idTxtObj = 'searchCSZ'+ eval(i+1);
			if(trim($(idTxtObj).value) == "")
			{
				continue;
			}
			else
			{
				allCSZ += trim($(idTxtObj).value.replace(/;/g,'')) + ';';
			}
		}
		$('searchCSZ').value = allCSZ.substr(0, allCSZ.length-1);
		funCloseAdvanceSearch();
		return true;
	}
	if(srchcrt == "mls")
	{
		if(trim($("searchMLS").value) == "")
		{
			alert("Please input MLS number to search.");
			return false;
		}
		searchByMlsNo();
		return true;
	}
	if(srchcrt == "more")
	{
		if(CompareMinMax(null) === false)
		{
			return false;
		}
		setAllToCookie("sqft");
		setAllToCookie("listdate");
		setAllToCookie("county");
		funCloseAdvanceSearch();		
		return true;
	}	
	
	if((srchcrt == 'price') && (CompareMinMax(srchcrt) === false))
	{
		return false;
	}
	if((srchcrt == 'beds') && (CompareMinMax(srchcrt) === false))
	{
		return false;
	}
	if((srchcrt == 'baths') && (CompareMinMax(srchcrt) === false))
	{
		return false;
	}
	if(srchcrt == 'power')
	{		
		var validate = validatePower();
		if(validate === false)
			return false;

		if($("txtArea") && $("txtArea").value != "")
		{
			setSearchCookie("neighborhood","");
			headerContent("neighborhood");
		}
		setAllToCookie("mlssource");
		setAllToCookie("proptype");
		setAllToCookie("propstatus");
		setAllToCookie("sqftp");
		setAllToCookie("listdatep");
		setAllToCookie("listagent");
		setAllToCookie("lotsize");
		setAllToCookie("age");
		setAllToCookie("yearbuilt");
		setAllToCookie("daysonmarket");
		setAllToCookie("garage");
		setAllToCookie("stories");
		setAllToCookie("eleschool");
		setAllToCookie("midschool");
		setAllToCookie("highschool");
		setAllToCookie("saledate");
		setAllToCookie("saleprice");
		setAllToCookie("saleagent");
		setAllToCookie("area");
		setAllToCookie("polygon");
		setAllToCookie("powerradial");
		setAllToCookie("listagtid");
		setAllToCookie("listoff");
		setAllToCookie("saleagtid");
		setAllToCookie("saleoff");
		setAllToCookie("fire");
		setAllToCookie("pool");
		setAllToCookie("roof");
		funCloseAdvanceSearch();
		return true;
	}

	setAllToCookie(srchcrt);
	headerContent(srchcrt);
	funCloseAdvanceSearch();	
	return true;
}

function validatePower()
{
	/* Prop Type */
	if(chooseChecked('divPType',true) == '')
	{
		alert("Please select atleast one property type");
		return false;
	}

	/* Prop Status */
	if(chooseChecked('divPStatus',true) == '')
	{
		alert("Please select atleast one property status");
		return false;
	}

	/* Sales Price */
	var minSalesP = Number(money2num($('txtSalePriceFrom').value));	
	var maxSalesP = Number(money2num($('txtSalePriceTo').value));	
	if(minSalesP<0 || maxSalesP<0)
	{
		alert("Please enter valid price range");
		$('txtSalePriceFrom').value = '';
		$('txtSalePriceTo').value = '';
		return false;
	}
	if((minSalesP>maxSalesP) && (minSalesP != "" && maxSalesP != ""))
	{
		alert("Please enter valid price range");
		$('txtSalePriceFrom').value = '';
		$('txtSalePriceTo').value = '';
		return false;
	}
	 
	/* Sqft */
	/*var sqftMin = Number($("minPSize").value);
	var sqftMax = Number($("maxPSize").value);
	if(sqftMin>sqftMax && sqftMax != 0)
	{
		alert("Please enter valid range for square feet");
		$("minPSize").selectedIndex=0;
		$("maxPSize").selectedIndex=0;
		return false;
	}*/

	var sqftMin = Number($F('minPSize'));
	var sqftMax = Number($F('maxPSize'));
	if(isNaN(sqftMin))
	{
		alert("Please enter numerical values only for min sqft.");
		$('minPSize').value = '';
		$('minPSize').focus();
		return false;
	}

	if(isNaN(sqftMax))
	{
		alert("Please enter numerical values only for max sqft.");
		$('maxPSize').value = '';
		$('maxPSize').focus();
		return false;
	}

	if(sqftMin<0 || sqftMax<0)
	{
		alert("Please enter valid square feet range.");
		$('minPSize').value = '';
		$('maxPSize').value = '';
		$('minPSize').focus();
		return false;
	}

	if(sqftMin>sqftMax && (sqftMin != "" && sqftMax != ""))
	{
		alert("Please enter valid square feet range.");
		//$("minPSize").value='';
		//$("maxPSize").value='';
		return false;
	}
	
	/* Lot Sqft */
	/*var sqftLotMin = Number($("minLotSize").value);
	var sqftLotMax = Number($("maxLotSize").value);
	if(sqftLotMin>sqftLotMax && sqftLotMax != 0)
	{
		alert("Please enter valid range for lot size");
		$("minLotSize").selectedIndex=0;
		$("maxLotSize").selectedIndex=0;
		return false;
	}*/
	var sqftLotMin = Number($F('minLotSize'));
	var sqftLotMax = Number($F('maxLotSize'));
	if(isNaN(sqftLotMin))
	{
		alert("Please enter numerical values only for min lot size.");
		$('minLotSize').value = '';
		$('minLotSize').focus();
		return false;
	}

	if(isNaN(sqftLotMax))
	{
		alert("Please enter numerical values only for max lot size.");		
		$('maxLotSize').value = '';
		$('maxLotSize').focus();
		return false;
	}

	if(sqftLotMin<0 || sqftLotMax<0)
	{
		alert("Please enter valid lot size range.");
		$('minLotSize').value = '';
		$('maxLotSize').value = '';
		$('minLotSize').focus();
		return false;
	}

	if(sqftLotMin>sqftLotMax && (sqftLotMin != "" && sqftLotMax != ""))
	{
		alert("Please enter valid lot size range.");
		//$("minLotSize").value='';
		//$("maxLotSize").value='';
		return false;
	}

	/* List Date */
	if($("txtPLFDate").value != "")
	{
		if(!validDate("txtPLFDate","Please select from list date less than current date"))
			return false;
	}

	if($("txtPLTDate").value != "")
	{
		if(!validDate("txtPLTDate","Please select to list date less than current date"))
			return false;
	}

	if(trim($("txtPLFDate").value) != "" && trim($("txtPLTDate").value) != "")
	{
		var valLFDate = $("txtPLFDate").value;
		var arrLFDate = valLFDate.split("-");		
		var objLFDate = new Date();
		objLFDate.setYear(arrLFDate[2]);
		objLFDate.setMonth(arrLFDate[0]);
		objLFDate.setDate(arrLFDate[1]);
		var tsLFDate = objLFDate.getTime()
		var valLTDate = $("txtPLTDate").value;
		var arrLTDate = valLTDate.split("-");		
		var objLTDate = new Date();
		objLTDate.setYear(arrLTDate[2]);
		objLTDate.setMonth(arrLTDate[0]);
		objLTDate.setDate(arrLTDate[1]);
		var tsLTDate = objLTDate.getTime()
		if(tsLFDate > tsLTDate)
		{
			alert("To date should not be less than From date.");
			$('txtPLFDate').value = '';
			$('txtPLTDate').value = '';
			return false;
		}
	}
	
	/* Sale Date */
	if($("txtSFDate").value != "")
	{
		if(!validDate("txtSFDate","Please select from sale date less than current date"))
			return false;
	}

	if($("txtSTDate").value != "")
	{
		if(!validDate("txtSTDate","Please select to sale date less than current date"))
			return false;
	}
	if(trim($("txtSFDate").value) != "" && trim($("txtSTDate").value) != "")
	{
		var valLFDate = $("txtSFDate").value;
		var arrLFDate = valLFDate.split("-");		
		var objLFDate = new Date();
		objLFDate.setYear(arrLFDate[2]);
		objLFDate.setMonth(arrLFDate[0]);
		objLFDate.setDate(arrLFDate[1]);
		var tsLFDate = objLFDate.getTime()
		var valLTDate = $("txtSTDate").value;
		var arrLTDate = valLTDate.split("-");		
		var objLTDate = new Date();
		objLTDate.setYear(arrLTDate[2]);
		objLTDate.setMonth(arrLTDate[0]);
		objLTDate.setDate(arrLTDate[1]);
		var tsLTDate = objLTDate.getTime()
		if(tsLFDate > tsLTDate)
		{
			alert("To date should not be less than From date.");
			$('txtSFDate').value = '';
			$('txtSTDate').value = '';
			return false;
		}
	}
	
	/* Age */
	var minAge = Number($('txtAgeFrom').value);
	var maxAge = Number($('txtAgeTo').value);
	if(isNaN(minAge))
	{
		alert("Please enter numerical values only.");
		$('txtAgeFrom').value = '';
		$('txtAgeTo').value = '';
		return false;
	}
	else if(isNaN(maxAge))
	{
		alert("Please enter numerical values only.");
		$('txtAgeFrom').value = '';
		$('txtAgeTo').value = '';
		return false;
	}
	else if(minAge>maxAge && (minAge != "" && maxAge != ""))
	{
		alert("Please enter valid range for age.");
		//$('txtAgeFrom').value = '';
		//$('txtAgeTo').value = '';
		return false;
	}
	
	/* Year Build */
	var minYr = Number($F('txtYearBuiltFrom'));
	var maxYr = Number($F('txtYearBuiltTo'));
	if(isNaN(minYr))
	{
		alert("Please enter numerical values only.");
		$('txtYearBuiltFrom').value = '';
		$('txtYearBuiltTo').value = '';
		return false;
	}
	else if(isNaN(maxYr))
	{
		alert("Please enter numerical values only.");
		$('txtYearBuiltFrom').value = '';
		$('txtYearBuiltTo').value = '';
		return false;
	}
	else if($F('txtYearBuiltFrom') != '' && $F('txtYearBuiltFrom').length != 4 )
	{
		alert("Please enter 4 digit year value.");
		$('txtYearBuiltFrom').value = '';
		$('txtYearBuiltTo').value = '';
		return false;
	}
	else if($F('txtYearBuiltTo') != '' && $F('txtYearBuiltTo').length != 4)
	{
		alert("Please enter 4 digit year value.");
		$('txtYearBuiltFrom').value = '';
		$('txtYearBuiltTo').value = '';
		return false;
	}
	else if(minYr>maxYr && (minYr != "" && maxYr != ""))
	{
		alert("Please enter valid range for year build.");
		//$('txtYearBuiltFrom').value = '';
		//$('txtYearBuiltTo').value = '';
		return false;
	}
	
	/* Days on Market */
	var minMkt = Number($F('txtDaysMarketFrom'));
	var maxMkt = Number($F('txtDaysMarketTo'));
	if(isNaN(minMkt))
	{
		alert("Please enter numerical values only.");
		$('txtDaysMarketFrom').value = '';
		$('txtDaysMarketTo').value = '';
		return false;
	}
	else if(isNaN(maxMkt))
	{
		alert("Please enter numerical values only.");
		$('txtDaysMarketFrom').value = '';
		$('txtDaysMarketTo').value = '';
		return false;
	}
	else if(minMkt>maxMkt && (minMkt != "" && maxMkt != ""))
	{
		alert("Please enter valid range for days on market.");
		//$('txtDaysMarketFrom').value = '';
		//$('txtDaysMarketTo').value = '';
		return false;
	}
	
	/* Stories */
	var stories = Number($F('txtStories'));
	if(isNaN(stories))
	{
		alert("Please enter numerical values only.");
		$('txtStories').value = '';
		return false;
	}
	
	/* Listing Agt Id*/
	if($("txtListAgtId").value != "")
	{
		var listAgtId = trim($("txtListAgtId").value);
		var tstRegex = /^([a-zA-Z0-9_-]+)$/;
		if(!tstRegex.test(listAgtId))
		{
			alert("Listing Agent Id should not contain special characters.");
		    $('txtListAgtId').value = '';
		    return false;
		}
	}

	/* Selling Agt Id*/
	if($("txtSaleAgtId").value != "")
	{
		var saleAgtId = trim($("txtSaleAgtId").value);
		var tstRegex = /^([a-zA-Z0-9_-]+)$/;
		if(!tstRegex.test(saleAgtId))
		{
			alert("Selling Agent Id should not contain special characters.");		    
		    $('txtSaleAgtId').value = '';
		    return false;
		}
	}
	
	return true;
}

function funGoAdvanceSearch(srchcrt,page)
{
	if(srchcrt == "multicity")
	{
		var boolAllCityBlank = true;
		for(var i=0;i<20;i++)
		{
			var idTxtObj = 'searchCSZ'+ eval(i+1);
			if(trim($(idTxtObj).value) != "")
			{
				boolAllCityBlank = false;
				break;
			}
		}
		if (boolAllCityBlank == true)
		{
			alert("Please specify either City & State or Zip for atleast one.");
			return;
		}
	}	
	var boolSaveAdvanceSearch = funSaveAdvanceSearch(srchcrt,page);
	if(boolSaveAdvanceSearch == true)
	{
		if($('chkmapSearchSelect') != null && $('chkmapSearchSelect').checked == true && typeof(reloadDragZoomAll) != 'undefined') 
		{
			reloadDragZoomAll();
		}
		else
		{
			explore(page);
		}	
	}	
}
function funGetNeighborHood(srchcrt,page)
{
	var cbfnGetNeighborHood = function(reqObj)
	{
		var response = reqObj.responseText;
		if(response.toString() != 'null')
		{
			arrDataNeighborHood = eval(response);
			if(arrDataNeighborHood.length > 0)
			{
				$('divPopUpSHNeighborHood').style.height = "150px";
				var strCKNH = getSearchCookie("neighborhood");
				var arrCKNH = strCKNH.split(',');
				var ihNeighborHood = new StringBuffer();
				var lenArrDataNeighborHood = arrDataNeighborHood.length;
				ihNeighborHood.append('<table cellpadding="0" cellspacing="0" style="width:250px; height:100%;" border="0">');
					ihNeighborHood.append('<tr>'); 
						ihNeighborHood.append('<td style="width:10%;">'); 
							ihNeighborHood.append('<input type="checkbox" value=""  id="chbSHNHAll" name="chbSHNHAll" onclick="javscript:funSetSHNHAll();"/>');
						ihNeighborHood.append('</td>'); 
						ihNeighborHood.append('<td style="width:80%;">'); 
							ihNeighborHood.append('<span class="contentSHPopup lang">all</span>');
						ihNeighborHood.append('</td>'); 
					ihNeighborHood.append('</tr>'); 
				for(var i=0;i<lenArrDataNeighborHood;i++)
				{
					if(typeof(arrDataNeighborHood[i]['neighborhood']) != "undefined" && trim(arrDataNeighborHood[i]['neighborhood'])!="")
					{
						ihNeighborHood.append('<tr>'); 
							ihNeighborHood.append('<td style="width:10%;">'); 
								if((arrCKNH.in_array(arrDataNeighborHood[i]['neighborhood']) !== false) || (trim(strCKNH) == 'all'))
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['neighborhood']+'" onclick="javascript:funUnchkAllChkBox(this);" checked="checked" />');
								}
								else
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['neighborhood']+'" onclick="javascript:funUnchkAllChkBox(this);" />');
								}	
							ihNeighborHood.append('</td>'); 
							ihNeighborHood.append('<td style="width:80%;">'); 
								ihNeighborHood.append('<span class="contentSHPopup lang">'+arrDataNeighborHood[i]['neighborhood']+'</span>');
							ihNeighborHood.append('</td>'); 
						ihNeighborHood.append('</tr>'); 
					}
					else if(typeof(arrDataNeighborHood[i]['area']) != "undefined" && trim(arrDataNeighborHood[i]['area'])!="")
					{
						ihNeighborHood.append('<tr>'); 
							ihNeighborHood.append('<td style="width:10%;">'); 
								if((arrCKNH.in_array(arrDataNeighborHood[i]['area']) !== false) || (trim(strCKNH) == 'all'))
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['area']+'" onclick="javascript:funUnchkAllChkBox(this);" checked="checked" />');
								}
								else
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['area']+'" onclick="javascript:funUnchkAllChkBox(this);" />');
								}	
							ihNeighborHood.append('</td>'); 
							ihNeighborHood.append('<td style="width:80%;">'); 
								ihNeighborHood.append('<span class="contentSHPopup lang">'+arrDataNeighborHood[i]['code']+" - "+arrDataNeighborHood[i]['area']+'</span>');
							ihNeighborHood.append('</td>'); 
						ihNeighborHood.append('</tr>'); 
					}
				}	
				ihNeighborHood.append('</table>');
				$("divSHDataNeighborHood").innerHTML = ihNeighborHood.toString();
				var arrChkBox = $('divSHDataNeighborHood').getElementsByTagName("input");
				var lenArrChkBox = arrChkBox.length;
				var allChked = true;
				for(var i=0;i<lenArrChkBox;i++)
				{
			    	if((arrChkBox[i].id == "chbSHNHAll") || (arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true))
			    	{
			    		continue;
			    	}
					else
					{
						allChked = false;
						break;
					}
				}
				if(allChked == true)
				{
					$("chbSHNHAll").checked = true;
				}
				Element.removeClassName($("divSHNeighborHood").getElementsByTagName('a')[0],'linkAdvanceSearch');
				Element.addClassName($("divSHNeighborHood").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
				$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
				$("divPopUpSHMLSInfo").style.visibility = "visible";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
			}
			else
			{
				$('divPopUpSHNeighborHood').style.height = "55px";
				$("divPopUpSHControls").innerHTML = '&nbsp<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';
				$("divSHDataNeighborHood").innerHTML = '<span class="contentSHPopup">Neighborhood information not available for &nbsp;\"' + getSearchCookie("city") + ', ' + getSearchCookie("state") + '\".</span>';
				$("divPopUpSHMLSInfo").style.visibility = "hidden";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
				headerContent("county");
			}
		}
		else
		{
			$('divPopUpSHNeighborHood').style.height = "50px";
			$("divPopUpSHControls").innerHTML = '&nbsp<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';
			$("divSHDataNeighborHood").innerHTML = '<span class="contentSHPopup">Neighborhood information for \"' + getSearchCookie("city") + '", ' + getSearchCookie("state") + '\" is coming soon.</span>';
			$("divPopUpSHMLSInfo").style.visibility = "hidden";
			$("divPopUpSHControls").style.display = "inline";
			$("divPopUpSHNeighborHood").style.display = "inline";
			headerContent("county");
		}		
	}
	var url = "../../getCountyNeighborHood.php";
	var qs = "getDataNeighborHood=1&city="+getSearchCookie('city')+"&state="+getSearchCookie("state")+"&zip="+getSearchCookie("zip");

	if($("mlsSource"))
		qs +="&ds="+$F("mlsSource");
	else if(getSearchCookie('mlsSource'))
		qs +="&ds="+escape(getSearchCookie('mlsSource'));

	$("divSHDataNeighborHood").innerHTML = "";
	ajaxRequest(url,qs,cbfnGetNeighborHood);
}
function funGetCounty(srchcrt,page)
{
	var cbfnGetCounty = function(reqObj)
	{
		var response = reqObj.responseText;
		if(response.toString() != 'null')
		{
			arrDataCounty = eval(trim(response));
			if(arrDataCounty.length > 0)
			{
				var strCKCounty = getSearchCookie("county");
				var arrCKCounty = strCKCounty.split(',');
				var ihCounty = new StringBuffer();
				var lenArrDataCounty = arrDataCounty.length;
				ihCounty.append('<table cellpadding="0" cellspacing="0" style="width:320px;*width:100%;height:100%;">');
				for(var i=0;i<lenArrDataCounty;i++)
				{
					var countyName = arrDataCounty[i]['county'];
					ihCounty.append('<tr>'); 
						ihCounty.append('<td style="width:6%;">'); 
							if(arrCKCounty.in_array(countyName) !== false)
							{
								ihCounty.append('<input type="checkbox" value="'+countyName+'" checked="checked" />');
							}
							else
							{
								ihCounty.append('<input type="checkbox" value="'+countyName+'"  />');
							}	
						ihCounty.append('</td>'); 
						ihCounty.append('<td style="width:94%;">'); 
							ihCounty.append('<span class="contentSHPopup lang">'+countyName+'</span>');
						ihCounty.append('</td>'); 
					ihCounty.append('</tr>'); 
				}	
				ihCounty.append('</table>');
				
				$("divSHDataCounty").innerHTML = ihCounty.toString();
				$("divPopUpSHCounty").style.display = "inline";
			}
			else
			{
				$("divSHDataCounty").innerHTML = '<span class="contentSHPopup">County information for \"' + getSearchCookie("city") + ', ' + getSearchCookie("state") + '\" is coming soon.</span>';
				if(bkTheme == 'realestateone' || bkTheme == 'maxbroock' || bkTheme == 'jensenwhite')
				{
					$("divPopUpSHCounty").style.display = "none";
				}
				else
				{
					$("divPopUpSHCounty").style.display = "inline";
				}
			}
		}
		else
		{
			
			$("divSHDataCounty").innerHTML = '<span class="contentSHPopup">County information for \"' + getSearchCookie("city") + ', ' + getSearchCookie("state") + '\" is coming soon.</span>';
			if(bkTheme == 'realestateone' || bkTheme == 'maxbroock' || bkTheme == 'jensenwhite')
			{
			$("divPopUpSHCounty").style.display = "none";
			}
			else
			{
				$("divPopUpSHCounty").style.display = "inline";
			}
		}
	}
	if ($('searchCSZ').value.search(/;/) > -1)
	{
		$("divSHDataCounty").innerHTML = '<span class="contentSHPopup">Please select single city to enable county search.</span>';
		$("divPopUpSHCounty").style.display = "inline";
		return;
	}
	var isContradict = funCheckContradict();
	if((isContradict != null) && (isContradict != 0))
	{
		var url = "../../getCountyNeighborHood.php";
		var qs = "getDataCounty=1&city="+getSearchCookie('city')+"&state="+getSearchCookie("state")+"&zip="+getSearchCookie("zip");
		$("divSHDataCounty").innerHTML = "";
		ajaxRequest(url,qs,cbfnGetCounty);
	}
	else
	{
		return;
	}	
}

function funShowMultiCity()
{
	if($('divPopUpMultiCity') == null)
	{
		var ihMultiCity = new StringBuffer();
		ihMultiCity.append('<table align="center" style="border:3px double #192046;display:block;position:relative;border-collapse: separate;border-spacing: 3px;width:100%;*width:93%;" >');
		ihMultiCity.append('<tr>');
		ihMultiCity.append('<td valign="middle" >');
		ihMultiCity.append('<div id="divDataMultiCity" name="divDataMultiCity" style="width:290px;height:270px;position:relative;float:left;display:inline;vertical-align:middle;overflow:auto" align="left">');
			ihMultiCity.append('<table  id="multiCTFirst" align="center" border="0" width="100%" style="display:block;position:relative;border-collapse: separate;border-spacing: 3px;" >');
				ihMultiCity.append('<tr>');
					ihMultiCity.append('<td align="left" colspan="2">');
						ihMultiCity.append('<span id="multiErr"></span>');
					ihMultiCity.append('</td>');													
				ihMultiCity.append('</tr>');
				ihMultiCity.append('<tr>');
					ihMultiCity.append('<td align="left" colspan="2">');
						ihMultiCity.append('<span class="contentSHPopupNew lang" align="left">City, State</span>');
					ihMultiCity.append('</td>');													
				ihMultiCity.append('</tr>');
			ihMultiCity.append('</table>');									
		ihMultiCity.append('</div>');
		ihMultiCity.append('</td>');													
		ihMultiCity.append('</tr>');
		
		ihMultiCity.append('<tr>');
					ihMultiCity.append('<td align="right" colspan="2" width="100%" class="borderTop">');
						ihMultiCity.append('<a href="javascript:gotoSingPropMulti();" class="linkOkCancleSH">Go</a>&nbsp;&nbsp;');
						ihMultiCity.append('<a href="javascript:clearMulti();" class="linkOkCancleSH">Clear All</a>&nbsp;&nbsp;');
						ihMultiCity.append('<a href="javascript:closePopUpMultiCity();" class="linkOkCancleSH">Close</a>&nbsp;');
					ihMultiCity.append('</td>');													
				ihMultiCity.append('</tr>');
		ihMultiCity.append('</table><input type="hidden" id="lat"><input type="hidden" id="longi">');									
		
		var myDiv = document.createElement('div');
		myDiv.id = "divPopUpMultiCity";
		myDiv.name = "divPopUpMultiCity";
		myDiv.style.display = "none";
		myDiv.style.position = "absolute";
		myDiv.className = "divContainerAdvannceSearchMulti";
		if(isIE)
		{
			myDiv.style.width = "290px";
			myDiv.style.styleFloat = "left";
		}
		else
		{
			myDiv.style.width = "290px";
			myDiv.style.cssFloat = "left";
		}
		myDiv.style.height = "300px";
		myDiv.innerHTML = ihMultiCity.toString();
		document.body.appendChild(myDiv);
	}
	return $('divPopUpMultiCity');
}

function clearMulti()
{
	if(isIE)
	{
		var tbl = document.getElementById('multiCTFirst');
		var lastRow = tbl.rows.length;
		while(lastRow != 2)
		{
			tbl.deleteRow(lastRow-1);
			lastRow--;
		}
	}
	else
	{
		ihMultiCity = "";
		ihMultiCity += '<tr>';
			ihMultiCity += '<td align="left" colspan="2">';
				ihMultiCity += '<span id="multiErr"></span>';
			ihMultiCity += '</td>';													
		ihMultiCity += '</tr>';
		ihMultiCity += '<tr>';
			ihMultiCity += '<td align="left" colspan="2">';
				ihMultiCity += '<span class="contentSHPopupNew lang" align="left">City, State</span>';
			ihMultiCity += '</td>';													
		ihMultiCity += '</tr>';
		if($("multiCTFirst"))
			$("multiCTFirst").innerHTML = ihMultiCity;
	}
	
	cityList = new Hash();
}

function closePopUpMultiCity()
{
	$('divPopUpMultiCity').style.display = "none";
}

function gotoSingPropMulti()
{
	var lat = "";
	var lng = "";
	lat = $("lat").value;
	lng = $("longi").value;
	//alert(2 +" "+lat+","+lng);
	var state="";
	var city="";
	if(bkTheme=="lmsre")
	{
		var typeIncookie = "";
		typeInCookie = getSearchCookie("searchType");
		if(typeInCookie=="'non mls'")
			setSearchCookie("searchType","");
	}
	var cityLst = $('multiCTFirst').getElementsByTagName("input");
	for(i=0;i<=cityLst.length;i++)
	{
		if($(cityLst[i]) && $(cityLst[i]).value!="")
		{
			var arrCityState = (trim($(cityLst[i]).value)).split(",");
			city += trim(arrCityState[0]) + "|";
			state += trim(arrCityState[1]) + "|";
		}	
	}
	if(city.length==0)
	{
		alert("Please select atleast one city");
		return;
	}
	city = city.substring(0,city.length-1);
	state = state.substring(0,state.length-1);
	listAllCity = city;
	var zip="";	var page=""; var action="start";var otherArgs="";

	
	page=bkTheme.toUpperCase();
		
	getGeoAdd(lat,lng,city,state,zip,page,action,otherArgs)
}

var arrDataCounty = new Array();
var arrDataNeighborHood = new Array();
function funShowAdvanceSearch(srchcrt,page,e)
{	
	funCloseAdvanceSearch();
	if($("divContainerAdvannceSearch"))
		$("divContainerAdvannceSearch").style.display="";
	if($("divPopUpSHPower"))
		$("divPopUpSHPower").style.display="";	

	$("divContainerAdvanceSearch").style.width = "290px";
	switch(srchcrt)
	{
		case "multicity":
			$("divContainerAdvanceSearch").style.width = "250px";
			Element.removeClassName($("divSHMultiCity").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHMultiCity").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHMultiCity").style.display = "inline";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
			break;
		case "more":
			setAllCookieValue('sqft');
     		setAllCookieValue('listdate');
			$("divContainerAdvanceSearch").style.width = "400px";
			$("divPopUpSHSqft").style.display = "inline";
			$("divPopUpSHListDate").style.display = "inline";
			
			//for property styles
			if($("divPopUpSHPropStyle"))
			{
				var arrChkBox = $('propStyleDv').getElementsByTagName("input");
				var lenArrChkBox = arrChkBox.length;
				var allChked = true;
				var strChkBox = getSearchCookie("propStyle");

				if(strChkBox == "" || strChkBox == null)
				{
					for(var i=0;i<lenArrChkBox;i++)
					{
				    	if(arrChkBox[i].id == "chkStyleAll")
				    	{
				    		continue;
				    	}
		    			if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == false)
		    			{
		    				arrChkBox[i].checked = true;
		    			}
					}
				}
				else
				{
					var arrStrChkBox = strChkBox.split(":");
					for(var i=0;i<lenArrChkBox;i++)
					{
						if (arrChkBox[i].id == "chkStyleAll")
						{
							continue;
						}
						if(arrChkBox[i].type == "checkbox")
						{
							var valChkBox = arrChkBox[i].value;
		    				if(arrStrChkBox.in_array(valChkBox) !== false)
		    				{
		    					arrChkBox[i].checked = true;
		    				}
							else
							{
								allChked = false;
								arrChkBox[i].checked = false;
							}
						}						
					}
				}

				if(allChked == true)
				{
					$("chkStyleAll").checked = true;
				}
				else
				{
					var confAllChked = true;
					for(var i=0;i<lenArrChkBox;i++)
					{
						if (arrChkBox[i].id == "chkStyleAll")
						{
							continue;
						}
						if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
						{
							confAllChked = false;
							break;
						}
					}
					
					if(confAllChked == true)
					{
						for(var i=0;i<lenArrChkBox;i++)
						{
							if(arrChkBox[i].type == "checkbox")
								arrChkBox[i].checked = true;
						}
					}
					else
						$("chkStyleAll").checked = false;
				}
				$("divPopUpSHPropStyle").style.display = "inline";
			}

			//for parking styles
			if($("divPopUpSHGarage"))
			{
				setAllCookieValue("garage");
				/*var arrChkBox = $('parkingStyleDv').getElementsByTagName("input");
				var lenArrChkBox = arrChkBox.length;
				var allChked = true;
				for(var i=0;i<lenArrChkBox;i++)
				{
					if (arrChkBox[i].id == "chkParkingStyleAll")
					{
						continue;
					}
					if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
					{
						continue;
					}
					else
					{
						allChked = false;
						break;
					}
				}
				if(allChked == true)
				{
					$("chkParkingStyleAll").checked = true;
				}
				else
				{
					$("chkParkingStyleAll").checked = false;
				}*/
				$("divPopUpSHGarage").style.display = "inline";
			}

			$("divPopUpSHMLSInfo").style.visibility = "hidden";
			$('searchCSZ').value = $('searchCSZ').value.replace (/^\s+/g, '').replace (/\s+$/g, '').replace (/\s+/g, ' ');
			if(countySearchEnabled == 1)
			{
				if((trim($('searchCSZ').value) == "")||(trim($('searchCSZ').value).toLowerCase () == "required"))
				{
					var ihCounty = "";
					ihCounty = ihCounty + '<a href="javascript:void(0);" onclick="javascript:funGetCounty(\'county\',\''+page+'\');" class="linkOkCancleSH lang">Get County Information</a>'; 
					$("divSHDataCounty").innerHTML = ihCounty;
					$("divPopUpSHCounty").style.display = "inline";
				}
				else
				{
					var isCompare = funCompareSearchCookie();
					if(isCompare === 1)
					{
						var ihCounty = "";
						ihCounty = ihCounty + '<a href="javascript:void(0);" onclick="javascript:funGetCounty(\'county\',\''+page+'\');" class="linkOkCancleSH lang">Get County Information</a>'; 
						$("divSHDataCounty").innerHTML = ihCounty;
						$("divPopUpSHCounty").style.display = "inline";
					}
					else
					{
						if(arrDataCounty.length == 0)
						{
							funGetCounty(srchcrt,page);
						}
						else
						{
							var strCKCounty = getSearchCookie("county");
							var arrCKCounty = strCKCounty.split(',');
							var ihCounty = "";
							var lenArrDataCounty = arrDataCounty.length;
							ihCounty = ihCounty + '<table cellpadding="0" cellspacing="0" style="width:100%;height:100%;">';
							for(var i=0;i<lenArrDataCounty;i++)
							{
								var countyName = arrDataCounty[i]['county'];
								ihCounty = ihCounty + '<tr>'; 
									ihCounty = ihCounty + '<td style="width:20%;">'; 
										if(arrCKCounty.in_array(countyName) !== false)
										{
											ihCounty = ihCounty + '<input type="checkbox" value="'+countyName+'" checked="checked" />';
										}
										else
										{
											ihCounty = ihCounty + '<input type="checkbox" value="'+countyName+'"  />';
										}	
									ihCounty = ihCounty + '</td>'; 
									ihCounty = ihCounty + '<td style="width:80%;">'; 
										ihCounty = ihCounty + '<span class="contentSHPopup lang">'+countyName+'</span>';
									ihCounty = ihCounty + '</td>'; 
								ihCounty = ihCounty + '</tr>'; 
							}	
							ihCounty = ihCounty + '</table>';
							
							$("divSHDataCounty").innerHTML = ihCounty;
							$("divPopUpSHCounty").style.display = "inline";
						}
					}
				}
			}
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "county":
			var isContradict = funCheckContradict();
			if(isContradict == null || isContradict == 0)
			{
				return;
			}
			if(arrDataCounty.length == 0)
			{
				funGetCounty(srchcrt,page);
			}
			else
			{
				var strCKCounty = getSearchCookie("county");
				var arrCKCounty = strCKCounty.split(',');
				var ihCounty = "";
				var lenArrDataCounty = arrDataCounty.length;
				ihCounty = ihCounty + '<table cellpadding="0" cellspacing="0" style="width:100%;height:100%;">';
				for(var i=0;i<lenArrDataCounty;i++)
				{
					var countyName = arrDataCounty[i]['county'];
					ihCounty = ihCounty + '<tr>'; 
						ihCounty = ihCounty + '<td style="width:20%;">'; 
							if(arrCKCounty.in_array(countyName) !== false)
							{
								ihCounty = ihCounty + '<input type="checkbox" value="'+countyName+'" checked="checked" />';
							}
							else
							{
								ihCounty = ihCounty + '<input type="checkbox" value="'+countyName+'"  />';
							}	
						ihCounty = ihCounty + '</td>'; 
						ihCounty = ihCounty + '<td style="width:80%;">'; 
							ihCounty = ihCounty + '<span class="contentSHPopup lang">'+countyName+'</span>';
						ihCounty = ihCounty + '</td>'; 
					ihCounty = ihCounty + '</tr>'; 
				}	
				ihCounty = ihCounty + '</table>';
				
				$("divSHDataCounty").innerHTML = ihCounty;
				Element.removeClassName($("divSHCounty").getElementsByTagName('a')[0],'linkAdvanceSearch');
				Element.addClassName($("divSHCounty").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
				$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHMLSInfo").style.visibility = "visible";
				$("divPopUpSHCounty").style.display = "inline";
			}
			break;
		case "neighborhood":
			if ($('searchCSZ').value.search(/;/) > -1)
			{
				$('divPopUpSHNeighborHood').style.height = "50px";
				$("divPopUpSHControls").innerHTML = '&nbsp<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';
				$("divSHDataNeighborHood").innerHTML = '<span class="contentSHPopup">Please select single city to enable neighborhood search.</span>';
				$("divPopUpSHMLSInfo").style.visibility = "hidden";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
				headerContent("neighborhood");
				break;
			}
			if($('chkmapSearchSelect') != null && $('chkmapSearchSelect').checked == true) 			
			{
				$('divPopUpSHNeighborHood').style.height = "50px";
				$("divPopUpSHControls").innerHTML = '&nbsp<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';
				$("divSHDataNeighborHood").innerHTML = '<span class="contentSHPopup">Please disable Map Search to enable neighborhood search.</span>';
				$("divPopUpSHMLSInfo").style.visibility = "hidden";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
				headerContent("neighborhood");
				break;
			}
			if(trim(getSearchCookie("county")) != "" && countySearchEnabled == "1")	
			{
				$('divPopUpSHNeighborHood').style.height = "50px";
				$("divPopUpSHControls").innerHTML = '&nbsp<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';
				$("divSHDataNeighborHood").innerHTML = '<span class="contentSHPopup">Please deselect county to enable neighborhood search.</span>';
				$("divPopUpSHMLSInfo").style.visibility = "hidden";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
				headerContent("neighborhood");
				break;
			}
			if($("txtArea") && $("txtArea").value != "")
			{
				$('divPopUpSHNeighborHood').style.height = "50px";
				$("divPopUpSHControls").innerHTML = '&nbsp<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';
				$("divSHDataNeighborHood").innerHTML = '<span class="contentSHPopup">Please disable Area Search to enable neighborhood search.</span>';
				$("divPopUpSHMLSInfo").style.visibility = "hidden";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
				headerContent("neighborhood");
				break;
			}
			
			var isContradict = funCheckContradict();
			if(isContradict == null || isContradict == 0)  
			{
				return;
			}
			if(arrDataNeighborHood.length == 0)
			{
				funGetNeighborHood(srchcrt,page);
			}
			else
			{
				$('divPopUpSHNeighborHood').style.height = "150px";
				var strCKNH = getSearchCookie("neighborhood");
				var arrCKNH = strCKNH.split(',');
				var ihNeighborHood = new StringBuffer();
				var lenArrDataNeighborHood= arrDataNeighborHood.length;
				ihNeighborHood.append('<table cellpadding="0" cellspacing="0" style="width:250px; height:100%;" border="0">');
					ihNeighborHood.append('<tr>'); 
						ihNeighborHood.append('<td style="width:30px;">'); 
							ihNeighborHood.append('<input type="checkbox" value=""  id="chbSHNHAll" name="chbSHNHAll" onclick="javscript:funSetSHNHAll();"/>');
						ihNeighborHood.append('</td>'); 
						ihNeighborHood.append('<td style="width:220px;">'); 
							ihNeighborHood.append('<span class="contentSHPopup lang">all</span>');
						ihNeighborHood.append('</td>'); 
					ihNeighborHood.append('</tr>'); 
				for(var i=0;i<lenArrDataNeighborHood;i++)
				{
					ihNeighborHood.append('<tr>'); 
						ihNeighborHood.append('<td style="width:30px;">'); 
							if(typeof(arrDataNeighborHood[i]['neighborhood']) != "undefined")
							{
								if((arrCKNH.in_array(arrDataNeighborHood[i]['neighborhood']) !== false) || (trim(strCKNH) == 'all'))
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['neighborhood']+'" onclick="javascript:funUnchkAllChkBox(this);" checked="checked" />');
								}
								else
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['neighborhood']+'" onclick="javascript:funUnchkAllChkBox(this);" />');
								}	
							}
							else if(typeof(arrDataNeighborHood[i]['area']) != "undefined")
							{
								if((arrCKNH.in_array(arrDataNeighborHood[i]['area']) !== false) || (trim(strCKNH) == 'all'))
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['area']+'" onclick="javascript:funUnchkAllChkBox(this);" checked="checked" />');
								}
								else
								{
									ihNeighborHood.append('<input type="checkbox" value="'+arrDataNeighborHood[i]['area']+'" onclick="javascript:funUnchkAllChkBox(this);" />');
								}
							}
						ihNeighborHood.append('</td>');
						ihNeighborHood.append('<td style="width:220px;">');
							if(typeof(arrDataNeighborHood[i]['neighborhood']) != "undefined")
								ihNeighborHood.append('<span class="contentSHPopup lang">'+arrDataNeighborHood[i]['neighborhood']+'</span>');
							else if(typeof(arrDataNeighborHood[i]['area']) != "undefined")
								ihNeighborHood.append('<span class="contentSHPopup lang">'+arrDataNeighborHood[i]['code']+" - "+arrDataNeighborHood[i]['area']+'</span>');
						ihNeighborHood.append('</td>'); 
					ihNeighborHood.append('</tr>'); 
				}	
				ihNeighborHood.append('</table>');
				$("divSHDataNeighborHood").innerHTML = ihNeighborHood.toString();
				var arrChkBox = $('divSHDataNeighborHood').getElementsByTagName("input");
				var lenArrChkBox = arrChkBox.length;
				var allChked = true;
				for(var i=0;i<lenArrChkBox;i++)
				{
			    	if((arrChkBox[i].id == "chbSHNHAll") || (arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true))
			    	{
			    		continue;
			    	}
					else
					{
						allChked = false;
						break;
					}
				}
				if(allChked == true)
				{
					$("chbSHNHAll").checked = true;
				}
				Element.removeClassName($("divSHNeighborHood").getElementsByTagName('a')[0],'linkAdvanceSearch');
				Element.addClassName($("divSHNeighborHood").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
				$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
				$("divPopUpSHMLSInfo").style.visibility = "visible";
				$("divPopUpSHControls").style.display = "inline";
				$("divPopUpSHNeighborHood").style.display = "inline";
			}
			break;
		case "price":
			Element.removeClassName($("divSHPrice").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHPrice").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHPrice").style.display = "inline";
			if($("minPrice") && getSearchCookie("minPrice")!='0' && getSearchCookie("minPrice")!='') $("minPrice").value = addCommas(getSearchCookie("minPrice"));
			if($("maxPrice") && getSearchCookie("maxPrice")!='0' && getSearchCookie("maxPrice")!='') $("maxPrice").value = addCommas(getSearchCookie("maxPrice"));
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "beds":
			setAllCookieValue('beds');
			Element.removeClassName($("divSHBeds").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHBeds").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHBeds").style.display = "inline";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "baths":
			setAllCookieValue('baths');
			Element.removeClassName($("divSHBaths").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHBaths").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHBaths").style.display = "inline";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "sqft":
			Element.removeClassName($("divSHSqft").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHSqft").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHSqft").style.display = "inline";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "listdate":
			Element.removeClassName($("divSHListDate").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHListDate").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHListDate").style.display = "inline";
			$("divPopUpSHMLSInfo").style.visibility = "visible";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "type":
			var arrChkBox = $('divPopUpSHType').getElementsByTagName("input");
			var lenArrChkBox = arrChkBox.length;
			var allChked = true;
			for(var i=0;i<lenArrChkBox;i++)
			{
				if (arrChkBox[i].id == "chbSHTypeAll")
				{
					continue;
				}
				if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
				{
					continue;
				}
				else
				{
					allChked = false;
					break;
				}
			}
			if(allChked == true)
			{
				$("chbSHTypeAll").checked = true;
			}
			else
			{
				$("chbSHTypeAll").checked = false;
			}

			Element.removeClassName($("divSHType").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHType").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHType").style.display = "inline";
			$("divPopUpSHMLSInfo").style.visibility = "visible";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "mls":
			Element.removeClassName($("divSHMLS").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHMLS").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			if(trim(getSearchCookie('mlsno')) != "")
			{
				$("searchMLS").value = trim(getSearchCookie('mlsno'));
			}
			else
			{
				$("searchMLS").value = "";
			}
			$("divPopUpSHMLS").style.display = "inline";
			$("divPopUpSHMLSInfo").style.visibility = "visible";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "sortby":
			Element.removeClassName($("divSHSortBy").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSHSortBy").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divPopUpSHSortBy").style.display = "inline";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;		
		case "power":
			$("divContainerAdvanceSearch").style.width = "456px";
			if($("divSHPowerSortBy"))
			{
				Element.removeClassName($("divSHPowerSortBy").getElementsByTagName('a')[0],'linkAdvanceSearch');
				Element.addClassName($("divSHPowerSortBy").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			}
			$("divPopUpSHPower").style.display = "inline";
			$("divPopUpSHControls").innerHTML = '<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchOK" name="anchorAdvanceSearchOK" onclick="javascript:funSaveAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">save</a>&nbsp;&nbsp;<a href="#" class="linkOkCancleSH lang"  id="anchorAdvanceSearchGo" name="anchorAdvanceSearchGo" onclick="javascript:funGoAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">go</a>&nbsp;&nbsp;<a href="javascript:void(0);" class="linkOkCancleSH lang"  id="anchorAdvanceSearchClose" name="anchorAdvanceSearchClose" onclick="javascript:funCloseAdvanceSearch(\''+srchcrt+'\',\''+page+'\');">close</a>';	
			$("divPopUpSHControls").style.display = "inline";
			break;
		case "saveSearch":
			Element.removeClassName($("divSaveSearch").getElementsByTagName('a')[0],'linkAdvanceSearch');
			Element.addClassName($("divSaveSearch").getElementsByTagName('a')[0],'linkSelAdvanceSearch');
			$("divSaveSearch").style.display = "inline";
			if($("errDivP")) $("errDivP").innerHTML = "";
			if($("txtSrchNm"))
			{
				$("txtSrchNm").value = "";
				$("txtSrchNm").className = 'lang';
			}
			if($("txtClient")) $("txtClient").value = "";
			if($("txtEmails"))
			{
				$("txtEmails").value = "";
				$("txtEmails").className = 'lang';
			}
			break;
		default: 
			return;
	}
	
	var element = Event.element(e);
	var objDiv = element.parentNode;
	var posLeft = getPositionLeft(objDiv);
	if(srchcrt=="power")
		posLeft -=7; 
	var posTop = getPositionTop(objDiv);
	$("divContainerAdvanceSearch").style.left = posLeft + "px";
	$("divContainerAdvanceSearch").style.top = eval(posTop + 15) + "px";
	if(!isIE && srchcrt=="more")	
			$("divContainerAdvanceSearch").style.top = eval(posTop + 9) + "px";
	$("divContainerAdvanceSearch").style.display = "block";
	
}

//====================================================
//LMSRE specific:
//it will check on two pan map..if multicity then give
//alert else allow to go and perform other action
//====================================================
function checkMultiCity()
{
		var cityPipeList = getSearchCookie("city");
		var stateMy = getSearchCookie("state");
		if($("searchCSZ"))
			var csz = $("searchCSZ").value;
		var flag = false;
		if(cityPipeList.indexOf("|") > -1)
		{
			flag=true;
		}
		else
		{
			flag=false;
		}
		return flag;
}
//====================================================
//LMSRE specific:
//called while dragging any bit,and onclik of 
//dashboard tab.
//====================================================
function callMultiCityCheck_Dashboard(fromWhere,bitzName)
{

	var cityPipeList = getSearchCookie("city");
	var csz = $("searchCSZ").value;	
	if(cityPipeList.indexOf("|") > -1  || csz=="required" || csz=="")
	{
		if(fromWhere == 'dashboard')
		{	
			bitzName = "dashboard";
			showPopupDivforMenu(bitzName,'mapit');
		}
		if(fromWhere == 'mapit')
		{
			bitzName = "mapit";
			showPopupDivforMenu(bitzName,'dashboard');
		}
		return false;
	}
	else if(fromWhere == "dashboard")
	{
		var qs = new Querystring();
		var isNoSearch = qs.get('noSearch');
		if(isNoSearch != null && trim(isNoSearch) == 1)
		{
			location.href="../dashboard/dashboardIndex.php?noSearch=1";
		}
		else if (bkTheme == 'reotexashomes') //to load reo bit as default on dashboard of reotexashomes
		{
			var now = new Date();
			now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
			var myObject = new Object();
			myObject.widget1X1="bankowned";
			setCookie("strWidgetCookie",$H(myObject).toJSON(),now);

			location.href="../dashboard/dashboardIndex.php";
		}
		else
		{
			location.href="../dashboard/dashboardIndex.php";
		}
	}
	else if(fromWhere == "mapit")
	{
		callExploreNeighbourhood(); 
	}
}
function callMultiCityCheck_Dashboard_Metro(fromWhere,bitzName)
{
	var cityPipeList = getSearchCookie("city");
	
	if(cityPipeList.indexOf("|") > -1)
	{
		if(fromWhere == "dragbit")
		{
			//DO NOTHING
		}
		else
		{
			if(fromWhere == 'dashboard')
				bitzName = "dashboard";
			showPopupDivforMenu(bitzName,'mapit');
			return false;
		}
	}
	if(fromWhere == "dashboard")
	{
		location.href="../dashboard/dashboardIndex.php";
	}
}
/**
 * Extra useful functions to the standard javascript prototypes.
 * Added By: Pankit Bhanushali
 */
Array.prototype.intersection = function( value ) {

	var result = new Array();
	
	if( typeof value != "object" ) {
		value = new Array(value);
	}
	
    for( var tc = 0; tc<this.length; tc++) {
		for( var vc = 0; vc < value.length; vc++ ) {
	        if( this[tc] == value[vc] ) {
				result.push_back(value[vc]);
			}
		}
    }
    return result;
}
Array.prototype.push_back = function( value ) {
	if( typeof value == "object" && value.length ) {
		for( var count = 0; count < value.length; count++ ) {
			this[this.length] = value[count];
		}
	} else {
		this[this.length] = value;
	}
}

/** code for brokeragent light box to get all office list **/
function getOffice(type)
{
	var queryString="type=off";
	if(type != null)
		queryString="type=offLoc";
	var url="/app/listing/getOffice.php";
	ajaxRequest(url,queryString,officeCallBack);	
}

//Callback for Assign Lead
function officeCallBack(originalResponse)
{
	var responce = originalResponse.responseText;
	
	
	/*****************sanju, this code can u used if company name depends on office location****************************/
	
	/*
	var respArr = responce.split('<!sep!>');
	if(respArr[0] == 'offLoc')
	{
		$('allOfficeLoc').innerHTML = respArr[1];
		if($('radioOffice').checked)
			$('txtOfficeLoc').disabled= false;
		else
			$('txtOfficeLoc').disabled= true;
	}
	else if(respArr[0] == 'offM')
	{
		$('allOffice').innerHTML = respArr[1];
		if($('radioOffice').checked)
			$('txtOffice').disabled= false;
		else
			$('txtOffice').disabled= true;
	}
	else if(respArr[0] == 'off')
	{
		$('allOffice').innerHTML = respArr[1];
		if($('radioOffice').checked)
			$('txtOffice').disabled= false;
		else
			$('txtOffice').disabled= true;
	}
	* 
	********************************************/
	
	/********************sanju, code that will load both company name and office loc simultanously*************************************/
	
	
	$('allOffice').innerHTML = responce;
	if($('radioOffice').checked)
		$('txtOffice').disabled= false;
	else
		$('txtOffice').disabled= true;
	
	
	/***************************************************************/
}

function offLocChanged()
{
	var offLocId = escape($("txtOfficeLoc").options[$("txtOfficeLoc").selectedIndex].value);
	var queryString="olid="+offLocId;
	var url="/app/listing/getOffice.php";
	ajaxRequest(url,queryString,officeCallBack);	
}

function funExploreMlsAddrMap()
{
	showDetail=1;
	latp = latLong.lat;
	lngp = latLong.lng;

	var city = getSearchCookie("city");
	var zip = getSearchCookie("zip");
	var state = getSearchCookie("state");
	var ad = getSearchCookie("searchAddress");	
	/*var mapLoadedBits = getCookie("strMapitCK");
	
	if (mapLoadedBits != "")
	{
		mapLoadedBits = mapLoadedBits + ",mlsaddrsearch";
	}
	else
	{
		mapLoadedBits = "mlsaddrsearch";
	}*/

	if(mapToShow == "")
	{
		setMapItCookie("mlsaddrsearch","add");
		newUrl = "/app/listing/singlePropertyLanding.php?PHPSESSID=&status=EXP&address=" + ad + "," + city + "," + state + "," + zip + ",,,," + latp + "," + lngp;
	}
	else
	{
		setMapItCookie("mlsNHoodMode","add");
		newUrl = "/app/listing/singlePropertyLanding.php?status=N&code=propView=1:::searchAddress="+ad+":::city="+city+":::state="+state+":::zip="+zip+":::neighborhood=:::county=:::minPrice="+getSearchCookie("minPrice")+":::maxPrice="+getSearchCookie("maxPrice")+":::searchBeds="+getSearchCookie("searchBeds")+":::searchBaths="+getSearchCookie("searchBaths")+":::id=355&mapCenter=("+latp+","+lngp+")&valChkMapSearchSelect=1&fe=&f=1&propLatitude="+latp+"&propLongitude="+lngp+"&mapZoom=13";
	}
	var myQs = new Querystring();
	var frm = myQs.get("frm");
	var aid = myQs.get("aid");
	if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
	{
		newUrl = newUrl + "&frm=agt&aid="+aid;

		//agentsite statistics
		var beds = getSearchCookie("searchBeds");
		var baths = getSearchCookie("searchBaths");
		var type = getSearchCookie("searchType");
		var minprice = getSearchCookie("minPrice");
		var maxprice = getSearchCookie("maxPrice");

		var url = "../../classes/emailStats.php";
		var qs = "from=search&aid="+aid+"&city="+city+"&type="+type+"&beds="+beds+"&baths="+baths+"&price="+minprice+"-"+maxprice+"&addr="+ad+"&mlsno=";

		ajaxRequest(url,qs);
		//statistics done
	}
	window.location.href = newUrl;
	return;
}

function gotoSellDshbrd(uid)
{
	if (uid != 1)
	{
		var myObject = new Object();
		myObject.widget1X1="recentsales";
		myObject.widget1X2="marketsnapshot";
		myObject.widget1X3="equity";
		myObject.widget2X1="valuehome";
		myObject.widget2X2="";
		myObject.widget2X3="";
		myObject.widget3X1="";
		myObject.widget3X2="";
		myObject.widget3X3="";

		var now = new Date();
		now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
		setCookie("strWidgetCookie",$H(myObject).toJSON(),now);

		location.href = "http://" + location.hostname + "/app/dashboard/dashboardIndex.php";
	}
	else
	{
		var queryStr="widgetsConf=1,1,25|1,2,46|1,3,57|2,1,58|2,2,|2,3,|3,1,|3,2,|3,3,&setUserPref=1";
		var url ="/app/dashboard/dshbrdProcess.php";
		ajaxRequest(url,queryStr,loadDecDash);
	}
}
function loadDecDash(response)
{
	location.href = "http://" + location.hostname + "/app/dashboard/dashboard.php";
}

function gotoDashBrdFoot(call)
{
	if(call == '1' || call == '0' )
		location.href = "http://" + location.hostname + "/terabitzApi/finance/index.php";
	else if(call == 'openhouse')
	{
		setSearchCookie("listType","openHome");		
		setSearchCookie("ohflag","1");		
		url = 	'/Search/'+getSearchCookie("state")+'/'+getSearchCookie("city");
		location.href = url;
	}
	else
	{
		ClrQckSrchCookies();
		location.href = "http://" + location.hostname + "/app/listing/singlePropertyLandingNew.php";
	}
}

function gotoDashBrdFoot_org(call)
{
	var city = getSearchCookie("city");
	var state= getSearchCookie("state");

	if(trim(city) == '' && city != null)
	{
		var now = new Date();
		now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
		city = "San Jose";
		state = "CA";
		latLongStr = "[{'lat':'37.316466','lng':'-121.873881'}]";
		setCookie("latLongCk",latLongStr, now);
		latLong = eval(getCookie("latLongCk"))[0];
		setSearchCookie("city", city);			
		setSearchCookie ("state", state);
	}

	if (call == 'openhouse')
		callMapIt(call);
	else if (call == 1 || call == 0)
		gotoSellDshbrd(call);
	else
		callMapIt();
}

startStack=function() { };  // A stack of functions to run onload/domready

registerOnLoad = function(func) 
{
   var orgOnLoad = startStack;
   startStack = function () {
      orgOnLoad();
      func();
      return;
   }
}

var ranOnload=false; // Flag to determine if we've ran the starting stack already.

if (document.addEventListener) 
{
  // Mozilla actually has a DOM READY event.
   document.addEventListener("DOMContentLoaded", function(){if (!ranOnload) {ranOnload=true; startStack();}}, false);
}
else if (document.all && !window.opera)
{
  // This is the IE style which exploits a property of the (standards defined) defer attribute
  document.write("<scr" + "ipt id='DOMReady' defer=true " + "src=//:><\/scr" + "ipt>");  
  document.getElementById("DOMReady").onreadystatechange=function(){
    if (this.readyState=="complete"&&(!ranOnload)){
      ranOnload=true;
      startStack();
    }
  }
}

// Commented by ravi. Do not put onload funtion in Common files.

/*var orgOnLoad=window.onload;
window.onload=function() 
{
	if (typeof(orgOnLoad)=='function') 
	{
		orgOnLoad();
	}
	if (!ranOnload) 
	{
		ranOnload=true;
		startStack();
	}
}*/

var funRplcImgBitzBar = function()
{
	if($('divIconCollect'))
	{
		var dashIcons = $('divIconCollect').getElementsByClassName('dashIconsDrag');
		for(var i=0;i<dashIcons.length;i++)
		{
			var divImgId = dashIcons[i].id;
			var widgetName = divImgId.gsub('divImg_','');
			var imgId =  'img_'+widgetName;
			$(imgId).src = $(imgId).src.gsub('blankImg.gif',eval('widgetsData.'+widgetName+'.img_n'));
		}
	}
	
}
/*
registerOnLoad(funRplcImgBitzBar);

var startup1 = function() {
   alert("I'm the first function!")
}

registerOnLoad(startup1);
registerOnLoad(function () {
   alert("I'm the second function!")
});
*/

function funMakeBitClickable(bitName,page,from)
{
	var ihBitz = new StringBuffer();
		ihBitz.append('<table border="0" style="font-size:0.7em;width:100%;height:100%;border-spacing:0px;">');
			ihBitz.append('<tr>');
				if(page != null && trim(page) == 'dashboard')
				{
					var innerTitleText = "Click to load on dashboard";
				}
				else
				{
					var innerTitleText = "Click to load on map";
				}	
				if(from=="API")
				{
					var innerTitleText = "Click on the bit to load.";
				}
				ihBitz.append('<td align="center" valign="top"  onmouseover="try{showTooltip(\''+innerTitleText.stripTags()+'\',event);}catch(e){}" onmouseout="try{hideTooltip();}catch(e){}">');
					try
					{
						var bitImg = eval('widgetsData.'+bitName+'.img_n');
						var bitTitle = eval('widgetsData.'+bitName+'.title');
					}
					catch(e)
					{
						var bitImg = "";
						var bitTitle = "";
						
					}
				if(page != null && trim(page) == 'dashboard')
					{
						ihBitz.append('<img id="img_'+bitName+'" style="cursor:pointer;" class="crsr" src="../../wt/'+bkTheme+'/images/dashboard/toolbarIcons/'+bitImg+'"  title="" alt="'+bitTitle+'" onclick="javascript:funLoadOnDashboard(\''+bitName+'\');" />');
					}
					else
					{
						ihBitz.append('<img id="img_'+bitName+'" style="cursor:pointer;" class="crsr" src="../../wt/'+bkTheme+'/images/dashboard/toolbarIcons/'+bitImg+'"  title="" alt="'+bitTitle+'" onclick="javascript:funLoadOnMap(\''+bitName+'\');" />');
					}	
				ihBitz.append('</td>');
			ihBitz.append('</tr>');
		ihBitz.append('</table>');
		if($('divImg_'+bitName))
		{
            $('divImg_'+bitName).innerHTML = ihBitz.toString();
            $('img_'+bitName).onmouseover = revealThumbnail;
            $('img_'+bitName).onmouseout = hideThumbnail;
        }
}
function funLoadedOnMap(bitName,page)
{
	//alert('This bit is already loaded on map.'); 
	if(bitName == "wikipedia")
	{
		mapItCtrl.removeIcon_(mapItCtrl.getContainer_(),bitName);
		map.removeOverlay(wikiLayer);
		funMakeBitClickable(bitName);
		
		var currUrl = location.href;
		if(!currUrl.include("singlePropertyLanding.php"))
			unfillLoaded(bitName);
		return;
	}
	if(typeof(unfillLoaded)!="undefined")
	{
		unfillLoaded(bitName);
	}
	closeMapBit (bitName);
	funMakeBitClickable (bitName);
	return;
}
function funLoadedOnDashboard(bitName,page)
{
	//alert('This bit is already loaded on Dashboard.'); 
	funCloseWidget(null,bitName);
	return;
}
function funMakeBitNonClickable(bitName,page)
{
	var ihBitz = new StringBuffer();
		ihBitz.append('<table border="0" style="font-size:0.7em;width:100%;height:100%;border-spacing:0px;">');
			ihBitz.append('<tr>');
				if(page != null && trim(page) == 'dashboard')
				{
					var innerTitleText = "Click on the bit to remove.";
				}
				else
				{
					var innerTitleText = "Click on the bit to remove.";
				}	
				ihBitz.append('<td align="center" valign="top"  class="maskNonClickableBit" onmouseover="try{showTooltip(\''+innerTitleText.stripTags()+'\',event);}catch(e){}" onmouseout="try{hideTooltip();}catch(e){}">');
					var bitImg = eval('widgetsData.'+bitName+'.img_n');
					var bitTitle = eval('widgetsData.'+bitName+'.title');
					if(page != null && trim(page) == 'dashboard')
					{
						ihBitz.append('<img  id="img_'+bitName+'"  class="crsr" src="../../wt/'+bkTheme+'/images/dashboard/toolbarIcons/'+bitImg+'"  title="" alt="'+bitTitle+'" onclick="javascript:funLoadedOnDashboard(\''+bitName+'\');" />');
					}
					else
					{
						ihBitz.append('<img  id="img_'+bitName+'"  class="crsr" src="../../wt/'+bkTheme+'/images/dashboard/toolbarIcons/'+bitImg+'"  title="" alt="'+bitTitle+'" onclick="javascript:funLoadedOnMap(\''+bitName+'\');" />');
					}	
				ihBitz.append('</td>');
			ihBitz.append('</tr>');
		ihBitz.append('</table>');
	$('divImg_'+bitName).innerHTML = ihBitz.toString();
	$('img_'+bitName).onmouseover = hideThumbnail;
	$('img_'+bitName).onmouseout = hideThumbnail;
//	$('divImg_'+bitName).style.display = 'none';
}
function funMakeSummaryHeader(page)
{
	/*var ihSummaryHeader = new StringBuffer();
	if(page != null && trim(page) == 'dashboard')
		ihSummaryHeader = ihSummaryHeader + '<table style="width:180px;height:17px;" cellspacin="0" cellpadding="0" id="tblSummaryHeader">';
	else
		ihSummaryHeader = ihSummaryHeader + '<table style="width:178px;height:17px;" cellspacin="0" cellpadding="0" id="tblSummaryHeader">';
        ihSummaryHeader = ihSummaryHeader + '<tr>';
			ihSummaryHeader = ihSummaryHeader + '<td class="bgLeftSummaryHeader">&nbsp;</td>';
			if(page != null && trim(page) == 'dashboard')
				ihSummaryHeader = ihSummaryHeader + '<td class="bgMiddleSummaryHeader" align="center" valign="middle" id="tdSummaryHeader" style="width:164px;">';
			else
				ihSummaryHeader = ihSummaryHeader + '<td class="bgMiddleSummaryHeader" align="center" valign="middle" id="tdSummaryHeader" style="width:164px;">';
				
					ihSummaryHeader = ihSummaryHeader + '<span class="textSummaryHeader" id="spanSummaryHeader" >';
					if(page != null && trim(page) == 'dashboard')
						ihSummaryHeader = ihSummaryHeader + 'Currently active on dashboard';
					else
						ihSummaryHeader = ihSummaryHeader + 'Currently active on map';
					ihSummaryHeader = ihSummaryHeader + '</span>';
					
			ihSummaryHeader = ihSummaryHeader + '</td>';
			ihSummaryHeader = ihSummaryHeader + '<td class="bgRightSummaryHeader">&nbsp;</td>';
		ihSummaryHeader = ihSummaryHeader + '</tr>';
		
	ihSummaryHeader = ihSummaryHeader + '</table>';
	
	var myDiv = document.createElement('div');
	if(page != null && trim(page) == 'dashboard')
		myDiv.style.width = '180px';
	else
		myDiv.style.width = '170px';
	myDiv.style.position = 'absolute';
	if(page != null && trim(page) == 'dashboard')
	{
		var objSummaryArea = document.getElementById('divSummaryArea');
		var posLeft = getPositionLeft(objSummaryArea);
		var posTop = getPositionTop(objSummaryArea);
		myDiv.style.left = posLeft+'px';
		myDiv.style.top = (posTop-17)+'px';
	}
	else
	{
		var objIconContaner = document.getElementById('myIconContainer');
		var posLeft = getPositionLeft(objIconContaner);
		var posTop = getPositionTop(objIconContaner);
		myDiv.style.left = posLeft+'px';
		myDiv.style.top = (posTop-17)+'px';
	}	
	myDiv.innerHTML = ihSummaryHeader;
	document.body.appendChild(myDiv);*/
}
function funMakeSummaryArea(page)
{
	/*var objBitzBarHeader = document.getElementsByClassName('menuTrTb')[0];
	var posLeft = getPositionLeft(objBitzBarHeader);
	var posTop = getPositionTop(objBitzBarHeader);
	
	var divSummaryArea = document.createElement("div");
	divSummaryArea.id="divSummaryArea";
	divSummaryArea.className = "containerClass";
	
	if(page != null && trim(page) == 'dashboard')
		divSummaryArea.style.width = "178px";
	else
		divSummaryArea.style.width = "168px";
	divSummaryArea.style.cursor = 'default';	
	divSummaryArea.style.height = "50px";
	divSummaryArea.style.position = "absolute";
	divSummaryArea.style.left = eval(posLeft-190)+'px';
	divSummaryArea.style.top = eval(posTop+35)+'px';
	if(page != null && trim(page) == 'dashboard')
	{
		divSummaryArea.innerHTML = '<table cellspacing="0" cellpadding="0" style="cursor:default;width:100%;height:100%;"><tr><td style="width:100%;height:100%;" align="center" valign="middle" class="infoSummaryHeader">Click icons on right to populate dashboard.</td></tr></table>';
	}
	else
	{
		divSummaryArea.innerHTML = '<table cellspacing="0" cellpadding="0" style="cursor:default;width:100%;height:100%;"><tr><td style="width:100%;height:100%;" align="center" valign="middle" class="infoSummaryHeader">Click icons on right to populate map.</td></tr></table>';
	}
	//document.body.appendChild(divSummaryArea);
	funMakeSummaryHeader(page);*/
}
function funShowCrossedImage(objImg)
{
	var imgSrc = objImg.src;
	var newSrc = imgSrc.replace('.gif','Crossed.gif');
	objImg.src = newSrc;
}
function funHideCrossedImage(objImg)
{
	var imgSrc = objImg.src;
	var newSrc = imgSrc.replace('Crossed.gif','.gif');
	objImg.src = newSrc;
}
var cntLoadedBitz = 0;
function funAddBitToSummaryArea(bitName,page)
{
	if(page != null && trim(page) == 'dashboard')
	{
		if(cntLoadedBitz == 0)
		{
			//$('divSummaryArea').innerHTML = '';
		}
		var objDiv = document.createElement('div');
		objDiv.id = 'divSumBit_'+bitName;
		if(isIE)
			objDiv.style.styleFloat = 'left';
		else
			objDiv.style.cssFloat = 'left';
		objDiv.style.position = 'relative';
		objDiv.style.display = 'inline';
		objDiv.style.width = '29px';
		objDiv.style.height = '25px';
		objDiv.innerHTML = '<img src="/wt/'+bkTheme+'/images/common/'+bitName+'.gif" title="Remove '+unescape(widgetsData[bitName]['title']).stripTags()+'" alt="'+unescape(widgetsData[bitName]['title']).stripTags()+'" style="cursor:pointer" onmouseover="javascript:funShowCrossedImage(this);" onmouseout="javascript:funHideCrossedImage(this);" onclick="javascript:funRemoveBit(\''+bitName+'\',\''+page+'\');">';		
		//$('divSummaryArea').appendChild(objDiv);
		cntLoadedBitz = cntLoadedBitz + 1;
	}	
}
function funRemoveBit(bitName,page)
{
	if(page != null && trim(page) == 'dashboard')
	{
		funCloseWidget(null,bitName);
	}
}
function funRemoveImageFromSummaryArea(bitName,page,removeAll)
{
	if(removeAll != null && removeAll == true)
	{
		cntLoadedBitz = 0;
		//$('divSummaryArea').innerHTML = '<table cellspacing="0" cellpadding="0" style="cursor:default;width:100%;height:100%;"><tr><td style="width:100%;height:100%;" align="center" valign="middle" class="infoSummaryHeader">Click icons on right to populate dashboard.</td></tr></table>';
		return;
	}
	if(page != null && trim(page) == 'dashboard')
	{
		//if(($('divSummaryArea') != null) && ($('divSumBit_'+bitName) != null))
		//	$('divSummaryArea').removeChild($('divSumBit_'+bitName));
		cntLoadedBitz = cntLoadedBitz - 1;
		if(cntLoadedBitz == 0)
		{
		//	$('divSummaryArea').innerHTML = '<table cellspacing="0" cellpadding="0" style="cursor:default;width:100%;height:100%;"><tr><td style="width:100%;height:100%;" align="center" valign="middle" class="infoSummaryHeader">Click icons on right to populate dashboard.</td></tr></table>';
		}
	}
}

function openChatPage()
{
	var url = '/help/interoContactUs.php?hCity=' + getSearchCookie("city") + '&hState=' + getSearchCookie("state");
	window.open (url, '', '');
}

function setMapItckBlank(dshbrdUsrId)
{
	if(typeof(dshbrdUsrId) != "undefined" && dshbrdUsrId != "")
		setCookie('strMapitCK','');
}

function addCommas(num)
{
	var nStr = new String(num);
	if(nStr.indexOf(',') > 0)
	{					
		nStr = nStr.replace(/\,/g,'');
	}
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function numFormat(txtPrice)
{
	if($(txtPrice).value != '')
	{
		var price = $(txtPrice).value;
	
		if(price.indexOf(',') > 0)
		{					
			price = price.replace(/\,/g,'');
		}
		$(txtPrice).value = addCommas(price);
	}
}

function keyDown(e,txtprice)
{
	var keycode = e.keyCode;
	if(keycode!=37&& keycode!=38 &&keycode!=39&&keycode!=40)
	{
		numFormat(txtprice);
	}
}

function roundPrice(txtPrice)
{
	if($(txtPrice).value != '')
	{
		var valPrice = $(txtPrice).value;
		
		if(valPrice.indexOf(',') >= 0)
		{			
			valPrice = valPrice.replace(/\,/g,'');
		}
		if (!isNaN(valPrice))
		{
		   //$(txtPrice).value=addCommas(Math.round(valPrice));
		   $(txtPrice).value=addCommas(Math.round(valPrice));
		}
	}
}

function setAllCheckedStyle(from)
{
	if(typeof(from)!="undefined")
	{
		divId = "RSpropStyleDv";
		chkAllId = "RSchkStyleAll";
	}
	else
	{
		divId = "propStyleDv";
		chkAllId = "chkStyleAll";
	}

	if($(divId))
	{
		var arrChkBox = $(divId).getElementsByTagName("input");
		var lenChkBox = arrChkBox.length;

		for(var i=0;i<lenChkBox;i++)
		{	
			if(arrChkBox[i].id == chkAllId)
				continue;
			if(($(chkAllId).checked == true) && (arrChkBox[i].type == "checkbox"))
				arrChkBox[i].checked = true;
			else if(arrChkBox[i].type == "checkbox")
				arrChkBox[i].checked = false;
		}
	}
}

/*function setAllCheckedParkingStyle()
{
	if($("parkingStyleDv"))
	{
		var arrChkBox = $("parkingStyleDv").getElementsByTagName("input");
		var lenChkBox = arrChkBox.length;

		for(var i=0;i<lenChkBox;i++)
		{	
			if(arrChkBox[i].id == "chkParkingStyleAll")
				continue;
			if(($('chkParkingStyleAll').checked == true) && (arrChkBox[i].type == "checkbox"))
				arrChkBox[i].checked = true;
			else if(arrChkBox[i].type == "checkbox")
				arrChkBox[i].checked = false;
		}
	}
}*/

function chkAllOpt(chkAllID,divId)
{
   if($(divId))
	{
   var arrChkBox = $(divId).getElementsByTagName("input");
   lenOptWA = arrChkBox.length;
   lenOpt = arrChkBox.length - 1;
   chkCnt = 0;
   for(i=0;i<lenOptWA;i++)
   {
     if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
     {
       if(arrChkBox[i].id == chkAllID)
        continue;
       else
        chkCnt++; 
     }
   }
   if(chkCnt == lenOpt)
       $(chkAllID).checked = true;
   else
       $(chkAllID).checked = false; 
	}
}

function chkAllUnderDiv(divId,val)
{
	if($(divId)) {
		var arrChkBox = $(divId).getElementsByTagName("input");
		lenOptWA = arrChkBox.length;
		for(i=0;i<lenOptWA;i++)
		{
			if(arrChkBox[i].type == "checkbox" && val)		
				arrChkBox[i].checked = true;
			else
				arrChkBox[i].checked = false;
		}
	}
}

/*************** START ******************** USED FOR NEW POWER SEARCH AND LIST SEARCH CODE **********************/
function ClrQckSrchCookies()
{	
	funClrQckSrchCookies();
	deleteCookie("latLongCk");
	if($("helpBox")) $("helpBox").hide();
	if($('mlsSearchDiv')) $('mlsSearchDiv').hide();	
	if($('propHeroDiv')) $('propHeroDiv').hide();
	if($('botPagiRow')) $('botPagiRow').hide();	
	if($("paginationTd")) $("paginationTd").style.display = "none";	
	if($("recOperationDiv")) $('recOperationDiv').hide();
	if($('proListingDiv')) { $('proListingDiv').innerHTML = ""; $('proListingDiv').hide();	}
	if($('lrgSmlMapDiv')) $('lrgSmlMapDiv').hide();
	if($('limitBar')) $('limitBar').innerHTML ='';
	if($('divAutoComp')) $('divAutoComp').hide();
	if($('divLocalSearch')) $('divLocalSearch').hide();

	totalRecords = 0;	
	//TO CLEAR POWER SEARCH NEIGHBORHOOD
	if(typeof(clearNbr) == 'function' )
		clearNbr();
	if(typeof(clearGarage) == 'function' )
		clearGarage();
	tmpSpanMCTCookie = '';
	tmpSpanNBRCookie = '';
	if($('searchAddress')) $('searchAddress').disabled = false;
	if($('RSsearchAddress')) $('RSsearchAddress').disabled = false;	
	
	chkAllUnderDiv('divLocalSearch',false);
	removeSearchCookie("multicity");	
	removeSearchCookie("mctSpanHTML");
	if($('showMultiCity')) $('showMultiCity').innerHTML = "";
	
	removeSearchCookie("minPrice");
	removeSearchCookie("maxPrice");
	removeSearchCookie("listType");
	if(bkTheme == "reotexashomes")
	{ setSearchCookie("listType","bankOwned"); }
	removeSearchCookie("propDesc");
	removeSearchCookie("ckLFDate");
	removeSearchCookie("ckLTDate");
	removeSearchCookie("mlsno");
	removeSearchCookie("nbrSpanHTML");
	//removeSearchCookie("spanHTML");
	removeSearchCookie("lat");
	removeSearchCookie("lng");	
	removeSearchCookie("polygon");
	removeSearchCookie("area");		
	if($('clrSerArea')) $('clrSerArea').style.display='none';
	if($('drawSerArea')) $('drawSerArea').style.display='';	
	lfDate = ''; ltDate = ''; mlsno = '';
	if($("RStxtLFDate"))  $("RStxtLFDate").value = '';
	if($("RStxtLTDate"))  $("RStxtLTDate").value = '';
	if($("RSsearchMLS")) $("RSsearchMLS").value = '';
	if($('frmAdvanceSearch')) $('frmAdvanceSearch').reset();
	if($('frmPropSearch')) $('frmPropSearch').reset();
	if($('rsNHoodCntr')) $('rsNHoodCntr').style.display='none';	
	if($('shoNbhood')) $('shoNbhood').innerHTML= '';
	if($('keySerDiv'))  $('keySerDiv').innerHTML= '';
	//Added by surya for clearing the data from  temp string
	unChkstr  = "";
	chkdDat   = "";
	alwdCnt = 0 ;
	if (typeof(alwdCntMCT) != "undefined") alwdCntMCT = 0;
	if($('RSchbSHTypeAll')) $('RSchbSHTypeAll').checked = true;
	if($('polygonDiv')) $('polygonDiv').style.display='';	
	if($('serByNbrhood')) $('serByNbrhood').style.display='';		
	if($('searchMLS')) $('searchMLS').value = '';
	if($('pStatusList')) $('pStatusList').innerHTML = "";
	if($('pTypeList')) $('pTypeList').innerHTML = "";	
	if ($('crawlerNotificationArea'))
		$('crawlerNotificationArea').innerHTML = '';
	try 
	{
		funSetSHTypeAll('RS'); 
	} 
	catch (err)
	{ 
	}
	if($('RSsearchMLS')) $('RSsearchMLS').value = '';	
	if(typeof(initPower) != 'undefined' && !initPower) 
	{
		try {
				savePrpType(); 
			}
		catch(err)
		{
		
		}
	}
	if($('bit_select_box')) $('bit_select_box').value = "";
	totalRecords = 0;		
	if($('noRecTbl'))
	{		
		if(typeof(initPower) != 'undefined' && initPower)
		{
			var noRMsg = 'Select search criteria and Click "Agent View" Or "Consumer View".';
		}
		else
		{
			var noRMsg = 'Select search criteria and Click "UPDATE RESULTS".';
		}
		$('noRecTblMsg').innerHTML = noRMsg;
		$('noRecTbl').show();
	}

	if(!goToMap)
	{
		if($('SortPageTbl')) { $('SortPageTbl').hide(); }
		if($("picdivImg_0") && totalRecords > 0)
		{
			if($('favRoloDiv')) $('favRoloDiv').style.display = '';
		}
		else
		{
			if($('favRoloDiv')) $('favRoloDiv').style.display = 'none';
		}
		
		if( $("mapDiv") ) { $("mapDiv").style.display = 'none'; }
		if( $("drawsearchinfobar") ) { $("drawsearchinfobar").style.display = 'none'; }		
		if($('impMapShow'))
		{
			$('impMapShow').hide(); 
			$('impMapShow').innerHTML='View On Map'; 
		}
	}
	clearChkBoxInDiv("prpTyp");
    clearChkBoxInDiv("prpStat");
	if($("searchAddress")) $("searchAddress").className = "textboxSH";
	removeSearchCookie("spanStyleHTML");
	removeSearchCookie("propStyle")
	if($('prpStyleText')) $('prpStyleText').innerHTML = "";
	if(typeof(showMultiCityRelated) != "undefined" && typeof(showMultiCityRelated) == "function") 
	{
		showMultiCityRelated();
	}	
}

/************************** USED FOR NEW POWER SEARCH AND LIST SEARCH CODE **********************/

/************************************* Lead Management For Ezee Doc Function Starts Here ***************************/

function createHomeValuePopUp()
{		
	
		if($('errLeadPro'))$('errLeadPro').innerHTML = "";
		if($('txtConsEmail')){$('txtConsEmail').className = "";$('txtConsEmail').value="";}
		if($('txtConsAddress'))$('txtConsAddress').className = "";
		if($('txtConsPhone'))$('txtConsPhone').className = "";
		if($('txtConsCity'))$('txtConsCity').className = "";
		if($('txtConsState'))$('txtConsState').className = "";
		if($('txtConsZip'))$('txtConsZip').className = "";

				flg=false;	
				
					if(($("txtAddress") && $("txtCSZ")) && ($("txtAddress") != null && $("txtCSZ")!= null))
					{
						var adr = escape($("txtAddress").value + "," + $("txtCSZ").value);
						var url = "/agentsite/processAgent.php";
						var qs = "process=validateAddress&address="+adr;
						ajaxRequest(url,qs,function(reqobj){ 
							var varResponse = trim(reqobj.responseText);
								if(varResponse != "")
								{
									flg = true;
									var arr = varResponse.split("|");
									
									if($("txtAddress"))$("txtAddress").value = arr[0];
									if($("txtCSZ"))$("txtCSZ").value = arr[1] + ", " + arr[2] + " " + arr[3];
									city=arr[1];
									state=arr[2];
									zip= arr[3];
								}
								else
								{
									alert("Invalid Address");
								}
						},false);

						if(flg)
						{
							
							top.$('leadFrmHomePopUp').style.display= "block";
							top.$('txtConsAddress').value=$('txtAddress').value;
							top.$('txtConsCity').value=city;
							top.$('txtConsState').value=state;
							top.$('txtConsZip').value=zip;
							top.$('errEmailPro').innerHTML="&nbsp;";		
							top.leadEmailDlg1.show();
							if(top.$('txtConsName'))top.$('txtConsName').focus();	
						}
					}
					else
						{
							
							if(typeof(estimateAddress) != "undefined"  && (typeof(estimateCity)!= "undefined" && typeof(estimateState)!= "undefined" && typeof(estimateZip)!= "undefined" ))
								{

										if($('leadFrmHomePopUp1')) $('leadFrmHomePopUp1').style.display= "block";	
										if($('txtConsName') != null)$('txtConsName').value = "";
										if($('txtConsAddress') != null){$('txtConsAddress').className=""; $('txtConsAddress').value=estimateAddress ; }
										if($('txtConsCity') != null){$('txtConsCity').className="" ; $('txtConsCity').value=estimateCity ;}
										if($('txtConsState') != null){$('txtConsState').className="" ; $('txtConsState').value=estimateState ;}
										if($('txtConsZip') != null){$('txtConsZip').className=""; $('txtConsZip').value=estimateZip ;}
										if(document.saleform.sale)
											document.saleform.sale[0].checked = true ;
										if($("txtConsComments") != null)$("txtConsComments").value = "";
										if($('errEmailPro')) $('errEmailPro').innerHTML="&nbsp;";		
										if(leadEmailDlg1 != "undefined") leadEmailDlg1.show();
										if($('leadFrmHomePopUp1_c')) $('leadFrmHomePopUp1_c').style.zIndex='17';
										if($('leadFrmHomePopUp1_mask')) $('leadFrmHomePopUp1_mask').style.zIndex='16';
										
								}
						}

			
				
				
			
}
	
/************************* Lead Management For Ezee Doc Function Ends Here *********************/

/*********************** USED FOR NEW POWER SEARCH AND LIST SEARCH CODE **********************/

function goToListSearch()
{	
	url = 	'/Search/'+getSearchCookie("state")+'/'+getSearchCookie("city");
	var qs = new Querystring();
	if(qs.get("frm") != null && trim(qs.get("frm")) == 'agt' && qs.get("aid") != null)
	{
		url += "?frm="+trim(qs.get("frm"))+"&aid="+trim(qs.get("aid"));
	}
	location.href=url;
}
function goToTools()
{
	url = 	'/terabitzApi/finance/index.php?city='+getSearchCookie("city")+'&state='+getSearchCookie("state");
	var qs = new Querystring();
	if(qs.get("frm") != null && trim(qs.get("frm")) == 'agt' && qs.get("aid") != null)
	{
		url += "&frm="+trim(qs.get("frm"))+"&aid="+trim(qs.get("aid"));
	}
	location.href=url;
}


function clearChkBoxInDiv(divId)
{
        if($(divId))
		{			
			var arrChkBox = $(divId).getElementsByTagName("input");
			for(i=0;i<arrChkBox.length;i++)
			{
				if(arrChkBox[i].type == "checkbox" && arrChkBox[i].checked == true)
				{
					arrChkBox[i].checked = false;
				}
			}
        }
}

function clearCityStateMLS()
{
	removeSearchCookie("city");	
	removeSearchCookie("state");
	removeSearchCookie("mlsno");
}

// Added For Giving Alert To Registered User When It Clicks On Vendor Login Page

function redirectUser()
{
  var confirmation = confirm("All your current sessions will expire if you navigate to this page. Do u wish to continue. !!")
	if(confirmation == true)
	{
	    location.href = 'http://'+document.location.host+'/app/vendor/login.php';
	}
	else
		return false;
}

function checkInArray(fStr,serArr)
{
    for (key in serArr)
    {
        if(serArr[key] == fStr)
        return true;
    }
    return false;
}

function cmImplodeArr(arr,sep)
{
	var arrStr="";
	for(i=0;i<arr.length;i++)
	{	
		arrStr += arr[i];
		if(i<((arr.length) - 1)){arrStr += sep;}
	}
	return arrStr;
}

function cmExplodeArr(arrStr,sep)
{
	var arrSplt=Array();
	arrSplt=arrStr.split(sep);
	return arrSplt;
}

function goToToolsWithBit(bit, chkVar)
{
	url = 	'/terabitzApi/finance/index.php?city='+getSearchCookie("city")+'&state='+getSearchCookie("state");
	var qs = new Querystring();	
	if(qs.get("frm") != null && trim(qs.get("frm")) == 'agt' && qs.get("aid") != null)
	{
		url += "&frm="+trim(qs.get("frm"))+"&aid="+trim(qs.get("aid"));
	}	
	if(bit != '')
		url += "&bit="+bit+"&chkVar=" + chkVar;
	location.href=url;
}

// To set value of list box
// used on list search and property alert
function setListBoxValue (listId, listVal)
{
	if ($(listId))
	{
		for (i=0; i<$(listId).length; i++)
		{
			if ($(listId)[i].value == listVal)
			{
				$(listId).selectedIndex = i;
				break;
			}
		}	
	}
}

function setMultiselectListBoxValue (listId, listVal, separator)
{
	if (separator == null)
		separator = ",";

	if ($(listId))
	{
		listVal = separator + listVal + separator;

		for (i=0; i<$(listId).length; i++)
		{
			if (listVal.indexOf (separator + $(listId)[i].value + separator) != -1)
			{
				$(listId)[i].selected = true;
			}
		}	
	}
}

function goToMapSearchEmerge()
{
	if(getSearchCookie("polygon"))
		removePolyRelated();
	if(getSearchCookie("neighborhood") && bkTheme != 'pruone')
		removeSearchCookie("neighborhood");

	if(getSearchCookie("city") == "")
	{
		defCity = defCity.replace('%20',' ');
		setSearchCookie("city",defCity);
		setSearchCookie("state",defState);
		setSearchCookie("lat",defLat);
		setSearchCookie("lng",defLng);
	}

	if(getSearchCookie("mlsno") && getSearchCookie("mlsno") != "")
		setSearchCookie("mlsno","");

	flgPoly = true;	
	if(flgPoly)
	{
		if(getSearchCookie("lat") && getSearchCookie("lat") != "")
		{
			//DO NOTHING
		}
		else if(getCookie("latLongCk") && getCookie("latLongCk") != "")
		{
			var mainLatLng = eval(getCookie("latLongCk"))[0];
			if(mainLatLng.lat == "")
				setSearchCookie("lat",defLat);
			else
				setSearchCookie("lat",mainLatLng.lat);

			if(mainLatLng.lng == "")
				setSearchCookie("lng",defLng);
			else
				setSearchCookie("lng",mainLatLng.lng);
		}
		else
			setSearchCookie("lat",defLat);

		if(getSearchCookie("lng") && getSearchCookie("lng") != "")
		{
			//DO NOTHING
		}
		else
			setSearchCookie("lng",defLng);
			
		setSearchCookie("searchAddress","");
		var url = "";
        if(typeof(mapToShow) != "undefined" && mapToShow == "")
			url='/app/listing/singlePropertyLanding.php?status=EXP&address=,'+getSearchCookie("city")+','+getSearchCookie("state")+','+getSearchCookie("zip")+',,,,'+getSearchCookie("lat")+','+getSearchCookie("lng")+'&widgetnames=';
		else
			url='/app/listing/singlePropertyLanding.php?status=N&code=propView=1:::searchAddress='+getSearchCookie("searchAddress")+':::city='+getSearchCookie("city")+':::state='+getSearchCookie("state")+':::zip='+getSearchCookie("zip")+':::neighborhood=:::county=:::minPrice=:::maxPrice=:::searchBeds=:::searchBaths=&mapCenter=('+getSearchCookie("lat")+','+getSearchCookie("lng")+')&valChkMapSearchSelect=1&fe=&f=1&propLatitude='+getSearchCookie("lat")+'&propLongitude='+getSearchCookie("lng")+'&clrbitz=1&mapZoom=13';
  		 
		 var qs = new Querystring();
		 var ct = getSearchCookie("city");
 		 var st = getSearchCookie("state");
		 if(typeof(agentSiteRendering) != 'undefined' && agentSiteRendering == true)
			 url += "&frm=agt&aid="+agentId;

	
		goToMap = true;
		//ClrQckSrchCookies(); commented by dhaval
		
		setSearchCookie("city",ct);
		setSearchCookie("state",st);
		
		location.href=url;
	}
}

function getApiData(map2, city, state, nhood, lat, lng, aid)
{	
	if(typeof(aid) == "undefined")
		aid = "";
	if($("apiLoading")) $("apiLoading").show();
	if(city == null || city == 'undefined') {
		city = '';
		state = '';
	}
	else if(nhood == null || nhood == 'undefined') {
		nhood = '';
	}

	if (map2 != null && typeof(map2) != 'undefined')
	{
		glatlng = map2.getCenter();

		minx = glatlng.lng()-0.05;
		miny = glatlng.lat()-0.05;
		maxx = glatlng.lng()+0.05;
		maxy = glatlng.lat()+0.05;

		lat = glatlng.lat();
		lng = glatlng.lng();
	}
	else if (typeof(lat) != 'undefined' && typeof(lng) != 'undefined')
	{
		minx = lng-0.05;
		miny = lat-0.05;
		maxx = lng+0.05;
		maxy = lat+0.05;
	}
	else
	{
		minx = 0;
		miny = 0;
		maxx = 0;
		maxy = 0;

		lat = 0;
		lng = 0;
	}

    var url = "/getApiData.php?lat="+lat+"&lng="+lng+'&minx='+minx+'&miny='+miny+'&maxx='+maxx+'&maxy='+maxy + '&city=' + city + '&state=' + state + '&nhood=' + nhood + '&aid=' + aid;
    if($("schoolratingsdiv")) $("schoolratingsdiv").innerHTML = '';
    if($("areaphotosdiv")) $("areaphotosdiv").innerHTML = '';


	new Ajax.Request(url,{onCreate: function()
		{
			if($("apiLoading")) $("apiLoading").show();
		},method:"get",
		onComplete: function(){
			if($("apiLoading")) $("apiLoading").hide();
		},
		onSuccess:function(r) {
			if($("apiDiv")) $("apiDiv").show();
			apiresp = r.responseText.evalJSON(true);
            if($("schoolratingsdiv"))  $("schoolratingsdiv").innerHTML = apiresp.schools;
            if($("areaphotosdiv"))  $("areaphotosdiv").innerHTML = apiresp.areaphotos;
	}});
}

function doGeoCode(csz,addr)
{
	var url = "/classes/getCSZ.php";
	var qs = "csz="+trim(csz)+"&address="+addr;	
    var err = false;            
    var retArray = new $H();

	ajaxRequest(url,qs,function(r)
	{      
		var ge_response = eval('(' + trim(r.responseText) + ')');
		if(ge_response[0].status == "0")
		{			
			retArray['addr'] = ge_response[0].address;
			retArray['city'] = ge_response[0].city;
			retArray['state'] = ge_response[0].state;
			retArray['zip'] = ge_response[0].zip;
			retArray['lat'] = ge_response[0].latitude;
			retArray['lng']= ge_response[0].longitude;
			var latLongStr = "[{'lat':'"+retArray['lat']+"','lng':'"+retArray['lng']+"'}]";
			var now = new Date();
			now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
			setCookie("latLongCk",latLongStr,now);	
		}
		else
		{			
			if(addr != "")
				alert("Sorry, We couldn't find a location for '"+ addr+ " " +csz+"'");			
			else
				alert("Sorry, We couldn't find a location for '"+csz+"'");
                        err = true; 
		}               
	},false);
	 
	 if(err)               
		  return false;
	  else 
		return retArray;
}

/*Function for cameraview-for powersearch*/
function setHeroDiv(imgIndex,pics,link,divId)
{
	if($("propHeroDiv")==null || $("propHeroDiv")=="undefined")
	{
		var propHeroDiv = document.createElement("div");
		propHeroDiv.id = "propHeroDiv";
		document.body.appendChild(propHeroDiv);

	}

	
	$("propHeroDiv").setStyle({position:'absolute',zIndex:'4',display:'none',backgroundImage:'url(/vendor/rolodex/Images/heroFrame.png)',backgroundRepeat:'no-repeat',height:'205px',width:'270px'});
	if($(divId))
	{
		var top = getPositionTop(divId);
		var left = getPositionLeft(divId);
		//alert(top + " == "+ left);
		$("propHeroDiv").style.top =  top+"px";
		if(divId == 'mapDiv')
		{
			$("propHeroDiv").style.left = (left)+"px";
		}
		else	
		{
			$("propHeroDiv").style.left = (left+100)+"px";
		}
	}
	else
	{
		$("propHeroDiv").style.top =  ((screen.height/2)-100)+"px";
		$("propHeroDiv").style.left = ((screen.width/2)-300)+"px";
	}
	var strPics = unescape(pics);
	var picArr = strPics.split(",");
	var htmlStr = new StringBuffer();

	if(picArr ==  "" || (picArr.length == 1 && picArr[0].include("/images/listing/noImageThmb.jpg"))) //please do not remove this condition added by abhishek
	{
		var image = "http://"+window.location.hostname+"/wt/"+bkTheme+"/images/listing/noImageThmbBig.jpg";
		htmlStr.append('<img src="'+image+'" height="185" width="250" style="position:absolute;top:10px;left:10px"/>');
		htmlStr.append('<div class="imgPointer" onclick="hideHeroDiv();" style="background-image:url(\'/vendor/rolodex/Images/savedDelBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:240px;top:12px;width:20px;height:20px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/savedDelBtn.png\', sizingMethod=\'scale\');"/></div>');
		htmlStr.append('<a id="roloDetailImg" style="background-image:url(\'/vendor/rolodex/Images/roloInfoBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:96px;top:177px;width:75px;height:19px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloInfoBtn.png\', sizingMethod=\'scale\');" href="'+link+'" target="_blank"></a>');
	}
	else if(imgIndex == 0)
	{
		if(imgIndex == (picArr.length-1))
		{	
			var image = picArr[imgIndex];
			htmlStr.append('<img width="250" height="185" src="'+image+'" style="position:absolute;top:10px;left:10px"/>');
			htmlStr.append('<div class="imgPointer" onclick="javascript:alert(\'No additional photos are available for this property\');" style="background-image:url(\'/vendor/rolodex/Images/roloLtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:20px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloLtBtn.png\', sizingMethod=\'scale\');"	/></div>');
			htmlStr.append('<div class="imgPointer" onclick="javascript:alert(\'No additional photos are available for this property\');" style="background-image:url(\'/vendor/rolodex/Images/roloRtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;right:18px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloRtBtn.png\', sizingMethod=\'scale\');"/></div>');
			htmlStr.append('<div class="imgPointer" onclick="hideHeroDiv();" style="background-image:url(\'/vendor/rolodex/Images/savedDelBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:240px;top:12px;width:20px;height:20px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/savedDelBtn.png\', sizingMethod=\'scale\');"/></div>');	
			htmlStr.append('<a id="roloDetailImg" style="background-image:url(\'/vendor/rolodex/Images/roloInfoBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:96px;top:177px;width:75px;height:19px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloInfoBtn.png\', sizingMethod=\'scale\');" href="'+link+'" target="_blank"></a>');
		}
		else
		{
			var image = picArr[0];
			htmlStr.append('<img width="250" height="185" src="'+image+'" style="position:absolute;top:10px;left:10px"/>');
			htmlStr.append('<div class="imgPointer" onclick="setHeroDiv('+(picArr.length-1)+',\''+pics+'\',\''+link+'\',\''+divId+'\')" style="background-image:url(\'/vendor/rolodex/Images/roloLtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:20px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloLtBtn.png\', sizingMethod=\'scale\');"	/></div>');
			htmlStr.append('<div class="imgPointer" onclick="setHeroDiv('+(imgIndex+1)+',\''+pics+'\',\''+link+'\',\''+divId+'\')" style="background-image:url(\'/vendor/rolodex/Images/roloRtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;right:18px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloRtBtn.png\', sizingMethod=\'scale\');"/></div>');
			htmlStr.append('<div class="imgPointer" onclick="hideHeroDiv();" style="background-image:url(\'/vendor/rolodex/Images/savedDelBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:240px;top:12px;width:20px;height:20px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/savedDelBtn.png\', sizingMethod=\'scale\');"/></div>');
			htmlStr.append('<a id="roloDetailImg" style="background-image:url(\'/vendor/rolodex/Images/roloInfoBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:96px;top:177px;width:75px;height:19px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloInfoBtn.png\', sizingMethod=\'scale\');" href="'+link+'" target="_blank"></a>');
		}
	}
	else if(imgIndex == (picArr.length-1))
	{
		var image = picArr[imgIndex];
		htmlStr.append('<img width="250" height="185" src="'+image+'" style="position:absolute;top:10px;left:10px"/>');
		htmlStr.append('<div class="imgPointer" onclick="setHeroDiv('+(imgIndex-1)+',\''+pics+'\',\''+link+'\',\''+divId+'\')" style="background-image:url(\'/vendor/rolodex/Images/roloLtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:20px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloLtBtn.png\', sizingMethod=\'scale\');"	/></div>');
		htmlStr.append('<div class="imgPointer" onclick="setHeroDiv(0,\''+pics+'\',\''+link+'\',\''+divId+'\')" style="background-image:url(\'/vendor/rolodex/Images/roloRtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;right:18px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloRtBtn.png\', sizingMethod=\'scale\');"/></div>');
		htmlStr.append('<div class="imgPointer" onclick="hideHeroDiv();" style="background-image:url(\'/vendor/rolodex/Images/savedDelBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:240px;top:12px;width:20px;height:20px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/savedDelBtn.png\', sizingMethod=\'scale\');"/></div>');	
		htmlStr.append('<a id="roloDetailImg" style="background-image:url(\'/vendor/rolodex/Images/roloInfoBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:96px;top:177px;width:75px;height:19px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloInfoBtn.png\', sizingMethod=\'scale\');" href="'+link+'" target="_blank"></a>');
	}
	else
	{
		var image = picArr[imgIndex];
		htmlStr.append('<img width="250" height="185" src="'+image+'" style="position:absolute;top:10px;left:10px"/>');
		htmlStr.append('<div class="imgPointer" onclick="setHeroDiv('+(imgIndex-1)+',\''+pics+'\',\''+link+'\',\''+divId+'\')" style="background-image:url(\'/vendor/rolodex/Images/roloLtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:20px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloLtBtn.png\', sizingMethod=\'scale\');"	/></div>');
		htmlStr.append('<div class="imgPointer" onclick="setHeroDiv('+(imgIndex+1)+',\''+pics+'\',\''+link+'\',\''+divId+'\')" style="background-image:url(\'/vendor/rolodex/Images/roloRtBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;right:18px;top:172px;width:30px;height:30px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloRtBtn.png\', sizingMethod=\'scale\');"/></div>');
		htmlStr.append('<div class="imgPointer" onclick="hideHeroDiv();" style="background-image:url(\'/vendor/rolodex/Images/savedDelBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:240px;top:12px;width:20px;height:20px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/savedDelBtn.png\', sizingMethod=\'scale\');"/></div>');
		htmlStr.append('<a id="roloDetailImg" style="background-image:url(\'/vendor/rolodex/Images/roloInfoBtn.png\');background-repeat:no-repeat;*background-image:none;cursor:pointer;*cursor:hand;position:absolute;left:96px;top:177px;width:75px;height:19px;z-index:11;*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/vendor/rolodex/Images/roloInfoBtn.png\', sizingMethod=\'scale\');" href="'+link+'" target="_blank"></a>');
	}
	$("propHeroDiv").style.display="";
	$("propHeroDiv").innerHTML = htmlStr.toString();
}

function hideHeroDiv()
{
	if($("propHeroDiv")) $("propHeroDiv").style.display="none";
}

function getSearchCriteriaString()
{
	var searchCrtStr = '';
	if(trim(getSearchCookie('searchCriteria')) != "")
	{
		var searchCriteriaStr = trim(getSearchCookie('searchCriteria'));
		switch(searchCriteriaStr)
		{
			case 'brokeropenHome':
					searchCriteriaStr = "broker open home";
					break;	
			case 'officeListing':
					searchCriteriaStr = "office listing";
					break;		
		}
		searchCrtStr += "Only " + searchCriteriaStr +" properties having ";
	}
	else
		searchCrtStr += "Having ";
	
	if(trim(getSearchCookie('area')) != "" && trim(getSearchCookie('subNhood')) == "")
		searchCrtStr += "area surrounded by "

	if(trim(getSearchCookie('city')) != "")
		searchCrtStr += trim(getSearchCookie('city')) +", "+trim(getSearchCookie('state'));
	if(trim(getSearchCookie('zip')) != "")
		searchCrtStr += " " + trim(getSearchCookie('zip'));
		
	if(trim(getSearchCookie('neighborhood')) != "" )
	{
		if(trim(searchCrtStr) != "") searchCrtStr += " ";
		searchCrtStr += "neighborhood: " + trim(getSearchCookie('neighborhood'));
	}
		
	if(trim(getSearchCookie('subNhood')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += " ";
		searchCrtStr += "sub-neighborhood: " + trim(getSearchCookie('subNhood'));
	}
	
	if(trim(getSearchCookie('address')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "address: " + trim(unescape(getSearchCookie('address').replace(/\|/g, ',')));
	}
	
	if(trim(getSearchCookie('minPrice')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "minimum price: " + trim(getSearchCookie('minPrice'));
	}
	if(trim(getSearchCookie('maxPrice')) != "")
		searchCrtStr += " and maximum price: " + trim(getSearchCookie('maxPrice'));

	if(trim(getSearchCookie('searchBeds')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "beds: " + trim(getSearchCookie('searchBeds'))+"+";
	}

	if(trim(getSearchCookie('searchBaths')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "baths: " + trim(getSearchCookie('searchBaths'))+"+";
	}

	if(trim(getSearchCookie('searchType')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		if(trim(getSearchCookie('searchTypeText')))
			searchCrtStr += "property type: " + trim(getSearchCookie('searchTypeText'));
		else
			searchCrtStr += "property type: Any " ;

	}
	
	if(trim(getSearchCookie('minPSize')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "minimum sqft: " + trim(getSearchCookie('minPSize'));
	}
	if(trim(getSearchCookie('maxPSize')) != "")
		searchCrtStr += " and maximum sqft: " + trim(getSearchCookie('maxPSize'));
	
	if(trim(getSearchCookie('mlsno')) != "")
	{		
		searchCrtStr = "Having "
		searchCrtStr += "mls no: " + trim(getSearchCookie('mlsno').replace(/\,/g,", "));
		return trim(searchCrtStr);
	}
	if(trim(getSearchCookie('keywordSrch')) != "")
	{
		searchCrtStr += ", Keyword having " + trim(getSearchCookie('keywordSrch'));
		return trim(searchCrtStr);
	}
	
	//GETTING TEMPLATE SEARCH CRITERIA
	if(typeof(getTplSearchCriteria) == "function")
	{
		var searchCrtStr1 = getTplSearchCriteria();
		if(trim(searchCrtStr1) != "") searchCrtStr += ", ";
		searchCrtStr += searchCrtStr1;
	}

	return trim(searchCrtStr);
}

function getSearchCriteriaStringForEmail()
{
	var searchCrtStr = '';
	if(trim(getSearchCookie('searchCriteria')) != "")
	{
		var searchCriteriaStr = trim(getSearchCookie('searchCriteria'));
		switch(searchCriteriaStr)
		{
			case 'brokeropenHome':
					searchCriteriaStr = "broker open home";
					break;	
			case 'officeListing':
					searchCriteriaStr = "office listing";
					break;		
		}
		searchCrtStr += "Only " + searchCriteriaStr +" properties having ";
	}
	else
		searchCrtStr += "";
	
	if(trim(getSearchCookie('area')) != "" && trim(getSearchCookie('subNhood')) == "")
		searchCrtStr += "Area surrounded by "

	if(trim(getSearchCookie('city')) != "")
		searchCrtStr += " City: " + trim(getSearchCookie('city')) +", State: "+trim(getSearchCookie('state'));
	if(trim(getSearchCookie('zip')) != "")
		searchCrtStr += ", Zip: " + trim(getSearchCookie('zip'));
		
	if(trim(getSearchCookie('neighborhood')) != "" )
	{
		if(trim(searchCrtStr) != "") searchCrtStr += " ";
		searchCrtStr += "Neighborhood: " + trim(getSearchCookie('neighborhood'));
	}
		
	if(trim(getSearchCookie('subNhood')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += " ";
		searchCrtStr += "Sub-neighborhood: " + trim(getSearchCookie('subNhood'));
	}
	
	if(trim(getSearchCookie('address')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "Address: " + trim(unescape(getSearchCookie('address').replace(/\|/g, ',')));
	}
	
	if(trim(getSearchCookie('minPrice')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "Minimum price: " + trim(getSearchCookie('minPrice'));
	}
	if(trim(getSearchCookie('maxPrice')) != "")
		searchCrtStr += " and Maximum price: " + trim(getSearchCookie('maxPrice'));

	if(trim(getSearchCookie('searchBeds')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "Bedroom(s): " + trim(getSearchCookie('searchBeds'))+"+";
	}

	if(trim(getSearchCookie('searchBaths')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "Bathroom(s): " + trim(getSearchCookie('searchBaths'))+"+";
	}

	if(trim(getSearchCookie('searchType')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		if(trim(getSearchCookie('searchTypeText')))
			searchCrtStr += "Property type: " + trim(getSearchCookie('searchTypeText'));
		else
			searchCrtStr += "Property type: Any " ;

	}
	
	if(trim(getSearchCookie('minPSize')) != "")
	{
		if(trim(searchCrtStr) != "") searchCrtStr += ", ";
		searchCrtStr += "Minimum sqft: " + trim(getSearchCookie('minPSize'));
	}
	if(trim(getSearchCookie('maxPSize')) != "")
		searchCrtStr += " and Maximum sqft: " + trim(getSearchCookie('maxPSize'));
	
	if(trim(getSearchCookie('mlsno')) != "")
	{		
		searchCrtStr = "Having "
		searchCrtStr += "mls no: " + trim(getSearchCookie('mlsno').replace(/\,/g,", "));
		return trim(searchCrtStr);
	}
	if(trim(getSearchCookie('keywordSrch')) != "")
	{
		searchCrtStr += ", Keyword having " + trim(getSearchCookie('keywordSrch'));
		return trim(searchCrtStr);
	}

	return trim(searchCrtStr);
}


/*userReg.js*/

var imgThmPath = "/wt/"+bkTheme+"/images/";
var flag;
var memberType = 'buyer';
var inviteId;
var from;
var regButtonFocus=false;

function entRegSub(event,id) 
{
	if (!regButtonFocus)
	{
		if (event && event.keyCode == 13)
		{
			if(id=="frmReg"){}
				//chkAvailable(0,'UR');
		}
	}	
	return false;		
}

function selectMember(mType,brokerid)
{
	memberType=mType;
	if (mType=='buyer')
	{
			memberType="buyer";
			brokerId = brokerid;
			$('title0').innerHTML="";
	}
	if (mType=='seller')
	{
			memberType="seller";
			brokerId = brokerid;
			$('title0').innerHTML="";
	}
	if (mType=='agent')
	{
			memberType="agent";
			$('title0').innerHTML="";
			brokerId = brokerid;			
	}

	if (mType=='broker')
	{
			memberType="broker";
			$('title0').innerHTML="Broker Membership Registration";
	}
}

function clientTimeZone()
{
	var d = new Date()
	var min=(d.getTimezoneOffset()/60)*(-1);
	var stringMin=''+min;
	if(stringMin.search(/\./)<0)
	{
		if(stringMin.search(/\-/)<0)
		{
			tz="+"+stringMin+":00";
		}
		else
		{
			tz=stringMin+":00";
		}		
	}
	else
	{
		tzArr=stringMin.split(".");
		
		if(tzArr[1].length>1)
		{
			mn=60*(parseFloat(tzArr[1])/100);
		}
		else
		{
			mn=60*(parseFloat(tzArr[1])/10);
		}
		
		if(stringMin.search(/\-/)<0)
		{
			tz="+"+tzArr[0]+":"+mn;
		}
		else
		{
			tz=tzArr[0]+":"+mn;
		}		
	}
	if(tz=="-5:00" || tz=="-6:00" || tz=="-7:00" || tz=="-8:00" || tz=="-10:00")
		$('timesel').value=tz;
	else
		$('timesel').value="-10:00";
}

function setChkBtn()
{
	$('divChkAvailable').innerHTML='<button id="btnNext" class="loginBtn" name="btnNext" type="button" onclick="chkAvailable(1);">Check Availability</button>';
}

function chkAvailable(f,frm) 
{
	$('fname').className="textbox";

	chkU=($F('email1').substring(0,5));
	chkID=($F('email1').substring(5,$F('email1').length));
	
	if(trim($F('fname')) == '')
	{
		$('msgbox1').innerHTML="Please enter name";
		$('fname').className="textboxRed";
		$('fname').focus();
		return false;
	}

	
	if(chkU=='guest')
	{
		if ((chkID.match(/[0-5][0-9][0-9][0-9]/)==chkID) && (chkID<5001))
		{
			$('divChkAvailable').innerHTML="<font color='red'>User already exists, please try again.</font>";
			$('email1').className="textbox";
			$('password1').className="textbox";
			$('password2').className="textbox";
			$('fname').className="textbox";			
			return false;
		}
	}
		
	if(!isBlank('email1','e-mail address'))
	{
		$('msgbox1').innerHTML=alertErrorMsg;
		$('email1').className="textboxRed";
		$('email1').focus();
		return false;
	}
	else
	{
		if (!emailIsValid('email1'))
		{
			$('msgbox1').innerHTML=alertErrorMsg;
			$('email1').className="textboxRed";
			$('email1').focus();
			return false;
		}
		else
		{
			from=frm;
			var url = '/app/user/checklogin.php';
			var queryString = "loginId=" + $F('email1');
			flag=f;
			$('regDiv').style.display="none";
			$('msgbox').innerHTML='Processing! Please wait <img alt="Registration" src="' + imgThmPath + '/common/loaderLogin.gif" />';
			ajaxRequest(url,queryString,usrMyCallBack);
		}
	}
}

function usrMyCallBack(originalRequest)
{
	var checkLog=originalRequest.responseText;
	$('msgbox').innerHTML = "";
	$('msgbox1').innerHTML = "";
	$('regDiv').style.display="block";
	$('email1').className="textbox";
	$('password1').className="textbox";
	$('password2').className="textbox";
	$('fname').className="textbox";
	$('phoneNumber').className="textbox";
	if(checkLog!=0)
	{	
		$('msgbox1').innerHTML="<font color='red'>User already exists, please try again.</font>";
		$('email1').className="textboxRed";
		$('email1').value="";
		$('password1').value="";
		$('password2').value="";
		$('fname').value="";
		clientTimeZone();
	}
	else
	{
		if (flag==0)
		{
			submitRegister();	
		}
		else if(flag==1)
		{
			$('divChkAvailable').innerHTML="<font color='green' class='clrChkAvailable'>You Got It!</font>";
		}
	}	
}

function validateForm()
{
	$('fname').className="textbox";
	$('email1').className="textbox";
	$('password1').className="textbox";
	$('password2').className="textbox";
	$('fname').className="textbox";	
	$('phoneNumber').className="textbox";
	$('msgbox1').innerHTML  = "";
	
	if(trim($F('fname')) == '')
	{
		$('msgbox1').innerHTML="Please specify valid name";
		$('fname').className="textboxRed";
		$('fname').focus();
		return false;
	}
	else if (!emailIsValid('email1'))
	{
		$('msgbox1').innerHTML=alertErrorMsg;
		$('email1').className="textboxRed";
		return false;
	}
	else if(trim($F('phoneNumber')) == '' || !phoneIsValid('phoneNumber'))
	{
		$('msgbox1').innerHTML="Please enter valid phone number like 306-954-2548";			
		$('phoneNumber').className="textboxRed";
		return false;
	}
	else if (!passwordIsValid('password1','password2',5,15))
	{
		$('msgbox1').innerHTML=alertErrorMsg;
		$('password1').value="";
		$('password2').value="";
		$('password1').className="textboxRed";
		$('password2').className="textboxRed";
		$('password1').focus();
		return false;
	}		
	else if($("yes"))
	{
		if($("yes").checked == true && ($("agentName").value == "" || $("agentName").value == "0"))
		{
			$('msgbox1').innerHTML="Please Enter Agent Name";			
			return false;
		}

	}
	return true;
}

function submitRegister() 
{
	if ( $('tdLoginHeader'))
		$('tdLoginHeader').style.paddingLeft = '5px';

	if ( $('txtLoginHeader'))
		$('txtLoginHeader').style.display = 'none';

	$('regDiv').style.display="none";
	$('msgbox').innerHTML = 'Processing! Please wait <img alt="Registration" src="' + imgThmPath + '/common/loaderLogin.gif" />';
	var myPageUrl="";

	if(myPage != "") myPage = myPage;

	if (validateForm())
    {		
    	if(myPage != "" && typeof(myPage) != 'undefined')
			myPageUrl = '&fromPage='+myPage;
		
    	var theQuery = "email1="+ $F('email1');
    	theQuery = theQuery + "&password="+ escape($F('password1'));
		theQuery = theQuery + "&eoa=B";
		theQuery = theQuery + "&fname="+ $F('fname');		
		if(memberType=='buyer' || memberType=='' || memberType=='undefined')
		{
			theQuery = theQuery + "&eua=B"+"&BKID="+brokerId;
		}		
		if(memberType=='seller')
		{
			theQuery = theQuery + "&eua=Sl"+"&BKID="+brokerId;
		}		
		if(memberType=='agent')
		{
		   	theQuery = theQuery + "&eua=A"+"&BKID="+brokerId+"&inviteId="+inviteId;
		}	
		var objQS = new Querystring();	
		var agentId = objQS.get('agd');
		if(agentId == null || agentId == "" || agentId == "0" ) { agentId = objQS.get('aid'); }
		if( (agentId) && (agentId != null ) )
		{
			theQuery = theQuery + "&agid="+ trim(agentId);
		}
		else if(typeof(fromSiteFlg) != "undefined" && fromSiteFlg == "agentsite" && typeof(aid) != "undefined" && aid != "")
		{
			agentId = aid;
			theQuery = theQuery + "&agid="+ trim(aid);
		}
		else if( typeof(agtHomeSite) != "undefined" && agtHomeSite == "1" && agent_userId != "")
		{
			agentId = agent_userId;
			theQuery = theQuery + "&agid="+ trim(agent_userId);
		}
		else if(typeof(aid) != "undefined" && aid != "")
		{
			agentId =  aid;
			theQuery = theQuery + "&agid="+ trim(aid);
		}
		else
		{
			theQuery = theQuery + "&agid=0";
		}
		var frm = objQS.get('frm');		
		theQuery = theQuery + "&phoneNumber="+ $F('phoneNumber')+myPageUrl;
		//working with agent checkbox
		if($("yes").checked)	
		{
			//changes done when ATP ask for agents should b shown in dropdown...Jahnvi
			var agentArr = $('agentName').value.split("=^^=");
			theQuery = theQuery + "&agentName="+ escape(agentArr[0])+"&wagtid="+agentArr[1];
		}
		if(typeof(ref_url) != 'undefined' && typeof(ref_url) != null)
		{
			if(ref_url.indexOf('/Search') != -1)
			{
				theQuery = theQuery + "&serCrt="+escape(encodeURI(getSearchCriteriaStringForEmail()));
			}
		}
		theQuery = theQuery + "&comments="+escape(encodeURI(trim($F('txtComments'))));
		var url = '/app/user/userAdd.php';
		ajaxRequest(url,theQuery,userAdd);
	}
	else
	{
		$('regDiv').style.display="block";
		$('msgbox').innerHTML = "";
	}
}

function userAdd(originalRequest)
{
	var checkLog=trim(originalRequest.responseText);
	if(from!="UR")
	{
		var checkLog=originalRequest.responseText;
		if(checkLog=="SU")
		{
			var url = '/app/auth/validateLogin.php';
			var queryString = "usid=" + $F('email1') + "&pass=" + escape($F('password1'))+"&from="+from;
			ajaxRequest(url,queryString,login);
		}
		else
		{
			_alert("User Not Registered, please try again!");
			$('regDiv').style.display="block";
			$('msgbox').innerHTML = "";
		}
	}
	else
	{
		var checkLog=trim(originalRequest.responseText);
		var agentLogin="";

		if(checkLog.indexOf("=^^=") != -1)
		{
			//Call For Agentsite user only
			var response  = checkLog.split("=^^=");
			checkLog = response[0];
			agentLogin = response[1];
		}
		if(trim(checkLog)=="SU")
		{
			var objQs=new Querystring();
			var agtid=objQs.get('agd');	
			var frm = objQs.get('frm');
			if ((agtid) && (agtid != null ))
			{				
				//case if regstration from agentsite
				if(typeof(ref_url) != 'undefined')
					location.href = ref_url;
				else
					location.href='/app/user/congratulations.php?setHeader=null&frm=agt&aid='+agtid;
			}
			else
			{
				if(typeof(ref_url) != 'undefined')
					location.href = ref_url;
				else
					location.href='/app/user/congratulations.php?setHeader=null';
			}
			$A(document.getElementsByTagName("input")).each(function(node){node.value="";node.className="textbox"});
			setChkBtn();
			$("msgbox1").innerHTML = "";
		}
		else
		{
			_alert("User Not Registered, please try again!");
			$('regDiv').style.display="block";
			$('msgbox').innerHTML = "";
		}
	}
}

/*signIn.js*/

/* function handling the user login process*/
var signInButtonFocus=false;
var passCheck=true;
var loginCheck=true;
var myPage="";
var myref = '';
function rememberIdPassword(uname,password)
{
	strCookie = uname+";"+password;
	var now = new Date();
	now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
	if($("chkRemember").checked == true)
	{
		setCookie("remConsIdPwd",strCookie,now);
	}
	else
	{
		setCookie("remConsIdPwd","");
	}
}

function chkCookieRemember()
{
	var strck = "";
	strck = getCookie("remConsIdPwd");
	if(strck=="" || strck==null )
	{}
	else
	{
		var strcksplit = strck.split(";");
		$("usrName").value = strcksplit[0];
		$("usrPwd").value = strcksplit[1];
		$("chkRemember").checked = true
	}
}
function entSub(event,id,fromPage) 
{
	if (!signInButtonFocus)
	{
		if (event && event.keyCode == 13)
		{
			if(id=="frmLogin")
				validateUserLogin('UR',fromPage);
			else if(id=="frmFgtLogin")
				submitForget();
			else if(id=="frmFgtLoginV")
				submitForgetVendor();
			else if ( id == "frmLoginNewNew" )
				validateLoginForNewWidget ();
		
		}
	}	
	return false;		
}

function validateUserLogin(from,fromPage)
{
	myPage=fromPage;
	if($('optCLogin') && $('optCLogin').checked == true)
		var lStatus  = 	'C';
	else
		var lStatus = 'L';

	if(!isBlank('usrName',"e-mail address"))
	{
		$('failMsg1').innerHTML=alertErrorMsg;
		$('usrName').focus();
		$('usrName').className="textboxRed";
		$('usrPwd').className="textbox";
		return false;
	}

	if(!isBlank('usrPwd',"Password"))
	{
		$('failMsg1').innerHTML=alertErrorMsg;
		$('usrPwd').focus();
		$('usrName').className="textbox";
		$('usrPwd').className="textboxRed";
		return false;
	}

	var url = '/app/auth/validateLogin.php';
	var queryString = "usid=" + $F('usrName') + "&pass=" + escape($F('usrPwd'))+"&from="+from;

	queryString = queryString +"&status="+lStatus;
	if(location.pathname.search("vendor")!=-1)
		queryString = queryString +"&page=vendor";
	
	Element.toggle('signBtn');
	Element.toggle('signInDiv');	
	ajaxRequest(url,queryString,login);	
}

function login(originalRequest)
{	
	var uname = $F('usrName');
	var password = $F('usrPwd');
	if(trim(ref_url) != "")
		refral = ref_url;	
	if(originalRequest.responseText=="other")
	{
		location.href='/app/misc/newWidget.php?PHPSESSID='+sessid;
		return;
	}
	var checkLog=originalRequest.responseText;
	var arr=checkLog.split('|');	
	switch (arr[0])
	{
		case 'NR':
			$('failMsg1').innerHTML="E-mail and password did not match!";
			$('usrName').value="";
			$('usrPwd').value="";
			$('usrName').focus();
			$('usrName').className="textbox";
			$('usrPwd').className="textbox";
			Element.toggle('signInDiv');
			Element.toggle('signBtn');
		break;
		case 'NA':
			var objQs=new Querystring();
			var agtid=objQs.get('agd');

			if(myPage != "" && typeof(myPage) != 'undefined')
				myPage = '&fromPage='+myPage;
				
			if(agtid!=null && trim(agtid)!='')
			{
				//case if regstration from agentsite
				location.href='/app/auth/accountNotActivated.php?setHeader=null&uid='+arr[1]+'&frm=agt&aid='+agtid+myPage;
			}
			else
		    {
				location.href='/app/auth/accountNotActivated.php?setHeader=null&uid='+arr[1]+myPage;
			}			
		break;
		case 'FST':
			rememberIdPassword(uname,password);
			location.href='/app/auth/intermediateProfile.php?PHPSESSID='+sessid+'&page=login';
		break;
		case 'misc':
			rememberIdPassword(uname,password);
			location.href='/app/misc/newWidget.php??PHPSESSID='+sessid;
		break;
		case 'SP':
			rememberIdPassword(uname,password);
			location.href='../ajaxim/support.php?PHPSESSID='+sessid;
		break;		
		case 'SRCH':
			rememberIdPassword(uname,password);
			loginDlg.hide();
			var arr = chkCalledFrom.split(',');
			if (arr[0] == "addMyFavourite")
			{
				addMyFavourite(arr[1]);
			}
			else
			{
				addMyOpenHome(arr[1]);
			}
			ajaxRequest('./addMenuBar.php','type=searchResult',setMenuCallBack);
		break;
		case 'B':
			rememberIdPassword(uname,password);
			location.href=refral;
		break;
		case 'A':
			rememberIdPassword(uname,password);
			location.href=refral;
ak;
		case 'BK':
			rememberIdPassword(uname,password);
			location.href=refral;
		case 'FBDA':
			alert("Your account has been deactivated. Try again later.");
//			top.GB_hide();
			return;
		break;
	}
}

function validateLoginForNewWidget()
{
	if(!isBlank('usrName',"e-mail address"))
	{
		$('failMsg1').innerHTML=alertErrorMsg;
		$('usrName').focus();
		$('usrName').className="textboxRed";
		$('usrPwd').className="textbox";
		return false;
	}
	if(!isBlank('usrPwd',"Password"))
	{
		$('failMsg1').innerHTML=alertErrorMsg;
		$('usrPwd').focus();
		$('usrName').className="textbox";
		$('usrPwd').className="textboxRed";
		return false;
	}
	var url = '/app/auth/validateLogin.php';
	var queryString = "usid=" + $F('usrName') + "&pass=" + escape($F('usrPwd'));
	Element.toggle('signBtn');
	Element.toggle('signInDiv');

	ajaxRequest(url,queryString,newWindgetLogin);
}

function newWindgetLogin (originalRequest)
{
	var checkLog=originalRequest.responseText;
	var arr=checkLog.split('|');

	if ( arr[0] == 'NR' )
	{
		$('failMsg1').innerHTML="E-mail and password did not match!";
		$('usrName').value="";
		$('usrPwd').value="";
		$('usrName').focus();
		$('usrName').className="textbox";
		$('usrPwd').className="textbox";
		Element.toggle('signInDiv');
		Element.toggle('signBtn');
	}
	else
	{
		location.href='/app/misc/newWidget.php';
	}
}

function setMenuCallBack(originalRequest)
{
	var response = originalRequest.responseText;	
	$('divMenu').innerHTML=response;	
}

function sendNewEmail(uid,fromPage)
{
	var url = '/app/auth/sendNewEmail.php';
	var queryString = "uid=" +uid + "&fromPage=" + fromPage;
	ajaxRequest(url,queryString,mailCallBack);
}

function mailCallBack(originalRequest)
{
	var status=trim(originalRequest.responseText);

	if(status=="1")
	{
		_alert("Email has been sent to you.");
	}
	else
	{
		_alert("Not able to send you email now. Please try again later.");
	}
}

function continueProfile(role,statu)
{
	switch (statu)
	{
		case 'N':
			location.href='/app/user/userInformation.php?PHPSESSID='+sessid;
		break;
		case 'Y':
			switch(role)
			{
				case 'B':
					location.href='/index.php';
				break;
				case 'A':
					location.href='/app/dashboard/dashboard.php?PHPSESSID='+sessid;
				break;
				case 'BK':
					location.href='/app/dashboard/dashboard.php?PHPSESSID='+sessid;
				break;
			}
		break;
	}
}

function forgotPassword(switchLoginDiv)
{
	if(switchLoginDiv == 1)
	{
		$('divLogin').style.display = "none";
		$('fgetLink').style.display = 'none';
		$('divForget').style.display = 'block';
		$('fgetUserName').focus();
	}
	else
	{
		$('divForget').style.display = 'none';
		$('fgetLink').style.display = 'block';
		$('divLogin').style.display = "block";
		
		$('usrName').className="textbox";
		$('usrPwd').className="textbox";
		
		if($('usrName').value==""){
			$('usrName').focus();
		}
		else {
			$('usrPwd').focus();
		}
		
	}	
	$('failMsg2').innerHTML="";
	$('failMsg1').innerHTML="";
	$('fgetUserName').className="textbox";
	
	
}

function submitForgetVendor(from)
{
	if(!isBlank('fgetUserName',"e-mail address"))
	{
		$('failMsg2').innerHTML=alertErrorMsg;
		$('fgetUserName').focus();
		$('fgetUserName').className="textboxRed";
		return false;
	}
	var url = '/app/auth/resendLogin.php';
	var queryString = "usid=" + $F('fgetUserName') + "&from=vendor";
	$('fgetUserName').value="";
	$('usrName').value="";
	$('usrPwd').value="";
	if (from == 'landing')
		ajaxRequest(url,queryString,resendLanding);
	else
		ajaxRequest(url,queryString,resendLogin);
}

function submitForget(from)
{
	if(!isBlank('fgetUserName',"e-mail address"))
	{
		$('failMsg2').innerHTML=alertErrorMsg;
		$('fgetUserName').focus();
		$('fgetUserName').className="textboxRed";
		return false;
	}
	var url = '/app/auth/resendLogin.php';
	var queryString = "usid=" + $F('fgetUserName');
	$('fgetUserName').value="";
	$('usrName').value="";
	$('usrPwd').value="";
	if (from == 'landing')
		ajaxRequest(url,queryString,resendLanding);
	else
		ajaxRequest(url,queryString,resendLogin);
}

function resendLogin(originalRequest)
{
	var status=trim(originalRequest.responseText);
	$('failMsg2').innerHTML="";
	$('fgetUserName').className="textbox";
	switch(status)
	{
		case 'NR':
			_alert("You are not registered with the system!");
			
			$('usrName').className="textbox";
			$('usrPwd').className="textbox";
			
		break;		
		case 'SU':
			_alert("Email has been sent to you.");
		break;		
		default:
			_alert("Not able to send you email now. Please try again later.");	
	}
	$('divForget').style.display='none';
	$('divLogin').style.display='block';
	$('fgetLink').style.display = 'block';
	$('usrName').focus();
}

function resendLanding(originalRequest)
{
	var status=originalRequest.responseText;
	switch(status)
	{
		case 'NR':
			_alert("Yor are not registered with the system!Please Register and then Login");
		break;		
		case 'SU':
			_alert("Email has been sent to you.");
		break;		
		default:
			_alert("Not able to send you email now. Please try again later.");	
	}
	$('failMsg2').innerHTML="&nbsp;";
	$('fgetUserName').focus();
	$('fgetUserName').className="textbox";
}

function validateLoginForWidget()
{
	alert('for new code');
}

function capsDetect( e,id ) {
	if( !e ) { e = window.event; } if( !e ) { MWJ_say_Caps( false,e,id ); return; }
	//what (case sensitive in good browsers) key was pressed
	var theKey = e.which ? e.which : ( e.keyCode ? e.keyCode : ( e.charCode ? e.charCode : 0 ) );
	//was the shift key was pressed
	var theShift = e.shiftKey || ( e.modifiers && ( e.modifiers & 4 ) ); //bitWise AND
	//if upper case, check if shift is not pressed. if lower case, check if shift is pressed
	MWJ_say_Caps( ( theKey > 64 && theKey < 91 && !theShift ) || ( theKey > 96 && theKey < 123 && theShift ),e,id );
}
function MWJ_say_Caps( oC,e,id ) {
	if( typeof( capsError ) == 'string' ) { if( oC ) { alert( capsError ); } } else { capsError( oC,e,id ); }
}

function capsError( capsEngaged,event,id )
{
	if( capsEngaged )
	{
		createCapsDiv(event,id);
	}
	else
	{
		closeSticky(id);
		loginCheck=true;
		passCheck=true;
	}
}

function closeSticky(id)
{
	if($(id))
	{
		$(id).remove();
		if(id=="capsLoginDiv")
			loginCheck=false;
		else if(id=="capsPasswdDiv")
			passCheck=false;
	}
}

function createCapsDiv(evt,id)
{
	if($(id))
	{
		if(id=="capsLoginDiv")
		{
			$('capsLoginDiv').style.display="block";
			if($('capsPasswdDiv'))
			$('capsPasswdDiv').style.display="none";		
		}
		else if(id=="capsPasswdDiv")
		{
			if($('capsLoginDiv'))
				$('capsLoginDiv').style.display="none";
			$('capsPasswdDiv').style.display="block";		
		} 
		return;
	}
	myDiv=document.createElement('div');
	if(id=="capsLoginDiv" && loginCheck)
	{
		var divLeft = getPositionLeft("usrName");
		var divTop = getPositionTop("usrName");
		var leftPos = eval(divLeft+150);
		var topPos = divTop;
		myDiv.id=id;
		var toSet="<table width=\"275px\" border=\"0\"><tr><td class=\"helpTopLeft\"/><td class=\"helpTopCenter\" align=\"right\"/><td class=\"helpTopRight crsr\" title=\"Donot show this warning again!\" onclick=\"closeSticky('"+id+"');\"\"/></tr><tr><td class=\"helpMiddleLeft\"/><td class=\"widHelpInner\"><table width=\"100%\" height=\"100%\" style=\"font-size:1.2em\"><tr><td colspan=\"2\" class=\"stickyLabel\" align=\"center\"><span class=\"lang\"><u>Caps Lock Is On</u></span></td></tr><tr><td class=\"stickyLabel\">Having The Caps Lock on may cause you<br/>to enter your password incorrectly.</td></tr><tr><td>&nbsp;</td></tr><tr><td colspan=\"2\">You should press Caps Lock to turn it off<br />before entering your password.</td></tr></table></td><td class=\"helpMiddleRight\"/></tr><tr><td class=\"helpBottomLeft\"/><td class=\"helpBottomCenter\"></td><td class=\"helpBottomRight\"/></tr></table>";
		myDiv.style.height="80px";
		myDiv.style.width="200px";
		myDiv.style.zIndex="1000";
		myDiv.style.position="absolute";
		myDiv.style.left=leftPos+"px";
		myDiv.style.top=topPos+"px";
		$('divLogin').appendChild(myDiv);
		myDiv.innerHTML=toSet;
		if($("capsPasswdDiv"))
		{
			$('capsPasswdDiv').style.display="none";			
		}
			
	}
	else if(id=="capsPasswdDiv" && passCheck)
	{
		var divLeft = getPositionLeft("usrPwd");
		var divTop = getPositionTop("usrPwd");
		var leftPos = eval(divLeft+150);
		var topPos = divTop;
		myDiv.id=id;
		var toSet="<table width=\"275px\" border=\"0\"><tr><td class=\"helpTopLeft\"/><td class=\"helpTopCenter\" align=\"right\"/><td class=\"helpTopRight crsr\" title=\"Donot show this warning again!\" onclick=\"closeSticky('"+id+"');\"\"/></tr><tr><td class=\"helpMiddleLeft\"/><td class=\"widHelpInner\"><table width=\"100%\" height=\"100%\" style=\"font-size:1.2em\"><tr><td colspan=\"2\" class=\"stickyLabel\" align=\"center\"><span class=\"lang\"><u>Caps Lock Is On</u></span></td></tr><tr><td class=\"stickyLabel\">Having The Caps Lock on may cause you<br/>to enter your password incorrectly.</td></tr><tr><td>&nbsp;</td></tr><tr><td colspan=\"2\">You should press Caps Lock to turn it off<br />before entering your password.</td></tr></table></td><td class=\"helpMiddleRight\"/></tr><tr><td class=\"helpBottomLeft\"/><td class=\"helpBottomCenter\"></td><td class=\"helpBottomRight\"/></tr></table>";
		myDiv.style.height="80px";
		myDiv.style.width="200px";
		myDiv.style.zIndex="1000";
		myDiv.style.position="absolute";
		myDiv.style.left=leftPos+"px";
		myDiv.style.top=topPos+"px";
		$('divLogin').appendChild(myDiv);
		myDiv.innerHTML=toSet;
		if($("capsLoginDiv"))
		{
			$('capsLoginDiv').style.display="none";			
		}
	}	
}

function setCreateAccHeader()
{	
	var alertType = '';
	if(typeof(myPriceParmObj) != 'undefined' && typeof(myPriceParmObj.alertType) != 'undefined' && typeof(myPriceParmObj.alertType) != null)
		alertType = myPriceParmObj.alertType;
	if($('rowCreateAccTxt'))
	{
		if(myref == 'homeSaveLink')
			$('rowCreateAccTxt').innerHTML = 'To save this property, please create an account.';
		else if(myref == 'homeSHViewLink')
			$('rowCreateAccTxt').innerHTML = 'Please create an account to view details.';
		else if(myref == 'homeSavePSAlertLink')
			$('rowCreateAccTxt').innerHTML = 'To receive status alerts on this property, please create an account.';
		else if(myref == 'homeSaveEmailAlertLink' || alertType == 'marketReport')
			$('rowCreateAccTxt').innerHTML = 'To create an email alert, please create an account.';
		else
			$('rowCreateAccTxt').innerHTML = 'Please create an account to view details.';
	}

	if((typeof(fromSiteFlg) != "undefined" && fromSiteFlg == "agentsite" && typeof(aid) != "undefined" && aid != "") || ( typeof(frmAid) != "undefined" && frmAid != "") || ( typeof(agtHomeSite) != "undefined" && agtHomeSite == "1" && agent_userId != "") || (typeof(aid) != "undefined" && aid != ""))
	{
		$('rowWorkingAgt').hide();
	}
}
function showAgentNames()
{
	var optArr = document.getElementById('tblCreateAcc').getElementsByTagName("option");
	if($("yes").checked == true)
	{
		if(optArr.length ==0 )
		{
			var qs='';
			qs += "limit=all&showAgents=dropdown";
			var url = "/getAgents.php";
			ajaxRequest(url,qs,cbfngetAgents);
		}
		$("agentNameSelectBox").style.display=""; 
		$("agentNameLabel").style.display=""; 
	}
	else
	{
		$("agentNameSelectBox").style.display="none"; 
		$("agentNameLabel").style.display="none"; 
	}
}
function cbfngetAgents(resp)
{
	var response = resp.responseText;
	$("agentNameSelectBox").innerHTML = response;
}

function validateFBLogin(uid)
{	
	var url = '/app/auth/validateFBLogin.php';
	var queryString = "userid="+uid;	
	
	Element.toggle('signBtn');
	Element.toggle('signInDiv');	
	ajaxRequest(url,queryString,login);
}

/***** New Code for Signin Page..Chintan Shah... ******/
function showLoginTbl()
{
	document.getElementById('tblCreateAcc').style.display="none";
	document.getElementById('tblForgotPass').style.display="none";
	document.getElementById('tblLoginAcc').style.display="";
	document.getElementById('tblMarketReportSample').style.display="none";
	document.getElementById('tblEmailAlertSample').style.display="none";
	document.getElementById('tblHomeSiteSample').style.display="none";
	setTimeout(function () 
	{
		if($('txtLoginHeader') )
		{
			if ( $('tblLoginAcc').style.display != "none" )
				$('txtLoginHeader').focus(); 
		}
	},4000);
} 
function showCreareAccTbl()
{
	document.getElementById('tblCreateAcc').style.display="";
	document.getElementById('tblMarketReportSample').style.display="none";
	document.getElementById('tblEmailAlertSample').style.display="none";
	document.getElementById('tblHomeSiteSample').style.display="none";
	document.getElementById('tblLoginAcc').style.display="none";
	document.getElementById('tblForgotPass').style.display="none";
	if($('txtLoginHeader'))$('txtLoginHeader').focus();
}
function showForgotPassTbl()
{
	document.getElementById('tblCreateAcc').style.display="none";
	document.getElementById('tblLoginAcc').style.display="none";
	document.getElementById('tblForgotPass').style.display="";
	if($('txtLoginHeader'))$('txtLoginHeader').focus();
}	
function showEmailAlertSample()
{
	document.getElementById('tblCreateAcc').style.display="none";
	document.getElementById('tblEmailAlertSample').style.display="";
	document.getElementById('tblHomeSiteSample').style.display="none";
	document.getElementById('tblMarketReportSample').style.display="none";
	if($('txtLoginHeader'))$('txtLoginHeader').focus();
}
function showHomeSiteSample()
{
	document.getElementById('tblCreateAcc').style.display="none";
	document.getElementById('tblHomeSiteSample').style.display="";
	document.getElementById('tblEmailAlertSample').style.display="none";		
	document.getElementById('tblMarketReportSample').style.display="none";
	if($('txtLoginHeader'))$('txtLoginHeader').focus();
}
function showMarketReportSample()
{
	document.getElementById('tblCreateAcc').style.display="none";
	document.getElementById('tblMarketReportSample').style.display="";
	document.getElementById('tblEmailAlertSample').style.display="none";
	document.getElementById('tblHomeSiteSample').style.display="none";	
	if($('txtLoginHeader'))$('txtLoginHeader').focus();
}

function openLoginDiv()
{
	window.scrollTo(0,0);
	document.getElementById('light').style.display='block';
	document.getElementById('fade').style.display='block';
	//document.documentElement.style.overflow=document.body.style.overflow='hidden';
	document.documentElement.style.overflow = 'hidden';	 // firefox, chrome
	document.body.scroll = "no";	// ie only
}

function closeLoginDiv()
{
	clearAllEle();

	document.getElementById('tblCreateAcc').style.display="none";
	document.getElementById('tblMarketReportSample').style.display="none";
	document.getElementById('tblEmailAlertSample').style.display="none";
	document.getElementById('tblMarketReportSample').style.display="none";
	document.getElementById('tblLoginAcc').style.display="none";	

	document.getElementById('light').style.display='none';
	document.getElementById('fade').style.display='none';
	document.documentElement.style.overflowY = 'scroll';	 // firefox, chrome
	document.body.scroll = "yes";	// ie only
}

function clearAllEle()
{
	if ( document.getElementById('tblCreateAcc').style.display != 'none' )
	{
		document.getElementById('msgbox1').innerHTML = '';
		document.getElementById('fname').value = '';
		document.getElementById('fname').className = 'textbox';
		document.getElementById('email1').value = '';
		document.getElementById('email1').className = 'textbox';
		document.getElementById('phoneNumber').value = '';
		document.getElementById('phoneNumber').className = 'textbox';
		document.getElementById('password1').value = '';
		document.getElementById('password1').className = 'textbox';
		document.getElementById('password2').value = '';
		document.getElementById('password2').className = 'textbox';
		document.getElementById('txtComments').value = '';		
		document.getElementById('txtComments').className = 'textbox';
	}
	else if ( document.getElementById('tblLoginAcc').style.display != 'none' )
	{
		document.getElementById('failMsg1').innerHTML = '';
		document.getElementById('usrName').value = '';
		document.getElementById('usrName').className = 'textbox';
		document.getElementById('usrPwd').value = '';
		document.getElementById('usrPwd').className = 'textbox';
		document.getElementById('chkRemember').checked = false;
	}
	else if ( document.getElementById('tblForgotPass').style.display != 'none' )
	{
		document.getElementById('failMsg2').innerHTML = '';
		document.getElementById('fgetUserName').value = '';
		document.getElementById('fgetUserName').className = 'textbox';
	}
}

function opensignInRegDlg(ref,chkSignIn,op,fromPage)
{
	frompage = fromPage;

	if(typeof(fromPage) != "undefined" && fromPage != "")
		myPage = fromPage;
	else
		myPage = 'propSearch';

	if(typeof(op) == 'undefined') op = '';
	if(ref == '') { ref = '/index.php';}
	var flag = false;
	myref = ref_url = ref;	
	if(chkSignIn != "R" && chkSignInReqd == "1") flag = true;

	if( (uid == "" || uid == "0") && (chkSignIn == "R" || flag) )
	{
			if(ref_url == 'homeSHViewLink' || ref_url == 'homeSaveLink' || ref_url == 'homeSavePSAlertLink' || ref_url == 'homeSaveEmailAlertLink' || ref_url == 'aSavSearch' || ref_url == 'getEmlAlertOH')
			{
				var curPage = document.location.href;

				if(curPage.indexOf('?') != -1)
					ref_url = curPage+'&cf='+ref_url;			
				else
					ref_url = curPage+'?cf='+ref_url;

			}				
			openLoginDiv();
			if (op == 'login' )
				showLoginTbl();
			else
				showCreareAccTbl();
	}
	else
	{
		window.location.href = ref;
	}		
}
/***************************************************/


/*validation.js*/

var alertErrorMsg="";

function isYear(id)
{
	var dt = new Date();
	dt = dt.getFullYear();
	var yr = Number($(id).value);
	if(isNaN(yr))
	{
		alertErrorMsg = "Please Enter valid Year.";
		return false;
	}
	if(yr<1000 || yr>3000)
	{
		alertErrorMsg = "Please Enter valid Year.";
		return false;
	}
/*	if($(id).value.length != oflength)
	{
		alertErrorMsg = "Only "+oflength+" characters alllowed."
		return false;
	}*/
	return true;
}
function isSqft(id)
{
	var sqft = $(id).value;
	sqft = sqft.gsub(",","");
	if(isNaN(Number(sqft)))
	{
		alertErrorMsg = "Enter valid value.";
		return false;
	}
	return true;
}
function isOfLength(id,oflength,limit)
{
	if(limit==null)
	{
		if($(id).value.length != oflength)
		{
			alertErrorMsg = "Only "+oflength+" characters alllowed."
			return false;
		}
	}
	else
	if($(id).value.length > oflength)
	{
		alertErrorMsg = "Maximum "+oflength+" characters alllowed."
		return false;
	}
	return true;
}

function isOverMaxLength(id,maxlength)
{
	return $(id).value.length > maxlength;
}

function isUnderMinLength(id,minlength)
{
	return $(id).value.length < minlength;
}

function regExTest(id,expression)
{
	return $(id).value.match(expression) != null;
}

function isDecimal(val)
{
	var decimalRE = "^(\\+|-)?[0-9][0-9]*(\\.[0-9]*)?$";
	return val.match(decimalRE) != null;
}

function isNonDecimal(number)
{
	numRegExp = /^[0-9]+$/
  	return numRegExp.test(number);
}

function isNonNegDecimal(element)
{
	var nonnegdecimalRE = "^[0-9][0-9]*(\\.[0-9]*)?$";
	return regExTest(element,nonnegdecimalRE);
}

function isProperMoney(id)
{
	if($(id).value<=0)
		return null;
	var nonnegdecimalRE = "^[0-9][0-9]*(\\.[0-9]*)?$";
	var num=String(money2num($(id).value));
	return num.match(nonnegdecimalRE) != null;
	
}

function usernameIsValid(id,min,max)
{
	if (!isBlank(id,'Username')) 
	{
		return false;
	}
	if (isOverMaxLength(id,max) || isUnderMinLength(id,min))
	{
		alertErrorMsg = "Username should between "+min+" - "+max+" characters";
		return false;
	}
	var uName = $(id).value;
	var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
	for (var i = 0; i < uName.length; i++) 
	{
  		if (iChars.indexOf(uName.charAt(i)) != -1)
  		{
  			alertErrorMsg = "Username should not contain special characters";
  			return false;
  		}
  	}
	return true;
}

function passwordIsValid(id,reid,min,max)
{
	if ($F(id) != $F(reid))
	{
		alertErrorMsg = "Password do not match";
		return false;
	}
	if (!isBlank(id,'Password')) //|| (IsDecimal('txtName'))
	{
		return false;
	}
	if (isOverMaxLength(id,max) || isUnderMinLength(id,min))
	{
		alertErrorMsg = "Password should be between "+min+" - "+max+" characters";
		return false;
	}
	return true;
}

function emailIsValid(id)
{
	var testresults;
	if (!isBlank(id,"E-mail Address")) //|| (IsDecimal('txtName'))
	{
		alertErrorMsg = "Please Enter E-mail.";
		return false;
	}
	var str=$F(id);
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(str))
	{
		testresults=true;
	}
	else
	{
		alertErrorMsg = "Please input a valid email address!";
		$(id).value="";
		$(id).focus();
		testresults=false;
	}
	return (testresults)
}

function chkOnlyEmailIsValid(id)
{
	var testresults;
	var str=$F(id);
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	
	if (filter.test(str) || str == "")
	{
		testresults=true;
	}
	else
	{
		alertErrorMsg = "Please input a valid email address!";
		$(id).value="";
		$(id).focus();
		testresults=false;
	}
	return (testresults)
}

function isValidURL(id,newRegEx){

	var flag=0;
	if (!isBlank(id,"URL")) //|| (IsDecimal('txtName'))
	{
		alertErrorMsg = "Please Enter URL.";
		return false;
	}
	var url=$F(id);

	if (url.indexOf ('http://') == -1)
	{
		if (url.indexOf ('https://') == -1)
		{
			$(id).focus();
			alertErrorMsg = "URL must start with http:// or https://";
			return false;
		}
		else
			flag=1;
	}
	else
		flag=1;

	if(flag==1)
	{
		if(url.substring(0,7)=="http://" || url.substring(0,8)=="https://" )
		{	//nothing 	
		}
		else
		{
			$(id).focus();
			alertErrorMsg = "URL must start with http:// or https://";
			return false;
		}

	}  
	var newRegCheck = false;
	if(newRegEx)
	{
		if(newRegEx != '' || newRegEx == '1')
			newRegCheck = true;
	}

	if(newRegCheck)
	{
		var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	}
	else
	{
		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
	{
    	$(id).value="";
		$(id).focus();
		alertErrorMsg = "Please Enter valid URL.";		
        return false;
    }
} 

function validURL(id){
	if (!isBlank(id,"URL")) //|| (IsDecimal('txtName'))
	{
		alertErrorMsg = "Please Enter URL.";
		return false;
	}
	var url=$F(id);
    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
	{
    	$(id).value="";
		$(id).focus();
		alertErrorMsg = "Please Enter valid URL.";		
        return false;
    }
}


function phoneIsValid(id,disp)
{
	return validatePhone(id,disp);
}

function zipIsValid(id,how)
{
	(how==null)?"alert":"";
	var valid = "0123456789-";
	var hyphencount = 0;

	if($F(id) != "" && $F(id) != " ")
	{
		//alert("val = "+document.getElementById(id).value+"ens");
		if ($(id).value.length!=5 && $(id).value.length!=10)
		{
			if(how=="alert")
				_alert("Please enter your 5 digit or 5 digit+4 zip code.");
			else
				alertErrorMsg = "Please enter your 5 digit or 5 digit+4 zip code.";
			$(id).value="";
			$(id).focus();
			return false;
		}
		for (var i=0; i < $(id).value.length; i++)
		{
			temp = "" + $(id).value.substring(i, i+1);
			if (temp == "-") hyphencount++;
			if (valid.indexOf(temp) == "-1")
			{
				if(how=="alert")
					_alert("Invalid characters in your zip code.  Please try again.");
				else
					alertErrorMsg = "Invalid characters in your zip code.";
				$(id).value="";
				$(id).focus();
				return false;
			}
			if ((hyphencount > 1) || (($(id).value.length==10) && ""+$(id).value.charAt(5)!="-"))
			{
				if(how=="alert")
					_alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
				else
					alertErrorMsg = "The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.";
				
				$(id).value="";
				$(id).focus();
				return false;
			}
		}
	}
	return true;
}

function zipValid(id)
{
	var valid = "0123456789-";
	var hyphencount = 0;

	if($F(id) != "" && $F(id) != " ")
	{
		//alert("val = "+document.getElementById(id).value+"ens");
		if ($(id).value.length!=5 && $(id).value.length!=10)
		{
			alertErrorMsg = "Please enter your 5 digit or 5 digit+4 zip code.";
			$(id).value="";
			$(id).focus();
			return false;
		}
		for (var i=0; i < $(id).value.length; i++)
		{
			temp = "" + $(id).value.substring(i, i+1);
			if (temp == "-") hyphencount++;
			if (valid.indexOf(temp) == "-1")
			{
				alertErrorMsg = "Invalid characters in your zip code.";
				$(id).value="";
				$(id).focus();
				return false;
			}
			if ((hyphencount > 1) || (($(id).value.length==10) && ""+$(id).value.charAt(5)!="-"))
			{
				alertErrorMsg = "The hyphen character should be used formatted properly.";
				$(id).value="";
				$(id).focus();
				return false;
			}
		}
	}
	return true;
}


function numberIsValid(id,msg,disp,min,max)
{
	if (($F(id) != "") && ($F(id) != " ") && (isNaN($F(id))))
	{
		alertErrorMsg=msg;
		//alert(msg);
		$(id).value="";
		$(id).focus();
		return false;
	}
	if (min !=null && isUnderMinLength(id,min) && ($F(id) != "") && ($F(id) != " "))
	{
		alertErrorMsg=disp+" should be more than "+min+" characters";
		$(id).value="";
		$(id).focus();
		return false;
	}
	if (max !=null && isOverMaxLength(id,max) && ($F(id) != "") && ($F(id) != " "))
	{
		alertErrorMsg=disp+" should be less than "+max+" characters";
		$(id).value="";
		$(id).focus();
		return false;
	}
	return true;
}

function albhabetIsValid(id,msg,disp,min,max)
{
	if(($F(id) != "") && ($F(id) != " ") && $F(id).match(/^[A-Za-z\s]+$/g) == null)
	{
		alertErrorMsg=msg;
		$(id).value="";
		$(id).focus();
		return false;
	}
	if((min != null) && isUnderMinLength(id,min) && ($F(id) != "") && ($F(id) != " "))
	{
		//alert("Value of "+disp+" should have atleast "+min+" characters.")
		alertErrorMsg="Value of "+disp+" should have atleast "+min+" characters.";
		$(id).value="";
		$(id).focus();
		return false;
	}
	if((max != null) && isOverMaxLength(id,max) && ($F(id) != "") && ($F(id) != " "))
	{
		//alert("Value of "+disp+"allows only "+max+" characters.")
		alertErrorMsg="Value of "+disp+"allows only "+max+" characters.";
		$(id).value="";
		$(id).focus();
		return false;
	}
	return true;
}

function alphaNumericIsValid(id,msg,disp,min,max)
{
	if(($F(id) != "") && ($F(id) != " ") && $F(id).match(/^[A-Za-z0-9_\s]+$/g) == null)
	{
		alertErrorMsg=msg;
		$(id).value="";
		$(id).focus();
		return false;
	}
	if((min != null) && isUnderMinLength(id,min) && ($F(id) != "") && ($F(id) != " "))
	{
		//alert("Value of "+disp+" should have atleast "+min+" characters.")
		alertErrorMsg="Value of "+disp+" should have atleast "+min+" characters.";
		$(id).value="";
		$(id).focus();
		return false;
	}
	if((max != null) && isOverMaxLength(id,max) && ($F(id) != "") && ($F(id) != " "))
	{
		//alert("Value of "+disp+"allows only "+max+" characters.")
		alertErrorMsg="Value of "+disp+"allows only "+max+" characters.";
		$(id).value="";
		$(id).focus();
		return false;
	}
	return true;
}

function isBlank(id,disp)
{
	if(trim($F(id)) == "")
	{
		alertErrorMsg="Please enter "+disp;
		$(id).focus();
		return false;
	}
	return true;
}
function isBlank_withoutfocus(id,disp)
{
	if(trim($F(id)) == "")
	{
		alertErrorMsg="Please enter "+disp;
		return false;
	}
	return true;
}
function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
function mobileIsValid(id,disp)
{
	return validatePhone(id,disp);
}
function faxIsValid(id,disp)
{
	return validatePhone(id,disp);
}

function percentageIsValid(id)
{
	var testresults;
	var filter = /^\d{1,2}(\.\d{1,2})?$/;
	var str=$F(id);
	if (!isBlank(id,"Percentage")) //|| (IsDecimal('txtName'))
	{
		alertErrorMsg = "Please Enter Percentage.";
		return false;
	}
	if (filter.test(str))
	{
		testresults=true;
	}
	else
	{
		alertErrorMsg = "Please input a valid Percentage value!";
		$(id).value="";
		$(id).focus();
		testresults=false;
	}
	return testresults;
}


function siteIsValid(id)
{
	var testresults;
	if (!isBlank(id,"E-mail Address")) //|| (IsDecimal('txtName'))
	{
		alertErrorMsg = "Please Enter E-mail.";
		return false;
	}
	var str=$F(id);
	var filter=/^([\w-]+(?:\.[\w-]+)*)\.((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	//var filter = /(\w+):\/\/([\w\.]+)\/([\w\/]+)/;
	if (filter.test(str))
	{
		testresults=true;
	}
	else
	{
		alertErrorMsg = "Please input a valid site address!";
		$(id).value="";
		$(id).focus();
		testresults=false;
	}
	return (testresults)
}

// Date Validation Javascript
// copyright 30th October 2004, by Stephen Chapman
// http://javascript.about.com

// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.

function valDateFmt(datefmt) {myOption = -1;
for (i=0; i<datefmt.length; i++) {if (datefmt[i].checked) {myOption = i;}}
if (myOption == -1) {_alert("You must select a date format");return ' ';}
return datefmt[myOption].value;}
function valDateRng(daterng) {myOption = -1;
for (i=0; i<daterng.length; i++) {if (daterng[i].checked) {myOption = i;}}
if (myOption == -1) {_alert("You must select a date range");return ' ';}
return daterng[myOption].value;}
function stripBlanks(fld) {var result = "";for (i=0; i<fld.length; i++) {
if (fld.charAt(i) != " " || c > 0) {result += fld.charAt(i);
if (fld.charAt(i) != " ") c = result.length;}}return result.substr(0,c);}
var numb = '0123456789';
function isValid(parm,val) {if (parm == "") return true;
for (i=0; i<parm.length; i++) {if (val.indexOf(parm.charAt(i),0) == -1)
return false;}return true;}
function isNum(parm) {return isValid(parm,numb);}
var mth = new Array(' ','january','february','march','april','may','june','july','august','september','october','november','december');
var day = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
function validateDate(fld,fmt,rng)
{
	var dd, mm, yy;
	var today = new Date;
	var t = new Date;
	fld = stripBlanks(fld);
	if (fld == '') return false;
	var d1 = fld.split('\/');
	if (d1.length != 3) d1 = fld.split(' ');
	if (d1.length != 3) return false;
	if (fmt == 'u' || fmt == 'U')
	{
	 	dd = d1[1];
	 	mm = d1[0];
	 	yy = d1[2];
	 }
	else if (fmt == 'j' || fmt == 'J') {
	  dd = d1[2]; mm = d1[1]; yy = d1[0];}
	else if (fmt == 'w' || fmt == 'W'){
	  dd = d1[0]; mm = d1[1]; yy = d1[2];}
	else return false;
	var n = dd.lastIndexOf('st');
	if (n > -1) dd = dd.substr(0,n);
	n = dd.lastIndexOf('nd');
	if (n > -1) dd = dd.substr(0,n);
	n = dd.lastIndexOf('rd');
	if (n > -1) dd = dd.substr(0,n);
	n = dd.lastIndexOf('th');
	if (n > -1) dd = dd.substr(0,n);
	n = dd.lastIndexOf(',');
	if (n > -1) dd = dd.substr(0,n);
	n = mm.lastIndexOf(',');
	if (n > -1) mm = mm.substr(0,n);
	if (!isNum(dd)) return false;
	if (!isNum(yy)) return false;
	if (!isNum(mm)) {
	  var nn = mm.toLowerCase();
	  for (var i=1; i < 13; i++) {
	    if (nn == mth[i] ||
	        nn == mth[i].substr(0,3)) {mm = i; i = 13;}
	  }
}
if (!isNum(mm)) return false;
dd = parseFloat(dd); mm = parseFloat(mm); yy = parseFloat(yy);
if (yy < 100) yy += 2000;
if (yy < 1582 || yy > 4881) return false;
if (mm == 2 && (yy%400 == 0 || (yy%4 == 0 && yy%100 != 0))) day[mm-1]++;
if (mm < 1 || mm > 12) return false;
if (dd < 1 || dd > day[mm-1]) return false;
t.setDate(dd); t.setMonth(mm-1); t.setFullYear(yy);
if (rng == 'p' || rng == 'P') {
if (t > today) return false;
}
else if (rng == 'f' || rng == 'F') {
if (t < today) return false;
}
else if (rng != 'a' && rng != 'A') return false;
return true;
}

/*Function to check phone validation in format 306-954-2548 or 3-306-954-2548 */
function validatePhone(id,disp)
{
	var title = '';
	if(trim(disp)!='')
		title = disp;
	else
		title = 'Phone';

	var decimalRE = /^\s*(\d{1}-\d{3}-\d{3}-\d{4}|\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4})\s*$/;
	//var decimalRE = /^\s*(\d{1}-\d{3}-\d{3}-\d{4}|\(\d{1}\-\d{3}\) \d{3}-\d{4})\s*$/;
	if(trim($(id).value)=="")
		return true;
//	var decimalRE = "^(\\+|-)?[0-9][0-9]*(\\.[0-9]*)?$";
	if(numTotal($(id).value)==0)
	{
		alertErrorMsg = title + " is not Valid.<br/>Please input in format like 306-954-2548 or 3-306-954-2548";
		return false;
		
	}
	if (trim($F(id)) != "" && $(id).value.match(decimalRE) == null)
	{
		alertErrorMsg = title + " is not Valid.<br/>Please input in format like 306-954-2548 or 3-306-954-2548";
		return false;
	}
	return true;
}
	/*----------------------------------SUGGESTION EMAIL POPUP VALIDATION START--------------------------------- */
	var sugEmailPopup;
	function showSuggestionPopup()
	{	
		if($('emailPopupSuggestion'))
		{
			sugEmailPopup = createDialog('emailPopupSuggestion');		
			$('emailPopupSuggestion').style.display='block';
			if($('emailPopupSuggestion_c')) $('emailPopupSuggestion_c').style.zIndex='17';
			if($('emailPopupSuggestion_mask')) $('emailPopupSuggestion_mask').style.zIndex='16';
			if($('divContainerAdvanceSearch')) $('divContainerAdvanceSearch').style.zIndex='15';
			sugEmailPopup.show();			
			$('errEmailPro').innerHTML = '';
			$('txtComments').className = ''; $('txtComments').value = '';
			$('txtEmail').className = ''; $('txtEmail').value = '';
			$('txtName').className = ''; $('txtName').value = '';
			$('errEmailPro').innerHTML = '';
			$('sent').value = '0';

			//hide all related zindex specific div related to BUG# 10875
			if($("powerAdvSearch")) $("powerAdvSearch").style.display = "none";
			if($("divSaveSearch")) $("divSaveSearch").style.display = "none";
			if($("prpTyp")) $("prpTyp").style.display = "none";
			if($("prpStat")) $("prpStat").style.display = "none";
			if($("trSaleDate")) $("trSaleDate").style.display = "none";

			if(typeof(spl)!= "undefined")
			{	if(!spl)
				{
					hideMapList();	
					hidePwrsrchrel();
				}
			}
			
			//related to the bug specific to suggestion box;
			//Hide ProListing DIV
			if($('mapDiv') && $('mapDiv').style.display!='none')
			{
				if($("proListingDiv")){$("proListingDiv").style.display="none";}
			}
			//hide all related zindex specific div
		}
	}
	function sendSuggestion()
	{
		if($('sent').value == '0')
		{
			$('errEmailPro').innerHTML = '';
			$('txtComments').className = '';
			$('txtEmail').className = '';
			$('txtName').className = '';
			$('errEmailPro').innerHTML = '';			
			var sent = false;
			var comments = trim($('txtComments').value);
			var name = trim($('txtName').value);
			var email = trim($('txtEmail').value);
			var specialchars = "!@#$%^&*()+=-[]\\\';,/{}|\":<>?``";


			if(name)
			{
				var fName = name;
				for (var charNo = 0; charNo < fName.length; charNo++) 
				{
					if (specialchars.indexOf(fName.charAt(charNo)) != -1)
					{
						errorMsg = "Name should not contain special characters.";
						$('errEmailPro').innerHTML = errorMsg;
						$('txtName').className 	= "textboxRed";
						$('txtName').focus();
						return false ;	  				
					}
				}
			}
			
			if(email != '' && !emailIsValid("txtEmail"))
			{
				$('errEmailPro').innerHTML = "Please specify valid email.";
				$('txtEmail').focus();
				$('txtEmail').className="textboxRed";
				return false;
			}
			if(comments == '')
			{
				$('errEmailPro').innerHTML = "Please specify suggestions.";
				$('txtComments').focus();
				$('txtComments').className="textboxRed";
				return false;
			}
			if(comments)
			{			
				var specialchars = "#%^()+=[]\\\'/{}|\"<>``";
				for (var charNo = 0; charNo < comments.length; charNo++) 
				{
					if (specialchars.indexOf(comments.charAt(charNo)) != -1)
					{
						errorMsg = "Suggestions should not contain special characters.";
						$('errEmailPro').innerHTML = errorMsg;
						$('txtComments').className 	= "textboxRed";
						$('txtComments').focus();
						return false ;	  				
					}
				}
			}
			$('sent').value = '1';
			var url = "/app/listing/singlePropertyLandingNew.php";
			var qs = "action=suggestion&name="+name+"&email="+email+"&comments="+encodeURI(comments);
			ajaxRequest(url,qs,function(reqobj)
			{ 
				var varResponse = trim(reqobj.responseText);	
				if(varResponse == '1')
				{
					$('errEmailPro').innerHTML = "Your suggestions have been sent successfully.";
					$('txtComments').value = '';
					$('txtName').value = '';
					$('txtEmail').value = '';
					$('sent').value = '0';
				}
				else
				{
					$('errEmailPro').innerHTML = "Problem in email sending.";					
					$('sent').value = '0';
				}
				setTimeout('sugEmailPopup.hide();',800);
			});
		}
	}

	function atPropContactUs(fromPage, fromTitle, fromUrl)
	{
		var myQs = new Querystring();
		var frm = myQs.get("frm");
		var aid = myQs.get("aid");

		$('txtName').style.border="solid 1px #7F9DB9";
		$('txtFromEmail').style.border="solid 1px #7F9DB9";

		if(!isBlank('txtName','Full Name'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtName').style.border="solid 1px red";
			return false;
		}
		else if(!emailIsValid('txtFromEmail'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtFromEmail').style.border="solid 1px red";
			return false;
		}		
		if($F('txtPhone') != "")
		{
			var id = 'txtPhone';
			var decimalRE = /^\s*(\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4})\s*$/;			
			if(numTotal($(id).value)==0)
			{
				alertErrorMsg = "Phone is not Valid.\nPlease input in format like 306-954-2548";
				$('errPublish').innerHTML = alertErrorMsg;
				return false;				
			}
			if (trim($F(id)) != "" && $(id).value.match(decimalRE) == null)
			{
				alertErrorMsg = "Phone is not Valid.\nPlease input in format like 306-954-2548";
				$('errPublish').innerHTML = alertErrorMsg;
				return false;
			}				
		}

		if(agtContact != "")
			agtContact = "&agtContact="+agtContact;
		
		var qry = "name="+$('txtName').value+"&email="+$('txtFromEmail').value+"&phone="+$('txtPhone').value+"&comment="+escape($('txtComments').value)+"&sendMail=1"+agtContact;	

		if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
		{
			qry += "&aid="+aid;
		}
		try
		{
			var strSearchCriteria = getSearchCriteriaStringForEmail();
			qry = qry + "&searchCriteria="+escape(encodeURI(strSearchCriteria));
		}
		catch (ex)
		{
			// Do Nothing
		}

		if (fromPage != null && fromPage != 'undefined')
			qry += "&from_page="+fromPage;
		if (fromTitle != null && fromTitle != 'undefined')
			qry += "&from_title="+escape(fromTitle);
		if (fromUrl != null && fromUrl != 'undefined')
			qry += "&from_url="+escape(fromUrl);

		var url = "/help/atproperties/ContactUs.php";
		ajaxRequest(url,qry,function(reqobj)
		{ 
			var varResponse = trim(reqobj.responseText);	
			if(varResponse == '1')
			{
				alert("Your information have been sent successfully.");
				$('errPublish').innerHTML = "";
				$('txtFromEmail').value = "";
				$('txtName').value = "";
				$('txtPhone').value = "";
				$('txtComments').value = "";
				window.close();
			}
			else
				alert("Problem in email sending.");
		});		
	}
 /*----------------------------------SUGGESTION EMAIL POPUP VALIDATION END--------------------------------- */

	function illustratedContactUs(fromPage, fromTitle, fromUrl)
	{
		var myQs = new Querystring();
		var frm = myQs.get("frm");
		var aid = myQs.get("aid");

		if(!isBlank('txtName','Full Name'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtName').style.border="solid 1px red";
			return false;
		}
		else
		{
			$('txtName').style.border="";
			$('txtName').className = "ipboxes";
			$('errPublish').html = "";
		}
		
		if(!emailIsValid('txtFromEmail'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtFromEmail').style.border="solid 1px red";
			return false;
		}
		else
		{
			$('txtFromEmail').style.border="";
			$('txtFromEmail').className = "ipboxes";
			$('errPublish').html = "";
		}

		if($F('txtPhone') != "")
		{
			var id = 'txtPhone';
			var decimalRE = /^\s*(\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4})\s*$/;			
			if(numTotal($(id).value)==0)
			{
				alertErrorMsg = "Phone is not Valid.\nPlease input in format like 306-954-2548";
				$('errPublish').innerHTML = alertErrorMsg;
				$('txtPhone').style.border="solid 1px red";
				return false;				
			}
			else if (trim($F(id)) != "" && $(id).value.match(decimalRE) == null)
			{
				alertErrorMsg = "Phone is not Valid.\nPlease input in format like 306-954-2548";
				$('errPublish').innerHTML = alertErrorMsg;
				$('txtPhone').style.border="solid 1px red";
				return false;
			}	
			else
			{
				$('txtPhone').style.border="";
				$('txtPhone').className = "ipboxes";
				$('errPublish').html = "";
			}
		}
		else
		{
			$('txtPhone').style.border="";
			$('txtPhone').className = "ipboxes";
			$('errPublish').html = "";
		}

		if(agtContact != "")
			agtContact = "&agtContact="+agtContact;
		
		var qry = "name="+$('txtName').value+"&email="+$('txtFromEmail').value+"&phone="+$('txtPhone').value+"&comment="+escape($('txtComments').value)+"&sendMail=1"+agtContact;	

		if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
		{
			qry += "&aid="+aid;
		}

		try
		{
			var strSearchCriteria = getSearchCriteriaStringForEmail();
			qry = qry + "&searchCriteria="+escape(encodeURI(strSearchCriteria));
		}
		catch (ex)
		{
			// Do Nothing
		}

		if (fromPage != null && fromPage != 'undefined')
			qry += "&from_page="+fromPage;
		if (fromTitle != null && fromTitle != 'undefined')
			qry += "&from_title="+escape(fromTitle);
		if (fromUrl != null && fromUrl != 'undefined')
			qry += "&from_url="+escape(fromUrl);

		var url = "/help/illustrated/ContactUs.php";
		ajaxRequest(url,qry,function(reqobj)
		{ 
			var varResponse = trim(reqobj.responseText);	
			if(varResponse == '1')
			{
				alert("Your information has been sent successfully.");
				$('errPublish').innerHTML = "";
				$('txtFromEmail').value = "";
				$('txtName').value = "";
				$('txtPhone').value = "";
				$('txtComments').value = "";
				window.close();
			}
			else
				alert("Problem in email sending.");
		});		
	}

	function illustratedCarrier()
	{
		var myQs = new Querystring();
		var frm = myQs.get("frm");
		var aid = myQs.get("aid");

		if(!isBlank('txtName','Full Name'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtName').style.border="solid 1px red";
			return false;
		}
		else
		{
			$('txtName').style.border="";
			$('txtName').className = "ipboxes";
			$('errPublish').html = "";
		}
		
		if(!emailIsValid('txtFromEmail'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtFromEmail').style.border="solid 1px red";
			return false;
		}
		else
		{
			$('txtFromEmail').style.border="";
			$('txtFromEmail').className = "ipboxes";
			$('errPublish').html = "";
		}

		if(!isBlank('txtPhone','Phone'))
		{
			$('errPublish').innerHTML = alertErrorMsg;
			$('txtPhone').style.border="solid 1px red";
			return false;
		}
		else if($F('txtPhone') != "")
		{
			var id = 'txtPhone';
			var decimalRE = /^\s*(\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4})\s*$/;			
			if(numTotal($(id).value)==0)
			{
				alertErrorMsg = "Phone is not Valid.\nPlease input in format like 306-954-2548";
				$('errPublish').innerHTML = alertErrorMsg;
				$('txtPhone').style.border="solid 1px red";
				return false;				
			}
			else if (trim($F(id)) != "" && $(id).value.match(decimalRE) == null)
			{
				alertErrorMsg = "Phone is not Valid.\nPlease input in format like 306-954-2548";
				$('errPublish').innerHTML = alertErrorMsg;
				$('txtPhone').style.border="solid 1px red";
				return false;
			}	
			else
			{
				$('txtPhone').style.border="";
				$('txtPhone').className = "ipboxes";
				$('errPublish').html = "";
			}
		}
		else
		{
			$('txtPhone').style.border="";
			$('txtPhone').className = "ipboxes";
			$('errPublish').html = "";
		}

		if(agtContact != "")
			agtContact = "&agtContact="+agtContact;
		
		var qry = "name="+$('txtName').value+"&email="+$('txtFromEmail').value+"&phone="+$('txtPhone').value+"&comment="+escape($('txtComments').value)+"&sendMail=1"+agtContact;	

		if(frm != null && trim(frm) == 'agt' && aid != null && trim(aid) != "")
		{
			qry += "&aid="+aid;
		}

		var url = "/help/illustrated/carrier.php";
		ajaxRequest(url,qry,function(reqobj)
		{ 
			var varResponse = trim(reqobj.responseText);	
			if(varResponse == '1')
			{
				alert("Your information has been sent successfully.");
				$('errPublish').innerHTML = "";
				$('txtFromEmail').value = "";
				$('txtName').value = "";
				$('txtPhone').value = "";
				$('txtComments').value = "";
				window.close();
			}
			else
				alert("Problem in email sending.");
		});		
	}

/* function for home valuation */
function isValidNumber(val){
	  if(val==null){return false;}
	  if (val.length==0){return false;}
	  var DecimalFound = false;
	  for (var i = 0; i < val.length; i++) {
			var ch = val.charAt(i);
			if (i == 0 && ch == "-") {
				  continue;
			}
			if (ch == "." && !DecimalFound) {
				  DecimalFound = true;
				  continue;
			}
			if (ch < "0" || ch > "9") {
				  return false;
			}
	  }
	  return true;
}

function addLeadFrmHomeValuation()
{
	$('errLeadProSelect').innerHTML = "";	
	$('txtConsEmailSelect').className = "";
	$('txtConsPhoneSelect').className = "";
	$('txtConsAddressSelect').className = "";
	$('txtConsCitySelect').className = "";
	$('txtConsStateSelect').className = "";
	$('txtConsZipSelect').className = "";

	$('txtConsBedsSelect').className = "";
	$('txtConsBathsSelect').className = "";
	$('txtConsSqftSelect').className = "";
	$('txtConsYearbuiltSelect').className = "";

	if(trim($('txtConsEmailSelect').value) == '')
	{
		errorMsg = "Please Enter Email.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsEmailSelect').className 	= "textboxRed";
		$('txtConsEmailSelect').focus();
		return false;
	}

	if(trim($('txtConsPhoneSelect').value) != '')
	{
		if(!validatePhone("txtConsPhoneSelect"))
		{
		    errorMsg = "Phone is not Valid.<br/>Please input in format like 306-954-2548.";
			$('errLeadProSelect').innerHTML =  errorMsg;
			$('txtConsPhoneSelect').className = "textboxRed";
			$('txtConsPhoneSelect').focus();
			return false;
		}
	}

	if(!emailIsValid("txtConsEmailSelect"))
	{
		errorMsg = "Please Enter Valid Email.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsEmailSelect').className 	= "textboxRed";
		$('txtConsEmailSelect').focus();
		
		return false;
	}

	if(trim($('txtConsAddressSelect').value)== "")
	{
		errorMsg = "Please Enter Address.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsAddressSelect').className = "textboxRed";
		$('txtConsAddressSelect').focus();
		return false;
	
	}

	if(trim($('txtConsCitySelect').value)== "")
	{
		errorMsg = "Please Enter City.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsCitySelect').className = "textboxRed";
		$('txtConsCitySelect').focus();
		return false;
	
	}

	if(trim($('txtConsStateSelect').value)== "")
	{
		errorMsg = "Please Enter State.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsStateSelect').className = "textboxRed";
		$('txtConsStateSelect').focus();
		return false;
	
	}

	if(trim($('txtConsZipSelect').value)== "")
	{
		errorMsg = "Please Enter Zip.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsZipSelect').className = "textboxRed";
		$('txtConsZipSelect').focus();
		return false;
	
	}
	if(!isNumeric($('txtConsZipSelect').value))
	{
		errorMsg = "Please Enter Valid Zip.";
		$('errLeadProSelect').innerHTML = errorMsg;
		$('txtConsZipSelect').className = "textboxRed";
		$('txtConsZipSelect').focus();
		return false;
	}

	if($("txtConsBedsSelect").value != "" && !isValidNumber($("txtConsBedsSelect").value))
	{
		$('errLeadProSelect').innerHTML = 'Please enter valid numeric value for Bedroom.';
		$('txtConsBedsSelect').className = "textboxRed";
		$('txtConsBedsSelect').focus();
		return false;
	}
	if($("txtConsBathsSelect").value != "" && !isValidNumber($("txtConsBathsSelect").value))
	{
		$('errLeadProSelect').innerHTML = 'Please enter valid numeric value for Bathroom.';
		$('txtConsBathsSelect').className = "textboxRed";
		$('txtConsBathsSelect').focus();
		return false;
	}
	if($("txtConsSqftSelect").value != "" && !isValidNumber($("txtConsSqftSelect").value))
	{
		$('errLeadProSelect').innerHTML = 'Please enter valid numeric value for Sq. Ft.'; 
		$('txtConsSqftSelect').className = "textboxRed";
		$('txtConsSqftSelect').focus();
		return false;
	}
	if($("txtConsYearbuiltSelect").value != "" && !isNumeric($("txtConsYearbuiltSelect").value))
	{
		$('errLeadProSelect').innerHTML = 'Please enter valid numeric value for Year Built.'; 
		$('txtConsYearbuiltSelect').className = "textboxRed";
		$('txtConsYearbuiltSelect').focus();
		return false;
	}

	var queryString="";
	var userType;
	queryString = "" ;
	
	if(trim($('txtConsNameSelect').value) != "")
		{queryString += "&name="+trim($('txtConsNameSelect').value);}

	if(trim($('txtConsPhoneSelect').value) != "")
		{queryString += "&phone="+trim($('txtConsPhoneSelect').value)}

	queryString +="&email="+trim($('txtConsEmailSelect').value)+"&address="+escape(encodeURI(trim($("txtConsAddressSelect").value)))+"&city="+trim($("txtConsCitySelect").value)+"&state="+trim($("txtConsStateSelect").value)+"&zip="+trim($("txtConsZipSelect").value);

	if(trim($("txtConsCommentsSelect").value) != "")
		{queryString += "&comments="+trim(escape($("txtConsCommentsSelect").value));}

	queryString+="&leadStatus=N";
	
	queryString += "&beds="+trim($('txtConsBedsSelect').value);
	queryString += "&baths="+trim($('txtConsBathsSelect').value);
	queryString += "&sqft="+trim($('txtConsSqftSelect').value);
	queryString += "&yearbuilt="+trim($('txtConsYearbuiltSelect').value);
	
	var objQs = new Querystring();
	var ouid = objQs.get('ouid');	
	var aid = objQs.get('aid');	
	if(aid!=null && trim(aid)!= '')
	{
		queryString = queryString+ "&frm=agt";
		queryString = queryString+ "&aid="+aid;
	}
	else if(ouid!=null && trim(ouid)!= '')
	{
		queryString = queryString+ "&frm=frch";
		queryString = queryString+ "&ouid="+ouid;
	}
	else
		queryString = queryString+ "&frm=bk";

	if($('propType'))
	{
		if($('propType').selectedIndex == 0)
			queryString+= "&propType=";
		else
			queryString+= "&propType="+$('propType').value.replace (/\'/g, '');
	}
	else
		queryString+= "&propType=";

	queryString+= "&sendMail=1";

	var url = "/help/illustrated/valueMyHome.php";

	ajaxRequest(url,queryString,function(originalResponse){
		var res = 	 originalResponse.responseText;
		if(res == '1')
		{
			alert('Your request has been submitted successfully.');
			$('txtConsNameSelect').value = "";
			$('txtConsEmailSelect').value = "";
			$('txtConsPhoneSelect').value = "";
			$('txtConsAddressSelect').value = "";
			$('txtConsCitySelect').value = "";
			$('txtConsStateSelect').value = "";
			$('txtConsZipSelect').value = "";
			$('txtConsBedsSelect').value = "";
			$('txtConsBathsSelect').value = "";
			$('txtConsSqftSelect').value = "";
			$('txtConsYearbuiltSelect').value = "";
			$('txtConsCommentsSelect').value = "";
			$('propType').selectedIndex = 0;
		}
		else
		{
			alert('There is an error while submitting your request.!!');
			return false;
		}		
	});
}

/*../vendor/yui/SinglePropMin-YUI.js*/

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
yahoo-min.js
*/


if(typeof YAHOO=="undefined"){var YAHOO={};}
YAHOO.namespace=function(){var a=arguments,o=null,i,j,d;for(i=0;i<a.length;++i){d=a[i].split(".");o=YAHOO;for(j=(d[0]=="YAHOO")?1:0;j<d.length;++j){o[d[j]]=o[d[j]]||{};o=o[d[j]];}}
return o;};YAHOO.log=function(msg,cat,src){var l=YAHOO.widget.Logger;if(l&&l.log){return l.log(msg,cat,src);}else{return false;}};YAHOO.extend=function(subc,superc,overrides){var F=function(){};F.prototype=superc.prototype;subc.prototype=new F();subc.prototype.constructor=subc;subc.superclass=superc.prototype;if(superc.prototype.constructor==Object.prototype.constructor){superc.prototype.constructor=superc;}
if(overrides){for(var i in overrides){subc.prototype[i]=overrides[i];}}};YAHOO.augment=function(r,s){var rp=r.prototype,sp=s.prototype,a=arguments,i,p;if(a[2]){for(i=2;i<a.length;++i){rp[a[i]]=sp[a[i]];}}else{for(p in sp){if(!rp[p]){rp[p]=sp[p];}}}};YAHOO.namespace("util","widget","example");

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
even-min.js
*/


YAHOO.util.CustomEvent=function(type,oScope,silent,signature){this.type=type;this.scope=oScope||window;this.silent=silent;this.signature=signature||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}
var onsubscribeType="_YUICEOnSubscribe";if(type!==onsubscribeType){this.subscribeEvent=new YAHOO.util.CustomEvent(onsubscribeType,this,true);}};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(fn,obj,override){if(this.subscribeEvent){this.subscribeEvent.fire(fn,obj,override);}
this.subscribers.push(new YAHOO.util.Subscriber(fn,obj,override));},unsubscribe:function(fn,obj){var found=false;for(var i=0,len=this.subscribers.length;i<len;++i){var s=this.subscribers[i];if(s&&s.contains(fn,obj)){this._delete(i);found=true;}}
return found;},fire:function(){var len=this.subscribers.length;if(!len&&this.silent){return true;}
var args=[],ret=true,i;for(i=0;i<arguments.length;++i){args.push(arguments[i]);}
var argslength=args.length;if(!this.silent){}
for(i=0;i<len;++i){var s=this.subscribers[i];if(s){if(!this.silent){}
var scope=s.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var param=null;if(args.length>0){param=args[0];}
ret=s.fn.call(scope,param,s.obj);}else{ret=s.fn.call(scope,this.type,args,s.obj);}
if(false===ret){if(!this.silent){}
return false;}}}
return true;},unsubscribeAll:function(){for(var i=0,len=this.subscribers.length;i<len;++i){this._delete(len-1-i);}},_delete:function(index){var s=this.subscribers[index];if(s){delete s.fn;delete s.obj;}
this.subscribers.splice(index,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(fn,obj,override){this.fn=fn;this.obj=obj||null;this.override=override;};YAHOO.util.Subscriber.prototype.getScope=function(defaultScope){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}
return defaultScope;};YAHOO.util.Subscriber.prototype.contains=function(fn,obj){if(obj){return(this.fn==fn&&this.obj==obj);}else{return(this.fn==fn);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+(this.obj||"")+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var loadComplete=false;var listeners=[];var unloadListeners=[];var legacyEvents=[];var legacyHandlers=[];var retryCount=0;var onAvailStack=[];var legacyMap=[];var counter=0;return{POLL_RETRYS:200,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,OBJ:3,ADJ_SCOPE:4,isSafari:(/Safari|Konqueror|KHTML/gi).test(navigator.userAgent),isIE:(!this.isSafari&&!navigator.userAgent.match(/opera/gi)&&navigator.userAgent.match(/msie/gi)),_interval:null,startInterval:function(){if(!this._interval){var self=this;var callback=function(){self._tryPreloadAttach();};this._interval=setInterval(callback,this.POLL_INTERVAL);}},onAvailable:function(p_id,p_fn,p_obj,p_override){onAvailStack.push({id:p_id,fn:p_fn,obj:p_obj,override:p_override,checkReady:false});retryCount=this.POLL_RETRYS;this.startInterval();},onContentReady:function(p_id,p_fn,p_obj,p_override){onAvailStack.push({id:p_id,fn:p_fn,obj:p_obj,override:p_override,checkReady:true});retryCount=this.POLL_RETRYS;this.startInterval();},addListener:function(el,sType,fn,obj,override){if(!fn||!fn.call){return false;}
if(this._isValidCollection(el)){var ok=true;for(var i=0,len=el.length;i<len;++i){ok=this.on(el[i],sType,fn,obj,override)&&ok;}
return ok;}else if(typeof el=="string"){var oEl=this.getEl(el);if(oEl){el=oEl;}else{this.onAvailable(el,function(){YAHOO.util.Event.on(el,sType,fn,obj,override);});return true;}}
if(!el){return false;}
if("unload"==sType&&obj!==this){unloadListeners[unloadListeners.length]=[el,sType,fn,obj,override];return true;}
var scope=el;if(override){if(override===true){scope=obj;}else{scope=override;}}
var wrappedFn=function(e){return fn.call(scope,YAHOO.util.Event.getEvent(e),obj);};var li=[el,sType,fn,wrappedFn,scope];var index=listeners.length;listeners[index]=li;if(this.useLegacyEvent(el,sType)){var legacyIndex=this.getLegacyIndex(el,sType);if(legacyIndex==-1||el!=legacyEvents[legacyIndex][0]){legacyIndex=legacyEvents.length;legacyMap[el.id+sType]=legacyIndex;legacyEvents[legacyIndex]=[el,sType,el["on"+sType]];legacyHandlers[legacyIndex]=[];el["on"+sType]=function(e){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(e),legacyIndex);};}
legacyHandlers[legacyIndex].push(li);}else{try{this._simpleAdd(el,sType,wrappedFn,false);}catch(e){this.removeListener(el,sType,fn);return false;}}
return true;},fireLegacyEvent:function(e,legacyIndex){var ok=true;var le=legacyHandlers[legacyIndex];for(var i=0,len=le.length;i<len;++i){var li=le[i];if(li&&li[this.WFN]){var scope=li[this.ADJ_SCOPE];var ret=li[this.WFN].call(scope,e);ok=(ok&&ret);}}
return ok;},getLegacyIndex:function(el,sType){var key=this.generateId(el)+sType;if(typeof legacyMap[key]=="undefined"){return-1;}else{return legacyMap[key];}},useLegacyEvent:function(el,sType){if(!el.addEventListener&&!el.attachEvent){return true;}else if(this.isSafari){if("click"==sType||"dblclick"==sType){return true;}}
return false;},removeListener:function(el,sType,fn){var i,len;if(typeof el=="string"){el=this.getEl(el);}else if(this._isValidCollection(el)){var ok=true;for(i=0,len=el.length;i<len;++i){ok=(this.removeListener(el[i],sType,fn)&&ok);}
return ok;}
if(!fn||!fn.call){return this.purgeElement(el,false,sType);}
if("unload"==sType){for(i=0,len=unloadListeners.length;i<len;i++){var li=unloadListeners[i];if(li&&li[0]==el&&li[1]==sType&&li[2]==fn){unloadListeners.splice(i,1);return true;}}
return false;}
var cacheItem=null;var index=arguments[3];if("undefined"==typeof index){index=this._getCacheIndex(el,sType,fn);}
if(index>=0){cacheItem=listeners[index];}
if(!el||!cacheItem){return false;}
if(this.useLegacyEvent(el,sType)){var legacyIndex=this.getLegacyIndex(el,sType);var llist=legacyHandlers[legacyIndex];if(llist){for(i=0,len=llist.length;i<len;++i){li=llist[i];if(li&&li[this.EL]==el&&li[this.TYPE]==sType&&li[this.FN]==fn){llist.splice(i,1);break;}}}}else{try{this._simpleRemove(el,sType,cacheItem[this.WFN],false);}catch(e){return false;}}
delete listeners[index][this.WFN];delete listeners[index][this.FN];listeners.splice(index,1);return true;},getTarget:function(ev,resolveTextNode){var t=ev.target||ev.srcElement;return this.resolveTextNode(t);},resolveTextNode:function(node){if(node&&3==node.nodeType){return node.parentNode;}else{return node;}},getPageX:function(ev){var x=ev.pageX;if(!x&&0!==x){x=ev.clientX||0;if(this.isIE){x+=this._getScrollLeft();}}
return x;},getPageY:function(ev){var y=ev.pageY;if(!y&&0!==y){y=ev.clientY||0;if(this.isIE){y+=this._getScrollTop();}}
return y;},getXY:function(ev){return[this.getPageX(ev),this.getPageY(ev)];},getRelatedTarget:function(ev){var t=ev.relatedTarget;if(!t){if(ev.type=="mouseout"){t=ev.toElement;}else if(ev.type=="mouseover"){t=ev.fromElement;}}
return this.resolveTextNode(t);},getTime:function(ev){if(!ev.time){var t=new Date().getTime();try{ev.time=t;}catch(e){return t;}}
return ev.time;},stopEvent:function(ev){this.stopPropagation(ev);this.preventDefault(ev);},stopPropagation:function(ev){if(ev.stopPropagation){ev.stopPropagation();}else{ev.cancelBubble=true;}},preventDefault:function(ev){if(ev.preventDefault){ev.preventDefault();}else{ev.returnValue=false;}},getEvent:function(e){var ev=e||window.event;if(!ev){var c=this.getEvent.caller;while(c){ev=c.arguments[0];if(ev&&Event==ev.constructor){break;}
c=c.caller;}}
return ev;},getCharCode:function(ev){return ev.charCode||ev.keyCode||0;},_getCacheIndex:function(el,sType,fn){for(var i=0,len=listeners.length;i<len;++i){var li=listeners[i];if(li&&li[this.FN]==fn&&li[this.EL]==el&&li[this.TYPE]==sType){return i;}}
return-1;},generateId:function(el){var id=el.id;if(!id){id="yuievtautoid-"+counter;++counter;el.id=id;}
return id;},_isValidCollection:function(o){return(o&&o.length&&typeof o!="string"&&!o.tagName&&!o.alert&&typeof o[0]!="undefined");},elCache:{},getEl:function(id){return document.getElementById(id);},clearCache:function(){},_load:function(e){loadComplete=true;var EU=YAHOO.util.Event;if(this.isIE){EU._simpleRemove(window,"load",EU._load);}},_tryPreloadAttach:function(){if(this.locked){return false;}
this.locked=true;var tryAgain=!loadComplete;if(!tryAgain){tryAgain=(retryCount>0);}
var notAvail=[];for(var i=0,len=onAvailStack.length;i<len;++i){var item=onAvailStack[i];if(item){var el=this.getEl(item.id);if(el){if(!item.checkReady||loadComplete||el.nextSibling||(document&&document.body)){var scope=el;if(item.override){if(item.override===true){scope=item.obj;}else{scope=item.override;}}
item.fn.call(scope,item.obj);onAvailStack[i]=null;}}else{notAvail.push(item);}}}
retryCount=(notAvail.length===0)?0:retryCount-1;if(tryAgain){this.startInterval();}else{clearInterval(this._interval);this._interval=null;}
this.locked=false;return true;},purgeElement:function(el,recurse,sType){var elListeners=this.getListeners(el,sType);if(elListeners){for(var i=0,len=elListeners.length;i<len;++i){var l=elListeners[i];this.removeListener(el,l.type,l.fn);}}
if(recurse&&el&&el.childNodes){for(i=0,len=el.childNodes.length;i<len;++i){this.purgeElement(el.childNodes[i],recurse,sType);}}},getListeners:function(el,sType){var elListeners=[];if(listeners&&listeners.length>0){for(var i=0,len=listeners.length;i<len;++i){var l=listeners[i];if(l&&l[this.EL]===el&&(!sType||sType===l[this.TYPE])){elListeners.push({type:l[this.TYPE],fn:l[this.FN],obj:l[this.OBJ],adjust:l[this.ADJ_SCOPE],index:i});}}}
return(elListeners.length)?elListeners:null;},_unload:function(e){var EU=YAHOO.util.Event,i,j,l,len,index;for(i=0,len=unloadListeners.length;i<len;++i){l=unloadListeners[i];if(l){var scope=window;if(l[EU.ADJ_SCOPE]){if(l[EU.ADJ_SCOPE]===true){scope=l[EU.OBJ];}else{scope=l[EU.ADJ_SCOPE];}}
l[EU.FN].call(scope,EU.getEvent(e),l[EU.OBJ]);unloadListeners[i]=null;l=null;scope=null;}}
unloadListeners=null;if(listeners&&listeners.length>0){j=listeners.length;while(j){index=j-1;l=listeners[index];if(l){EU.removeListener(l[EU.EL],l[EU.TYPE],l[EU.FN],index);}
j=j-1;}
l=null;EU.clearCache();}
for(i=0,len=legacyEvents.length;i<len;++i){legacyEvents[i][0]=null;legacyEvents[i]=null;}
legacyEvents=null;EU._simpleRemove(window,"unload",EU._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var dd=document.documentElement,db=document.body;if(dd&&(dd.scrollTop||dd.scrollLeft)){return[dd.scrollTop,dd.scrollLeft];}else if(db){return[db.scrollTop,db.scrollLeft];}else{return[0,0];}},_simpleAdd:function(){if(window.addEventListener){return function(el,sType,fn,capture){el.addEventListener(sType,fn,(capture));};}else if(window.attachEvent){return function(el,sType,fn,capture){el.attachEvent("on"+sType,fn);};}else{return function(){};}}(),_simpleRemove:function(){if(window.removeEventListener){return function(el,sType,fn,capture){el.removeEventListener(sType,fn,(capture));};}else if(window.detachEvent){return function(el,sType,fn){el.detachEvent("on"+sType,fn);};}else{return function(){};}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;if(document&&document.body){EU._load();}else{EU._simpleAdd(window,"load",EU._load);}
EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}
YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(p_type,p_fn,p_obj,p_override){this.__yui_events=this.__yui_events||{};var ce=this.__yui_events[p_type];if(ce){ce.subscribe(p_fn,p_obj,p_override);}else{this.__yui_subscribers=this.__yui_subscribers||{};var subs=this.__yui_subscribers;if(!subs[p_type]){subs[p_type]=[];}
subs[p_type].push({fn:p_fn,obj:p_obj,override:p_override});}},unsubscribe:function(p_type,p_fn,p_obj){this.__yui_events=this.__yui_events||{};var ce=this.__yui_events[p_type];if(ce){return ce.unsubscribe(p_fn,p_obj);}else{return false;}},createEvent:function(p_type,p_config){this.__yui_events=this.__yui_events||{};var opts=p_config||{};var events=this.__yui_events;if(events[p_type]){}else{var scope=opts.scope||this;var silent=opts.silent||null;var ce=new YAHOO.util.CustomEvent(p_type,scope,silent,YAHOO.util.CustomEvent.FLAT);events[p_type]=ce;if(opts.onSubscribeCallback){ce.subscribeEvent.subscribe(opts.onSubscribeCallback);}
this.__yui_subscribers=this.__yui_subscribers||{};var qs=this.__yui_subscribers[p_type];if(qs){for(var i=0;i<qs.length;++i){ce.subscribe(qs[i].fn,qs[i].obj,qs[i].override);}}}
return events[p_type];},fireEvent:function(p_type,arg1,arg2,etc){this.__yui_events=this.__yui_events||{};var ce=this.__yui_events[p_type];if(ce){var args=[];for(var i=1;i<arguments.length;++i){args.push(arguments[i]);}
return ce.fire.apply(ce,args);}else{return null;}},hasEvent:function(type){if(this.__yui_events){if(this.__yui_events[type]){return true;}}
return false;}};

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
yahoo-dom-event.js
*/

(function(){var Y=YAHOO.util,getStyle,setStyle,id_counter=0,propertyCache={};var ua=navigator.userAgent.toLowerCase(),isOpera=(ua.indexOf('opera')>-1),isSafari=(ua.indexOf('safari')>-1),isGecko=(!isOpera&&!isSafari&&ua.indexOf('gecko')>-1),isIE=(!isOpera&&ua.indexOf('msie')>-1);var patterns={HYPHEN:/(-[a-z])/i};var toCamel=function(property){if(!patterns.HYPHEN.test(property)){return property;}
if(propertyCache[property]){return propertyCache[property];}
while(patterns.HYPHEN.exec(property)){property=property.replace(RegExp.$1,RegExp.$1.substr(1).toUpperCase());}
propertyCache[property]=property;return property;};if(document.defaultView&&document.defaultView.getComputedStyle){getStyle=function(el,property){var value=null;var computed=document.defaultView.getComputedStyle(el,'');if(computed){value=computed[toCamel(property)];}
return el.style[property]||value;};}else if(document.documentElement.currentStyle&&isIE){getStyle=function(el,property){switch(toCamel(property)){case'opacity':var val=100;try{val=el.filters['DXImageTransform.Microsoft.Alpha'].opacity;}catch(e){try{val=el.filters('alpha').opacity;}catch(e){}}
return val/100;break;default:var value=el.currentStyle?el.currentStyle[property]:null;return(el.style[property]||value);}};}else{getStyle=function(el,property){return el.style[property];};}
if(isIE){setStyle=function(el,property,val){switch(property){case'opacity':if(typeof el.style.filter=='string'){el.style.filter='alpha(opacity='+val*100+')';if(!el.currentStyle||!el.currentStyle.hasLayout){el.style.zoom=1;}}
break;default:el.style[property]=val;}};}else{setStyle=function(el,property,val){el.style[property]=val;};}
YAHOO.util.Dom={get:function(el){if(!el){return null;}
if(typeof el!='string'&&!(el instanceof Array)){return el;}
if(typeof el=='string'){return document.getElementById(el);}
else{var collection=[];for(var i=0,len=el.length;i<len;++i){collection[collection.length]=Y.Dom.get(el[i]);}
return collection;}
return null;},getStyle:function(el,property){property=toCamel(property);var f=function(element){return getStyle(element,property);};return Y.Dom.batch(el,f,Y.Dom,true);},setStyle:function(el,property,val){property=toCamel(property);var f=function(element){setStyle(element,property,val);};Y.Dom.batch(el,f,Y.Dom,true);},getXY:function(el){var f=function(el){if(el.parentNode===null||el.offsetParent===null||this.getStyle(el,'display')=='none'){return false;}
var parentNode=null;var pos=[];var box;if(el.getBoundingClientRect){box=el.getBoundingClientRect();var doc=document;if(!this.inDocument(el)&&parent.document!=document){doc=parent.document;if(!this.isAncestor(doc.documentElement,el)){return false;}}
var scrollTop=Math.max(doc.documentElement.scrollTop,doc.body.scrollTop);var scrollLeft=Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft);return[box.left+scrollLeft,box.top+scrollTop];}
else{pos=[el.offsetLeft,el.offsetTop];parentNode=el.offsetParent;if(parentNode!=el){while(parentNode){pos[0]+=parentNode.offsetLeft;pos[1]+=parentNode.offsetTop;parentNode=parentNode.offsetParent;}}
if(isSafari&&this.getStyle(el,'position')=='absolute'){pos[0]-=document.body.offsetLeft;pos[1]-=document.body.offsetTop;}}
if(el.parentNode){parentNode=el.parentNode;}
else{parentNode=null;}
while(parentNode&&parentNode.tagName.toUpperCase()!='BODY'&&parentNode.tagName.toUpperCase()!='HTML')
{if(Y.Dom.getStyle(parentNode,'display')!='inline'){pos[0]-=parentNode.scrollLeft;pos[1]-=parentNode.scrollTop;}
if(parentNode.parentNode){parentNode=parentNode.parentNode;}else{parentNode=null;}}
return pos;};return Y.Dom.batch(el,f,Y.Dom,true);},getX:function(el){var f=function(el){return Y.Dom.getXY(el)[0];};return Y.Dom.batch(el,f,Y.Dom,true);},getY:function(el){var f=function(el){return Y.Dom.getXY(el)[1];};return Y.Dom.batch(el,f,Y.Dom,true);},setXY:function(el,pos,noRetry){var f=function(el){var style_pos=this.getStyle(el,'position');if(style_pos=='static'){this.setStyle(el,'position','relative');style_pos='relative';}
var pageXY=this.getXY(el);if(pageXY===false){return false;}
var delta=[parseInt(this.getStyle(el,'left'),10),parseInt(this.getStyle(el,'top'),10)];if(isNaN(delta[0])){delta[0]=(style_pos=='relative')?0:el.offsetLeft;}
if(isNaN(delta[1])){delta[1]=(style_pos=='relative')?0:el.offsetTop;}
if(pos[0]!==null){el.style.left=pos[0]-pageXY[0]+delta[0]+'px';}
if(pos[1]!==null){el.style.top=pos[1]-pageXY[1]+delta[1]+'px';}
if(!noRetry){var newXY=this.getXY(el);if((pos[0]!==null&&newXY[0]!=pos[0])||(pos[1]!==null&&newXY[1]!=pos[1])){this.setXY(el,pos,true);}}};Y.Dom.batch(el,f,Y.Dom,true);},setX:function(el,x){Y.Dom.setXY(el,[x,null]);},setY:function(el,y){Y.Dom.setXY(el,[null,y]);},getRegion:function(el){var f=function(el){var region=new Y.Region.getRegion(el);return region;};return Y.Dom.batch(el,f,Y.Dom,true);},getClientWidth:function(){return Y.Dom.getViewportWidth();},getClientHeight:function(){return Y.Dom.getViewportHeight();},getElementsByClassName:function(className,tag,root){var method=function(el){return Y.Dom.hasClass(el,className);};return Y.Dom.getElementsBy(method,tag,root);},hasClass:function(el,className){var re=new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)');var f=function(el){return re.test(el['className']);};return Y.Dom.batch(el,f,Y.Dom,true);},addClass:function(el,className){var f=function(el){if(this.hasClass(el,className)){return;}
el['className']=[el['className'],className].join(' ');};Y.Dom.batch(el,f,Y.Dom,true);},removeClass:function(el,className){var re=new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)','g');var f=function(el){if(!this.hasClass(el,className)){return;}
var c=el['className'];el['className']=c.replace(re,' ');if(this.hasClass(el,className)){this.removeClass(el,className);}};Y.Dom.batch(el,f,Y.Dom,true);},replaceClass:function(el,oldClassName,newClassName){if(oldClassName===newClassName){return false;}
var re=new RegExp('(?:^|\\s+)'+oldClassName+'(?:\\s+|$)','g');var f=function(el){if(!this.hasClass(el,oldClassName)){this.addClass(el,newClassName);return;}
el['className']=el['className'].replace(re,' '+newClassName+' ');if(this.hasClass(el,oldClassName)){this.replaceClass(el,oldClassName,newClassName);}};Y.Dom.batch(el,f,Y.Dom,true);},generateId:function(el,prefix){prefix=prefix||'yui-gen';el=el||{};var f=function(el){if(el){el=Y.Dom.get(el);}else{el={};}
if(!el.id){el.id=prefix+id_counter++;}
return el.id;};return Y.Dom.batch(el,f,Y.Dom,true);},isAncestor:function(haystack,needle){haystack=Y.Dom.get(haystack);if(!haystack||!needle){return false;}
var f=function(needle){if(haystack.contains&&!isSafari){return haystack.contains(needle);}
else if(haystack.compareDocumentPosition){return!!(haystack.compareDocumentPosition(needle)&16);}
else{var parent=needle.parentNode;while(parent){if(parent==haystack){return true;}
else if(!parent.tagName||parent.tagName.toUpperCase()=='HTML'){return false;}
parent=parent.parentNode;}
return false;}};return Y.Dom.batch(needle,f,Y.Dom,true);},inDocument:function(el){var f=function(el){return this.isAncestor(document.documentElement,el);};return Y.Dom.batch(el,f,Y.Dom,true);},getElementsBy:function(method,tag,root){tag=tag||'*';var nodes=[];if(root){root=Y.Dom.get(root);if(!root){return nodes;}}else{root=document;}
var elements=root.getElementsByTagName(tag);if(!elements.length&&(tag=='*'&&root.all)){elements=root.all;}
for(var i=0,len=elements.length;i<len;++i){if(method(elements[i])){nodes[nodes.length]=elements[i];}}
return nodes;},batch:function(el,method,o,override){var id=el;el=Y.Dom.get(el);var scope=(override)?o:window;if(!el||el.tagName||!el.length){if(!el){return false;}
return method.call(scope,el,o);}
var collection=[];for(var i=0,len=el.length;i<len;++i){if(!el[i]){id=el[i];}
collection[collection.length]=method.call(scope,el[i],o);}
return collection;},getDocumentHeight:function(){var scrollHeight=(document.compatMode!='CSS1Compat')?document.body.scrollHeight:document.documentElement.scrollHeight;var h=Math.max(scrollHeight,Y.Dom.getViewportHeight());return h;},getDocumentWidth:function(){var scrollWidth=(document.compatMode!='CSS1Compat')?document.body.scrollWidth:document.documentElement.scrollWidth;var w=Math.max(scrollWidth,Y.Dom.getViewportWidth());return w;},getViewportHeight:function(){var height=self.innerHeight;var mode=document.compatMode;if((mode||isIE)&&!isOpera){height=(mode=='CSS1Compat')?document.documentElement.clientHeight:document.body.clientHeight;}
return height;},getViewportWidth:function(){var width=self.innerWidth;var mode=document.compatMode;if(mode||isIE){width=(mode=='CSS1Compat')?document.documentElement.clientWidth:document.body.clientWidth;}
return width;}};})();YAHOO.util.Region=function(t,r,b,l){this.top=t;this[1]=t;this.right=r;this.bottom=b;this.left=l;this[0]=l;};YAHOO.util.Region.prototype.contains=function(region){return(region.left>=this.left&&region.right<=this.right&&region.top>=this.top&&region.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(region){var t=Math.max(this.top,region.top);var r=Math.min(this.right,region.right);var b=Math.min(this.bottom,region.bottom);var l=Math.max(this.left,region.left);if(b>=t&&r>=l){return new YAHOO.util.Region(t,r,b,l);}else{return null;}};YAHOO.util.Region.prototype.union=function(region){var t=Math.min(this.top,region.top);var r=Math.max(this.right,region.right);var b=Math.max(this.bottom,region.bottom);var l=Math.min(this.left,region.left);return new YAHOO.util.Region(t,r,b,l);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(el){var p=YAHOO.util.Dom.getXY(el);var t=p[1];var r=p[0]+el.offsetWidth;var b=p[1]+el.offsetHeight;var l=p[0];return new YAHOO.util.Region(t,r,b,l);};YAHOO.util.Point=function(x,y){if(x instanceof Array){y=x[1];x=x[0];}
this.x=this.right=this.left=this[0]=x;this.y=this.top=this.bottom=this[1]=y;};YAHOO.util.Point.prototype=new YAHOO.util.Region();


/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
connection-min.js
*/
YAHOO.util.Connect={_msxml_progid:['MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'],_http_header:{},_has_http_headers:false,_use_default_post_header:true,_default_post_header:'application/x-www-form-urlencoded',_isFormSubmit:false,_isFileUpload:false,_formNode:null,_sFormData:null,_poll:{},_timeOut:{},_polling_interval:50,_transaction_id:0,setProgId:function(id)
{this._msxml_progid.unshift(id);},setDefaultPostHeader:function(b)
{this._use_default_post_header=b;},setPollingInterval:function(i)
{if(typeof i=='number'&&isFinite(i)){this._polling_interval=i;}},createXhrObject:function(transactionId)
{var obj,http;try
{http=new XMLHttpRequest();obj={conn:http,tId:transactionId};}
catch(e)
{for(var i=0;i<this._msxml_progid.length;++i){try
{http=new ActiveXObject(this._msxml_progid[i]);obj={conn:http,tId:transactionId};break;}
catch(e){}}}
finally
{return obj;}},getConnectionObject:function()
{var o;var tId=this._transaction_id;try
{o=this.createXhrObject(tId);if(o){this._transaction_id++;}}
catch(e){}
finally
{return o;}},asyncRequest:function(method,uri,callback,postData)
{var o=this.getConnectionObject();if(!o){return null;}
else{if(this._isFormSubmit){if(this._isFileUpload){this.uploadFile(o.tId,callback,uri,postData);this.releaseObject(o);return;}
if(method=='GET'){if(this._sFormData.length!=0){uri+=((uri.indexOf('?')==-1)?'?':'&')+this._sFormData;}
else{uri+="?"+this._sFormData;}}
else if(method=='POST'){postData=postData?this._sFormData+"&"+postData:this._sFormData;}}
o.conn.open(method,uri,true);if(this._isFormSubmit||(postData&&this._use_default_post_header)){this.initHeader('Content-Type',this._default_post_header);if(this._isFormSubmit){this.resetFormState();}}
if(this._has_http_headers){this.setHeader(o);}
this.handleReadyState(o,callback);o.conn.send(postData||null);return o;}},handleReadyState:function(o,callback)
{var oConn=this;if(callback&&callback.timeout){this._timeOut[o.tId]=window.setTimeout(function(){oConn.abort(o,callback,true);},callback.timeout);}
this._poll[o.tId]=window.setInterval(function(){if(o.conn&&o.conn.readyState==4){window.clearInterval(oConn._poll[o.tId]);delete oConn._poll[o.tId];if(callback&&callback.timeout){delete oConn._timeOut[o.tId];}
oConn.handleTransactionResponse(o,callback);}},this._polling_interval);},handleTransactionResponse:function(o,callback,isAbort)
{if(!callback){this.releaseObject(o);return;}
var httpStatus,responseObject;try
{if(o.conn.status!==undefined&&o.conn.status!=0){httpStatus=o.conn.status;}
else{httpStatus=13030;}}
catch(e){httpStatus=13030;}
if(httpStatus>=200&&httpStatus<300){try
{responseObject=this.createResponseObject(o,callback.argument);if(callback.success){if(!callback.scope){callback.success(responseObject);}
else{callback.success.apply(callback.scope,[responseObject]);}}}
catch(e){}}
else{try
{switch(httpStatus){case 12002:case 12029:case 12030:case 12031:case 12152:case 13030:responseObject=this.createExceptionObject(o.tId,callback.argument,(isAbort?isAbort:false));if(callback.failure){if(!callback.scope){callback.failure(responseObject);}
else{callback.failure.apply(callback.scope,[responseObject]);}}
break;default:responseObject=this.createResponseObject(o,callback.argument);if(callback.failure){if(!callback.scope){callback.failure(responseObject);}
else{callback.failure.apply(callback.scope,[responseObject]);}}}}
catch(e){}}
this.releaseObject(o);responseObject=null;},createResponseObject:function(o,callbackArg)
{var obj={};var headerObj={};try
{var headerStr=o.conn.getAllResponseHeaders();var header=headerStr.split('\n');for(var i=0;i<header.length;i++){var delimitPos=header[i].indexOf(':');if(delimitPos!=-1){headerObj[header[i].substring(0,delimitPos)]=header[i].substring(delimitPos+2);}}}
catch(e){}
obj.tId=o.tId;obj.status=o.conn.status;obj.statusText=o.conn.statusText;obj.getResponseHeader=headerObj;obj.getAllResponseHeaders=headerStr;obj.responseText=o.conn.responseText;obj.responseXML=o.conn.responseXML;if(typeof callbackArg!==undefined){obj.argument=callbackArg;}
return obj;},createExceptionObject:function(tId,callbackArg,isAbort)
{var COMM_CODE=0;var COMM_ERROR='communication failure';var ABORT_CODE=-1;var ABORT_ERROR='transaction aborted';var obj={};obj.tId=tId;if(isAbort){obj.status=ABORT_CODE;obj.statusText=ABORT_ERROR;}
else{obj.status=COMM_CODE;obj.statusText=COMM_ERROR;}
if(callbackArg){obj.argument=callbackArg;}
return obj;},initHeader:function(label,value)
{if(this._http_header[label]===undefined){this._http_header[label]=value;}
else{this._http_header[label]=value+","+this._http_header[label];}
this._has_http_headers=true;},setHeader:function(o)
{for(var prop in this._http_header){if(this._http_header.hasOwnProperty(prop)){o.conn.setRequestHeader(prop,this._http_header[prop]);}}
delete this._http_header;this._http_header={};this._has_http_headers=false;},setForm:function(formId,isUpload,secureUri)
{this.resetFormState();var oForm;if(typeof formId=='string'){oForm=(document.getElementById(formId)||document.forms[formId]);}
else if(typeof formId=='object'){oForm=formId;}
else{return;}
if(isUpload){this.createFrame(secureUri?secureUri:null);this._isFormSubmit=true;this._isFileUpload=true;this._formNode=oForm;return;}
var oElement,oName,oValue,oDisabled;var hasSubmit=false;for(var i=0;i<oForm.elements.length;i++){oElement=oForm.elements[i];oDisabled=oForm.elements[i].disabled;oName=oForm.elements[i].name;oValue=oForm.elements[i].value;if(!oDisabled&&oName)
{switch(oElement.type)
{case'select-one':case'select-multiple':for(var j=0;j<oElement.options.length;j++){if(oElement.options[j].selected){if(window.ActiveXObject){this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text)+'&';}
else{this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text)+'&';}}}
break;case'radio':case'checkbox':if(oElement.checked){this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oValue)+'&';}
break;case'file':case undefined:case'reset':case'button':break;case'submit':if(hasSubmit==false){this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oValue)+'&';hasSubmit=true;}
break;default:this._sFormData+=encodeURIComponent(oName)+'='+encodeURIComponent(oValue)+'&';break;}}}
this._isFormSubmit=true;this._sFormData=this._sFormData.substr(0,this._sFormData.length-1);return this._sFormData;},resetFormState:function(){this._isFormSubmit=false;this._isFileUpload=false;this._formNode=null;this._sFormData="";},createFrame:function(secureUri){var frameId='yuiIO'+this._transaction_id;if(window.ActiveXObject){var io=document.createElement('<iframe id="'+frameId+'" name="'+frameId+'" />');if(typeof secureUri=='boolean'){io.src='javascript:false';}
else if(typeof secureURI=='string'){io.src=secureUri;}}
else{var io=document.createElement('iframe');io.id=frameId;io.name=frameId;}
io.style.position='absolute';io.style.top='-1000px';io.style.left='-1000px';document.body.appendChild(io);},appendPostData:function(postData)
{var formElements=[];var postMessage=postData.split('&');for(var i=0;i<postMessage.length;i++){var delimitPos=postMessage[i].indexOf('=');if(delimitPos!=-1){formElements[i]=document.createElement('input');formElements[i].type='hidden';formElements[i].name=postMessage[i].substring(0,delimitPos);formElements[i].value=postMessage[i].substring(delimitPos+1);this._formNode.appendChild(formElements[i]);}}
return formElements;},uploadFile:function(id,callback,uri,postData){var frameId='yuiIO'+id;var io=document.getElementById(frameId);this._formNode.action=uri;this._formNode.method='POST';this._formNode.target=frameId;if(this._formNode.encoding){this._formNode.encoding='multipart/form-data';}
else{this._formNode.enctype='multipart/form-data';}
if(postData){var oElements=this.appendPostData(postData);}
this._formNode.submit();if(oElements&&oElements.length>0){try
{for(var i=0;i<oElements.length;i++){this._formNode.removeChild(oElements[i]);}}
catch(e){}}
this.resetFormState();var uploadCallback=function()
{var obj={};obj.tId=id;obj.argument=callback.argument;try
{obj.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;obj.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}
catch(e){}
if(callback.upload){if(!callback.scope){callback.upload(obj);}
else{callback.upload.apply(callback.scope,[obj]);}}
if(YAHOO.util.Event){YAHOO.util.Event.removeListener(io,"load",uploadCallback);}
else if(window.detachEvent){io.detachEvent('onload',uploadCallback);}
else{io.removeEventListener('load',uploadCallback,false);}
setTimeout(function(){document.body.removeChild(io);},100);};if(YAHOO.util.Event){YAHOO.util.Event.addListener(io,"load",uploadCallback);}
else if(window.attachEvent){io.attachEvent('onload',uploadCallback);}
else{io.addEventListener('load',uploadCallback,false);}},abort:function(o,callback,isTimeout)
{if(this.isCallInProgress(o)){o.conn.abort();window.clearInterval(this._poll[o.tId]);delete this._poll[o.tId];if(isTimeout){delete this._timeOut[o.tId];}
this.handleTransactionResponse(o,callback,true);return true;}
else{return false;}},isCallInProgress:function(o)
{if(o.conn){return o.conn.readyState!=4&&o.conn.readyState!=0;}
else{return false;}},releaseObject:function(o)
{o.conn=null;o=null;}};


/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2

tabview-min.js
*/

YAHOO.util.Lang={isArray:function(val){if(val.constructor&&val.constructor.toString().indexOf('Array')>-1){return true;}else{return YAHOO.util.Lang.isObject(val)&&val.constructor==Array;}},isBoolean:function(val){return typeof val=='boolean';},isFunction:function(val){return typeof val=='function';},isNull:function(val){return val===null;},isNumber:function(val){return!isNaN(val);},isObject:function(val){return typeof val=='object'||YAHOO.util.Lang.isFunction(val);},isString:function(val){return typeof val=='string';},isUndefined:function(val){return typeof val=='undefined';}};YAHOO.util.Attribute=function(hash,owner){if(owner){this.owner=owner;this.configure(hash,true);}};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,validator:null,getValue:function(){return this.value;},setValue:function(value,silent){var beforeRetVal;var owner=this.owner;var name=this.name;var event={type:name,prevValue:this.getValue(),newValue:value};if(this.readOnly||(this.writeOnce&&this._written)){return false;}
if(this.validator&&!this.validator.call(owner,value)){return false;}
if(!silent){beforeRetVal=owner.fireBeforeChangeEvent(event);if(beforeRetVal===false){return false;}}
if(this.method){this.method.call(owner,value);}
this.value=value;this._written=true;event.type=name;if(!silent){this.owner.fireChangeEvent(event);}
return true;},configure:function(map,init){map=map||{};this._written=false;this._initialConfig=this._initialConfig||{};for(var key in map){if(key&&map.hasOwnProperty(key)){this[key]=map[key];if(init){this._initialConfig[key]=map[key];}}}},resetValue:function(){return this.setValue(this._initialConfig.value);},resetConfig:function(){this.configure(this._initialConfig);},refresh:function(silent){this.setValue(this.value,silent);}};(function(){var Lang=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(key){var configs=this._configs||{};var config=configs[key];if(!config){return undefined;}
return config.value;},set:function(key,value,silent){var configs=this._configs||{};var config=configs[key];if(!config){return false;}
return config.setValue(value,silent);},getAttributeKeys:function(){var configs=this._configs;var keys=[];var config;for(var key in configs){config=configs[key];if(configs.hasOwnProperty(key)&&!Lang.isUndefined(config)){keys[keys.length]=key;}}
return keys;},setAttributes:function(map,silent){for(var key in map){if(map.hasOwnProperty(key)){this.set(key,map[key],silent);}}},resetValue:function(key,silent){var configs=this._configs||{};if(configs[key]){this.set(key,configs[key]._initialConfig.value,silent);return true;}
return false;},refresh:function(key,silent){var configs=this._configs;key=((Lang.isString(key))?[key]:key)||this.getAttributeKeys();for(var i=0,len=key.length;i<len;++i){if(configs[key[i]]&&!Lang.isUndefined(configs[key[i]].value)&&!Lang.isNull(configs[key[i]].value)){configs[key[i]].refresh(silent);}}},register:function(key,map){this._configs=this._configs||{};if(this._configs[key]){return false;}
map.name=key;this._configs[key]=new YAHOO.util.Attribute(map,this);return true;},getAttributeConfig:function(key){var configs=this._configs||{};var config=configs[key]||{};var map={};for(key in config){if(config.hasOwnProperty(key)){map[key]=config[key];}}
return map;},configureAttribute:function(key,map,init){var configs=this._configs||{};if(!configs[key]){return false;}
configs[key].configure(map,init);},resetAttributeConfig:function(key){var configs=this._configs||{};configs[key].resetConfig();},fireBeforeChangeEvent:function(e){var type='before';type+=e.type.charAt(0).toUpperCase()+e.type.substr(1)+'Change';e.type=type;return this.fireEvent(e.type,e);},fireChangeEvent:function(e){e.type+='Change';return this.fireEvent(e.type,e);}};YAHOO.augment(YAHOO.util.AttributeProvider,YAHOO.util.EventProvider);})();(function(){var Dom=YAHOO.util.Dom,Lang=YAHOO.util.Lang,EventPublisher=YAHOO.util.EventPublisher,AttributeProvider=YAHOO.util.AttributeProvider;YAHOO.util.Element=function(el,map){if(arguments.length){this.init(el,map);}};YAHOO.util.Element.prototype={DOM_EVENTS:null,appendChild:function(child){child=child.get?child.get('element'):child;this.get('element').appendChild(child);},getElementsByTagName:function(tag){return this.get('element').getElementsByTagName(tag);},hasChildNodes:function(){return this.get('element').hasChildNodes();},insertBefore:function(element,before){element=element.get?element.get('element'):element;before=(before&&before.get)?before.get('element'):before;this.get('element').insertBefore(element,before);},removeChild:function(child){child=child.get?child.get('element'):child;this.get('element').removeChild(child);return true;},replaceChild:function(newNode,oldNode){newNode=newNode.get?newNode.get('element'):newNode;oldNode=oldNode.get?oldNode.get('element'):oldNode;return this.get('element').replaceChild(newNode,oldNode);},initAttributes:function(map){map=map||{};var element=Dom.get(map.element)||null;this.register('element',{value:element,readOnly:true});},addListener:function(type,fn,obj,scope){var el=this.get('element');var scope=scope||this;el=this.get('id')||el;if(!this._events[type]){if(this.DOM_EVENTS[type]){YAHOO.util.Event.addListener(el,type,function(e){if(e.srcElement&&!e.target){e.target=e.srcElement;}
this.fireEvent(type,e);},obj,scope);}
this.createEvent(type,this);this._events[type]=true;}
this.subscribe.apply(this,arguments);},on:function(){this.addListener.apply(this,arguments);},removeListener:function(type,fn){this.unsubscribe.apply(this,arguments);},addClass:function(className){Dom.addClass(this.get('element'),className);},getElementsByClassName:function(className,tag){return Dom.getElementsByClassName(className,tag,this.get('element'));},hasClass:function(className){return Dom.hasClass(this.get('element'),className);},removeClass:function(className){return Dom.removeClass(this.get('element'),className);},replaceClass:function(oldClassName,newClassName){return Dom.replaceClass(this.get('element'),oldClassName,newClassName);},setStyle:function(property,value){return Dom.setStyle(this.get('element'),property,value);},getStyle:function(property){return Dom.getStyle(this.get('element'),property);},fireQueue:function(){var queue=this._queue;for(var i=0,len=queue.length;i<len;++i){this[queue[i][0]].apply(this,queue[i][1]);}},appendTo:function(parent,before){parent=(parent.get)?parent.get('element'):Dom.get(parent);before=(before&&before.get)?before.get('element'):Dom.get(before);var element=this.get('element');var newAddition=!Dom.inDocument(element);if(!element){return false;}
if(!parent){return false;}
if(element.parent!=parent){if(before){parent.insertBefore(element,before);}else{parent.appendChild(element);}}
if(!newAddition){return false;}
var keys=this.getAttributeKeys();for(var key in keys){if(!Lang.isUndefined(element[key])){this.refresh(key);}}},get:function(key){var configs=this._configs||{};var el=configs.element;if(el&&!configs[key]&&!Lang.isUndefined(el.value[key])){return el.value[key];}
return AttributeProvider.prototype.get.call(this,key);},set:function(key,value,silent){var el=this.get('element');if(!el){this._queue[this._queue.length]=['set',arguments];return false;}
if(!this._configs[key]&&!Lang.isUndefined(el[key])){_registerHTMLAttr.call(this,key);}
return AttributeProvider.prototype.set.apply(this,arguments);},register:function(key){var configs=this._configs||{};var element=this.get('element')||null;if(element&&!Lang.isUndefined(element[key])){return false;}
return AttributeProvider.prototype.register.apply(this,arguments);},configureAttribute:function(property,map,init){var el=this.get('element');if(!el){this._queue[this._queue.length]=['configureAttribute',arguments];return;}
if(!this._configs[property]&&!Lang.isUndefined(el[property])){_registerHTMLAttr.call(this,property,map);}
return AttributeProvider.prototype.configureAttribute.apply(this,arguments);},getAttributeKeys:function(){var el=this.get('element');var keys=AttributeProvider.prototype.getAttributeKeys.call(this);for(var key in el){if(!this._configs[key]){keys[key]=keys[key]||el[key];}}
return keys;},init:function(el,attr){this._queue=this._queue||[];this._events=this._events||{};this._configs=this._configs||{};attr=attr||{};attr.element=attr.element||el||null;this.DOM_EVENTS={'click':true,'keydown':true,'keypress':true,'keyup':true,'mousedown':true,'mousemove':true,'mouseout':true,'mouseover':true,'mouseup':true};var readyHandler=function(){this.initAttributes(attr);this.setAttributes(attr,true);this.fireQueue();this.fireEvent('contentReady',{type:'contentReady',target:attr.element});};if(Lang.isString(el)){_registerHTMLAttr.call(this,'id',{value:el});YAHOO.util.Event.onAvailable(el,function(){attr.element=Dom.get(el);this.fireEvent('available',{type:'available',target:attr.element});},this,true);YAHOO.util.Event.onContentReady(el,function(){readyHandler.call(this);},this,true);}else{readyHandler.call(this);}}};var _registerHTMLAttr=function(key,map){var el=this.get('element');map=map||{};map.name=key;map.method=map.method||function(value){el[key]=value;};map.value=map.value||el[key];this._configs[key]=new YAHOO.util.Attribute(map,this);};YAHOO.augment(YAHOO.util.Element,AttributeProvider);})();(function(){var Dom=YAHOO.util.Dom,Event=YAHOO.util.Event,Lang=YAHOO.util.Lang;var Tab=function(el,attr){attr=attr||{};if(arguments.length==1&&!Lang.isString(el)&&!el.nodeName){attr=el;el=attr.element;}
if(!el&&!attr.element){el=_createTabElement.call(this,attr);}
this.loadHandler={success:function(o){this.set('content',o.responseText);},failure:function(o){}};Tab.superclass.constructor.call(this,el,attr);this.DOM_EVENTS={};};YAHOO.extend(Tab,YAHOO.util.Element);var proto=Tab.prototype;proto.LABEL_TAGNAME='em';proto.ACTIVE_CLASSNAME='selected';proto.DISABLED_CLASSNAME='disabled';proto.LOADING_CLASSNAME='loading';proto.dataConnection=null;proto.loadHandler=null;proto.toString=function(){var el=this.get('element');var id=el.id||el.tagName;return"Tab "+id;};proto.initAttributes=function(attr){attr=attr||{};Tab.superclass.initAttributes.call(this,attr);var el=this.get('element');this.register('activationEvent',{value:attr.activationEvent||'click'});this.register('labelEl',{value:attr.labelEl||_getlabelEl.call(this),method:function(value){var current=this.get('labelEl');if(current){if(current==value){return false;}
this.replaceChild(value,current);}else if(el.firstChild){this.insertBefore(value,el.firstChild);}else{this.appendChild(value);}}});this.register('label',{value:attr.label||_getLabel.call(this),method:function(value){var labelEl=this.get('labelEl');if(!labelEl){this.set('labelEl',_createlabelEl.call(this));}
_setLabel.call(this,value);}});this.register('contentEl',{value:attr.contentEl||document.createElement('div'),method:function(value){var current=this.get('contentEl');if(current){if(current==value){return false;}
this.replaceChild(value,current);}}});this.register('content',{value:attr.content,method:function(value){this.get('contentEl').innerHTML=value;}});var _dataLoaded=false;this.register('dataSrc',{value:attr.dataSrc});this.register('cacheData',{value:attr.cacheData||false,validator:Lang.isBoolean});this.register('loadMethod',{value:attr.loadMethod||'GET',validator:Lang.isString});this.register('dataLoaded',{value:false,validator:Lang.isBoolean,writeOnce:true});this.register('dataTimeout',{value:attr.dataTimeout||null,validator:Lang.isNumber});this.register('active',{value:attr.active||this.hasClass(this.ACTIVE_CLASSNAME),method:function(value){if(value===true){this.addClass(this.ACTIVE_CLASSNAME);this.set('title','active');}else{this.removeClass(this.ACTIVE_CLASSNAME);this.set('title','');}},validator:function(value){return Lang.isBoolean(value)&&!this.get('disabled');}});this.register('disabled',{value:attr.disabled||this.hasClass(this.DISABLED_CLASSNAME),method:function(value){if(value===true){Dom.addClass(this.get('element'),this.DISABLED_CLASSNAME);}else{Dom.removeClass(this.get('element'),this.DISABLED_CLASSNAME);}},validator:Lang.isBoolean});this.register('href',{value:attr.href||'#',method:function(value){this.getElementsByTagName('a')[0].href=value;},validator:Lang.isString});this.register('contentVisible',{value:attr.contentVisible,method:function(value){if(value==true){this.get('contentEl').style.display='block';if(this.get('dataSrc')){if(!this.get('dataLoaded')||!this.get('cacheData')){_dataConnect.call(this);}}}else{this.get('contentEl').style.display='none';}},validator:Lang.isBoolean});};var _createTabElement=function(attr){var el=document.createElement('li');var a=document.createElement('a');a.href=attr.href||'#';el.appendChild(a);var label=attr.label||null;var labelEl=attr.labelEl||null;if(labelEl){if(!label){label=_getLabel.call(this,labelEl);}}else{labelEl=_createlabelEl.call(this);}
a.appendChild(labelEl);return el;};var _getlabelEl=function(){return this.getElementsByTagName(this.LABEL_TAGNAME)[0];};var _createlabelEl=function(){var el=document.createElement(this.LABEL_TAGNAME);return el;};var _setLabel=function(label){var el=this.get('labelEl');el.innerHTML=label;};var _getLabel=function(){var label,el=this.get('labelEl');if(!el){return undefined;}
return el.innerHTML;};var _dataConnect=function(){if(!YAHOO.util.Connect){return false;}
Dom.addClass(this.get('contentEl').parentNode,this.LOADING_CLASSNAME);this.dataConnection=YAHOO.util.Connect.asyncRequest(this.get('loadMethod'),this.get('dataSrc'),{success:function(o){this.loadHandler.success.call(this,o);this.set('dataLoaded',true);this.dataConnection=null;Dom.removeClass(this.get('contentEl').parentNode,this.LOADING_CLASSNAME);},failure:function(o){this.loadHandler.failure.call(this,o);this.dataConnection=null;Dom.removeClass(this.get('contentEl').parentNode,this.LOADING_CLASSNAME);},scope:this,timeout:this.get('dataTimeout')});};YAHOO.widget.Tab=Tab;})();(function(){YAHOO.widget.TabView=function(el,attr){attr=attr||{};if(arguments.length==1&&!Lang.isString(el)&&!el.nodeName){attr=el;el=attr.element||null;}
if(!el&&!attr.element){el=_createTabViewElement.call(this,attr);}
YAHOO.widget.TabView.superclass.constructor.call(this,el,attr);};YAHOO.extend(YAHOO.widget.TabView,YAHOO.util.Element);var proto=YAHOO.widget.TabView.prototype;var Dom=YAHOO.util.Dom;var Lang=YAHOO.util.Lang;var Event=YAHOO.util.Event;var Tab=YAHOO.widget.Tab;proto.CLASSNAME='yui-navset';proto.TAB_PARENT_CLASSNAME='yui-nav';proto.CONTENT_PARENT_CLASSNAME='yui-content';proto._tabParent=null;proto._contentParent=null;proto.addTab=function(tab,index){var tabs=this.get('tabs');if(!tabs){this._queue[this._queue.length]=['addTab',arguments];return false;}
index=(index===undefined)?tabs.length:index;var before=this.getTab(index);var self=this;var el=this.get('element');var tabParent=this._tabParent;var contentParent=this._contentParent;var tabElement=tab.get('element');var contentEl=tab.get('contentEl');if(before){tabParent.insertBefore(tabElement,before.get('element'));}else{tabParent.appendChild(tabElement);}
if(contentEl&&!Dom.isAncestor(contentParent,contentEl)){contentParent.appendChild(contentEl);}
if(!tab.get('active')){tab.set('contentVisible',false,true);}else{this.set('activeTab',tab,true);}
var activate=function(e){YAHOO.util.Event.preventDefault(e);self.set('activeTab',this);};tab.addListener(tab.get('activationEvent'),activate);tab.addListener('activationEventChange',function(e){if(e.prevValue!=e.newValue){tab.removeListener(e.prevValue,activate);tab.addListener(e.newValue,activate);}});tabs.splice(index,0,tab);};proto.DOMEventHandler=function(e){var el=this.get('element');var target=YAHOO.util.Event.getTarget(e);var tabParent=this._tabParent;if(Dom.isAncestor(tabParent,target)){var tabEl;var tab=null;var contentEl;var tabs=this.get('tabs');for(var i=0,len=tabs.length;i<len;i++){tabEl=tabs[i].get('element');contentEl=tabs[i].get('contentEl');if(target==tabEl||Dom.isAncestor(tabEl,target)){tab=tabs[i];break;}}
if(tab){tab.fireEvent(e.type,e);}}};proto.getTab=function(index){return this.get('tabs')[index];};proto.getTabIndex=function(tab){var index=null;var tabs=this.get('tabs');for(var i=0,len=tabs.length;i<len;++i){if(tab==tabs[i]){index=i;break;}}
return index;};proto.removeTab=function(tab){var tabCount=this.get('tabs').length;var index=this.getTabIndex(tab);var nextIndex=index+1;if(tab==this.get('activeTab')){if(tabCount>1){if(index+1==tabCount){this.set('activeIndex',index-1);}else{this.set('activeIndex',index+1);}}}
this._tabParent.removeChild(tab.get('element'));this._contentParent.removeChild(tab.get('contentEl'));this._configs.tabs.value.splice(index,1);};proto.toString=function(){var name=this.get('id')||this.get('tagName');return"TabView "+name;};proto.contentTransition=function(newTab,oldTab){newTab.set('contentVisible',true);oldTab.set('contentVisible',false);};proto.initAttributes=function(attr){YAHOO.widget.TabView.superclass.initAttributes.call(this,attr);if(!attr.orientation){attr.orientation='top';}
var el=this.get('element');this.register('tabs',{value:[],readOnly:true});this._tabParent=this.getElementsByClassName(this.TAB_PARENT_CLASSNAME,'ul')[0]||_createTabParent.call(this);this._contentParent=this.getElementsByClassName(this.CONTENT_PARENT_CLASSNAME,'div')[0]||_createContentParent.call(this);this.register('orientation',{value:attr.orientation,method:function(value){var current=this.get('orientation');this.addClass('yui-navset-'+value);if(current!=value){this.removeClass('yui-navset-'+current);}
switch(value){case'bottom':this.appendChild(this._tabParent);break;}}});this.register('activeIndex',{value:attr.activeIndex,method:function(value){this.set('activeTab',this.getTab(value));},validator:function(value){return!this.getTab(value).get('disabled');}});this.register('activeTab',{value:attr.activeTab,method:function(tab){var activeTab=this.get('activeTab');if(tab){tab.set('active',true);}
if(activeTab&&activeTab!=tab){activeTab.set('active',false);}
if(activeTab&&tab!=activeTab){this.contentTransition(tab,activeTab);}else if(tab){tab.set('contentVisible',true);}},validator:function(value){return!value.get('disabled');}});if(this._tabParent){_initTabs.call(this);}
for(var type in this.DOM_EVENTS){if(this.DOM_EVENTS.hasOwnProperty(type)){this.addListener.call(this,type,this.DOMEventHandler);}}};var _initTabs=function(){var tab,attr,contentEl;var el=this.get('element');var tabs=_getChildNodes(this._tabParent);var contentElements=_getChildNodes(this._contentParent);for(var i=0,len=tabs.length;i<len;++i){attr={};if(contentElements[i]){attr.contentEl=contentElements[i];}
tab=new YAHOO.widget.Tab(tabs[i],attr);this.addTab(tab);if(tab.hasClass(tab.ACTIVE_CLASSNAME)){this._configs.activeTab.value=tab;}}};var _createTabViewElement=function(attr){var el=document.createElement('div');if(this.CLASSNAME){el.className=this.CLASSNAME;}
return el;};var _createTabParent=function(attr){var el=document.createElement('ul');if(this.TAB_PARENT_CLASSNAME){el.className=this.TAB_PARENT_CLASSNAME;}
this.get('element').appendChild(el);return el;};var _createContentParent=function(attr){var el=document.createElement('div');if(this.CONTENT_PARENT_CLASSNAME){el.className=this.CONTENT_PARENT_CLASSNAME;}
this.get('element').appendChild(el);return el;};var _getChildNodes=function(el){var nodes=[];var childNodes=el.childNodes;for(var i=0,len=childNodes.length;i<len;++i){if(childNodes[i].nodeType==1){nodes[nodes.length]=childNodes[i];}}
return nodes;};})();



/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
*/


(function(){var Event=YAHOO.util.Event;var Dom=YAHOO.util.Dom;YAHOO.util.DragDrop=function(id,sGroup,config){if(id){this.init(id,sGroup,config);}};YAHOO.util.DragDrop.prototype={id:null,config:null,dragElId:null,handleElId:null,invalidHandleTypes:null,invalidHandleIds:null,invalidHandleClasses:null,startPageX:0,startPageY:0,groups:null,locked:false,lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isTarget:true,padding:null,_domRef:null,__ygDragDrop:true,constrainX:false,constrainY:false,minX:0,maxX:0,minY:0,maxY:0,maintainOffset:false,xTicks:null,yTicks:null,primaryButtonOnly:true,available:false,hasOuterHandles:false,b4StartDrag:function(x,y){},startDrag:function(x,y){},b4Drag:function(e){},onDrag:function(e){},onDragEnter:function(e,id){},b4DragOver:function(e){},onDragOver:function(e,id){},b4DragOut:function(e){},onDragOut:function(e,id){},b4DragDrop:function(e){},onDragDrop:function(e,id){},onInvalidDrop:function(e){},b4EndDrag:function(e){},endDrag:function(e){},b4MouseDown:function(e){},onMouseDown:function(e){},onMouseUp:function(e){},onAvailable:function(){},getEl:function(){if(!this._domRef){this._domRef=Dom.get(this.id);}
return this._domRef;},getDragEl:function(){return Dom.get(this.dragElId);},init:function(id,sGroup,config){this.initTarget(id,sGroup,config);Event.on(this.id,"mousedown",this.handleMouseDown,this,true);},initTarget:function(id,sGroup,config){this.config=config||{};this.DDM=YAHOO.util.DDM;this.groups={};if(typeof id!=="string"){YAHOO.log("id is not a string, assuming it is an HTMLElement");id=Dom.generateId(id);}
this.id=id;this.addToGroup((sGroup)?sGroup:"default");this.handleElId=id;Event.onAvailable(id,this.handleOnAvailable,this,true);this.setDragElId(id);this.invalidHandleTypes={A:"A"};this.invalidHandleIds={};this.invalidHandleClasses=[];this.applyConfig();},applyConfig:function(){this.padding=this.config.padding||[0,0,0,0];this.isTarget=(this.config.isTarget!==false);this.maintainOffset=(this.config.maintainOffset);this.primaryButtonOnly=(this.config.primaryButtonOnly!==false);},handleOnAvailable:function(){this.available=true;this.resetConstraints();this.onAvailable();},setPadding:function(iTop,iRight,iBot,iLeft){if(!iRight&&0!==iRight){this.padding=[iTop,iTop,iTop,iTop];}else if(!iBot&&0!==iBot){this.padding=[iTop,iRight,iTop,iRight];}else{this.padding=[iTop,iRight,iBot,iLeft];}},setInitPosition:function(diffX,diffY){var el=this.getEl();if(!this.DDM.verifyEl(el)){return;}
var dx=diffX||0;var dy=diffY||0;var p=Dom.getXY(el);this.initPageX=p[0]-dx;this.initPageY=p[1]-dy;this.lastPageX=p[0];this.lastPageY=p[1];this.setStartPosition(p);},setStartPosition:function(pos){var p=pos||Dom.getXY(this.getEl());this.deltaSetXY=null;this.startPageX=p[0];this.startPageY=p[1];},addToGroup:function(sGroup){this.groups[sGroup]=true;this.DDM.regDragDrop(this,sGroup);},removeFromGroup:function(sGroup){if(this.groups[sGroup]){delete this.groups[sGroup];}
this.DDM.removeDDFromGroup(this,sGroup);},setDragElId:function(id){this.dragElId=id;},setHandleElId:function(id){if(typeof id!=="string"){YAHOO.log("id is not a string, assuming it is an HTMLElement");id=Dom.generateId(id);}
this.handleElId=id;this.DDM.regHandle(this.id,id);},setOuterHandleElId:function(id){if(typeof id!=="string"){YAHOO.log("id is not a string, assuming it is an HTMLElement");id=Dom.generateId(id);}
Event.on(id,"mousedown",this.handleMouseDown,this,true);this.setHandleElId(id);this.hasOuterHandles=true;},unreg:function(){Event.removeListener(this.id,"mousedown",this.handleMouseDown);this._domRef=null;this.DDM._remove(this);},isLocked:function(){return(this.DDM.isLocked()||this.locked);},handleMouseDown:function(e,oDD){var button=e.which||e.button;if(this.primaryButtonOnly&&button>1){return;}
if(this.isLocked()){return;}
this.DDM.refreshCache(this.groups);var pt=new YAHOO.util.Point(Event.getPageX(e),Event.getPageY(e));if(!this.hasOuterHandles&&!this.DDM.isOverTarget(pt,this)){}else{if(this.clickValidator(e)){this.setStartPosition();this.b4MouseDown(e);this.onMouseDown(e);this.DDM.handleMouseDown(e,this);this.DDM.stopEvent(e);}else{}}},clickValidator:function(e){var target=Event.getTarget(e);return(this.isValidHandleChild(target)&&(this.id==this.handleElId||this.DDM.handleWasClicked(target,this.id)));},addInvalidHandleType:function(tagName){var type=tagName.toUpperCase();this.invalidHandleTypes[type]=type;},addInvalidHandleId:function(id){if(typeof id!=="string"){YAHOO.log("id is not a string, assuming it is an HTMLElement");id=Dom.generateId(id);}
this.invalidHandleIds[id]=id;},addInvalidHandleClass:function(cssClass){this.invalidHandleClasses.push(cssClass);},removeInvalidHandleType:function(tagName){var type=tagName.toUpperCase();delete this.invalidHandleTypes[type];},removeInvalidHandleId:function(id){if(typeof id!=="string"){YAHOO.log("id is not a string, assuming it is an HTMLElement");id=Dom.generateId(id);}
delete this.invalidHandleIds[id];},removeInvalidHandleClass:function(cssClass){for(var i=0,len=this.invalidHandleClasses.length;i<len;++i){if(this.invalidHandleClasses[i]==cssClass){delete this.invalidHandleClasses[i];}}},isValidHandleChild:function(node){var valid=true;var nodeName;try{nodeName=node.nodeName.toUpperCase();}catch(e){nodeName=node.nodeName;}
valid=valid&&!this.invalidHandleTypes[nodeName];valid=valid&&!this.invalidHandleIds[node.id];for(var i=0,len=this.invalidHandleClasses.length;valid&&i<len;++i){valid=!Dom.hasClass(node,this.invalidHandleClasses[i]);}
return valid;},setXTicks:function(iStartX,iTickSize){this.xTicks=[];this.xTickSize=iTickSize;var tickMap={};for(var i=this.initPageX;i>=this.minX;i=i-iTickSize){if(!tickMap[i]){this.xTicks[this.xTicks.length]=i;tickMap[i]=true;}}
for(i=this.initPageX;i<=this.maxX;i=i+iTickSize){if(!tickMap[i]){this.xTicks[this.xTicks.length]=i;tickMap[i]=true;}}
this.xTicks.sort(this.DDM.numericSort);},setYTicks:function(iStartY,iTickSize){this.yTicks=[];this.yTickSize=iTickSize;var tickMap={};for(var i=this.initPageY;i>=this.minY;i=i-iTickSize){if(!tickMap[i]){this.yTicks[this.yTicks.length]=i;tickMap[i]=true;}}
for(i=this.initPageY;i<=this.maxY;i=i+iTickSize){if(!tickMap[i]){this.yTicks[this.yTicks.length]=i;tickMap[i]=true;}}
this.yTicks.sort(this.DDM.numericSort);},setXConstraint:function(iLeft,iRight,iTickSize){this.leftConstraint=iLeft;this.rightConstraint=iRight;this.minX=this.initPageX-iLeft;this.maxX=this.initPageX+iRight;if(iTickSize){this.setXTicks(this.initPageX,iTickSize);}
this.constrainX=true;},clearConstraints:function(){this.constrainX=false;this.constrainY=false;this.clearTicks();},clearTicks:function(){this.xTicks=null;this.yTicks=null;this.xTickSize=0;this.yTickSize=0;},setYConstraint:function(iUp,iDown,iTickSize){this.topConstraint=iUp;this.bottomConstraint=iDown;this.minY=this.initPageY-iUp;this.maxY=this.initPageY+iDown;if(iTickSize){this.setYTicks(this.initPageY,iTickSize);}
this.constrainY=true;},resetConstraints:function(){if(this.initPageX||this.initPageX===0){var dx=(this.maintainOffset)?this.lastPageX-this.initPageX:0;var dy=(this.maintainOffset)?this.lastPageY-this.initPageY:0;this.setInitPosition(dx,dy);}else{this.setInitPosition();}
if(this.constrainX){this.setXConstraint(this.leftConstraint,this.rightConstraint,this.xTickSize);}
if(this.constrainY){this.setYConstraint(this.topConstraint,this.bottomConstraint,this.yTickSize);}},getTick:function(val,tickArray){if(!tickArray){return val;}else if(tickArray[0]>=val){return tickArray[0];}else{for(var i=0,len=tickArray.length;i<len;++i){var next=i+1;if(tickArray[next]&&tickArray[next]>=val){var diff1=val-tickArray[i];var diff2=tickArray[next]-val;return(diff2>diff1)?tickArray[i]:tickArray[next];}}
return tickArray[tickArray.length-1];}},toString:function(){return("DragDrop "+this.id);}};})();if(!YAHOO.util.DragDropMgr){YAHOO.util.DragDropMgr=function(){var Event=YAHOO.util.Event;return{ids:{},handleIds:{},dragCurrent:null,dragOvers:{},deltaX:0,deltaY:0,preventDefault:true,stopPropagation:true,initalized:false,locked:false,init:function(){this.initialized=true;},POINT:0,INTERSECT:1,STRICT_INTERSECT:2,mode:0,_execOnAll:function(sMethod,args){for(var i in this.ids){for(var j in this.ids[i]){var oDD=this.ids[i][j];if(!this.isTypeOfDD(oDD)){continue;}
oDD[sMethod].apply(oDD,args);}}},_onLoad:function(){this.init();Event.on(document,"mouseup",this.handleMouseUp,this,true);Event.on(document,"mousemove",this.handleMouseMove,this,true);Event.on(window,"unload",this._onUnload,this,true);Event.on(window,"resize",this._onResize,this,true);},_onResize:function(e){this._execOnAll("resetConstraints",[]);},lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isLocked:function(){return this.locked;},locationCache:{},useCache:true,clickPixelThresh:3,clickTimeThresh:1000,dragThreshMet:false,clickTimeout:null,startX:0,startY:0,regDragDrop:function(oDD,sGroup){if(!this.initialized){this.init();}
if(!this.ids[sGroup]){this.ids[sGroup]={};}
this.ids[sGroup][oDD.id]=oDD;},removeDDFromGroup:function(oDD,sGroup){if(!this.ids[sGroup]){this.ids[sGroup]={};}
var obj=this.ids[sGroup];if(obj&&obj[oDD.id]){delete obj[oDD.id];}},_remove:function(oDD){for(var g in oDD.groups){if(g&&this.ids[g][oDD.id]){delete this.ids[g][oDD.id];}}
delete this.handleIds[oDD.id];},regHandle:function(sDDId,sHandleId){if(!this.handleIds[sDDId]){this.handleIds[sDDId]={};}
this.handleIds[sDDId][sHandleId]=sHandleId;},isDragDrop:function(id){return(this.getDDById(id))?true:false;},getRelated:function(p_oDD,bTargetsOnly){var oDDs=[];for(var i in p_oDD.groups){for(j in this.ids[i]){var dd=this.ids[i][j];if(!this.isTypeOfDD(dd)){continue;}
if(!bTargetsOnly||dd.isTarget){oDDs[oDDs.length]=dd;}}}
return oDDs;},isLegalTarget:function(oDD,oTargetDD){var targets=this.getRelated(oDD,true);for(var i=0,len=targets.length;i<len;++i){if(targets[i].id==oTargetDD.id){return true;}}
return false;},isTypeOfDD:function(oDD){return(oDD&&oDD.__ygDragDrop);},isHandle:function(sDDId,sHandleId){return(this.handleIds[sDDId]&&this.handleIds[sDDId][sHandleId]);},getDDById:function(id){for(var i in this.ids){if(this.ids[i][id]){return this.ids[i][id];}}
return null;},handleMouseDown:function(e,oDD){this.currentTarget=YAHOO.util.Event.getTarget(e);this.dragCurrent=oDD;var el=oDD.getEl();this.startX=YAHOO.util.Event.getPageX(e);this.startY=YAHOO.util.Event.getPageY(e);this.deltaX=this.startX-el.offsetLeft;this.deltaY=this.startY-el.offsetTop;this.dragThreshMet=false;this.clickTimeout=setTimeout(function(){var DDM=YAHOO.util.DDM;DDM.startDrag(DDM.startX,DDM.startY);},this.clickTimeThresh);},startDrag:function(x,y){clearTimeout(this.clickTimeout);if(this.dragCurrent){this.dragCurrent.b4StartDrag(x,y);this.dragCurrent.startDrag(x,y);}
this.dragThreshMet=true;},handleMouseUp:function(e){if(!this.dragCurrent){return;}
clearTimeout(this.clickTimeout);if(this.dragThreshMet){this.fireEvents(e,true);}else{}
this.stopDrag(e);this.stopEvent(e);},stopEvent:function(e){if(this.stopPropagation){YAHOO.util.Event.stopPropagation(e);}
if(this.preventDefault){YAHOO.util.Event.preventDefault(e);}},stopDrag:function(e){if(this.dragCurrent){if(this.dragThreshMet){this.dragCurrent.b4EndDrag(e);this.dragCurrent.endDrag(e);}
this.dragCurrent.onMouseUp(e);}
this.dragCurrent=null;this.dragOvers={};},handleMouseMove:function(e){if(!this.dragCurrent){return true;}
if(YAHOO.util.Event.isIE&&!e.button){this.stopEvent(e);return this.handleMouseUp(e);}
if(!this.dragThreshMet){var diffX=Math.abs(this.startX-YAHOO.util.Event.getPageX(e));var diffY=Math.abs(this.startY-YAHOO.util.Event.getPageY(e));if(diffX>this.clickPixelThresh||diffY>this.clickPixelThresh){this.startDrag(this.startX,this.startY);}}
if(this.dragThreshMet){this.dragCurrent.b4Drag(e);this.dragCurrent.onDrag(e);this.fireEvents(e,false);}
this.stopEvent(e);return true;},fireEvents:function(e,isDrop){var dc=this.dragCurrent;if(!dc||dc.isLocked()){return;}
var x=YAHOO.util.Event.getPageX(e);var y=YAHOO.util.Event.getPageY(e);var pt=new YAHOO.util.Point(x,y);var oldOvers=[];var outEvts=[];var overEvts=[];var dropEvts=[];var enterEvts=[];for(var i in this.dragOvers){var ddo=this.dragOvers[i];if(!this.isTypeOfDD(ddo)){continue;}
if(!this.isOverTarget(pt,ddo,this.mode)){outEvts.push(ddo);}
oldOvers[i]=true;delete this.dragOvers[i];}
for(var sGroup in dc.groups){if("string"!=typeof sGroup){continue;}
for(i in this.ids[sGroup]){var oDD=this.ids[sGroup][i];if(!this.isTypeOfDD(oDD)){continue;}
if(oDD.isTarget&&!oDD.isLocked()&&oDD!=dc){if(this.isOverTarget(pt,oDD,this.mode)){if(isDrop){dropEvts.push(oDD);}else{if(!oldOvers[oDD.id]){enterEvts.push(oDD);}else{overEvts.push(oDD);}
this.dragOvers[oDD.id]=oDD;}}}}}
if(this.mode){if(outEvts.length){dc.b4DragOut(e,outEvts);dc.onDragOut(e,outEvts);}
if(enterEvts.length){dc.onDragEnter(e,enterEvts);}
if(overEvts.length){dc.b4DragOver(e,overEvts);dc.onDragOver(e,overEvts);}
if(dropEvts.length){dc.b4DragDrop(e,dropEvts);dc.onDragDrop(e,dropEvts);}}else{var len=0;for(i=0,len=outEvts.length;i<len;++i){dc.b4DragOut(e,outEvts[i].id);dc.onDragOut(e,outEvts[i].id);}
for(i=0,len=enterEvts.length;i<len;++i){dc.onDragEnter(e,enterEvts[i].id);}
for(i=0,len=overEvts.length;i<len;++i){dc.b4DragOver(e,overEvts[i].id);dc.onDragOver(e,overEvts[i].id);}
for(i=0,len=dropEvts.length;i<len;++i){dc.b4DragDrop(e,dropEvts[i].id);dc.onDragDrop(e,dropEvts[i].id);}}
if(isDrop&&!dropEvts.length){dc.onInvalidDrop(e);}},getBestMatch:function(dds){var winner=null;var len=dds.length;if(len==1){winner=dds[0];}else{for(var i=0;i<len;++i){var dd=dds[i];if(this.mode==this.INTERSECT&&dd.cursorIsOver){winner=dd;break;}else{if(!winner||!winner.overlap||(dd.overlap&&winner.overlap.getArea()<dd.overlap.getArea())){winner=dd;}}}}
return winner;},refreshCache:function(groups){for(var sGroup in groups){if("string"!=typeof sGroup){continue;}
for(var i in this.ids[sGroup]){var oDD=this.ids[sGroup][i];if(this.isTypeOfDD(oDD)){var loc=this.getLocation(oDD);if(loc){this.locationCache[oDD.id]=loc;}else{delete this.locationCache[oDD.id];}}}}},verifyEl:function(el){try{if(el){var parent=el.offsetParent;if(parent){return true;}}}catch(e){}
return false;},getLocation:function(oDD){if(!this.isTypeOfDD(oDD)){return null;}
var el=oDD.getEl(),pos,x1,x2,y1,y2,t,r,b,l;try{pos=YAHOO.util.Dom.getXY(el);}catch(e){}
if(!pos){return null;}
x1=pos[0];x2=x1+el.offsetWidth;y1=pos[1];y2=y1+el.offsetHeight;t=y1-oDD.padding[0];r=x2+oDD.padding[1];b=y2+oDD.padding[2];l=x1-oDD.padding[3];return new YAHOO.util.Region(t,r,b,l);},isOverTarget:function(pt,oTarget,intersect){var loc=this.locationCache[oTarget.id];if(!loc||!this.useCache){loc=this.getLocation(oTarget);this.locationCache[oTarget.id]=loc;}
if(!loc){return false;}
oTarget.cursorIsOver=loc.contains(pt);var dc=this.dragCurrent;if(!dc||!dc.getTargetCoord||(!intersect&&!dc.constrainX&&!dc.constrainY)){return oTarget.cursorIsOver;}
oTarget.overlap=null;var pos=dc.getTargetCoord(pt.x,pt.y);var el=dc.getDragEl();var curRegion=new YAHOO.util.Region(pos.y,pos.x+el.offsetWidth,pos.y+el.offsetHeight,pos.x);var overlap=curRegion.intersect(loc);if(overlap){oTarget.overlap=overlap;return(intersect)?true:oTarget.cursorIsOver;}else{return false;}},_onUnload:function(e,me){this.unregAll();},unregAll:function(){if(this.dragCurrent){this.stopDrag();this.dragCurrent=null;}
this._execOnAll("unreg",[]);for(i in this.elementCache){delete this.elementCache[i];}
this.elementCache={};this.ids={};},elementCache:{},getElWrapper:function(id){var oWrapper=this.elementCache[id];if(!oWrapper||!oWrapper.el){oWrapper=this.elementCache[id]=new this.ElementWrapper(YAHOO.util.Dom.get(id));}
return oWrapper;},getElement:function(id){return YAHOO.util.Dom.get(id);},getCss:function(id){var el=YAHOO.util.Dom.get(id);return(el)?el.style:null;},ElementWrapper:function(el){this.el=el||null;this.id=this.el&&el.id;this.css=this.el&&el.style;},getPosX:function(el){return YAHOO.util.Dom.getX(el);},getPosY:function(el){return YAHOO.util.Dom.getY(el);},swapNode:function(n1,n2){if(n1.swapNode){n1.swapNode(n2);}else{var p=n2.parentNode;var s=n2.nextSibling;if(s==n1){p.insertBefore(n1,n2);}else if(n2==n1.nextSibling){p.insertBefore(n2,n1);}else{n1.parentNode.replaceChild(n2,n1);p.insertBefore(n1,s);}}},getScroll:function(){var t,l,dde=document.documentElement,db=document.body;if(dde&&(dde.scrollTop||dde.scrollLeft)){t=dde.scrollTop;l=dde.scrollLeft;}else if(db){t=db.scrollTop;l=db.scrollLeft;}else{YAHOO.log("could not get scroll property");}
return{top:t,left:l};},getStyle:function(el,styleProp){return YAHOO.util.Dom.getStyle(el,styleProp);},getScrollTop:function(){return this.getScroll().top;},getScrollLeft:function(){return this.getScroll().left;},moveToEl:function(moveEl,targetEl){var aCoord=YAHOO.util.Dom.getXY(targetEl);YAHOO.util.Dom.setXY(moveEl,aCoord);},getClientHeight:function(){return YAHOO.util.Dom.getViewportHeight();},getClientWidth:function(){return YAHOO.util.Dom.getViewportWidth();},numericSort:function(a,b){return(a-b);},_timeoutCount:0,_addListeners:function(){var DDM=YAHOO.util.DDM;if(YAHOO.util.Event&&document){DDM._onLoad();}else{if(DDM._timeoutCount>2000){}else{setTimeout(DDM._addListeners,10);if(document&&document.body){DDM._timeoutCount+=1;}}}},handleWasClicked:function(node,id){if(this.isHandle(id,node.id)){return true;}else{var p=node.parentNode;while(p){if(this.isHandle(id,p.id)){return true;}else{p=p.parentNode;}}}
return false;}};}();YAHOO.util.DDM=YAHOO.util.DragDropMgr;YAHOO.util.DDM._addListeners();}
YAHOO.util.DD=function(id,sGroup,config){if(id){this.init(id,sGroup,config);}};YAHOO.extend(YAHOO.util.DD,YAHOO.util.DragDrop,{scroll:true,autoOffset:function(iPageX,iPageY){var x=iPageX-this.startPageX;var y=iPageY-this.startPageY;this.setDelta(x,y);},setDelta:function(iDeltaX,iDeltaY){this.deltaX=iDeltaX;this.deltaY=iDeltaY;},setDragElPos:function(iPageX,iPageY){var el=this.getDragEl();this.alignElWithMouse(el,iPageX,iPageY);},alignElWithMouse:function(el,iPageX,iPageY){var oCoord=this.getTargetCoord(iPageX,iPageY);if(!this.deltaSetXY){var aCoord=[oCoord.x,oCoord.y];YAHOO.util.Dom.setXY(el,aCoord);var newLeft=parseInt(YAHOO.util.Dom.getStyle(el,"left"),10);var newTop=parseInt(YAHOO.util.Dom.getStyle(el,"top"),10);this.deltaSetXY=[newLeft-oCoord.x,newTop-oCoord.y];}else{YAHOO.util.Dom.setStyle(el,"left",(oCoord.x+this.deltaSetXY[0])+"px");YAHOO.util.Dom.setStyle(el,"top",(oCoord.y+this.deltaSetXY[1])+"px");}
this.cachePosition(oCoord.x,oCoord.y);this.autoScroll(oCoord.x,oCoord.y,el.offsetHeight,el.offsetWidth);},cachePosition:function(iPageX,iPageY){if(iPageX){this.lastPageX=iPageX;this.lastPageY=iPageY;}else{var aCoord=YAHOO.util.Dom.getXY(this.getEl());this.lastPageX=aCoord[0];this.lastPageY=aCoord[1];}},autoScroll:function(x,y,h,w){if(this.scroll){var clientH=this.DDM.getClientHeight();var clientW=this.DDM.getClientWidth();var st=this.DDM.getScrollTop();var sl=this.DDM.getScrollLeft();var bot=h+y;var right=w+x;var toBot=(clientH+st-y-this.deltaY);var toRight=(clientW+sl-x-this.deltaX);var thresh=40;var scrAmt=(document.all)?80:30;if(bot>clientH&&toBot<thresh){window.scrollTo(sl,st+scrAmt);}
if(y<st&&st>0&&y-st<thresh){window.scrollTo(sl,st-scrAmt);}
if(right>clientW&&toRight<thresh){window.scrollTo(sl+scrAmt,st);}
if(x<sl&&sl>0&&x-sl<thresh){window.scrollTo(sl-scrAmt,st);}}},getTargetCoord:function(iPageX,iPageY){var x=iPageX-this.deltaX;var y=iPageY-this.deltaY;if(this.constrainX){if(x<this.minX){x=this.minX;}
if(x>this.maxX){x=this.maxX;}}
if(this.constrainY){if(y<this.minY){y=this.minY;}
if(y>this.maxY){y=this.maxY;}}
x=this.getTick(x,this.xTicks);y=this.getTick(y,this.yTicks);return{x:x,y:y};},applyConfig:function(){YAHOO.util.DD.superclass.applyConfig.call(this);this.scroll=(this.config.scroll!==false);},b4MouseDown:function(e){this.autoOffset(YAHOO.util.Event.getPageX(e),YAHOO.util.Event.getPageY(e));},b4Drag:function(e){this.setDragElPos(YAHOO.util.Event.getPageX(e),YAHOO.util.Event.getPageY(e));},toString:function(){return("DD "+this.id);}});YAHOO.util.DDProxy=function(id,sGroup,config){if(id){this.init(id,sGroup,config);this.initFrame();}};YAHOO.util.DDProxy.dragElId="ygddfdiv";YAHOO.extend(YAHOO.util.DDProxy,YAHOO.util.DD,{resizeFrame:true,centerFrame:false,createFrame:function(){var self=this;var body=document.body;if(!body||!body.firstChild){setTimeout(function(){self.createFrame();},50);return;}
var div=this.getDragEl();if(!div){div=document.createElement("div");div.id=this.dragElId;var s=div.style;s.position="absolute";s.visibility="hidden";s.cursor="move";s.border="2px solid #aaa";s.zIndex=999;body.insertBefore(div,body.firstChild);}},initFrame:function(){this.createFrame();},applyConfig:function(){YAHOO.util.DDProxy.superclass.applyConfig.call(this);this.resizeFrame=(this.config.resizeFrame!==false);this.centerFrame=(this.config.centerFrame);this.setDragElId(this.config.dragElId||YAHOO.util.DDProxy.dragElId);},showFrame:function(iPageX,iPageY){var el=this.getEl();var dragEl=this.getDragEl();var s=dragEl.style;this._resizeProxy();if(this.centerFrame){this.setDelta(Math.round(parseInt(s.width,10)/2),Math.round(parseInt(s.height,10)/2));}
this.setDragElPos(iPageX,iPageY);YAHOO.util.Dom.setStyle(dragEl,"visibility","visible");},_resizeProxy:function(){if(this.resizeFrame){var DOM=YAHOO.util.Dom;var el=this.getEl();var dragEl=this.getDragEl();var bt=parseInt(DOM.getStyle(dragEl,"borderTopWidth"),10);var br=parseInt(DOM.getStyle(dragEl,"borderRightWidth"),10);var bb=parseInt(DOM.getStyle(dragEl,"borderBottomWidth"),10);var bl=parseInt(DOM.getStyle(dragEl,"borderLeftWidth"),10);if(isNaN(bt)){bt=0;}
if(isNaN(br)){br=0;}
if(isNaN(bb)){bb=0;}
if(isNaN(bl)){bl=0;}
var newWidth=Math.max(0,el.offsetWidth-br-bl);var newHeight=Math.max(0,el.offsetHeight-bt-bb);DOM.setStyle(dragEl,"width",newWidth+"px");DOM.setStyle(dragEl,"height",newHeight+"px");}},b4MouseDown:function(e){var x=YAHOO.util.Event.getPageX(e);var y=YAHOO.util.Event.getPageY(e);this.autoOffset(x,y);this.setDragElPos(x,y);},b4StartDrag:function(x,y){this.showFrame(x,y);},b4EndDrag:function(e){YAHOO.util.Dom.setStyle(this.getDragEl(),"visibility","hidden");},endDrag:function(e){var DOM=YAHOO.util.Dom;var lel=this.getEl();var del=this.getDragEl();DOM.setStyle(del,"visibility","");DOM.setStyle(lel,"visibility","hidden");YAHOO.util.DDM.moveToEl(lel,del);DOM.setStyle(del,"visibility","hidden");DOM.setStyle(lel,"visibility","");},toString:function(){return("DDProxy "+this.id);}});YAHOO.util.DDTarget=function(id,sGroup,config){if(id){this.initTarget(id,sGroup,config);}};YAHOO.extend(YAHOO.util.DDTarget,YAHOO.util.DragDrop,{toString:function(){return("DDTarget "+this.id);}});



/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
container-min.js
*/

YAHOO.util.Config=function(owner){if(owner){this.init(owner);}};YAHOO.util.Config.prototype={owner:null,queueInProgress:false,checkBoolean:function(val){if(typeof val=='boolean'){return true;}else{return false;}},checkNumber:function(val){if(isNaN(val)){return false;}else{return true;}}};YAHOO.util.Config.prototype.init=function(owner){this.owner=owner;this.configChangedEvent=new YAHOO.util.CustomEvent("configChanged");this.queueInProgress=false;var config={};var initialConfig={};var eventQueue=[];var fireEvent=function(key,value){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event){property.event.fire(value);}};this.addProperty=function(key,propertyObject){key=key.toLowerCase();config[key]=propertyObject;propertyObject.event=new YAHOO.util.CustomEvent(key);propertyObject.key=key;if(propertyObject.handler){propertyObject.event.subscribe(propertyObject.handler,this.owner,true);}
this.setProperty(key,propertyObject.value,true);if(!propertyObject.suppressEvent){this.queueProperty(key,propertyObject.value);}};this.getConfig=function(){var cfg={};for(var prop in config){var property=config[prop];if(typeof property!='undefined'&&property.event){cfg[prop]=property.value;}}
return cfg;};this.getProperty=function(key){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event){return property.value;}else{return undefined;}};this.resetProperty=function(key){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event){if(initialConfig[key]&&initialConfig[key]!='undefined'){this.setProperty(key,initialConfig[key]);}
return true;}else{return false;}};this.setProperty=function(key,value,silent){key=key.toLowerCase();if(this.queueInProgress&&!silent){this.queueProperty(key,value);return true;}else{var property=config[key];if(typeof property!='undefined'&&property.event){if(property.validator&&!property.validator(value)){return false;}else{property.value=value;if(!silent){fireEvent(key,value);this.configChangedEvent.fire([key,value]);}
return true;}}else{return false;}}};this.queueProperty=function(key,value){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event){if(typeof value!='undefined'&&property.validator&&!property.validator(value)){return false;}else{if(typeof value!='undefined'){property.value=value;}else{value=property.value;}
var foundDuplicate=false;for(var i=0;i<eventQueue.length;i++){var queueItem=eventQueue[i];if(queueItem){var queueItemKey=queueItem[0];var queueItemValue=queueItem[1];if(queueItemKey.toLowerCase()==key){eventQueue[i]=null;eventQueue.push([key,(typeof value!='undefined'?value:queueItemValue)]);foundDuplicate=true;break;}}}
if(!foundDuplicate&&typeof value!='undefined'){eventQueue.push([key,value]);}}
if(property.supercedes){for(var s=0;s<property.supercedes.length;s++){var supercedesCheck=property.supercedes[s];for(var q=0;q<eventQueue.length;q++){var queueItemCheck=eventQueue[q];if(queueItemCheck){var queueItemCheckKey=queueItemCheck[0];var queueItemCheckValue=queueItemCheck[1];if(queueItemCheckKey.toLowerCase()==supercedesCheck.toLowerCase()){eventQueue.push([queueItemCheckKey,queueItemCheckValue]);eventQueue[q]=null;break;}}}}}
return true;}else{return false;}};this.refireEvent=function(key){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event&&typeof property.value!='undefined'){if(this.queueInProgress){this.queueProperty(key);}else{fireEvent(key,property.value);}}};this.applyConfig=function(userConfig,init){if(init){initialConfig=userConfig;}
for(var prop in userConfig){this.queueProperty(prop,userConfig[prop]);}};this.refresh=function(){for(var prop in config){this.refireEvent(prop);}};this.fireQueue=function(){this.queueInProgress=true;for(var i=0;i<eventQueue.length;i++){var queueItem=eventQueue[i];if(queueItem){var key=queueItem[0];var value=queueItem[1];var property=config[key];property.value=value;fireEvent(key,value);}}
this.queueInProgress=false;eventQueue=[];};this.subscribeToConfigEvent=function(key,handler,obj,override){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event){if(!YAHOO.util.Config.alreadySubscribed(property.event,handler,obj)){property.event.subscribe(handler,obj,override);}
return true;}else{return false;}};this.unsubscribeFromConfigEvent=function(key,handler,obj){key=key.toLowerCase();var property=config[key];if(typeof property!='undefined'&&property.event){return property.event.unsubscribe(handler,obj);}else{return false;}};this.toString=function(){var output="Config";if(this.owner){output+=" ["+this.owner.toString()+"]";}
return output;};this.outputEventQueue=function(){var output="";for(var q=0;q<eventQueue.length;q++){var queueItem=eventQueue[q];if(queueItem){output+=queueItem[0]+"="+queueItem[1]+", ";}}
return output;};};YAHOO.util.Config.alreadySubscribed=function(evt,fn,obj){for(var e=0;e<evt.subscribers.length;e++){var subsc=evt.subscribers[e];if(subsc&&subsc.obj==obj&&subsc.fn==fn){return true;}}
return false;};YAHOO.widget.Module=function(el,userConfig){if(el){this.init(el,userConfig);}};YAHOO.widget.Module.IMG_ROOT="http://us.i1.yimg.com/us.yimg.com/i/";YAHOO.widget.Module.IMG_ROOT_SSL="https://a248.e.akamai.net/sec.yimg.com/i/";YAHOO.widget.Module.CSS_MODULE="module";YAHOO.widget.Module.CSS_HEADER="hd";YAHOO.widget.Module.CSS_BODY="bd";YAHOO.widget.Module.CSS_FOOTER="ft";YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL="javascript:false;";YAHOO.widget.Module.textResizeEvent=new YAHOO.util.CustomEvent("textResize");YAHOO.widget.Module.prototype={constructor:YAHOO.widget.Module,element:null,header:null,body:null,footer:null,id:null,imageRoot:YAHOO.widget.Module.IMG_ROOT,initEvents:function(){this.beforeInitEvent=new YAHOO.util.CustomEvent("beforeInit");this.initEvent=new YAHOO.util.CustomEvent("init");this.appendEvent=new YAHOO.util.CustomEvent("append");this.beforeRenderEvent=new YAHOO.util.CustomEvent("beforeRender");this.renderEvent=new YAHOO.util.CustomEvent("render");this.changeHeaderEvent=new YAHOO.util.CustomEvent("changeHeader");this.changeBodyEvent=new YAHOO.util.CustomEvent("changeBody");this.changeFooterEvent=new YAHOO.util.CustomEvent("changeFooter");this.changeContentEvent=new YAHOO.util.CustomEvent("changeContent");this.destroyEvent=new YAHOO.util.CustomEvent("destroy");this.beforeShowEvent=new YAHOO.util.CustomEvent("beforeShow");this.showEvent=new YAHOO.util.CustomEvent("show");this.beforeHideEvent=new YAHOO.util.CustomEvent("beforeHide");this.hideEvent=new YAHOO.util.CustomEvent("hide");},platform:function(){var ua=navigator.userAgent.toLowerCase();if(ua.indexOf("windows")!=-1||ua.indexOf("win32")!=-1){return"windows";}else if(ua.indexOf("macintosh")!=-1){return"mac";}else{return false;}}(),browser:function(){var ua=navigator.userAgent.toLowerCase();if(ua.indexOf('opera')!=-1){return'opera';}else if(ua.indexOf('msie 7')!=-1){return'ie7';}else if(ua.indexOf('msie')!=-1){return'ie';}else if(ua.indexOf('safari')!=-1){return'safari';}else if(ua.indexOf('gecko')!=-1){return'gecko';}else{return false;}}(),isSecure:function(){if(window.location.href.toLowerCase().indexOf("https")===0){return true;}else{return false;}}(),initDefaultConfig:function(){this.cfg.addProperty("visible",{value:true,handler:this.configVisible,validator:this.cfg.checkBoolean});this.cfg.addProperty("effect",{suppressEvent:true,supercedes:["visible"]});this.cfg.addProperty("monitorresize",{value:true,handler:this.configMonitorResize});},init:function(el,userConfig){this.initEvents();this.beforeInitEvent.fire(YAHOO.widget.Module);this.cfg=new YAHOO.util.Config(this);if(this.isSecure){this.imageRoot=YAHOO.widget.Module.IMG_ROOT_SSL;}
if(typeof el=="string"){var elId=el;el=document.getElementById(el);if(!el){el=document.createElement("DIV");el.id=elId;}}
this.element=el;if(el.id){this.id=el.id;}
var childNodes=this.element.childNodes;if(childNodes){for(var i=0;i<childNodes.length;i++){var child=childNodes[i];switch(child.className){case YAHOO.widget.Module.CSS_HEADER:this.header=child;break;case YAHOO.widget.Module.CSS_BODY:this.body=child;break;case YAHOO.widget.Module.CSS_FOOTER:this.footer=child;break;}}}
this.initDefaultConfig();YAHOO.util.Dom.addClass(this.element,YAHOO.widget.Module.CSS_MODULE);if(userConfig){this.cfg.applyConfig(userConfig,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.renderEvent,this.cfg.fireQueue,this.cfg)){this.renderEvent.subscribe(this.cfg.fireQueue,this.cfg,true);}
this.initEvent.fire(YAHOO.widget.Module);},initResizeMonitor:function(){if(this.browser!="opera"){var resizeMonitor=document.getElementById("_yuiResizeMonitor");if(!resizeMonitor){resizeMonitor=document.createElement("iframe");var bIE=(this.browser.indexOf("ie")===0);if(this.isSecure&&YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL&&bIE){resizeMonitor.src=YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL;}
resizeMonitor.id="_yuiResizeMonitor";resizeMonitor.style.visibility="hidden";document.body.appendChild(resizeMonitor);resizeMonitor.style.width="10em";resizeMonitor.style.height="10em";resizeMonitor.style.position="absolute";var nLeft=-1*resizeMonitor.offsetWidth,nTop=-1*resizeMonitor.offsetHeight;resizeMonitor.style.top=nTop+"px";resizeMonitor.style.left=nLeft+"px";resizeMonitor.style.borderStyle="none";resizeMonitor.style.borderWidth="0";YAHOO.util.Dom.setStyle(resizeMonitor,"opacity","0");resizeMonitor.style.visibility="visible";if(!bIE){var doc=resizeMonitor.contentWindow.document;doc.open();doc.close();}}
var fireTextResize=function(){YAHOO.widget.Module.textResizeEvent.fire();};if(resizeMonitor&&resizeMonitor.contentWindow){this.resizeMonitor=resizeMonitor;YAHOO.widget.Module.textResizeEvent.subscribe(this.onDomResize,this,true);if(!YAHOO.widget.Module.textResizeInitialized){if(!YAHOO.util.Event.addListener(this.resizeMonitor.contentWindow,"resize",fireTextResize)){YAHOO.util.Event.addListener(this.resizeMonitor,"resize",fireTextResize);}
YAHOO.widget.Module.textResizeInitialized=true;}}}},onDomResize:function(e,obj){var nLeft=-1*this.resizeMonitor.offsetWidth,nTop=-1*this.resizeMonitor.offsetHeight;this.resizeMonitor.style.top=nTop+"px";this.resizeMonitor.style.left=nLeft+"px";},setHeader:function(headerContent){if(!this.header){this.header=document.createElement("DIV");this.header.className=YAHOO.widget.Module.CSS_HEADER;}
if(typeof headerContent=="string"){this.header.innerHTML=headerContent;}else{this.header.innerHTML="";this.header.appendChild(headerContent);}
this.changeHeaderEvent.fire(headerContent);this.changeContentEvent.fire();},appendToHeader:function(element){if(!this.header){this.header=document.createElement("DIV");this.header.className=YAHOO.widget.Module.CSS_HEADER;}
this.header.appendChild(element);this.changeHeaderEvent.fire(element);this.changeContentEvent.fire();},setBody:function(bodyContent){if(!this.body){this.body=document.createElement("DIV");this.body.className=YAHOO.widget.Module.CSS_BODY;}
if(typeof bodyContent=="string")
{this.body.innerHTML=bodyContent;}else{this.body.innerHTML="";this.body.appendChild(bodyContent);}
this.changeBodyEvent.fire(bodyContent);this.changeContentEvent.fire();},appendToBody:function(element){if(!this.body){this.body=document.createElement("DIV");this.body.className=YAHOO.widget.Module.CSS_BODY;}
this.body.appendChild(element);this.changeBodyEvent.fire(element);this.changeContentEvent.fire();},setFooter:function(footerContent){if(!this.footer){this.footer=document.createElement("DIV");this.footer.className=YAHOO.widget.Module.CSS_FOOTER;}
if(typeof footerContent=="string"){this.footer.innerHTML=footerContent;}else{this.footer.innerHTML="";this.footer.appendChild(footerContent);}
this.changeFooterEvent.fire(footerContent);this.changeContentEvent.fire();},appendToFooter:function(element){if(!this.footer){this.footer=document.createElement("DIV");this.footer.className=YAHOO.widget.Module.CSS_FOOTER;}
this.footer.appendChild(element);this.changeFooterEvent.fire(element);this.changeContentEvent.fire();},render:function(appendToNode,moduleElement){this.beforeRenderEvent.fire();if(!moduleElement){moduleElement=this.element;}
var me=this;var appendTo=function(element){if(typeof element=="string"){element=document.getElementById(element);}
if(element){element.appendChild(me.element);me.appendEvent.fire();}};if(appendToNode){appendTo(appendToNode);}else{if(!YAHOO.util.Dom.inDocument(this.element)){return false;}}
if(this.header&&!YAHOO.util.Dom.inDocument(this.header)){var firstChild=moduleElement.firstChild;if(firstChild){moduleElement.insertBefore(this.header,firstChild);}else{moduleElement.appendChild(this.header);}}
if(this.body&&!YAHOO.util.Dom.inDocument(this.body)){if(this.footer&&YAHOO.util.Dom.isAncestor(this.moduleElement,this.footer)){moduleElement.insertBefore(this.body,this.footer);}else{moduleElement.appendChild(this.body);}}
if(this.footer&&!YAHOO.util.Dom.inDocument(this.footer)){moduleElement.appendChild(this.footer);}
this.renderEvent.fire();return true;},destroy:function(){var parent;if(this.element){YAHOO.util.Event.purgeElement(this.element,true);parent=this.element.parentNode;}
if(parent){parent.removeChild(this.element);}
this.element=null;this.header=null;this.body=null;this.footer=null;for(var e in this){if(e instanceof YAHOO.util.CustomEvent){e.unsubscribeAll();}}
YAHOO.widget.Module.textResizeEvent.unsubscribe(this.onDomResize,this);this.destroyEvent.fire();},show:function(){this.cfg.setProperty("visible",true);},hide:function(){this.cfg.setProperty("visible",false);},configVisible:function(type,args,obj){var visible=args[0];if(visible){this.beforeShowEvent.fire();YAHOO.util.Dom.setStyle(this.element,"display","block");this.showEvent.fire();}else{this.beforeHideEvent.fire();YAHOO.util.Dom.setStyle(this.element,"display","none");this.hideEvent.fire();}},configMonitorResize:function(type,args,obj){var monitor=args[0];if(monitor){this.initResizeMonitor();}else{YAHOO.widget.Module.textResizeEvent.unsubscribe(this.onDomResize,this,true);this.resizeMonitor=null;}}};YAHOO.widget.Module.prototype.toString=function(){return"Module "+this.id;};YAHOO.widget.Overlay=function(el,userConfig){YAHOO.widget.Overlay.superclass.constructor.call(this,el,userConfig);};YAHOO.extend(YAHOO.widget.Overlay,YAHOO.widget.Module);YAHOO.widget.Overlay.IFRAME_SRC="javascript:false;";YAHOO.widget.Overlay.TOP_LEFT="tl";YAHOO.widget.Overlay.TOP_RIGHT="tr";YAHOO.widget.Overlay.BOTTOM_LEFT="bl";YAHOO.widget.Overlay.BOTTOM_RIGHT="br";YAHOO.widget.Overlay.CSS_OVERLAY="overlay";YAHOO.widget.Overlay.prototype.init=function(el,userConfig){YAHOO.widget.Overlay.superclass.init.call(this,el);this.beforeInitEvent.fire(YAHOO.widget.Overlay);YAHOO.util.Dom.addClass(this.element,YAHOO.widget.Overlay.CSS_OVERLAY);if(userConfig){this.cfg.applyConfig(userConfig,true);}
if(this.platform=="mac"&&this.browser=="gecko"){if(!YAHOO.util.Config.alreadySubscribed(this.showEvent,this.showMacGeckoScrollbars,this)){this.showEvent.subscribe(this.showMacGeckoScrollbars,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.hideEvent,this.hideMacGeckoScrollbars,this)){this.hideEvent.subscribe(this.hideMacGeckoScrollbars,this,true);}}
this.initEvent.fire(YAHOO.widget.Overlay);};YAHOO.widget.Overlay.prototype.initEvents=function(){YAHOO.widget.Overlay.superclass.initEvents.call(this);this.beforeMoveEvent=new YAHOO.util.CustomEvent("beforeMove",this);this.moveEvent=new YAHOO.util.CustomEvent("move",this);};YAHOO.widget.Overlay.prototype.initDefaultConfig=function(){YAHOO.widget.Overlay.superclass.initDefaultConfig.call(this);this.cfg.addProperty("x",{handler:this.configX,validator:this.cfg.checkNumber,suppressEvent:true,supercedes:["iframe"]});this.cfg.addProperty("y",{handler:this.configY,validator:this.cfg.checkNumber,suppressEvent:true,supercedes:["iframe"]});this.cfg.addProperty("xy",{handler:this.configXY,suppressEvent:true,supercedes:["iframe"]});this.cfg.addProperty("context",{handler:this.configContext,suppressEvent:true,supercedes:["iframe"]});this.cfg.addProperty("fixedcenter",{value:false,handler:this.configFixedCenter,validator:this.cfg.checkBoolean,supercedes:["iframe","visible"]});this.cfg.addProperty("width",{handler:this.configWidth,suppressEvent:true,supercedes:["iframe"]});this.cfg.addProperty("height",{handler:this.configHeight,suppressEvent:true,supercedes:["iframe"]});this.cfg.addProperty("zIndex",{value:null,handler:this.configzIndex});this.cfg.addProperty("constraintoviewport",{value:false,handler:this.configConstrainToViewport,validator:this.cfg.checkBoolean,supercedes:["iframe","x","y","xy"]});this.cfg.addProperty("iframe",{value:(this.browser=="ie"?true:false),handler:this.configIframe,validator:this.cfg.checkBoolean,supercedes:["zIndex"]});};YAHOO.widget.Overlay.prototype.moveTo=function(x,y){this.cfg.setProperty("xy",[x,y]);};YAHOO.widget.Overlay.prototype.hideMacGeckoScrollbars=function(){YAHOO.util.Dom.removeClass(this.element,"show-scrollbars");YAHOO.util.Dom.addClass(this.element,"hide-scrollbars");};YAHOO.widget.Overlay.prototype.showMacGeckoScrollbars=function(){YAHOO.util.Dom.removeClass(this.element,"hide-scrollbars");YAHOO.util.Dom.addClass(this.element,"show-scrollbars");};YAHOO.widget.Overlay.prototype.configVisible=function(type,args,obj){var visible=args[0];var currentVis=YAHOO.util.Dom.getStyle(this.element,"visibility");if(currentVis=="inherit"){var e=this.element.parentNode;while(e.nodeType!=9&&e.nodeType!=11){currentVis=YAHOO.util.Dom.getStyle(e,"visibility");if(currentVis!="inherit"){break;}
e=e.parentNode;}
if(currentVis=="inherit"){currentVis="visible";}}
var effect=this.cfg.getProperty("effect");var effectInstances=[];if(effect){if(effect instanceof Array){for(var i=0;i<effect.length;i++){var eff=effect[i];effectInstances[effectInstances.length]=eff.effect(this,eff.duration);}}else{effectInstances[effectInstances.length]=effect.effect(this,effect.duration);}}
var isMacGecko=(this.platform=="mac"&&this.browser=="gecko");if(visible){if(isMacGecko){this.showMacGeckoScrollbars();}
if(effect){if(visible){if(currentVis!="visible"||currentVis===""){this.beforeShowEvent.fire();for(var j=0;j<effectInstances.length;j++){var ei=effectInstances[j];if(j===0&&!YAHOO.util.Config.alreadySubscribed(ei.animateInCompleteEvent,this.showEvent.fire,this.showEvent)){ei.animateInCompleteEvent.subscribe(this.showEvent.fire,this.showEvent,true);}
ei.animateIn();}}}}else{if(currentVis!="visible"||currentVis===""){this.beforeShowEvent.fire();YAHOO.util.Dom.setStyle(this.element,"visibility","visible");this.cfg.refireEvent("iframe");this.showEvent.fire();}}}else{if(isMacGecko){this.hideMacGeckoScrollbars();}
if(effect){if(currentVis=="visible"){this.beforeHideEvent.fire();for(var k=0;k<effectInstances.length;k++){var h=effectInstances[k];if(k===0&&!YAHOO.util.Config.alreadySubscribed(h.animateOutCompleteEvent,this.hideEvent.fire,this.hideEvent)){h.animateOutCompleteEvent.subscribe(this.hideEvent.fire,this.hideEvent,true);}
h.animateOut();}}else if(currentVis===""){YAHOO.util.Dom.setStyle(this.element,"visibility","hidden");}}else{if(currentVis=="visible"||currentVis===""){this.beforeHideEvent.fire();YAHOO.util.Dom.setStyle(this.element,"visibility","hidden");this.cfg.refireEvent("iframe");this.hideEvent.fire();}}}};YAHOO.widget.Overlay.prototype.doCenterOnDOMEvent=function(){if(this.cfg.getProperty("visible")){this.center();}};YAHOO.widget.Overlay.prototype.configFixedCenter=function(type,args,obj){var val=args[0];if(val){this.center();if(!YAHOO.util.Config.alreadySubscribed(this.beforeShowEvent,this.center,this)){this.beforeShowEvent.subscribe(this.center,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(YAHOO.widget.Overlay.windowResizeEvent,this.doCenterOnDOMEvent,this)){YAHOO.widget.Overlay.windowResizeEvent.subscribe(this.doCenterOnDOMEvent,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(YAHOO.widget.Overlay.windowScrollEvent,this.doCenterOnDOMEvent,this)){YAHOO.widget.Overlay.windowScrollEvent.subscribe(this.doCenterOnDOMEvent,this,true);}}else{YAHOO.widget.Overlay.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent,this);YAHOO.widget.Overlay.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent,this);}};YAHOO.widget.Overlay.prototype.configHeight=function(type,args,obj){var height=args[0];var el=this.element;YAHOO.util.Dom.setStyle(el,"height",height);this.cfg.refireEvent("iframe");};YAHOO.widget.Overlay.prototype.configWidth=function(type,args,obj){var width=args[0];var el=this.element;YAHOO.util.Dom.setStyle(el,"width",width);this.cfg.refireEvent("iframe");};YAHOO.widget.Overlay.prototype.configzIndex=function(type,args,obj){var zIndex=args[0];var el=this.element;if(!zIndex){zIndex=YAHOO.util.Dom.getStyle(el,"zIndex");if(!zIndex||isNaN(zIndex)){zIndex=0;}}
if(this.iframe){if(zIndex<=0){zIndex=1;}
YAHOO.util.Dom.setStyle(this.iframe,"zIndex",(zIndex-1));}
YAHOO.util.Dom.setStyle(el,"zIndex",zIndex);this.cfg.setProperty("zIndex",zIndex,true);};YAHOO.widget.Overlay.prototype.configXY=function(type,args,obj){var pos=args[0];var x=pos[0];var y=pos[1];this.cfg.setProperty("x",x);this.cfg.setProperty("y",y);this.beforeMoveEvent.fire([x,y]);x=this.cfg.getProperty("x");y=this.cfg.getProperty("y");this.cfg.refireEvent("iframe");this.moveEvent.fire([x,y]);};YAHOO.widget.Overlay.prototype.configX=function(type,args,obj){var x=args[0];var y=this.cfg.getProperty("y");this.cfg.setProperty("x",x,true);this.cfg.setProperty("y",y,true);this.beforeMoveEvent.fire([x,y]);x=this.cfg.getProperty("x");y=this.cfg.getProperty("y");YAHOO.util.Dom.setX(this.element,x,true);this.cfg.setProperty("xy",[x,y],true);this.cfg.refireEvent("iframe");this.moveEvent.fire([x,y]);};YAHOO.widget.Overlay.prototype.configY=function(type,args,obj){var x=this.cfg.getProperty("x");var y=args[0];this.cfg.setProperty("x",x,true);this.cfg.setProperty("y",y,true);this.beforeMoveEvent.fire([x,y]);x=this.cfg.getProperty("x");y=this.cfg.getProperty("y");YAHOO.util.Dom.setY(this.element,y,true);this.cfg.setProperty("xy",[x,y],true);this.cfg.refireEvent("iframe");this.moveEvent.fire([x,y]);};YAHOO.widget.Overlay.prototype.showIframe=function(){if(this.iframe){this.iframe.style.display="block";}};YAHOO.widget.Overlay.prototype.hideIframe=function(){if(this.iframe){this.iframe.style.display="none";}};YAHOO.widget.Overlay.prototype.configIframe=function(type,args,obj){var val=args[0];if(val){if(!YAHOO.util.Config.alreadySubscribed(this.showEvent,this.showIframe,this)){this.showEvent.subscribe(this.showIframe,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.hideEvent,this.hideIframe,this)){this.hideEvent.subscribe(this.hideIframe,this,true);}
var x=this.cfg.getProperty("x");var y=this.cfg.getProperty("y");if(!x||!y){this.syncPosition();x=this.cfg.getProperty("x");y=this.cfg.getProperty("y");}
if(!isNaN(x)&&!isNaN(y)){if(!this.iframe){this.iframe=document.createElement("iframe");if(this.isSecure){this.iframe.src=YAHOO.widget.Overlay.IFRAME_SRC;}
var parent=this.element.parentNode;if(parent){parent.appendChild(this.iframe);}else{document.body.appendChild(this.iframe);}
YAHOO.util.Dom.setStyle(this.iframe,"position","absolute");YAHOO.util.Dom.setStyle(this.iframe,"border","none");YAHOO.util.Dom.setStyle(this.iframe,"margin","0");YAHOO.util.Dom.setStyle(this.iframe,"padding","0");YAHOO.util.Dom.setStyle(this.iframe,"opacity","0");if(this.cfg.getProperty("visible")){this.showIframe();}else{this.hideIframe();}}
var iframeDisplay=YAHOO.util.Dom.getStyle(this.iframe,"display");if(iframeDisplay=="none"){this.iframe.style.display="block";}
YAHOO.util.Dom.setXY(this.iframe,[x,y]);var width=this.element.clientWidth;var height=this.element.clientHeight;YAHOO.util.Dom.setStyle(this.iframe,"width",(width+2)+"px");YAHOO.util.Dom.setStyle(this.iframe,"height",(height+2)+"px");if(iframeDisplay=="none"){this.iframe.style.display="none";}}}else{if(this.iframe){this.iframe.style.display="none";}
this.showEvent.unsubscribe(this.showIframe,this);this.hideEvent.unsubscribe(this.hideIframe,this);}};YAHOO.widget.Overlay.prototype.configConstrainToViewport=function(type,args,obj){var val=args[0];if(val){if(!YAHOO.util.Config.alreadySubscribed(this.beforeMoveEvent,this.enforceConstraints,this)){this.beforeMoveEvent.subscribe(this.enforceConstraints,this,true);}}else{this.beforeMoveEvent.unsubscribe(this.enforceConstraints,this);}};YAHOO.widget.Overlay.prototype.configContext=function(type,args,obj){var contextArgs=args[0];if(contextArgs){var contextEl=contextArgs[0];var elementMagnetCorner=contextArgs[1];var contextMagnetCorner=contextArgs[2];if(contextEl){if(typeof contextEl=="string"){this.cfg.setProperty("context",[document.getElementById(contextEl),elementMagnetCorner,contextMagnetCorner],true);}
if(elementMagnetCorner&&contextMagnetCorner){this.align(elementMagnetCorner,contextMagnetCorner);}}}};YAHOO.widget.Overlay.prototype.align=function(elementAlign,contextAlign){var contextArgs=this.cfg.getProperty("context");if(contextArgs){var context=contextArgs[0];var element=this.element;var me=this;if(!elementAlign){elementAlign=contextArgs[1];}
if(!contextAlign){contextAlign=contextArgs[2];}
if(element&&context){var elementRegion=YAHOO.util.Dom.getRegion(element);var contextRegion=YAHOO.util.Dom.getRegion(context);var doAlign=function(v,h){switch(elementAlign){case YAHOO.widget.Overlay.TOP_LEFT:me.moveTo(h,v);break;case YAHOO.widget.Overlay.TOP_RIGHT:me.moveTo(h-element.offsetWidth,v);break;case YAHOO.widget.Overlay.BOTTOM_LEFT:me.moveTo(h,v-element.offsetHeight);break;case YAHOO.widget.Overlay.BOTTOM_RIGHT:me.moveTo(h-element.offsetWidth,v-element.offsetHeight);break;}};switch(contextAlign){case YAHOO.widget.Overlay.TOP_LEFT:doAlign(contextRegion.top,contextRegion.left);break;case YAHOO.widget.Overlay.TOP_RIGHT:doAlign(contextRegion.top,contextRegion.right);break;case YAHOO.widget.Overlay.BOTTOM_LEFT:doAlign(contextRegion.bottom,contextRegion.left);break;case YAHOO.widget.Overlay.BOTTOM_RIGHT:doAlign(contextRegion.bottom,contextRegion.right);break;}}}};YAHOO.widget.Overlay.prototype.enforceConstraints=function(type,args,obj){var pos=args[0];var x=pos[0];var y=pos[1];var offsetHeight=this.element.offsetHeight;var offsetWidth=this.element.offsetWidth;var viewPortWidth=YAHOO.util.Dom.getViewportWidth();var viewPortHeight=YAHOO.util.Dom.getViewportHeight();var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;var topConstraint=scrollY+10;var leftConstraint=scrollX+10;var bottomConstraint=scrollY+viewPortHeight-offsetHeight-10;var rightConstraint=scrollX+viewPortWidth-offsetWidth-10;if(x<leftConstraint){x=leftConstraint;}else if(x>rightConstraint){x=rightConstraint;}
if(y<topConstraint){y=topConstraint;}else if(y>bottomConstraint){y=bottomConstraint;}
this.cfg.setProperty("x",x,true);this.cfg.setProperty("y",y,true);this.cfg.setProperty("xy",[x,y],true);};YAHOO.widget.Overlay.prototype.center=function(){var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;var viewPortWidth=YAHOO.util.Dom.getClientWidth();var viewPortHeight=YAHOO.util.Dom.getClientHeight();var elementWidth=this.element.offsetWidth;var elementHeight=this.element.offsetHeight;var x=(viewPortWidth/2)-(elementWidth/2)+scrollX;var y=(viewPortHeight/2)-(elementHeight/2)+scrollY;this.cfg.setProperty("xy",[parseInt(x,10),parseInt(y,10)]);this.cfg.refireEvent("iframe");};YAHOO.widget.Overlay.prototype.syncPosition=function(){var pos=YAHOO.util.Dom.getXY(this.element);this.cfg.setProperty("x",pos[0],true);this.cfg.setProperty("y",pos[1],true);this.cfg.setProperty("xy",pos,true);};YAHOO.widget.Overlay.prototype.onDomResize=function(e,obj){YAHOO.widget.Overlay.superclass.onDomResize.call(this,e,obj);var me=this;setTimeout(function(){me.syncPosition();me.cfg.refireEvent("iframe");me.cfg.refireEvent("context");},0);};YAHOO.widget.Overlay.prototype.destroy=function(){if(this.iframe){this.iframe.parentNode.removeChild(this.iframe);}
this.iframe=null;YAHOO.widget.Overlay.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent,this);YAHOO.widget.Overlay.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent,this);YAHOO.widget.Overlay.superclass.destroy.call(this);};YAHOO.widget.Overlay.prototype.toString=function(){return"Overlay "+this.id;};YAHOO.widget.Overlay.windowScrollEvent=new YAHOO.util.CustomEvent("windowScroll");YAHOO.widget.Overlay.windowResizeEvent=new YAHOO.util.CustomEvent("windowResize");YAHOO.widget.Overlay.windowScrollHandler=function(e){if(YAHOO.widget.Module.prototype.browser=="ie"||YAHOO.widget.Module.prototype.browser=="ie7"){if(!window.scrollEnd){window.scrollEnd=-1;}
clearTimeout(window.scrollEnd);window.scrollEnd=setTimeout(function(){YAHOO.widget.Overlay.windowScrollEvent.fire();},1);}else{YAHOO.widget.Overlay.windowScrollEvent.fire();}};YAHOO.widget.Overlay.windowResizeHandler=function(e){if(YAHOO.widget.Module.prototype.browser=="ie"||YAHOO.widget.Module.prototype.browser=="ie7"){if(!window.resizeEnd){window.resizeEnd=-1;}
clearTimeout(window.resizeEnd);window.resizeEnd=setTimeout(function(){YAHOO.widget.Overlay.windowResizeEvent.fire();},100);}else{YAHOO.widget.Overlay.windowResizeEvent.fire();}};YAHOO.widget.Overlay._initialized=null;if(YAHOO.widget.Overlay._initialized===null){YAHOO.util.Event.addListener(window,"scroll",YAHOO.widget.Overlay.windowScrollHandler);YAHOO.util.Event.addListener(window,"resize",YAHOO.widget.Overlay.windowResizeHandler);YAHOO.widget.Overlay._initialized=true;}
YAHOO.widget.OverlayManager=function(userConfig){this.init(userConfig);};YAHOO.widget.OverlayManager.CSS_FOCUSED="focused";YAHOO.widget.OverlayManager.prototype={constructor:YAHOO.widget.OverlayManager,overlays:null,initDefaultConfig:function(){this.cfg.addProperty("overlays",{suppressEvent:true});this.cfg.addProperty("focusevent",{value:"mousedown"});},init:function(userConfig){this.cfg=new YAHOO.util.Config(this);this.initDefaultConfig();if(userConfig){this.cfg.applyConfig(userConfig,true);}
this.cfg.fireQueue();var activeOverlay=null;this.getActive=function(){return activeOverlay;};this.focus=function(overlay){var o=this.find(overlay);if(o){this.blurAll();activeOverlay=o;YAHOO.util.Dom.addClass(activeOverlay.element,YAHOO.widget.OverlayManager.CSS_FOCUSED);this.overlays.sort(this.compareZIndexDesc);var topZIndex=YAHOO.util.Dom.getStyle(this.overlays[0].element,"zIndex");if(!isNaN(topZIndex)&&this.overlays[0]!=overlay){activeOverlay.cfg.setProperty("zIndex",(parseInt(topZIndex,10)+2));}
this.overlays.sort(this.compareZIndexDesc);}};this.remove=function(overlay){var o=this.find(overlay);if(o){var originalZ=YAHOO.util.Dom.getStyle(o.element,"zIndex");o.cfg.setProperty("zIndex",-1000,true);this.overlays.sort(this.compareZIndexDesc);this.overlays=this.overlays.slice(0,this.overlays.length-1);o.cfg.setProperty("zIndex",originalZ,true);o.cfg.setProperty("manager",null);o.focusEvent=null;o.blurEvent=null;o.focus=null;o.blur=null;}};this.blurAll=function(){activeOverlay=null;for(var o=0;o<this.overlays.length;o++){YAHOO.util.Dom.removeClass(this.overlays[o].element,YAHOO.widget.OverlayManager.CSS_FOCUSED);}};var overlays=this.cfg.getProperty("overlays");if(!this.overlays){this.overlays=[];}
if(overlays){this.register(overlays);this.overlays.sort(this.compareZIndexDesc);}},register:function(overlay){if(overlay instanceof YAHOO.widget.Overlay){overlay.cfg.addProperty("manager",{value:this});overlay.focusEvent=new YAHOO.util.CustomEvent("focus");overlay.blurEvent=new YAHOO.util.CustomEvent("blur");var mgr=this;overlay.focus=function(){mgr.focus(this);this.focusEvent.fire();};overlay.blur=function(){mgr.blurAll();this.blurEvent.fire();};var focusOnDomEvent=function(e,obj){overlay.focus();};var focusevent=this.cfg.getProperty("focusevent");YAHOO.util.Event.addListener(overlay.element,focusevent,focusOnDomEvent,this,true);var zIndex=YAHOO.util.Dom.getStyle(overlay.element,"zIndex");if(!isNaN(zIndex)){overlay.cfg.setProperty("zIndex",parseInt(zIndex,10));}else{overlay.cfg.setProperty("zIndex",0);}
this.overlays.push(overlay);return true;}else if(overlay instanceof Array){var regcount=0;for(var i=0;i<overlay.length;i++){if(this.register(overlay[i])){regcount++;}}
if(regcount>0){return true;}}else{return false;}},find:function(overlay){if(overlay instanceof YAHOO.widget.Overlay){for(var o=0;o<this.overlays.length;o++){if(this.overlays[o]==overlay){return this.overlays[o];}}}else if(typeof overlay=="string"){for(var p=0;p<this.overlays.length;p++){if(this.overlays[p].id==overlay){return this.overlays[p];}}}
return null;},compareZIndexDesc:function(o1,o2){var zIndex1=o1.cfg.getProperty("zIndex");var zIndex2=o2.cfg.getProperty("zIndex");if(zIndex1>zIndex2){return-1;}else if(zIndex1<zIndex2){return 1;}else{return 0;}},showAll:function(){for(var o=0;o<this.overlays.length;o++){this.overlays[o].show();}},hideAll:function(){for(var o=0;o<this.overlays.length;o++){this.overlays[o].hide();}},toString:function(){return"OverlayManager";}};YAHOO.util.KeyListener=function(attachTo,keyData,handler,event){if(!event){event=YAHOO.util.KeyListener.KEYDOWN;}
var keyEvent=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(typeof attachTo=='string'){attachTo=document.getElementById(attachTo);}
if(typeof handler=='function'){keyEvent.subscribe(handler);}else{keyEvent.subscribe(handler.fn,handler.scope,handler.correctScope);}
function handleKeyPress(e,obj){if(!keyData.shift){keyData.shift=false;}
if(!keyData.alt){keyData.alt=false;}
if(!keyData.ctrl){keyData.ctrl=false;}
if(e.shiftKey==keyData.shift&&e.altKey==keyData.alt&&e.ctrlKey==keyData.ctrl){var dataItem;var keyPressed;if(keyData.keys instanceof Array){for(var i=0;i<keyData.keys.length;i++){dataItem=keyData.keys[i];if(dataItem==e.charCode){keyEvent.fire(e.charCode,e);break;}else if(dataItem==e.keyCode){keyEvent.fire(e.keyCode,e);break;}}}else{dataItem=keyData.keys;if(dataItem==e.charCode){keyEvent.fire(e.charCode,e);}else if(dataItem==e.keyCode){keyEvent.fire(e.keyCode,e);}}}}
this.enable=function(){if(!this.enabled){YAHOO.util.Event.addListener(attachTo,event,handleKeyPress);this.enabledEvent.fire(keyData);}
this.enabled=true;};this.disable=function(){if(this.enabled){YAHOO.util.Event.removeListener(attachTo,event,handleKeyPress);this.disabledEvent.fire(keyData);}
this.enabled=false;};this.toString=function(){return"KeyListener ["+keyData.keys+"] "+attachTo.tagName+(attachTo.id?"["+attachTo.id+"]":"");};};YAHOO.util.KeyListener.KEYDOWN="keydown";YAHOO.util.KeyListener.KEYUP="keyup";YAHOO.widget.Tooltip=function(el,userConfig){YAHOO.widget.Tooltip.superclass.constructor.call(this,el,userConfig);};YAHOO.extend(YAHOO.widget.Tooltip,YAHOO.widget.Overlay);YAHOO.widget.Tooltip.CSS_TOOLTIP="tt";YAHOO.widget.Tooltip.prototype.init=function(el,userConfig){if(document.readyState&&document.readyState!="complete"){var deferredInit=function(){this.init(el,userConfig);};YAHOO.util.Event.addListener(window,"load",deferredInit,this,true);}else{YAHOO.widget.Tooltip.superclass.init.call(this,el);this.beforeInitEvent.fire(YAHOO.widget.Tooltip);YAHOO.util.Dom.addClass(this.element,YAHOO.widget.Tooltip.CSS_TOOLTIP);if(userConfig){this.cfg.applyConfig(userConfig,true);}
this.cfg.queueProperty("visible",false);this.cfg.queueProperty("constraintoviewport",true);this.setBody("");this.render(this.cfg.getProperty("container"));this.initEvent.fire(YAHOO.widget.Tooltip);}};YAHOO.widget.Tooltip.prototype.initDefaultConfig=function(){YAHOO.widget.Tooltip.superclass.initDefaultConfig.call(this);this.cfg.addProperty("preventoverlap",{value:true,validator:this.cfg.checkBoolean,supercedes:["x","y","xy"]});this.cfg.addProperty("showdelay",{value:200,handler:this.configShowDelay,validator:this.cfg.checkNumber});this.cfg.addProperty("autodismissdelay",{value:5000,handler:this.configAutoDismissDelay,validator:this.cfg.checkNumber});this.cfg.addProperty("hidedelay",{value:250,handler:this.configHideDelay,validator:this.cfg.checkNumber});this.cfg.addProperty("text",{handler:this.configText,suppressEvent:true});this.cfg.addProperty("container",{value:document.body,handler:this.configContainer});};YAHOO.widget.Tooltip.prototype.configText=function(type,args,obj){var text=args[0];if(text){this.setBody(text);}};YAHOO.widget.Tooltip.prototype.configContainer=function(type,args,obj){var container=args[0];if(typeof container=='string'){this.cfg.setProperty("container",document.getElementById(container),true);}};YAHOO.widget.Tooltip.prototype.configContext=function(type,args,obj){var context=args[0];if(context){if(!(context instanceof Array)){if(typeof context=="string"){this.cfg.setProperty("context",[document.getElementById(context)],true);}else{this.cfg.setProperty("context",[context],true);}
context=this.cfg.getProperty("context");}
if(this._context){for(var c=0;c<this._context.length;++c){var el=this._context[c];YAHOO.util.Event.removeListener(el,"mouseover",this.onContextMouseOver);YAHOO.util.Event.removeListener(el,"mousemove",this.onContextMouseMove);YAHOO.util.Event.removeListener(el,"mouseout",this.onContextMouseOut);}}
this._context=context;for(var d=0;d<this._context.length;++d){var el2=this._context[d];YAHOO.util.Event.addListener(el2,"mouseover",this.onContextMouseOver,this);YAHOO.util.Event.addListener(el2,"mousemove",this.onContextMouseMove,this);YAHOO.util.Event.addListener(el2,"mouseout",this.onContextMouseOut,this);}}};YAHOO.widget.Tooltip.prototype.onContextMouseMove=function(e,obj){obj.pageX=YAHOO.util.Event.getPageX(e);obj.pageY=YAHOO.util.Event.getPageY(e);};YAHOO.widget.Tooltip.prototype.onContextMouseOver=function(e,obj){if(obj.hideProcId){clearTimeout(obj.hideProcId);obj.hideProcId=null;}
var context=this;YAHOO.util.Event.addListener(context,"mousemove",obj.onContextMouseMove,obj);if(context.title){obj._tempTitle=context.title;context.title="";}
obj.showProcId=obj.doShow(e,context);};YAHOO.widget.Tooltip.prototype.onContextMouseOut=function(e,obj){var el=this;if(obj._tempTitle){el.title=obj._tempTitle;obj._tempTitle=null;}
if(obj.showProcId){clearTimeout(obj.showProcId);obj.showProcId=null;}
if(obj.hideProcId){clearTimeout(obj.hideProcId);obj.hideProcId=null;}
obj.hideProcId=setTimeout(function(){obj.hide();},obj.cfg.getProperty("hidedelay"));};YAHOO.widget.Tooltip.prototype.doShow=function(e,context){var yOffset=25;if(this.browser=="opera"&&context.tagName=="A"){yOffset+=12;}
var me=this;return setTimeout(function(){if(me._tempTitle){me.setBody(me._tempTitle);}else{me.cfg.refireEvent("text");}
me.moveTo(me.pageX,me.pageY+yOffset);if(me.cfg.getProperty("preventoverlap")){me.preventOverlap(me.pageX,me.pageY);}
YAHOO.util.Event.removeListener(context,"mousemove",me.onContextMouseMove);me.show();me.hideProcId=me.doHide();},this.cfg.getProperty("showdelay"));};YAHOO.widget.Tooltip.prototype.doHide=function(){var me=this;return setTimeout(function(){me.hide();},this.cfg.getProperty("autodismissdelay"));};YAHOO.widget.Tooltip.prototype.preventOverlap=function(pageX,pageY){var height=this.element.offsetHeight;var elementRegion=YAHOO.util.Dom.getRegion(this.element);elementRegion.top-=5;elementRegion.left-=5;elementRegion.right+=5;elementRegion.bottom+=5;var mousePoint=new YAHOO.util.Point(pageX,pageY);if(elementRegion.contains(mousePoint)){this.cfg.setProperty("y",(pageY-height-5));}};YAHOO.widget.Tooltip.prototype.toString=function(){return"Tooltip "+this.id;};YAHOO.widget.Panel=function(el,userConfig){YAHOO.widget.Panel.superclass.constructor.call(this,el,userConfig);};YAHOO.extend(YAHOO.widget.Panel,YAHOO.widget.Overlay);YAHOO.widget.Panel.CSS_PANEL="panel";YAHOO.widget.Panel.CSS_PANEL_CONTAINER="panel-container";YAHOO.widget.Panel.prototype.init=function(el,userConfig){YAHOO.widget.Panel.superclass.init.call(this,el);this.beforeInitEvent.fire(YAHOO.widget.Panel);YAHOO.util.Dom.addClass(this.element,YAHOO.widget.Panel.CSS_PANEL);this.buildWrapper();if(userConfig){this.cfg.applyConfig(userConfig,true);}
this.beforeRenderEvent.subscribe(function(){var draggable=this.cfg.getProperty("draggable");if(draggable){if(!this.header){this.setHeader("&#160;");}}},this,true);var me=this;var doBlur=function(){this.blur();};this.showMaskEvent.subscribe(function(){var checkFocusable=function(el){if((el.tagName=="A"||el.tagName=="BUTTON"||el.tagName=="SELECT"||el.tagName=="INPUT"||el.tagName=="TEXTAREA")&&el.type!="hidden"){if(!YAHOO.util.Dom.isAncestor(me.element,el)){YAHOO.util.Event.addListener(el,"focus",doBlur,el,true);return true;}}else{return false;}};this.focusableElements=YAHOO.util.Dom.getElementsBy(checkFocusable);},this,true);this.hideMaskEvent.subscribe(function(){for(var i=0;i<this.focusableElements.length;i++){var el2=this.focusableElements[i];YAHOO.util.Event.removeListener(el2,"focus",doBlur);}},this,true);this.beforeShowEvent.subscribe(function(){this.cfg.refireEvent("underlay");},this,true);this.initEvent.fire(YAHOO.widget.Panel);};YAHOO.widget.Panel.prototype.initEvents=function(){YAHOO.widget.Panel.superclass.initEvents.call(this);this.showMaskEvent=new YAHOO.util.CustomEvent("showMask");this.hideMaskEvent=new YAHOO.util.CustomEvent("hideMask");this.dragEvent=new YAHOO.util.CustomEvent("drag");};YAHOO.widget.Panel.prototype.initDefaultConfig=function(){YAHOO.widget.Panel.superclass.initDefaultConfig.call(this);this.cfg.addProperty("close",{value:true,handler:this.configClose,validator:this.cfg.checkBoolean,supercedes:["visible"]});this.cfg.addProperty("draggable",{value:true,handler:this.configDraggable,validator:this.cfg.checkBoolean,supercedes:["visible"]});this.cfg.addProperty("underlay",{value:"shadow",handler:this.configUnderlay,supercedes:["visible"]});this.cfg.addProperty("modal",{value:false,handler:this.configModal,validator:this.cfg.checkBoolean,supercedes:["visible"]});this.cfg.addProperty("keylisteners",{handler:this.configKeyListeners,suppressEvent:true,supercedes:["visible"]});};YAHOO.widget.Panel.prototype.configClose=function(type,args,obj){var val=args[0];var doHide=function(e,obj){obj.hide();};if(val){if(!this.close){this.close=document.createElement("DIV");YAHOO.util.Dom.addClass(this.close,"close");if(this.isSecure){YAHOO.util.Dom.addClass(this.close,"secure");}else{YAHOO.util.Dom.addClass(this.close,"nonsecure");}
this.close.innerHTML="&#160;";this.innerElement.appendChild(this.close);YAHOO.util.Event.addListener(this.close,"click",doHide,this);}else{this.close.style.display="block";}}else{if(this.close){this.close.style.display="none";}}};YAHOO.widget.Panel.prototype.configDraggable=function(type,args,obj){var val=args[0];if(val){if(this.header){YAHOO.util.Dom.setStyle(this.header,"cursor","move");this.registerDragDrop();}}else{if(this.dd){this.dd.unreg();}
if(this.header){YAHOO.util.Dom.setStyle(this.header,"cursor","auto");}}};YAHOO.widget.Panel.prototype.configUnderlay=function(type,args,obj){var val=args[0];switch(val.toLowerCase()){case"shadow":YAHOO.util.Dom.removeClass(this.element,"matte");YAHOO.util.Dom.addClass(this.element,"shadow");if(!this.underlay){this.underlay=document.createElement("DIV");this.underlay.className="underlay";this.underlay.innerHTML="&#160;";this.element.appendChild(this.underlay);}
this.sizeUnderlay();break;case"matte":YAHOO.util.Dom.removeClass(this.element,"shadow");YAHOO.util.Dom.addClass(this.element,"matte");break;default:YAHOO.util.Dom.removeClass(this.element,"shadow");YAHOO.util.Dom.removeClass(this.element,"matte");break;}};YAHOO.widget.Panel.prototype.configModal=function(type,args,obj){var modal=args[0];if(modal){this.buildMask();if(!YAHOO.util.Config.alreadySubscribed(this.beforeShowEvent,this.showMask,this)){this.beforeShowEvent.subscribe(this.showMask,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.hideEvent,this.hideMask,this)){this.hideEvent.subscribe(this.hideMask,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(YAHOO.widget.Overlay.windowResizeEvent,this.sizeMask,this)){YAHOO.widget.Overlay.windowResizeEvent.subscribe(this.sizeMask,this,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.destroyEvent,this.removeMask,this)){this.destroyEvent.subscribe(this.removeMask,this,true);}
this.cfg.refireEvent("zIndex");}else{this.beforeShowEvent.unsubscribe(this.showMask,this);this.hideEvent.unsubscribe(this.hideMask,this);YAHOO.widget.Overlay.windowResizeEvent.unsubscribe(this.sizeMask,this);this.destroyEvent.unsubscribe(this.removeMask,this);}};YAHOO.widget.Panel.prototype.removeMask=function(){if(this.mask){if(this.mask.parentNode){this.mask.parentNode.removeChild(this.mask);}
this.mask=null;}};YAHOO.widget.Panel.prototype.configKeyListeners=function(type,args,obj){var listeners=args[0];if(listeners){if(listeners instanceof Array){for(var i=0;i<listeners.length;i++){var listener=listeners[i];if(!YAHOO.util.Config.alreadySubscribed(this.showEvent,listener.enable,listener)){this.showEvent.subscribe(listener.enable,listener,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.hideEvent,listener.disable,listener)){this.hideEvent.subscribe(listener.disable,listener,true);this.destroyEvent.subscribe(listener.disable,listener,true);}}}else{if(!YAHOO.util.Config.alreadySubscribed(this.showEvent,listeners.enable,listeners)){this.showEvent.subscribe(listeners.enable,listeners,true);}
if(!YAHOO.util.Config.alreadySubscribed(this.hideEvent,listeners.disable,listeners)){this.hideEvent.subscribe(listeners.disable,listeners,true);this.destroyEvent.subscribe(listeners.disable,listeners,true);}}}};YAHOO.widget.Panel.prototype.configHeight=function(type,args,obj){var height=args[0];var el=this.innerElement;YAHOO.util.Dom.setStyle(el,"height",height);this.cfg.refireEvent("underlay");this.cfg.refireEvent("iframe");};YAHOO.widget.Panel.prototype.configWidth=function(type,args,obj){var width=args[0];var el=this.innerElement;YAHOO.util.Dom.setStyle(el,"width",width);this.cfg.refireEvent("underlay");this.cfg.refireEvent("iframe");};YAHOO.widget.Panel.prototype.configzIndex=function(type,args,obj){YAHOO.widget.Panel.superclass.configzIndex.call(this,type,args,obj);var maskZ=0;var currentZ=YAHOO.util.Dom.getStyle(this.element,"zIndex");if(this.mask){if(!currentZ||isNaN(currentZ)){currentZ=0;}
if(currentZ===0){this.cfg.setProperty("zIndex",1);}else{maskZ=currentZ-1;YAHOO.util.Dom.setStyle(this.mask,"zIndex",maskZ);}}};YAHOO.widget.Panel.prototype.buildWrapper=function(){var elementParent=this.element.parentNode;var originalElement=this.element;var wrapper=document.createElement("DIV");wrapper.className=YAHOO.widget.Panel.CSS_PANEL_CONTAINER;wrapper.id=originalElement.id+"_c";if(elementParent){elementParent.insertBefore(wrapper,originalElement);}
wrapper.appendChild(originalElement);this.element=wrapper;this.innerElement=originalElement;YAHOO.util.Dom.setStyle(this.innerElement,"visibility","inherit");};YAHOO.widget.Panel.prototype.sizeUnderlay=function(){if(this.underlay&&this.browser!="gecko"&&this.browser!="safari"){this.underlay.style.width=this.innerElement.offsetWidth+"px";this.underlay.style.height=this.innerElement.offsetHeight+"px";}};YAHOO.widget.Panel.prototype.onDomResize=function(e,obj){YAHOO.widget.Panel.superclass.onDomResize.call(this,e,obj);var me=this;setTimeout(function(){me.sizeUnderlay();},0);};YAHOO.widget.Panel.prototype.registerDragDrop=function(){if(this.header){this.dd=new YAHOO.util.DD(this.element.id,this.id);if(!this.header.id){this.header.id=this.id+"_h";}
var me=this;this.dd.startDrag=function(){if(me.browser=="ie"){YAHOO.util.Dom.addClass(me.element,"drag");}
if(me.cfg.getProperty("constraintoviewport")){var offsetHeight=me.element.offsetHeight;var offsetWidth=me.element.offsetWidth;var viewPortWidth=YAHOO.util.Dom.getViewportWidth();var viewPortHeight=YAHOO.util.Dom.getViewportHeight();var scrollX=window.scrollX||document.documentElement.scrollLeft;var scrollY=window.scrollY||document.documentElement.scrollTop;var topConstraint=scrollY+10;var leftConstraint=scrollX+10;var bottomConstraint=scrollY+viewPortHeight-offsetHeight-10;var rightConstraint=scrollX+viewPortWidth-offsetWidth-10;this.minX=leftConstraint;this.maxX=rightConstraint;this.constrainX=true;this.minY=topConstraint;this.maxY=bottomConstraint;this.constrainY=true;}else{this.constrainX=false;this.constrainY=false;}
me.dragEvent.fire("startDrag",arguments);};this.dd.onDrag=function(){me.syncPosition();me.cfg.refireEvent("iframe");if(this.platform=="mac"&&this.browser=="gecko"){this.showMacGeckoScrollbars();}
me.dragEvent.fire("onDrag",arguments);};this.dd.endDrag=function(){if(me.browser=="ie"){YAHOO.util.Dom.removeClass(me.element,"drag");}
me.dragEvent.fire("endDrag",arguments);};this.dd.setHandleElId(this.header.id);this.dd.addInvalidHandleType("INPUT");this.dd.addInvalidHandleType("SELECT");this.dd.addInvalidHandleType("TEXTAREA");}};YAHOO.widget.Panel.prototype.buildMask=function(){if(!this.mask){this.mask=document.createElement("DIV");this.mask.id=this.id+"_mask";this.mask.className="mask";this.mask.innerHTML="&#160;";var maskClick=function(e,obj){YAHOO.util.Event.stopEvent(e);};var firstChild=document.body.firstChild;if(firstChild){document.body.insertBefore(this.mask,document.body.firstChild);}else{document.body.appendChild(this.mask);}}};YAHOO.widget.Panel.prototype.hideMask=function(){if(this.cfg.getProperty("modal")&&this.mask){this.mask.style.display="none";this.hideMaskEvent.fire();YAHOO.util.Dom.removeClass(document.body,"masked");}};YAHOO.widget.Panel.prototype.showMask=function(){if(this.cfg.getProperty("modal")&&this.mask){YAHOO.util.Dom.addClass(document.body,"masked");this.sizeMask();this.mask.style.display="block";this.showMaskEvent.fire();}};YAHOO.widget.Panel.prototype.sizeMask=function(){if(this.mask){this.mask.style.height=YAHOO.util.Dom.getDocumentHeight()+"px";this.mask.style.width=YAHOO.util.Dom.getDocumentWidth()+"px";}};YAHOO.widget.Panel.prototype.render=function(appendToNode){return YAHOO.widget.Panel.superclass.render.call(this,appendToNode,this.innerElement);};YAHOO.widget.Panel.prototype.toString=function(){return"Panel "+this.id;};YAHOO.widget.Dialog=function(el,userConfig){YAHOO.widget.Dialog.superclass.constructor.call(this,el,userConfig);};YAHOO.extend(YAHOO.widget.Dialog,YAHOO.widget.Panel);YAHOO.widget.Dialog.CSS_DIALOG="dialog";YAHOO.widget.Dialog.prototype.initDefaultConfig=function(){YAHOO.widget.Dialog.superclass.initDefaultConfig.call(this);this.callback={success:null,failure:null,argument:null};this.cfg.addProperty("postmethod",{value:"async",handler:this.configPostMethod,validator:function(val){if(val!="form"&&val!="async"&&val!="none"&&val!="manual"){return false;}else{return true;}}});this.cfg.addProperty("buttons",{value:"none",handler:this.configButtons});};YAHOO.widget.Dialog.prototype.initEvents=function(){YAHOO.widget.Dialog.superclass.initEvents.call(this);this.beforeSubmitEvent=new YAHOO.util.CustomEvent("beforeSubmit");this.submitEvent=new YAHOO.util.CustomEvent("submit");this.manualSubmitEvent=new YAHOO.util.CustomEvent("manualSubmit");this.asyncSubmitEvent=new YAHOO.util.CustomEvent("asyncSubmit");this.formSubmitEvent=new YAHOO.util.CustomEvent("formSubmit");this.cancelEvent=new YAHOO.util.CustomEvent("cancel");};YAHOO.widget.Dialog.prototype.init=function(el,userConfig){YAHOO.widget.Dialog.superclass.init.call(this,el);this.beforeInitEvent.fire(YAHOO.widget.Dialog);YAHOO.util.Dom.addClass(this.element,YAHOO.widget.Dialog.CSS_DIALOG);this.cfg.setProperty("visible",false);if(userConfig){this.cfg.applyConfig(userConfig,true);}
this.showEvent.subscribe(this.focusFirst,this,true);this.beforeHideEvent.subscribe(this.blurButtons,this,true);this.beforeRenderEvent.subscribe(function(){var buttonCfg=this.cfg.getProperty("buttons");if(buttonCfg&&buttonCfg!="none"){if(!this.footer){this.setFooter("");}}},this,true);this.initEvent.fire(YAHOO.widget.Dialog);};YAHOO.widget.Dialog.prototype.doSubmit=function(){var pm=this.cfg.getProperty("postmethod");switch(pm){case"async":var method=this.form.getAttribute("method")||'POST';method=method.toUpperCase();YAHOO.util.Connect.setForm(this.form);var cObj=YAHOO.util.Connect.asyncRequest(method,this.form.getAttribute("action"),this.callback);this.asyncSubmitEvent.fire();break;case"form":this.form.submit();this.formSubmitEvent.fire();break;case"none":case"manual":this.manualSubmitEvent.fire();break;}};YAHOO.widget.Dialog.prototype.registerForm=function(){var form=this.element.getElementsByTagName("FORM")[0];if(!form){var formHTML="<form name=\"frm_"+this.id+"\" action=\"\"></form>";this.body.innerHTML+=formHTML;form=this.element.getElementsByTagName("FORM")[0];}
this.firstFormElement=function(){for(var f=0;f<form.elements.length;f++){var el=form.elements[f];if(el.focus&&!el.disabled){if(el.type&&el.type!="hidden"){return el;}}}
return null;}();this.lastFormElement=function(){for(var f=form.elements.length-1;f>=0;f--){var el=form.elements[f];if(el.focus&&!el.disabled){if(el.type&&el.type!="hidden"){return el;}}}
return null;}();this.form=form;if(this.cfg.getProperty("modal")&&this.form){var me=this;var firstElement=this.firstFormElement||this.firstButton;if(firstElement){this.preventBackTab=new YAHOO.util.KeyListener(firstElement,{shift:true,keys:9},{fn:me.focusLast,scope:me,correctScope:true});this.showEvent.subscribe(this.preventBackTab.enable,this.preventBackTab,true);this.hideEvent.subscribe(this.preventBackTab.disable,this.preventBackTab,true);}
var lastElement=this.lastButton||this.lastFormElement;if(lastElement){this.preventTabOut=new YAHOO.util.KeyListener(lastElement,{shift:false,keys:9},{fn:me.focusFirst,scope:me,correctScope:true});this.showEvent.subscribe(this.preventTabOut.enable,this.preventTabOut,true);this.hideEvent.subscribe(this.preventTabOut.disable,this.preventTabOut,true);}}};YAHOO.widget.Dialog.prototype.configClose=function(type,args,obj){var val=args[0];var doCancel=function(e,obj){obj.cancel();};if(val){if(!this.close){this.close=document.createElement("DIV");YAHOO.util.Dom.addClass(this.close,"close");if(this.isSecure){YAHOO.util.Dom.addClass(this.close,"secure");}else{YAHOO.util.Dom.addClass(this.close,"nonsecure");}
this.close.innerHTML="&#160;";this.innerElement.appendChild(this.close);YAHOO.util.Event.addListener(this.close,"click",doCancel,this);}else{this.close.style.display="block";}}else{if(this.close){this.close.style.display="none";}}};YAHOO.widget.Dialog.prototype.configButtons=function(type,args,obj){var buttons=args[0];if(buttons!="none"){this.buttonSpan=null;this.buttonSpan=document.createElement("SPAN");this.buttonSpan.className="button-group";for(var b=0;b<buttons.length;b++){var button=buttons[b];var htmlButton=document.createElement("BUTTON");htmlButton.setAttribute("type","button");if(button.isDefault){htmlButton.className="default";this.defaultHtmlButton=htmlButton;}
htmlButton.appendChild(document.createTextNode(button.text));YAHOO.util.Event.addListener(htmlButton,"click",button.handler,this,true);this.buttonSpan.appendChild(htmlButton);button.htmlButton=htmlButton;if(b===0){this.firstButton=button.htmlButton;}
if(b==(buttons.length-1)){this.lastButton=button.htmlButton;}}
this.setFooter(this.buttonSpan);this.cfg.refireEvent("iframe");this.cfg.refireEvent("underlay");}else{if(this.buttonSpan){if(this.buttonSpan.parentNode){this.buttonSpan.parentNode.removeChild(this.buttonSpan);}
this.buttonSpan=null;this.firstButton=null;this.lastButton=null;this.defaultHtmlButton=null;}}};YAHOO.widget.Dialog.prototype.focusFirst=function(type,args,obj){if(args){var e=args[1];if(e){YAHOO.util.Event.stopEvent(e);}}
if(this.firstFormElement){this.firstFormElement.focus();}else{this.focusDefaultButton();}};YAHOO.widget.Dialog.prototype.focusLast=function(type,args,obj){if(args){var e=args[1];if(e){YAHOO.util.Event.stopEvent(e);}}
var buttons=this.cfg.getProperty("buttons");if(buttons&&buttons instanceof Array){this.focusLastButton();}else{if(this.lastFormElement){this.lastFormElement.focus();}}};YAHOO.widget.Dialog.prototype.focusDefaultButton=function(){if(this.defaultHtmlButton){this.defaultHtmlButton.focus();}};YAHOO.widget.Dialog.prototype.blurButtons=function(){var buttons=this.cfg.getProperty("buttons");if(buttons&&buttons instanceof Array){var html=buttons[0].htmlButton;if(html){html.blur();}}};YAHOO.widget.Dialog.prototype.focusFirstButton=function(){var buttons=this.cfg.getProperty("buttons");if(buttons&&buttons instanceof Array){var html=buttons[0].htmlButton;if(html){html.focus();}}};YAHOO.widget.Dialog.prototype.focusLastButton=function(){var buttons=this.cfg.getProperty("buttons");if(buttons&&buttons instanceof Array){var html=buttons[buttons.length-1].htmlButton;if(html){html.focus();}}};YAHOO.widget.Dialog.prototype.configPostMethod=function(type,args,obj){var postmethod=args[0];this.registerForm();YAHOO.util.Event.addListener(this.form,"submit",function(e){YAHOO.util.Event.stopEvent(e);this.submit();this.form.blur();},this,true);};YAHOO.widget.Dialog.prototype.validate=function(){return true;};YAHOO.widget.Dialog.prototype.submit=function(){if(this.validate()){this.beforeSubmitEvent.fire();this.doSubmit();this.submitEvent.fire();this.hide();return true;}else{return false;}};YAHOO.widget.Dialog.prototype.cancel=function(){this.cancelEvent.fire();this.hide();};YAHOO.widget.Dialog.prototype.getData=function(){var form=this.form;var data={};if(form){for(var i=0;i<form.elements.length;i++){var formItem=form.elements[i];if(formItem){if(formItem.tagName){switch(formItem.tagName){case"INPUT":switch(formItem.type){case"checkbox":data[formItem.name]=formItem.checked;break;case"textbox":case"text":case"hidden":data[formItem.name]=formItem.value;break;}
break;case"TEXTAREA":data[formItem.name]=formItem.value;break;case"SELECT":var val=[];for(var x=0;x<formItem.options.length;x++){var option=formItem.options[x];if(option.selected){var selval=option.value;if(!selval||selval===""){selval=option.text;}
val[val.length]=selval;}}
data[formItem.name]=val;break;}}else if(formItem[0]&&formItem[0].tagName){if(formItem[0].tagName=="INPUT"){switch(formItem[0].type){case"radio":for(var r=0;r<formItem.length;r++){var radio=formItem[r];if(radio.checked){data[radio.name]=radio.value;break;}}
break;case"checkbox":var cbArray=[];for(var c=0;c<formItem.length;c++){var check=formItem[c];if(check.checked){cbArray[cbArray.length]=check.value;}}
data[formItem[0].name]=cbArray;break;}}}}}}
return data;};YAHOO.widget.Dialog.prototype.toString=function(){return"Dialog "+this.id;};YAHOO.widget.SimpleDialog=function(el,userConfig){YAHOO.widget.SimpleDialog.superclass.constructor.call(this,el,userConfig);};YAHOO.extend(YAHOO.widget.SimpleDialog,YAHOO.widget.Dialog);YAHOO.widget.SimpleDialog.ICON_BLOCK="nt/ic/ut/bsc/blck16_1.gif";YAHOO.widget.SimpleDialog.ICON_ALARM="nt/ic/ut/bsc/alrt16_1.gif";YAHOO.widget.SimpleDialog.ICON_HELP="nt/ic/ut/bsc/hlp16_1.gif";YAHOO.widget.SimpleDialog.ICON_INFO="nt/ic/ut/bsc/info16_1.gif";YAHOO.widget.SimpleDialog.ICON_WARN="nt/ic/ut/bsc/warn16_1.gif";YAHOO.widget.SimpleDialog.ICON_TIP="nt/ic/ut/bsc/tip16_1.gif";YAHOO.widget.SimpleDialog.CSS_SIMPLEDIALOG="simple-dialog";YAHOO.widget.SimpleDialog.prototype.initDefaultConfig=function(){YAHOO.widget.SimpleDialog.superclass.initDefaultConfig.call(this);this.cfg.addProperty("icon",{value:"none",handler:this.configIcon,suppressEvent:true});this.cfg.addProperty("text",{value:"",handler:this.configText,suppressEvent:true,supercedes:["icon"]});};YAHOO.widget.SimpleDialog.prototype.init=function(el,userConfig){YAHOO.widget.SimpleDialog.superclass.init.call(this,el);this.beforeInitEvent.fire(YAHOO.widget.SimpleDialog);YAHOO.util.Dom.addClass(this.element,YAHOO.widget.SimpleDialog.CSS_SIMPLEDIALOG);this.cfg.queueProperty("postmethod","manual");if(userConfig){this.cfg.applyConfig(userConfig,true);}
this.beforeRenderEvent.subscribe(function(){if(!this.body){this.setBody("");}},this,true);this.initEvent.fire(YAHOO.widget.SimpleDialog);};YAHOO.widget.SimpleDialog.prototype.registerForm=function(){YAHOO.widget.SimpleDialog.superclass.registerForm.call(this);this.form.innerHTML+="<input type=\"hidden\" name=\""+this.id+"\" value=\"\"/>";};YAHOO.widget.SimpleDialog.prototype.configIcon=function(type,args,obj){var icon=args[0];if(icon&&icon!="none"){var iconHTML="<img src=\""+this.imageRoot+icon+"\" class=\"icon\" />";this.body.innerHTML=iconHTML+this.body.innerHTML;}};YAHOO.widget.SimpleDialog.prototype.configText=function(type,args,obj){var text=args[0];if(text){this.setBody(text);this.cfg.refireEvent("icon");}};YAHOO.widget.SimpleDialog.prototype.toString=function(){return"SimpleDialog "+this.id;};YAHOO.widget.ContainerEffect=function(overlay,attrIn,attrOut,targetElement,animClass){if(!animClass){animClass=YAHOO.util.Anim;}
this.overlay=overlay;this.attrIn=attrIn;this.attrOut=attrOut;this.targetElement=targetElement||overlay.element;this.animClass=animClass;};YAHOO.widget.ContainerEffect.prototype.init=function(){this.beforeAnimateInEvent=new YAHOO.util.CustomEvent("beforeAnimateIn");this.beforeAnimateOutEvent=new YAHOO.util.CustomEvent("beforeAnimateOut");this.animateInCompleteEvent=new YAHOO.util.CustomEvent("animateInComplete");this.animateOutCompleteEvent=new YAHOO.util.CustomEvent("animateOutComplete");this.animIn=new this.animClass(this.targetElement,this.attrIn.attributes,this.attrIn.duration,this.attrIn.method);this.animIn.onStart.subscribe(this.handleStartAnimateIn,this);this.animIn.onTween.subscribe(this.handleTweenAnimateIn,this);this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn,this);this.animOut=new this.animClass(this.targetElement,this.attrOut.attributes,this.attrOut.duration,this.attrOut.method);this.animOut.onStart.subscribe(this.handleStartAnimateOut,this);this.animOut.onTween.subscribe(this.handleTweenAnimateOut,this);this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut,this);};YAHOO.widget.ContainerEffect.prototype.animateIn=function(){this.beforeAnimateInEvent.fire();this.animIn.animate();};YAHOO.widget.ContainerEffect.prototype.animateOut=function(){this.beforeAnimateOutEvent.fire();this.animOut.animate();};YAHOO.widget.ContainerEffect.prototype.handleStartAnimateIn=function(type,args,obj){};YAHOO.widget.ContainerEffect.prototype.handleTweenAnimateIn=function(type,args,obj){};YAHOO.widget.ContainerEffect.prototype.handleCompleteAnimateIn=function(type,args,obj){};YAHOO.widget.ContainerEffect.prototype.handleStartAnimateOut=function(type,args,obj){};YAHOO.widget.ContainerEffect.prototype.handleTweenAnimateOut=function(type,args,obj){};YAHOO.widget.ContainerEffect.prototype.handleCompleteAnimateOut=function(type,args,obj){};YAHOO.widget.ContainerEffect.prototype.toString=function(){var output="ContainerEffect";if(this.overlay){output+=" ["+this.overlay.toString()+"]";}
return output;};YAHOO.widget.ContainerEffect.FADE=function(overlay,dur){var fade=new YAHOO.widget.ContainerEffect(overlay,{attributes:{opacity:{from:0,to:1}},duration:dur,method:YAHOO.util.Easing.easeIn},{attributes:{opacity:{to:0}},duration:dur,method:YAHOO.util.Easing.easeOut},overlay.element);fade.handleStartAnimateIn=function(type,args,obj){YAHOO.util.Dom.addClass(obj.overlay.element,"hide-select");if(!obj.overlay.underlay){obj.overlay.cfg.refireEvent("underlay");}
if(obj.overlay.underlay){obj.initialUnderlayOpacity=YAHOO.util.Dom.getStyle(obj.overlay.underlay,"opacity");obj.overlay.underlay.style.filter=null;}
YAHOO.util.Dom.setStyle(obj.overlay.element,"visibility","visible");YAHOO.util.Dom.setStyle(obj.overlay.element,"opacity",0);};fade.handleCompleteAnimateIn=function(type,args,obj){YAHOO.util.Dom.removeClass(obj.overlay.element,"hide-select");if(obj.overlay.element.style.filter){obj.overlay.element.style.filter=null;}
if(obj.overlay.underlay){YAHOO.util.Dom.setStyle(obj.overlay.underlay,"opacity",obj.initialUnderlayOpacity);}
obj.overlay.cfg.refireEvent("iframe");obj.animateInCompleteEvent.fire();};fade.handleStartAnimateOut=function(type,args,obj){YAHOO.util.Dom.addClass(obj.overlay.element,"hide-select");if(obj.overlay.underlay){obj.overlay.underlay.style.filter=null;}};fade.handleCompleteAnimateOut=function(type,args,obj){YAHOO.util.Dom.removeClass(obj.overlay.element,"hide-select");if(obj.overlay.element.style.filter){obj.overlay.element.style.filter=null;}
YAHOO.util.Dom.setStyle(obj.overlay.element,"visibility","hidden");YAHOO.util.Dom.setStyle(obj.overlay.element,"opacity",1);obj.overlay.cfg.refireEvent("iframe");obj.animateOutCompleteEvent.fire();};fade.init();return fade;};YAHOO.widget.ContainerEffect.SLIDE=function(overlay,dur){var x=overlay.cfg.getProperty("x")||YAHOO.util.Dom.getX(overlay.element);var y=overlay.cfg.getProperty("y")||YAHOO.util.Dom.getY(overlay.element);var clientWidth=YAHOO.util.Dom.getClientWidth();var offsetWidth=overlay.element.offsetWidth;var slide=new YAHOO.widget.ContainerEffect(overlay,{attributes:{points:{to:[x,y]}},duration:dur,method:YAHOO.util.Easing.easeIn},{attributes:{points:{to:[(clientWidth+25),y]}},duration:dur,method:YAHOO.util.Easing.easeOut},overlay.element,YAHOO.util.Motion);slide.handleStartAnimateIn=function(type,args,obj){obj.overlay.element.style.left=(-25-offsetWidth)+"px";obj.overlay.element.style.top=y+"px";};slide.handleTweenAnimateIn=function(type,args,obj){var pos=YAHOO.util.Dom.getXY(obj.overlay.element);var currentX=pos[0];var currentY=pos[1];if(YAHOO.util.Dom.getStyle(obj.overlay.element,"visibility")=="hidden"&&currentX<x){YAHOO.util.Dom.setStyle(obj.overlay.element,"visibility","visible");}
obj.overlay.cfg.setProperty("xy",[currentX,currentY],true);obj.overlay.cfg.refireEvent("iframe");};slide.handleCompleteAnimateIn=function(type,args,obj){obj.overlay.cfg.setProperty("xy",[x,y],true);obj.startX=x;obj.startY=y;obj.overlay.cfg.refireEvent("iframe");obj.animateInCompleteEvent.fire();};slide.handleStartAnimateOut=function(type,args,obj){var vw=YAHOO.util.Dom.getViewportWidth();var pos=YAHOO.util.Dom.getXY(obj.overlay.element);var yso=pos[1];var currentTo=obj.animOut.attributes.points.to;obj.animOut.attributes.points.to=[(vw+25),yso];};slide.handleTweenAnimateOut=function(type,args,obj){var pos=YAHOO.util.Dom.getXY(obj.overlay.element);var xto=pos[0];var yto=pos[1];obj.overlay.cfg.setProperty("xy",[xto,yto],true);obj.overlay.cfg.refireEvent("iframe");};slide.handleCompleteAnimateOut=function(type,args,obj){YAHOO.util.Dom.setStyle(obj.overlay.element,"visibility","hidden");obj.overlay.cfg.setProperty("xy",[x,y]);obj.animateOutCompleteEvent.fire();};slide.init();return slide;};




/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.2
*/


YAHOO.widget.Slider=function(sElementId,sGroup,oThumb,sType){if(sElementId){this.init(sElementId,sGroup,true);this.initSlider(sType);this.initThumb(oThumb);}};YAHOO.widget.Slider.getHorizSlider=function(sBGElId,sHandleElId,iLeft,iRight,iTickSize){return new YAHOO.widget.Slider(sBGElId,sBGElId,new YAHOO.widget.SliderThumb(sHandleElId,sBGElId,iLeft,iRight,0,0,iTickSize),"horiz");};YAHOO.widget.Slider.getVertSlider=function(sBGElId,sHandleElId,iUp,iDown,iTickSize){return new YAHOO.widget.Slider(sBGElId,sBGElId,new YAHOO.widget.SliderThumb(sHandleElId,sBGElId,0,0,iUp,iDown,iTickSize),"vert");};YAHOO.widget.Slider.getSliderRegion=function(sBGElId,sHandleElId,iLeft,iRight,iUp,iDown,iTickSize){return new YAHOO.widget.Slider(sBGElId,sBGElId,new YAHOO.widget.SliderThumb(sHandleElId,sBGElId,iLeft,iRight,iUp,iDown,iTickSize),"region");};YAHOO.widget.Slider.ANIM_AVAIL=true;YAHOO.extend(YAHOO.widget.Slider,YAHOO.util.DragDrop,{initSlider:function(sType){this.type=sType;this.createEvent("change",this);this.createEvent("slideStart",this);this.createEvent("slideEnd",this);this.isTarget=false;this.animate=YAHOO.widget.Slider.ANIM_AVAIL;this.backgroundEnabled=true;this.tickPause=40;this.enableKeys=true;this.keyIncrement=20;this.moveComplete=true;this.animationDuration=0.2;},initThumb:function(t){var self=this;this.thumb=t;t.cacheBetweenDrags=true;t.onChange=function(){self.handleThumbChange();};if(t._isHoriz&&t.xTicks&&t.xTicks.length){this.tickPause=Math.round(360/t.xTicks.length);}else if(t.yTicks&&t.yTicks.length){this.tickPause=Math.round(360/t.yTicks.length);}
t.onMouseDown=function(){return self.focus();};t.onMouseUp=function(){self.thumbMouseUp();};t.onDrag=function(){self.fireEvents(true);};t.onAvailable=function(){return self.setStartSliderState();};},onAvailable:function(){var Event=YAHOO.util.Event;Event.on(this.id,"keydown",this.handleKeyDown,this,true);Event.on(this.id,"keypress",this.handleKeyPress,this,true);},handleKeyPress:function(e){if(this.enableKeys){var Event=YAHOO.util.Event;var kc=Event.getCharCode(e);switch(kc){case 0x25:case 0x26:case 0x27:case 0x28:case 0x24:case 0x23:Event.preventDefault(e);break;default:}}},handleKeyDown:function(e){if(this.enableKeys){var Event=YAHOO.util.Event;var kc=Event.getCharCode(e),t=this.thumb;var h=this.getXValue(),v=this.getYValue();var horiz=false;var changeValue=true;switch(kc){case 0x25:h-=this.keyIncrement;break;case 0x26:v-=this.keyIncrement;break;case 0x27:h+=this.keyIncrement;break;case 0x28:v+=this.keyIncrement;break;case 0x24:h=t.leftConstraint;v=t.topConstraint;break;case 0x23:h=t.rightConstraint;v=t.bottomConstraint;break;default:changeValue=false;}
if(changeValue){if(t._isRegion){this.setRegionValue(h,v,true);}else{var newVal=(t._isHoriz)?h:v;this.setValue(newVal,true);}
Event.stopEvent(e);}}},setStartSliderState:function(){this.setThumbCenterPoint();this.baselinePos=YAHOO.util.Dom.getXY(this.getEl());this.thumb.startOffset=this.thumb.getOffsetFromParent(this.baselinePos);if(this.thumb._isRegion){if(this.deferredSetRegionValue){this.setRegionValue.apply(this,this.deferredSetRegionValue,true);this.deferredSetRegionValue=null;}else{this.setRegionValue(0,0,true,true);}}else{if(this.deferredSetValue){this.setValue.apply(this,this.deferredSetValue,true);this.deferredSetValue=null;}else{this.setValue(0,true,true);}}},setThumbCenterPoint:function(){var el=this.thumb.getEl();if(el){this.thumbCenterPoint={x:parseInt(el.offsetWidth/2,10),y:parseInt(el.offsetHeight/2,10)};}},lock:function(){this.thumb.lock();this.locked=true;},unlock:function(){this.thumb.unlock();this.locked=false;},thumbMouseUp:function(){if(!this.isLocked()&&!this.moveComplete){this.endMove();}},getThumb:function(){return this.thumb;},focus:function(){var el=this.getEl();if(el.focus){try{el.focus();}catch(e){}}
this.verifyOffset();if(this.isLocked()){return false;}else{this.onSlideStart();return true;}},onChange:function(firstOffset,secondOffset){},onSlideStart:function(){},onSlideEnd:function(){},getValue:function(){return this.thumb.getValue();},getXValue:function(){return this.thumb.getXValue();},getYValue:function(){return this.thumb.getYValue();},handleThumbChange:function(){var t=this.thumb;if(t._isRegion){t.onChange(t.getXValue(),t.getYValue());this.fireEvent("change",{x:t.getXValue(),y:t.getYValue()});}else{t.onChange(t.getValue());this.fireEvent("change",t.getValue());}},setValue:function(newOffset,skipAnim,force){if(!this.thumb.available){this.deferredSetValue=arguments;return false;}
if(this.isLocked()&&!force){return false;}
if(isNaN(newOffset)){return false;}
var t=this.thumb;var newX,newY;this.verifyOffset(true);if(t._isRegion){return false;}else if(t._isHoriz){this.onSlideStart();newX=t.initPageX+newOffset+this.thumbCenterPoint.x;this.moveThumb(newX,t.initPageY,skipAnim);}else{this.onSlideStart();newY=t.initPageY+newOffset+this.thumbCenterPoint.y;this.moveThumb(t.initPageX,newY,skipAnim);}
return true;},setRegionValue:function(newOffset,newOffset2,skipAnim,force){if(!this.thumb.available){this.deferredSetRegionValue=arguments;return false;}
if(this.isLocked()&&!force){return false;}
if(isNaN(newOffset)){return false;}
var t=this.thumb;if(t._isRegion){this.onSlideStart();var newX=t.initPageX+newOffset+this.thumbCenterPoint.x;var newY=t.initPageY+newOffset2+this.thumbCenterPoint.y;this.moveThumb(newX,newY,skipAnim);return true;}
return false;},verifyOffset:function(checkPos){var newPos=YAHOO.util.Dom.getXY(this.getEl());if(newPos[0]!=this.baselinePos[0]||newPos[1]!=this.baselinePos[1]){this.thumb.resetConstraints();this.baselinePos=newPos;return false;}
return true;},moveThumb:function(x,y,skipAnim){var t=this.thumb;var self=this;if(!t.available){return;}
t.setDelta(this.thumbCenterPoint.x,this.thumbCenterPoint.y);var _p=t.getTargetCoord(x,y);var p=[_p.x,_p.y];this.fireEvent("slideStart");if(this.animate&&YAHOO.widget.Slider.ANIM_AVAIL&&t._graduated&&!skipAnim){this.lock();this.curCoord=YAHOO.util.Dom.getXY(this.thumb.getEl());setTimeout(function(){self.moveOneTick(p);},this.tickPause);}else if(this.animate&&YAHOO.widget.Slider.ANIM_AVAIL&&!skipAnim){this.lock();var oAnim=new YAHOO.util.Motion(t.id,{points:{to:p}},this.animationDuration,YAHOO.util.Easing.easeOut);oAnim.onComplete.subscribe(function(){self.endMove();});oAnim.animate();}else{t.setDragElPos(x,y);this.endMove();}},moveOneTick:function(finalCoord){var t=this.thumb,tmp;var nextCoord=null;if(t._isRegion){nextCoord=this._getNextX(this.curCoord,finalCoord);var tmpX=(nextCoord)?nextCoord[0]:this.curCoord[0];nextCoord=this._getNextY([tmpX,this.curCoord[1]],finalCoord);}else if(t._isHoriz){nextCoord=this._getNextX(this.curCoord,finalCoord);}else{nextCoord=this._getNextY(this.curCoord,finalCoord);}
if(nextCoord){this.curCoord=nextCoord;this.thumb.alignElWithMouse(t.getEl(),nextCoord[0],nextCoord[1]);if(!(nextCoord[0]==finalCoord[0]&&nextCoord[1]==finalCoord[1])){var self=this;setTimeout(function(){self.moveOneTick(finalCoord);},this.tickPause);}else{this.endMove();}}else{this.endMove();}},_getNextX:function(curCoord,finalCoord){var t=this.thumb;var thresh;var tmp=[];var nextCoord=null;if(curCoord[0]>finalCoord[0]){thresh=t.tickSize-this.thumbCenterPoint.x;tmp=t.getTargetCoord(curCoord[0]-thresh,curCoord[1]);nextCoord=[tmp.x,tmp.y];}else if(curCoord[0]<finalCoord[0]){thresh=t.tickSize+this.thumbCenterPoint.x;tmp=t.getTargetCoord(curCoord[0]+thresh,curCoord[1]);nextCoord=[tmp.x,tmp.y];}else{}
return nextCoord;},_getNextY:function(curCoord,finalCoord){var t=this.thumb;var thresh;var tmp=[];var nextCoord=null;if(curCoord[1]>finalCoord[1]){thresh=t.tickSize-this.thumbCenterPoint.y;tmp=t.getTargetCoord(curCoord[0],curCoord[1]-thresh);nextCoord=[tmp.x,tmp.y];}else if(curCoord[1]<finalCoord[1]){thresh=t.tickSize+this.thumbCenterPoint.y;tmp=t.getTargetCoord(curCoord[0],curCoord[1]+thresh);nextCoord=[tmp.x,tmp.y];}else{}
return nextCoord;},b4MouseDown:function(e){this.thumb.autoOffset();this.thumb.resetConstraints();},onMouseDown:function(e){if(!this.isLocked()&&this.backgroundEnabled){var x=YAHOO.util.Event.getPageX(e);var y=YAHOO.util.Event.getPageY(e);this.focus();this.moveThumb(x,y);}},onDrag:function(e){if(!this.isLocked()){var x=YAHOO.util.Event.getPageX(e);var y=YAHOO.util.Event.getPageY(e);this.moveThumb(x,y,true);}},endMove:function(){this.unlock();this.moveComplete=true;this.fireEvents();},fireEvents:function(thumbEvent){var t=this.thumb;if(!thumbEvent){t.cachePosition();}
if(!this.isLocked()){if(t._isRegion){var newX=t.getXValue();var newY=t.getYValue();if(newX!=this.previousX||newY!=this.previousY){this.onChange(newX,newY);this.fireEvent("change",{x:newX,y:newY});}
this.previousX=newX;this.previousY=newY;}else{var newVal=t.getValue();if(newVal!=this.previousVal){this.onChange(newVal);this.fireEvent("change",newVal);}
this.previousVal=newVal;}
if(this.moveComplete){this.onSlideEnd();this.fireEvent("slideEnd");this.moveComplete=false;}}},toString:function(){return("Slider ("+this.type+") "+this.id);}});YAHOO.augment(YAHOO.widget.Slider,YAHOO.util.EventProvider);YAHOO.widget.SliderThumb=function(id,sGroup,iLeft,iRight,iUp,iDown,iTickSize){if(id){YAHOO.widget.SliderThumb.superclass.constructor.call(this,id,sGroup);this.parentElId=sGroup;}
this.isTarget=false;this.tickSize=iTickSize;this.maintainOffset=true;this.initSlider(iLeft,iRight,iUp,iDown,iTickSize);this.scroll=false;};YAHOO.extend(YAHOO.widget.SliderThumb,YAHOO.util.DD,{startOffset:null,_isHoriz:false,_prevVal:0,_graduated:false,getOffsetFromParent0:function(parentPos){var myPos=YAHOO.util.Dom.getXY(this.getEl());var ppos=parentPos||YAHOO.util.Dom.getXY(this.parentElId);return[(myPos[0]-ppos[0]),(myPos[1]-ppos[1])];},getOffsetFromParent:function(parentPos){var el=this.getEl();if(!this.deltaOffset){var myPos=YAHOO.util.Dom.getXY(el);var ppos=parentPos||YAHOO.util.Dom.getXY(this.parentElId);var newOffset=[(myPos[0]-ppos[0]),(myPos[1]-ppos[1])];var l=parseInt(YAHOO.util.Dom.getStyle(el,"left"),10);var t=parseInt(YAHOO.util.Dom.getStyle(el,"top"),10);var deltaX=l-newOffset[0];var deltaY=t-newOffset[1];if(isNaN(deltaX)||isNaN(deltaY)){}else{this.deltaOffset=[deltaX,deltaY];}}else{var newLeft=parseInt(YAHOO.util.Dom.getStyle(el,"left"),10);var newTop=parseInt(YAHOO.util.Dom.getStyle(el,"top"),10);newOffset=[newLeft+this.deltaOffset[0],newTop+this.deltaOffset[1]];}
return newOffset;},initSlider:function(iLeft,iRight,iUp,iDown,iTickSize){this.initLeft=iLeft;this.initRight=iRight;this.initUp=iUp;this.initDown=iDown;this.setXConstraint(iLeft,iRight,iTickSize);this.setYConstraint(iUp,iDown,iTickSize);if(iTickSize&&iTickSize>1){this._graduated=true;}
this._isHoriz=(iLeft||iRight);this._isVert=(iUp||iDown);this._isRegion=(this._isHoriz&&this._isVert);},clearTicks:function(){YAHOO.widget.SliderThumb.superclass.clearTicks.call(this);this.tickSize=0;this._graduated=false;},getValue:function(){if(!this.available){return 0;}
var val=(this._isHoriz)?this.getXValue():this.getYValue();return val;},getXValue:function(){if(!this.available){return 0;}
var newOffset=this.getOffsetFromParent();return(newOffset[0]-this.startOffset[0]);},getYValue:function(){if(!this.available){return 0;}
var newOffset=this.getOffsetFromParent();return(newOffset[1]-this.startOffset[1]);},toString:function(){return"SliderThumb "+this.id;},onChange:function(x,y){}});if("undefined"==typeof YAHOO.util.Anim){YAHOO.widget.Slider.ANIM_AVAIL=false;}



/*../vendor/yui_252/build/yahoo-dom-event/yahoo-dom-event.js*/

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.5.2
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=A[C].split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules;if(!I[A]){I[A]={versions:[],builds:[]};}var B=I[A],H=D.version,G=D.build,F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(var C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null,air:0};var B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}A=B.match(/AdobeAIR\/([^\s]*)/);if(A){C.air=A[0];}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var A=YAHOO.lang,C=["toString","valueOf"],B={isArray:function(D){if(D){return A.isNumber(D.length)&&A.isFunction(D.splice);}return false;},isBoolean:function(D){return typeof D==="boolean";},isFunction:function(D){return typeof D==="function";},isNull:function(D){return D===null;},isNumber:function(D){return typeof D==="number"&&isFinite(D);},isObject:function(D){return(D&&(typeof D==="object"||A.isFunction(D)))||false;},isString:function(D){return typeof D==="string";},isUndefined:function(D){return typeof D==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(F,E){for(var D=0;D<C.length;D=D+1){var H=C[D],G=E[H];if(A.isFunction(G)&&G!=Object.prototype[H]){F[H]=G;}}}:function(){},extend:function(H,I,G){if(!I||!H){throw new Error("extend failed, please check that "+"all dependencies are included.");}var E=function(){};E.prototype=I.prototype;H.prototype=new E();H.prototype.constructor=H;H.superclass=I.prototype;if(I.prototype.constructor==Object.prototype.constructor){I.prototype.constructor=I;}if(G){for(var D in G){if(A.hasOwnProperty(G,D)){H.prototype[D]=G[D];}}A._IEEnumFix(H.prototype,G);}},augmentObject:function(H,G){if(!G||!H){throw new Error("Absorb failed, verify dependencies.");}var D=arguments,F,I,E=D[2];if(E&&E!==true){for(F=2;F<D.length;F=F+1){H[D[F]]=G[D[F]];}}else{for(I in G){if(E||!(I in H)){H[I]=G[I];}}A._IEEnumFix(H,G);}},augmentProto:function(G,F){if(!F||!G){throw new Error("Augment failed, verify dependencies.");}var D=[G.prototype,F.prototype];for(var E=2;E<arguments.length;E=E+1){D.push(arguments[E]);}A.augmentObject.apply(this,D);},dump:function(D,I){var F,H,K=[],L="{...}",E="f(){...}",J=", ",G=" => ";if(!A.isObject(D)){return D+"";}else{if(D instanceof Date||("nodeType" in D&&"tagName" in D)){return D;}else{if(A.isFunction(D)){return E;}}}I=(A.isNumber(I))?I:3;if(A.isArray(D)){K.push("[");for(F=0,H=D.length;F<H;F=F+1){if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}if(K.length>1){K.pop();}K.push("]");}else{K.push("{");for(F in D){if(A.hasOwnProperty(D,F)){K.push(F+G);if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}}if(K.length>1){K.pop();}K.push("}");}return K.join("");},substitute:function(S,E,L){var I,H,G,O,P,R,N=[],F,J="dump",M=" ",D="{",Q="}";for(;;){I=S.lastIndexOf(D);if(I<0){break;}H=S.indexOf(Q,I);if(I+1>=H){break;}F=S.substring(I+1,H);O=F;R=null;G=O.indexOf(M);if(G>-1){R=O.substring(G+1);O=O.substring(0,G);}P=E[O];if(L){P=L(O,P,R);}if(A.isObject(P)){if(A.isArray(P)){P=A.dump(P,parseInt(R,10));}else{R=R||"";var K=R.indexOf(J);if(K>-1){R=R.substring(4);}if(P.toString===Object.prototype.toString||K>-1){P=A.dump(P,parseInt(R,10));}else{P=P.toString();}}}else{if(!A.isString(P)&&!A.isNumber(P)){P="~-"+N.length+"-~";N[N.length]=F;}}S=S.substring(0,I)+P+S.substring(H+1);}for(I=N.length-1;I>=0;I=I-1){S=S.replace(new RegExp("~-"+I+"-~"),"{"+N[I]+"}","g");}return S;},trim:function(D){try{return D.replace(/^\s+|\s+$/g,"");}catch(E){return D;}},merge:function(){var G={},E=arguments;for(var F=0,D=E.length;F<D;F=F+1){A.augmentObject(G,E[F],true);}return G;},later:function(K,E,L,G,H){K=K||0;E=E||{};var F=L,J=G,I,D;if(A.isString(L)){F=E[L];}if(!F){throw new TypeError("method undefined");}if(!A.isArray(J)){J=[G];}I=function(){F.apply(E,J);};D=(H)?setInterval(I,K):setTimeout(I,K);return{interval:H,cancel:function(){if(this.interval){clearInterval(D);}else{clearTimeout(D);}}};},isValue:function(D){return(A.isObject(D)||A.isString(D)||A.isNumber(D)||A.isBoolean(D));}};A.hasOwnProperty=(Object.prototype.hasOwnProperty)?function(D,E){return D&&D.hasOwnProperty(E);}:function(D,E){return !A.isUndefined(D[E])&&D.constructor.prototype[E]!==D[E];};B.augmentObject(A,B,true);YAHOO.util.Lang=A;A.augment=A.augmentProto;YAHOO.augment=A.augmentProto;YAHOO.extend=A.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.5.2",build:"1076"});(function(){var B=YAHOO.util,K,I,J={},F={},M=window.document;YAHOO.env._id_counter=YAHOO.env._id_counter||0;var C=YAHOO.env.ua.opera,L=YAHOO.env.ua.webkit,A=YAHOO.env.ua.gecko,G=YAHOO.env.ua.ie;var E={HYPHEN:/(-[a-z])/i,ROOT_TAG:/^body|html$/i,OP_SCROLL:/^(?:inline|table-row)$/i};var N=function(P){if(!E.HYPHEN.test(P)){return P;}if(J[P]){return J[P];}var Q=P;while(E.HYPHEN.exec(Q)){Q=Q.replace(RegExp.$1,RegExp.$1.substr(1).toUpperCase());}J[P]=Q;return Q;};var O=function(Q){var P=F[Q];if(!P){P=new RegExp("(?:^|\\s+)"+Q+"(?:\\s+|$)");F[Q]=P;}return P;};if(M.defaultView&&M.defaultView.getComputedStyle){K=function(P,S){var R=null;if(S=="float"){S="cssFloat";}var Q=P.ownerDocument.defaultView.getComputedStyle(P,"");if(Q){R=Q[N(S)];}return P.style[S]||R;};}else{if(M.documentElement.currentStyle&&G){K=function(P,R){switch(N(R)){case"opacity":var T=100;try{T=P.filters["DXImageTransform.Microsoft.Alpha"].opacity;}catch(S){try{T=P.filters("alpha").opacity;}catch(S){}}return T/100;case"float":R="styleFloat";default:var Q=P.currentStyle?P.currentStyle[R]:null;return(P.style[R]||Q);}};}else{K=function(P,Q){return P.style[Q];};}}if(G){I=function(P,Q,R){switch(Q){case"opacity":if(YAHOO.lang.isString(P.style.filter)){P.style.filter="alpha(opacity="+R*100+")";if(!P.currentStyle||!P.currentStyle.hasLayout){P.style.zoom=1;}}break;case"float":Q="styleFloat";default:P.style[Q]=R;}};}else{I=function(P,Q,R){if(Q=="float"){Q="cssFloat";}P.style[Q]=R;};}var D=function(P,Q){return P&&P.nodeType==1&&(!Q||Q(P));};YAHOO.util.Dom={get:function(R){if(R&&(R.nodeType||R.item)){return R;}if(YAHOO.lang.isString(R)||!R){return M.getElementById(R);}if(R.length!==undefined){var S=[];for(var Q=0,P=R.length;Q<P;++Q){S[S.length]=B.Dom.get(R[Q]);}return S;}return R;},getStyle:function(P,R){R=N(R);var Q=function(S){return K(S,R);};return B.Dom.batch(P,Q,B.Dom,true);},setStyle:function(P,R,S){R=N(R);var Q=function(T){I(T,R,S);};B.Dom.batch(P,Q,B.Dom,true);},getXY:function(P){var Q=function(R){if((R.parentNode===null||R.offsetParent===null||this.getStyle(R,"display")=="none")&&R!=R.ownerDocument.body){return false;}return H(R);};return B.Dom.batch(P,Q,B.Dom,true);},getX:function(P){var Q=function(R){return B.Dom.getXY(R)[0];};return B.Dom.batch(P,Q,B.Dom,true);},getY:function(P){var Q=function(R){return B.Dom.getXY(R)[1];};return B.Dom.batch(P,Q,B.Dom,true);},setXY:function(P,S,R){var Q=function(V){var U=this.getStyle(V,"position");if(U=="static"){this.setStyle(V,"position","relative");U="relative";}var X=this.getXY(V);if(X===false){return false;}var W=[parseInt(this.getStyle(V,"left"),10),parseInt(this.getStyle(V,"top"),10)];if(isNaN(W[0])){W[0]=(U=="relative")?0:V.offsetLeft;}if(isNaN(W[1])){W[1]=(U=="relative")?0:V.offsetTop;}if(S[0]!==null){V.style.left=S[0]-X[0]+W[0]+"px";}if(S[1]!==null){V.style.top=S[1]-X[1]+W[1]+"px";}if(!R){var T=this.getXY(V);if((S[0]!==null&&T[0]!=S[0])||(S[1]!==null&&T[1]!=S[1])){this.setXY(V,S,true);}}};B.Dom.batch(P,Q,B.Dom,true);},setX:function(Q,P){B.Dom.setXY(Q,[P,null]);},setY:function(P,Q){B.Dom.setXY(P,[null,Q]);},getRegion:function(P){var Q=function(R){if((R.parentNode===null||R.offsetParent===null||this.getStyle(R,"display")=="none")&&R!=R.ownerDocument.body){return false;}var S=B.Region.getRegion(R);return S;};return B.Dom.batch(P,Q,B.Dom,true);},getClientWidth:function(){return B.Dom.getViewportWidth();},getClientHeight:function(){return B.Dom.getViewportHeight();},getElementsByClassName:function(T,X,U,V){X=X||"*";U=(U)?B.Dom.get(U):null||M;if(!U){return[];}var Q=[],P=U.getElementsByTagName(X),W=O(T);for(var R=0,S=P.length;R<S;++R){if(W.test(P[R].className)){Q[Q.length]=P[R];if(V){V.call(P[R],P[R]);}}}return Q;},hasClass:function(R,Q){var P=O(Q);var S=function(T){return P.test(T.className);};return B.Dom.batch(R,S,B.Dom,true);},addClass:function(Q,P){var R=function(S){if(this.hasClass(S,P)){return false;}S.className=YAHOO.lang.trim([S.className,P].join(" "));return true;};return B.Dom.batch(Q,R,B.Dom,true);},removeClass:function(R,Q){var P=O(Q);var S=function(T){if(!Q||!this.hasClass(T,Q)){return false;}var U=T.className;T.className=U.replace(P," ");if(this.hasClass(T,Q)){this.removeClass(T,Q);}T.className=YAHOO.lang.trim(T.className);return true;};return B.Dom.batch(R,S,B.Dom,true);},replaceClass:function(S,Q,P){if(!P||Q===P){return false;}var R=O(Q);var T=function(U){if(!this.hasClass(U,Q)){this.addClass(U,P);return true;}U.className=U.className.replace(R," "+P+" ");if(this.hasClass(U,Q)){this.replaceClass(U,Q,P);}U.className=YAHOO.lang.trim(U.className);return true;};return B.Dom.batch(S,T,B.Dom,true);},generateId:function(P,R){R=R||"yui-gen";var Q=function(S){if(S&&S.id){return S.id;}var T=R+YAHOO.env._id_counter++;if(S){S.id=T;}return T;};return B.Dom.batch(P,Q,B.Dom,true)||Q.apply(B.Dom,arguments);},isAncestor:function(P,Q){P=B.Dom.get(P);Q=B.Dom.get(Q);if(!P||!Q){return false;}if(P.contains&&Q.nodeType&&!L){return P.contains(Q);}else{if(P.compareDocumentPosition&&Q.nodeType){return !!(P.compareDocumentPosition(Q)&16);}else{if(Q.nodeType){return !!this.getAncestorBy(Q,function(R){return R==P;});}}}return false;},inDocument:function(P){return this.isAncestor(M.documentElement,P);},getElementsBy:function(W,Q,R,T){Q=Q||"*";R=(R)?B.Dom.get(R):null||M;if(!R){return[];}var S=[],V=R.getElementsByTagName(Q);for(var U=0,P=V.length;U<P;++U){if(W(V[U])){S[S.length]=V[U];if(T){T(V[U]);}}}return S;},batch:function(T,W,V,R){T=(T&&(T.tagName||T.item))?T:B.Dom.get(T);if(!T||!W){return false;}var S=(R)?V:window;if(T.tagName||T.length===undefined){return W.call(S,T,V);}var U=[];for(var Q=0,P=T.length;Q<P;++Q){U[U.length]=W.call(S,T[Q],V);}return U;},getDocumentHeight:function(){var Q=(M.compatMode!="CSS1Compat")?M.body.scrollHeight:M.documentElement.scrollHeight;var P=Math.max(Q,B.Dom.getViewportHeight());return P;},getDocumentWidth:function(){var Q=(M.compatMode!="CSS1Compat")?M.body.scrollWidth:M.documentElement.scrollWidth;var P=Math.max(Q,B.Dom.getViewportWidth());return P;},getViewportHeight:function(){var P=self.innerHeight;
var Q=M.compatMode;if((Q||G)&&!C){P=(Q=="CSS1Compat")?M.documentElement.clientHeight:M.body.clientHeight;}return P;},getViewportWidth:function(){var P=self.innerWidth;var Q=M.compatMode;if(Q||G){P=(Q=="CSS1Compat")?M.documentElement.clientWidth:M.body.clientWidth;}return P;},getAncestorBy:function(P,Q){while(P=P.parentNode){if(D(P,Q)){return P;}}return null;},getAncestorByClassName:function(Q,P){Q=B.Dom.get(Q);if(!Q){return null;}var R=function(S){return B.Dom.hasClass(S,P);};return B.Dom.getAncestorBy(Q,R);},getAncestorByTagName:function(Q,P){Q=B.Dom.get(Q);if(!Q){return null;}var R=function(S){return S.tagName&&S.tagName.toUpperCase()==P.toUpperCase();};return B.Dom.getAncestorBy(Q,R);},getPreviousSiblingBy:function(P,Q){while(P){P=P.previousSibling;if(D(P,Q)){return P;}}return null;},getPreviousSibling:function(P){P=B.Dom.get(P);if(!P){return null;}return B.Dom.getPreviousSiblingBy(P);},getNextSiblingBy:function(P,Q){while(P){P=P.nextSibling;if(D(P,Q)){return P;}}return null;},getNextSibling:function(P){P=B.Dom.get(P);if(!P){return null;}return B.Dom.getNextSiblingBy(P);},getFirstChildBy:function(P,R){var Q=(D(P.firstChild,R))?P.firstChild:null;return Q||B.Dom.getNextSiblingBy(P.firstChild,R);},getFirstChild:function(P,Q){P=B.Dom.get(P);if(!P){return null;}return B.Dom.getFirstChildBy(P);},getLastChildBy:function(P,R){if(!P){return null;}var Q=(D(P.lastChild,R))?P.lastChild:null;return Q||B.Dom.getPreviousSiblingBy(P.lastChild,R);},getLastChild:function(P){P=B.Dom.get(P);return B.Dom.getLastChildBy(P);},getChildrenBy:function(Q,S){var R=B.Dom.getFirstChildBy(Q,S);var P=R?[R]:[];B.Dom.getNextSiblingBy(R,function(T){if(!S||S(T)){P[P.length]=T;}return false;});return P;},getChildren:function(P){P=B.Dom.get(P);if(!P){}return B.Dom.getChildrenBy(P);},getDocumentScrollLeft:function(P){P=P||M;return Math.max(P.documentElement.scrollLeft,P.body.scrollLeft);},getDocumentScrollTop:function(P){P=P||M;return Math.max(P.documentElement.scrollTop,P.body.scrollTop);},insertBefore:function(Q,P){Q=B.Dom.get(Q);P=B.Dom.get(P);if(!Q||!P||!P.parentNode){return null;}return P.parentNode.insertBefore(Q,P);},insertAfter:function(Q,P){Q=B.Dom.get(Q);P=B.Dom.get(P);if(!Q||!P||!P.parentNode){return null;}if(P.nextSibling){return P.parentNode.insertBefore(Q,P.nextSibling);}else{return P.parentNode.appendChild(Q);}},getClientRegion:function(){var R=B.Dom.getDocumentScrollTop(),Q=B.Dom.getDocumentScrollLeft(),S=B.Dom.getViewportWidth()+Q,P=B.Dom.getViewportHeight()+R;return new B.Region(R,S,P,Q);}};var H=function(){if(M.documentElement.getBoundingClientRect){return function(Q){var R=Q.getBoundingClientRect();var P=Q.ownerDocument;return[R.left+B.Dom.getDocumentScrollLeft(P),R.top+B.Dom.getDocumentScrollTop(P)];};}else{return function(R){var S=[R.offsetLeft,R.offsetTop];var Q=R.offsetParent;var P=(L&&B.Dom.getStyle(R,"position")=="absolute"&&R.offsetParent==R.ownerDocument.body);if(Q!=R){while(Q){S[0]+=Q.offsetLeft;S[1]+=Q.offsetTop;if(!P&&L&&B.Dom.getStyle(Q,"position")=="absolute"){P=true;}Q=Q.offsetParent;}}if(P){S[0]-=R.ownerDocument.body.offsetLeft;S[1]-=R.ownerDocument.body.offsetTop;}Q=R.parentNode;while(Q.tagName&&!E.ROOT_TAG.test(Q.tagName)){if(Q.scrollTop||Q.scrollLeft){if(!E.OP_SCROLL.test(B.Dom.getStyle(Q,"display"))){if(!C||B.Dom.getStyle(Q,"overflow")!=="visible"){S[0]-=Q.scrollLeft;S[1]-=Q.scrollTop;}}}Q=Q.parentNode;}return S;};}}();})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this[0]=B;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.5.2",build:"1076"});YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B<A;++B){var C=this.subscribers[B];if(C&&C.contains(D,F)){this._delete(B);E=true;}}return E;},fire:function(){this.lastError=null;var K=[],E=this.subscribers.length;if(!E&&this.silent){return true;}var I=[].slice.call(arguments,0),G=true,D,J=false;if(!this.silent){}var C=this.subscribers.slice(),A=YAHOO.util.Event.throwErrors;for(D=0;D<E;++D){var M=C[D];if(!M){J=true;}else{if(!this.silent){}var L=M.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var B=null;if(I.length>0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){for(var A=this.subscribers.length-1;A>-1;A--){this._delete(A);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var K=this;var L=function(){K._tryPreloadAttach();};this._interval=setInterval(L,this.POLL_INTERVAL);}},onAvailable:function(P,M,Q,O,N){var K=(YAHOO.lang.isString(P))?[P]:P;for(var L=0;L<K.length;L=L+1){F.push({id:K[L],fn:M,obj:Q,override:O,checkReady:N});}C=this.POLL_RETRYS;this.startInterval();},onContentReady:function(M,K,N,L){this.onAvailable(M,K,N,L,true);},onDOMReady:function(K,M,L){if(this.DOMReady){setTimeout(function(){var N=window;if(L){if(L===true){N=M;}else{N=L;}}K.call(N,"DOMReady",[],M);},0);}else{this.DOMReadyEvent.subscribe(K,M,L);}},addListener:function(M,K,V,Q,L){if(!V||!V.call){return false;}if(this._isValidCollection(M)){var W=true;for(var R=0,T=M.length;R<T;++R){W=this.on(M[R],K,V,Q,L)&&W;}return W;}else{if(YAHOO.lang.isString(M)){var P=this.getEl(M);if(P){M=P;}else{this.onAvailable(M,function(){YAHOO.util.Event.on(M,K,V,Q,L);});return true;}}}if(!M){return false;}if("unload"==K&&Q!==this){J[J.length]=[M,K,V,Q,L];return true;}var Y=M;if(L){if(L===true){Y=Q;}else{Y=L;}}var N=function(Z){return V.call(Y,YAHOO.util.Event.getEvent(Z,M),Q);};var X=[M,K,V,N,Y,Q,L];var S=I.length;I[S]=X;if(this.useLegacyEvent(M,K)){var O=this.getLegacyIndex(M,K);if(O==-1||M!=G[O][0]){O=G.length;B[M.id+K]=O;G[O]=[M,K,M["on"+K]];E[O]=[];M["on"+K]=function(Z){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(Z),O);};}E[O].push(X);}else{try{this._simpleAdd(M,K,N,false);}catch(U){this.lastError=U;this.removeListener(M,K,V);return false;}}return true;},fireLegacyEvent:function(O,M){var Q=true,K,S,R,T,P;S=E[M].slice();for(var L=0,N=S.length;L<N;++L){R=S[L];if(R&&R[this.WFN]){T=R[this.ADJ_SCOPE];P=R[this.WFN].call(T,O);Q=(Q&&P);}}K=G[M];if(K&&K[2]){K[2](O);}return Q;},getLegacyIndex:function(L,M){var K=this.generateId(L)+M;if(typeof B[K]=="undefined"){return -1;}else{return B[K];}},useLegacyEvent:function(L,M){if(this.webkit&&("click"==M||"dblclick"==M)){var K=parseInt(this.webkit,10);if(!isNaN(K)&&K<418){return true;}}return false;},removeListener:function(L,K,T){var O,R,V;if(typeof L=="string"){L=this.getEl(L);}else{if(this._isValidCollection(L)){var U=true;for(O=L.length-1;O>-1;O--){U=(this.removeListener(L[O],K,T)&&U);}return U;}}if(!T||!T.call){return this.purgeElement(L,false,K);}if("unload"==K){for(O=J.length-1;O>-1;O--){V=J[O];if(V&&V[0]==L&&V[1]==K&&V[2]==T){J.splice(O,1);return true;}}return false;}var P=null;var Q=arguments[3];if("undefined"===typeof Q){Q=this._getCacheIndex(L,K,T);}if(Q>=0){P=I[Q];}if(!L||!P){return false;}if(this.useLegacyEvent(L,K)){var N=this.getLegacyIndex(L,K);var M=E[N];if(M){for(O=0,R=M.length;O<R;++O){V=M[O];if(V&&V[this.EL]==L&&V[this.TYPE]==K&&V[this.FN]==T){M.splice(O,1);break;}}}}else{try{this._simpleRemove(L,K,P[this.WFN],false);}catch(S){this.lastError=S;return false;}}delete I[Q][this.WFN];delete I[Q][this.FN];I.splice(Q,1);return true;},getTarget:function(M,L){var K=M.target||M.srcElement;return this.resolveTextNode(K);},resolveTextNode:function(L){try{if(L&&3==L.nodeType){return L.parentNode;}}catch(K){}return L;},getPageX:function(L){var K=L.pageX;if(!K&&0!==K){K=L.clientX||0;if(this.isIE){K+=this._getScrollLeft();}}return K;},getPageY:function(K){var L=K.pageY;if(!L&&0!==L){L=K.clientY||0;if(this.isIE){L+=this._getScrollTop();}}return L;
},getXY:function(K){return[this.getPageX(K),this.getPageY(K)];},getRelatedTarget:function(L){var K=L.relatedTarget;if(!K){if(L.type=="mouseout"){K=L.toElement;}else{if(L.type=="mouseover"){K=L.fromElement;}}}return this.resolveTextNode(K);},getTime:function(M){if(!M.time){var L=new Date().getTime();try{M.time=L;}catch(K){this.lastError=K;return L;}}return M.time;},stopEvent:function(K){this.stopPropagation(K);this.preventDefault(K);},stopPropagation:function(K){if(K.stopPropagation){K.stopPropagation();}else{K.cancelBubble=true;}},preventDefault:function(K){if(K.preventDefault){K.preventDefault();}else{K.returnValue=false;}},getEvent:function(M,K){var L=M||window.event;if(!L){var N=this.getEvent.caller;while(N){L=N.arguments[0];if(L&&Event==L.constructor){break;}N=N.caller;}}return L;},getCharCode:function(L){var K=L.keyCode||L.charCode||0;if(YAHOO.env.ua.webkit&&(K in D)){K=D[K];}return K;},_getCacheIndex:function(O,P,N){for(var M=0,L=I.length;M<L;M=M+1){var K=I[M];if(K&&K[this.FN]==N&&K[this.EL]==O&&K[this.TYPE]==P){return M;}}return -1;},generateId:function(K){var L=K.id;if(!L){L="yuievtautoid-"+A;++A;K.id=L;}return L;},_isValidCollection:function(L){try{return(L&&typeof L!=="string"&&L.length&&!L.tagName&&!L.alert&&typeof L[0]!=="undefined");}catch(K){return false;}},elCache:{},getEl:function(K){return(typeof K==="string")?document.getElementById(K):K;},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(L){if(!H){H=true;var K=YAHOO.util.Event;K._ready();K._tryPreloadAttach();}},_ready:function(L){var K=YAHOO.util.Event;if(!K.DOMReady){K.DOMReady=true;K.DOMReadyEvent.fire();K._simpleRemove(document,"DOMContentLoaded",K._ready);}},_tryPreloadAttach:function(){if(F.length===0){C=0;clearInterval(this._interval);this._interval=null;return ;}if(this.locked){return ;}if(this.isIE){if(!this.DOMReady){this.startInterval();return ;}}this.locked=true;var Q=!H;if(!Q){Q=(C>0&&F.length>0);}var P=[];var R=function(T,U){var S=T;if(U.override){if(U.override===true){S=U.obj;}else{S=U.override;}}U.fn.call(S,U.obj);};var L,K,O,N,M=[];for(L=0,K=F.length;L<K;L=L+1){O=F[L];if(O){N=this.getEl(O.id);if(N){if(O.checkReady){if(H||N.nextSibling||!Q){M.push(O);F[L]=null;}}else{R(N,O);F[L]=null;}}else{P.push(O);}}}for(L=0,K=M.length;L<K;L=L+1){O=M[L];R(this.getEl(O.id),O);}C--;if(Q){for(L=F.length-1;L>-1;L--){O=F[L];if(!O||!O.id){F.splice(L,1);}}this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;},purgeElement:function(O,P,R){var M=(YAHOO.lang.isString(O))?this.getEl(O):O;var Q=this.getListeners(M,R),N,K;if(Q){for(N=Q.length-1;N>-1;N--){var L=Q[N];this.removeListener(M,L.type,L.fn);}}if(P&&M&&M.childNodes){for(N=0,K=M.childNodes.length;N<K;++N){this.purgeElement(M.childNodes[N],P,R);}}},getListeners:function(M,K){var P=[],L;if(!K){L=[I,J];}else{if(K==="unload"){L=[J];}else{L=[I];}}var R=(YAHOO.lang.isString(M))?this.getEl(M):M;for(var O=0;O<L.length;O=O+1){var T=L[O];if(T){for(var Q=0,S=T.length;Q<S;++Q){var N=T[Q];if(N&&N[this.EL]===R&&(!K||K===N[this.TYPE])){P.push({type:N[this.TYPE],fn:N[this.FN],obj:N[this.OBJ],adjust:N[this.OVERRIDE],scope:N[this.ADJ_SCOPE],index:Q});}}}}return(P.length)?P:null;},_unload:function(Q){var K=YAHOO.util.Event,N,M,L,P,O,R=J.slice();for(N=0,P=J.length;N<P;++N){L=R[N];if(L){var S=window;if(L[K.ADJ_SCOPE]){if(L[K.ADJ_SCOPE]===true){S=L[K.UNLOAD_OBJ];}else{S=L[K.ADJ_SCOPE];}}L[K.FN].call(S,K.getEvent(Q,L[K.EL]),L[K.UNLOAD_OBJ]);R[N]=null;L=null;S=null;}}J=null;if(I){for(M=I.length-1;M>-1;M--){L=I[M];if(L){K.removeListener(L[K.EL],L[K.TYPE],L[K.FN],M);}}L=null;}G=null;K._simpleRemove(window,"unload",K._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var K=document.documentElement,L=document.body;if(K&&(K.scrollTop||K.scrollLeft)){return[K.scrollTop,K.scrollLeft];}else{if(L){return[L.scrollTop,L.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(M,N,L,K){M.addEventListener(N,L,(K));};}else{if(window.attachEvent){return function(M,N,L,K){M.attachEvent("on"+N,L);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(M,N,L,K){M.removeEventListener(N,L,(K));};}else{if(window.detachEvent){return function(L,M,K){L.detachEvent("on"+M,K);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;
/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;
if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C<F.length;++C){B.subscribe(F[C].fn,F[C].obj,F[C].override);}}}return I[G];},fireEvent:function(E,D,A,C){this.__yui_events=this.__yui_events||{};var G=this.__yui_events[E];if(!G){return null;}var B=[];for(var F=1;F<arguments.length;++F){B.push(arguments[F]);}return G.fire.apply(G,B);},hasEvent:function(A){if(this.__yui_events){if(this.__yui_events[A]){return true;}}return false;}};YAHOO.util.KeyListener=function(A,F,B,C){if(!A){}else{if(!F){}else{if(!B){}}}if(!C){C=YAHOO.util.KeyListener.KEYDOWN;}var D=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(typeof A=="string"){A=document.getElementById(A);}if(typeof B=="function"){D.subscribe(B);}else{D.subscribe(B.fn,B.scope,B.correctScope);}function E(J,I){if(!F.shift){F.shift=false;}if(!F.alt){F.alt=false;}if(!F.ctrl){F.ctrl=false;}if(J.shiftKey==F.shift&&J.altKey==F.alt&&J.ctrlKey==F.ctrl){var G;if(F.keys instanceof Array){for(var H=0;H<F.keys.length;H++){G=F.keys[H];if(G==J.charCode){D.fire(J.charCode,J);break;}else{if(G==J.keyCode){D.fire(J.keyCode,J);break;}}}}else{G=F.keys;if(G==J.charCode){D.fire(J.charCode,J);}else{if(G==J.keyCode){D.fire(J.keyCode,J);}}}}}this.enable=function(){if(!this.enabled){YAHOO.util.Event.addListener(A,C,E);this.enabledEvent.fire(F);}this.enabled=true;};this.disable=function(){if(this.enabled){YAHOO.util.Event.removeListener(A,C,E);this.disabledEvent.fire(F);}this.enabled=false;};this.toString=function(){return"KeyListener ["+F.keys+"] "+A.tagName+(A.id?"["+A.id+"]":"");};};YAHOO.util.KeyListener.KEYDOWN="keydown";YAHOO.util.KeyListener.KEYUP="keyup";YAHOO.util.KeyListener.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38};YAHOO.register("event",YAHOO.util.Event,{version:"2.5.2",build:"1076"});YAHOO.register("yahoo-dom-event", YAHOO, {version: "2.5.2", build: "1076"});


/*../vendor/yui_252/build/animation/animation-min.js*/

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.5.2
*/
(function(){var B=YAHOO.util;var A=function(D,C,E,F){if(!D){}this.init(D,C,E,F);};A.NAME="Anim";A.prototype={toString:function(){var C=this.getEl()||{};var D=C.id||C.tagName;return(this.constructor.NAME+": "+D);},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(C,E,D){return this.method(this.currentFrame,E,D-E,this.totalFrames);},setAttribute:function(C,E,D){if(this.patterns.noNegatives.test(C)){E=(E>0)?E:0;}B.Dom.setStyle(this.getEl(),C,E+D);},getAttribute:function(C){var E=this.getEl();var G=B.Dom.getStyle(E,C);if(G!=="auto"&&!this.patterns.offsetUnit.test(G)){return parseFloat(G);}var D=this.patterns.offsetAttribute.exec(C)||[];var H=!!(D[3]);var F=!!(D[2]);if(F||(B.Dom.getStyle(E,"position")=="absolute"&&H)){G=E["offset"+D[0].charAt(0).toUpperCase()+D[0].substr(1)];}else{G=0;}return G;},getDefaultUnit:function(C){if(this.patterns.defaultUnit.test(C)){return"px";}return"";},setRuntimeAttribute:function(D){var I;var E;var F=this.attributes;this.runtimeAttributes[D]={};var H=function(J){return(typeof J!=="undefined");};if(!H(F[D]["to"])&&!H(F[D]["by"])){return false;}I=(H(F[D]["from"]))?F[D]["from"]:this.getAttribute(D);if(H(F[D]["to"])){E=F[D]["to"];}else{if(H(F[D]["by"])){if(I.constructor==Array){E=[];for(var G=0,C=I.length;G<C;++G){E[G]=I[G]+F[D]["by"][G]*1;}}else{E=I+F[D]["by"]*1;}}}this.runtimeAttributes[D].start=I;this.runtimeAttributes[D].end=E;this.runtimeAttributes[D].unit=(H(F[D].unit))?F[D]["unit"]:this.getDefaultUnit(D);return true;},init:function(E,J,I,C){var D=false;var F=null;var H=0;E=B.Dom.get(E);this.attributes=J||{};this.duration=!YAHOO.lang.isUndefined(I)?I:1;this.method=C||B.Easing.easeNone;this.useSeconds=true;this.currentFrame=0;this.totalFrames=B.AnimMgr.fps;this.setEl=function(M){E=B.Dom.get(M);};this.getEl=function(){return E;};this.isAnimated=function(){return D;};this.getStartTime=function(){return F;};this.runtimeAttributes={};this.animate=function(){if(this.isAnimated()){return false;}this.currentFrame=0;this.totalFrames=(this.useSeconds)?Math.ceil(B.AnimMgr.fps*this.duration):this.duration;if(this.duration===0&&this.useSeconds){this.totalFrames=1;}B.AnimMgr.registerElement(this);return true;};this.stop=function(M){if(!this.isAnimated()){return false;}if(M){this.currentFrame=this.totalFrames;this._onTween.fire();}B.AnimMgr.stop(this);};var L=function(){this.onStart.fire();this.runtimeAttributes={};for(var M in this.attributes){this.setRuntimeAttribute(M);}D=true;H=0;F=new Date();};var K=function(){var O={duration:new Date()-this.getStartTime(),currentFrame:this.currentFrame};O.toString=function(){return("duration: "+O.duration+", currentFrame: "+O.currentFrame);};this.onTween.fire(O);var N=this.runtimeAttributes;for(var M in N){this.setAttribute(M,this.doMethod(M,N[M].start,N[M].end),N[M].unit);}H+=1;};var G=function(){var M=(new Date()-F)/1000;var N={duration:M,frames:H,fps:H/M};N.toString=function(){return("duration: "+N.duration+", frames: "+N.frames+", fps: "+N.fps);};D=false;H=0;this.onComplete.fire(N);};this._onStart=new B.CustomEvent("_start",this,true);this.onStart=new B.CustomEvent("start",this);this.onTween=new B.CustomEvent("tween",this);this._onTween=new B.CustomEvent("_tween",this,true);this.onComplete=new B.CustomEvent("complete",this);this._onComplete=new B.CustomEvent("_complete",this,true);this._onStart.subscribe(L);this._onTween.subscribe(K);this._onComplete.subscribe(G);}};B.Anim=A;})();YAHOO.util.AnimMgr=new function(){var C=null;var B=[];var A=0;this.fps=1000;this.delay=1;this.registerElement=function(F){B[B.length]=F;A+=1;F._onStart.fire();this.start();};this.unRegister=function(G,F){F=F||E(G);if(!G.isAnimated()||F==-1){return false;}G._onComplete.fire();B.splice(F,1);A-=1;if(A<=0){this.stop();}return true;};this.start=function(){if(C===null){C=setInterval(this.run,this.delay);}};this.stop=function(H){if(!H){clearInterval(C);for(var G=0,F=B.length;G<F;++G){this.unRegister(B[0],0);}B=[];C=null;A=0;}else{this.unRegister(H);}};this.run=function(){for(var H=0,F=B.length;H<F;++H){var G=B[H];if(!G||!G.isAnimated()){continue;}if(G.currentFrame<G.totalFrames||G.totalFrames===null){G.currentFrame+=1;if(G.useSeconds){D(G);}G._onTween.fire();}else{YAHOO.util.AnimMgr.stop(G,H);}}};var E=function(H){for(var G=0,F=B.length;G<F;++G){if(B[G]==H){return G;}}return -1;};var D=function(G){var J=G.totalFrames;var I=G.currentFrame;var H=(G.currentFrame*G.duration*1000/G.totalFrames);var F=(new Date()-G.getStartTime());var K=0;if(F<G.duration*1000){K=Math.round((F/H-1)*G.currentFrame);}else{K=J-(I+1);}if(K>0&&isFinite(K)){if(G.currentFrame+K>=J){K=J-(I+1);}G.currentFrame+=K;}};};YAHOO.util.Bezier=new function(){this.getPosition=function(E,D){var F=E.length;var C=[];for(var B=0;B<F;++B){C[B]=[E[B][0],E[B][1]];}for(var A=1;A<F;++A){for(B=0;B<F-A;++B){C[B][0]=(1-D)*C[B][0]+D*C[parseInt(B+1,10)][0];C[B][1]=(1-D)*C[B][1]+D*C[parseInt(B+1,10)][1];}}return[C[0][0],C[0][1]];};};(function(){var A=function(F,E,G,H){A.superclass.constructor.call(this,F,E,G,H);};A.NAME="ColorAnim";var C=YAHOO.util;YAHOO.extend(A,C.Anim);var D=A.superclass;var B=A.prototype;B.patterns.color=/color$/i;B.patterns.rgb=/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;B.patterns.hex=/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;B.patterns.hex3=/^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;B.patterns.transparent=/^transparent|rgba\(0, 0, 0, 0\)$/;B.parseColor=function(E){if(E.length==3){return E;}var F=this.patterns.hex.exec(E);if(F&&F.length==4){return[parseInt(F[1],16),parseInt(F[2],16),parseInt(F[3],16)];}F=this.patterns.rgb.exec(E);if(F&&F.length==4){return[parseInt(F[1],10),parseInt(F[2],10),parseInt(F[3],10)];}F=this.patterns.hex3.exec(E);if(F&&F.length==4){return[parseInt(F[1]+F[1],16),parseInt(F[2]+F[2],16),parseInt(F[3]+F[3],16)];}return null;};B.getAttribute=function(E){var G=this.getEl();if(this.patterns.color.test(E)){var H=YAHOO.util.Dom.getStyle(G,E);
if(this.patterns.transparent.test(H)){var F=G.parentNode;H=C.Dom.getStyle(F,E);while(F&&this.patterns.transparent.test(H)){F=F.parentNode;H=C.Dom.getStyle(F,E);if(F.tagName.toUpperCase()=="HTML"){H="#fff";}}}}else{H=D.getAttribute.call(this,E);}return H;};B.doMethod=function(F,J,G){var I;if(this.patterns.color.test(F)){I=[];for(var H=0,E=J.length;H<E;++H){I[H]=D.doMethod.call(this,F,J[H],G[H]);}I="rgb("+Math.floor(I[0])+","+Math.floor(I[1])+","+Math.floor(I[2])+")";}else{I=D.doMethod.call(this,F,J,G);}return I;};B.setRuntimeAttribute=function(F){D.setRuntimeAttribute.call(this,F);if(this.patterns.color.test(F)){var H=this.attributes;var J=this.parseColor(this.runtimeAttributes[F].start);var G=this.parseColor(this.runtimeAttributes[F].end);if(typeof H[F]["to"]==="undefined"&&typeof H[F]["by"]!=="undefined"){G=this.parseColor(H[F].by);for(var I=0,E=J.length;I<E;++I){G[I]=J[I]+G[I];}}this.runtimeAttributes[F].start=J;this.runtimeAttributes[F].end=G;}};C.ColorAnim=A;})();
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright 2001 Robert Penner All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
YAHOO.util.Easing={easeNone:function(B,A,D,C){return D*B/C+A;},easeIn:function(B,A,D,C){return D*(B/=C)*B+A;},easeOut:function(B,A,D,C){return -D*(B/=C)*(B-2)+A;},easeBoth:function(B,A,D,C){if((B/=C/2)<1){return D/2*B*B+A;}return -D/2*((--B)*(B-2)-1)+A;},easeInStrong:function(B,A,D,C){return D*(B/=C)*B*B*B+A;},easeOutStrong:function(B,A,D,C){return -D*((B=B/C-1)*B*B*B-1)+A;},easeBothStrong:function(B,A,D,C){if((B/=C/2)<1){return D/2*B*B*B*B+A;}return -D/2*((B-=2)*B*B*B-2)+A;},elasticIn:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F)==1){return A+G;}if(!E){E=F*0.3;}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}return -(B*Math.pow(2,10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E))+A;},elasticOut:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F)==1){return A+G;}if(!E){E=F*0.3;}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}return B*Math.pow(2,-10*C)*Math.sin((C*F-D)*(2*Math.PI)/E)+G+A;},elasticBoth:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F/2)==2){return A+G;}if(!E){E=F*(0.3*1.5);}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}if(C<1){return -0.5*(B*Math.pow(2,10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E))+A;}return B*Math.pow(2,-10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E)*0.5+G+A;},backIn:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}return E*(B/=D)*B*((C+1)*B-C)+A;},backOut:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}return E*((B=B/D-1)*B*((C+1)*B+C)+1)+A;},backBoth:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}if((B/=D/2)<1){return E/2*(B*B*(((C*=(1.525))+1)*B-C))+A;}return E/2*((B-=2)*B*(((C*=(1.525))+1)*B+C)+2)+A;},bounceIn:function(B,A,D,C){return D-YAHOO.util.Easing.bounceOut(C-B,0,D,C)+A;},bounceOut:function(B,A,D,C){if((B/=C)<(1/2.75)){return D*(7.5625*B*B)+A;}else{if(B<(2/2.75)){return D*(7.5625*(B-=(1.5/2.75))*B+0.75)+A;}else{if(B<(2.5/2.75)){return D*(7.5625*(B-=(2.25/2.75))*B+0.9375)+A;}}}return D*(7.5625*(B-=(2.625/2.75))*B+0.984375)+A;},bounceBoth:function(B,A,D,C){if(B<C/2){return YAHOO.util.Easing.bounceIn(B*2,0,D,C)*0.5+A;}return YAHOO.util.Easing.bounceOut(B*2-C,0,D,C)*0.5+D*0.5+A;}};(function(){var A=function(H,G,I,J){if(H){A.superclass.constructor.call(this,H,G,I,J);}};A.NAME="Motion";var E=YAHOO.util;YAHOO.extend(A,E.ColorAnim);var F=A.superclass;var C=A.prototype;C.patterns.points=/^points$/i;C.setAttribute=function(G,I,H){if(this.patterns.points.test(G)){H=H||"px";F.setAttribute.call(this,"left",I[0],H);F.setAttribute.call(this,"top",I[1],H);}else{F.setAttribute.call(this,G,I,H);}};C.getAttribute=function(G){if(this.patterns.points.test(G)){var H=[F.getAttribute.call(this,"left"),F.getAttribute.call(this,"top")];}else{H=F.getAttribute.call(this,G);}return H;};C.doMethod=function(G,K,H){var J=null;if(this.patterns.points.test(G)){var I=this.method(this.currentFrame,0,100,this.totalFrames)/100;J=E.Bezier.getPosition(this.runtimeAttributes[G],I);}else{J=F.doMethod.call(this,G,K,H);}return J;};C.setRuntimeAttribute=function(P){if(this.patterns.points.test(P)){var H=this.getEl();var J=this.attributes;var G;var L=J["points"]["control"]||[];var I;var M,O;if(L.length>0&&!(L[0] instanceof Array)){L=[L];}else{var K=[];for(M=0,O=L.length;M<O;++M){K[M]=L[M];}L=K;}if(E.Dom.getStyle(H,"position")=="static"){E.Dom.setStyle(H,"position","relative");}if(D(J["points"]["from"])){E.Dom.setXY(H,J["points"]["from"]);}else{E.Dom.setXY(H,E.Dom.getXY(H));}G=this.getAttribute("points");if(D(J["points"]["to"])){I=B.call(this,J["points"]["to"],G);
var N=E.Dom.getXY(this.getEl());for(M=0,O=L.length;M<O;++M){L[M]=B.call(this,L[M],G);}}else{if(D(J["points"]["by"])){I=[G[0]+J["points"]["by"][0],G[1]+J["points"]["by"][1]];for(M=0,O=L.length;M<O;++M){L[M]=[G[0]+L[M][0],G[1]+L[M][1]];}}}this.runtimeAttributes[P]=[G];if(L.length>0){this.runtimeAttributes[P]=this.runtimeAttributes[P].concat(L);}this.runtimeAttributes[P][this.runtimeAttributes[P].length]=I;}else{F.setRuntimeAttribute.call(this,P);}};var B=function(G,I){var H=E.Dom.getXY(this.getEl());G=[G[0]-H[0]+I[0],G[1]-H[1]+I[1]];return G;};var D=function(G){return(typeof G!=="undefined");};E.Motion=A;})();(function(){var D=function(F,E,G,H){if(F){D.superclass.constructor.call(this,F,E,G,H);}};D.NAME="Scroll";var B=YAHOO.util;YAHOO.extend(D,B.ColorAnim);var C=D.superclass;var A=D.prototype;A.doMethod=function(E,H,F){var G=null;if(E=="scroll"){G=[this.method(this.currentFrame,H[0],F[0]-H[0],this.totalFrames),this.method(this.currentFrame,H[1],F[1]-H[1],this.totalFrames)];}else{G=C.doMethod.call(this,E,H,F);}return G;};A.getAttribute=function(E){var G=null;var F=this.getEl();if(E=="scroll"){G=[F.scrollLeft,F.scrollTop];}else{G=C.getAttribute.call(this,E);}return G;};A.setAttribute=function(E,H,G){var F=this.getEl();if(E=="scroll"){F.scrollLeft=H[0];F.scrollTop=H[1];}else{C.setAttribute.call(this,E,H,G);}};B.Scroll=D;})();YAHOO.register("animation",YAHOO.util.Anim,{version:"2.5.2",build:"1076"});

/*../vendor/yui_260/build/connection/connection-min.js*/

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.6.0
*/
YAHOO.util.Connect={_msxml_progid:["Microsoft.XMLHTTP","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP"],_http_headers:{},_has_http_headers:false,_use_default_post_header:true,_default_post_header:"application/x-www-form-urlencoded; charset=UTF-8",_default_form_header:"application/x-www-form-urlencoded",_use_default_xhr_header:true,_default_xhr_header:"XMLHttpRequest",_has_default_headers:true,_default_headers:{},_isFormSubmit:false,_isFileUpload:false,_formNode:null,_sFormData:null,_poll:{},_timeOut:{},_polling_interval:50,_transaction_id:0,_submitElementValue:null,_hasSubmitListener:(function(){if(YAHOO.util.Event){YAHOO.util.Event.addListener(document,"click",function(B){var A=YAHOO.util.Event.getTarget(B);if(A.nodeName.toLowerCase()=="input"&&(A.type&&A.type.toLowerCase()=="submit")){YAHOO.util.Connect._submitElementValue=encodeURIComponent(A.name)+"="+encodeURIComponent(A.value);}});return true;}return false;})(),startEvent:new YAHOO.util.CustomEvent("start"),completeEvent:new YAHOO.util.CustomEvent("complete"),successEvent:new YAHOO.util.CustomEvent("success"),failureEvent:new YAHOO.util.CustomEvent("failure"),uploadEvent:new YAHOO.util.CustomEvent("upload"),abortEvent:new YAHOO.util.CustomEvent("abort"),_customEvents:{onStart:["startEvent","start"],onComplete:["completeEvent","complete"],onSuccess:["successEvent","success"],onFailure:["failureEvent","failure"],onUpload:["uploadEvent","upload"],onAbort:["abortEvent","abort"]},setProgId:function(A){this._msxml_progid.unshift(A);},setDefaultPostHeader:function(A){if(typeof A=="string"){this._default_post_header=A;}else{if(typeof A=="boolean"){this._use_default_post_header=A;}}},setDefaultXhrHeader:function(A){if(typeof A=="string"){this._default_xhr_header=A;}else{this._use_default_xhr_header=A;}},setPollingInterval:function(A){if(typeof A=="number"&&isFinite(A)){this._polling_interval=A;}},createXhrObject:function(F){var E,A;try{A=new XMLHttpRequest();E={conn:A,tId:F};}catch(D){for(var B=0;B<this._msxml_progid.length;++B){try{A=new ActiveXObject(this._msxml_progid[B]);E={conn:A,tId:F};break;}catch(C){}}}finally{return E;}},getConnectionObject:function(A){var C;var D=this._transaction_id;try{if(!A){C=this.createXhrObject(D);}else{C={};C.tId=D;C.isUpload=true;}if(C){this._transaction_id++;}}catch(B){}finally{return C;}},asyncRequest:function(F,C,E,A){var D=(this._isFileUpload)?this.getConnectionObject(true):this.getConnectionObject();var B=(E&&E.argument)?E.argument:null;if(!D){return null;}else{if(E&&E.customevents){this.initCustomEvents(D,E);}if(this._isFormSubmit){if(this._isFileUpload){this.uploadFile(D,E,C,A);return D;}if(F.toUpperCase()=="GET"){if(this._sFormData.length!==0){C+=((C.indexOf("?")==-1)?"?":"&")+this._sFormData;}}else{if(F.toUpperCase()=="POST"){A=A?this._sFormData+"&"+A:this._sFormData;}}}if(F.toUpperCase()=="GET"&&(E&&E.cache===false)){C+=((C.indexOf("?")==-1)?"?":"&")+"rnd="+new Date().valueOf().toString();}D.conn.open(F,C,true);if(this._use_default_xhr_header){if(!this._default_headers["X-Requested-With"]){this.initHeader("X-Requested-With",this._default_xhr_header,true);}}if((F.toUpperCase()==="POST"&&this._use_default_post_header)&&this._isFormSubmit===false){this.initHeader("Content-Type",this._default_post_header);}if(this._has_default_headers||this._has_http_headers){this.setHeader(D);}this.handleReadyState(D,E);D.conn.send(A||"");if(this._isFormSubmit===true){this.resetFormState();}this.startEvent.fire(D,B);if(D.startEvent){D.startEvent.fire(D,B);}return D;}},initCustomEvents:function(A,C){var B;for(B in C.customevents){if(this._customEvents[B][0]){A[this._customEvents[B][0]]=new YAHOO.util.CustomEvent(this._customEvents[B][1],(C.scope)?C.scope:null);A[this._customEvents[B][0]].subscribe(C.customevents[B]);}}},handleReadyState:function(C,D){var B=this;var A=(D&&D.argument)?D.argument:null;if(D&&D.timeout){this._timeOut[C.tId]=window.setTimeout(function(){B.abort(C,D,true);},D.timeout);}this._poll[C.tId]=window.setInterval(function(){if(C.conn&&C.conn.readyState===4){window.clearInterval(B._poll[C.tId]);delete B._poll[C.tId];if(D&&D.timeout){window.clearTimeout(B._timeOut[C.tId]);delete B._timeOut[C.tId];}B.completeEvent.fire(C,A);if(C.completeEvent){C.completeEvent.fire(C,A);}B.handleTransactionResponse(C,D);}},this._polling_interval);},handleTransactionResponse:function(F,G,A){var D,C;var B=(G&&G.argument)?G.argument:null;try{if(F.conn.status!==undefined&&F.conn.status!==0){D=F.conn.status;}else{D=13030;}}catch(E){D=13030;}if(D>=200&&D<300||D===1223){C=this.createResponseObject(F,B);if(G&&G.success){if(!G.scope){G.success(C);}else{G.success.apply(G.scope,[C]);}}this.successEvent.fire(C);if(F.successEvent){F.successEvent.fire(C);}}else{switch(D){case 12002:case 12029:case 12030:case 12031:case 12152:case 13030:C=this.createExceptionObject(F.tId,B,(A?A:false));if(G&&G.failure){if(!G.scope){G.failure(C);}else{G.failure.apply(G.scope,[C]);}}break;default:C=this.createResponseObject(F,B);if(G&&G.failure){if(!G.scope){G.failure(C);}else{G.failure.apply(G.scope,[C]);}}}this.failureEvent.fire(C);if(F.failureEvent){F.failureEvent.fire(C);}}this.releaseObject(F);C=null;},createResponseObject:function(A,G){var D={};var I={};try{var C=A.conn.getAllResponseHeaders();var F=C.split("\n");for(var E=0;E<F.length;E++){var B=F[E].indexOf(":");if(B!=-1){I[F[E].substring(0,B)]=F[E].substring(B+2);}}}catch(H){}D.tId=A.tId;D.status=(A.conn.status==1223)?204:A.conn.status;D.statusText=(A.conn.status==1223)?"No Content":A.conn.statusText;D.getResponseHeader=I;D.getAllResponseHeaders=C;D.responseText=A.conn.responseText;D.responseXML=A.conn.responseXML;if(G){D.argument=G;}return D;},createExceptionObject:function(H,D,A){var F=0;var G="communication failure";var C=-1;var B="transaction aborted";var E={};E.tId=H;if(A){E.status=C;E.statusText=B;}else{E.status=F;E.statusText=G;}if(D){E.argument=D;}return E;},initHeader:function(A,D,C){var B=(C)?this._default_headers:this._http_headers;B[A]=D;if(C){this._has_default_headers=true;}else{this._has_http_headers=true;
}},setHeader:function(A){var B;if(this._has_default_headers){for(B in this._default_headers){if(YAHOO.lang.hasOwnProperty(this._default_headers,B)){A.conn.setRequestHeader(B,this._default_headers[B]);}}}if(this._has_http_headers){for(B in this._http_headers){if(YAHOO.lang.hasOwnProperty(this._http_headers,B)){A.conn.setRequestHeader(B,this._http_headers[B]);}}delete this._http_headers;this._http_headers={};this._has_http_headers=false;}},resetDefaultHeaders:function(){delete this._default_headers;this._default_headers={};this._has_default_headers=false;},setForm:function(M,H,C){var L,B,K,I,P,J=false,F=[],O=0,E,G,D,N,A;this.resetFormState();if(typeof M=="string"){L=(document.getElementById(M)||document.forms[M]);}else{if(typeof M=="object"){L=M;}else{return ;}}if(H){this.createFrame(C?C:null);this._isFormSubmit=true;this._isFileUpload=true;this._formNode=L;return ;}for(E=0,G=L.elements.length;E<G;++E){B=L.elements[E];P=B.disabled;K=B.name;if(!P&&K){K=encodeURIComponent(K)+"=";I=encodeURIComponent(B.value);switch(B.type){case"select-one":if(B.selectedIndex>-1){A=B.options[B.selectedIndex];F[O++]=K+encodeURIComponent((A.attributes.value&&A.attributes.value.specified)?A.value:A.text);}break;case"select-multiple":if(B.selectedIndex>-1){for(D=B.selectedIndex,N=B.options.length;D<N;++D){A=B.options[D];if(A.selected){F[O++]=K+encodeURIComponent((A.attributes.value&&A.attributes.value.specified)?A.value:A.text);}}}break;case"radio":case"checkbox":if(B.checked){F[O++]=K+I;}break;case"file":case undefined:case"reset":case"button":break;case"submit":if(J===false){if(this._hasSubmitListener&&this._submitElementValue){F[O++]=this._submitElementValue;}else{F[O++]=K+I;}J=true;}break;default:F[O++]=K+I;}}}this._isFormSubmit=true;this._sFormData=F.join("&");this.initHeader("Content-Type",this._default_form_header);return this._sFormData;},resetFormState:function(){this._isFormSubmit=false;this._isFileUpload=false;this._formNode=null;this._sFormData="";},createFrame:function(A){var B="yuiIO"+this._transaction_id;var C;if(YAHOO.env.ua.ie){C=document.createElement('<iframe id="'+B+'" name="'+B+'" />');if(typeof A=="boolean"){C.src="javascript:false";}}else{C=document.createElement("iframe");C.id=B;C.name=B;}C.style.position="absolute";C.style.top="-1000px";C.style.left="-1000px";document.body.appendChild(C);},appendPostData:function(A){var D=[],B=A.split("&"),C,E;for(C=0;C<B.length;C++){E=B[C].indexOf("=");if(E!=-1){D[C]=document.createElement("input");D[C].type="hidden";D[C].name=decodeURIComponent(B[C].substring(0,E));D[C].value=decodeURIComponent(B[C].substring(E+1));this._formNode.appendChild(D[C]);}}return D;},uploadFile:function(D,N,E,C){var I="yuiIO"+D.tId,J="multipart/form-data",L=document.getElementById(I),O=this,K=(N&&N.argument)?N.argument:null,M,H,B,G;var A={action:this._formNode.getAttribute("action"),method:this._formNode.getAttribute("method"),target:this._formNode.getAttribute("target")};this._formNode.setAttribute("action",E);this._formNode.setAttribute("method","POST");this._formNode.setAttribute("target",I);if(YAHOO.env.ua.ie){this._formNode.setAttribute("encoding",J);}else{this._formNode.setAttribute("enctype",J);}if(C){M=this.appendPostData(C);}this._formNode.submit();this.startEvent.fire(D,K);if(D.startEvent){D.startEvent.fire(D,K);}if(N&&N.timeout){this._timeOut[D.tId]=window.setTimeout(function(){O.abort(D,N,true);},N.timeout);}if(M&&M.length>0){for(H=0;H<M.length;H++){this._formNode.removeChild(M[H]);}}for(B in A){if(YAHOO.lang.hasOwnProperty(A,B)){if(A[B]){this._formNode.setAttribute(B,A[B]);}else{this._formNode.removeAttribute(B);}}}this.resetFormState();var F=function(){if(N&&N.timeout){window.clearTimeout(O._timeOut[D.tId]);delete O._timeOut[D.tId];}O.completeEvent.fire(D,K);if(D.completeEvent){D.completeEvent.fire(D,K);}G={tId:D.tId,argument:N.argument};try{G.responseText=L.contentWindow.document.body?L.contentWindow.document.body.innerHTML:L.contentWindow.document.documentElement.textContent;G.responseXML=L.contentWindow.document.XMLDocument?L.contentWindow.document.XMLDocument:L.contentWindow.document;}catch(P){}if(N&&N.upload){if(!N.scope){N.upload(G);}else{N.upload.apply(N.scope,[G]);}}O.uploadEvent.fire(G);if(D.uploadEvent){D.uploadEvent.fire(G);}YAHOO.util.Event.removeListener(L,"load",F);setTimeout(function(){document.body.removeChild(L);O.releaseObject(D);},100);};YAHOO.util.Event.addListener(L,"load",F);},abort:function(E,G,A){var D;var B=(G&&G.argument)?G.argument:null;if(E&&E.conn){if(this.isCallInProgress(E)){E.conn.abort();window.clearInterval(this._poll[E.tId]);delete this._poll[E.tId];if(A){window.clearTimeout(this._timeOut[E.tId]);delete this._timeOut[E.tId];}D=true;}}else{if(E&&E.isUpload===true){var C="yuiIO"+E.tId;var F=document.getElementById(C);if(F){YAHOO.util.Event.removeListener(F,"load");document.body.removeChild(F);if(A){window.clearTimeout(this._timeOut[E.tId]);delete this._timeOut[E.tId];}D=true;}}else{D=false;}}if(D===true){this.abortEvent.fire(E,B);if(E.abortEvent){E.abortEvent.fire(E,B);}this.handleTransactionResponse(E,G,true);}return D;},isCallInProgress:function(B){if(B&&B.conn){return B.conn.readyState!==4&&B.conn.readyState!==0;}else{if(B&&B.isUpload===true){var A="yuiIO"+B.tId;return document.getElementById(A)?true:false;}else{return false;}}},releaseObject:function(A){if(A&&A.conn){A.conn=null;A=null;}}};YAHOO.register("connection",YAHOO.util.Connect,{version:"2.6.0",build:"1321"});

/*../vendor/yui_260/build/datasource/datasource-min.js*/

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.6.0
*/
(function(){var lang=YAHOO.lang,util=YAHOO.util,Ev=util.Event;util.DataSourceBase=function(oLiveData,oConfigs){if(oLiveData===null||oLiveData===undefined){return ;}this.liveData=oLiveData;this._oQueue={interval:null,conn:null,requests:[]};this.responseSchema={};if(oConfigs&&(oConfigs.constructor==Object)){for(var sConfig in oConfigs){if(sConfig){this[sConfig]=oConfigs[sConfig];}}}var maxCacheEntries=this.maxCacheEntries;if(!lang.isNumber(maxCacheEntries)||(maxCacheEntries<0)){maxCacheEntries=0;}this._aIntervals=[];this.createEvent("cacheRequestEvent");this.createEvent("cacheResponseEvent");this.createEvent("requestEvent");this.createEvent("responseEvent");this.createEvent("responseParseEvent");this.createEvent("responseCacheEvent");this.createEvent("dataErrorEvent");this.createEvent("cacheFlushEvent");var DS=util.DataSourceBase;this._sName="DataSource instance"+DS._nIndex;DS._nIndex++;};var DS=util.DataSourceBase;lang.augmentObject(DS,{TYPE_UNKNOWN:-1,TYPE_JSARRAY:0,TYPE_JSFUNCTION:1,TYPE_XHR:2,TYPE_JSON:3,TYPE_XML:4,TYPE_TEXT:5,TYPE_HTMLTABLE:6,TYPE_SCRIPTNODE:7,TYPE_LOCAL:8,ERROR_DATAINVALID:"Invalid data",ERROR_DATANULL:"Null data",_nIndex:0,_nTransactionId:0,issueCallback:function(callback,params,error,scope){if(lang.isFunction(callback)){callback.apply(scope,params);}else{if(lang.isObject(callback)){scope=callback.scope||scope||window;var callbackFunc=callback.success;if(error){callbackFunc=callback.failure;}if(callbackFunc){callbackFunc.apply(scope,params.concat([callback.argument]));}}}},parseString:function(oData){if(!lang.isValue(oData)){return null;}var string=oData+"";if(lang.isString(string)){return string;}else{return null;}},parseNumber:function(oData){var number=oData*1;if(lang.isNumber(number)){return number;}else{return null;}},convertNumber:function(oData){return DS.parseNumber(oData);},parseDate:function(oData){var date=null;if(!(oData instanceof Date)){date=new Date(oData);}else{return oData;}if(date instanceof Date){return date;}else{return null;}},convertDate:function(oData){return DS.parseDate(oData);}});DS.Parser={string:DS.parseString,number:DS.parseNumber,date:DS.parseDate};DS.prototype={_sName:null,_aCache:null,_oQueue:null,_aIntervals:null,maxCacheEntries:0,liveData:null,dataType:DS.TYPE_UNKNOWN,responseType:DS.TYPE_UNKNOWN,responseSchema:null,toString:function(){return this._sName;},getCachedResponse:function(oRequest,oCallback,oCaller){var aCache=this._aCache;if(this.maxCacheEntries>0){if(!aCache){this._aCache=[];}else{var nCacheLength=aCache.length;if(nCacheLength>0){var oResponse=null;this.fireEvent("cacheRequestEvent",{request:oRequest,callback:oCallback,caller:oCaller});for(var i=nCacheLength-1;i>=0;i--){var oCacheElem=aCache[i];if(this.isCacheHit(oRequest,oCacheElem.request)){oResponse=oCacheElem.response;this.fireEvent("cacheResponseEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});if(i<nCacheLength-1){aCache.splice(i,1);this.addToCache(oRequest,oResponse);}oResponse.cached=true;break;}}return oResponse;}}}else{if(aCache){this._aCache=null;}}return null;},isCacheHit:function(oRequest,oCachedRequest){return(oRequest===oCachedRequest);},addToCache:function(oRequest,oResponse){var aCache=this._aCache;if(!aCache){return ;}while(aCache.length>=this.maxCacheEntries){aCache.shift();}var oCacheElem={request:oRequest,response:oResponse};aCache[aCache.length]=oCacheElem;this.fireEvent("responseCacheEvent",{request:oRequest,response:oResponse});},flushCache:function(){if(this._aCache){this._aCache=[];this.fireEvent("cacheFlushEvent");}},setInterval:function(nMsec,oRequest,oCallback,oCaller){if(lang.isNumber(nMsec)&&(nMsec>=0)){var oSelf=this;var nId=setInterval(function(){oSelf.makeConnection(oRequest,oCallback,oCaller);},nMsec);this._aIntervals.push(nId);return nId;}else{}},clearInterval:function(nId){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){if(tracker[i]===nId){tracker.splice(i,1);clearInterval(nId);}}},clearAllIntervals:function(){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){clearInterval(tracker[i]);}tracker=[];},sendRequest:function(oRequest,oCallback,oCaller){var oCachedResponse=this.getCachedResponse(oRequest,oCallback,oCaller);if(oCachedResponse){DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);return null;}return this.makeConnection(oRequest,oCallback,oCaller);},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData;this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId;},handleResponse:function(oRequest,oRawResponse,oCallback,oCaller,tId){this.fireEvent("responseEvent",{tId:tId,request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller});var xhr=(this.dataType==DS.TYPE_XHR)?true:false;var oParsedResponse=null;var oFullResponse=oRawResponse;if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oRawResponse&&oRawResponse.getResponseHeader)?oRawResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML;}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON;}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT;}}}}else{if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML;}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT;}}}}}}}switch(this.responseType){case DS.TYPE_JSARRAY:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseArrayData(oRequest,oFullResponse);
break;case DS.TYPE_JSON:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}try{if(lang.isString(oFullResponse)){if(lang.JSON){oFullResponse=lang.JSON.parse(oFullResponse);}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse(oFullResponse);}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON();}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length);}if(oFullResponse.length>0){var objEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,objEnd+1);oFullResponse=eval("("+oFullResponse+")");}}}}}}catch(e){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseJSONData(oRequest,oFullResponse);break;case DS.TYPE_HTMLTABLE:if(xhr&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseHTMLTableData(oRequest,oFullResponse);break;case DS.TYPE_XML:if(xhr&&oRawResponse.responseXML){oFullResponse=oRawResponse.responseXML;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseXMLData(oRequest,oFullResponse);break;case DS.TYPE_TEXT:if(xhr&&lang.isString(oRawResponse.responseText)){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseTextData(oRequest,oFullResponse);break;default:oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseData(oRequest,oFullResponse);break;}oParsedResponse=oParsedResponse||{};if(!oParsedResponse.results){oParsedResponse.results=[];}if(!oParsedResponse.meta){oParsedResponse.meta={};}if(oParsedResponse&&!oParsedResponse.error){oParsedResponse=this.doBeforeCallback(oRequest,oFullResponse,oParsedResponse,oCallback);this.fireEvent("responseParseEvent",{request:oRequest,response:oParsedResponse,callback:oCallback,caller:oCaller});this.addToCache(oRequest,oParsedResponse);}else{oParsedResponse.error=true;this.fireEvent("dataErrorEvent",{request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});}oParsedResponse.tId=tId;DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);},doBeforeParseData:function(oRequest,oFullResponse,oCallback){return oFullResponse;},doBeforeCallback:function(oRequest,oFullResponse,oParsedResponse,oCallback){return oParsedResponse;},parseData:function(oRequest,oFullResponse){if(lang.isValue(oFullResponse)){var oParsedResponse={results:oFullResponse,meta:{}};return oParsedResponse;}return null;},parseArrayData:function(oRequest,oFullResponse){if(lang.isArray(oFullResponse)){var results=[],i,j,rec,field,data;if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(i=fields.length-1;i>=0;--i){if(typeof fields[i]!=="object"){fields[i]={key:fields[i]};}}var parsers={},p;for(i=fields.length-1;i>=0;--i){p=(typeof fields[i].parser==="function"?fields[i].parser:DS.Parser[fields[i].parser+""])||fields[i].converter;if(p){parsers[fields[i].key]=p;}}var arrType=lang.isArray(oFullResponse[0]);for(i=oFullResponse.length-1;i>-1;i--){var oResult={};rec=oFullResponse[i];if(typeof rec==="object"){for(j=fields.length-1;j>-1;j--){field=fields[j];data=arrType?rec[j]:rec[field.key];if(parsers[field.key]){data=parsers[field.key].call(this,data);}if(data===undefined){data=null;}oResult[field.key]=data;}}else{if(lang.isString(rec)){for(j=fields.length-1;j>-1;j--){field=fields[j];data=rec;if(parsers[field.key]){data=parsers[field.key].call(this,data);}if(data===undefined){data=null;}oResult[field.key]=data;}}}results[i]=oResult;}}else{results=oFullResponse;}var oParsedResponse={results:results};return oParsedResponse;}return null;},parseTextData:function(oRequest,oFullResponse){if(lang.isString(oFullResponse)){if(lang.isString(this.responseSchema.recordDelim)&&lang.isString(this.responseSchema.fieldDelim)){var oParsedResponse={results:[]};var recDelim=this.responseSchema.recordDelim;var fieldDelim=this.responseSchema.fieldDelim;if(oFullResponse.length>0){var newLength=oFullResponse.length-recDelim.length;if(oFullResponse.substr(newLength)==recDelim){oFullResponse=oFullResponse.substr(0,newLength);}if(oFullResponse.length>0){var recordsarray=oFullResponse.split(recDelim);for(var i=0,len=recordsarray.length,recIdx=0;i<len;++i){var bError=false,sRecord=recordsarray[i];if(lang.isString(sRecord)&&(sRecord.length>0)){var fielddataarray=recordsarray[i].split(fieldDelim);var oResult={};if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(var j=fields.length-1;j>-1;j--){try{var data=fielddataarray[j];if(lang.isString(data)){if(data.charAt(0)=='"'){data=data.substr(1);}if(data.charAt(data.length-1)=='"'){data=data.substr(0,data.length-1);}var field=fields[j];var key=(lang.isValue(field.key))?field.key:field;if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}else{bError=true;}}catch(e){bError=true;}}}else{oResult=fielddataarray;}if(!bError){oParsedResponse.results[recIdx++]=oResult;}}}}}return oParsedResponse;}}return null;},parseXMLResult:function(result){var oResult={},schema=this.responseSchema;try{for(var m=schema.fields.length-1;m>=0;m--){var field=schema.fields[m];var key=(lang.isValue(field.key))?field.key:field;var data=null;var xmlAttr=result.attributes.getNamedItem(key);if(xmlAttr){data=xmlAttr.value;}else{var xmlNode=result.getElementsByTagName(key);if(xmlNode&&xmlNode.item(0)&&xmlNode.item(0)){data=xmlNode.item(0).firstChild.nodeValue;var item=xmlNode.item(0);data=(item.text)?item.text:(item.textContent)?item.textContent:null;
if(!data){var datapieces=[];for(var j=0,len=item.childNodes.length;j<len;j++){if(item.childNodes[j].nodeValue){datapieces[datapieces.length]=item.childNodes[j].nodeValue;}}if(datapieces.length>0){data=datapieces.join("");}}}}if(data===null){data="";}if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}}catch(e){}return oResult;},parseXMLData:function(oRequest,oFullResponse){var bError=false,schema=this.responseSchema,oParsedResponse={meta:{}},xmlList=null,metaNode=schema.metaNode,metaLocators=schema.metaFields||{},i,k,loc,v;try{xmlList=(schema.resultNode)?oFullResponse.getElementsByTagName(schema.resultNode):null;metaNode=metaNode?oFullResponse.getElementsByTagName(metaNode)[0]:oFullResponse;if(metaNode){for(k in metaLocators){if(lang.hasOwnProperty(metaLocators,k)){loc=metaLocators[k];v=metaNode.getElementsByTagName(loc)[0];if(v){v=v.firstChild.nodeValue;}else{v=metaNode.attributes.getNamedItem(loc);if(v){v=v.value;}}if(lang.isValue(v)){oParsedResponse.meta[k]=v;}}}}}catch(e){}if(!xmlList||!lang.isArray(schema.fields)){bError=true;}else{oParsedResponse.results=[];for(i=xmlList.length-1;i>=0;--i){var oResult=this.parseXMLResult(xmlList.item(i));oParsedResponse.results[i]=oResult;}}if(bError){oParsedResponse.error=true;}else{}return oParsedResponse;},parseJSONData:function(oRequest,oFullResponse){var oParsedResponse={results:[],meta:{}};if(lang.isObject(oFullResponse)&&this.responseSchema.resultsList){var schema=this.responseSchema,fields=schema.fields,resultsList=oFullResponse,results=[],metaFields=schema.metaFields||{},fieldParsers=[],fieldPaths=[],simpleFields=[],bError=false,i,len,j,v,key,parser,path;var buildPath=function(needle){var path=null,keys=[],i=0;if(needle){needle=needle.replace(/\[(['"])(.*?)\1\]/g,function(x,$1,$2){keys[i]=$2;return".@"+(i++);}).replace(/\[(\d+)\]/g,function(x,$1){keys[i]=parseInt($1,10)|0;return".@"+(i++);}).replace(/^\./,"");if(!/[^\w\.\$@]/.test(needle)){path=needle.split(".");for(i=path.length-1;i>=0;--i){if(path[i].charAt(0)==="@"){path[i]=keys[parseInt(path[i].substr(1),10)];}}}else{}}return path;};var walkPath=function(path,origin){var v=origin,i=0,len=path.length;for(;i<len&&v;++i){v=v[path[i]];}return v;};path=buildPath(schema.resultsList);if(path){resultsList=walkPath(path,oFullResponse);if(resultsList===undefined){bError=true;}}else{bError=true;}if(!resultsList){resultsList=[];}if(!lang.isArray(resultsList)){resultsList=[resultsList];}if(!bError){if(schema.fields){var field;for(i=0,len=fields.length;i<len;i++){field=fields[i];key=field.key||field;parser=((typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""])||field.converter;path=buildPath(key);if(parser){fieldParsers[fieldParsers.length]={key:key,parser:parser};}if(path){if(path.length>1){fieldPaths[fieldPaths.length]={key:key,path:path};}else{simpleFields[simpleFields.length]={key:key,path:path[0]};}}else{}}for(i=resultsList.length-1;i>=0;--i){var r=resultsList[i],rec={};for(j=simpleFields.length-1;j>=0;--j){rec[simpleFields[j].key]=(r[simpleFields[j].path]!==undefined)?r[simpleFields[j].path]:r[j];}for(j=fieldPaths.length-1;j>=0;--j){rec[fieldPaths[j].key]=walkPath(fieldPaths[j].path,r);}for(j=fieldParsers.length-1;j>=0;--j){var p=fieldParsers[j].key;rec[p]=fieldParsers[j].parser(rec[p]);if(rec[p]===undefined){rec[p]=null;}}results[i]=rec;}}else{results=resultsList;}for(key in metaFields){if(lang.hasOwnProperty(metaFields,key)){path=buildPath(metaFields[key]);if(path){v=walkPath(path,oFullResponse);oParsedResponse.meta[key]=v;}}}}else{oParsedResponse.error=true;}oParsedResponse.results=results;}else{oParsedResponse.error=true;}return oParsedResponse;},parseHTMLTableData:function(oRequest,oFullResponse){var bError=false;var elTable=oFullResponse;var fields=this.responseSchema.fields;var oParsedResponse={results:[]};for(var i=0;i<elTable.tBodies.length;i++){var elTbody=elTable.tBodies[i];for(var j=elTbody.rows.length-1;j>-1;j--){var elRow=elTbody.rows[j];var oResult={};for(var k=fields.length-1;k>-1;k--){var field=fields[k];var key=(lang.isValue(field.key))?field.key:field;var data=elRow.cells[k].innerHTML;if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}oParsedResponse.results[j]=oResult;}}if(bError){oParsedResponse.error=true;}else{}return oParsedResponse;}};lang.augmentProto(DS,util.EventProvider);util.LocalDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_LOCAL;if(oLiveData){if(YAHOO.lang.isArray(oLiveData)){this.responseType=DS.TYPE_JSARRAY;}else{if(oLiveData.nodeType&&oLiveData.nodeType==9){this.responseType=DS.TYPE_XML;}else{if(oLiveData.nodeName&&(oLiveData.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;oLiveData=oLiveData.cloneNode(true);}else{if(YAHOO.lang.isString(oLiveData)){this.responseType=DS.TYPE_TEXT;}else{if(YAHOO.lang.isObject(oLiveData)){this.responseType=DS.TYPE_JSON;}}}}}}else{oLiveData=[];this.responseType=DS.TYPE_JSARRAY;}this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.LocalDataSource,DS);lang.augmentObject(util.LocalDataSource,DS);util.FunctionDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_JSFUNCTION;oLiveData=oLiveData||function(){};this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.FunctionDataSource,DS,{makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData(oRequest);if(this.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML;
}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT;}}}}}}this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId;}});lang.augmentObject(util.FunctionDataSource,DS);util.ScriptNodeDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_SCRIPTNODE;oLiveData=oLiveData||"";this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.ScriptNodeDataSource,DS,{getUtility:util.Get,asyncMode:"allowAll",scriptCallbackParam:"callback",generateRequestCallback:function(id){return"&"+this.scriptCallbackParam+"=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]";},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});if(util.ScriptNodeDataSource._nPending===0){util.ScriptNodeDataSource.callbacks=[];util.ScriptNodeDataSource._nId=0;}var id=util.ScriptNodeDataSource._nId;util.ScriptNodeDataSource._nId++;var oSelf=this;util.ScriptNodeDataSource.callbacks[id]=function(oRawResponse){if((oSelf.asyncMode!=="ignoreStaleResponses")||(id===util.ScriptNodeDataSource.callbacks.length-1)){if(oSelf.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){oSelf.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse.nodeType&&oRawResponse.nodeType==9){oSelf.responseType=DS.TYPE_XML;}else{if(oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){oSelf.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){oSelf.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){oSelf.responseType=DS.TYPE_TEXT;}}}}}}oSelf.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);}else{}delete util.ScriptNodeDataSource.callbacks[id];};util.ScriptNodeDataSource._nPending++;var sUri=this.liveData+oRequest+this.generateRequestCallback(id);this.getUtility.script(sUri,{autopurge:true,onsuccess:util.ScriptNodeDataSource._bumpPendingDown,onfail:util.ScriptNodeDataSource._bumpPendingDown});return tId;}});lang.augmentObject(util.ScriptNodeDataSource,DS);lang.augmentObject(util.ScriptNodeDataSource,{_nId:0,_nPending:0,callbacks:[]});util.XHRDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_XHR;this.connMgr=this.connMgr||util.Connect;oLiveData=oLiveData||"";this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.XHRDataSource,DS,{connMgr:null,connXhrMode:"allowAll",connMethodPost:false,connTimeout:0,makeConnection:function(oRequest,oCallback,oCaller){var oRawResponse=null;var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oSelf=this;var oConnMgr=this.connMgr;var oQueue=this._oQueue;var _xhrSuccess=function(oResponse){if(oResponse&&(this.asyncMode=="ignoreStaleResponses")&&(oResponse.tId!=oQueue.conn.tId)){return null;}else{if(!oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);return null;}else{if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oResponse.getResponseHeader)?oResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML;}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON;}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT;}}}}}this.handleResponse(oRequest,oResponse,oCallback,oCaller,tId);}}};var _xhrFailure=function(oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,callback:oCallback,caller:oCaller,message:DS.ERROR_DATAINVALID});if(lang.isString(this.liveData)&&lang.isString(oRequest)&&(this.liveData.lastIndexOf("?")!==this.liveData.length-1)&&(oRequest.indexOf("?")!==0)){}oResponse=oResponse||{};oResponse.error=true;DS.issueCallback(oCallback,[oRequest,oResponse],true,oCaller);return null;};var _xhrCallback={success:_xhrSuccess,failure:_xhrFailure,scope:this};if(lang.isNumber(this.connTimeout)){_xhrCallback.timeout=this.connTimeout;}if(this.connXhrMode=="cancelStaleRequests"){if(oQueue.conn){if(oConnMgr.abort){oConnMgr.abort(oQueue.conn);oQueue.conn=null;}else{}}}if(oConnMgr&&oConnMgr.asyncRequest){var sLiveData=this.liveData;var isPost=this.connMethodPost;var sMethod=(isPost)?"POST":"GET";var sUri=(isPost||!lang.isValue(oRequest))?sLiveData:sLiveData+oRequest;var sRequest=(isPost)?oRequest:null;if(this.connXhrMode!="queueRequests"){oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest);}else{if(oQueue.conn){var allRequests=oQueue.requests;allRequests.push({request:oRequest,callback:_xhrCallback});if(!oQueue.interval){oQueue.interval=setInterval(function(){if(oConnMgr.isCallInProgress(oQueue.conn)){return ;}else{if(allRequests.length>0){sUri=(isPost||!lang.isValue(allRequests[0].request))?sLiveData:sLiveData+allRequests[0].request;sRequest=(isPost)?allRequests[0].request:null;oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,allRequests[0].callback,sRequest);allRequests.shift();}else{clearInterval(oQueue.interval);oQueue.interval=null;}}},50);}}else{oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest);}}}else{DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);}return tId;}});lang.augmentObject(util.XHRDataSource,DS);util.DataSource=function(oLiveData,oConfigs){oConfigs=oConfigs||{};var dataType=oConfigs.dataType;if(dataType){if(dataType==DS.TYPE_LOCAL){lang.augmentObject(util.DataSource,util.LocalDataSource);return new util.LocalDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_XHR){lang.augmentObject(util.DataSource,util.XHRDataSource);return new util.XHRDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_SCRIPTNODE){lang.augmentObject(util.DataSource,util.ScriptNodeDataSource);
return new util.ScriptNodeDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_JSFUNCTION){lang.augmentObject(util.DataSource,util.FunctionDataSource);return new util.FunctionDataSource(oLiveData,oConfigs);}}}}}if(YAHOO.lang.isString(oLiveData)){lang.augmentObject(util.DataSource,util.XHRDataSource);return new util.XHRDataSource(oLiveData,oConfigs);}else{if(YAHOO.lang.isFunction(oLiveData)){lang.augmentObject(util.DataSource,util.FunctionDataSource);return new util.FunctionDataSource(oLiveData,oConfigs);}else{lang.augmentObject(util.DataSource,util.LocalDataSource);return new util.LocalDataSource(oLiveData,oConfigs);}}};lang.augmentObject(util.DataSource,DS);})();YAHOO.util.Number={format:function(B,F){F=F||{};if(!YAHOO.lang.isNumber(B)){B*=1;}if(YAHOO.lang.isNumber(B)){var D=(B<0);var J=B+"";var G=(F.decimalSeparator)?F.decimalSeparator:".";var H;if(YAHOO.lang.isNumber(F.decimalPlaces)){var I=F.decimalPlaces;var C=Math.pow(10,I);J=Math.round(B*C)/C+"";H=J.lastIndexOf(".");if(I>0){if(H<0){J+=G;H=J.length-1;}else{if(G!=="."){J=J.replace(".",G);}}while((J.length-1-H)<I){J+="0";}}}if(F.thousandsSeparator){var L=F.thousandsSeparator;H=J.lastIndexOf(G);H=(H>-1)?H:J.length;var K=J.substring(H);var A=-1;for(var E=H;E>0;E--){A++;if((A%3===0)&&(E!==H)&&(!D||(E>1))){K=L+K;}K=J.charAt(E-1)+K;}J=K;}J=(F.prefix)?F.prefix+J:J;J=(F.suffix)?J+F.suffix:J;return J;}else{return B;}}};(function(){var A=function(C,E,D){if(typeof D==="undefined"){D=10;}for(;parseInt(C,10)<D&&D>1;D/=10){C=E.toString()+C;}return C.toString();};var B={formats:{a:function(D,C){return C.a[D.getDay()];},A:function(D,C){return C.A[D.getDay()];},b:function(D,C){return C.b[D.getMonth()];},B:function(D,C){return C.B[D.getMonth()];},C:function(C){return A(parseInt(C.getFullYear()/100,10),0);},d:["getDate","0"],e:["getDate"," "],g:function(C){return A(parseInt(B.formats.G(C)%100,10),0);},G:function(E){var F=E.getFullYear();var D=parseInt(B.formats.V(E),10);var C=parseInt(B.formats.W(E),10);if(C>D){F++;}else{if(C===0&&D>=52){F--;}}return F;},H:["getHours","0"],I:function(D){var C=D.getHours()%12;return A(C===0?12:C,0);},j:function(G){var F=new Date(""+G.getFullYear()+"/1/1 GMT");var D=new Date(""+G.getFullYear()+"/"+(G.getMonth()+1)+"/"+G.getDate()+" GMT");var C=D-F;var E=parseInt(C/60000/60/24,10)+1;return A(E,0,100);},k:["getHours"," "],l:function(D){var C=D.getHours()%12;return A(C===0?12:C," ");},m:function(C){return A(C.getMonth()+1,0);},M:["getMinutes","0"],p:function(D,C){return C.p[D.getHours()>=12?1:0];},P:function(D,C){return C.P[D.getHours()>=12?1:0];},s:function(D,C){return parseInt(D.getTime()/1000,10);},S:["getSeconds","0"],u:function(C){var D=C.getDay();return D===0?7:D;},U:function(F){var C=parseInt(B.formats.j(F),10);var E=6-F.getDay();var D=parseInt((C+E)/7,10);return A(D,0);},V:function(F){var E=parseInt(B.formats.W(F),10);var C=(new Date(""+F.getFullYear()+"/1/1")).getDay();var D=E+(C>4||C<=1?0:1);if(D===53&&(new Date(""+F.getFullYear()+"/12/31")).getDay()<4){D=1;}else{if(D===0){D=B.formats.V(new Date(""+(F.getFullYear()-1)+"/12/31"));}}return A(D,0);},w:"getDay",W:function(F){var C=parseInt(B.formats.j(F),10);var E=7-B.formats.u(F);var D=parseInt((C+E)/7,10);return A(D,0,10);},y:function(C){return A(C.getFullYear()%100,0);},Y:"getFullYear",z:function(E){var D=E.getTimezoneOffset();var C=A(parseInt(Math.abs(D/60),10),0);var F=A(Math.abs(D%60),0);return(D>0?"-":"+")+C+F;},Z:function(C){var D=C.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/,"$2").replace(/[a-z ]/g,"");if(D.length>4){D=B.formats.z(C);}return D;},"%":function(C){return"%";}},aggregates:{c:"locale",D:"%m/%d/%y",F:"%Y-%m-%d",h:"%b",n:"\n",r:"locale",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"},format:function(G,F,D){F=F||{};if(!(G instanceof Date)){return YAHOO.lang.isValue(G)?G:"";}var H=F.format||"%m/%d/%Y";if(H==="YYYY/MM/DD"){H="%Y/%m/%d";}else{if(H==="DD/MM/YYYY"){H="%d/%m/%Y";}else{if(H==="MM/DD/YYYY"){H="%m/%d/%Y";}}}D=D||"en";if(!(D in YAHOO.util.DateLocale)){if(D.replace(/-[a-zA-Z]+$/,"") in YAHOO.util.DateLocale){D=D.replace(/-[a-zA-Z]+$/,"");}else{D="en";}}var J=YAHOO.util.DateLocale[D];var C=function(L,K){var M=B.aggregates[K];return(M==="locale"?J[K]:M);};var E=function(L,K){var M=B.formats[K];if(typeof M==="string"){return G[M]();}else{if(typeof M==="function"){return M.call(G,G,J);}else{if(typeof M==="object"&&typeof M[0]==="string"){return A(G[M[0]](),M[1]);}else{return K;}}}};while(H.match(/%[cDFhnrRtTxX]/)){H=H.replace(/%([cDFhnrRtTxX])/g,C);}var I=H.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g,E);C=E=undefined;return I;}};YAHOO.namespace("YAHOO.util");YAHOO.util.Date=B;YAHOO.util.DateLocale={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],r:"%I:%M:%S %p",x:"%d/%m/%y",X:"%T"};YAHOO.util.DateLocale["en"]=YAHOO.lang.merge(YAHOO.util.DateLocale,{});YAHOO.util.DateLocale["en-US"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"],{c:"%a %d %b %Y %I:%M:%S %p %Z",x:"%m/%d/%Y",X:"%I:%M:%S %p"});YAHOO.util.DateLocale["en-GB"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"],{r:"%l:%M:%S %P %Z"});YAHOO.util.DateLocale["en-AU"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"]);})();YAHOO.register("datasource",YAHOO.util.DataSource,{version:"2.6.0",build:"1321"});

/*../vendor/yui_260/build/autocomplete/autocomplete-min.js*/

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.6.0
*/
YAHOO.widget.DS_JSArray=YAHOO.util.LocalDataSource;YAHOO.widget.DS_JSFunction=YAHOO.util.FunctionDataSource;YAHOO.widget.DS_XHR=function(B,A,D){var C=new YAHOO.util.XHRDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_ScriptNode=function(B,A,D){var C=new YAHOO.util.ScriptNodeDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_XHR.TYPE_JSON=YAHOO.util.DataSourceBase.TYPE_JSON;YAHOO.widget.DS_XHR.TYPE_XML=YAHOO.util.DataSourceBase.TYPE_XML;YAHOO.widget.DS_XHR.TYPE_FLAT=YAHOO.util.DataSourceBase.TYPE_TEXT;YAHOO.widget.AutoComplete=function(G,B,J,C){if(G&&B&&J){if(J instanceof YAHOO.util.DataSourceBase){this.dataSource=J;}else{return ;}this.key=0;var D=J.responseSchema;if(J._aDeprecatedSchema){var K=J._aDeprecatedSchema;if(YAHOO.lang.isArray(K)){if((J.responseType===YAHOO.util.DataSourceBase.TYPE_JSON)||(J.responseType===YAHOO.util.DataSourceBase.TYPE_UNKNOWN)){D.resultsList=K[0];this.key=K[1];D.fields=(K.length<3)?null:K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_XML){D.resultNode=K[0];this.key=K[1];D.fields=K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_TEXT){D.recordDelim=K[0];D.fieldDelim=K[1];}}}J.responseSchema=D;}}if(YAHOO.util.Dom.inDocument(G)){if(YAHOO.lang.isString(G)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+G;this._elTextbox=document.getElementById(G);}else{this._sName=(G.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+G.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._elTextbox=G;}YAHOO.util.Dom.addClass(this._elTextbox,"yui-ac-input");}else{return ;}if(YAHOO.util.Dom.inDocument(B)){if(YAHOO.lang.isString(B)){this._elContainer=document.getElementById(B);}else{this._elContainer=B;}if(this._elContainer.style.display=="none"){}var E=this._elContainer.parentNode;var A=E.tagName.toLowerCase();if(A=="div"){YAHOO.util.Dom.addClass(E,"yui-ac");}else{}}else{return ;}if(this.dataSource.dataType===YAHOO.util.DataSourceBase.TYPE_LOCAL){this.applyLocalFilter=true;}if(C&&(C.constructor==Object)){for(var I in C){if(I){this[I]=C[I];}}}this._initContainerEl();this._initProps();this._initListEl();this._initContainerHelperEls();var H=this;var F=this._elTextbox;YAHOO.util.Event.addListener(F,"keyup",H._onTextboxKeyUp,H);YAHOO.util.Event.addListener(F,"keydown",H._onTextboxKeyDown,H);YAHOO.util.Event.addListener(F,"focus",H._onTextboxFocus,H);YAHOO.util.Event.addListener(F,"blur",H._onTextboxBlur,H);YAHOO.util.Event.addListener(B,"mouseover",H._onContainerMouseover,H);YAHOO.util.Event.addListener(B,"mouseout",H._onContainerMouseout,H);YAHOO.util.Event.addListener(B,"click",H._onContainerClick,H);YAHOO.util.Event.addListener(B,"scroll",H._onContainerScroll,H);YAHOO.util.Event.addListener(B,"resize",H._onContainerResize,H);YAHOO.util.Event.addListener(F,"keypress",H._onTextboxKeyPress,H);YAHOO.util.Event.addListener(window,"unload",H._onWindowUnload,H);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerPopulateEvent=new YAHOO.util.CustomEvent("containerPopulate",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);this.textboxChangeEvent=new YAHOO.util.CustomEvent("textboxChange",this);F.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.applyLocalFilter=null;YAHOO.widget.AutoComplete.prototype.queryMatchCase=false;YAHOO.widget.AutoComplete.prototype.queryMatchContains=false;YAHOO.widget.AutoComplete.prototype.queryMatchSubset=false;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.typeAheadDelay=0.5;YAHOO.widget.AutoComplete.prototype.queryInterval=500;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.suppressInputUpdate=false;YAHOO.widget.AutoComplete.prototype.resultTypeList=true;YAHOO.widget.AutoComplete.prototype.queryQuestionMark=true;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.getInputEl=function(){return this._elTextbox;};YAHOO.widget.AutoComplete.prototype.getContainerEl=function(){return this._elContainer;
};YAHOO.widget.AutoComplete.prototype.isFocused=function(){return(this._bFocused===null)?false:this._bFocused;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListEl=function(){return this._elList;};YAHOO.widget.AutoComplete.prototype.getListItemMatch=function(A){if(A._sResultMatch){return A._sResultMatch;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemData=function(A){if(A._oResultData){return A._oResultData;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemIndex=function(A){if(YAHOO.lang.isNumber(A._nItemIndex)){return A._nItemIndex;}else{return null;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(B){if(this._elHeader){var A=this._elHeader;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setFooter=function(B){if(this._elFooter){var A=this._elFooter;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setBody=function(A){if(this._elBody){var B=this._elBody;YAHOO.util.Event.purgeElement(B,true);if(A){B.innerHTML=A;B.style.display="block";}else{B.innerHTML="";B.style.display="none";}this._elList=null;}};YAHOO.widget.AutoComplete.prototype.generateRequest=function(B){var A=this.dataSource.dataType;if(A===YAHOO.util.DataSourceBase.TYPE_XHR){if(!this.dataSource.connMethodPost){B=(this.queryQuestionMark?"?":"")+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}else{B=(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}else{if(A===YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE){B="&"+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}return B;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(B){var A=(this.delimChar)?this._elTextbox.value+B:B;this._sendQuery(A);};YAHOO.widget.AutoComplete.prototype.collapseContainer=function(){this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(E){var D,C,A;for(var B=E.length;B>=this.minQueryLength;B--){A=this.generateRequest(E.substr(0,B));this.dataRequestEvent.fire(this,D,A);C=this.dataSource.getCachedResponse(A);if(C){return this.filterResults.apply(this.dataSource,[E,C,C,{scope:this}]);}}return null;};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(C,B,A){var D=((this.responseStripAfter!=="")&&(B.indexOf))?B.indexOf(this.responseStripAfter):-1;if(D!=-1){B=B.substring(0,D);}return B;};YAHOO.widget.AutoComplete.prototype.filterResults=function(J,L,P,K){if(J&&J!==""){P=YAHOO.widget.AutoComplete._cloneObject(P);var H=K.scope,O=this,B=P.results,M=[],D=false,I=(O.queryMatchCase||H.queryMatchCase),A=(O.queryMatchContains||H.queryMatchContains);for(var C=B.length-1;C>=0;C--){var F=B[C];var E=null;if(YAHOO.lang.isString(F)){E=F;}else{if(YAHOO.lang.isArray(F)){E=F[0];}else{if(this.responseSchema.fields){var N=this.responseSchema.fields[0].key||this.responseSchema.fields[0];E=F[N];}else{if(this.key){E=F[this.key];}}}}if(YAHOO.lang.isString(E)){var G=(I)?E.indexOf(decodeURIComponent(J)):E.toLowerCase().indexOf(decodeURIComponent(J).toLowerCase());if((!A&&(G===0))||(A&&(G>-1))){M.unshift(F);}}}P.results=M;}else{}return P;};YAHOO.widget.AutoComplete.prototype.handleResponse=function(C,A,B){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(C,A,B);}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(C,A,B){return true;};YAHOO.widget.AutoComplete.prototype.formatResult=function(B,D,A){var C=(A)?A:"";return C;};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(D,A,C,B){return true;};YAHOO.widget.AutoComplete.prototype.destroy=function(){var B=this.toString();var A=this._elTextbox;var D=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(A,true);YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";for(var C in this){if(YAHOO.lang.hasOwnProperty(this,C)){this[C]=null;}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0;
YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=null;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var B=this.minQueryLength;if(!YAHOO.lang.isNumber(B)){this.minQueryLength=1;}var E=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(E)||(E<1)){this.maxResultsDisplayed=10;}var F=this.queryDelay;if(!YAHOO.lang.isNumber(F)||(F<0)){this.queryDelay=0.2;}var C=this.typeAheadDelay;if(!YAHOO.lang.isNumber(C)||(C<0)){this.typeAheadDelay=0.2;}var A=this.delimChar;if(YAHOO.lang.isString(A)&&(A.length>0)){this.delimChar=[A];}else{if(!YAHOO.lang.isArray(A)){this.delimChar=null;}}var D=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(D)||(D<0)){this.animSpeed=0.3;}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed);}else{this._oAnim.duration=this.animSpeed;}}if(this.forceSelection&&A){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var A=document.createElement("div");A.className="yui-ac-shadow";A.style.width=0;A.style.height=0;this._elShadow=this._elContainer.appendChild(A);}if(this.useIFrame&&!this._elIFrame){var B=document.createElement("iframe");B.src=this._iFrameSrc;B.frameBorder=0;B.scrolling="no";B.style.position="absolute";B.style.width=0;B.style.height=0;B.tabIndex=-1;B.style.padding=0;this._elIFrame=this._elContainer.appendChild(B);}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var C=document.createElement("div");C.className="yui-ac-content";C.style.display="none";this._elContent=this._elContainer.appendChild(C);var B=document.createElement("div");B.className="yui-ac-hd";B.style.display="none";this._elHeader=this._elContent.appendChild(B);var D=document.createElement("div");D.className="yui-ac-bd";this._elBody=this._elContent.appendChild(D);var A=document.createElement("div");A.className="yui-ac-ft";A.style.display="none";this._elFooter=this._elContent.appendChild(A);}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var C=this.maxResultsDisplayed;var A=this._elList||document.createElement("ul");var B;while(A.childNodes.length<C){B=document.createElement("li");B.style.display="none";B._nItemIndex=A.childNodes.length;A.appendChild(B);}if(!this._elList){var D=this._elBody;YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";this._elList=D.appendChild(A);}};YAHOO.widget.AutoComplete.prototype._enableIntervalDetection=function(){var A=this;if(!A._queryInterval&&A.queryInterval){A._queryInterval=setInterval(function(){A._onInterval();},A.queryInterval);}};YAHOO.widget.AutoComplete.prototype._onInterval=function(){var A=this._elTextbox.value;var B=this._sLastTextboxValue;if(A!=B){this._sLastTextboxValue=A;this._sendQuery(A);}};YAHOO.widget.AutoComplete.prototype._clearInterval=function(){if(this._queryInterval){clearInterval(this._queryInterval);this._queryInterval=null;}};YAHOO.widget.AutoComplete.prototype._isIgnoreKey=function(A){if((A==9)||(A==13)||(A==16)||(A==17)||(A>=18&&A<=20)||(A==27)||(A>=33&&A<=35)||(A>=36&&A<=40)||(A>=44&&A<=45)||(A==229)){return true;}return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(G){if(this.minQueryLength<0){this._toggleContainer(false);return ;}var I=(this.delimChar)?this.delimChar:null;if(I){var B=-1;for(var F=I.length-1;F>=0;F--){var D=G.lastIndexOf(I[F]);if(D>B){B=D;}}if(I[F]==" "){for(var E=I.length-1;E>=0;E--){if(G[B-1]==I[E]){B--;break;}}}if(B>-1){var H=B+1;while(G.charAt(H)==" "){H+=1;}this._sPastSelections=G.substring(0,H);G=G.substr(H);}else{this._sPastSelections="";}}if((G&&(G.length<this.minQueryLength))||(!G&&this.minQueryLength>0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);}this._toggleContainer(false);return ;}G=encodeURIComponent(G);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var A=this.getSubsetMatches(G);if(A){this.handleResponse(G,A,{query:G});return ;}}if(this.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse;}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults;}var C=this.generateRequest(G);this.dataRequestEvent.fire(this,G,C);this.dataSource.sendRequest(C,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:G}});};YAHOO.widget.AutoComplete.prototype._populateList=function(K,F,C){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID);}K=(C&&C.query)?C.query:K;var H=this.doBeforeLoadData(K,F,C);if(H&&!F.error){this.dataReturnEvent.fire(this,K,F.results);if(this._bFocused||(this._bFocused===null)){var M=decodeURIComponent(K);
this._sCurQuery=M;this._bItemSelected=false;var R=F.results,A=Math.min(R.length,this.maxResultsDisplayed),J=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(A>0){if(!this._elList||(this._elList.childNodes.length<A)){this._initListEl();}this._initContainerHelperEls();var I=this._elList.childNodes;for(var Q=A-1;Q>=0;Q--){var P=I[Q],E=R[Q];if(this.resultTypeList){var B=[];B[0]=(YAHOO.lang.isString(E))?E:E[J]||E[this.key];var L=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(L)&&(L.length>1)){for(var N=1,S=L.length;N<S;N++){B[B.length]=E[L[N].key||L[N]];}}else{if(YAHOO.lang.isArray(E)){B=E;}else{if(YAHOO.lang.isString(E)){B=[E];}else{B[1]=E;}}}E=B;}P._sResultMatch=(YAHOO.lang.isString(E))?E:(YAHOO.lang.isArray(E))?E[0]:(E[J]||"");P._oResultData=E;P.innerHTML=this.formatResult(E,M,P._sResultMatch);P.style.display="";}if(A<I.length){var G;for(var O=I.length-1;O>=A;O--){G=I[O];G.style.display="none";}}this._nDisplayedItems=A;this.containerPopulateEvent.fire(this,K,R);if(this.autoHighlight){var D=this._elList.firstChild;this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);this._typeAhead(D,K);}else{this._toggleHighlight(this._elCurListItem,"from");}H=this.doBeforeExpandContainer(this._elTextbox,this._elContainer,K,R);this._toggleContainer(H);}else{this._toggleContainer(false);}return ;}}else{this.dataErrorEvent.fire(this,K);}};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var C=this._elTextbox.value;var B=(this.delimChar)?this.delimChar[0]:null;var A=(B)?C.lastIndexOf(B,C.length-2):-1;if(A>-1){this._elTextbox.value=C.substring(0,A);}else{this._elTextbox.value="";}this._sPastSelections=this._elTextbox.value;this.selectionEnforceEvent.fire(this);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var A=null;for(var B=this._nDisplayedItems-1;B>=0;B--){var C=this._elList.childNodes[B];var D=(""+C._sResultMatch).toLowerCase();if(D==this._sCurQuery.toLowerCase()){A=C;break;}}return(A);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(B,D){if(!this.typeAhead||(this._nKeyCode==8)){return ;}var A=this,C=this._elTextbox;if(C.setSelectionRange||C.createTextRange){this._nTypeAheadDelayID=setTimeout(function(){var F=C.value.length;A._updateValue(B);var G=C.value.length;A._selectText(C,F,G);var E=C.value.substr(F,G);A.typeAheadEvent.fire(A,D,E);},(this.typeAheadDelay*1000));}};YAHOO.widget.AutoComplete.prototype._selectText=function(D,A,B){if(D.setSelectionRange){D.setSelectionRange(A,B);}else{if(D.createTextRange){var C=D.createTextRange();C.moveStart("character",A);C.moveEnd("character",B-D.value.length);C.select();}else{D.select();}}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(D){var E=this._elContent.offsetWidth+"px";var B=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var C=this._elIFrame;if(D){C.style.width=E;C.style.height=B;C.style.padding="";}else{C.style.width=0;C.style.height=0;C.style.padding=0;}}if(this.useShadow&&this._elShadow){var A=this._elShadow;if(D){A.style.width=E;A.style.height=B;}else{A.style.width=0;A.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(I){var D=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return ;}if(!I){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(!this._bContainerOpen){this._elContent.style.display="none";return ;}}var A=this._oAnim;if(A&&A.getEl()&&(this.animHoriz||this.animVert)){if(A.isAnimated()){A.stop(true);}var G=this._elContent.cloneNode(true);D.appendChild(G);G.style.top="-9000px";G.style.width="";G.style.height="";G.style.display="";var F=G.offsetWidth;var C=G.offsetHeight;var B=(this.animHoriz)?0:F;var E=(this.animVert)?0:C;A.attributes=(I)?{width:{to:F},height:{to:C}}:{width:{to:B},height:{to:E}};if(I&&!this._bContainerOpen){this._elContent.style.width=B+"px";this._elContent.style.height=E+"px";}else{this._elContent.style.width=F+"px";this._elContent.style.height=C+"px";}D.removeChild(G);G=null;var H=this;var J=function(){A.onComplete.unsubscribeAll();if(I){H._toggleContainerHelpers(true);H._bContainerOpen=I;H.containerExpandEvent.fire(H);}else{H._elContent.style.display="none";H._bContainerOpen=I;H.containerCollapseEvent.fire(H);}};this._toggleContainerHelpers(false);this._elContent.style.display="";A.onComplete.subscribe(J);A.animate();}else{if(I){this._elContent.style.display="";this._toggleContainerHelpers(true);this._bContainerOpen=I;this.containerExpandEvent.fire(this);}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=I;this.containerCollapseEvent.fire(this);}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(A,C){if(A){var B=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,B);this._elCurListItem=null;}if((C=="to")&&B){YAHOO.util.Dom.addClass(A,B);this._elCurListItem=A;}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(B,C){if(B==this._elCurListItem){return ;}var A=this.prehighlightClassName;if((C=="mouseover")&&A){YAHOO.util.Dom.addClass(B,A);}else{YAHOO.util.Dom.removeClass(B,A);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(C){if(!this.suppressInputUpdate){var F=this._elTextbox;var E=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var B=C._sResultMatch;var D="";if(E){D=this._sPastSelections;D+=B+E;if(E!=" "){D+=" ";}}else{D=B;}F.value=D;if(F.type=="textarea"){F.scrollTop=F.scrollHeight;}var A=F.value.length;this._selectText(F,A,A);this._elCurListItem=C;}};YAHOO.widget.AutoComplete.prototype._selectItem=function(A){this._bItemSelected=true;this._updateValue(A);this._sPastSelections=this._elTextbox.value;this._clearInterval();this.itemSelectEvent.fire(this,A,A._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem);
}else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(G){if(this._bContainerOpen){var F=this._elCurListItem;var E=-1;if(F){E=F._nItemIndex;}var C=(G==40)?(E+1):(E-1);if(C<-2||C>=this._nDisplayedItems){return ;}if(F){this._toggleHighlight(F,"from");this.itemArrowFromEvent.fire(this,F);}if(C==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery;}else{this._elTextbox.value=this._sCurQuery;}return ;}if(C==-2){this._toggleContainer(false);return ;}var D=this._elList.childNodes[C];var A=this._elContent;var B=((YAHOO.util.Dom.getStyle(A,"overflow")=="auto")||(YAHOO.util.Dom.getStyle(A,"overflowY")=="auto"));if(B&&(C>-1)&&(C<this._nDisplayedItems)){if(G==40){if((D.offsetTop+D.offsetHeight)>(A.scrollTop+A.offsetHeight)){A.scrollTop=(D.offsetTop+D.offsetHeight)-A.offsetHeight;}else{if((D.offsetTop+D.offsetHeight)<A.scrollTop){A.scrollTop=D.offsetTop;}}}else{if(D.offsetTop<A.scrollTop){this._elContent.scrollTop=D.offsetTop;}else{if(D.offsetTop>(A.scrollTop+A.offsetHeight)){this._elContent.scrollTop=(D.offsetTop+D.offsetHeight)-A.offsetHeight;}}}}this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);if(this.typeAhead){this._updateValue(D);}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseover");}else{C._toggleHighlight(D,"to");}C.itemMouseOverEvent.fire(C,D);break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=true;return ;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseout");}else{C._toggleHighlight(D,"from");}C.itemMouseOutEvent.fire(C,D);break;case"ul":C._toggleHighlight(C._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=false;return ;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":C._toggleHighlight(D,"to");C._selectItem(D);return ;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(A,B){B._elTextbox.focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(A,B){B._toggleContainerHelpers(B._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(A,B){var C=A.keyCode;if(B._nTypeAheadDelayID!=-1){clearTimeout(B._nTypeAheadDelayID);}switch(C){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B.delimChar&&(B._nKeyCode!=C)){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B._nKeyCode!=C){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 27:B._toggleContainer(false);return ;case 39:B._jumpSelection();break;case 38:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;case 40:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;default:B._bItemSelected=false;B._toggleHighlight(B._elCurListItem,"from");B.textboxKeyEvent.fire(B,C);break;}if(C===18){B._enableIntervalDetection();}B._nKeyCode=C;};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(A,B){var C=A.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(C){case 9:if(B._bContainerOpen){if(B.delimChar){YAHOO.util.Event.stopEvent(A);}if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;default:break;}}else{if(C==229){B._enableIntervalDetection();}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(A,C){var B=this.value;C._initProps();var D=A.keyCode;if(C._isIgnoreKey(D)){return ;}if(C._nDelayID!=-1){clearTimeout(C._nDelayID);}C._nDelayID=setTimeout(function(){C._sendQuery(B);},(C.queryDelay*1000));};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(A,B){if(!B._bFocused){B._elTextbox.setAttribute("autocomplete","off");B._bFocused=true;B._sInitInputValue=B._elTextbox.value;B.textboxFocusEvent.fire(B);}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(A,C){if(!C._bOverContainer||(C._nKeyCode==9)){if(!C._bItemSelected){var B=C._textMatchesOption();if(!C._bContainerOpen||(C._bContainerOpen&&(B===null))){if(C.forceSelection){C._clearSelection();}else{C.unmatchedItemSelectEvent.fire(C,C._sCurQuery);}}else{if(C.forceSelection){C._selectItem(B);}}}if(C._bContainerOpen){C._toggleContainer(false);}C._clearInterval();C._bFocused=false;if(C._sInitInputValue!==C._elTextbox.value){C.textboxChangeEvent.fire(C);}C.textboxBlurEvent.fire(C);}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(A,B){if(B&&B._elTextbox&&B.allowBrowserAutocomplete){B._elTextbox.setAttribute("autocomplete","on");}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(A){return this.generateRequest(A);};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var C=[],B=this._elList.childNodes;for(var A=B.length-1;A>=0;A--){C[A]=B[A];}return C;};YAHOO.widget.AutoComplete._cloneObject=function(D){if(!YAHOO.lang.isValue(D)){return D;
}var F={};if(YAHOO.lang.isFunction(D)){F=D;}else{if(YAHOO.lang.isArray(D)){var E=[];for(var C=0,B=D.length;C<B;C++){E[C]=YAHOO.widget.AutoComplete._cloneObject(D[C]);}F=E;}else{if(YAHOO.lang.isObject(D)){for(var A in D){if(YAHOO.lang.hasOwnProperty(D,A)){if(YAHOO.lang.isValue(D[A])&&YAHOO.lang.isObject(D[A])||YAHOO.lang.isArray(D[A])){F[A]=YAHOO.widget.AutoComplete._cloneObject(D[A]);}else{F[A]=D[A];}}}}else{F=D;}}}return F;};YAHOO.register("autocomplete",YAHOO.widget.AutoComplete,{version:"2.6.0",build:"1321"});

/*indexPropSrch.js*/

widthMoreOpt=0;
maxMoreOpt=330;
//For Mls Propery Alert
function saveSearchAlert()
{
	var neighBorHood = "";
	var subNhood	 = "";
	var selValArr	 = "";
	var subNhoodId	 = "";
	var city	 = ""; 
	var state	 = ""; 
	var zip		 = "";
	var propLat	 = "";
	var propLong = "";
	var queryStr = "";
	var agentId = "";

	var cUrl = "/app/mlsPropertyAlert/propertyFinder.php";

	if(trim($('srchName').value) == "Enter Name for your search alert")
	{
		$('srchName').value = "";
	}

	if(trim($('srchName').value) == "")
	{
		$('srchName').value = "Enter Name for your search alert";
		alert ("Please Enter Alert name");
		return;
	}	
	
	var searchCSZ = $("searchCSZ").value;
	if(trim($('searchCSZ').value) == "" || trim($('searchCSZ').value) == "Enter Neighborhood, City or ZIP code")
	{
		alert("Please Enter Neighborhood, City or ZIP code");		
		$('searchCSZ').focus();
		return;
	}	

	if(validateAmSearchCriteria())
	{
		if($F('selVal') == "NBR")
		{			
			var neighBorHood = escape(encodeURI(searchCSZ));		
		}
		else if($F('selVal').indexOf("SNBR") != -1)
		{
			var subNhood	= searchCSZ;
			var selValArr	= $F('selVal').split("_");
			var subNhoodId	= selValArr[1];				
		}
		else if($F('selVal').indexOf("CS") != -1)		
		{		
			var retArray = doGeoCode(searchCSZ,"");

			var city	= retArray['city'];
			var state	= retArray['state'];
			var zip		= retArray['zip'];
			var propLat	= retArray['lat'];
			var propLong	= retArray['lng'];	
		}

		if(fromPage == 'agt')
		{
			agentId = '&frm=agt&aid='+ aid;
		}
		
		//Selection On Search
		if($F('selVal') == 'NBR')
			queryStr += '&Neighbourhood=' + neighBorHood;
		else if($F("selVal").indexOf("SNBR") != -1)
			queryStr += '&SubNHoodName=' + subNhood.replace(/\&/g,'_') + '&SubNHoodId=' + subNhoodId;	
		else
			queryStr += '&City=' + city + '&State=' + state + '&Zip='+ zip + '&Latitude=' + propLat + '&Longitude=' + propLong;
		
		if($('searchType').options[$('searchType').selectedIndex].text == "Any")
			queryStr += "&PropertyType=";
		else
			queryStr += "&PropertyType=" + $('searchType').options[$('searchType').selectedIndex].text;
		
		if($("searchBeds").value != "")
			queryStr += "&minBeds=" + $("searchBeds").value;

		if($("searchBaths").value != "")
			queryStr += "&minBaths=" + $("searchBaths").value;		

		if($("minprice").value != "")
			queryStr += "&minPrice=" + ($("minprice").value).replace(',','');

		if($("maxprice").value != "")
			queryStr += "&maxPrice=" + ($("maxprice").value).replace(',','');

		if($("chkOpnHome") && $("chkOpnHome").checked)
			queryStr += "&OpenHome=1";

		if($('chkForeClosureListings') && $('chkForeClosureListings').checked)
		{
			//setSearchCookie("searchCriteria","bankOwned");
			queryStr += "&BankOwned=true";
		}
		if($('chkOnlyPhotos') && $('chkOnlyPhotos').checked)
			queryStr += "&Photo=1";
		queryStr += "&Active=1";
		
		queryStr += agentId + "&SrchNm="+ escape($('srchName').value);		
		ajaxRequest(cUrl,queryStr,alertCallBackfn,false);	
	}
}

function alertCallBackfn(reqObj)
{
	var response = trim(reqObj.responseText);
	
	if(response.indexOf("=^^=") != -1)
	{
		var allResponse  = response.split("=^^=");
		response	= allResponse[0];		
	}

	if(trim(response) == "SUC")
	{
    	alert("Email Alert Saved Successfully.");
		hideAlertBox();
   	}
	else
   	{
   		alert("Email Alert can not be saved.");
		hideAlertBox();
   	}	
}

function showAlertBox(url)
{
	if(uid == '')
	{
		/*var searchCSZ = $("searchCSZ").value;
		if(trim($('searchCSZ').value) == "" || trim($('searchCSZ').value) == "Enter Neighborhood, City or ZIP code")
		{
			alert("Please Enter Neighborhood, City or ZIP code");		
			$('searchCSZ').focus();
			return;
		}	*/

		if(validateAmSearchCriteria())
		{
			if($('selVal').value == "NBR")
			{
				var nbrName = trim($F("searchCSZ")).replace('&','|and|');
				nbrName = nbrName.replace('/','__');
				removeSearchCookie('city');
				removeSearchCookie('state');
				removeSearchCookie('zip');
				removeSearchCookie('subNhoodId');
				removeSearchCookie('subNhood');
				removeSearchCookie('polygon');
				removeSearchCookie('area');
				setSearchCookie("neighborhood",trim($F("searchCSZ")));
				setSearchCookie("nbrIndex","1");
			}
			else if($F('selVal').indexOf("SNBR") != -1)
			{
				removeSearchCookie('city');
				removeSearchCookie('state');
				removeSearchCookie('zip');
				removeSearchCookie('neighborhood');
				var sNbrID = $F('selVal').split('_');							
				getPolygonFrmSNbr(sNbrID[1]);
				if(getSearchCookie('area') != "")
				{
					setSearchCookie("subNhoodId",sNbrID[1]);
					setSearchCookie("subNhood",$F("searchCSZ"));
				}	
			}
			else if($F('selVal').indexOf("CS") != -1)
			{
				if($F("searchCSZ") != "Enter Neighborhood, City or ZIP code" && $F("searchCSZ") != "")
				{			
				var getGeoAddress = doGeoCode($("searchCSZ").value,'');
				if(!getGeoAddress)
					return;

				var city  = getGeoAddress['city'];
				var state = getGeoAddress['state'];
				var zip = getGeoAddress['zip'];
				setSearchCookie("city",city);
				setSearchCookie("state",state);
				setSearchCookie("zip",zip);
				removeSearchCookie('polygon');
				removeSearchCookie('area');
				removeSearchCookie('subNhoodId');
				removeSearchCookie('subNhood');
				removeSearchCookie('neighborhood');
				}
			}
			/*else
			{
				setSearchCookie("city",defCity);
				setSearchCookie("state",defState);
				removeSearchCookie('polygon');
				removeSearchCookie('area');			
				removeSearchCookie('subNhoodId');
				removeSearchCookie('subNhood');
				removeSearchCookie('neighborhood');
			}*/
			if($('chkOpnHome') && $('chkOpnHome').checked) 
			{
				setSearchCookie("searchCriteria","brokeropenHome");
			}

			opensignInRegDlg(url,'R','login');
		}
	}
	else
	{
		//$('divAlertMe').style.display = 'none';
		//$('divSaveAlertMe').style.display = '';
		openEmailAlertBox('divAlertBox');
	}
}

function hideAlertBox()
{
	//$('divAlertMe').style.display = '';
	//$('divSaveAlertMe').style.display = 'none';
	openEmailAlertBox('divAlertBox');
	$('srchName').value = 'Enter Name for your search alert';
}


function validateAmSearchCriteria()
{		
	if($('minprice').value == 'Min')
		$('minprice').value = '';
	if($('maxprice').value == 'Max')
		$('maxprice').value = '';
	//----------------price param validation
	if($F('minprice') != "" || $F('maxprice') != "")
	{
		if(isNaN($F('minprice').replace(/,/g,'')) || isNaN($F('maxprice').replace(/,/g,'')))
		{
			alert("Please enter valid price range");
			$('minprice').value = '';
			$('maxprice').value = '';
			$('minprice').focus();
			return false;
		}
	}

	var minP = Number(money2num($('minprice').value));	
	var maxP = Number(money2num($('maxprice').value));
	if(minP<0 || maxP<0)
	{
		alert("Please enter valid price range");
		$('minprice').value = '';
		$('maxprice').value = '';
		$('minprice').focus();
		return false;
	}

	if((minP>maxP) && (minP != "" && maxP != ""))
	{
		alert("Please enter valid price range");
		$('minprice').value = '';
		$('maxprice').value = '';
		$('minprice').focus();
		return false;
	}	
	
	if (maxP == "0")
	{
		$('maxprice').value = '';
		maxP = "";
	}
	if (minP == "0")
	{
		$('minprice').value = '';
		minP = "";
	}
	
	if( maxP != "" && minP != "" && parseInt(maxP) <= parseInt(minP) )
	{
			$('minprice').focus();
			alert("Maximum price should be greater than minimum price.");
			$("maxprice").value = "";
			$('minprice').value = "";			
			return false;
	}
	//----------------
	setSearchCookie("minPrice",minP);
	setSearchCookie("maxPrice",maxP);
	setSearchCookie("searchBeds",$F('searchBeds'));			
	setSearchCookie("searchBaths",$F('searchBaths'));
	setSearchCookie("searchType",$F('searchType'));

	if($('chkOpnHome') && $('chkOpnHome').checked) 
	{
		setSearchCookie("searchCriteria","brokeropenHome");
	}
	if($('chkRecRed') && $('chkRecRed').checked)
	{
		setSearchCookie("searchCriteria","recentlyReduced");
	}
	if($('chkForeClosureListings') && $('chkForeClosureListings').checked)
	{
		//setSearchCookie("searchCriteria","bankOwned");
		setSearchCookie("BankOwned","true");
	}
	/*if($('SandicorListing') && $('SandicorListing').checked)
	{
		setSearchCookie("SandicorListing","SANDICOR");
	}*/
	if($('chkOnlyPhotos') && $('chkOnlyPhotos').checked)
	{
		setSearchCookie("Photo","1");
	}
	if($('chkVirtualTour') && $('chkVirtualTour').checked)
	{
		setSearchCookie("searchCriteria","virtualTour");
	}
	return true;
}

function showToolTip(toolTip,i)
{
	var divId='roloImg'+i;
	var top = getPositionTop(divId);
	var left = getPositionLeft(divId);
	$('toolTipDiv').style.top=(top+82) + "px";
	$('toolTipDiv').style.left=(left) + "px";		
	$('toolTipDiv').innerHTML = ' <span style="font-weight:normal;color:#FFF;font-family:tahoma;font-size:11px;"> '+toolTip+' </span> ';
	$('toolTipDiv').show();
}
function hideToolTip()
{
	$('toolTipDiv').hide();
}
function serCSZOnFocus(e)
{
	if($F('searchCSZ') == '' && e.type != "focus")
		$('searchCSZ').value = 'Enter Neighborhood, City or ZIP code';
	else if($F('searchCSZ') == 'Enter Neighborhood, City or ZIP code' && e.type != "blur")
		$('searchCSZ').value = '';
}
function gotoMap(moreOpt)
{		
	var lat = '';
	var lng = '';
	if(!isNaN(trim($F('searchCSZ'))))
	{
		$('selVal').value = 'CS';
	}
	var url = "/Search/";
	if ($("searchCSZ").value == "" || $F("searchCSZ").toLowerCase() == "required" || $F("searchCSZ") == "Enter Neighborhood, City or ZIP code")
	{
		//if(moreOpt != "moreOpt")
		//{
			alert ("Please Enter Neighborhood, City or ZIP code");
			$("searchCSZ").value = "";
			return;
		//}
	}
	
	if($('selVal').value == "NBR")
	{
		var nbrName = trim($F("searchCSZ")).replace('&','|and|');
		nbrName = nbrName.replace('/','__');
		removeSearchCookie('city');
		removeSearchCookie('state');
		removeSearchCookie('zip');
		removeSearchCookie('subNhoodId');
		removeSearchCookie('subNhood');
		removeSearchCookie('polygon');
		removeSearchCookie('area');
		setSearchCookie("neighborhood",trim($F("searchCSZ")));
		setSearchCookie("nbrIndex","1");
		//url = "/Search/nhood_"+nbrName;			
		url = "/Search/";			
	}
	else if($F('selVal').indexOf("SNBR") != -1)
	{
		removeSearchCookie('city');
		removeSearchCookie('state');
		removeSearchCookie('zip');
		removeSearchCookie('neighborhood');
		var sNbrID = $F('selVal').split('_');							
		getPolygonFrmSNbr(sNbrID[1]);
		if(getSearchCookie('area') != "")
		{
			setSearchCookie("subNhoodId",sNbrID[1]);
			setSearchCookie("subNhood",$F("searchCSZ"));
		}	
	}
	else if($F('selVal').indexOf("CS") != -1)
	{
		if($F("searchCSZ") != "Enter Neighborhood, City or ZIP code" && $F("searchCSZ") != "")
		{			
		var getGeoAddress = doGeoCode($("searchCSZ").value,'');
		if(!getGeoAddress)
			return;

		var city  = getGeoAddress['city'];
		var state = getGeoAddress['state'];
		var zip = getGeoAddress['zip'];
		lat = getGeoAddress['lat'];
		lng = getGeoAddress['lng'];
		setSearchCookie("city",city);
		setSearchCookie("state",state);
		setSearchCookie("zip",zip);
		removeSearchCookie('polygon');
		removeSearchCookie('area');
		//url += state+"/"+city;
		url = "/Search/";
		removeSearchCookie('subNhoodId');
		removeSearchCookie('subNhood');
		removeSearchCookie('neighborhood');
		}
	}
	else
	{
		//url += defState+"/"+defCity;
		url = "/Search/";
		setSearchCookie("city",defCity);
		setSearchCookie("state",defState);
		removeSearchCookie('polygon');
		removeSearchCookie('area');			
		removeSearchCookie('subNhoodId');
		removeSearchCookie('subNhood');
		removeSearchCookie('neighborhood');
	}
	
	if(validateAmSearchCriteria())
	{	
		if(moreOpt == "moreOpt") 
			setSearchCookie("moreOpt","1");
		else
			removeSearchCookie("moreOpt");
		
		if(fromPage == 'agt')
		{
			url = url + '?frm=agt&aid='+aid;
			if(moreOpt == 'mapView')
				url = url +'&fromPage=mapView';
			else if(moreOpt == "ds") 
			{
				url = url +'&drawSearch=1';					
			}
		}
		else
		{
			if(moreOpt == 'mapView')
				url = url +'?fromPage=mapView';
			else if(moreOpt == "ds") 
			{
				url = url +'?drawSearch=1';
			}
		}

		if(moreOpt == "ds") 
		{
			if(lat == '' && lng == '')
			{
				lat = defLat;
				lng = defLng;
			}
			var latLongStr = "[{'lat':'"+lat+"','lng':'"+lng+"'}]";				
			var now = new Date();
			now.setTime(now.getTime() + 3650 * 24 * 60 * 60 * 1000);
			setSearchCookie('lat',lat);
			setSearchCookie('lng',lng);
			setCookie("latLongCk",latLongStr,now);	
		}
		
		ref_url = url;
		if(chkSignInReqd)
			opensignInRegDlg(ref_url,'C');
		else
			location.href = url;
	}
}

function exploreEnter(event)
{
	if(event && event.keyCode == 13)
	{			
		gotoMap();				
	}
}

function clearSelVal(event)
{
	if(event && event.keyCode != 13)
	{
		$('selVal').value='';			
	}
}

function redirectSearch(type)
{
	removeSearchCookie('city');
	removeSearchCookie('state');
	removeSearchCookie('zip');
	removeSearchCookie('subNhoodId');
	removeSearchCookie('subNhood');
	removeSearchCookie('polygon');
	removeSearchCookie('minPrice');
	removeSearchCookie('maxPrice');
	removeSearchCookie('searchBeds');
	removeSearchCookie('searchBaths');
	removeSearchCookie('searchType');
	setSearchCookie("searchCriteria",type);
	if(fromPage == 'agt')
		window.open('/Search/');
	else
		location.href = '/Search/';
}

function loadFromCookie()
{
	var qs = new Querystring();
	//city,state,searchCriteria,neighborhood,subNhood,minPrice,maxPrice,searchBeds,searchBaths,searchType
	if(qs.get("city") != null)
	{
		setSearchCookie("city",qs.get("city"));
	}
	if(qs.get("state") != null)
	{
		setSearchCookie("state",qs.get("state"));
	}

	if(getSearchCookie('minPrice') != '' && getSearchCookie('minPrice') != 'undefined')
		$('minprice').value = getSearchCookie('minPrice');
	if( getSearchCookie('maxPrice') != '' && getSearchCookie('maxPrice') != 'undefined')
		$('maxprice').value = getSearchCookie('maxPrice');
	if(getSearchCookie('searchBeds') != '' && getSearchCookie('searchBeds') != 'undefined')
		$('searchBeds').value = getSearchCookie('searchBeds');
	if(getSearchCookie('searchBaths') != '' && getSearchCookie('searchBaths') != 'undefined')
		$('searchBaths').value = getSearchCookie('searchBaths');
	if(getSearchCookie('searchType') != '' && getSearchCookie('searchType') != 'undefined')
		$('searchType').value = getSearchCookie('searchType');
	if(getSearchCookie('neighborhood') != '' && getSearchCookie('neighborhood') != 'undefined')
	{
		$('selVal').value = "NBR";
		$('searchCSZ').value = getSearchCookie('neighborhood');
	}
	else if(getSearchCookie('subNhood') != '' && getSearchCookie('subNhood') != 'undefined')
	{
		$('selVal').value = "SNBR_"+ getSearchCookie('subNhoodId');
		$('searchCSZ').value = getSearchCookie('subNhood');
	}
	else if(getSearchCookie('city') != '' && getSearchCookie('city') != 'undefined')
	{
		$('selVal').value = "CS";
		$('searchCSZ').value = getSearchCookie('city')+', '+getSearchCookie('state');
	}

	if(getSearchCookie("searchCriteria") == "brokeropenHome")
	{
		$('chkOpnHome').checked = true;
	}
	else if(getSearchCookie("searchCriteria") == "newListing")
	{
		if($('chkRecRed'))
			$('chkRecRed').checked = true;
	}
	else if(getSearchCookie("searchCriteria") == "virtualTour")
	{
		if($('chkVirtualTour'))
			$('chkVirtualTour').checked = true;
	}
	if(getSearchCookie("BankOwned") == "true")
	{
		if($('chkForeClosureListings'))
			$('chkForeClosureListings').checked = true;
	}
	/*if(getSearchCookie('SandicorListing') != '' && getSearchCookie('SandicorListing') != 'undefined')
	{
		$('SandicorListing').checked = true;
	}*/
	if(getSearchCookie('Photo') != '' && getSearchCookie('Photo') == '1')
	{
		$('chkOnlyPhotos').checked = true;
	}
}

function priceOnFocus(obj,e)
{
	var id = obj.id;
	if(id == 'minprice')
	{
		if($F(id) == '' && id == 'minprice' && e.type != "focus")
			$(id).value = 'Min';
		else if($F(id) == 'Min' && e.type != "blur")
			$(id).value = '';
	}
	else if(id == 'maxprice')
	{
		if($F(id) == '' && id == 'maxprice' && e.type != "focus")
			$(id).value = 'Max';
		else if($F(id) == 'Max' && e.type != "blur")
			$(id).value = '';
	}
}

function alertNameOnFocus()
{
	if($F('srchName') == '')
		$('srchName').value = 'Enter Name for your search alert';
	else if($F('srchName') == 'Enter Name for your search alert')
		$('srchName').value = '';
}

function viewAllLink(city,state,mapView,minPrice,maxPrice,propType)
{
	ClrQckSrchCookies();
	setSearchCookie("city",city);
	setSearchCookie("state",state);
	if(typeof(minPrice) != "undefined" && minPrice != '')
		setSearchCookie("minPrice",minPrice);
	if(typeof(maxPrice) != "undefined" && maxPrice != '')
		setSearchCookie("maxPrice",maxPrice);
	if(typeof(propType) != "undefined" && propType != '')
	{
		propType = "'"+propType.replace("|","','")+"'";
		setSearchCookie("searchType",propType);
	}
	var url = '/Search/'+state+'/'+city;
	if(fromPage == 'agt')
	{
		url = url + '?frm=agt&aid='+aid;
		if(mapView == 'mapView')
			url = url +'&fromPage=mapView';
	}
	else
	{
		if(mapView == 'mapView')
			url = url +'?fromPage=mapView';
	}
	location.href = url;
}

function loadAgentsByOffId(page)
{
	$('divAgents').innerHTML = '<img src="/wt/'+bkTheme+'/images/landing/indexLoader.gif" />';
	var offId = $('cmbOffice').value;
	var url = '/help/'+bkTheme+'/randomAgents.php';
	var qs = '?op=search&offId='+offId+'&page='+page;
	ajaxRequest(url,qs,resAgents = function(originalRequest) {
				var response =  trim(originalRequest.responseText);
				$('divAgents').innerHTML = response;
			}
	);
}

function cityAutoComplete()
{
	var matchCont = '';
	YAHOO.example.BasicRemote = function()
	{
		// Use an XHRDataSource
		var oDS = new YAHOO.util.XHRDataSource("/getCity.php?getCityNbr=1");
			oDS.connMethodPost = true;


		// Set the responseType
		oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
		// Define the schema of the delimited results
		oDS.responseSchema =
		{
			recordDelim: "\n",
			fieldDelim: "\t"
		};

		// Enable caching
		oDS.maxCacheEntries = 180;
		// Instantiate the AutoComplete
		var oAC = new YAHOO.widget.AutoComplete("searchCSZ", "myContainer", oDS);
		oAC.maxResultsDisplayed = 20;
		//for IE6 BUG
		oAC.useIFrame = true;
		oAC.generateRequest = function()
		{
			matchCont = '';
			return "city="+$('searchCSZ').value;
		};
		oAC.resultTypeList = false;
		oAC.formatResult = function(oResultData, sQuery, sResultMatch)
		{
			var sKey = sResultMatch;
			var sKeyRemainder = sKey.substr(sQuery.length);
			var aMarkup = ["<div id=\'data\' class=\'yui-skin-sam\'>","<span style=\'font-weight:bold\'>", sQuery, "</span>", sKeyRemainder, "<span style=\'color:red;display:none;\'>"+ oResultData[1]+"</span></div>"];
			matchCont +='~!@'+oResultData;
			return (aMarkup.join(""));
		};
		//define your itemSelect handler function:
		var itemSelectHandler = function(Event) 
		{			
			if($('selVal')){$('selVal').value="";}
			var myArr= $("searchCSZ").value.split("&nbsp;");							
			$("searchCSZ").value=myArr[0];
			if(typeof(myArr[1])!="undefined" && myArr[1]!="")
			{	
				$('myAutoComplete').style.marginTop = "0px";
				var re = new RegExp("<span style='display:none;'>([a-zA-Z0-9_]+)<\/span>");
				var m = re.exec(myArr[1]);				
				if (m != null){if($('selVal')){$('selVal').value=m[1];}}				
			}
		};
		var dataReturnEventon = function()
		{			
			if(trim(matchCont) != "")
			{	
				matchContArr = matchCont.split('~!@');						
				if(matchContArr.length > 0 && trim($F('selVal')) == "" )
				{	
					var matchContStr = matchContArr[(matchContArr.length)-1];
					var matchContStrArr = matchContStr.split('&nbsp;');
					$('searchCSZ').value = matchContStrArr[0];
					var re = new RegExp("<span style='display:none;'>([a-zA-Z0-9_]+)<\/span>");
					var m = re.exec(matchContStrArr[1]);
					if (m != null){if($('selVal')){$('selVal').value=m[1];}}
				}
			}			
		}
		//subscribe your handler to the event, assuming
		//you have an AutoComplete instance myAC:
		oAC.itemSelectEvent.subscribe(itemSelectHandler);
		oAC.textboxBlurEvent.subscribe(dataReturnEventon);
	}();	
}

function openEmailAlertBox(divId)
{	
	var moreOptDivObj = $(divId);
	var width = moreOptDivObj.style.width;
	width = parseInt(width);	
	if(width == 100)
		expandMoreOpt(divId);
	else
		collapseMoreOpt(divId);
}
function expandMoreOpt(divId)
{  
   var divObj = $(divId);  
   if($(divId+'Text'))$(divId+'Text').style.display = 'none';
   if(widthMoreOpt != maxMoreOpt)
   {
     widthMoreOpt+=10;
     divObj.style.width = widthMoreOpt+'px';	
     window.setTimeout("expandMoreOpt('"+divId+"');", 1);
   }
   divObj.style.display="";
   if(widthMoreOpt == maxMoreOpt)
   {
	 if($(divId+"Img"))$(divId+"Img").src = "/wt/"+bkTheme+"/images/landing/close.png";
	 if($(divId+'Save'))$(divId+'Save').style.display = '';
   }
}

function collapseMoreOpt(divId)
{
   var divObj = $(divId);
   widthMoreOpt = divObj.style.width;
   widthMoreOpt = parseInt(widthMoreOpt);
   if($(divId+'Save'))$(divId+'Save').style.display = 'none';
   if(widthMoreOpt > 100)
   {
     widthMoreOpt-=10;
     divObj.style.width = parseInt(widthMoreOpt)+'px';	
     window.setTimeout("collapseMoreOpt('"+divId+"');", 1);
   }
   divObj.style.display="";
   if(widthMoreOpt == 100) 
   {
	   if($(divId+"Img"))$(divId+"Img").src = "/wt/"+bkTheme+"/images/landing/plus.png";
	   if($(divId+'Text'))$(divId+'Text').style.display = '';
   }
}
function openAlertBox(divId)
{
	$(divId).style.width = maxMoreOpt+'px';
	if($(divId+'Save'))$(divId+'Save').style.display = '';
	if($(divId+'Text'))$(divId+'Text').style.display = 'none';
	if($(divId+"Img"))$(divId+"Img").src = "/wt/"+bkTheme+"/images/landing/close.png";
}

function loadCommunityVideo()
{
	if($('videoObjDiv'))
	{
		var valueVar = '';
		valueVar = trim($F('cmbVideo'));

		var objHtml = '<object width="290" height="220">';																
		objHtml = objHtml + '<param name="movie" value="'+valueVar+'"></param>';
		objHtml = objHtml + '<param name="allowFullScreen" value="true"></param>';
		objHtml = objHtml + '<param name="wmode" value="transparent"></param>';
		objHtml = objHtml + '<param name="allowscriptaccess" value="always"></param>';
		objHtml = objHtml + '<embed src="'+valueVar+'" wmode="transparent" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="290" height="220"></embed>';
		objHtml = objHtml + '</object>';
		
		$('videoObjDiv').innerHTML = objHtml;
	}
}

/*../vendor/carousel/lib/effects.js*/

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';
  if (this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if (this.slice(0,1) == '#') {  
      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if (this.length==7) color = this.toLowerCase();  
    }  
  }  
  return (color.length==7 ? color : (arguments[0] || this));  
};

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

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if (Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
};

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
};

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

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

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  Transitions: {
    linear: Prototype.K,
    sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + 0.5;
    },
    reverse: function(pos) {
      return 1-pos;
    },
    flicker: function(pos) {
      var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
      return pos > 1 ? 1 : pos;
    },
    wobble: function(pos) {
      return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
    },
    pulse: function(pos, pulses) { 
      pulses = pulses || 5; 
      return (
        ((pos % (1/pulses)) * pulses).round() == 0 ? 
              ((pos * pulses * 2) - (pos * pulses * 2).floor()) : 
          1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
        );
    },
    spring: function(pos) { 
      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); 
    },
    none: function(pos) {
      return 0;
    },
    full: function(pos) {
      return 1;
    }
  },
  DefaultOptions: {
    duration:   1.0,   // seconds
    fps:        100,   // 100= assume 66fps max.
    sync:       false, // true for combining
    from:       0.0,
    to:         1.0,
    delay:      0.0,
    queue:      'parallel'
  },
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if (child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            new Element('span', {style: tagifyStyle}).update(
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if (((typeof element == 'object') || 
        Object.isFunction(element)) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || { });
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || { });
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create(Enumerable, {
  initialize: function() {
    this.effects  = [];
    this.interval = null;    
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = Object.isString(effect.options.queue) ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if (!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if (this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++) 
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if (!Object.isString(queueName)) return queueName;
    
    return this.instances.get(queueName) ||
      this.instances.set(queueName, new Effect.ScopedQueue());
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.Base = Class.create({
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;
    
    eval('this.render = function(pos){ '+
      'if (this.state=="idle"){this.state="running";'+
      codeForEvent(this.options,'beforeSetup')+
      (this.setup ? 'this.setup();':'')+ 
      codeForEvent(this.options,'afterSetup')+
      '};if (this.state=="running"){'+
      'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
      'this.position=pos;'+
      codeForEvent(this.options,'beforeUpdate')+
      (this.update ? 'this.update(pos);':'')+
      codeForEvent(this.options,'afterUpdate')+
      '}}');
    
    this.event('beforeStart');
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if (timePos >= this.startOn) {
      if (timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if (this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = (pos * this.totalFrames).round();
      if (frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if (this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if (!Object.isFunction(this[property])) data.set(property, this[property]);
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
});

Effect.Parallel = Class.create(Effect.Base, {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if (effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Tween = Class.create(Effect.Base, {
  initialize: function(object, from, to) {
    object = Object.isString(object) ? $(object) : object;
    var args = $A(arguments), method = args.last(), 
      options = args.length == 5 ? args[3] : null;
    this.method = Object.isFunction(method) ? method.bind(object) :
      Object.isFunction(object[method]) ? object[method].bind(object) : 
      function(value) { object[method] = value };
    this.start(Object.extend({ from: from, to: to }, options || { }));
  },
  update: function(position) {
    this.method(position);
  }
});

Effect.Event = Class.create(Effect.Base, {
  initialize: function() {
    this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    // make this work on IE on elements without 'layout'
    if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || { });
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if (this.options.mode == 'absolute') {
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: (this.options.x  * position + this.originalLeft).round() + 'px',
      top:  (this.options.y  * position + this.originalTop).round()  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};

Effect.Scale = Class.create(Effect.Base, {
  initialize: function(element, percent) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || { });
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = { };
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if (fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if (this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if (/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if (!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if (this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = { };
    if (this.options.scaleX) d.width = width.round() + 'px';
    if (this.options.scaleY) d.height = height.round() + 'px';
    if (this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if (this.elementPositioning == 'absolute') {
        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if (this.options.scaleY) d.top = -topd + 'px';
        if (this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if (this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = { };
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if (!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if (!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
    scrollOffsets = document.viewport.getScrollOffsets(),
    elementOffsets = $(element).cumulativeOffset(),
    max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();  

  if (options.offset) elementOffsets[1] += options.offset;

  return new Effect.Tween(null,
    scrollOffsets.top,
    elementOffsets[1] > max ? max : elementOffsets[1],
    options,
    function(p){ scrollTo(scrollOffsets.left, p.round()) }
  );
};

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
    from: element.getOpacity() || 1.0,
    to:   0.0,
    afterFinishInternal: function(effect) { 
      if (effect.options.to!=0) return;
      effect.element.hide().setStyle({opacity: oldOpacity}); 
    }
  }, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show(); 
  }}, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element)
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || { })
   );
};

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || { })
  );
};

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      })
    }
  }, arguments[1] || { }));
};

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        } 
      }, arguments[1] || { }));
};

Effect.Shake = function(element) {
  element = $(element);
  var options = Object.extend({
    distance: 20,
    duration: 0.5
  }, arguments[1] || {});
  var distance = parseFloat(options.distance);
  var split = parseFloat(options.duration) / 10.0;
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element,
      { x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
};

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || { })
  );
};

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
    }
   }, arguments[1] || { })
  );
};

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, { 
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping(); 
    }
  });
};

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
};

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping(); 
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
};

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || { };
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
};

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || { }));
};

Effect.Morph = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: { }
    }, arguments[1] || { });
    
    if (!Object.isString(options.style)) this.style = $H(options.style);
    else {
      if (options.style.include(':'))
        this.style = options.style.parseStyle();
      else {
        this.element.addClassName(options.style);
        this.style = $H(this.element.getStyles());
        this.element.removeClassName(options.style);
        var css = this.element.getStyles();
        this.style = this.style.reject(function(style) {
          return style.value == css[style.key];
        });
        options.afterFinishInternal = function(effect) {
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            effect.element.style[transform.style] = '';
          });
        }
      }
    }
    this.start(options);
  },
  
  setup: function(){
    function parseColor(color){
      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if (value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if (property == 'opacity') {
        value = parseFloat(value);
        if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if (Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return { 
        style: property.camelize(), 
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      )
    });
  },
  update: function(position) {
    var style = { }, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] = 
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        (transform.originalValue +
          (transform.targetValue - transform.originalValue) * position).toFixed(3) + 
            (transform.unit === null ? '' : transform.unit);
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create({
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || { };
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      track = $H(track);
      var data = track.values().first();
      this.tracks.push($H({
        ids:     track.keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
        var elements = [$(ids) || $$(ids)].flatten();
        return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');
  
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
  var style, styleRules = $H();
  if (Prototype.Browser.WebKit)
    style = new Element('div',{style:this}).style;
  else {
    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
    style = String.__parseStyleElement.childNodes[0].style;
  }
  
  Element.CSS_PROPERTIES.each(function(property){
    if (style[property]) styleRules.set(property, style[property]); 
  });
  
  if (Prototype.Browser.IE && this.include('opacity'))
    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);

  return styleRules;
};

if (document.defaultView && document.defaultView.getComputedStyle) {
  Element.getStyles = function(element) {
    var css = document.defaultView.getComputedStyle($(element), null);
    return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
      styles[property] = css[property];
      return styles;
    });
  };
} else {
  Element.getStyles = function(element) {
    element = $(element);
    var css = element.currentStyle, styles;
    styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) {
      hash.set(property, css[property]);
      return hash;
    });
    if (!styles.opacity) styles.set('opacity', element.getOpacity());
    return styles;
  };
};

Effect.Methods = {
  morph: function(element, style) {
    element = $(element);
    new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
    return element;
  },
  visualEffect: function(element, effect, options) {
    element = $(element)
    var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
    new Effect[klass](element, options);
    return element;
  },
  highlight: function(element, options) {
    element = $(element);
    new Effect.Highlight(element, options);
    return element;
  }
};

$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
  'pulsate shake puff squish switchOff dropOut').each(
  function(effect) { 
    Effect.Methods[effect] = function(element, options){
      element = $(element);
      Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
      return element;
    }
  }
);

$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( 
  function(f) { Effect.Methods[f] = Element[f]; }
);

Element.addMethods(Effect.Methods);


/*../vendor/carousel/dist/carousel.js*/

/*  Prototype-UI, version trunk
 *
 *  Prototype-UI is freely distributable under the terms of an MIT-style license.
 *  For details, see the PrototypeUI web site: http://www.prototype-ui.com/
 *
 *--------------------------------------------------------------------------*/

if(typeof Prototype == 'undefined' || !Prototype.Version.match("1.6"))
  throw("Prototype-UI library require Prototype library >= 1.6.0");

if (Prototype.Browser.WebKit) {
  Prototype.Browser.WebKitVersion = parseFloat(navigator.userAgent.match(/AppleWebKit\/([\d\.\+]*)/)[1]);
  Prototype.Browser.Safari2 = (Prototype.Browser.WebKitVersion < 420);
}

if (Prototype.Browser.IE) {
  Prototype.Browser.IEVersion = parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]);
  Prototype.Browser.IE6 =  Prototype.Browser.IEVersion == 6;
  Prototype.Browser.IE7 =  Prototype.Browser.IEVersion == 7;
}

Prototype.falseFunction = function() { return false };
Prototype.trueFunction  = function() { return true  };

/*
Namespace: UI

  Introduction:
    Prototype-UI is a library of user interface components based on the Prototype framework.
    Its aim is to easilly improve user experience in web applications.

    It also provides utilities to help developers.

  Guideline:
    - Prototype conventions are followed
    - Everything should be unobstrusive
    - All components are themable with CSS stylesheets, various themes are provided

  Warning:
    Prototype-UI is still under deep development, this release is targeted to developers only.
    All interfaces are subjects to changes, suggestions are welcome.

    DO NOT use it in production for now.

  Authors:
    - Sébastien Gruhier, <http://www.xilinus.com>
    - Samuel Lebeau, <http://gotfresh.info>
*/

var UI = {
  Abstract: { },
  Ajax: { }
};
Object.extend(Class.Methods, {
  extend: Object.extend.methodize(),

  addMethods: Class.Methods.addMethods.wrap(function(proceed, source) {
    // ensure we are not trying to add null or undefined
    if (!source) return this;

    // no callback, vanilla way
    if (!source.hasOwnProperty('methodsAdded'))
      return proceed(source);

    var callback = source.methodsAdded;
    delete source.methodsAdded;
    proceed(source);
    callback.call(source, this);
    source.methodsAdded = callback;

    return this;
  }),

  addMethod: function(name, lambda) {
    var methods = {};
    methods[name] = lambda;
    return this.addMethods(methods);
  },

  method: function(name) {
    return this.prototype[name].valueOf();
  },

  classMethod: function() {
    $A(arguments).flatten().each(function(method) {
      this[method] = (function() {
        return this[method].apply(this, arguments);
      }).bind(this.prototype);
    }, this);
    return this;
  },

  // prevent any call to this method
  undefMethod: function(name) {
    this.prototype[name] = undefined;
    return this;
  },

  // remove the class' own implementation of this method
  removeMethod: function(name) {
    delete this.prototype[name];
    return this;
  },

  aliasMethod: function(newName, name) {
    this.prototype[newName] = this.prototype[name];
    return this;
  },

  aliasMethodChain: function(target, feature) {
    feature = feature.camelcase();

    this.aliasMethod(target+"Without"+feature, target);
    this.aliasMethod(target, target+"With"+feature);

    return this;
  }
});
Object.extend(Number.prototype, {
  // Snap a number to a grid
  snap: function(round) {
    return parseInt(round == 1 ? this : (this / round).floor() * round);
  }
});
/*
Interface: String

*/

Object.extend(String.prototype, {
  camelcase: function() {
    var string = this.dasherize().camelize();
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  /*
    Method: makeElement
      toElement is unfortunately already taken :/

      Transforms html string into an extended element or null (when failed)

      > '<li><a href="#">some text</a></li>'.makeElement(); // => LI href#
      > '<img src="foo" id="bar" /><img src="bar" id="bar" />'.makeElement(); // => IMG#foo (first one)

    Returns:
      Extended element

  */
  makeElement: function() {
    var wrapper = new Element('div'); wrapper.innerHTML = this;
    return wrapper.down();
  }
});
Object.extend(Array.prototype, {
  empty: function() {
    return !this.length;
  },

  extractOptions: function() {
    return this.last().constructor === Object ? this.pop() : { };
  },

  removeAt: function(index) {
    var object = this[index];
    this.splice(index, 1);
    return object;
  },

  remove: function(object) {
    var index;
    while ((index = this.indexOf(object)) != -1)
      this.removeAt(index);
    return object;
  },

  insert: function(index) {
    var args = $A(arguments);
    args.shift();
    this.splice.apply(this, [ index, 0 ].concat(args));
    return this;
  }
});
Element.addMethods({
  getScrollDimensions: function(element) {
    return {
      width:  element.scrollWidth,
      height: element.scrollHeight
    }
  },

  getScrollOffset: function(element) {
    return Element._returnOffset(element.scrollLeft, element.scrollTop);
  },

  setScrollOffset: function(element, offset) {
    element = $(element);
    if (arguments.length == 3)
      offset = { left: offset, top: arguments[2] };
    element.scrollLeft = offset.left;
    element.scrollTop  = offset.top;
    return element;
  },

  // returns "clean" numerical style (without "px") or null if style can not be resolved
  // or is not numeric
  getNumStyle: function(element, style) {
    var value = parseFloat($(element).getStyle(style));
    return isNaN(value) ? null : value;
  },

  // by Tobie Langel (http://tobielangel.com/2007/5/22/prototype-quick-tip)
  appendText: function(element, text) {
    element = $(element);
    text = String.interpret(text);
    element.appendChild(document.createTextNode(text));
    return element;
  }
});

document.whenReady = function(callback) {
  if (document.loaded)
    callback.call(document);
  else
    document.observe('dom:loaded', callback);
};

Object.extend(document.viewport, {
  // Alias this method for consistency
  getScrollOffset: document.viewport.getScrollOffsets,

  setScrollOffset: function(offset) {
    Element.setScrollOffset(Prototype.Browser.WebKit ? document.body : document.documentElement, offset);
  },

  getScrollDimensions: function() {
    return Element.getScrollDimensions(Prototype.Browser.WebKit ? document.body : document.documentElement);
  }
});
/*
Interface: UI.Options
  Mixin to handle *options* argument in initializer pattern.

  TODO: find a better example than Circle that use an imaginary Point function,
        this example should be used in tests too.

  It assumes class defines a property called *options*, containing
  default options values.

  Instances hold their own *options* property after a first call to <setOptions>.

  Example:
    > var Circle = Class.create(UI.Options, {
    >
    >   // default options
    >   options: {
    >     radius: 1,
    >     origin: Point(0, 0)
    >   },
    >
    >   // common usage is to call setOptions in initializer
    >   initialize: function(options) {
    >     this.setOptions(options);
    >   }
    > });
    >
    > var circle = new Circle({ origin: Point(1, 4) });
    >
    > circle.options
    > // => { radius: 1, origin: Point(1,4) }

  Accessors:
    There are builtin methods to automatically write options accessors. All those
    methods can take either an array of option names nor option names as arguments.
    Notice that those methods won't override an accessor method if already present.

     * <optionsGetter> creates getters
     * <optionsSetter> creates setters
     * <optionsAccessor> creates both getters and setters

    Common usage is to invoke them on a class to create accessors for all instances
    of this class.
    Invoking those methods on a class has the same effect as invoking them on the class prototype.
    See <classMethod> for more details.

    Example:
    > // Creates getter and setter for the "radius" options of circles
    > Circle.optionsAccessor('radius');
    >
    > circle.setRadius(4);
    > // 4
    >
    > circle.getRadius();
    > // => 4 (circle.options.radius)

  Inheritance support:
    Subclasses can refine default *options* values, after a first instance call on setOptions,
    *options* attribute will hold all default options values coming from the inheritance hierarchy.
*/

(function() {
  UI.Options = {
    methodsAdded: function(klass) {
      klass.classMethod($w(' setOptions allOptions optionsGetter optionsSetter optionsAccessor '));
    },

    // Group: Methods

    /*
      Method: setOptions
        Extends object's *options* property with the given object
    */
    setOptions: function(options) {
      if (!this.hasOwnProperty('options'))
        this.options = this.allOptions();

      this.options = Object.extend(this.options, options || {});
    },

    /*
      Method: allOptions
        Computes the complete default options hash made by reverse extending all superclasses
        default options.

        > Widget.prototype.allOptions();
    */
    allOptions: function() {
      var superclass = this.constructor.superclass, ancestor = superclass && superclass.prototype;
      return (ancestor && ancestor.allOptions) ?
          Object.extend(ancestor.allOptions(), this.options) :
          Object.clone(this.options);
    },

    /*
      Method: optionsGetter
        Creates default getters for option names given as arguments.
        With no argument, creates getters for all option names.
    */
    optionsGetter: function() {
      addOptionsAccessors(this, arguments, false);
    },

    /*
      Method: optionsSetter
        Creates default setters for option names given as arguments.
        With no argument, creates setters for all option names.
    */
    optionsSetter: function() {
      addOptionsAccessors(this, arguments, true);
    },

    /*
      Method: optionsAccessor
        Creates default getters/setters for option names given as arguments.
        With no argument, creates accessors for all option names.
    */
    optionsAccessor: function() {
      this.optionsGetter.apply(this, arguments);
      this.optionsSetter.apply(this, arguments);
    }
  };

  // Internal
  function addOptionsAccessors(receiver, names, areSetters) {
    names = $A(names).flatten();

    if (names.empty())
      names = Object.keys(receiver.allOptions());

    names.each(function(name) {
      var accessorName = (areSetters ? 'set' : 'get') + name.camelcase();

      receiver[accessorName] = receiver[accessorName] || (areSetters ?
        // Setter
        function(value) { return this.options[name] = value } :
        // Getter
        function()      { return this.options[name]         });
    });
  }
})();
/*
  Class: UI.Carousel

  Main class to handle a carousel of elements in a page. A carousel :
    * could be vertical or horizontal
    * works with liquid layout
    * is designed by CSS

  Assumptions:
    * Elements should be from the same size

  Example:
    > ...
    > <div id="horizontal_carousel">
    >   <div class="previous_button"></div>
    >   <div class="container">
    >     <ul>
    >       <li> What ever you like</li>
    >     </ul>
    >   </div>
    >   <div class="next_button"></div>
    > </div>
    > <script>
    > new UI.Carousel("horizontal_carousel");
    > </script>
    > ...
*/
UI.Carousel = Class.create(UI.Options, {
  // Group: Options
  options: {
	// Property: direction
	//   Can be horizontal or vertical, horizontal by default
    direction               : "horizontal",

    // Property: previousButton
    //   Selector of previous button inside carousel element, ".previous_button" by default,
    //   set it to false to ignore previous button
    previousButton          : ".previous_button",

    // Property: nextButton
    //   Selector of next button inside carousel element, ".next_button" by default,
    //   set it to false to ignore next button
    nextButton              : ".next_button",

    // Property: container
    //   Selector of carousel container inside carousel element, ".container" by default,
    container               : ".container",

    // Property: scrollInc
    //   Define the maximum number of elements that gonna scroll each time, auto by default
    scrollInc               : "auto",

    // Property: disabledButtonSuffix
    //   Define the suffix classanme used when a button get disabled, to '_disabled' by default
    //   Previous button classname will be previous_button_disabled
    disabledButtonSuffix : '_disabled',

    // Property: overButtonSuffix
    //   Define the suffix classanme used when a button has a rollover status, '_over' by default
    //   Previous button classname will be previous_button_over
    overButtonSuffix : '_over',

	opacity : '1.0'
  },

  /*
    Group: Attributes

      Property: element
        DOM element containing the carousel

      Property: id
        DOM id of the carousel's element

      Property: container
        DOM element containing the carousel's elements

      Property: elements
        Array containing the carousel's elements as DOM elements

      Property: previousButton
        DOM id of the previous button

      Property: nextButton
        DOM id of the next button

      Property: posAttribute
        Define if the positions are from left or top

      Property: dimAttribute
        Define if the dimensions are horizontal or vertical

      Property: elementSize
        Size of each element, it's an integer

      Property: nbVisible
        Number of visible elements, it's a float

      Property: animating
        Define whether the carousel is in animation or not
  */

  /*
    Group: Events
      List of events fired by a carousel

      Notice: Carousel custom events are automatically namespaced in "carousel:" (see Prototype custom events).

      Examples:
        This example will observe all carousels
        > document.observe('carousel:scroll:ended', function(event) {
        >   alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled");
        > });

        This example will observe only this carousel
        > new UI.Carousel('horizontal_carousel').observe('scroll:ended', function(event) {
        >   alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled");
        > });

      Property: previousButton:enabled
        Fired when the previous button has just been enabled

      Property: previousButton:disabled
        Fired when the previous button has just been disabled

      Property: nextButton:enabled
        Fired when the next button has just been enabled

      Property: nextButton:disabled
        Fired when the next button has just been disabled

      Property: scroll:started
        Fired when a scroll has just started

      Property: scroll:ended
        Fired when a scroll has been done,
        memo.shift = number of elements scrolled, it's a float

      Property: sizeUpdated
        Fired when the carousel size has just been updated.
        Tips: memo.carousel.currentSize() = the new carousel size
  */

  // Group: Constructor

  /*
    Method: initialize
      Constructor function, should not be called directly

    Parameters:
      element - DOM element
      options - (Hash) list of optional parameters

    Returns:
      this
  */
  initialize: function(element, options) {
    this.setOptions(options);
    this.element = $(element);
    this.id = this.element.id;
    this.container   = this.element.down(this.options.container).firstDescendant();
    this.elements    = this.container.childElements();
    this.previousButton = this.options.previousButton == false ? null : this.element.down(this.options.previousButton);
    this.nextButton = this.options.nextButton == false ? null : this.element.down(this.options.nextButton);

    this.posAttribute = (this.options.direction == "horizontal" ? "left" : "top");
    this.dimAttribute = (this.options.direction == "horizontal" ? "width" : "height");

    this.elementSize = this.computeElementSize();
    this.nbVisible = this.currentSize() / this.elementSize;

    var scrollInc = this.options.scrollInc;
    if (scrollInc == "auto")
      scrollInc = Math.floor(this.nbVisible);
    [ this.previousButton, this.nextButton ].each(function(button) {
      if (!button) return;
      var className = (button == this.nextButton ? "next_button" : "previous_button") + this.options.overButtonSuffix;
      button.clickHandler = this.scroll.bind(this, (button == this.nextButton ? -1 : 1) * scrollInc * this.elementSize);
      button.observe("click", button.clickHandler)
            .observe("mouseover", function() {button.addClassName(className)}.bind(this))
            .observe("mouseout",  function() {button.removeClassName(className)}.bind(this));
    }, this);
    this.updateButtons();
  },

  // Group: Destructor

  /*
    Method: destroy
      Cleans up DOM and memory
  */
  destroy: function($super) {
    [ this.previousButton, this.nextButton ].each(function(button) {
      if (!button) return;
        button.stopObserving("click", button.clickHandler);
    }, this);
	  this.element.remove();
	  this.fire('destroyed');
  },

  // Group: Event handling

  /*
    Method: fire
      Fires a carousel custom event automatically namespaced in "carousel:" (see Prototype custom events).
      The memo object contains a "carousel" property referring to the carousel.

    Example:
      > document.observe('carousel:scroll:ended', function(event) {
      >   alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled");
      > });

    Parameters:
      eventName - an event name
      memo      - a memo object

    Returns:
      fired event
  */
  fire: function(eventName, memo) {
    memo = memo || { };
    memo.carousel = this;
    return this.element.fire('carousel:' + eventName, memo);
  },

  /*
    Method: observe
      Observe a carousel event with a handler function automatically bound to the carousel

    Parameters:
      eventName - an event name
      handler   - a handler function

    Returns:
      this
  */
  observe: function(eventName, handler) {
    this.element.observe('carousel:' + eventName, handler.bind(this));
    return this;
  },

  /*
    Method: stopObserving
      Unregisters a carousel event, it must take the same parameters as this.observe (see Prototype stopObserving).

    Parameters:
      eventName - an event name
      handler   - a handler function

    Returns:
      this
  */
  stopObserving: function(eventName, handler) {
	  this.element.stopObserving('carousel:' + eventName, handler);
	  return this;
  },

  // Group: Actions

  /*
    Method: checkScroll
      Check scroll position to avoid unused space at right or bottom

    Parameters:
      position       - position to check
      updatePosition - should the container position be updated ? true/false

    Returns:
      position
  */
  checkScroll: function(position, updatePosition) {
    if (position > 0)
      position = 0;
    else {
      var limit = this.elements.last().positionedOffset()[this.posAttribute] + this.elementSize;
      var carouselSize = this.currentSize();

      if (position + limit < carouselSize)
        position += carouselSize - (position + limit);
      position = Math.min(position, 0);
    }
    if (updatePosition)
      this.container.style[this.posAttribute] = position + "px";

    return position;
  },

  /*
    Method: scroll
      Scrolls carousel from maximum deltaPixel

    Parameters:
      deltaPixel - a float

    Returns:
      this
  */
  scroll: function(deltaPixel) {
    if (this.animating)
      return this;

    // Compute new position
    var position =  this.currentPosition() + deltaPixel;

    // Check bounds
    position = this.checkScroll(position, false);

    // Compute shift to apply
    deltaPixel = position - this.currentPosition();
    if (deltaPixel != 0) {
      this.animating = true;
      this.fire("scroll:started");

      var that = this;
      // Move effects
      this.container.morph("opacity:" + this.options.opacity, {duration: 0.2, afterFinish: function() {
        that.container.morph(that.posAttribute + ": " + position + "px", {
          duration: 0.4,
          delay: 0.2,
          afterFinish: function() {
            that.container.morph("opacity:1", {
              duration: 0.2,
              afterFinish: function() {
                that.animating = false;
                that.updateButtons()
                  .fire("scroll:ended", { shift: deltaPixel / that.currentSize() });
              }
            });
          }
        });
      }});
    }
    return this;
  },

  /*
    Method: scrollTo
      Scrolls carousel, so that element with specified index is the left-most.
      This method is convenient when using carousel in a tabbed navigation.
      Clicking on first tab should scroll first container into view, clicking on a fifth - fifth one, etc.
      Indexing starts with 0.

    Parameters:
      Index of an element which will be a left-most visible in the carousel

    Returns:
      this
  */
  scrollTo: function(index) {
    if (this.animating || index < 0 || index > this.elements.length || index == this.currentIndex() || isNaN(parseInt(index)))
      return this;
    return this.scroll((this.currentIndex() - index) * this.elementSize);
  },

  /*
    Method: updateButtons
      Update buttons status to enabled or disabled
      Them status is defined by classNames and fired as carousel's custom events

    Returns:
      this
  */
  updateButtons: function() {
	  this.updatePreviousButton();
    this.updateNextButton();
    return this;
  },

  updatePreviousButton: function() {
    var position = this.currentPosition();
    var previousClassName = "previous_button" + this.options.disabledButtonSuffix;

    if (this.previousButton.hasClassName(previousClassName) && position != 0) {
      this.previousButton.removeClassName(previousClassName);
      this.fire('previousButton:enabled');
    }
    if (!this.previousButton.hasClassName(previousClassName) && position == 0) {
	    this.previousButton.addClassName(previousClassName);
      this.fire('previousButton:disabled');
    }
  },

  updateNextButton: function() {
    var lastPosition = this.currentLastPosition();
    var size = this.currentSize();
    var nextClassName = "next_button" + this.options.disabledButtonSuffix;

    if (this.nextButton.hasClassName(nextClassName) && lastPosition != size) {
      this.nextButton.removeClassName(nextClassName);
      this.fire('nextButton:enabled');
    }
    if (!this.nextButton.hasClassName(nextClassName) && lastPosition == size) {
	    this.nextButton.addClassName(nextClassName);
      this.fire('nextButton:disabled');
    }
  },

  // Group: Size and Position

  /*
    Method: computeElementSize
      Return elements size in pixel, height or width depends on carousel orientation.

    Returns:
      an integer value
  */
  computeElementSize: function() {
    return this.elements.first().getDimensions()[this.dimAttribute];
  },

  /*
    Method: currentIndex
      Returns current visible index of a carousel.
      For example, a horizontal carousel with image #3 on left will return 3 and with half of image #3 will return 3.5
      Don't forget that the first image have an index 0

    Returns:
      a float value
  */
  currentIndex: function() {
    return - this.currentPosition() / this.elementSize;
  },

  /*
    Method: currentLastPosition
      Returns the current position from the end of the last element. This value is in pixel.

    Returns:
      an integer value, if no images a present it will return 0
  */
  currentLastPosition: function() {
    if (this.container.childElements().empty())
      return 0;
    return this.currentPosition() +
           this.elements.last().positionedOffset()[this.posAttribute] +
           this.elementSize;
  },

  /*
    Method: currentPosition
      Returns the current position in pixel.
      Tips: To get the position in elements use currentIndex()

    Returns:
      an integer value
  */
  currentPosition: function() {
    return this.container.getNumStyle(this.posAttribute);
  },

  /*
    Method: currentSize
      Returns the current size of the carousel in pixel

    Returns:
      Carousel's size in pixel
  */
  currentSize: function() {
    return this.container.parentNode.getDimensions()[this.dimAttribute];
  },

  /*
    Method: updateSize
      Should be called if carousel size has been changed (usually called with a liquid layout)

    Returns:
      this
  */
  updateSize: function() {
    this.nbVisible = this.currentSize() / this.elementSize;
    var scrollInc = this.options.scrollInc;
    if (scrollInc == "auto")
      scrollInc = Math.floor(this.nbVisible);

    [ this.previousButton, this.nextButton ].each(function(button) {
      if (!button) return;
      button.stopObserving("click", button.clickHandler);
      button.clickHandler = this.scroll.bind(this, (button == this.nextButton ? -1 : 1) * scrollInc * this.elementSize);
      button.observe("click", button.clickHandler);
    }, this);

    this.checkScroll(this.currentPosition(), true);
    this.updateButtons().fire('sizeUpdated');
    return this;
  }
});
/*
  Class: UI.Ajax.Carousel

  Gives the AJAX power to carousels. An AJAX carousel :
    * Use AJAX to add new elements on the fly

  Example:
    > new UI.Ajax.Carousel("horizontal_carousel",
    >   {url: "get-more-elements", elementSize: 250});
*/
UI.Ajax.Carousel = Class.create(UI.Carousel, {
  // Group: Options
  //
  //   Notice:
  //     It also include of all carousel's options
  options: {
	// Property: elementSize
	//   Required, it define the size of all elements
    elementSize : -1,

	// Property: url
	//   Required, it define the URL used by AJAX carousel to request new elements details
    url         : null
  },

  /*
    Group: Attributes

      Notice:
        It also include of all carousel's attributes

      Property: elementSize
        Size of each elements, it's an integer

      Property: endIndex
        Index of the last loaded element

      Property: hasMore
        Flag to define if there's still more elements to load

      Property: requestRunning
        Define whether a request is processing or not

      Property: updateHandler
        Callback to update carousel, usually used after request success

      Property: url
        URL used to request additional elements
  */

  /*
    Group: Events
      List of events fired by an AJAX carousel, it also include of all carousel's custom events

      Property: request:started
        Fired when the request has just started

      Property: request:ended
        Fired when the request has succeed
  */

  // Group: Constructor

  /*
    Method: initialize
      Constructor function, should not be called directly

    Parameters:
      element - DOM element
      options - (Hash) list of optional parameters

    Returns:
      this
  */
  initialize: function($super, element, options) {
    if (!options.url)
      throw("url option is required for UI.Ajax.Carousel");
    if (!options.elementSize)
      throw("elementSize option is required for UI.Ajax.Carousel");

    $super(element, options);

    this.endIndex = 0;
    this.hasMore  = true;

    // Cache handlers
    this.updateHandler = this.update.bind(this);
    this.updateAndScrollHandler = function(nbElements, transport, json) {
	    this.update(transport, json);
	    this.scroll(nbElements);
	  }.bind(this);

    // Run first ajax request to fill the carousel
    this.runRequest.bind(this).defer({parameters: {from: 0, to: Math.ceil(this.nbVisible) - 1}, onSuccess: this.updateHandler});
  },

  // Group: Actions

  /*
    Method: runRequest
      Request the new elements details

    Parameters:
      options - (Hash) list of optional parameters

    Returns:
      this
  */
  runRequest: function(options) {
    this.requestRunning = true;
    new Ajax.Request(this.options.url, Object.extend({method: "GET"}, options));
    this.fire("request:started");
    return this;
  },

  /*
    Method: scroll
      Scrolls carousel from maximum deltaPixel

    Parameters:
      deltaPixel - a float

    Returns:
      this
  */
  scroll: function($super, deltaPixel) {
    if (this.animating || this.requestRunning)
      return this;

    var nbElements = (-deltaPixel) / this.elementSize;
    // Check if there is not enough
    if (this.hasMore && nbElements > 0 && this.currentIndex() + this.nbVisible + nbElements - 1 > this.endIndex) {
      var from = this.endIndex + 1;
      var to   = Math.ceil(from + this.nbVisible - 1);
      this.runRequest({parameters: {from: from, to: to}, onSuccess: this.updateAndScrollHandler.curry(deltaPixel).bind(this)});
      return this;
    }
    else
      $super(deltaPixel);
  },

  /*
    Method: update
      Update the carousel

    Parameters:
      transport - XMLHttpRequest object
      json      - JSON object

    Returns:
      this
  */
  update: function(transport, json) {
    this.requestRunning = false;
    this.fire("request:ended");
    if (!json)
      json = transport.responseJSON;
    this.hasMore = json.more;

    this.endIndex = Math.max(this.endIndex, json.to);
    this.elements = this.container.insert({bottom: json.html}).childElements();
    return this.updateButtons();
  },

  // Group: Size and Position

  /*
    Method: computeElementSize
      Return elements size in pixel

    Returns:
      an integer value
  */
  computeElementSize: function() {
    return this.options.elementSize;
  },

  /*
    Method: updateSize
      Should be called if carousel size has been changed (usually called with a liquid layout)

    Returns:
      this
  */
  updateSize: function($super) {
    var nbVisible = this.nbVisible;
    $super();
    // If we have enough space for at least a new element
    if (Math.floor(this.nbVisible) - Math.floor(nbVisible) >= 1 && this.hasMore) {
      if (this.currentIndex() + Math.floor(this.nbVisible) >= this.endIndex) {
        var nbNew = Math.floor(this.currentIndex() + Math.floor(this.nbVisible) - this.endIndex);
        this.runRequest({parameters: {from: this.endIndex + 1, to: this.endIndex + nbNew}, onSuccess: this.updateHandler});
      }
    }
    return this;
  },

  updateNextButton: function($super) {
    var lastPosition = this.currentLastPosition();
    var size = this.currentSize();
    var nextClassName = "next_button" + this.options.disabledButtonSuffix;

    if (this.nextButton.hasClassName(nextClassName) && lastPosition != size) {
      this.nextButton.removeClassName(nextClassName);
      this.fire('nextButton:enabled');
    }
    if (!this.nextButton.hasClassName(nextClassName) && lastPosition == size && !this.hasMore) {
	    this.nextButton.addClassName(nextClassName);
      this.fire('nextButton:disabled');
    }
  }
});
