/* - prototype.js - */
/*  Prototype JavaScript framework, version 1.5.1
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.1',

  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
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      (document.createElement('div').__proto__ !==
       document.createElement('form').__proto__)
  },

  ScriptFragment: '<script[^>]*>([\u0001-\uFFFF]*?)</script>',
  JSONFilter: /^\/\*-secure-\s*(.*)\s*\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  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.ownerDocument === document) return;
    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (value !== undefined)
        results.push(property.toJSON() + ': ' + value);
    }
    return '{' + results.join(', ') + '}';
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
  	if( typeof $A == 'function')
  		return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [event || window.event].concat(args));
  }
}

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';
  }
});

Date.prototype.toJSON = function() {
  return '"' + this.getFullYear() + '-' +
    (this.getMonth() + 1).toPaddedString(2) + '-' +
    this.getDate().toPaddedString(2) + 'T' +
    this.getHours().toPaddedString(2) + ':' +
    this.getMinutes().toPaddedString(2) + ':' +
    this.getSeconds().toPaddedString(2) + '"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
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 = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (hash[key].constructor != Array) 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) {
    var result = '';
    for (var i = 0; i < count; i++) result += this;
    return result;
  },

  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}');
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(json)))
        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);
  }
});

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 (typeof replacement == 'function') 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();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break = {}, $continue = new Error('"throw $continue" is deprecated, use "return" instead');

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

if (Prototype.Browser.WebKit) {
  $A = Array.from = function(iterable) {
    if (!iterable) return [];
    if (!(typeof iterable == 'function' && iterable == '[object NodeList]') &&
      iterable.toArray) {
      return iterable.toArray();
    } else {
      var results = [];
      for (var i = 0, length = iterable.length; i < length; i++)
        results.push(iterable[i]);
      return results;
    }
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  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 (value !== undefined) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  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 (arguments[i].constructor == Array) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(object) {
  if (object instanceof Hash) this.merge(object);
  else Object.extend(this, object || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];
    parts.add = arguments.callee.addPair;

    this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;
      var value = pair.value;

      if (value && typeof value == 'object') {
        if (value.constructor == Array) value.each(function(value) {
          parts.add(pair.key, value);
        });
        return;
      }
      parts.add(pair.key, value);
    });

    return parts.join('&');
  },

  toJSON: function(object) {
    var results = [];
    this.prototype._each.call(object, function(pair) {
      var value = Object.toJSON(pair.value);
      if (value !== undefined) results.push(pair.key.toJSON() + ': ' + value);
    });
    return '{' + results.join(', ') + '}';
  }
});

Hash.toQueryString.addPair = function(key, value, prefix) {
  key = encodeURIComponent(key);
  if (value === undefined) this.push(key);
  else this.push(key + '=' + (value == null ? '' : encodeURIComponent(value)));
}

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  },

  toJSON: function() {
    return Hash.toJSON(this);
  }
});

function $H(object) {
  if (object instanceof Hash) return object;
  return new Hash(object);
};

// Safari iterates over shadowed properties
if (function() {
  var i = 0, Test = function(value) { this.key = value };
  Test.prototype.key = 'foo';
  for (var property in new Test('bar')) i++;
  return i > 1;
}()) Hash.prototype._each = function(iterator) {
  var cache = [];
  for (var key in this) {
    var value = this[key];
    if ((value && value == Hash.prototype[key]) || cache.include(key)) continue;
    cache.push(key);
    var pair = [key, value];
    pair.key = key;
    pair.value = value;
    iterator(pair);
  }
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});

    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    //解决页面中携带BASE导致跨域的问题
    if(this.url.indexOf('http') !=0 && location.href != document.baseURI){
    	this.url = location.protocol+"//"+location.host+this.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 = Hash.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 {
      if (this.options.onCreate) this.options.onCreate(this.transport);
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.body);
	  //this.transport.abort();
      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();
	}
    catch (e) {
      this.dispatchException(e);
    }
  },
  abort:function(){
  	this.transport.abort();
  },
  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = this.getHeader('Content-type');
      if (contentType && contentType.strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? json.evalJSON() : 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.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    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(query.snapshotItem(i));
    return results;
  };

  document.getElementsByClassName = function(className, parentElement) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  }

} else document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  var elements = [], child;
  for (var i = 0, length = children.length; i < length; i++) {
    child = children[i];
    if (Element.hasClassName(child, className))
      elements.push(Element.extend(child));
  }
  return elements;
};

/*--------------------------------------------------------------------------*/

if (!window.Element) var Element = {};

Element.extend = function(element) {
  var F = Prototype.BrowserFeatures;
  if (!element || !element.tagName || element.nodeType == 3 ||
   element._extended || F.SpecificElementExtensions || element == window)
    return element;

  var methods = {}, tagName = element.tagName, cache = Element.extend.cache,
   T = Element.Methods.ByTag;

  // extend methods for all tags (Safari doesn't need this)
  if (!F.ElementExtensions) {
    Object.extend(methods, Element.Methods),
    Object.extend(methods, Element.Methods.Simulated);
  }

  // extend methods for specific tags
  if (T[tagName]) Object.extend(methods, T[tagName]);

  for (var property in methods) {
    var value = methods[property];
    if (typeof value == 'function' && !(property in element))
      element[property] = cache.findOrStore(value);
  }

  element._extended = Prototype.emptyFunction;
  return element;
};

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
};

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,style) {
	if( style == null )
		$(element).style.display = '';
	else 
		$(element).style.display = style;
		return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    html = typeof html == 'undefined' ? '' : html.toString();
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  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 $A($(element).getElementsByTagName('*')).each(Element.extend);
  },

  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 (typeof selector == 'string')
      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 expression ? Selector.findElement(ancestors, expression, index) :
      ancestors[index || 0];
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    var descendants = element.descendants();
    return expression ? Selector.findElement(descendants, expression, index) :
      descendants[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return expression ? Selector.findElement(previousSiblings, expression, index) :
      previousSiblings[index || 0];
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return expression ? Selector.findElement(nextSiblings, expression, index) :
      nextSiblings[index || 0];
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    return document.getElementsByClassName(className, element);
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      if (!element.attributes) return null;
      var t = Element._attributeTranslations;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name])  name = t.names[name];
      var attribute = element.attributes[name];
      return attribute ? attribute.nodeValue : null;
    }
    return element.getAttribute(name);
  },

  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;
    if (elementClassName.length == 0) return false;
    if (elementClassName == className ||
        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      return true;
    return false;
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // 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);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = Position.cumulativeOffset(element);
    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, camelized) {
    element = $(element);
    var elementStyle = element.style;

    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property])
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :
          (camelized ? property : property.camelize())] = 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.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != '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;
  }
};

Object.extend(Element.Methods, {
  childOf: Element.Methods.descendantOf,
  childElements: Element.Methods.immediateDescendants
});

if (Prototype.Browser.Opera) {
  Element.Methods._getStyle = Element.Methods.getStyle;
  Element.Methods.getStyle = function(element, style) {
    switch(style) {
      case 'left':
      case 'top':
      case 'right':
      case 'bottom':
        if (Element._getStyle(element, 'position') == 'static') return null;
      default: return Element._getStyle(element, style);
    }
  };
}
else if (Prototype.Browser.IE) {
  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) {
    element = $(element);
    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      style.filter = filter.replace(/alpha\([^\)]*\)/gi,'');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = filter.replace(/alpha\([^\)]*\)/gi, '') +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  // IE is missing .innerHTML support for TABLE-related elements
  Element.Methods.update = function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      depth.times(function() { div = div.firstChild });
      $A(div.childNodes).each(function(node) { element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() { html.evalScripts() }, 10);
    return element;
  }
}
else if (Prototype.Browser.Gecko) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

Element._attributeTranslations = {
  names: {
    colspan:   "colSpan",
    rowspan:   "rowSpan",
    valign:    "vAlign",
    datetime:  "dateTime",
    accesskey: "accessKey",
    tabindex:  "tabIndex",
    enctype:   "encType",
    maxlength: "maxLength",
    readonly:  "readOnly",
    longdesc:  "longDesc"
  },
  values: {
    _getAttr: function(element, attribute) {
      return element.getAttribute(attribute, 2);
    },
    _flag: function(element, attribute) {
      return $(element).hasAttribute(attribute) ? attribute : null;
    },
    style: function(element) {
      return element.style.cssText.toLowerCase();
    },
    title: function(element) {
      var node = element.getAttributeNode('title');
      return node.specified ? node.nodeValue : null;
    }
  }
};

(function() {
  Object.extend(this, {
    href: this._getAttr,
    src:  this._getAttr,
    type: this._getAttr,
    disabled: this._flag,
    checked:  this._flag,
    readonly: this._flag,
    multiple: this._flag
  });
}).call(Element._attributeTranslations.values);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations, node;
    attribute = t.names[attribute] || attribute;
    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.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 (tagName.constructor == Array) 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;
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  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 (typeof klass == "undefined") continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;
};

var Toggle = { display: Element.toggle };

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

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);
/* 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();

Selector.prototype = {
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  compileMatcher: function() {
    // Selectors with namespaced attributes can't use the XPath version
    if (Prototype.BrowserFeatures.XPath && !(/\[[\w-]*?:/).test(this.expression))
      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(typeof c[i] == 'function' ? 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(typeof x[i] == 'function' ? 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) {
    return this.findElements(document).include(element);
  },

  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: "[@#{1}]",
    attr: function(m) {
      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 (typeof h === 'function') 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, m, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = typeof x[i] == 'function' ? 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 = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); 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|([^'"][^\]]*?)))?\]/
  },

  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) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = 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._counted = true;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._counted)) 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])._counted) {
          n._counted = true;
          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, children = [], 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) {
      tagName = 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() == tagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!nodes && root == document) return targetNode ? [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) {
      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) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      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._counted) {
          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._counted) 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() + '-'); }
  },

  matchElements: function(elements, expression) {
    var matches = new Selector(expression).findElements(), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._counted) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    var exprs = expressions.join(','), expressions = [];
    exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    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;
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, getHash) {
    var data = elements.inject({}, function(result, element) {
      if (!element.disabled && element.name) {
        var key = element.name, value = $(element).getValue();
        if (value != null) {
         	if (key in result) {
            if (result[key].constructor != Array) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return getHash ? data : Hash.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, getHash) {
    return Form.serializeElements(Form.getElements(form), getHash);
  },

  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) {
    return $(form).getElements().find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['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;
    options.parameters = form.serialize(true);

    if (params) {
      if (typeof params == 'string') params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(form.readAttribute('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 Hash.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](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) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
  },

  inputSelector: function(element) {
    return element.checked ? element.value : null;
  },

  textarea: function(element) {
    return element.value;
  },

  select: function(element) {
    return this[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  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 = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
      ? this.lastValue != value : String(this.lastValue) != String(value));
    if (changed) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  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.bind(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();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

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,

  element: function(event) {
    return $(event.target || event.srcElement);
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0, length = Event.observers.length; i < length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
      (Prototype.Browser.WebKit || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (Prototype.Browser.WebKit || element.attachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (Prototype.Browser.IE)
  Event.observe(window, 'unload', Event.unloadCache, false);
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;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [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 == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: 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;
  },

  // 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 = this.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 = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.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;
  },

  page: 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)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    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 = Position.page(source);

    // find coordinate system to use
    target = $(target);
    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(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // 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)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    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';
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    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;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (Prototype.Browser.WebKit) {
  Position.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 [valueL, valueT];
  }
}

Element.addMethods();

function $E(str) 
{	
	//如果为undefined或null,直接返回，否则将被处理成字符?undifined"?null"
	if(str==null || str ==undefined)
		return str;		
	return encodeURIComponent(str);
}

function $N(str) 
{	
	return str==null?"":str;
}


/* - MapWorkFlow.js - */

var ABMap_piewidth = 256;
var ABMap_pieheight = 256;

var ABMap_zoomlevel = 18;

var ABMap_defaultImgSrc = "http://mapengine.mapabc.com/mapabcrasterengine/api/mapFiles/images/transparent.png";
var ABMap_lng_def = [];
var ABMap_lat_def = [];
var ABMap_pix_offset = [];	

var ABMap_images = "/images/map/";


function ABMap_getIn(n1, n2, n3)
{
    if (n2 != null) 
    {
        n1 = Math.max(n1, n2) 
    }
    if (n3 != null) 
    {
        n1 = Math.min(n1, n3)
    }
    return n1;
}



/*
*   map coord decode
*   Vqp.transformer([MHQJMPNLNOSNHKM,iulnmkqgqpqGKEN])
*/
String.prototype.hLp = function()
{
	var tmU = [];
    for (var i = 0; i < this.length; i++) 
    {
        tmU.push(this.charCodeAt(i));
    }
    return tmU;
}

var Vqp = 
{
    "__KEYCOUNT__": 256,
    "__keys__": [[0, 2, 1, 2, 8, 9, 4, 1, 7, 2, 5, 3, 9], [0, 3, 2, 2, 9, 5, 8, 2, 6, 8, 4, 6, 3], [1, 5, 2, 7, 1, 4, 7, 2, 4, 1, 4, 3, 0], [0, 7, 8, 3, 4, 9, 0, 6, 7, 7, 4, 4, 2], [0, 2, 1, 8, 4, 9, 3, 2, 3, 1, 5, 7, 8], [0, 0, 9, 5, 4, 7, 3, 0, 8, 7, 5, 2, 8], [0, 1, 5, 1, 1, 8, 2, 7, 1, 9, 1, 3, 5], [0, 5, 2, 5, 6, 0, 3, 4, 6, 7, 1, 3, 5], [1, 3, 2, 1, 8, 1, 8, 3, 7, 9, 2, 7, 0], [1, 2, 7, 7, 4, 3, 1, 5, 5, 0, 6, 4, 4], [1, 5, 2, 8, 9, 2, 5, 9, 6, 7, 3, 3, 5], [1, 7, 9, 4, 5, 0, 9, 4, 9, 6, 1, 9, 9], [0, 6, 8, 3, 3, 6, 3, 5, 2, 0, 0, 9, 1], [1, 1, 1, 4, 7, 8, 6, 9, 6, 8, 8, 4, 6], [0, 5, 2, 1, 2, 5, 7, 0, 0, 4, 7, 4, 1], [0, 7, 6, 4, 2, 3, 9, 0, 7, 8, 5, 6, 7], [0, 1, 7, 6, 0, 5, 4, 7, 6, 7, 7, 5, 7], [0, 5, 2, 9, 8, 1, 7, 8, 3, 8, 5, 4, 5], [0, 4, 3, 1, 2, 8, 3, 7, 0, 9, 4, 8, 8], [1, 0, 6, 7, 9, 4, 3, 5, 2, 9, 8, 7, 7], [1, 6, 4, 4, 6, 7, 1, 4, 4, 2, 6, 7, 5], [0, 8, 1, 7, 7, 5, 2, 6, 4, 3, 9, 7, 5], [1, 7, 0, 5, 6, 2, 5, 2, 7, 4, 6, 2, 8], [0, 4, 9, 2, 3, 0, 5, 4, 7, 8, 7, 0, 5], [1, 1, 0, 5, 1, 7, 2, 8, 7, 2, 6, 9, 3], [1, 4, 2, 3, 6, 1, 5, 3, 2, 0, 3, 6, 2], [1, 1, 6, 5, 1, 0, 6, 8, 9, 7, 1, 7, 9], [0, 6, 5, 4, 0, 7, 1, 7, 6, 2, 5, 4, 2], [1, 9, 8, 6, 6, 6, 8, 4, 5, 4, 0, 4, 0], [1, 2, 7, 1, 5, 0, 6, 8, 0, 1, 3, 7, 9], [1, 1, 6, 4, 9, 8, 6, 0, 6, 2, 1, 9, 8], [0, 0, 1, 9, 5, 3, 3, 9, 6, 7, 4, 1, 1], [0, 2, 8, 5, 7, 8, 6, 7, 3, 3, 1, 6, 4], [1, 8, 2, 5, 8, 4, 7, 6, 8, 8, 5, 7, 6], [0, 8, 3, 4, 9, 6, 1, 7, 8, 3, 0, 5, 5], [1, 3, 2, 6, 7, 4, 2, 8, 7, 4, 9, 6, 8], [1, 8, 8, 9, 3, 9, 1, 8, 5, 7, 2, 5, 0], [0, 5, 8, 3, 1, 8, 8, 0, 3, 9, 3, 8, 1], [1, 6, 0, 1, 1, 0, 3, 4, 3, 3, 3, 5, 9], [1, 0, 5, 1, 7, 9, 6, 2, 4, 6, 0, 3, 5], [1, 8, 2, 0, 9, 7, 1, 0, 5, 5, 8, 0, 6], [1, 8, 9, 6, 7, 3, 9, 4, 1, 9, 6, 6, 2], [0, 6, 0, 0, 8, 2, 6, 5, 9, 4, 1, 6, 2], [1, 7, 9, 7, 9, 4, 4, 2, 1, 1, 5, 7, 4], [1, 3, 0, 4, 3, 4, 6, 8, 6, 9, 1, 7, 0], [0, 1, 2, 3, 9, 4, 1, 8, 7, 2, 2, 9, 8], [1, 6, 5, 3, 2, 7, 6, 6, 9, 0, 0, 7, 7], [1, 6, 8, 4, 9, 7, 8, 0, 3, 6, 5, 4, 8], [0, 6, 6, 0, 9, 9, 4, 5, 5, 6, 8, 3, 7], [1, 0, 1, 3, 4, 0, 0, 1, 4, 8, 5, 7, 0], [1, 0, 2, 5, 8, 2, 2, 4, 8, 9, 7, 1, 6], [1, 4, 2, 6, 6, 8, 4, 5, 6, 6, 4, 5, 9], [1, 4, 4, 1, 7, 2, 0, 4, 6, 3, 3, 6, 7], [0, 2, 2, 3, 8, 0, 0, 8, 6, 0, 2, 1, 7], [0, 9, 4, 4, 8, 1, 2, 7, 3, 2, 6, 8, 0], [0, 9, 8, 4, 2, 1, 4, 5, 2, 4, 9, 5, 1], [0, 7, 2, 4, 7, 4, 3, 2, 4, 1, 5, 6, 9], [1, 1, 8, 4, 8, 8, 8, 4, 3, 4, 1, 2, 5], [0, 3, 2, 7, 5, 7, 0, 2, 7, 4, 5, 3, 5], [0, 3, 0, 4, 6, 6, 6, 5, 7, 2, 1, 9, 5], [1, 5, 6, 0, 1, 3, 2, 7, 3, 0, 9, 8, 6], [0, 5, 5, 1, 7, 1, 0, 7, 9, 0, 3, 5, 7], [0, 5, 4, 9, 7, 9, 7, 3, 8, 0, 1, 6, 3], [1, 9, 2, 7, 3, 7, 9, 4, 3, 9, 8, 8, 2], [0, 3, 1, 8, 9, 0, 9, 0, 4, 5, 5, 0, 9], [1, 8, 6, 1, 7, 7, 2, 4, 7, 9, 2, 0, 8], [0, 6, 1, 2, 7, 1, 4, 8, 4, 1, 1, 6, 0], [0, 3, 9, 8, 5, 5, 3, 0, 8, 7, 9, 3, 5], [0, 8, 4, 3, 7, 3, 1, 8, 2, 9, 1, 4, 7], [0, 1, 5, 3, 4, 0, 5, 5, 5, 8, 0, 7, 2], [0, 1, 7, 1, 8, 2, 1, 9, 8, 6, 1, 7, 0], [0, 7, 1, 6, 9, 7, 2, 7, 2, 4, 4, 3, 6], [0, 6, 2, 7, 2, 3, 4, 9, 3, 0, 1, 6, 3], [0, 2, 9, 1, 9, 9, 9, 1, 9, 5, 4, 4, 4], [0, 1, 8, 7, 0, 0, 5, 2, 1, 5, 7, 4, 6], [1, 9, 0, 8, 7, 3, 3, 5, 5, 4, 9, 0, 1], [1, 5, 8, 0, 1, 7, 0, 2, 3, 7, 3, 2, 9], [1, 3, 2, 0, 5, 2, 7, 5, 0, 2, 6, 8, 1], [0, 2, 7, 2, 3, 2, 2, 9, 6, 9, 4, 1, 6], [1, 6, 4, 7, 9, 6, 5, 9, 5, 8, 2, 7, 1], [1, 8, 1, 2, 6, 0, 2, 4, 0, 8, 0, 1, 6], [1, 6, 2, 4, 1, 2, 4, 1, 7, 2, 7, 0, 6], [0, 1, 8, 0, 5, 0, 4, 5, 5, 1, 0, 4, 7], [0, 8, 7, 6, 4, 3, 5, 5, 7, 8, 4, 9, 0], [0, 2, 7, 7, 0, 1, 6, 6, 1, 0, 9, 3, 5], [0, 7, 6, 9, 8, 3, 8, 6, 2, 9, 3, 7, 0], [1, 6, 6, 6, 0, 3, 0, 1, 0, 2, 5, 6, 1], [0, 0, 4, 5, 1, 0, 9, 4, 4, 9, 4, 0, 9], [0, 1, 6, 9, 4, 7, 5, 7, 8, 3, 5, 7, 0], [1, 2, 7, 1, 6, 6, 1, 5, 2, 8, 6, 3, 8], [1, 9, 1, 6, 7, 5, 1, 7, 4, 7, 6, 1, 8], [1, 7, 6, 7, 0, 2, 9, 6, 9, 8, 6, 7, 8], [0, 9, 8, 7, 3, 8, 1, 5, 2, 5, 2, 7, 5], [0, 7, 3, 5, 7, 9, 7, 6, 6, 9, 1, 7, 5], [1, 6, 7, 3, 4, 4, 7, 6, 2, 6, 6, 2, 3], [0, 1, 4, 2, 2, 8, 5, 0, 9, 2, 7, 3, 1], [0, 1, 4, 2, 1, 0, 0, 2, 1, 8, 9, 8, 3], [1, 7, 0, 8, 7, 9, 9, 6, 4, 8, 6, 2, 2], [1, 9, 3, 9, 9, 8, 7, 0, 8, 1, 1, 7, 3], [1, 0, 4, 3, 5, 8, 0, 4, 6, 5, 4, 5, 8], [0, 4, 8, 0, 5, 2, 3, 2, 3, 9, 4, 2, 3], [0, 7, 9, 0, 9, 7, 2, 7, 7, 0, 4, 8, 5], [1, 6, 5, 5, 3, 3, 2, 6, 1, 3, 4, 7, 1], [0, 2, 9, 0, 0, 2, 9, 1, 8, 8, 2, 8, 4], [1, 3, 2, 5, 0, 6, 2, 5, 3, 3, 6, 1, 1], [1, 9, 2, 9, 3, 3, 8, 9, 9, 7, 2, 3, 7], [1, 1, 8, 4, 0, 8, 2, 4, 8, 0, 0, 9, 2], [1, 5, 2, 6, 0, 6, 1, 3, 0, 4, 7, 3, 8], [1, 9, 3, 8, 1, 1, 7, 8, 6, 9, 0, 6, 8], [1, 3, 2, 7, 7, 2, 2, 4, 2, 5, 8, 3, 0], [1, 1, 1, 0, 7, 7, 3, 4, 7, 3, 6, 6, 8], [0, 9, 4, 2, 8, 9, 4, 8, 4, 3, 2, 5, 3], [0, 1, 0, 9, 2, 7, 2, 3, 9, 4, 5, 0, 8], [1, 0, 4, 5, 8, 4, 0, 0, 5, 2, 2, 1, 2], [0, 5, 0, 4, 5, 3, 2, 5, 4, 1, 3, 6, 9], [1, 3, 0, 2, 7, 8, 1, 7, 7, 3, 5, 5, 9], [1, 3, 7, 0, 0, 5, 8, 1, 7, 5, 6, 5, 2], [1, 8, 1, 9, 9, 9, 4, 8, 6, 0, 7, 7, 3], [0, 8, 3, 6, 2, 7, 4, 2, 1, 9, 1, 6, 8], [0, 4, 4, 4, 2, 6, 0, 4, 0, 1, 5, 1, 7], [1, 2, 7, 4, 7, 6, 6, 6, 3, 7, 7, 2, 9], [0, 9, 8, 9, 3, 3, 3, 9, 0, 7, 4, 2, 3], [0, 7, 6, 0, 9, 1, 7, 2, 4, 5, 8, 3, 3], [1, 6, 1, 5, 5, 3, 1, 3, 2, 1, 0, 5, 6], [0, 6, 2, 4, 1, 6, 6, 3, 4, 9, 2, 7, 0], [1, 6, 3, 2, 3, 6, 1, 7, 7, 5, 6, 7, 1], [1, 0, 4, 9, 2, 3, 3, 6, 2, 6, 9, 3, 2], [0, 3, 7, 3, 9, 1, 3, 9, 5, 8, 5, 8, 9], [1, 9, 0, 0, 3, 0, 9, 1, 2, 7, 8, 0, 3], [1, 0, 1, 2, 7, 7, 0, 0, 1, 8, 4, 1, 1], [0, 0, 5, 5, 9, 6, 9, 8, 1, 2, 1, 7, 2], [0, 1, 8, 7, 9, 0, 3, 5, 6, 3, 2, 9, 4], [1, 3, 1, 5, 7, 5, 0, 8, 5, 3, 2, 5, 0], [1, 1, 7, 3, 5, 0, 7, 7, 9, 6, 8, 9, 0], [0, 7, 7, 0, 9, 4, 2, 8, 8, 0, 2, 2, 0], [1, 6, 5, 8, 3, 1, 0, 9, 0, 2, 7, 2, 9], [1, 3, 5, 8, 4, 7, 6, 3, 1, 4, 3, 4, 7], [0, 8, 8, 7, 8, 2, 7, 0, 3, 9, 6, 2, 9], [1, 1, 6, 2, 6, 7, 5, 2, 5, 0, 8, 5, 5], [0, 9, 6, 7, 3, 0, 2, 3, 9, 5, 3, 7, 4], [1, 5, 2, 7, 3, 6, 0, 8, 3, 3, 9, 0, 3], [0, 3, 6, 8, 9, 1, 7, 7, 3, 8, 7, 3, 8], [0, 1, 2, 5, 4, 9, 8, 0, 3, 6, 4, 0, 4], [1, 2, 4, 1, 6, 8, 1, 5, 8, 3, 6, 4, 3], [1, 9, 3, 1, 0, 8, 4, 4, 0, 1, 6, 0, 8], [0, 4, 5, 1, 0, 2, 1, 7, 1, 6, 1, 3, 3], [0, 9, 5, 6, 8, 2, 2, 4, 0, 3, 9, 8, 1], [1, 9, 3, 5, 4, 3, 1, 2, 2, 2, 0, 8, 7], [0, 5, 6, 8, 1, 5, 7, 7, 8, 9, 4, 0, 6], [1, 0, 4, 6, 4, 6, 7, 4, 6, 0, 3, 6, 2], [1, 3, 3, 0, 2, 5, 3, 1, 9, 2, 3, 6, 8], [0, 6, 9, 6, 3, 6, 9, 6, 2, 1, 5, 0, 7], [1, 6, 5, 3, 0, 0, 0, 6, 2, 3, 8, 6, 0], [1, 0, 7, 1, 2, 0, 3, 0, 3, 0, 8, 8, 0], [0, 7, 1, 4, 3, 1, 8, 6, 7, 8, 1, 5, 4], [0, 6, 3, 5, 5, 4, 8, 9, 4, 8, 3, 1, 7], [0, 6, 4, 3, 1, 0, 7, 2, 9, 0, 5, 6, 7], [0, 6, 3, 7, 7, 0, 6, 8, 6, 7, 4, 6, 0], [0, 4, 2, 7, 2, 4, 1, 4, 6, 1, 8, 1, 7], [1, 1, 7, 9, 0, 7, 0, 5, 1, 8, 6, 3, 5], [1, 2, 0, 2, 7, 2, 7, 9, 1, 2, 7, 0, 3], [0, 3, 3, 6, 2, 0, 9, 1, 1, 0, 3, 5, 8], [1, 4, 0, 9, 9, 2, 5, 6, 5, 6, 8, 0, 5], [0, 3, 5, 3, 3, 3, 4, 6, 7, 5, 7, 0, 5], [0, 5, 8, 8, 5, 8, 5, 4, 7, 0, 5, 7, 3], [0, 5, 0, 7, 6, 4, 2, 7, 8, 3, 6, 1, 4], [0, 4, 7, 8, 6, 5, 3, 7, 7, 5, 7, 0, 7], [1, 3, 6, 5, 3, 0, 8, 5, 4, 9, 7, 7, 1], [1, 4, 8, 2, 8, 2, 8, 3, 4, 9, 4, 6, 7], [1, 4, 1, 6, 9, 4, 5, 7, 7, 4, 6, 7, 7], [0, 2, 8, 2, 3, 0, 7, 7, 1, 0, 1, 1, 0], [1, 2, 2, 4, 5, 4, 7, 1, 0, 1, 8, 6, 7], [0, 0, 7, 2, 4, 7, 2, 8, 2, 4, 4, 3, 9], [1, 9, 1, 3, 2, 4, 1, 3, 3, 7, 5, 6, 1], [1, 4, 7, 4, 6, 8, 6, 7, 4, 4, 1, 2, 8], [0, 1, 6, 7, 3, 9, 0, 4, 7, 2, 9, 6, 7], [0, 1, 3, 9, 1, 1, 1, 1, 6, 3, 0, 1, 1], [1, 2, 7, 0, 2, 0, 7, 9, 7, 2, 1, 5, 2], [0, 9, 1, 0, 4, 2, 8, 2, 2, 4, 2, 4, 0], [1, 1, 7, 9, 7, 9, 3, 0, 5, 3, 4, 5, 2], [0, 0, 7, 4, 3, 0, 8, 6, 7, 7, 7, 9, 6], [0, 7, 0, 4, 0, 6, 7, 6, 3, 2, 0, 7, 1], [0, 4, 8, 8, 0, 5, 3, 0, 7, 8, 4, 7, 9], [0, 6, 3, 3, 3, 6, 6, 3, 7, 0, 4, 8, 3], [0, 1, 2, 0, 6, 0, 3, 1, 0, 9, 9, 8, 0], [0, 7, 0, 3, 8, 2, 5, 0, 7, 5, 0, 0, 4], [1, 8, 8, 8, 2, 0, 6, 2, 5, 6, 2, 3, 2], [1, 6, 2, 5, 8, 0, 1, 9, 7, 3, 7, 6, 0], [0, 3, 6, 1, 9, 1, 6, 8, 2, 6, 5, 2, 5], [0, 3, 9, 7, 8, 9, 4, 5, 4, 8, 5, 5, 1], [1, 1, 5, 5, 2, 5, 3, 4, 5, 3, 5, 0, 9], [1, 0, 9, 4, 9, 6, 1, 7, 0, 0, 6, 0, 1], [0, 8, 4, 9, 9, 9, 3, 4, 1, 3, 5, 7, 7], [0, 7, 8, 0, 0, 3, 5, 5, 9, 4, 1, 8, 1], [1, 7, 3, 7, 6, 3, 2, 5, 6, 2, 7, 5, 0], [0, 0, 2, 6, 0, 6, 6, 2, 7, 6, 1, 6, 2], [1, 1, 6, 4, 7, 7, 9, 7, 0, 6, 2, 6, 6], [0, 2, 1, 1, 4, 7, 6, 8, 8, 8, 9, 4, 3], [0, 0, 8, 7, 5, 1, 9, 3, 1, 9, 8, 6, 0], [0, 3, 4, 4, 0, 7, 1, 8, 7, 2, 7, 9, 9], [1, 0, 4, 5, 3, 6, 0, 6, 6, 6, 4, 1, 5], [0, 9, 7, 9, 9, 5, 9, 2, 3, 0, 4, 6, 2], [1, 6, 5, 2, 7, 2, 1, 3, 5, 2, 5, 2, 1], [1, 9, 9, 4, 8, 6, 3, 7, 8, 3, 3, 0, 6], [0, 8, 2, 6, 6, 7, 8, 2, 1, 3, 2, 9, 2], [0, 4, 8, 1, 9, 2, 4, 8, 4, 5, 4, 6, 4], [1, 1, 7, 0, 7, 3, 5, 1, 4, 9, 5, 3, 1], [1, 7, 8, 8, 3, 5, 3, 1, 5, 7, 6, 1, 9], [1, 4, 5, 6, 5, 3, 2, 5, 3, 0, 3, 5, 5], [0, 0, 2, 1, 3, 8, 9, 1, 0, 9, 7, 6, 7], [0, 0, 7, 6, 1, 9, 1, 9, 5, 8, 9, 4, 0], [1, 5, 4, 4, 6, 8, 7, 3, 9, 9, 0, 7, 4], [1, 3, 0, 4, 8, 1, 2, 3, 9, 7, 1, 9, 5], [1, 2, 6, 1, 4, 6, 9, 4, 7, 1, 1, 2, 6], [0, 1, 6, 7, 5, 8, 3, 2, 7, 0, 4, 1, 1], [1, 6, 2, 7, 8, 7, 6, 8, 7, 2, 0, 3, 3], [0, 2, 1, 9, 2, 6, 7, 5, 9, 5, 2, 2, 2], [0, 5, 2, 0, 4, 7, 7, 3, 8, 1, 5, 0, 9], [1, 6, 5, 8, 6, 4, 0, 9, 6, 9, 0, 1, 8], [1, 2, 0, 8, 7, 9, 2, 4, 4, 0, 9, 8, 9], [1, 6, 5, 2, 0, 6, 1, 0, 4, 4, 1, 5, 8], [1, 5, 4, 2, 5, 6, 2, 5, 6, 2, 2, 9, 5], [1, 6, 9, 7, 2, 5, 1, 0, 6, 9, 1, 8, 1], [0, 0, 3, 9, 9, 0, 6, 7, 9, 5, 7, 4, 6], [1, 5, 8, 9, 9, 0, 6, 7, 9, 7, 9, 6, 1], [1, 3, 6, 4, 6, 3, 6, 8, 4, 5, 2, 8, 3], [0, 7, 4, 8, 4, 9, 7, 8, 0, 0, 1, 2, 2], [0, 4, 2, 9, 1, 3, 8, 8, 3, 0, 0, 9, 8], [1, 9, 0, 9, 2, 1, 2, 9, 3, 6, 5, 3, 2], [1, 1, 0, 2, 0, 5, 9, 9, 5, 4, 7, 8, 9], [1, 6, 0, 5, 9, 9, 1, 9, 0, 5, 4, 7, 1], [1, 0, 4, 0, 0, 3, 2, 4, 1, 6, 4, 6, 5], [1, 7, 3, 7, 3, 3, 7, 6, 1, 7, 7, 8, 6], [0, 9, 1, 7, 3, 5, 1, 8, 9, 3, 8, 6, 2], [1, 4, 9, 9, 3, 7, 5, 4, 4, 4, 4, 4, 0], [0, 3, 7, 7, 4, 3, 6, 1, 1, 3, 5, 1, 6], [0, 8, 5, 4, 3, 9, 3, 3, 1, 3, 4, 8, 1], [1, 6, 1, 9, 4, 6, 4, 6, 4, 5, 2, 1, 5], [1, 1, 1, 6, 8, 3, 9, 1, 1, 3, 0, 9, 9], [0, 5, 1, 6, 8, 4, 8, 8, 2, 4, 4, 9, 2], [0, 2, 3, 0, 1, 4, 2, 7, 1, 9, 9, 0, 6], [0, 8, 4, 2, 5, 1, 4, 9, 5, 2, 0, 4, 3], [0, 9, 1, 2, 5, 0, 6, 6, 5, 0, 3, 1, 8], [1, 7, 8, 7, 1, 7, 4, 6, 3, 3, 3, 3, 9], [0, 3, 7, 2, 9, 4, 1, 5, 4, 7, 2, 1, 0], [1, 2, 8, 1, 1, 6, 4, 7, 8, 2, 0, 5, 2], [1, 8, 3, 5, 4, 8, 0, 9, 7, 8, 0, 1, 8], [1, 7, 9, 9, 0, 4, 5, 7, 2, 9, 0, 1, 9], [0, 6, 6, 5, 6, 7, 0, 4, 0, 7, 8, 5, 1], [0, 6, 0, 6, 3, 1, 1, 5, 0, 9, 2, 2, 3], [1, 6, 3, 5, 6, 7, 1, 6, 6, 9, 7, 4, 9], [0, 9, 5, 9, 8, 2, 4, 3, 3, 2, 3, 5, 6], [0, 1, 6, 3, 8, 9, 9, 2, 8, 2, 5, 8, 6], [1, 4, 7, 6, 6, 5, 7, 3, 3, 3, 4, 1, 1], [1, 8, 2, 9, 0, 3, 8, 6, 8, 3, 3, 7, 3], [0, 2, 8, 4, 8, 5, 4, 8, 9, 5, 0, 5, 7]],
    "__maskKeyLength__": 13,
    "__getKeyNum__": function(vto)
    {
        var s = vto.substring(vto.length - 4, vto.length);  
        var aFX = s.hLp();                                  
        var bhw = 0;
        bhw |= aFX[0] & 3;
        bhw |= (aFX[1] & 3) << 2;
        bhw |= (aFX[2] & 3) << 4;
        bhw |= (aFX[3] & 3) << 6;
        return bhw - 0;
    },
    "getCoordinate": function(OXb)
    {
        var BHT = this.__getKeyNum__(OXb);
        var mvt = this.__keys__[BHT];
        var ock = OXb.substring(0, OXb.length - 4);
        var Jku = mvt[0];
        var tWl = 0;
        switch (Jku)
        {
            case 0:
                tWl = 23;
                break;
            case 1:
                tWl = 53;
                break;
        }
        var VkS = ock.hLp();
        for (var i = 0; i < VkS.length; i++) 
        {
            VkS[i] -= tWl;
            VkS[i] -= mvt[i + 1];
        }
        var OkB = [];
        for (var j = 0; j < VkS.length; j++) 
        {
            OkB.push(String.fromCharCode(VkS[j]));
        }
        ock = OkB.join("");
        return ock;
    },
    "transformer": function(iJO)
    {
		
        var OkB = [];
        for (var i = 0; i < iJO.length; i++) 
        {	
            if (isNaN(iJO[i])) 
            {
                OkB[i] = Vqp.getCoordinate(iJO[i]);
            }
            else 
            {
                OkB[i] = iJO[i];
            }
        }
		
        return OkB;
    }
};



function ABMap_getCoord(str){
	if(str){
		var tmp = str.split(",");
		var res = [];
		res[0] = parseFloat(tmp[0]);
		res[1] = parseFloat(tmp[1]);
		if(isNaN(res[0])||isNaN(res[1])){
			res = Vqp.transformer([tmp[0],tmp[1]]);
		}
		return res;	
	}
}



function ABMap_GridCodeFun(){
	this.MZe=0;
	this.IsLng=1;  
	this.IsLat=1;
	this.sQB=[-1,-1,-1,-1];
	this.nsP=[-1,-1,-1,-1];  
	this.bxV=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
	
	this.getGridCode = function(poi_xy){
		
		var lng = poi_xy[0];
		var lat = poi_xy[1];
		
		var para1 = parseInt(lng*3600000);
		var para2 = parseInt(lat*3600000);
		para1-=0;
		para2-=0;
		
		this.setMZe(para1,para2);
		
		if(para1<0){
			this.IsLng=-1;para1=-para1;
		}else{
			this.IsLng=1;
		}
		
		if(para2<0){
			this.IsLat=-1;para2=-para2;
		}else{
			this.IsLat=1;
		}
		
		this.setTmp(para1,para2);
		var res = this.getResult();
		return res;
	}

   		
	this.setMZe=function(PSR,COn){
		var XPi=parseInt(COn/2400000);
		var NVO=parseInt(PSR/3600000);
		if(NVO>100&&XPi>0){
			this.MZe=0;
		}else{
			this.MZe=1;
		}
	}

	this.setTmp=function(para1,para2){
		var Kdr=0;
		var KOs;
		var sgp;
			
		if(this.MZe==0){Kdr=100;}
		
		this.nsP[0]=parseInt(para2/2400000);  
		this.sQB[0]=parseInt(para1/3600000)-Kdr;   
		
		sgp=para2%2400000;
		KOs=para1%3600000;
		
		this.nsP[1]=parseInt(sgp/300000);
		this.sQB[1]=parseInt(KOs/450000);
		
		sgp=sgp%300000;
		KOs=KOs%450000;
		
		this.nsP[2]=parseInt(sgp/30000);
		this.sQB[2]=parseInt(KOs/45000);
	
		this.nsP[3]=parseInt((para2%30000)/10000);
		this.sQB[3]=parseInt((para1%45000)/15000);
		return;
	}

	this.getResult=function(){
		var CJs="";
		if(this.MZe==0){
			if(this.nsP[0]<10){CJs+="0";}	
			CJs+=this.nsP[0];
			
			if(this.sQB[0]<10){CJs+="0";}	
			CJs+=this.sQB[0];
		}else{
			
			if(this.IsLat==1){
			CJs+="N";
			}else{CJs+="S";}
				
			if(this.IsLng==1){
				CJs+="E";
			}else{CJs+="W";}
				
			if(this.nsP[0]<100){CJs+="0";}
			if(this.nsP[0]<10){CJs+="0";}
			CJs+=this.nsP[0];
			if(this.sQB[0]<100){CJs+="0";}
			if(this.sQB[0]<10){CJs+="0";}
			CJs+=this.sQB[0];
		}
		
		CJs+=this.nsP[1];
		CJs+=this.sQB[1];
		CJs+=this.bxV[this.nsP[2]];
		CJs+=this.bxV[this.sQB[2]];
		CJs+=this.bxV[this.nsP[3]];
		CJs+=this.bxV[this.sQB[3]];

		return CJs;
	}

}

function ABMap_disableSelection(target){ 
if (typeof target.onselectstart!="undefined") //IE  
    target.onselectstart=function(){return false} 
else if (typeof target.style.MozUserSelect!="undefined") //Firefox  
    target.style.MozUserSelect="none";
} 



function ABMapOptions(){
	this.mapContainerId = null;
	this.mapWidth = 800;
	this.mapHeight = 600;
	this.mapZoom = 7;
	this.mapCenterCoord = "116.3969,39.91744";
	this.zoomBarType = 2;  //2->small,  1->big map,new add-090326, 3->small,right top, 2->small left top
	this.isMousewheel = true;
	this.isDBLclick = true;  
	this.isOVMap = false;
	this.isGradualZoom = true;	
}



function ABMap(mapOptions){
	
	for(var property in mapOptions){
		this[property] = mapOptions[property];
	}
  
	this.mapDom = $(this.mapContainerId);   
	ABMap_disableSelection(this.mapDom);
	
	this.mapDom.style.width = this.mapWidth+"px";
	this.mapDom.style.height = this.mapHeight+"px";
	
	this.mapDom.style.position = 'relative';
	this.mapDom.style.backgroundColor = '#e8e3d8';
	this.mapDom.style.cursor =  "pointer";
	
	this.mapDom.style.overflow = 'hidden';
	
	/*
	if(this.zoomBarType == 2)
		this.mapDom.style.overflow = 'visible';
	*/
	//this.url_prefix_tmp = [[1,2,3,4,5,6],[4,5,6,1,2,3],[2,3,1,5,6,4],[5,6,4,2,3,1],[3,1,2,6,4,5],[6,4,5,3,1,2]];
	this.url_prefix_tmp = [[0,1,2,3],[1,0,3,2],[2,3,0,1],[3,2,1,0]];
	
	this.topDiv = null;   
	this.mapLayer = null;  
	this.aceteLayer = null;  
	this.ABBubbleDiv = null;
	this.mapTool = null;  
	this.screenDiv = null;
	this.toolDiv = null;
	this.ovmap = null;
	this.zoomLayer = null;  //for grade zoom 
	this.zoomArr = null;
	this.zoom_index = 0;
	
	this.img_src_x = null;
	this.img_src_y = null;
	this.left_location = 0;  
	this.top_location = 0;
	this.img_location = new Array();	
	
	this.aceteObj = new Array();
	this.aceteLineObj = new Array();
	this.currentTipIndex = -1;
	this.isLabelTip = false;
	
	//slider 
    this.as=null;
	this.slideid=null;
	this.pos_test=null;
    this.pixelsPerStep = 30;
    this.timePerStep = 60;
	
	
	this.adjust();
	this.mapTool = new ABMapTool(this);

	this.createScreenDiv();
	this.createTopDiv();
	this.createMapLayer();
	this.createZoomLayer();
	this.createAceteLayer();


	this.createBubbleDiv();
	this.addLogo();
	this.addScaleBar();
	this.addZoomBar_1();

	this.attmousewheel();
	
	this.ovstatus = false;
	if(this.isOVMap){
		this.newOverviewMap();	
	}	

	this.init();
	
}
	
ABMap.prototype.init = function(){

	var centerXY = ABMap_getCoord(this.mapCenterCoord);
	var tmp = this.latlngToPixel(centerXY,this.mapZoom);	
	this.fromPixelToImg(tmp);

	this.patchUpImg();
	
	if(this.isOVMap && this.ovstatus)
		this.ovmap.initMap();
}





ABMap.prototype.refreshZoomBar = function( ){
var s = 87+ this.mapZoom*8;
var c = this.toolDiv.firstChild;
c.style.top = s+'px';
}


ABMap.prototype.refreshZoomBarLoc = function( ){
	
	if(this.zoomBarType == 3){
		
	    this.toolDiv.style.right = (-this.mapWidth+27)+'px';
	}
}



ABMap.prototype.backTo = function( ){
	return null;
}
	
	
ABMap.prototype.createScreenDiv = function( ){
	var bDiv = document.createElement('div');
	bDiv.style.position = 'absolute';
	bDiv.style.zIndex = 2;
	
	this.mapDom.appendChild(bDiv);
	this.screenDiv = bDiv;
	
}
	
	
ABMap.prototype.createBubbleDiv = function( ){
	var bDiv = document.createElement('div');
	bDiv.id = 'ABBubbleDiv';
	bDiv.style.position = 'absolute';

	bDiv.style.display = 'none';
	bDiv.style.zIndex = 10;
	this.screenDiv.appendChild(bDiv);
	this.ABBubbleDiv = bDiv;
}



ABMap.prototype.createTopDiv = function(){
	var ttdiv = document.createElement('div');
	ttdiv.style.position = 'absolute';
	ttdiv.style.overflow = 'hidden';
	ttdiv.style.width = this.mapWidth+'px';
	ttdiv.style.height = this.mapHeight+'px';
	ttdiv.style.zIndex = 1;
	
	this.topDiv = document.createElement('div');
	this.topDiv.id = 'topDiv';
	this.topDiv.style.position = 'absolute';	
	this.topDiv.style.top = '0px';
	this.topDiv.style.left = '0px';
	this.topDiv.map = this;

	ttdiv.appendChild(this.topDiv);
	this.mapDom.appendChild(ttdiv);
	
	var map = this;
	ttdiv.onmousedown =  function(e){
		//e = (e)?e:((event)?event:null);
		map.mapTool.MyTool_onmousedown(e);
		return false;	
	}
	
	ttdiv.ondblclick = function(e){
		if(!map.isDBLclick)
		return;
		
		var pix = ABMap_getMapDivPix(e);	
		if(map.mapZoom == 0){

			var pix_x = -pix[0] + Math.ceil(map.mapWidth/2);
			var pix_y = -pix[1] + Math.ceil(map.mapHeight/2);
			map.slideBy([pix_x,pix_y]); 
			
		}else{
			var n = map.mapZoom-1;			
			var pix_x = map.img_src_x[0][0]*ABMap_piewidth - map.img_src_x[0][1]  + pix[0] - map.left_location;
			var pix_y = map.img_src_y[0][0]*ABMap_pieheight - map.img_src_y[0][1]  + pix[1] - map.top_location;				
			//map.zoomToByPixel_c(n,[pix_x,pix_y]);
			map.zoomToCenter(n,pix);
		}
		
	}
	
}


ABMap.prototype.attmousewheel = function(){
	
	if(document.attachEvent){
        this.topDiv.parentNode.attachEvent("onmousewheel",ABMap_scrollByWheel);
		this.aceteLayer.firstChild.attachEvent("onmousewheel",ABMap_stopParent);
    }
    else{
        this.topDiv.parentNode.addEventListener("DOMMouseScroll",ABMap_scrollByWheel,false);
		this.aceteLayer.firstChild.addEventListener("DOMMouseScroll",ABMap_stopParent,false);
    }

}



function ABMap_getMapDivPix(e){
	//x,y lefttop point
	var x = 0;
	var y = 0;
	
	e = (e)?e:((event)?event:null);	
	
	var SIP = null;
	if(e.srcElement){
		//IE
		e.cancelBubble = true;
		SIP=e.srcElement;
		x = e.offsetX;
		y = e.offsetY;
	}
	else if(e.target){
		//firefox
		e.stopPropagation();
		SIP=e.target;	
		x = e.layerX;
		y = e.layerY;
	}

	var res = null;
	if(SIP != null){
		var tmpobj = SIP;
		var imgleft = 0;
		var imgtop = 0;
		
		if(!((SIP.firstChild)&&(SIP.firstChild.id == "topDiv"))){
			while(tmpobj.id != "topDiv"){			
				imgleft += (tmpobj.style&&tmpobj.style.left != "")?parseInt(tmpobj.style.left):0;
				imgtop += (tmpobj.style&&tmpobj.style.top != "")?parseInt(tmpobj.style.top):0;
				tmpobj = tmpobj.parentNode;
				
			}
		}
		
		imgleft += (tmpobj.style.left != "")?parseInt(tmpobj.style.left):0;
		imgtop += (tmpobj.style.top != "")?parseInt(tmpobj.style.top):0;
	
		
		x = x+imgleft;
		y = y+imgtop;
		
		res =  [x,y];
	}
	
	return res;

	
}



function ABMap_scrollByWheel(e)
{
	
	var map1 = $("topDiv").map;
	if(!map1.isMousewheel)
		return;
	
	//x,y lefttop point
	var pix = ABMap_getMapDivPix(e);
	
	e = (e)?e:((event)?event:null);	
	
    var direct = 0;
    if(e.wheelDelta){
		e.cancelBubble=true; 
		//IE
        if(e.wheelDelta == 120){
            direct = -1;
        }
        else if(e.wheelDelta == -120){
            direct = 1;
        }
    }
    else if(e.detail != 1){
		e.stopPropagation(); 
		//firefox
        if(e.detail == -3){
            direct = -1;
        }
        else if(e.detail == 3){ 
            direct = 1;
        }
    }
	
	if(pix != null){

		var zoomvalue = map1.mapZoom + direct;
		//map1.zoomToByPixel(zoomvalue, pix);
		map1.zoomTo(zoomvalue, pix);
	}

}


ABMap.prototype.createZoomLayer = function(){
	var zoomDiv = null;
    zoomDiv = document.createElement('div');
    zoomDiv.style.zIndex = 1;
	zoomDiv.style.display = "none";
	zoomDiv.style.position = 'absolute';
	
    this.topDiv.appendChild(zoomDiv);	
	this.zoomLayer = zoomDiv;
}


	
ABMap.prototype.createMapLayer = function(){
	var mapDiv = null;
    mapDiv = document.createElement('div');
    mapDiv.style.zIndex = 1;
	mapDiv.style.position = 'absolute';

    this.topDiv.appendChild(mapDiv);	
	this.mapLayer = mapDiv;
}


ABMap.prototype.createAceteLayer = function(){	
	if(this.aceteLayer == null){
	var aceteDiv  = document.createElement('div');
	aceteDiv.style.position = 'absolute';
	aceteDiv.style.zIndex = 10;
	
	aceteDiv.style.left = '0px';
	aceteDiv.style.top = '0px';
		
	var tipDiv  = this.createTipLayer();
	var poiDiv  = this.createPoiLayer(2);
	var drawDiv  = this.createDrawLayer();
	var lineDiv = this.createPoiLayer(1);
	
	aceteDiv.appendChild(tipDiv);
	aceteDiv.appendChild(poiDiv);
	aceteDiv.appendChild(drawDiv);
	aceteDiv.appendChild(lineDiv);
	
	this.topDiv.appendChild(aceteDiv);
	this.aceteLayer = aceteDiv;
	
	
	aceteDiv.firstChild.onmousedown =  ABMap_stopParent;
	aceteDiv.firstChild.ondblclick = ABMap_stopParent;
	
	
  }
}	

function ABMap_stopParent(e){
	
	e = (e)?e:((event)?event:null);
	 if (window.event) { 
		e.cancelBubble=true; 
	 } else { 
		e.stopPropagation(); 
	 }
	 
	return false;	

}


ABMap.prototype.createTipLayer = function(){
	var tipDiv  = document.createElement('div');
	tipDiv.style.position = 'absolute';	
	tipDiv.style.display = 'none';	
	
	tipDiv.style.width = '472px';
	tipDiv.style.height = '0px';	
	tipDiv.style.zIndex=300; 
	tipDiv.style.cursor= 'auto'; 

	return tipDiv;
}


ABMap.prototype.setLabelTip = function(arg){
	if(!this.isLabelTip)
		this.isLabelTip = true;

	var tipDiv = this.aceteLayer.firstChild;	
	tipDiv.style.left = '0px';
	tipDiv.style.top = '0px';	
	tipDiv.style.width = '0px';
	tipDiv.style.height = '0px';
	
	tipDiv.innerHTML = arg;
	
	var map = this;
	var closeimg = tipDiv.firstChild.firstChild;
	closeimg.onclick = function(){map.closeTipWindow()};
}


ABMap.prototype.createPoiLayer = function(arg){
	var poiDiv  = document.createElement('div');
	poiDiv.style.position = 'absolute';	
	poiDiv.style.top = '0px';
	poiDiv.style.left = '0px';	
	
	poiDiv.style.width = '0px';
	poiDiv.style.height = '0px';	
	var t = 1;
	if(arg != null)
	t = arg;
	
	poiDiv.style.zIndex=t; 

	poiDiv.style.position='absolute'; 
	

	return poiDiv;
}


ABMap.prototype.createDrawLayer = function(){
	var drawDiv  = document.createElement('div');
	drawDiv.style.position = 'absolute';	
	drawDiv.style.top = '0px';
	drawDiv.style.left = '0px';	
	
	drawDiv.style.width = '0px';
	drawDiv.style.height = '0px';	
	drawDiv.style.zIndex=3; 

	drawDiv.style.position='absolute'; 
	

	return drawDiv;
}


ABMap.prototype.closeTipWindow = function(){
	this.aceteLayer.firstChild.style.display = 'none';
	this.currentTipIndex = -1;
}

ABMap.prototype.addLogo = function(){
	var logoDiv  = document.createElement('div');
	logoDiv.id = 'logoDiv';
	logoDiv.style.position = 'absolute';
	logoDiv.style.zIndex = '1';
	logoDiv.style.fontSize = "12px";
	
	if(this.zoomBarType == 2){
		logoDiv.style.width = '70px';
		logoDiv.innerHTML = "<a href='http://www.mapabc.com' style='color:#CCC' target='_blank'>mapabc.com</a>";
	}else{
		logoDiv.style.width = '130px';
		logoDiv.innerHTML = "\u5730\u56FE\u670D\u52A1&nbsp;-&nbsp;<a href='http://www.mapabc.com' target='_blank'>mapabc.com</a>";
	}
	
	logoDiv.style.right = (-this.mapWidth+7)+'px';
	logoDiv.style.bottom = (-this.mapHeight+3)+'px';
	
	logoDiv.style.height = '20px';
	logoDiv.style.cursor = 'default';
	this.screenDiv.appendChild(logoDiv);
}

ABMap.prototype.refreshLogo = function(args){
	var logoDiv  = $('logoDiv');

	var l = 7;
	var t = 3; 
	
	if(args){
		l += args[0];
		t += args[1];
	}
	
	l = l-this.mapWidth;
	t = t-this.mapHeight;	
	
	logoDiv.style.right = l+'px';
	logoDiv.style.bottom = t+'px';
}

ABMap.prototype.refreshScaleBar = function(){
	var scaleDiv  = $('scaleDiv');

	scaleDiv.style.left = '10px';
	scaleDiv.style.bottom = (-this.mapHeight+5)+'px';
}


ABMap.prototype.addScaleBar = function(){
	var scaleDiv  = document.createElement('div');
	scaleDiv.id = 'scaleDiv';
	scaleDiv.style.position = 'absolute';
	scaleDiv.style.zIndex = '1';
	scaleDiv.style.fontSize = "12px";
	scaleDiv.style.fontWeight = "bold";
	scaleDiv.style.cursor = 'default';
	
	var s  = document.createElement('div');
	s.id = "scaled";
	s.style.fontSize = "12px";
	s.style.fontWeight = "bold";
	s.style.width = "60px";
	s.align="left";
	s.innerHTML = "";	
	
	scaleDiv.appendChild(s);
	var Img = document.createElement('img');
	Img.src = ABMap_images+"scale.png";
	Img.align="left";
	scaleDiv.appendChild(Img);

	scaleDiv.style.left = '10px';
	scaleDiv.style.bottom = (-this.mapHeight+5)+'px';
	this.screenDiv.appendChild(scaleDiv);
}

ABMap.prototype.refreshScale = function(s){
	var scaleDiv  = $("scaled");	
	scaleDiv.innerHTML = s;	
}


ABMap.prototype.controllerBar = function(){
	
    var obj = document.createElement("div");
    obj.style.position = "absolute";
	
	if(this.zoomBarType == 2){
	    obj.style.left = '5px';
    	obj.style.top = '5px';
	}else if(this.zoomBarType == 3){
	    obj.style.right = (-this.mapWidth+27)+'px';
    	obj.style.top = '5px';
	}


    var z1 = document.createElement("img");
    z1.src = ABMap_images+"zoom_in.gif";
	z1.style.position = 'absolute';
	z1.style.top = '0px';
	z1.style.left = '0px';
	z1.style.width = "22px";
 	z1.style.height = "24px";
 

	
    var tmp = this;
    z1.onclick = function(){
        tmp.zoomIn();
    }
    var z2 = document.createElement("img");
    z2.src = ABMap_images+"zoom_out.gif";
	z2.style.position = 'absolute';
	z2.style.top = '24px';
	z2.style.left = '0px';
	z2.style.width = "22px";
 	z2.style.height = "24px";
 
    z2.onclick = function(){
        tmp.zoomOut();
    }
    obj.appendChild(z1);
    obj.appendChild(z2);
    this.screenDiv.appendChild(obj);
	
		this.toolDiv = obj;
}



ABMap.prototype.createTitleDiv = function(l,t,w,h,p){
	
	var titlediv = document.createElement('div');
	titlediv.style.position = 'absolute';
	titlediv.style.top = t+'px';
	titlediv.style.left = l+'px';
	titlediv.style.width = w+'px';
	titlediv.style.height = h+'px';

	if(p != null)
		titlediv.title = p;
	titlediv.style.cursor = "pointer";
	titlediv.style.zIndex = 20;
	titlediv.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
	titlediv.style.overflow = "hidden";

	return titlediv;
}


ABMap.prototype.addZoomBar_1 = function( ){
	if(this.zoomBarType != 1){
		this.controllerBar();
		return;
	}
	
	
	var ttdiv = document.createElement('div');
	ttdiv.style.position = 'absolute';

	ttdiv.style.top = '5px';
	ttdiv.style.left = '5px';
	
	var map = this;
	
	var img_cz = document.createElement('img');
	img_cz.style.position = 'absolute';
	var s = 87+ this.mapZoom*8;
	img_cz.style.top = s+'px';
	img_cz.style.left = '19px';
	img_cz.style.width = '22px';
	img_cz.style.height = '14px';
	img_cz.src = ABMap_images+ "slider.gif";   
	img_cz.style.zIndex = 20;
	img_cz.style.cursor = 'pointer';
	var x_tmp = 0,y_tmp = 0;
	
	img_cz.onmousedown = function(e){
		e = (e)?e:((event)?event:null);
		//x_tmp = e.clientX;
		y_tmp = e.clientY;
		
		
		document.onmousemove = function(e){
			e = (e)?e:((event)?event:null);	
			var offset = e.clientY - y_tmp;
			
			var o = parseInt(img_cz.style.top);
			
			o = o+offset;
			if(o>223)
				o = 223;
				
			if(o<87)
				o = 87;
			
			img_cz.style.top = (o)+'px';
			
			y_tmp = e.clientY;
			return false;
		}
		
		document.onmouseup = function(e){
			document.onmousemove = null;
			var o = parseInt(img_cz.style.top);
			var w = Math.floor((o-87)/8);
			var q = (o-87)%8;
			if(q>4)
				w +=1;
			o = 87+ w*8;
			img_cz.style.top = (o)+'px';	
			
			map.zoomTo(w);
			return false;
		}
		return false;	
	}
	
	ttdiv.appendChild(img_cz);
	
	//add title and cursor
	var tmp = this.createTitleDiv(1,20,17,17,unescape("\u5411\u5DE6\u5E73\u79FB"));  
	tmp.onclick = function(){map.slideBy([300,0])};
	ttdiv.appendChild(tmp);
	
	tmp = this.createTitleDiv(40,20,17,17,unescape("\u5411\u53F3\u5E73\u79FB"));
	tmp.onclick = function(){map.slideBy([-300,0])};
	ttdiv.appendChild(tmp);

	tmp = this.createTitleDiv(20,0,17,17,unescape("\u5411\u4E0A\u5E73\u79FB"));
	tmp.onclick = function(){map.slideBy([0,300])};
	ttdiv.appendChild(tmp);

	tmp = this.createTitleDiv(20,20,17,17,unescape("\u8FD4\u56DE\u4E0A\u4E00\u7ED3\u679C"));
	tmp.onclick = function(){map.backTo()};
	ttdiv.appendChild(tmp);

	tmp = this.createTitleDiv(20,40,17,17,unescape("\u5411\u4E0B\u5E73\u79FB"));
	tmp.onclick = function(){map.slideBy([0,-300])};
	ttdiv.appendChild(tmp);
	
	tmp = this.createTitleDiv(20,67,17,17,unescape("\u653E\u5927"));
	tmp.onclick = function(){map.zoomIn()};
	ttdiv.appendChild(tmp);

	tmp = this.createTitleDiv(20,241,17,17,unescape("\u7F29\u5C0F"));
	tmp.onclick = function(){map.zoomOut()};
	ttdiv.appendChild(tmp);	

/*
	tmp = this.createTitleDiv(20,87,17,150);
	tmp.onclick = function(e){	
		var off_x = -1;
		var off_y = -1;
			e = (e)?e:((event)?event:null);	
			var isie = (e)?1:((event)?2:0);
			
		var SIP = null;
		var direct = 0;
		if(e.srcElement != null){
			//IE
			e.cancelBubble = true;
			SIP=e.srcElement;
			off_x = e.offsetX;
			off_y = e.offsetY;
		}
		else if(e.target != null){
			//firefox		
			e.stopPropagation();
			SIP=e.target;	
			off_x = e.layerX;
			off_y = e.layerY;
		}
		
		if(off_y<=7){
				map.zoomTo(0);  //0
			}else
			if(off_y >=8 && off_y<=15){
				map.zoomTo(1);  //1
			}else
			if(off_y >=16 && off_y<=23){
				map.zoomTo(2);  //2
			}else
			if(off_y >=24 && off_y<=31){
				map.zoomTo(3);  //1
			}else
			if(off_y >=32 && off_y<=39){
				map.zoomTo(4);  //1
			}else
			if(off_y >=40 && off_y<=47){
				map.zoomTo(5);  //1
			}else
			if(off_y >=48 && off_y<=55){
				map.zoomTo(6);  //1
			}else
			if(off_y >=56 && off_y<=63){
				map.zoomTo(7);  //1
			}else
			if(off_y >=64 && off_y<=71){
				map.zoomTo(8);  //1
			}else
			if(off_y >=72 && off_y<=79){
				map.zoomTo(9);  //1
			}else
			if(off_y >=80 && off_y<=87){
				map.zoomTo(10);  //1
			}else
			if(off_y >=88 && off_y<=95){
				map.zoomTo(11);  //1
			}else
			if(off_y >=96 && off_y<=103){
				map.zoomTo(12);  //1
			}else
			if(off_y >=104 && off_y<=111){
				map.zoomTo(13);  //1
			}else
			if(off_y >=112 && off_y<=119){
				map.zoomTo(14);  //1
			}else
			if(off_y >=120 && off_y<=127){
				map.zoomTo(15);  //1
			}else
			if(off_y >=128 && off_y<=135){
				map.zoomTo(16);  //1
			}else
			if(off_y >=136 && off_y<=143){
				map.zoomTo(17);  //1
			}	
	}
	//ttdiv.appendChild(tmp);
*/

	var img_tool = document.createElement('img');
	img_tool.style.position = 'absolute';
	img_tool.style.top = '0px';
	img_tool.style.left = '0px';
	img_tool.style.width = '57px';
	img_tool.style.height = '257px';
	img_tool.src = ABMap_images+"tool.png";
	img_tool.style.cursor = 'default';
	img_tool.style.zIndex = 1;
	
	img_tool.onclick = function(e){
			
		var off_x = -1;
		var off_y = -1;
			e = (e)?e:((event)?event:null);	
			var isie = (e)?1:((event)?2:0);
			
		var SIP = null;
		
		var direct = 0;
		if(e.srcElement != null){
			//IE
			SIP=e.srcElement;
			
			off_x = e.offsetX;
			off_y = e.offsetY;
		}
		else if(e.target != null){
			//firefox		
			e.stopPropagation();
			SIP=e.target;	
			off_x = e.layerX;
			off_y = e.layerY;
		}
		
		
		
		if(off_x >=20 && off_x<=37){
			if(off_y >=87 && off_y<=94){
				map.zoomTo(0);  //0
			}else
			if(off_y >=95 && off_y<=102){
				map.zoomTo(1);  //1
			}else
			if(off_y >=103 && off_y<=110){
				map.zoomTo(2);  //2
			}else
			if(off_y >=111 && off_y<=118){
				map.zoomTo(3);  //1
			}else
			if(off_y >=119 && off_y<=126){
				map.zoomTo(4);  //1
			}else
			if(off_y >=127 && off_y<=134){
				map.zoomTo(5);  //1
			}else
			if(off_y >=135 && off_y<=142){
				map.zoomTo(6);  //1
			}else
			if(off_y >=143 && off_y<=150){
				map.zoomTo(7);  //1
			}else
			if(off_y >=151 && off_y<=158){
				map.zoomTo(8);  //1
			}else
			if(off_y >=159 && off_y<=166){
				map.zoomTo(9);  //1
			}else
			if(off_y >=167 && off_y<=172){
				map.zoomTo(10);  //1
			}else
			if(off_y >=175 && off_y<=180){
				map.zoomTo(11);  //1
			}else
			if(off_y >=183 && off_y<=188){
				map.zoomTo(12);  //1
			}else
			if(off_y >=191 && off_y<=196){
				map.zoomTo(13);  //1
			}else
			if(off_y >=199 && off_y<=204){
				map.zoomTo(14);  //1
			}else
			if(off_y >=205 && off_y<=212){
				map.zoomTo(15);  //1
			}else
			if(off_y >=213 && off_y<=220){
				map.zoomTo(16);  //1
			}else
			if(off_y >=221 && off_y<=228){
				map.zoomTo(17);  //1
			}
		}
	}
	
	
	ttdiv.appendChild(img_tool);
	
	
	this.screenDiv.appendChild(ttdiv);
	this.toolDiv = ttdiv;
}




ABMap.prototype.createImg = function(left1,top1,src1){
	var Img = null;
	 Img = document.createElement('img');

	Img.style.position = 'absolute';
	Img.style.left = left1+'px';
	Img.style.top = top1+'px';
	
	Img.style.width= ABMap_piewidth+'px';
	//Img.style.height= ABMap_pieheight+'px';

	Img.style.opacity = 1;
	
	Img.src = src1;

	return Img;
}



ABMap.prototype.adjust = function(){
	var c = ABMap_piewidth;
	for (var i = 0; i < ABMap_zoomlevel; i++) 
	{
		var e = c / 2;
		ABMap_lng_def.push(c / 360);
		ABMap_lat_def.push(c / (2 * Math.PI));
		ABMap_pix_offset.push(e);
		c *= 2
	}
}


ABMap.prototype.latlngToPixel = function(centerXY,zoom){
	if(centerXY){
		var center_x = centerXY[0];
		var center_y = centerXY[1];
		var zoomt = ABMap_zoomlevel-1-zoom;
		var pixel_x = Math.round(ABMap_pix_offset[zoomt]+center_x * ABMap_lng_def[zoomt]);
		var f = ABMap_getIn(Math.sin(center_y * (Math.PI / 180)), -0.9963, 0.9963);
		var pixel_y = Math.round(ABMap_pix_offset[zoomt]- 0.5 * Math.log((1 + f) / (1 - f)) * ABMap_lat_def[zoomt]);
		return [pixel_x,pixel_y];
	}
}


ABMap.prototype.PixelTolatlng = function(pixels,zoom){
	var zoomt = ABMap_zoomlevel-1-zoom;
	var lat_tmp = (ABMap_pix_offset[zoomt]-pixels[1])/ ABMap_lat_def[zoomt];   
	var lng = (pixels[0] - ABMap_pix_offset[zoomt])/ABMap_lng_def[zoomt];
	
	var lat = this.getDu(2 * Math.atan(Math.exp(lat_tmp)) - Math.PI / 2);
	
	return [lng,lat];
}
	
	
ABMap.prototype.getDu = function(para)
{
	return para / (Math.PI / 180)
}


//pixel is the point pixel coord value, pix is the offset from lefttop to the point
ABMap.prototype.fromPixelToImg = function(pixel,pix){
	
	var pixel_x = pixel[0];
	var pixel_y = pixel[1];
	
	this.img_src_x = new Array();
	this.img_src_y = new Array();
	
	var pixel_xn = Math.floor(pixel_x/ABMap_piewidth);    
	var pixel_yn = Math.floor(pixel_y/ABMap_pieheight);
	
	var poi_left = pixel_x - pixel_xn * ABMap_piewidth ;     
	var poi_top = pixel_y - pixel_yn * ABMap_pieheight ;   
	
	
	var halfwidth = Math.round(this.mapWidth/2);
	var halfheight = Math.round(this.mapHeight/2);
	if(pix != null){
		halfwidth = Math.round(pix[0]);
		halfheight = Math.round(pix[1]);	
	}
		
	var n1 = 0;
	while((n1*256+poi_left)<=halfwidth)
		n1++;
	
	poi_left = halfwidth - poi_left;
	pixel_xn -= n1;
	poi_left -= n1*256;
	
	var len = n1+1;
	while((len*256 + poi_left) <this.mapWidth)
		len++;
	
	for(var i=0;i<len;i++)
		this.img_src_x.push([pixel_xn+i, poi_left+256*i]);	
	
	n1 = 0;
	while((n1*256+poi_top)<=halfheight)
		n1++;
	
	poi_top = halfheight - poi_top;
	pixel_yn -= n1;
	poi_top -= n1*256;
	
	len = n1+1;
	while((len*256 +poi_top) <this.mapHeight)
		len++;
	
	for(var i=0;i<len;i++)
		this.img_src_y.push([pixel_yn+i, poi_top+256*i]);
	
}


ABMap.prototype.patchUpImg = function(){
	
	if(this.mapLayer == null)
	return;

	this.left_location = 0;  
	this.top_location = 0;
	this.topDiv.style.top = '0px';
	this.topDiv.style.left = '0px';
	
	var mapdiv = this.mapLayer;
	
	var x_n = this.img_src_x.length;
	var y_n = this.img_src_y.length;				
				
	var img_n =  mapdiv.childNodes.length;	
	for(var i =0;i<img_n;i++){
		mapdiv.removeChild(mapdiv.childNodes[0]);
	}	

	this.img_location = new Array();

	for(var i=0;i<x_n;i++){
		
		for(var j=0;j<y_n;j++){

			var url = this.getURL(this.img_src_x[i][0],this.img_src_y[j][0],this.mapZoom);

			var imgobj = this.createImg(this.img_src_x[i][1], this.img_src_y[j][1], url);
			mapdiv.appendChild(imgobj);
			
			this.img_location.push("z"+this.mapZoom+"x"+this.img_src_x[i][0]+"y"+this.img_src_y[j][0]);
		}	
	}
	var s = this.getScale();
	this.refreshScale(s);
}
	
	
ABMap.prototype.checkUrl = function(x,y,z){
	
	var tmp = ABMap_pix_offset[ABMap_zoomlevel - z -1]/(ABMap_piewidth/2);
	
	if(x>=0&&x<tmp&&y>=0&&y<tmp)
			return true;
	else
		return false;
	
}


ABMap.prototype.getUrlPrefix = function(x,y,z){
	var x1 = x%4;
	var y1 = y%4;
	
	var s = this.url_prefix_tmp[x1][y1];
	//var url_prefix = "http://map"+(s)+".aibang.com/mapcache?zoom="+z;
	var url_prefix ="http://emap"+s+".mapabc.com/mapabc/maptile?v=w2.61&zoom="+z;
	return url_prefix;
}


ABMap.prototype.getURL = function(x,y,z){

	var url_prefix = "";

	var url;
	if(this.checkUrl(x,y,z)){
		url_prefix = this.getUrlPrefix(x,y,z);
			
		url = url_prefix+"&x="+x+"&y="+y;
	}else
		url = ABMap_defaultImgSrc;
			
	return url;
	
}


//zoom to by pix,pix's location move to center. 
//pix is the offset between point and lefttop point
ABMap.prototype.zoomToCenter = function(newzoom,pix){
	
	if(newzoom == this.mapZoom || newzoom <0 || newzoom > (ABMap_zoomlevel-1))
		return;	
	
	//this.aceteLayer.style.visibility = "hidden";
	
	var cZoom = this.mapZoom;	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;
	
	var centerX_pixel = leftpix + pix[0];
	var centerY_pixel =  toppix + pix[1];
	
	
	var zoom_off =  cZoom - newzoom;
	var s = Math.pow(2,zoom_off);
	
	var centerX_pixel_n = Math.ceil(centerX_pixel* s );
	var centerY_pixel_n = Math.ceil(centerY_pixel* s );
	
	var zoom_offset = newzoom - this.mapZoom;
	if(this.isGradualZoom && Math.abs(zoom_offset) == 1){
		var tmp = this.mapLayer;
		this.mapLayer = this.zoomLayer;
		this.zoomLayer = tmp;
		tmp = null;
		
		this.mapLayer.style.display = 'none';
		this.zoomLayer.style.display = "";
		
		var loc_tmp = [this.left_location,this.top_location];	
		
		this.aceteLayer.style.visibility = "hidden";
		this.zoomAddix([centerX_pixel_n,centerY_pixel_n],newzoom);
		
		for(var i=0;i<this.zoomLayer.childNodes.length;i++){
			this.zoomLayer.childNodes[i].style.left = (parseInt(this.zoomLayer.childNodes[i].style.left)+loc_tmp[0])+"px";
			this.zoomLayer.childNodes[i].style.top = (parseInt(this.zoomLayer.childNodes[i].style.top)+loc_tmp[1])+"px";
		}
	
		this.zoom_index = 1;
		
		if(zoom_offset== -1)
			this.zoomArr = [[256],[299],[342],[385],[428],[471],[512]];
		else if(zoom_offset== 1)
	    	this.zoomArr = [[256],[235],[214],[193],[172],[151],[128]];
		
		this.gradualZoom_new(pix,true);
	
	}else{
		this.zoomLayer.style.display = 'none';
		this.aceteLayer.style.visibility = "hidden";
		this.zoomAddix([centerX_pixel_n,centerY_pixel_n],newzoom);
		this.aceteLayer.style.visibility = "visible";
	}

	this.backTo = function(){
		this.zoomTo(cZoom);
		this.backTo = function(){return null};
	}	
	
}



//zoom to by pix,pix's location move to center. 
//latlng is the coord of the point. 
ABMap.prototype.zoomToBylatlng_c = function(newzoom,latlng){
	
	if(newzoom == this.mapZoom || newzoom <0 || newzoom >(ABMap_zoomlevel-1))
		return;	

	this.zoomLayer.style.display = "none";

	var cZoom = this.mapZoom;	
	var pixelcoord_new = this.latlngToPixel(latlng,newzoom);
	
	this.aceteLayer.style.visibility = "hidden";
	this.zoomAddix(pixelcoord_new,newzoom);
	this.aceteLayer.style.visibility = "visible";

	this.backTo = function(){
		this.zoomTo(cZoom);
		this.backTo = function(){return null};
	}	
}





//zoom to by pix,pix's location move to center. 
//pix is the pixel coord of the point. 
ABMap.prototype.zoomToByPixel_c = function(newzoom,pix){
	
	if(newzoom == this.mapZoom || newzoom <0 || newzoom >(ABMap_zoomlevel-1))
		return;	

	this.zoomLayer.style.display = "none";
	
	var cZoom = this.mapZoom;	
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;
	
	var centerX_pixel = leftpix + this.mapWidth/2;
	var centerY_pixel =  toppix + this.mapHeight/2;
	
	
	var zoom_off =  cZoom - newzoom;
	var s = Math.pow(2,zoom_off);
	
	var centerX_pixel_n = Math.ceil(pix[0]* s );
	var centerY_pixel_n = Math.ceil(pix[1]* s );
	
	
	//var coord = this.PixelTolatlng(pix,cZoom);
	//var pixelcoord_new = this.latlngToPixel(coord,newzoom);
	
	
	
	
	this.aceteLayer.style.visibility = "hidden";
	//this.zoomAddix(pixelcoord_new,newzoom);
	this.zoomAddix([centerX_pixel_n,centerY_pixel_n],newzoom);
	this.aceteLayer.style.visibility = "visible";


	this.backTo = function(){
		this.zoomTo(cZoom);
		this.backTo = function(){return null};
	}	
	
}


ABMap.prototype.zoomAddix = function(center,newzoom,pix){
	//this.aceteLayer.style.visibility = "hidden";
	
	var centerX_pixel = center[0];
	var centerY_pixel = center[1];	
	
	this.stopLastSlide();
	if(this.isOVMap && this.ovstatus)
		this.ovmap.stopLastSlide();
	
	this.mapZoom = newzoom;
	this.fromPixelToImg(center,pix);
	this.patchUpImg();
	
	if(this.isOVMap && this.ovstatus){
		this.ovmap.zoomTo(newzoom);
	}	
	
	this.refreshAcete();
	//this.aceteLayer.style.visibility = "visible";
	
	if(this.zoomBarType == 1)
	    this.refreshZoomBar();
}


ABMap.prototype.gradualZoom_new = function(pix,iscenter){
	var len = this.zoomArr.length;

	var offsetx = 0;
	var offsety = 0;

	var x1 = 0;
	var y1 = 0;
		
	if(iscenter){
		x1 = this.mapWidth/2 - pix[0];
		y1 = this.mapHeight/2 - pix[1];
		
		if(x1>0)
			offsetx = Math.floor(x1/(len-1));
		else
			offsetx = Math.ceil(x1/(len-1));
		
		if(y1>0)
			offsety = Math.floor(y1/(len-1));
		else
			offsety = Math.ceil(y1/(len-1));
	}
	
	
	var mapsize = 256;
	var img_obj = this.zoomLayer.childNodes[0];
	var left = parseInt(img_obj.style.left);
	var top = parseInt(img_obj.style.top);
	
	while((left+mapsize) < pix[0])
		left += mapsize;
		
	while(left > pix[0])
		left -= mapsize;

	//top
	while((top+mapsize) < pix[1])
		top += mapsize;
	
	while(top > pix[1])
		top -= mapsize;
	
	
	for(var i =0;i<len;i++){
		var img_size = this.zoomArr[i][0];
		
		var x_tmp = offsetx*i;
		var y_tmp = offsety*i;
		
		if( i == (len-1)){
			x_tmp = x1;
			y_tmp = y1;
		}
		
		var left0 = Math.round(pix[0]) - Math.round((- left + pix[0] )*img_size/mapsize) +Math.round(x_tmp);
		 this.zoomArr[i].push(left0);
		
		var top0 = Math.round(pix[1]) - Math.round(( -top + pix[1] )*img_size/mapsize) +Math.round(y_tmp);
		this.zoomArr[i].push(top0);
	}
	
	this.gradualZoom_random(iscenter);

}


ABMap.prototype.gradualZoom_random = function( ){
	
	var len = this.zoomArr.length;
	if(this.zoom_index <len){
		var img_n = this.zoomLayer.childNodes.length;
		
		var size_tmp = this.zoomArr[this.zoom_index][0];
		var size_last = this.zoomArr[this.zoom_index-1][0];
		
		var posX_tmp = this.zoomArr[this.zoom_index][1];
		var posX_last = this.zoomArr[this.zoom_index-1][1];
		
		var posY_tmp = this.zoomArr[this.zoom_index][2];
		var posY_last = this.zoomArr[this.zoom_index-1][2];
		
		for(var i =0 ;i<img_n;i++){
			img_obj = this.zoomLayer.childNodes[i];
			
			var left1 = parseInt(img_obj.style.left);
			var top1 = parseInt(img_obj.style.top);
	
			var left_n = (left1 - posX_last)/size_last;
			var top_n = (top1 - posY_last)/size_last;
	
			img_obj.style.left = (posX_tmp+left_n*size_tmp)+"px";
			img_obj.style.top = (posY_tmp+top_n*size_tmp)+"px";
			
			img_obj.style.width = size_tmp+'px';
			
			if(!(window.navigator.userAgent.indexOf("Firefox")>=1))
			img_obj.style.height = size_tmp+'px';
			
			
		}
		
		var map = this;
		setTimeout(function(){map.gradualZoom_random( )}, 70);
	}else{
	
		this.mapLayer.style.display = '';	
		
		var indextmp = this.mapLayer.style.zIndex;
		if(indextmp <2){
			this.mapLayer.style.zIndex = 2;
			indextmp = 2;
		}
		this.zoomLayer.style.zIndex = indextmp-1;

		this.aceteLayer.style.visibility = "visible";
		
	}

	this.zoom_index += 1;	

}



ABMap.prototype.zoomTo = function(newzoom,pix){
	if(newzoom == this.mapZoom || newzoom <0 || newzoom >(ABMap_zoomlevel-1))
		return;	
	
	//this.aceteLayer.style.visibility = 'hidden';
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;
	
	var cZoom = this.mapZoom;
	var zoom_off =  cZoom - newzoom;
	var s = Math.pow(2,zoom_off);
	
	var offsetX = this.mapWidth/2;
	var offsetY = this.mapHeight/2;
	if(pix != null){
		offsetX = pix[0];
		offsetY = pix[1];
	}
	
	if(this.currentTipIndex >= 0 && !this.isLabelTip && pix == null){
		
		var point =  this.aceteObj[this.currentTipIndex];
		point = ABMap_getCoord(point.coord);
		var pix_tmp = this.latlngToPixel(point,this.mapZoom);

		var leftoffset = pix_tmp[0]-leftpix;
		var topoffset = pix_tmp[1]-toppix;	
		
		if(leftoffset >=0 && leftoffset <= this.mapWidth && topoffset >=0 && topoffset <= this.mapHeight){
			offsetX = pix_tmp[0] - leftpix;
			offsetY = pix_tmp[1] - toppix;		
		}
	}
	
	var pixelX = Math.round((leftpix+offsetX)*s);
	var pixelY = Math.round((toppix+offsetY)*s);
	

	var zoom_offset = newzoom - this.mapZoom;
	if(this.isGradualZoom && Math.abs(zoom_offset) == 1){
		var tmp = this.mapLayer;
		this.mapLayer = this.zoomLayer;
		this.zoomLayer = tmp;
		tmp = null;
		
		this.mapLayer.style.display = 'none';
		this.zoomLayer.style.display = "";
		
		var loc_tmp = [this.left_location,this.top_location];	
		
		this.aceteLayer.style.visibility = "hidden";
		this.zoomAddix([pixelX,pixelY],newzoom,[offsetX,offsetY]);	
		
		
		for(var i=0;i<this.zoomLayer.childNodes.length;i++){
			this.zoomLayer.childNodes[i].style.left = (parseInt(this.zoomLayer.childNodes[i].style.left)+loc_tmp[0])+"px";
			this.zoomLayer.childNodes[i].style.top = (parseInt(this.zoomLayer.childNodes[i].style.top)+loc_tmp[1])+"px";
		}
	
		this.zoom_index = 1;
		
		if(zoom_offset== -1)
			this.zoomArr = [[256],[299],[342],[385],[428],[471],[512]];
		else if(zoom_offset== 1)
	    	this.zoomArr = [[256],[235],[214],[193],[172],[151],[128]];
		
		this.gradualZoom_new([offsetX,offsetY],false);
		
	}else{
		this.zoomLayer.style.display = 'none';
		this.aceteLayer.style.visibility = "hidden";
		this.zoomAddix([pixelX,pixelY],newzoom,[offsetX,offsetY]);
		this.aceteLayer.style.visibility = "visible";
	}

	this.backTo = function(){
		this.zoomTo(cZoom,pix);
		this.backTo = function(){return null};
	}	
	
}


ABMap.prototype.refreshAcete = function( ){
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1];
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] ;
	
	var n = this.aceteLayer.childNodes[1].childNodes.length;
	//var n = this.aceteObj.length;
	var left1;
	var top1;
	for(var i =0;i<n;i++){
		var tmp = this.aceteLayer.childNodes[1].childNodes[i];
		
		
		
		var point =  this.aceteObj[tmp.poiObj_index];
		var pix = this.latlngToPixel(ABMap_getCoord(point.coord),this.mapZoom);
		
		left1 = pix[0] - leftpix;
		top1 = pix[1] - toppix;
		
		tmp.style.left = left1 +'px';
		tmp.style.top =  top1 +'px';
	}


	if(this.currentTipIndex>=0){
		
		var tmp = this.aceteLayer.firstChild;
		
		var point =  this.aceteObj[this.currentTipIndex];
		var pix = this.latlngToPixel(ABMap_getCoord(point.coord),this.mapZoom);

		var tmppix = [(pix[0]-leftpix),(pix[1]-toppix)];	

		if(this.isLabelTip){
			//add tip for label
			tmp.style.display = 'block';	
			tmp.style.left = (tmppix[0] +25) + 'px';
			tmp.style.top = ( tmppix[1]-75) + 'px';
			
		}else{
			
			//big map page
			var offsetheight = 39;
			try{
				var ht = tmp.childNodes[1].clientHeight;
				offsetheight += parseInt(ht);
			}catch(error){
			
			}
			
			offsetheight = parseInt(offsetheight);
	
			tmp.style.left = (tmppix[0] -56) + 'px';
			tmp.style.top = ( tmppix[1] - 33 - offsetheight) + 'px';			
		}
		
	}
	
	//draw point   drawPoi_xy
	if(this.mapTool.drawStatus != -1 && this.drawPoi_xy!= null){
		n = this.aceteLayer.childNodes[2].childNodes.length;

		for(var i =0;i<n;i++){

			var tmp = this.aceteLayer.childNodes[2].childNodes[i];
			
			var pix = this.latlngToPixel(this.drawPoi_xy,this.mapZoom);
			
			left1 = pix[0] - leftpix;// + this.left_location;
			top1 = pix[1] - toppix ; // + this.top_location;
			
			tmp.style.left = left1 +'px';
			tmp.style.top =  top1 +'px';
		}	
	}
	
	var line_layer = this.aceteLayer.childNodes[3];
	var line_n = line_layer.childNodes.length;
	
	for(var i =0;i<line_n;i++){
		line_layer.removeChild(line_layer.childNodes[0]);
	}
	
	var line_n = this.aceteLineObj.length;
	for(var i =0;i<line_n;i++){
		var tmpdiv = this.addPoly_vs(this.aceteLineObj[i]);
		line_layer.appendChild(tmpdiv);
	
	}
}


ABMap.prototype.zoomIn = function(){	
	if((this.mapZoom-1)>=0)
		this.zoomTo(this.mapZoom-1);
}
	
	
ABMap.prototype.zoomOut = function(){
	if((this.mapZoom+1)< ABMap_zoomlevel)
		this.zoomTo(this.mapZoom+1);
}
	
	
ABMap.prototype.getZoomValue = function(maxX,minX,maxY,minY){
	var topleft = this.latlngToPixel([minX,maxY],0);
	var bottomright = this.latlngToPixel([maxX,minY],0);
	
	var t_x = Math.abs(topleft[0] - bottomright[0])/this.mapWidth;
	var t_y = Math.abs(topleft[1] - bottomright[1])/this.mapHeight;	
	var res = 0;
	
	if(t_x > t_y){
		while(Math.pow(2,res) <t_x)
			res++;
	}else{
		while(Math.pow(2,res) <t_y)
			res++;
	}
	return res;
}


ABMap.prototype.getScale =function(){
	var centerpix = this.getCenterPixel();

	var poi1 = this.PixelTolatlng([centerpix[0] - 25, centerpix[1]],this.mapZoom);
	var poi2 = this.PixelTolatlng([centerpix[0] + 25, centerpix[1]],this.mapZoom);
	var distance = Math.round(this.calDistance(poi1,poi2));

	if (distance > 1000) 
	{
		distance /= 1000;
		distance = Math.round(distance) + "\u516C\u91CC";
	}
	else 
	{
		distance += "\u7C73";
	}
	return distance;
}
	
ABMap.prototype.calDistance = function(poi1,poi2){  

if(poi1[0]<-180) poi1[0] = -180;
if(poi1[0]>180) poi1[0] = 180;

if(poi2[0]<-180) poi2[0] = -180;
if(poi2[0]>180) poi2[0] = 180;

if(poi1[1]<-85.05) poi1[1] = -85.05;
if(poi1[1]>85.05) poi1[1] = 85.05;

if(poi2[1]<-85.05) poi2[1] = -85.05;
if(poi2[1]>85.05) poi2[1] = 85.05;



 var tmp1 = [this.getPai(poi1[0]),this.getPai(poi1[1])];
 var tmp2 =  [this.getPai(poi2[0]),this.getPai(poi2[1])];
 
var y_offset = (tmp1[1]-tmp2[1]);
var x_offset = (tmp1[0] - tmp2[0]);

	f = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(y_offset / 2), 2) + Math.cos(tmp1[1]) * Math.cos(tmp2[1]) * Math.pow(Math.sin(x_offset / 2), 2)));
return f * 6378137
}


ABMap.prototype.getPai = function(para){	
	return para* (Math.PI / 180);
}

ABMap.prototype.getLocation = function(str){
	var res =-1;
	for(var i=0;i<this.img_location.length;i++){
		if(str == this.img_location[i]){
			res = i;
			break;
		}
	}
	return res;
}


ABMap.prototype.checkmove = function(offset,ismoveov){

	//last slide haven't finished,new move tricked,then stop last slide.
	if(ismoveov == null){
		if(this.isOVMap && this.ovstatus)
			this.stopLastSlide();
	}

		
	this.topDiv.style.top = parseInt(this.topDiv.style.top)+offset[1] +'px';
	this.topDiv.style.left = parseInt(this.topDiv.style.left)+offset[0] +'px';
	
	this.left_location = this.left_location + offset[0];  
	this.top_location = this.top_location + offset[1];
	
	if((Math.abs(offset[0])>= this.mapWidth)||(Math.abs(offset[1])>= this.mapHeight)){
		this.checkWrap1(offset);	
	}else
		this.checkWrap(offset);
	
	if(this.isOVMap && this.ovstatus){
		var s = Math.pow(2,this.ovmap.levelgap);	
		var offset_x = offset[0]+this.ovmap.mainmap_checkmove_offx;
		var offset_y = offset[1]+this.ovmap.mainmap_checkmove_offy;	
		var t_x,t_y;
		
		t_x = Math.round(offset_x/s);
		t_y = Math.round(offset_y/s);
		
		this.ovmap.moveCenterDiv2([-t_x,-t_y]);

		this.ovmap.mainmap_checkmove_offx = offset_x - t_x*s;
		this.ovmap.mainmap_checkmove_offy = offset_y - t_y*s;
		
		if(ismoveov == null){
				this.ovmap.onMapMouseUp();
		}	
	}

}



//new checkWrap1, when offset > mapWidth/MapHeight;
//remove all the imgs, then add new imgs
ABMap.prototype.checkWrap1 = function(offset){
	
	var mapdiv = this.mapLayer;
	var tmp_n = mapdiv.childNodes.length;
	for(var i =0;i<tmp_n;i++)
		mapdiv.removeChild(mapdiv.childNodes[0]);

//add new imgs
	var img_tmpsrc_x = new Array();
	var img_tmpsrc_y =  new Array();
	var left = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var top = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;
	
	var pixel_xn = Math.floor(left/ABMap_piewidth);    
	var pixel_yn = Math.floor(top/ABMap_pieheight);

    var x_n = Math.floor((left+this.mapWidth)/ABMap_piewidth) - pixel_xn +1;
	var y_n = Math.floor((top+this.mapHeight)/ABMap_pieheight) - pixel_yn +1;
	
	var off_x = (pixel_xn - this.img_src_x[0][0])*ABMap_piewidth + this.img_src_x[0][1];
	var off_y = (pixel_yn - this.img_src_y[0][0])*ABMap_pieheight + this.img_src_y[0][1];
	
	this.img_src_x = new Array();
	this.img_src_y = new Array();
	
	for(var i=0;i<x_n;i++){
		var tmparray = [pixel_xn+i, off_x + i*ABMap_piewidth];
		this.img_src_x.push(tmparray);
	
	}
	
	for(var i=0;i<y_n;i++){
		var tmparray = [pixel_yn+i, off_y + i*ABMap_pieheight];
		this.img_src_y.push(tmparray);
	}
	
	
	this.img_location = new Array();

	for(var i=0;i<x_n;i++){
		
		for(var j=0;j<y_n;j++){
			var url = this.getURL(this.img_src_x[i][0],this.img_src_y[j][0],this.mapZoom);
			
			var imgobj = this.createImg(this.img_src_x[i][1], this.img_src_y[j][1], url);
			mapdiv.appendChild(imgobj);

			this.img_location.push("z"+this.mapZoom+"x"+this.img_src_x[i][0]+"y"+this.img_src_y[j][0]);
		}	
	}

}



ABMap.prototype.checkWrap = function(offset){
	var x_n = this.img_src_x.length;
	var y_n = this.img_src_y.length;
	

	var tmp  = 0;
	var left_n = right_n = top_n = bottom_n = 0;
	
	var mapdiv = this.mapLayer;
	
	
	tmp = this.img_src_x[0][1] + this.left_location;

	left_n = Math.ceil(tmp/256);     
	tmp =  this.img_src_x[x_n-1][1] + this.left_location - this.mapWidth;	
	right_n = -Math.ceil(tmp/256);    
	
	tmp = this.img_src_y[0][1] + this.top_location;
	top_n = Math.ceil(tmp/256);     
	tmp =  this.img_src_y[y_n-1][1] + this.top_location - this.mapHeight;	
	bottom_n = -Math.ceil(tmp/256);    
	
	if(left_n>0){
		for(var i=0;i<left_n;i++){
			var s = [this.img_src_x[0][0]-1,  this.img_src_x[0][1]-256];

			this.img_src_x.unshift(s);
			
			for(var j=0;j<this.img_src_y.length;j++){
				var ls =  "z"+this.mapZoom+"x"+s[0]+"y"+this.img_src_y[j][0];
				var url = this.getURL(s[0],this.img_src_y[j][0],this.mapZoom);

				var imgobj = this.createImg(s[1],this.img_src_y[j][1],url);				
				mapdiv.appendChild(imgobj);		
				this.img_location.push(ls);
			}
		}
	}
	
	
	if(right_n>0){
		for(var i=0;i<right_n;i++){
			var s = [this.img_src_x[this.img_src_x.length-1][0]+1,  this.img_src_x[this.img_src_x.length-1][1]+256]; 
			this.img_src_x.push(s);
			
			for(var j=0;j<this.img_src_y.length;j++){
				var ls =  "z"+this.mapZoom+"x"+s[0]+"y"+this.img_src_y[j][0];

				var url = this.getURL(s[0],this.img_src_y[j][0],this.mapZoom);

				var imgobj = this.createImg(s[1],this.img_src_y[j][1],url);

				mapdiv.appendChild(imgobj);
				this.img_location.push(ls);
				
			}
		}
	}
	
	
	if(top_n>0){
		for(var i=0;i<top_n;i++){
			var s = [this.img_src_y[0][0]-1,  this.img_src_y[0][1]-256];

			this.img_src_y.unshift(s);
			
			for(var j=0;j<this.img_src_x.length;j++){
				var ls =  "z"+this.mapZoom+"x"+this.img_src_x[j][0]+"y"+s[0];

				var url = this.getURL(this.img_src_x[j][0],s[0],this.mapZoom);

				var imgobj = this.createImg(this.img_src_x[j][1],s[1],url);
				
				mapdiv.appendChild(imgobj);
				this.img_location.push(ls);
			}
		}
	}	


	if(bottom_n > 0){
		for(var i=0;i<bottom_n;i++){
			var s =  [this.img_src_y[this.img_src_y.length-1][0]+1,  this.img_src_y[this.img_src_y.length-1][1]+256]; 
			this.img_src_y.push(s);
			
			for(var j=0;j<this.img_src_x.length;j++){
				var ls =  "z"+this.mapZoom+"x"+this.img_src_x[j][0]+"y"+s[0];

				var url = this.getURL(this.img_src_x[j][0],s[0],this.mapZoom);
				var imgobj = this.createImg(this.img_src_x[j][1],s[1],url);
				
				mapdiv.appendChild(imgobj);
				this.img_location.push(ls);
			}
		}
	}

	
	if(left_n<0){
		for(var i=0;i<Math.abs(left_n);i++){
			var s = this.img_src_x[0][0];
			this.img_src_x.shift();
			
			for(var j=0;j<this.img_src_y.length;j++){
				var ls =  "z"+this.mapZoom+"x"+s+"y"+this.img_src_y[j][0];
				var n = this.getLocation(ls);
				if(n>=0){
					mapdiv.removeChild(mapdiv.childNodes[n]);
					this.img_location.splice(n,1);
				}
			}
		}
	}
	
	if(right_n<0){	
		for(var i=0;i<Math.abs(right_n);i++){
			var len = this.img_src_x.length-1;
			var s = this.img_src_x[len][0];
			this.img_src_x.pop();
			
			for(var j=0;j<this.img_src_y.length;j++){
				var ls =  "z"+this.mapZoom+"x"+s+"y"+this.img_src_y[j][0];
				var n = this.getLocation(ls);
				if(n>=0){
					mapdiv.removeChild(mapdiv.childNodes[n]);
					this.img_location.splice(n,1);
				}
			}
		}
	}
	
	
	if(top_n<0){
		for(var i=0;i<Math.abs(top_n);i++){
			var s = this.img_src_y[0][0];
			this.img_src_y.shift();
			
			for(var j=0;j<this.img_src_x.length;j++){
				var ls =  "z"+this.mapZoom+"x"+this.img_src_x[j][0]+"y"+s;
				var n = this.getLocation(ls);
				if(n>=0){
					mapdiv.removeChild(mapdiv.childNodes[n]);
					this.img_location.splice(n,1);
				}
			}
		}
	}
	

	if(bottom_n < 0){
		for(var i=0;i<Math.abs(bottom_n);i++){
			var s = this.img_src_y[this.img_src_y.length-1][0];
			this.img_src_y.pop();
			
			for(var j=0;j<this.img_src_x.length;j++){
				var ls =  "z"+this.mapZoom+"x"+this.img_src_x[j][0]+"y"+s;
				var n = this.getLocation(ls);
				if(n>=0){
					mapdiv.removeChild(mapdiv.childNodes[n]);
					this.img_location.splice(n,1);
				}
			}
		}
	}
}

//1.stop last timeout, 2.move the left offset.
ABMap.prototype.stopLastSlide = function(){	
    if (this.slideid!=null) {
		ABMap_goQueueManager.dequeue( this.slideid );
		var tmp = this.as.length;
		var len = tmp - this.pos_test;
		//alert(this.slideid+";;;"+len+";;;"+tmp);
		var last_x = 0;
		var last_y = 0;
		for(var i=0;i<len;i++){
			//last.push( this.as[tmp-i-1]);
			last_x += this.as[tmp-i-1][0];
			last_y += this.as[tmp-i-1][1];
		}
		
		if(!(last_x==0&&last_y==0)){
			this.checkmove([last_x,last_y],false);
		}
		
		if(this.isOVMap && this.ovstatus){
			if(this.ovmap.afterBigMapSlide){
				this.ovmap.afterBigMapSlide();
				this.ovmap.afterBigMapSlide = false;
			}
		}
		this.slideid = null;
	}
}



//when slide finished,call this function
ABMap.prototype.slideBy_end = function(){	
	if(this.isOVMap && this.ovstatus){
		if(!this.ovmap.mainMapSliding){
			//if(this.isOVMap && this.ovstatus){	
				this.ovmap.onMapMouseUp();
			//}
		}else{
			if(this.ovmap.afterBigMapSlide){
				this.ovmap.afterBigMapSlide();
				this.ovmap.afterBigMapSlide = false;
			}
			this.ovmap.moveABmap_relocation();
			this.ovmap.mainMapSliding = false;
		}	
	}
	this.slideid=null;
}




ABMap.prototype.slideBy = function(offset){
	
	this.stopLastSlide();

	this.as = [];
	
	var x = offset[0];
	var y = offset[1];

    var absX = Math.abs(x);
    var absY = Math.abs(y);

    var distance = absX>absY?absX:absY;
    var steps = Math.round(distance/this.pixelsPerStep);
	
	if(steps == 0)
		return;
	
    var dx = dy = 0;

	dx = (x)/(steps*this.pixelsPerStep);
	dy = (y)/(steps*this.pixelsPerStep);

    var px=py=0;
	
    var i=0;
    while(i<steps-1){
        if (i>0){
          px+=this.as[i-1][0];
          py+=this.as[i-1][1];
        }

        var cx = px+Math.round(dx*this.pixelsPerStep);
        var cy = py+Math.round(dy*this.pixelsPerStep);
        this.as.push(new Array(cx-px,cy-py));
        i++;
    }
	if (i>0){
		px+=this.as[i-1][0];
    	py+=this.as[i-1][1];
	}
	this.as.push(new Array(x-px, y-py));
	

	this.slideid=ABMap_goQueueManager.enqueue(this.timePerStep,this,this.slide,[0]);

	this.backTo = function(){
		this.slideBy([-offset[0],-offset[1]]);
		this.backTo = function(){return null};
	}
	
}

ABMap.prototype.slide = function(pos)
{

    if (pos>=this.as.length){
		this.slideBy_end();

		return;
	}

	this.checkmove(this.as[pos],false);
	
    pos ++;
	this.pos_test = pos;
	
    this.slideid=ABMap_goQueueManager.enqueue(this.timePerStep,this,this.slide,[pos]);
	
}



ABMap.prototype.getCenterPixel = function(){
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location + Math.ceil(this.mapWidth/2);
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location + Math.ceil(this.mapHeight/2);
	
	return [leftpix,toppix];	
}


ABMap.prototype.setMapCenter =function(centerStr){
	if(centerStr){
		var cpix = this.getCenterPixel();
		var coord = ABMap_getCoord(centerStr);
		var pix = this.latlngToPixel(coord,this.mapZoom);
		var offsetx = cpix[0] - pix[0];
		var offsety = cpix[1] - pix[1];
		this.checkmove([offsetx,offsety]);
	}
}

ABMap.prototype.setMapCenterByPix =function(centerStr){	

	var cpix = this.getCenterPixel();
	var pix = centerStr;
	
	var offsetx = cpix[0] - pix[0];
	var offsety = cpix[1] - pix[1];
	this.checkmove([offsetx,offsety]);

}


ABMap.prototype.getMapCenter = function(){
	var pixcenter = this.getCenterPixel();	
	var res = this.PixelTolatlng(pixcenter,this.mapZoom);		
	return res;		
}

ABMap.prototype.getMapCenterGrid = function(){
	var center = this.getMapCenter();	
	var prj=new ABMap_GridCodeFun();
	return prj.getGridCode(center);
}

ABMap.prototype.setMapZoom = function(zoomStr){	
	this.zoomTo(zoomStr);
}
	
ABMap.prototype.getMapZoom = function(){	
	return this.mapZoom;
}
	
ABMap.prototype.setMapSize = function(sizeStr){
	 var tmp = this.getCenterPixel();	
	 
	 var offset_x = Math.ceil((sizeStr[0] - this.mapWidth)/2);
	 var offset_y = Math.ceil((sizeStr[1] - this.mapHeight)/2);

	 tmp[0] = tmp[0] + offset_x;
	 tmp[1] = tmp[1] + offset_y;
	 
	this.mapWidth = sizeStr[0];
	this.mapHeight = sizeStr[1];
	this.refreshLogo();
	this.refreshScaleBar();	
	this.refreshZoomBarLoc();
	
	this.mapDom.style.width = this.mapWidth+"px";
	this.mapDom.style.height = this.mapHeight+"px";

	this.mapDom.childNodes[1].style.width = this.mapWidth+"px";
	this.mapDom.childNodes[1].style.height = this.mapHeight+"px";
	
	this.fromPixelToImg(tmp);		
	this.patchUpImg();
	
	this.refreshAcete();
	//this.zoomToPois();
	
	if(this.isOVMap)
		this.refreshOverviewMap();
	
	
}
	
ABMap.prototype.getMapSize = function(){
	
	return [this.mapWidth,this.mapHeight];
	
}






ABMap.prototype.getMapExtentFP = function(args){
	if(this.aceteObj.length<2)
		return null;
	
	var coord = ABMap_getCoord(this.aceteObj[0].coord);
	var maxX = coord[0];
	var minX = maxX;
	var maxY = coord[1];
	var minY = maxY;
	
	
	for(var i =1;i<this.aceteObj.length;i++){
		coord = ABMap_getCoord(this.aceteObj[i].coord);
		
		if(maxX<coord[0])
			maxX = coord[0];
		
		if(minX>coord[0])
			minX = coord[0];
		
		if(maxY<coord[1])
			maxY = coord[1];

		if(minY>coord[1])
			minY = coord[1];
	}
	
	var tmpX = (maxX - minX)/5;
	var tmpY = (maxY - minY)/5;
	
	if(args == 0){
		tmpX = 0;
	 	tmpY = 0;
	}
	
	return [maxX+tmpX,minX-tmpX,maxY+tmpY,minY-tmpY];	
}



ABMap.prototype.zoomToPois = function(args){
	if(this.aceteObj == null)
		return;
		
	if(this.aceteObj.length == 0)
		return;
	
	var cpix = this.getCenterPixel();
	if(this.aceteObj.length == 1){
		var pointObject = this.aceteObj[0];
		var coord = ABMap_getCoord(pointObject.coord);
		
		var pix = this.latlngToPixel(coord,this.mapZoom);
		var offsetx = cpix[0] - pix[0];
		var offsety = cpix[1] - pix[1];
		this.checkmove([offsetx,offsety]);
		//this.setMapCenter(pointObject.coord);
	}else 
	if(this.aceteObj.length > 1){
		var ex = this.getMapExtentFP(args);
		var zoomvalue = this.getZoomValue(ex[0],ex[1],ex[2],ex[3]);
		var centerx = (ex[0]+ex[1])/2;
		var centery = (ex[2]+ex[3])/2;

		var pix = this.latlngToPixel([centerx,centery],this.mapZoom);
		if(zoomvalue == this.mapZoom){
			
			var offsetx = cpix[0] - pix[0];
			var offsety = cpix[1] - pix[1];
			this.checkmove([offsetx,offsety]);
			this.refreshAcete();
		}else{
			this.zoomToByPixel_c(zoomvalue,pix);
		}
	}

}



ABMap.prototype.addPoint = function(pointObject){
	if(this.aceteObj == null)
		this.aceteObj = new Array();
	
	this.aceteObj.push(pointObject);	
	
	//this.zoomToPois();	 //not suggested
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;
	
	var pois = ABMap_getCoord(pointObject.coord);
	var pix = this.latlngToPixel(pois,this.mapZoom);
	
	var tmp = [(pix[0]-leftpix),(pix[1]-toppix)];
	
	var divtmp = document.createElement('div');
	divtmp.style.position = 'absolute';	
	divtmp.style.left = tmp[0] +'px';
	divtmp.style.top = tmp[1] +'px';
	divtmp.style.zIndex =this.aceteObj.length;
	
	divtmp.id = pointObject.serial_id+"div";
	var zindextmp = this.aceteObj.length;
	divtmp.poiObj_index = zindextmp-1;
	var Img = null;



	if(pointObject.pointStyle.moreIcon != null){
		var moreIconLen = pointObject.pointStyle.moreIcon.length;
		for(var i=0;i<moreIconLen;i++){
			var moreIconTmp = pointObject.pointStyle.moreIcon[i];

			var Imgtmp = document.createElement('img');
			Imgtmp.style.position = 'absolute';
			Imgtmp.style.left = moreIconTmp.offsetX +'px';
			Imgtmp.style.top = moreIconTmp.offsetY+'px';
		
			Imgtmp.style.width= moreIconTmp.iconWidth+'px';
			Imgtmp.style.height= moreIconTmp.iconHeight+'px';
			Imgtmp.src = moreIconTmp.iconURL;
			divtmp.appendChild(Imgtmp);	
		}
	}

	//show img
	if(pointObject.pointStyle.hasIcon){
		Img = document.createElement('img');
		//Img.id = 'iconimg';
		Img.style.position = 'absolute';
		Img.style.left = pointObject.pointStyle.offset.iconX +'px';
		Img.style.top = pointObject.pointStyle.offset.iconY+'px';
	
		Img.style.width= pointObject.pointStyle.size.iconWidth+'px';
		Img.style.height= pointObject.pointStyle.size.iconHeight+'px';
		Img.src = pointObject.pointStyle.iconURL;
		divtmp.appendChild(Img);	
	}
	
	var map = this;
	// bus label
	if(pointObject.pointStyle.showBusLabel>0&& pointObject.pointStyle.busLabelObj != null){
		var labeldiv = document.createElement('div');
		labeldiv.id = 'buslabel';
		labeldiv.style.cursor = "default";
		labeldiv.style.position = 'absolute';
		labeldiv.style.left = pointObject.pointStyle.busLabelObj.offsetX +'px';
		labeldiv.style.bottom = pointObject.pointStyle.busLabelObj.offsetY+'px';
		labeldiv.innerHTML = pointObject.pointStyle.busLabelObj.labelContent;
	    
		
		Img.onclick = function(){		
			if(map.mapZoom == 2){
				var pix1 = map.getCenterPixel();	
				var pix_old = map.latlngToPixel(pois,2);
				var x = -pix_old[0] + pix1[0];
				var y = -pix_old[1] + pix1[1];
				map.checkmove([x,y]);
				
			}else{
				//this.zoomToByPixel_c(3,pix);
				map.zoomToBylatlng_c(2,pois);
			}
		}
		
		if(pointObject.pointStyle.showBusLabel == 1){
			labeldiv.style.visibility = "hidden";
			//需要img响应事件
			Img.onmouseover = function(){
				labeldiv.style.visibility = "visible";
				divtmp.style.zIndex = 200;
			}
			
			Img.onmouseout = function(){
				labeldiv.style.visibility = "hidden";
				divtmp.style.zIndex =divtmp.poiObj_index+1;
			}
		}
		divtmp.appendChild(labeldiv);	
	
	}
	
	
	//show label
	if(pointObject.pointStyle.showLabel){
		var labeldiv = document.createElement('div');
		labeldiv.style.cursor = "default";
		labeldiv.style.position = 'absolute';
		labeldiv.name = 'label';
		labeldiv.style.right = pointObject.pointStyle.offset.labelX +'px';
		labeldiv.style.bottom = pointObject.pointStyle.offset.labelY+'px';
		//labeldiv.style.width = "120px";
		labeldiv.innerHTML = pointObject.pointStyle.labelContent;
		
		labeldiv.onmouseover = function(){
			if(this.childNodes[0]){
				divtmp.style.zIndex = 100;
				this.childNodes[0].className = pointObject.pointStyle.labelClass2;
				
			}
		}
		
		labeldiv.onmouseout = function(){
			var index = zindextmp-1;
			if(this.childNodes[0]){//&& window["is_label_click"]!= index){
				
				if(typeof window["is_label_click"] != "undefined"){
					if(window["is_label_click"] == index)
						return;
				}
				
				divtmp.style.zIndex = zindextmp;
				this.childNodes[0].className = pointObject.pointStyle.labelClass;
			}
		
		}
		
		
		
		labeldiv.onclick = function(){
			var index = zindextmp-1;
			map.centerLabelByIndex.apply(map,[index]);
		
		}
			
		divtmp.appendChild(labeldiv);	
	}
	
	//show tip
	if(pointObject.pointStyle.tipParam != null&&pointObject.pointStyle.showTip){
		var t = this;
		
		Img.onclick = function(){
			var index = zindextmp-1;
			t.showTipDivByIndex.apply(t,[index]);
		};
	}	
	
	
	// show big icon
	if(pointObject.pointStyle.showBigIcon){
		Img.onmouseover = function(){
			Img.style.left = pointObject.pointStyle.offset.iconX2 +'px';
			Img.style.top = pointObject.pointStyle.offset.iconY2+'px';
		
			Img.style.width= pointObject.pointStyle.size.iconWidth2+'px';
			Img.style.height= pointObject.pointStyle.size.iconHeight2+'px';
			Img.src = pointObject.pointStyle.iconURL2;
			
			divtmp.style.zIndex = 100;
		}
		
		Img.onmouseout = function(){
			Img.style.left = pointObject.pointStyle.offset.iconX +'px';
			Img.style.top = pointObject.pointStyle.offset.iconY+'px';
		
			Img.style.width= pointObject.pointStyle.size.iconWidth+'px';
			Img.style.height= pointObject.pointStyle.size.iconHeight+'px';
			Img.src = pointObject.pointStyle.iconURL;
			
			divtmp.style.zIndex = zindextmp;
		}
		
		//open a new window
		Img.onclick = function(){
			var urltmp = pointObject.pointStyle.linkURL;
			window.open(urltmp,"_blank") 
		}
	
	}	
	
	
	//show bubble
	if(pointObject.pointStyle.bubbleParam != null&&pointObject.pointStyle.showBubble){

		var t = this;
		Img.onmouseover = function(){
			var index = zindextmp-1;
			t.showBubbleDivByIndex.apply(t,[index]);
		}
		
		Img.onmouseout = function(){
			var index = zindextmp-1;
			t.hideBubbleDivByIndex.apply(t,[index]);
		}
	}
	
	
	
	
	
	
	
	this.aceteLayer.childNodes[1].appendChild(divtmp);		
}




ABMap.prototype.changeLabelClsById = function(id,cls){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.changeLabelClsByIndex(n,cls);
}



ABMap.prototype.changeLabelClsByIndex = function(index,cls){
	var n = index;
	var pointObject = this.aceteObj[n];	
	
	
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	
	var ind = 0;
	for(;ind<s.childNodes.length;ind++){
		if(s.childNodes[ind].name){
			if(s.childNodes[ind].name == "label")
			break;
		}
	}
	
	var r = s.childNodes[ind];
	
	if(r.childNodes[0]){
		if(cls == 1){
			s.style.zIndex = n+1;
			r.childNodes[0].className = pointObject.pointStyle.labelClass;
		}
		else if(cls == 2){			
			s.style.zIndex = 100;
			r.childNodes[0].className = pointObject.pointStyle.labelClass2;
		}
		else{
			r.childNodes[0].className = cls;
			//change zIndex
			if(cls == pointObject.pointStyle.labelClass)
				s.style.zIndex = n+1;
			else if(cls == pointObject.pointStyle.labelClass2)
				s.style.zIndex = 100;
		}
	}
	
}



ABMap.prototype.centerLabelById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.centerLabelByIndex(n);
}


ABMap.prototype.centerLabelByIndex = function(index){
	
	var n = index;
	if(n == -1)
		return ;
	
	var pointObject = this.aceteObj[n];

	var pois = ABMap_getCoord(pointObject.coord);
	var pix = this.latlngToPixel(pois,this.mapZoom);

	if(this.mapZoom == 3){
		var pix1 = this.getCenterPixel();		
		var x = -pix[0] + pix1[0];
		var y = -pix[1] + pix1[1];
		this.checkmove([x,y]);
		
	}else{
		//this.zoomToByPixel_c(3,pix);
		this.zoomToBylatlng_c(3,pois);
	}
	
	if(this.isLabelTip){
		this.currentTipIndex = n;  
		//add tip for label
		var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1];
		var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1];
		pix = this.latlngToPixel(pois,this.mapZoom);
		
		var tmp = [(pix[0]-leftpix),(pix[1]-toppix)];	
		var t = this.aceteLayer.firstChild;  //tip div
		t.style.display = 'block';	
		t.style.left = (tmp[0] +25) + 'px';
		t.style.top = ( tmp[1]-75) + 'px';
	}
	
	try{
		centerLabel_callback(n);
	}catch(error){}
}


//buslabel 居中并修改显示比例尺
ABMap.prototype.centerBusLabelById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.centerBusLabelByIndex(n);
}

//buslabel 居中并修改显示比例尺
ABMap.prototype.centerBusLabelByIndex = function(index){
	
	var n = index;
	if(n == -1)
		return ;
	
	var pointObject = this.aceteObj[n];

	var pois = ABMap_getCoord(pointObject.coord);
	var pix = this.latlngToPixel(pois,this.mapZoom);

	if(this.mapZoom == 2){
		var pix1 = this.getCenterPixel();		
		var x = -pix[0] + pix1[0];
		var y = -pix[1] + pix1[1];
		this.checkmove([x,y]);
		
	}else{
		//this.zoomToByPixel_c(3,pix);
		this.zoomToBylatlng_c(2,pois);
	}
}

//buslabel 显示buslabel
ABMap.prototype.showBusLabelById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.showBusLabelByIndex(n);
}

//buslabel 显示buslabel
ABMap.prototype.showBusLabelByIndex = function(index){
	
	var n = index;
	if(n == -1)
		return ;
	
	var pointObject = this.aceteObj[n];	
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	var len = s.childNodes.length;
	for(var i=0;i<len;i++){
		if(s.childNodes[i].id == 'buslabel'){
			s.style.zIndex = 200;
			s.childNodes[i].style.visibility = "visible";
			break;
		}
	}
}


//buslabel 显示buslabel
ABMap.prototype.unshowBusLabelById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.unshowBusLabelByIndex(n);
}


//buslabel 显示buslabel
ABMap.prototype.unshowBusLabelByIndex = function(index){
	
	var n = index;
	if(n == -1)
		return ;
	
	var pointObject = this.aceteObj[n];	
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	var len = s.childNodes.length;
	for(var i=0;i<len;i++){
		if(s.childNodes[i].id == 'buslabel'){
			s.style.zIndex =s.poiObj_index+1;
			s.childNodes[i].style.visibility = "hidden";
			break;
		}
	}
}



ABMap.prototype.showBigIconById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.showBigIconByIndex(n);
}


ABMap.prototype.showBigIconByIndex = function(index){
	var n = index;
	var pointObject = this.aceteObj[n];	
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	var Img = s.firstChild;
	
	Img.style.left = pointObject.pointStyle.offset.iconX2 +'px';
	Img.style.top = pointObject.pointStyle.offset.iconY2+'px';

	Img.style.width= pointObject.pointStyle.size.iconWidth2+'px';
	Img.style.height= pointObject.pointStyle.size.iconHeight2+'px';
	Img.src = pointObject.pointStyle.iconURL2;
	
	s.style.zIndex = 100;

}


ABMap.prototype.unshowBigIconById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.unshowBigIconByIndex(n);
}


ABMap.prototype.unshowBigIconByIndex = function(index){
	var n = index;
	var pointObject = this.aceteObj[n];
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	var Img = s.firstChild;
	
	Img.style.left = pointObject.pointStyle.offset.iconX +'px';
	Img.style.top = pointObject.pointStyle.offset.iconY+'px';

	Img.style.width= pointObject.pointStyle.size.iconWidth+'px';
	Img.style.height= pointObject.pointStyle.size.iconHeight+'px';
	Img.src = pointObject.pointStyle.iconURL;
	
	if(n != -1){
		s.style.zIndex = n+1;
	}

}


ABMap.prototype.selectPointDivById = function(id){
    var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;		
	var pointObject = this.aceteObj[n];
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;

	var pois = ABMap_getCoord(pointObject.coord);
	var pix = this.latlngToPixel(pois,this.mapZoom);
	
	var tmp = [(pix[0]-leftpix),(pix[1]-toppix)];


	if(tmp[0]>=0 && tmp[0] <=this.mapWidth && tmp[1] >=0 && tmp[1] <= this.mapHeight){
		var b = this.screenDiv.firstChild;  //ABBubbleDiv
		
		b.style.display = 'none';
		
		b.style.right = (-tmp[0] - 64) +'px';
		b.style.top = (tmp[1])+'px';
		
		b.innerHTML = "";
		
	}
	
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	s.firstChild.src = pointObject.pointStyle.iconURL2;
	s.style.zIndex = 100;
}

ABMap.prototype.unSelectPointDivById = function(id){
    var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
    var b = this.screenDiv.firstChild;//$('ABBubbleDiv');
	
	b.style.display = 'none';
	b.innerHTML = "";
	
	var pointObject = this.aceteObj[n];
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	
	s.firstChild.src = pointObject.pointStyle.iconURL;
	
	if(n != -1){
		s.style.zIndex = n+1;
	}
}




ABMap.prototype.getAceteObjIndex = function(id){
	var n = -1;
	if(this.aceteObj != null){
		for(var i =0;i<this.aceteObj.length;i++){
			if(this.aceteObj[i].serial_id == id){
				n = i;
				break;
			}
		}
	}
	return n;

}

	
	
//only for tip, not for bubble
ABMap.prototype.removePoint = function(id){
	var n = this.getAceteObjIndex(id);
	
	if(n==-1) return;
	
	this.aceteObj[n] = null;
	this.aceteObj.splice(n,1);
	var l = this.aceteLayer.childNodes[1];
	
	var len = l.childNodes.length;
	for(var i=n+1;i<len;i++){
		var tmp = l.childNodes[i];
		tmp.poiObj_index = tmp.poiObj_index-1;
	}
	
	l.removeChild(l.childNodes[n]);

	if(this.currentTipIndex == n){
		this.closeTipWindow();
	}
}

ABMap.prototype.removeAllPoint = function(){
	
	var l = this.aceteLayer.childNodes[1];
	var len = l.childNodes.length;
	for(var i=0;i<len;i++){
		l.removeChild(l.childNodes[0]);
		this.aceteObj[i] = null;
	}
	
	this.aceteObj = null;
	this.closeTipWindow();

}


ABMap.prototype.setCursor = function(curname){
	this.mapDom.style.cursor = curname; 
}


function ABMapTool(mymap) {	
	this.ABMap = mymap;
	this.downpoi = [0,0];
	
	this.firstdown = [0,0];
	
	this.isMouseDown = false;
	
	this.lastCursor = "default";
	
	this.drawStatus = -1;
	this.clientPOI = null;
}	
	
ABMapTool.prototype.MyTool_onmousedown  = function(e){
	
		e = (e)?e:((event)?event:null);
		var x = e.clientX;
		var y = e.clientY;

		//this.lastCursor = this.ABMap.mapDom.style.cursor;
		this.ABMap.mapDom.style.cursor = 'move';
		
		this.downpoi[0] = x;
		this.downpoi[1] = y;
	    this.firstdown = [x,y];
		this.isMouseDown = true;
		
		var t = this;
		document.onmousemove = function(e){
			
			t.MyTool_onmousemove(e);
			
			return false;
		}
		
		document.onmouseup = function(e){
			
			t.MyTool_onmouseup(e);
			return false;
		}
		
		
		if(this.drawStatus == 1){
			this.clientPOI = [x,y];
		}

}


ABMapTool.prototype.MyTool_onmousemove  = function(e){
	
	if(this.isMouseDown){
		e = (e)?e:((event)?event:null);
		var x = e.clientX;
		var y = e.clientY;
		
		var offset = [x - this.downpoi[0], y - this.downpoi[1]];
		this.downpoi[0] = x;
		this.downpoi[1] = y;
		this.ABMap.checkmove(offset,false);
	}
}
	
ABMapTool.prototype.MyTool_onmouseup  = function(e){
	e = (e)?e:((event)?event:null);
	

	
	var x = e.clientX;
	var y = e.clientY;
	
	if(this.isMouseDown)
		this.isMouseDown = false;
	
	this.ABMap.mapDom.style.cursor = "pointer";

	document.onmousemove = null;
	document.onmouseup = null;
	
	var offset_x = this.firstdown[0]-x;
	var offset_y = this.firstdown[1]-y;
	/*
	if(offset_x ==0 && offset_y == 0)
		this.ABMap.checkmove([0,0],false);
	*/
	
	this.ABMap.backTo = function(){
		
		this.slideBy([offset_x,offset_y]);
		this.backTo = function(){return null};
	}
	
	//draw point
	if(this.drawStatus == 1){
		this.ABMap.setCursor("url(images/map/pointer3.cur), move;");
		if(this.clientPOI!=null && x == this.clientPOI[0] && y == this.clientPOI[1]){
			var pix = ABMap_getMapDivPix(e);

			this.ABMap.drawPoint_postimg(pix);
			
			try{
				drawPoint_callback();
			}catch(e){}
		}
		
		
	}
	
	if(this.ABMap.isOVMap && this.ABMap.ovstatus){
		//this.ABMap.ovmap.moveCenterDiv2(offset);
		this.ABMap.ovmap.onMapMouseUp();

	}
	
	// refresh scale value
	var s = this.ABMap.getScale();
	this.ABMap.refreshScale(s);
	
	return false;
}




function ABPointObject(){
	this.serial_id = null;
	this.coord = null;
	this.pointStyle = new ABPointStyle();
	
}


function ABPointMoreIcon(){
	this.iconURL = null;
	this.iconWidth = 0;
	this.iconHeight = 0;
	this.offsetX = 0;
	this.offsetY = 0; 
	
}

function ABBusLabel(){
	this.labelContent = "";
	this.offsetX = 0;
	this.offsetY = 0; 
	
}


function ABPointStyle(){
	this.hasIcon = true;
	this.showLabel = false;
	this.showTip = false;	
	this.showBubble = false;
	this.showBigIcon = false;
	
	//090223 新增
	this.showBusLabel = 0;  //为公交服务的.0为不考虑公交,1为在icon上响应onmouserove/click事件. 2为什么事件都不响应.
	this.busLabelObj = null;
	this.moreIcon = null;  //array类型,ABPointMoreIcon类型,存放图片地址.当不为空时,取出所有地址,作为该点的
	
	this.iconURL="http://mapengine.mapabc.com/mapabcrasterengine/api/mapFiles/images/star.png";
	this.iconURL2="http://mapengine.mapabc.com/mapabcrasterengine/api/mapFiles/images/star.png";
	this.size = new function(){
		this.iconWidth = 0;
		this.iconHeight = 0;
		this.iconWidth2 = 0;
		this.iconHeight2 = 0;
	};
	
	this.size.iconWidth = 30;
	this.size.iconHeight = 50;	
	
	this.offset = new function(){
		this.iconX = 0;
		this.iconY = 0; 
		this.iconX2 = 0;
		this.iconY2 = 0; 
		this.infoWindowX = 0;
		this.infoWindowY = 0;
		this.labelX = 0;
		this.labelY = 0;
	};
	
	this.offset.iconX = 0;
	this.offset.iconY = 0; 
	this.offset.iconX2 = 0;
	this.offset.iconY2 = 0; 
	this.offset.infoWindowX = 0;
	this.offset.infoWindowY = 0;
	this.offset.labelX = 0;
	this.offset.labelY = 0;
	this.labelContent = "test";
	this.labelClass = "cls1";
	this.labelClass2 = "cls2";
	
	
	this.maxdisscroll = 12;
	this.mindisscroll = 4;
	
	
	this.tipId = "di1";
	this.tipParam = null;
	this.bubbleParam = null;
	this.linkURL = null;
}






//setTimeOut && clearTimeOut
var ABMap_goQueueManager = new ABMap_queueManager();

function ABMap_queueManager()
{
    this.queue = new Array();
}

ABMap_queueManager.prototype.enqueue = function( timeout, obj, func, args )
{

    var pos = this.queue.length;
    for (var i=0; i< this.queue.length; i++)
    {
        if (this.queue[i] == null)
        {
            pos = i;
            break;
        }
    }
    var id = window.setTimeout( "ABMap_queueManager_execute("+pos+")", timeout );
    this.queue[pos] = new Array( id, obj, func, args );
    return pos;
}

ABMap_queueManager.prototype.dequeue = function( pos )
{

    if (this.queue[pos] != null)
    {
        window.clearTimeout( this.queue[pos][0] );
        this.queue[pos] = null;
    }
}

function ABMap_queueManager_execute( pos )
{
    if (ABMap_goQueueManager.queue[pos] != null)
    {
        var obj = ABMap_goQueueManager.queue[pos][1];
        var func = ABMap_goQueueManager.queue[pos][2];
        if (ABMap_goQueueManager.queue[pos][3] != null)
            func.apply( obj, ABMap_goQueueManager.queue[pos][3] );
        else
            func.apply( obj );
        ABMap_goQueueManager.queue[pos] = null;
    }
}

/* - secMap.js - */

var uGb={"__KEYCOUNT__":256,"__keys__":[[0,2,1,2,8,9,4,1,7,2,5,3,9],[0,3,2,2,9,5,8,2,6,8,4,6,3],[1,5,2,7,1,4,7,2,4,1,4,3,0],[0,7,8,3,4,9,0,6,7,7,4,4,2],[0,2,1,8,4,9,3,2,3,1,5,7,8],[0,0,9,5,4,7,3,0,8,7,5,2,8],[0,1,5,1,1,8,2,7,1,9,1,3,5],[0,5,2,5,6,0,3,4,6,7,1,3,5],[1,3,2,1,8,1,8,3,7,9,2,7,0],[1,2,7,7,4,3,1,5,5,0,6,4,4],[1,5,2,8,9,2,5,9,6,7,3,3,5],[1,7,9,4,5,0,9,4,9,6,1,9,9],[0,6,8,3,3,6,3,5,2,0,0,9,1],[1,1,1,4,7,8,6,9,6,8,8,4,6],[0,5,2,1,2,5,7,0,0,4,7,4,1],[0,7,6,4,2,3,9,0,7,8,5,6,7],[0,1,7,6,0,5,4,7,6,7,7,5,7],[0,5,2,9,8,1,7,8,3,8,5,4,5],[0,4,3,1,2,8,3,7,0,9,4,8,8],[1,0,6,7,9,4,3,5,2,9,8,7,7],[1,6,4,4,6,7,1,4,4,2,6,7,5],[0,8,1,7,7,5,2,6,4,3,9,7,5],[1,7,0,5,6,2,5,2,7,4,6,2,8],[0,4,9,2,3,0,5,4,7,8,7,0,5],[1,1,0,5,1,7,2,8,7,2,6,9,3],[1,4,2,3,6,1,5,3,2,0,3,6,2],[1,1,6,5,1,0,6,8,9,7,1,7,9],[0,6,5,4,0,7,1,7,6,2,5,4,2],[1,9,8,6,6,6,8,4,5,4,0,4,0],[1,2,7,1,5,0,6,8,0,1,3,7,9],[1,1,6,4,9,8,6,0,6,2,1,9,8],[0,0,1,9,5,3,3,9,6,7,4,1,1],[0,2,8,5,7,8,6,7,3,3,1,6,4],[1,8,2,5,8,4,7,6,8,8,5,7,6],[0,8,3,4,9,6,1,7,8,3,0,5,5],[1,3,2,6,7,4,2,8,7,4,9,6,8],[1,8,8,9,3,9,1,8,5,7,2,5,0],[0,5,8,3,1,8,8,0,3,9,3,8,1],[1,6,0,1,1,0,3,4,3,3,3,5,9],[1,0,5,1,7,9,6,2,4,6,0,3,5],[1,8,2,0,9,7,1,0,5,5,8,0,6],[1,8,9,6,7,3,9,4,1,9,6,6,2],[0,6,0,0,8,2,6,5,9,4,1,6,2],[1,7,9,7,9,4,4,2,1,1,5,7,4],[1,3,0,4,3,4,6,8,6,9,1,7,0],[0,1,2,3,9,4,1,8,7,2,2,9,8],[1,6,5,3,2,7,6,6,9,0,0,7,7],[1,6,8,4,9,7,8,0,3,6,5,4,8],[0,6,6,0,9,9,4,5,5,6,8,3,7],[1,0,1,3,4,0,0,1,4,8,5,7,0],[1,0,2,5,8,2,2,4,8,9,7,1,6],[1,4,2,6,6,8,4,5,6,6,4,5,9],[1,4,4,1,7,2,0,4,6,3,3,6,7],[0,2,2,3,8,0,0,8,6,0,2,1,7],[0,9,4,4,8,1,2,7,3,2,6,8,0],[0,9,8,4,2,1,4,5,2,4,9,5,1],[0,7,2,4,7,4,3,2,4,1,5,6,9],[1,1,8,4,8,8,8,4,3,4,1,2,5],[0,3,2,7,5,7,0,2,7,4,5,3,5],[0,3,0,4,6,6,6,5,7,2,1,9,5],[1,5,6,0,1,3,2,7,3,0,9,8,6],[0,5,5,1,7,1,0,7,9,0,3,5,7],[0,5,4,9,7,9,7,3,8,0,1,6,3],[1,9,2,7,3,7,9,4,3,9,8,8,2],[0,3,1,8,9,0,9,0,4,5,5,0,9],[1,8,6,1,7,7,2,4,7,9,2,0,8],[0,6,1,2,7,1,4,8,4,1,1,6,0],[0,3,9,8,5,5,3,0,8,7,9,3,5],[0,8,4,3,7,3,1,8,2,9,1,4,7],[0,1,5,3,4,0,5,5,5,8,0,7,2],[0,1,7,1,8,2,1,9,8,6,1,7,0],[0,7,1,6,9,7,2,7,2,4,4,3,6],[0,6,2,7,2,3,4,9,3,0,1,6,3],[0,2,9,1,9,9,9,1,9,5,4,4,4],[0,1,8,7,0,0,5,2,1,5,7,4,6],[1,9,0,8,7,3,3,5,5,4,9,0,1],[1,5,8,0,1,7,0,2,3,7,3,2,9],[1,3,2,0,5,2,7,5,0,2,6,8,1],[0,2,7,2,3,2,2,9,6,9,4,1,6],[1,6,4,7,9,6,5,9,5,8,2,7,1],[1,8,1,2,6,0,2,4,0,8,0,1,6],[1,6,2,4,1,2,4,1,7,2,7,0,6],[0,1,8,0,5,0,4,5,5,1,0,4,7],[0,8,7,6,4,3,5,5,7,8,4,9,0],[0,2,7,7,0,1,6,6,1,0,9,3,5],[0,7,6,9,8,3,8,6,2,9,3,7,0],[1,6,6,6,0,3,0,1,0,2,5,6,1],[0,0,4,5,1,0,9,4,4,9,4,0,9],[0,1,6,9,4,7,5,7,8,3,5,7,0],[1,2,7,1,6,6,1,5,2,8,6,3,8],[1,9,1,6,7,5,1,7,4,7,6,1,8],[1,7,6,7,0,2,9,6,9,8,6,7,8],[0,9,8,7,3,8,1,5,2,5,2,7,5],[0,7,3,5,7,9,7,6,6,9,1,7,5],[1,6,7,3,4,4,7,6,2,6,6,2,3],[0,1,4,2,2,8,5,0,9,2,7,3,1],[0,1,4,2,1,0,0,2,1,8,9,8,3],[1,7,0,8,7,9,9,6,4,8,6,2,2],[1,9,3,9,9,8,7,0,8,1,1,7,3],[1,0,4,3,5,8,0,4,6,5,4,5,8],[0,4,8,0,5,2,3,2,3,9,4,2,3],[0,7,9,0,9,7,2,7,7,0,4,8,5],[1,6,5,5,3,3,2,6,1,3,4,7,1],[0,2,9,0,0,2,9,1,8,8,2,8,4],[1,3,2,5,0,6,2,5,3,3,6,1,1],[1,9,2,9,3,3,8,9,9,7,2,3,7],[1,1,8,4,0,8,2,4,8,0,0,9,2],[1,5,2,6,0,6,1,3,0,4,7,3,8],[1,9,3,8,1,1,7,8,6,9,0,6,8],[1,3,2,7,7,2,2,4,2,5,8,3,0],[1,1,1,0,7,7,3,4,7,3,6,6,8],[0,9,4,2,8,9,4,8,4,3,2,5,3],[0,1,0,9,2,7,2,3,9,4,5,0,8],[1,0,4,5,8,4,0,0,5,2,2,1,2],[0,5,0,4,5,3,2,5,4,1,3,6,9],[1,3,0,2,7,8,1,7,7,3,5,5,9],[1,3,7,0,0,5,8,1,7,5,6,5,2],[1,8,1,9,9,9,4,8,6,0,7,7,3],[0,8,3,6,2,7,4,2,1,9,1,6,8],[0,4,4,4,2,6,0,4,0,1,5,1,7],[1,2,7,4,7,6,6,6,3,7,7,2,9],[0,9,8,9,3,3,3,9,0,7,4,2,3],[0,7,6,0,9,1,7,2,4,5,8,3,3],[1,6,1,5,5,3,1,3,2,1,0,5,6],[0,6,2,4,1,6,6,3,4,9,2,7,0],[1,6,3,2,3,6,1,7,7,5,6,7,1],[1,0,4,9,2,3,3,6,2,6,9,3,2],[0,3,7,3,9,1,3,9,5,8,5,8,9],[1,9,0,0,3,0,9,1,2,7,8,0,3],[1,0,1,2,7,7,0,0,1,8,4,1,1],[0,0,5,5,9,6,9,8,1,2,1,7,2],[0,1,8,7,9,0,3,5,6,3,2,9,4],[1,3,1,5,7,5,0,8,5,3,2,5,0],[1,1,7,3,5,0,7,7,9,6,8,9,0],[0,7,7,0,9,4,2,8,8,0,2,2,0],[1,6,5,8,3,1,0,9,0,2,7,2,9],[1,3,5,8,4,7,6,3,1,4,3,4,7],[0,8,8,7,8,2,7,0,3,9,6,2,9],[1,1,6,2,6,7,5,2,5,0,8,5,5],[0,9,6,7,3,0,2,3,9,5,3,7,4],[1,5,2,7,3,6,0,8,3,3,9,0,3],[0,3,6,8,9,1,7,7,3,8,7,3,8],[0,1,2,5,4,9,8,0,3,6,4,0,4],[1,2,4,1,6,8,1,5,8,3,6,4,3],[1,9,3,1,0,8,4,4,0,1,6,0,8],[0,4,5,1,0,2,1,7,1,6,1,3,3],[0,9,5,6,8,2,2,4,0,3,9,8,1],[1,9,3,5,4,3,1,2,2,2,0,8,7],[0,5,6,8,1,5,7,7,8,9,4,0,6],[1,0,4,6,4,6,7,4,6,0,3,6,2],[1,3,3,0,2,5,3,1,9,2,3,6,8],[0,6,9,6,3,6,9,6,2,1,5,0,7],[1,6,5,3,0,0,0,6,2,3,8,6,0],[1,0,7,1,2,0,3,0,3,0,8,8,0],[0,7,1,4,3,1,8,6,7,8,1,5,4],[0,6,3,5,5,4,8,9,4,8,3,1,7],[0,6,4,3,1,0,7,2,9,0,5,6,7],[0,6,3,7,7,0,6,8,6,7,4,6,0],[0,4,2,7,2,4,1,4,6,1,8,1,7],[1,1,7,9,0,7,0,5,1,8,6,3,5],[1,2,0,2,7,2,7,9,1,2,7,0,3],[0,3,3,6,2,0,9,1,1,0,3,5,8],[1,4,0,9,9,2,5,6,5,6,8,0,5],[0,3,5,3,3,3,4,6,7,5,7,0,5],[0,5,8,8,5,8,5,4,7,0,5,7,3],[0,5,0,7,6,4,2,7,8,3,6,1,4],[0,4,7,8,6,5,3,7,7,5,7,0,7],[1,3,6,5,3,0,8,5,4,9,7,7,1],[1,4,8,2,8,2,8,3,4,9,4,6,7],[1,4,1,6,9,4,5,7,7,4,6,7,7],[0,2,8,2,3,0,7,7,1,0,1,1,0],[1,2,2,4,5,4,7,1,0,1,8,6,7],[0,0,7,2,4,7,2,8,2,4,4,3,9],[1,9,1,3,2,4,1,3,3,7,5,6,1],[1,4,7,4,6,8,6,7,4,4,1,2,8],[0,1,6,7,3,9,0,4,7,2,9,6,7],[0,1,3,9,1,1,1,1,6,3,0,1,1],[1,2,7,0,2,0,7,9,7,2,1,5,2],[0,9,1,0,4,2,8,2,2,4,2,4,0],[1,1,7,9,7,9,3,0,5,3,4,5,2],[0,0,7,4,3,0,8,6,7,7,7,9,6],[0,7,0,4,0,6,7,6,3,2,0,7,1],[0,4,8,8,0,5,3,0,7,8,4,7,9],[0,6,3,3,3,6,6,3,7,0,4,8,3],[0,1,2,0,6,0,3,1,0,9,9,8,0],[0,7,0,3,8,2,5,0,7,5,0,0,4],[1,8,8,8,2,0,6,2,5,6,2,3,2],[1,6,2,5,8,0,1,9,7,3,7,6,0],[0,3,6,1,9,1,6,8,2,6,5,2,5],[0,3,9,7,8,9,4,5,4,8,5,5,1],[1,1,5,5,2,5,3,4,5,3,5,0,9],[1,0,9,4,9,6,1,7,0,0,6,0,1],[0,8,4,9,9,9,3,4,1,3,5,7,7],[0,7,8,0,0,3,5,5,9,4,1,8,1],[1,7,3,7,6,3,2,5,6,2,7,5,0],[0,0,2,6,0,6,6,2,7,6,1,6,2],[1,1,6,4,7,7,9,7,0,6,2,6,6],[0,2,1,1,4,7,6,8,8,8,9,4,3],[0,0,8,7,5,1,9,3,1,9,8,6,0],[0,3,4,4,0,7,1,8,7,2,7,9,9],[1,0,4,5,3,6,0,6,6,6,4,1,5],[0,9,7,9,9,5,9,2,3,0,4,6,2],[1,6,5,2,7,2,1,3,5,2,5,2,1],[1,9,9,4,8,6,3,7,8,3,3,0,6],[0,8,2,6,6,7,8,2,1,3,2,9,2],[0,4,8,1,9,2,4,8,4,5,4,6,4],[1,1,7,0,7,3,5,1,4,9,5,3,1],[1,7,8,8,3,5,3,1,5,7,6,1,9],[1,4,5,6,5,3,2,5,3,0,3,5,5],[0,0,2,1,3,8,9,1,0,9,7,6,7],[0,0,7,6,1,9,1,9,5,8,9,4,0],[1,5,4,4,6,8,7,3,9,9,0,7,4],[1,3,0,4,8,1,2,3,9,7,1,9,5],[1,2,6,1,4,6,9,4,7,1,1,2,6],[0,1,6,7,5,8,3,2,7,0,4,1,1],[1,6,2,7,8,7,6,8,7,2,0,3,3],[0,2,1,9,2,6,7,5,9,5,2,2,2],[0,5,2,0,4,7,7,3,8,1,5,0,9],[1,6,5,8,6,4,0,9,6,9,0,1,8],[1,2,0,8,7,9,2,4,4,0,9,8,9],[1,6,5,2,0,6,1,0,4,4,1,5,8],[1,5,4,2,5,6,2,5,6,2,2,9,5],[1,6,9,7,2,5,1,0,6,9,1,8,1],[0,0,3,9,9,0,6,7,9,5,7,4,6],[1,5,8,9,9,0,6,7,9,7,9,6,1],[1,3,6,4,6,3,6,8,4,5,2,8,3],[0,7,4,8,4,9,7,8,0,0,1,2,2],[0,4,2,9,1,3,8,8,3,0,0,9,8],[1,9,0,9,2,1,2,9,3,6,5,3,2],[1,1,0,2,0,5,9,9,5,4,7,8,9],[1,6,0,5,9,9,1,9,0,5,4,7,1],[1,0,4,0,0,3,2,4,1,6,4,6,5],[1,7,3,7,3,3,7,6,1,7,7,8,6],[0,9,1,7,3,5,1,8,9,3,8,6,2],[1,4,9,9,3,7,5,4,4,4,4,4,0],[0,3,7,7,4,3,6,1,1,3,5,1,6],[0,8,5,4,3,9,3,3,1,3,4,8,1],[1,6,1,9,4,6,4,6,4,5,2,1,5],[1,1,1,6,8,3,9,1,1,3,0,9,9],[0,5,1,6,8,4,8,8,2,4,4,9,2],[0,2,3,0,1,4,2,7,1,9,9,0,6],[0,8,4,2,5,1,4,9,5,2,0,4,3],[0,9,1,2,5,0,6,6,5,0,3,1,8],[1,7,8,7,1,7,4,6,3,3,3,3,9],[0,3,7,2,9,4,1,5,4,7,2,1,0],[1,2,8,1,1,6,4,7,8,2,0,5,2],[1,8,3,5,4,8,0,9,7,8,0,1,8],[1,7,9,9,0,4,5,7,2,9,0,1,9],[0,6,6,5,6,7,0,4,0,7,8,5,1],[0,6,0,6,3,1,1,5,0,9,2,2,3],[1,6,3,5,6,7,1,6,6,9,7,4,9],[0,9,5,9,8,2,4,3,3,2,3,5,6],[0,1,6,3,8,9,9,2,8,2,5,8,6],[1,4,7,6,6,5,7,3,3,3,4,1,1],[1,8,2,9,0,3,8,6,8,3,3,7,3],[0,2,8,4,8,5,4,8,9,5,0,5,7]],"__maskKeyLength__":13,"__getKeyNum__":function(TUQ){var s=TUQ.substring(TUQ.length-4,TUQ.length);var BuQ=s.fIf();var Eko=0;Eko|=BuQ[0]&3;Eko|=(BuQ[1]&3)<<2;Eko|=(BuQ[2]&3)<<4;Eko|=(BuQ[3]&3)<<6;return Eko-0;},"getCoordinate":function(AZe){var TMX=this.__getKeyNum__(AZe);var lgS=this.__keys__[TMX];var FOs=AZe.substring(0,AZe.length-4);var iGR=lgS[0];var vxW=0;switch(iGR){case 0:vxW=23;break;case 1:vxW=53;break;}

var GCW=FOs.fIf();for(var i=0;i<GCW.length;i++){GCW[i]-=vxW;GCW[i]-=lgS[i+1];}
var fSe=[];for(var j=0;j<GCW.length;j++){fSe.push(String.fromCharCode(GCW[j]));}
FOs=fSe.join("");return FOs;},"transformer":function(epc){var fSe=[];for(var i=0;i<epc.length;i++){if(isNaN(epc[i])){fSe[i]=uGb.getCoordinate(epc[i]);}
else{fSe[i]=epc[i];}}
return fSe;}};


function tES()
{
	this.nFQ=256;
	this.xqe=13;
	this.Nme=uGb.__keys__;
}

tES.prototype.vwZ=function()
{
	return parseInt(Math.random()*this.nFQ);
};

tES.prototype.teh=function(PBi,TMX)
{
	var whl=this.Nme[TMX];
	var btD=""+PBi;
	var BtM=new Array();
	for(var i=0;i<btD.length;i++){
		BtM.push(btD.charCodeAt(i));
	}
	var iGR=whl[0];
	var vxW=0;
	
	switch(iGR){
		case 0:
		vxW=23;
		break;
		case 1:
		vxW=53;
		break;
	}
	ZCI=BtM.length;
	var i=0;
	var YhU="";
	for(i=0;i<BtM.length&&i<whl.length-2;i++)
	{
		BtM[i]+=(parseInt(whl[i+1])+parseInt(vxW));
		YhU+=String.fromCharCode(BtM[i]);
	}
	YhU+=this.NIq(TMX);
	return YhU;
};

tES.prototype.McU=function(TUQ)
{
	var s=TUQ.substring(TUQ.length-4,TUQ.length);
	var BuQ=new Array(s.charCodeAt(0),s.charCodeAt(1),s.charCodeAt(2),s.charCodeAt(3));
	var Eko=0;
	Eko|=BuQ[0]&3;
	Eko|=(BuQ[1]&3)<<2;
	Eko|=(BuQ[2]&3)<<4;
	Eko|=(BuQ[3]&3)<<6;
	return Eko;
};

tES.prototype.getCoordinate=function(AZe)
{
	var TMX=this.McU(AZe);
	var lgS=this.Nme[TMX];
	var FOs=AZe.substring(0,AZe.length-4);
	var iGR=lgS[0];
	var vxW=0;
	switch(iGR){
		case 0:
		vxW=23;
		break;
		case 1:
		vxW=53;
		break;
	}
	var gHq="";
	for(var i=0;i<FOs.length;i++)
	{
		var VMH=FOs.charCodeAt(i);
		VMH-=vxW;
		VMH-=lgS[i+1];
		gHq+=String.fromCharCode(VMH);
	}
	return parseFloat(gHq);
};
tES.prototype.NIq=function(TMX)
{
	var BuQ=new Array(4);
	for(var i=0;i<BuQ.length;i++)
	{
		BuQ[i]=(Math.random()*10.0);
		BuQ[i]+=70;
		BuQ[i]=BuQ[i]>>2;
		BuQ[i]=BuQ[i]<<2;
	}
	BuQ[0]=BuQ[0]|TMX&3;
	BuQ[1]=BuQ[1]|(TMX&12)>>2;
	BuQ[2]=BuQ[2]|(TMX&48)>>4;
	BuQ[3]=BuQ[3]|(TMX&192)>>6;
	var TTq=String.fromCharCode(BuQ[0],BuQ[1],BuQ[2],BuQ[3]);
	return TTq;
};


//transfer lnglat to secret coordiate
function VtoS(para){ 

var lat = para[1];
var lng = para[0];
	
var HcJ=[];
var rZg=new tES();

HcJ.push(rZg.teh(lng,rZg.vwZ()));
HcJ.push(rZg.teh(lat,rZg.vwZ()));

return HcJ;

}


//return 2dem array
function ABMap_getCoord2(str){
	var tmp = str.split(";");
	var n = tmp.length;
	
	if(n <1)
		return null;
	
	var res = [];
	

	for(var i =0;i<n;i++){
		coor = tmp[i].split(",");
		coor[0] =  parseFloat(coor[0]);
		coor[1] =  parseFloat(coor[1]);
		
		if(isNaN(coor[0])||isNaN(coor[1])){
			coor = Vqp.transformer(tmp[i].split(","));
			coor[0] =  parseFloat(coor[0]);
			coor[1] =  parseFloat(coor[1]);
		}
		
		res.push(coor);
		
	}
	
	
	return res;	
}






ABMap.prototype.refreshOverviewMap = function(){
	var tmpdiv = $("ovmapDiv");
	var fdiv = tmpdiv.parentNode;
	fdiv.style.left =  (this.mapWidth-121)+'px';
	fdiv.style.top =   (this.mapHeight-121)+'px';
	
	var img1 = fdiv.lastChild;
	
	if(this.ovstatus){
		
			img1.src = ABMap_images+"overviewmap_out.png";
			img1.style.left = '105px';
			img1.style.top = '105px';
			fdiv.style.left = (this.mapWidth-121)+'px';
			fdiv.style.top = (this.mapHeight-121)+'px';
			this.refreshLogo([120,0]);
			this.ovmap.initMap();
	}else{
			img1.src = ABMap_images + "overviewmap_in.png";
			img1.style.left = '-1px';
			img1.style.top = '-1px';			
			fdiv.style.left = (this.mapWidth-15)+'px';
			fdiv.style.top = (this.mapHeight-15)+'px';
			this.refreshLogo([10,0]);	
	}

	
	
}



ABMap.prototype.newOverviewMap = function( ){
	this.ovstatus = true;
	var omapDivf  = document.createElement('div');
	omapDivf.style.position = 'absolute';
	omapDivf.style.zIndex = '1';
	
	omapDivf.style.left = (this.mapWidth-121)+'px';
	omapDivf.style.top = (this.mapHeight-121)+'px';
	omapDivf.style.width = '120px';
	omapDivf.style.height = '120px';
	omapDivf.style.cursor = 'default';

	omapDivf.style.borderLeft = "1px solid #979797";  //rgb(151,151,151)
	omapDivf.style.borderTop = "1px solid #979797"; //rgb(151,151,151)
	omapDivf.style.background = "#FFFFFF";
	this.screenDiv.appendChild(omapDivf);
	
	
	var omapDiv  = document.createElement('div');
	omapDiv.id = 'ovmapDiv';
	omapDiv.style.position = 'absolute';

	omapDiv.style.left = '8px';
	omapDiv.style.top = '8px';
	omapDiv.style.width = '110px';
	omapDiv.style.height = '110px';
	omapDiv.style.cursor = 'default';
	omapDiv.style.overflow = 'hidden';
	omapDiv.style.border = "1px solid #979797";
	//omapDiv.style.borderTop = "1px solid rgb(151,151,151)";
	omapDiv.style.background = "#e8e3d8";
	omapDivf.appendChild(omapDiv);
	
	
	
	var img1 = document.createElement('img');
	img1.style.position = 'absolute';
	img1.style.left = '105px';
	img1.style.top = '105px';
	img1.style.width = '15px';
	img1.style.height = '15px';
	img1.style.zIndex = 100;
	img1.src =  ABMap_images+"overviewmap_out.png";
	omapDivf.appendChild(img1);

	
	
	this.refreshLogo([120,0]);
	var map = this;
	img1.onclick = function(){
		
		if(map.ovstatus){
			this.src = ABMap_images + "overviewmap_in.png";
			this.style.left = '-1px';
			this.style.top = '-1px';
			map.ovstatus = false;
			omapDivf.style.left = (map.mapWidth-15)+'px';
			omapDivf.style.top = (map.mapHeight-15)+'px';
			map.refreshLogo([10,0]);
		}else {
			this.src = ABMap_images + "overviewmap_out.png";
			this.style.left = '105px';
			this.style.top = '105px';
			omapDivf.style.left = (map.mapWidth-121)+'px';
			omapDivf.style.top = (map.mapHeight-121)+'px';
			map.refreshLogo([120,0]);
			map.ovstatus = true;
			map.ovmap.initMap();
			
		}
	}
	
	
	this.ovmap = new ABovMap('ovmapDiv');
	this.ovmap.ABMap = this;

}






ABMap.prototype.showBubbleDivById = function(id){
	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.showBubbleDivByIndex(n);
}







ABMap.prototype.showBubbleDivByIndex = function(index){
	var n = index;
	if(n == -1)
		return ;
		
	var pointObject = this.aceteObj[n];
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - this.top_location;

	var pois = ABMap_getCoord(pointObject.coord);
	var pix = this.latlngToPixel(pois,this.mapZoom);
	
	var tmp = [(pix[0]-leftpix),(pix[1]-toppix)];


	if(tmp[0]>=0 && tmp[0] <=this.mapWidth && tmp[1] >=0 && tmp[1] <= this.mapHeight){
		var b = this.screenDiv.firstChild;  //ABBubbleDiv
		
		b.style.display = 'block';
		
		b.style.right = (-tmp[0] - 64) +'px';
		b.style.top = (tmp[1])+'px';
		
		b.innerHTML = pointObject.pointStyle.bubbleParam;
		
	}
	
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	s.firstChild.src = pointObject.pointStyle.iconURL2;
	s.style.zIndex = 100;
}
	
ABMap.prototype.hideBubbleDivByIndex = function(index){
	var n = index;
	
	var b = this.screenDiv.firstChild;//$('ABBubbleDiv');
	
	b.style.display = 'none';
	b.innerHTML = "";
	
	var pointObject = this.aceteObj[n];
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	
	s.firstChild.src = pointObject.pointStyle.iconURL;
	
	if(index != -1){
		s.style.zIndex = index+1;
	}
}


ABMap.prototype.hideBubbleDivById = function(id){

	var n = this.getAceteObjIndex(id);
	if(n == -1)
		return ;
		
	this.hideBubbleDivByIndex(n);
}


	
	//show tip by id 
ABMap.prototype.showTipDivById = function(id){

	var n =  this.getAceteObjIndex(id);
	if(n == -1)
		return ;
	
	this.showTipDivByIndex(n);
}


ABMap.prototype.showTipDivByIndex = function(index){
	var n = index;
	if(n == -1)
		return ;
	
	//change last tip's icon 
	if(this.currentTipIndex >=0){
		
		var sc = this.aceteLayer.childNodes[1].childNodes[this.currentTipIndex];
		
		var pointObjectc = this.aceteObj[this.currentTipIndex];
		sc.firstChild.style.left = pointObjectc.pointStyle.offset.iconX +'px';
		sc.firstChild.style.top = pointObjectc.pointStyle.offset.iconY+'px';
		
		sc.firstChild.style.width= pointObjectc.pointStyle.size.iconWidth+'px';
		sc.firstChild.style.height= pointObjectc.pointStyle.size.iconHeight+'px';
		sc.firstChild.src = pointObjectc.pointStyle.iconURL;
		sc.style.zIndex = this.currentTipIndex+1;
	}
		
		
	var pointObject = this.aceteObj[n];
	this.currentTipIndex = n;
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1];  //;// - this.left_location
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1]; //;- this.top_location

	var pois = ABMap_getCoord(pointObject.coord);
	var pix = this.latlngToPixel(pois,this.mapZoom);

	var tmp = [(pix[0]-leftpix),(pix[1]-toppix)];	
	
	var t = this.aceteLayer.firstChild;  //tip div
	
	t.style.display = 'block';	

	t.innerHTML = pointObject.pointStyle.tipParam;
	
	
	//change icon & icon idex
	var s = this.aceteLayer.childNodes[1].childNodes[n];
	
	
	
	s.firstChild.style.left = pointObject.pointStyle.offset.iconX2 +'px';
	s.firstChild.style.top = pointObject.pointStyle.offset.iconY2+'px';

	s.firstChild.style.width= pointObject.pointStyle.size.iconWidth2+'px';
	s.firstChild.style.height= pointObject.pointStyle.size.iconHeight2+'px';
	
	s.firstChild.src = pointObject.pointStyle.iconURL2;
	s.style.zIndex = 100;


	var map = this;
	var closeimg = t.firstChild.firstChild;
	closeimg.onclick = function(){
		map.closeTipWindow();
		
		s.firstChild.style.left = pointObject.pointStyle.offset.iconX +'px';
		s.firstChild.style.top = pointObject.pointStyle.offset.iconY+'px';
	
		s.firstChild.style.width= pointObject.pointStyle.size.iconWidth+'px';
		s.firstChild.style.height= pointObject.pointStyle.size.iconHeight+'px';
		
		s.firstChild.src = pointObject.pointStyle.iconURL;
		s.style.zIndex = index+1;
	}


	
	
	var offsetheight = 39;
	try{
		var ht = t.childNodes[1].clientHeight;
		offsetheight += parseInt(ht);
	}catch(error){}

	var offsetwidth = 472;

	t.style.top = ( tmp[1]-33 - offsetheight) + 'px';
	t.style.left = (tmp[0] -56) + 'px';



	//slide to tip extent
	var to = tmp[1] - 33 - offsetheight+ this.top_location;
	var lo = tmp[0] -56 + this.left_location;
	var ro = lo + offsetwidth;
	var bo = to + offsetheight;

	var sx =0;
	var sy = 0;

	if(ro > this.mapWidth){
		sx = -(ro-this.mapWidth) -10;
	}else if(lo<0)
		sx = -lo+10;
		
	if(bo > this.mapHeight-40)  //up icon
		sy = this.mapHeight - bo-40;  //up icon
	else if(to <0 )
		sy = -to+10;
	
	if(sx!=0 || sy!=0){
		
		if(Math.abs(sx)>this.mapWidth || Math.abs(sy)>this.mapHeight){
			this.checkmove([sx,sy]);
		}
		else
			this.slideBy([sx,sy]);
	
	}

	return null;
}




ABMap.prototype.getMapExtentFL = function(){
	if(this.aceteLineObj.length<1)
		return null;
	
	
	var coord = ABMap_getCoord2(this.aceteLineObj[0].coord)[0];
	var maxX = coord[0];
	var minX = maxX;
	var maxY = coord[1];
	var minY = maxY;
	
	
	for(var i =0;i<this.aceteLineObj.length;i++){
		coord_1 = ABMap_getCoord2(this.aceteLineObj[i].coord);
		for(var j=0;j<coord_1.length;j++){
			coord = coord_1[j];
			
			if(maxX<coord[0])
				maxX = coord[0];
			
			if(minX>coord[0])
				minX = coord[0];
			
			if(maxY<coord[1])
				maxY = coord[1];
	
			if(minY>coord[1])
				minY = coord[1];
		}
	}
	
	
	var tmpX = (maxX - minX)/5;
	var tmpY = (maxY - minY)/5;
	
	return [maxX+tmpX,minX-tmpX,maxY+tmpY,minY-tmpY];	
}


ABMap.prototype.zoomToPolys = function( ){
	if(this.aceteLineObj == null)
		return;
		
	if(this.aceteLineObj.length == 0)
		return;
	
		var ex = this.getMapExtentFL();
		var zoomvalue = this.getZoomValue(ex[0],ex[1],ex[2],ex[3]);

		var centerx = (ex[0]+ex[1])/2;
		var centery = (ex[2]+ex[3])/2;

		var cpix = this.getCenterPixel();
		var pix = this.latlngToPixel([centerx,centery],this.mapZoom);
		
		if(zoomvalue == this.mapZoom){	
			var offsetx = cpix[0] - pix[0];
			var offsety = cpix[1] - pix[1];
			this.checkmove([offsetx,offsety]);
			this.refreshAcete();
		}else{
			this.zoomToByPixel_c(zoomvalue,pix);
		}

}



ABMap.prototype.removeAllPoly = function(){
	this.aceteLineObj = new Array();
	
	var l = this.aceteLayer.childNodes[3];
	var len = l.childNodes.length;
	for(var i=0;i<len;i++){
		l.removeChild(l.childNodes[0]);
	}
}



ABMap.prototype.getArrowCoord = function(endArrowPix,width){
	try{
		var x1 = endArrowPix[0][0];
		var y1 = endArrowPix[0][1];
		var x2 = endArrowPix[1][0];
		var y2 = endArrowPix[1][1];
		
		var leftx,lefty,rightx,righty;
		
		var sidelen = 20;
		if(width!=null){
			sidelen = parseInt(width)*6;
		}
		
		
		var angle = Math.PI/8;

		var angle1 = Math.atan((y2-y1)/(x2-x1));
		
		var reangle = angle - angle1;
		
		var ytmp = sidelen* Math.sin(reangle);
		var xtmp = sidelen* Math.cos(reangle);
		
		if(x2>=x1){
			leftx = x2 - xtmp;
			lefty = y2 + ytmp;
		}else{
			leftx = x2 + xtmp;
			lefty = y2 - ytmp;
		}
		
		reangle = angle + angle1;
		
		ytmp = sidelen* Math.sin(reangle);
		xtmp = sidelen* Math.cos(reangle);
		
		if(x2>=x1){
			rightx = x2 - xtmp;
			righty = y2 - ytmp;
		}else{
			rightx = x2 + xtmp;
			righty = y2 + ytmp;
		}
		
		
		//var rightx = x2 - xtmp;
		//var righty = y2 - ytmp;
		
		return [[Math.round(leftx),Math.round(lefty)],[Math.round(rightx),Math.round(righty)]];
		
	}catch(e){}
}






ABMap.prototype.addPoly_vs = function(lineObj){
	//090410 endarrow
	
	
	var coords = ABMap_getCoord2(lineObj.coord);
	
	var pois = coords[0];
		
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1];// - this.left_location;
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1];// - this.top_location;

	var pix = this.latlngToPixel(pois,this.mapZoom);
	
	var loc = [(pix[0]-leftpix),(pix[1]-toppix)];
	
	var divtmp = document.createElement('div');
	divtmp.style.position = 'absolute';	
	divtmp.style.left = loc[0] +'px';
	divtmp.style.top = loc[1] +'px';

    var m = null;
	//var linepix = new Array();
	//linpix.push([0,0]);
	
	var linepix = "M0,0";
	var max_left = 0;
	var max_top = 0;
	var min_left = 0;
	var min_top = 0;
	
	var endArrowPix = new Array();
	
	//var vmllinepix = "0,0";
	var vmllinepix = "m 0,0 l";
	for(var i =1;i<coords.length;i++){
		pix_tmp = this.latlngToPixel(coords[i],this.mapZoom);
		loc_x = pix_tmp[0]-pix[0];
		loc_y = pix_tmp[1]-pix[1];
		
		if(loc_x >max_left)
			max_left = loc_x;
		
	    if(loc_y >max_top)
			max_top = loc_y;

		if(loc_x <min_left)
			min_left = loc_x;
		
	    if(loc_y <min_top)
			min_top = loc_y;
		
		linepix += " L"+loc_x+","+loc_y;
		
		vmllinepix += " "+loc_x+","+loc_y+",";
		//vmllinepix += " "+loc_x+","+loc_y;
		
		if(i >= coords.length-2){
			endArrowPix.push([loc_x,loc_y])
		}
		
	}
	
	if(endArrowPix.length==1){
	
		endArrowPix.splice(0,0,[0,0]);
	}
	
	
	
	
	
	var endArrowCoord = this.getArrowCoord(endArrowPix,lineObj.polyStyle.strokeWidth);
	
	if(lineObj.polyStyle.endArrow == true&&document.createElementNS&&endArrowCoord != null){
		var loc_x_max,loc_x_min,loc_y_max,loc_y_min;
		
		if(endArrowCoord[0][0]>endArrowCoord[1][0]){
			loc_x_max = endArrowCoord[0][0];
			loc_x_min = endArrowCoord[1][0];
		}else{
			loc_x_min = endArrowCoord[0][0];
			loc_x_max = endArrowCoord[1][0];	
		}
		
		if(endArrowCoord[0][1]>endArrowCoord[1][1]){
			loc_y_max = endArrowCoord[0][1];
			loc_y_min = endArrowCoord[1][1];
		}else{
			loc_y_min = endArrowCoord[0][1];
			loc_y_max = endArrowCoord[1][1];	
		}
		

		if(loc_x_max >max_left)
			max_left = loc_x_max;
		
	    if(loc_y_max >max_top)
			max_top = loc_y_max;

		if(loc_x_min <min_left)
			min_left = loc_x_min;
		
	    if(loc_y_min <min_top)
			min_top = loc_y_min;
	
	}
	
	
	
	//vmllinepix = vmllinepix.slice(0,vmllinepix.length-1);
	vmllinepix += " e";

	
	
   if (document.createElementNS) 
    {
		var offset = parseInt(lineObj.polyStyle.strokeWidth);
		
		var svgns = "http://www.w3.org/2000/svg";
		m = document.createElementNS(svgns, "svg");
		m.setAttribute("version", "1.1");
		m.setAttribute("overflow", "visible");
		m.setAttribute("width",(max_left-min_left +2*offset)+"px");
		m.setAttribute("height",(max_top - min_top+2*offset)+"px");
		
		m.setAttribute("style","position: absolute; left: "+(min_left-offset)+"px; top: "+(min_top-offset)+"px;");
		m.setAttribute("viewBox",(min_left-offset)+" "+(min_top-offset)+" "+(max_left-min_left+2*offset)+" "+(max_top - min_top+2*offset));
		
		var n = document.createElementNS(svgns, "path");
		
		n.setAttribute("id",lineObj.serial_id);
		
		n.setAttribute("d",linepix);
		
		
		n.setAttribute("stroke",lineObj.polyStyle.strokeColor);
		n.setAttribute("stroke-width",lineObj.polyStyle.strokeWidth+"pt");
		n.setAttribute("stroke-opacity",lineObj.polyStyle.strokeOpacity);
		n.setAttribute("stroke-linejoin","round");
		n.setAttribute("fill","none");
		
		if(lineObj.polyStyle.strokeShape >1){
			var dasharray = null;
			var w = lineObj.polyStyle.strokeWidth;
			switch(lineObj.polyStyle.strokeShape){
				case 2:
					dasharray =  3*w+","+w; //"6,2";
					break;
				case 3:
					dasharray = w+","+w;//"2,2";
					break;
				case 4:
					dasharray = 3*w+","+w+","+w+","+w; //"6,2,2,2";
					break;
				case 5:
					dasharray = 3*w+","+w+","+w+","+w+","+w+","+w; //"6,2,2,2,2,2";
					break;
				case 6:
					dasharray = w+","+3*w; //"2,6";
					break;
				case 7:
					dasharray = 5*w+","+5*w; //"10,6";  
					break;			
				case 8:
					dasharray = 10*w+","+3*w; //"20,6"; 
					break;
				case 9:
					dasharray = 5*w+","+3*w+","+w+","+3*w; //"10,6,2,6";
					break;
				case 10:
					dasharray = 10*w+","+3*w+","+w+","+3*w; //"20,6,2,6";
					break;		
				case 11:
					dasharray = 10*w+","+3*w+","+w+","+3*w+","+w+","+3*w; //"20,6,2,6,2,6"; 
					break;	
				default:
					break;
			}
			
			if(dasharray != null)
				n.setAttribute("stroke-dasharray",dasharray);
		}
		
		
		m.appendChild(n);
		
		
		//endArrow
		
		if(lineObj.polyStyle.endArrow == true&&this.mapZoom<7){
		//M0,0 L114,190 L418,270 L46,452 L160,612 L460,532
			var arrowpixtmp = "M"+endArrowCoord[0][0]+","+endArrowCoord[0][1]; //"M450,542";
			arrowpixtmp += " L"+endArrowPix[1][0]+","+endArrowPix[1][1];
			arrowpixtmp += " L"+endArrowCoord[1][0]+","+endArrowCoord[1][1];;
		
			var n2 = document.createElementNS(svgns, "path");
			
			n2.setAttribute("id",lineObj.serial_id+"_arrow");
			
			n2.setAttribute("d",arrowpixtmp);
			
			
			n2.setAttribute("stroke",lineObj.polyStyle.strokeColor);
			n2.setAttribute("stroke-width",lineObj.polyStyle.strokeWidth+"pt");
			n2.setAttribute("stroke-opacity",lineObj.polyStyle.strokeOpacity);
			n2.setAttribute("stroke-linejoin","round");
			n2.setAttribute("fill","none");
			
			
			if(lineObj.polyStyle.strokeShape >1){
				dasharray = null;
				w = lineObj.polyStyle.strokeWidth;
				switch(lineObj.polyStyle.strokeShape){
					case 2:
						dasharray =  3*w+","+w; //"6,2";
						break;
					case 3:
						dasharray = w+","+w;//"2,2";
						break;
					case 4:
						dasharray = 3*w+","+w+","+w+","+w; //"6,2,2,2";
						break;
					case 5:
						dasharray = 3*w+","+w+","+w+","+w+","+w+","+w; //"6,2,2,2,2,2";
						break;
					case 6:
						dasharray = w+","+3*w; //"2,6";
						break;
					case 7:
						dasharray = 5*w+","+5*w; //"10,6";  
						break;			
					case 8:
						dasharray = 10*w+","+3*w; //"20,6"; 
						break;
					case 9:
						dasharray = 5*w+","+3*w+","+w+","+3*w; //"10,6,2,6";
						break;
					case 10:
						dasharray = 10*w+","+3*w+","+w+","+3*w; //"20,6,2,6";
						break;		
					case 11:
						dasharray = 10*w+","+3*w+","+w+","+3*w+","+w+","+3*w; //"20,6,2,6,2,6"; 
						break;	
					default:
						break;
				}
				
				if(dasharray != null)
					n2.setAttribute("stroke-dasharray",dasharray);
			}
			
			
			m.appendChild(n2);
		}
		
			
	
	
	}
	else if(document.body.attachEvent) 
	{

		m = document.createElement("v:shape");
		
        m.coordsize = (max_left-min_left)+","+(max_top-min_top);
        m.style.width = (max_left-min_left)+"px";
        m.style.height = (max_top - min_top)+"px";
        m.path = vmllinepix;

        m.style.position = "absolute";
		m.style.left = "0px";
		m.style.top = "0px";
		
		m.StrokeColor = lineObj.polyStyle.strokeColor;
		m.StrokeWeight = lineObj.polyStyle.strokeWidth;
		m.Filled = "false";
		
		var men = document.createElement("v:stroke");
		men.opacity = lineObj.polyStyle.strokeOpacity;
		//men.endcap= "Round";
		men.joinstyle = "Round";
		
		if(lineObj.polyStyle.strokeShape >1){
			var dasharray = null;
			
			switch(lineObj.polyStyle.strokeShape){
				case 2:
					dasharray =  "ShortDash";
					break;
				case 3:
					dasharray = "ShortDot";
					break;
				case 4:
					dasharray = "ShortDashDot";
					break;
				case 5:
					dasharray = "ShortDashDotDot";
					break;
				case 6:
					dasharray = "Dot";
					break;
				case 7:
					dasharray = "Dash";  
					break;			
				case 8:
					dasharray = "LongDash"; 
					break;
				case 9:
					dasharray = "DashDot";
					break;
				case 10:
					dasharray = "LongDashDot";
					break;		
				case 11:
					dasharray = "LongDashDotDot"; 
					break;	
				default:
					break;
			}
			
			if(dasharray != null)
				men.dashstyle = dasharray;
		}
			
		
		m.appendChild(men);
		
		//endArrow
		if(lineObj.polyStyle.endArrow == true&&this.mapZoom<7){
			
			var arrow_max_left,arrow_min_left,arrow_max_top,arrow_min_top;
			
			if(endArrowCoord[0][0]>endArrowCoord[1][0]){
				arrow_max_left = endArrowCoord[0][0];
				arrow_min_left = endArrowCoord[1][0];
			}else{
				arrow_min_left = endArrowCoord[0][0];
				arrow_max_left = endArrowCoord[1][0];	
			}
			
			if(endArrowCoord[0][1]>endArrowCoord[1][1]){
				arrow_max_top = endArrowCoord[0][1];
				arrow_min_top = endArrowCoord[1][1];
			}else{
				arrow_min_top = endArrowCoord[0][1];
				arrow_max_top = endArrowCoord[1][1];	
			}
			
			if(endArrowPix[1][0]>arrow_max_left){
				arrow_max_left = endArrowPix[1][0];	
			}
			
			if(endArrowPix[1][0]<arrow_min_left){
				arrow_min_left = endArrowPix[1][0];	
			}
			if(endArrowPix[1][1]>arrow_max_top){
				arrow_max_top = endArrowPix[1][1];	
			}
			if(endArrowPix[1][1]<arrow_min_top){
				arrow_min_top = endArrowPix[1][1];	
			}

			var arrow_vmllinepix = "m "+endArrowCoord[0][0]+","+endArrowCoord[0][1]+" l";
			arrow_vmllinepix += " "+endArrowPix[1][0]+","+endArrowPix[1][1]+",";
			arrow_vmllinepix += " "+endArrowCoord[1][0]+","+endArrowCoord[1][1];
			
			m2 = document.createElement("v:shape");
			
			m2.coordsize = (arrow_max_left-arrow_min_left)+","+(arrow_max_top-arrow_min_top);
			m2.style.width = (arrow_max_left-arrow_min_left)+"px";
			m2.style.height = (arrow_max_top - arrow_min_top)+"px";
			m2.path = arrow_vmllinepix;
	
			m2.style.position = "absolute";
			m2.style.left = "0px";
			m2.style.top = "0px";
			
			m2.StrokeColor = lineObj.polyStyle.strokeColor;
			m2.StrokeWeight = lineObj.polyStyle.strokeWidth;
			m2.Filled = "false";
		
		
			var men2 = document.createElement("v:stroke");
			men2.opacity = lineObj.polyStyle.strokeOpacity;
			//men2.endcap= "Round";
			men2.joinstyle = "Round";
			
			if(lineObj.polyStyle.strokeShape >1){
				var dasharray = null;
				
				switch(lineObj.polyStyle.strokeShape){
					case 2:
						dasharray =  "ShortDash";
						break;
					case 3:
						dasharray = "ShortDot";
						break;
					case 4:
						dasharray = "ShortDashDot";
						break;
					case 5:
						dasharray = "ShortDashDotDot";
						break;
					case 6:
						dasharray = "Dot";
						break;
					case 7:
						dasharray = "Dash";  
						break;			
					case 8:
						dasharray = "LongDash"; 
						break;
					case 9:
						dasharray = "DashDot";
						break;
					case 10:
						dasharray = "LongDashDot";
						break;		
					case 11:
						dasharray = "LongDashDotDot"; 
						break;	
					default:
						break;
				}
				
				if(dasharray != null)
					men2.dashstyle = dasharray;
			}

			m2.appendChild(men2);
			divtmp.appendChild(m2);
			
		}
		
		
		
		
	}
	
	
	divtmp.appendChild(m);
	
	return divtmp;

}

//ABMap.line_pre_coord = null;

ABMap.prototype.addPoly = function(lineObj){
	
	
	this.aceteLineObj.push(lineObj);
	
	var divtmp = this.addPoly_vs(lineObj);
	
	this.aceteLayer.childNodes[3].appendChild(divtmp);	
}


ABMap.drawPoi_xy = null;


ABMap.prototype.drawPoint_postimg = function(loc){
	
	var drawdiv = this.aceteLayer.childNodes[2];
	
	var n = -1;
	
	for(var i =0;i<drawdiv.childNodes.length;i++){
		var idtmp = drawdiv.childNodes[i].id;
		if(idtmp == "draw_poi_div"){
			n = i;
			break;
		}
	}
	
	if(n!= -1){
		drawdiv = drawdiv.childNodes[n];
		drawdiv.style.left = (loc[0] - this.left_location)+'px';
		drawdiv.style.top = (loc[1] - this.top_location)+'px';	
		drawdiv.style.display = "block";
		
		var pix_x = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1]  + loc[0] - this.left_location;
		var pix_y = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1]  + loc[1] - this.top_location;
		
		this.drawPoi_xy = this.PixelTolatlng([pix_x,pix_y],this.mapZoom);
		
	}

}


ABMap.prototype.drawPoint_start = function( ){
	this.isDBLclick = false;  //not suggested,  won't set true 
	
	this.setCursor("url(/images/map/pointer3.cur), move");
	
	this.mapTool.drawStatus = 1;
	
	
	var divtmp = document.createElement('div');
	divtmp.style.position = 'absolute';	
	divtmp.style.left = '0px';
	divtmp.style.top = '0px';	
	divtmp.id = "draw_poi_div";
	divtmp.style.display = "none";
	
	var Img = document.createElement('img');

	Img.style.position = 'absolute';
	Img.style.left = '0px';
	Img.style.top = '-36px';
	
	Img.style.width= "37px";
	Img.style.height= "37px";
	Img.src =  ABMap_images + "poi.png";
	divtmp.appendChild(Img);	

	
	this.aceteLayer.childNodes[2].appendChild(divtmp);	
	
}

ABMap.prototype.drawPoint_end = function( ){
	
	var res = null;
	try{		
		if(this.drawPoi_xy != null){
			res = VtoS(this.drawPoi_xy);
			
			var prj=new ABMap_GridCodeFun();
			var grid =  prj.getGridCode(this.drawPoi_xy);
			if(grid != null)
			res.push(grid);
		}
	}catch(e){}
	
	return res;

}


ABMap.prototype.drawPoint_endAll = function( ){
	
	var res = null;
	try{
		this.setCursor("pointer");
		
		this.mapTool.drawStatus = -1;
		
		
		var drawdiv = this.aceteLayer.childNodes[2];
		
		var n = -1;
		
		for(var i =0;i<drawdiv.childNodes.length;i++){
			var idtmp = drawdiv.childNodes[i].id;
			if(idtmp == "draw_poi_div"){
				n = i;
				break;
			}
		}
		
		if(n!= -1){
			drawdiv.removeChild(drawdiv.childNodes[n]);
			
		}
		
		
		if(this.drawPoi_xy != null){
			res = VtoS(this.drawPoi_xy);
			
			var prj=new ABMap_GridCodeFun();
			var grid =  prj.getGridCode(this.drawPoi_xy);
			if(grid != null)
			res.push(grid);
		}
	}catch(e){}
	
	return res;

}


function ABPolyObject(){
	this.serial_id = null;
	this.coord = null;  //string,  //2 dim array [[p1_x,p1_y],[p2_x,p2_y],[p3_x,p3_y],[p4_x,p4_y]....]
	this.polyStyle = new ABPolyStyle();
	this.polyType = 1;  //1:polyline; 2:polygon
	
}


function ABPolyStyle(){
	this.strokeColor = '#0000FF';
	this.strokeWidth = '5';
	this.strokeOpacity =  0.5;
	this.strokeShape = 1;   //l1 linestyle defalut is dash line
	this.endArrow = false;
	
}







//ovmap object!!
function ABovMap(ovDiv){
	
	this.mainDiv = $(ovDiv);
	
	this.ABMap = null;
	
	this.mapZoom;
	this.levelgap; 
	this.defaultlevelgap;  
	
	this.centerDiv1 = null;
	this.centerDiv2 = null;
	
	this.mapDiv = null;
	
	this.img_src_x = [];   //[[nx,offsetx],[nx,offsetx]]
	this.img_src_y = [];   //[[ny,offsety],[ny,offsety]]
	
	this.centerDivsize = null;  
	this.centerDivloc = null;  
	this.centerDivloc2 = null;  
	
	this.mapWidth = 110;
	this.mapHeight = 110;
	
	//slide
	this.as=null;
	this.slideid=null;
	this.pos_test=null;
    this.pixelsPerStep = 5;
    this.timePerStep = 30;  //30
	this.mainMapSliding = false;   
	
	this.mainmap_checkmove_offx = 0;
	this.mainmap_checkmove_offy = 0;
	
	this.addMapMainDiv();
	this.addCenterDiv();
}

ABovMap.prototype.initMap = function(){
	var w
	var h;
	var gaptmp = 1;
	while(gaptmp <(ABMap_zoomlevel-1)){
			
	   w = Math.round(this.ABMap.mapWidth/Math.pow(2,gaptmp));
	   h = Math.round(this.ABMap.mapHeight/Math.pow(2,gaptmp));
	
		if(w <= (this.mapWidth/2)&&h<= (this.mapHeight/2) )
			break;

		gaptmp++;
	}

	this.defaultlevelgap = gaptmp;
	var zoomtmp = this.ABMap.mapZoom + gaptmp;
	
	if(zoomtmp >(ABMap_zoomlevel-1))
		zoomtmp = (ABMap_zoomlevel-1);
	
	this.mapZoom = zoomtmp;
	this.levelgap = this.mapZoom - this.ABMap.mapZoom;	

	var centerdiv_w = Math.round(this.ABMap.mapWidth/Math.pow(2,this.levelgap));
	var centerdiv_h = Math.round(this.ABMap.mapHeight/Math.pow(2,this.levelgap));
	
	var center_left = Math.round((this.mapWidth-centerdiv_w)/2)-2;
	var center_top = Math.round((this.mapHeight-centerdiv_h)/2)-2;
	
	this.centerDivsize = [centerdiv_w,centerdiv_h];
	this.centerDivloc = [center_left,center_top];

	this.initCenterDiv();	
	
	if(this.mapZoom == (ABMap_zoomlevel-1)){
		if(centerdiv_w>=this.mapWidth || centerdiv_h >= this.mapHeight){
			this.centerDiv1.style.display = 'none';
			this.centerDiv2.style.display = 'none';
		}
	}
	var centerpix = this.ABMap.getCenterPixel();
	var s = Math.pow(2,this.levelgap);
	var ovCenterX = Math.ceil(centerpix[0]/s);
	var ovCenterY = Math.ceil(centerpix[1]/s);
	
	this.fromPixelToImg([ovCenterX,ovCenterY]);
	this.initValue();
	this.patchUpImg();
}

ABovMap.prototype.initValue = function(){
	
	this.mapDiv.style.top = '0px';
	this.mapDiv.style.left = '0px';
	
	this.mainmap_checkmove_offx = 0;
	this.mainmap_checkmove_offy = 0;
}

ABovMap.prototype.addMapMainDiv = function(){

	var ttdiv = document.createElement('div');
	ttdiv.style.position = 'absolute';
	ttdiv.style.overflow = 'hidden';
	ttdiv.style.width = this.mapWidth+'px';
	ttdiv.style.height = this.mapHeight+'px';
	ttdiv.style.zIndex = 1;


	var mapMainDiv  = document.createElement('div');
	//mapMainDiv.style.overflow = 'hidden';
	mapMainDiv.id = "mapMainDiv";
	mapMainDiv.style.position = 'absolute';
	mapMainDiv.style.top = '0px';
	mapMainDiv.style.left = '0px';
	ttdiv.appendChild(mapMainDiv);
	
	this.mainDiv.appendChild(ttdiv);
	this.mapDiv = mapMainDiv;

	var clientCoord;
	var firstCoord;
	var ovmap = this;
	ttdiv.onmousedown = function(e){
		e = (e)?e:((event)?event:null);
		clientCoord = [e.clientX,e.clientY];
	 	firstCoord = [e.clientX,e.clientY];	
		center_x = parseInt(ovmap.centerDiv1.style.left);
		center_y = parseInt(ovmap.centerDiv1.style.top);
		
		document.onmousemove = function(e){
			e = (e)?e:((event)?event:null);
			
			var offset_x = e.clientX - clientCoord[0];
			var offset_y = e.clientY - clientCoord[1];
			clientCoord = [e.clientX,e.clientY];
			
			ovmap.centerDiv1.style.left = (parseInt(ovmap.centerDiv1.style.left) + offset_x)+'px';
			ovmap.centerDiv1.style.top = (parseInt(ovmap.centerDiv1.style.top) + offset_y)+'px';
			
			ovmap.checkmove([offset_x,offset_y]);
			return false;
		}
	
		document.onmouseup = function(e){
			 document.onmousemove = null;
			 document.onmouseup = null;
			 document.onmouseout = null;
			 
			e = (e)?e:((event)?event:null);
			var offset_x = e.clientX - firstCoord[0];
			var offset_y = e.clientY - firstCoord[1];		
			ovmap.moveABmap([offset_x,offset_y]);
			
			return false;	


		}
		
		
		document.onmouseout = function(e){
			
			e = (e)?e:((event)?event:null);
			
			if(e.target){ //firefox

				if(e.relatedTarget == null|| e.relatedTarget.tagName == "HTML"){
					document.onmousemove = null;
					document.onmouseup = null;
					document.onmouseout = null;
					
					var offset_x1 = parseInt(ovmap.centerDiv1.style.left) - ovmap.centerDivloc[0];
					var offset_y1 = parseInt(ovmap.centerDiv1.style.top) - ovmap.centerDivloc[1];	
					
					ovmap.moveABmap([offset_x1,offset_y1]);
					
					return false;
				}
			}else if(e.srcElement){  //ie
			
				if( e.toElement == null || e.toElement.tagName == "HTML" ){
					document.onmousemove = null;
					document.onmouseup = null;
					document.onmouseout = null;
					
					var offset_x1 = parseInt(ovmap.centerDiv1.style.left) - ovmap.centerDivloc[0];
					var offset_y1 = parseInt(ovmap.centerDiv1.style.top) - ovmap.centerDivloc[1];
					
					ovmap.moveABmap([offset_x1,offset_y1]);
					
					return false;
				}
			}
			
			return null;

		}	
		
		return false;
	}
}

ABovMap.prototype.getCenterPixel = function( ){
	var left_location = parseInt(this.mapDiv.style.left);
	var top_location = parseInt(this.mapDiv.style.top);
	
	var leftpix = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] - left_location + Math.ceil(this.mapWidth/2);
	var toppix = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] - top_location + Math.ceil(this.mapHeight/2);
	
	return [leftpix,toppix];	
}

//onmouseup
ABovMap.prototype.moveABmap = function(offset){

	var s = Math.pow(2,this.levelgap);
	var t = [offset[0]*s, offset[1]*s];

	var x = parseInt(this.centerDiv1.style.left);
	var y = parseInt(this.centerDiv1.style.top);
	
	var offx = x - this.centerDivloc[0];
	var offy = y - this.centerDivloc[1];

	if(Math.abs(offx) > this.centerDivsize[0] || Math.abs(offy) > this.centerDivsize[1]){
		this.ABMap.stopLastSlide();
		this.ABMap.checkmove(t,false);
		this.moveABmap_relocation();
	}else{
		this.mainMapSliding = true;
		/*
		this.afterBigMapSlide = function(){
			this.moveABmap_relocation();
		}*/
		this.ABMap.slideBy(t);
	}
}

ABovMap.prototype.moveABmap_relocation = function(){
	
	var c_div1_left = parseInt(this.centerDiv1.style.left);
	var c_div1_top = parseInt(this.centerDiv1.style.top);
	
	var c_div2_left = parseInt(this.centerDiv2.style.left);
	var c_div2_top = parseInt(this.centerDiv2.style.top);

	if(c_div1_left ==c_div2_left ==this.centerDivloc[0] && c_div1_top == c_div2_top == this.centerDivloc[1])
		return;
	
	
	this.centerDiv1.style.left = this.centerDivloc[0]+"px";
	this.centerDiv1.style.top = this.centerDivloc[1]+"px";
	
	this.centerDiv2.style.left = this.centerDivloc[0]+"px";
	this.centerDiv2.style.top = this.centerDivloc[1]+"px";

}

ABovMap.prototype.moveCenterDiv2 = function(offset){
	
	var l = parseInt(this.centerDiv1.style.left);
	var t = parseInt(this.centerDiv1.style.top);

	if(!(offset[0]==0&&offset[1]==0)){
		this.centerDiv1.style.left = (l+offset[0])+'px';
		this.centerDiv1.style.top = (t+offset[1])+'px';
	}
	this.centerDivloc2 = [l+offset[0],t+offset[1]];
}

ABovMap.prototype.checkmove = function(offset){

		var o_x = parseInt(this.mapDiv.style.left) + offset[0];
		var o_y = parseInt(this.mapDiv.style.top) + offset[1];
		
		this.mapDiv.style.left = o_x+'px';
		this.mapDiv.style.top = o_y +'px';

		var add_x = [];
		var add_y = [];
		if(Math.abs(offset[0])>ABMap_piewidth || Math.abs(offset[1]) >ABMap_pieheight){
			var left = this.img_src_x[0][0]*ABMap_piewidth - this.img_src_x[0][1] -o_x ;
			var top = this.img_src_y[0][0]*ABMap_pieheight - this.img_src_y[0][1] -o_y ;	
			
			var pixel_xn = Math.floor(left/ABMap_piewidth);    
			var pixel_yn = Math.floor(top/ABMap_pieheight);
		
			var x_n = Math.floor((left+this.mapWidth)/ABMap_piewidth) - pixel_xn +1;
			var y_n = Math.floor((top+this.mapHeight)/ABMap_pieheight) - pixel_yn +1;			
			
			var off_x = (pixel_xn - this.img_src_x[0][0])*ABMap_piewidth + this.img_src_x[0][1];
			var off_y = (pixel_yn - this.img_src_y[0][0])*ABMap_pieheight + this.img_src_y[0][1];
			
			this.img_src_x = [];
			this.img_src_y = [];
			var tmparray;
			for(var i=0;i<x_n;i++){
				tmparray = [pixel_xn+i, off_x + i*ABMap_piewidth];
				this.img_src_x.push(tmparray);
			}		
			for(var i=0;i<y_n;i++){
				tmparray = [pixel_yn+i, off_y + i*ABMap_pieheight];
				this.img_src_y.push(tmparray);
			}
			
		}else{

			var tmp ;
			//x: left +1
			if((this.img_src_x[0][1] + o_x) > 0){
				tmp =[this.img_src_x[0][0]-1,this.img_src_x[0][1]-ABMap_piewidth];
				this.img_src_x.unshift(tmp);
				add_x.push(tmp);
			}			
			//x: right +1
			if((this.img_src_x[this.img_src_x.length-1][1] +o_x+ABMap_piewidth) <this.mapWidth){
				tmp =[this.img_src_x[this.img_src_x.length-1][0]+1,this.img_src_x[this.img_src_x.length-1][1]+ABMap_piewidth];
				this.img_src_x.push(tmp);
				add_x.push(tmp);
			}
			//x: left -1
			if((this.img_src_x[0][1] + o_x +ABMap_piewidth ) < 0){
				this.img_src_x.shift();
			}				
			//x: right -1
			if((this.img_src_x[this.img_src_x.length-1][1] +o_x) >this.mapWidth){
				this.img_src_x.pop();
			}			
			//y: top +1
			if((this.img_src_y[0][1] + o_y) > 0){ 
				tmp = [this.img_src_y[0][0]-1,this.img_src_y[0][1]-ABMap_pieheight];
				this.img_src_y.unshift(tmp);
				add_y.push(tmp);
			}
			//y: bottom +1
			if((this.img_src_y[this.img_src_y.length-1][1] +o_y + ABMap_pieheight ) <this.mapHeight){
				tmp =[this.img_src_y[this.img_src_y.length-1][0]+1,this.img_src_y[this.img_src_y.length-1][1]+ABMap_pieheight];
				this.img_src_y.push(tmp);
				add_y.push(tmp);
			}				
			//y: top -1
			if((this.img_src_y[0][1] + o_y +ABMap_pieheight) < 0){ 
				this.img_src_y.shift();
			}
			//y: bottom -1
			if((this.img_src_y[this.img_src_y.length-1][1] +o_y) >this.mapHeight){
				this.img_src_y.pop();
			}
		}

		this.patchUpImg();
}

ABovMap.prototype.addCenterDiv = function(){

	var centerdiv1  = document.createElement('div');
	centerdiv1.style.position = 'absolute';
	centerdiv1.style.border = "2px solid #6666CC";
	
	centerdiv1.style.left = '0px';
	centerdiv1.style.top = '0px';
	centerdiv1.style.width = '0px';
	centerdiv1.style.height = '0px';
	centerdiv1.style.zIndex = 3;
	
	var tdiv  = document.createElement('div');
	
	tdiv.style.background = "#6666CC";
	tdiv.style.width =  '0px';
	tdiv.style.height =  '0px';
	tdiv.style.filter = 'alpha(opacity=30)';
	tdiv.style.opacity = '0.3';
	centerdiv1.appendChild(tdiv);
	//add centerdiv to which div???
	this.mainDiv.appendChild(centerdiv1);
	this.centerDiv1 = centerdiv1;
		
	var centerdiv2  = document.createElement('div');
	centerdiv2.style.position = 'absolute';
	centerdiv2.style.border = "2px solid #6666CC";
	
	centerdiv2.style.left = '0px';
	centerdiv2.style.top = '0px';
	centerdiv2.style.width = '0px';
	centerdiv2.style.height = '0px';
	centerdiv2.style.zIndex = 4;
		
	var tdiv2  = document.createElement('div');
	
	tdiv2.style.background = "#6666CC";
	tdiv2.style.width =  '0px';
	tdiv2.style.height =  '0px';
	tdiv2.style.filter = 'alpha(opacity=1)';
	tdiv2.style.opacity = '0.01';
	centerdiv2.appendChild(tdiv2);	

	this.mainDiv.appendChild(centerdiv2);
	this.centerDiv2 = centerdiv2;	
	
}


ABovMap.prototype.initCenterDiv = function(){
	this.centerDiv1.style.display = 'block';
	this.centerDiv2.style.display = 'block';
	
	this.centerDiv1.style.left = this.centerDivloc[0]+'px';
	this.centerDiv1.style.top = this.centerDivloc[1]+'px';
	this.centerDiv1.style.width = this.centerDivsize[0]+'px';
	this.centerDiv1.style.height = this.centerDivsize[1]+'px';
	
	var tdiv  = this.centerDiv1.firstChild;
	tdiv.style.width =  this.centerDivsize[0]+'px';
	tdiv.style.height =  this.centerDivsize[1]+'px';

	this.centerDiv2.style.left = this.centerDivloc[0]+'px';
	this.centerDiv2.style.top = this.centerDivloc[1]+'px';
	this.centerDiv2.style.width = this.centerDivsize[0]+'px';
	this.centerDiv2.style.height = this.centerDivsize[1]+'px';
	
	var tdiv2  = this.centerDiv2.firstChild;
	tdiv2.style.width =  this.centerDivsize[0]+'px';
	tdiv2.style.height =  this.centerDivsize[1]+'px';
	
	var timer = null;
	var minimap = this;
	this.centerDiv2.onmousedown = function(e){
		e = (e)?e:((event)?event:null);
		clientCoord = [e.clientX,e.clientY];
		var ttdiv = this.parentNode;
		
		var cdiv = this;
		var cdiv_x = parseInt(cdiv.style.left);
		var cdiv_y = parseInt(cdiv.style.top);
		///alert('a');
		if(timer != null){
			window.clearInterval(timer);
			timer = null;
		}
		
		var timer_x = 0;
		var timer_y = 0;
		document.onmousemove = function(e){
			e = (e)?e:((event)?event:null);
			var left = cdiv_x+e.clientX-clientCoord[0];
			var top = cdiv_y+e.clientY-clientCoord[1];
			
			cdiv.style.left = left+"px";
			cdiv.style.top = top+"px";
			if(timer != null){
				window.clearInterval(timer);
				timer = null;
			}
			var left_o = minimap.mapWidth-(left+minimap.centerDivsize[0]);
			var top_o = minimap.mapHeight-(top+minimap.centerDivsize[1]);
			var t = [];
			
			if(left>=0){
				if(left_o>0)
					t[0] = 0;
				else
					t[0] = -5;
			}else
				t[0] = 5;

		
			if(top >= 0){
				if(top_o>0)
					t[1] = 0;
				else
					t[1] = -5;
			}else
				t[1] = 5;
			
			if(!(t[0] ==0&&t[1]==0)){
				minimap.checkmove(t);
				timer_x += t[0];
				timer_y += t[1];
				minimap.moveScreenDiv1(t);
				timer = window.setInterval(function(){minimap.checkmove(t);timer_x += t[0];timer_y += t[1];minimap.moveScreenDiv1(t)},70);
			}
			return false;
		}
				
		document.onmouseup = function(e){
			document.onmousemove = null;
			document.onmouseup = null;
			document.onmouseout = null;
			
			if(timer != null){
				window.clearInterval(timer);
				timer = null;
			}
			e = (e)?e:((event)?event:null);

			var mapdiv_offset = [timer_x,timer_y];
			timer_x = 0;
			timer_y = 0;
					
			minimap.onMoveCenter([clientCoord[0] - e.clientX, clientCoord[1] - e.clientY],mapdiv_offset);
			
			return false;
		}	
		
		
		document.onmouseout = function(e){
			
			e = (e)?e:((event)?event:null);
			
			if(e.target){ //firefox

				if(e.relatedTarget == null|| e.relatedTarget.tagName == "HTML"){
					document.onmousemove = null;
					document.onmouseup = null;
					document.onmouseout = null;
					
					if(timer != null){
						window.clearInterval(timer);
						timer = null;
					}
					e = (e)?e:((event)?event:null);
		
					var mapdiv_offset = [timer_x,timer_y];
					timer_x = 0;
					timer_y = 0;
					minimap.onMoveCenter([clientCoord[0] - e.clientX, clientCoord[1] - e.clientY],mapdiv_offset);
					
					return false;
				}
			}else if(e.srcElement){  //ie
			
				if( e.toElement == null || e.toElement.tagName == "HTML" ){
					document.onmousemove = null;
					document.onmouseup = null;
					document.onmouseout = null;
					
					if(timer != null){
						window.clearInterval(timer);
						timer = null;
					}
					e = (e)?e:((event)?event:null);
		
					var mapdiv_offset = [timer_x,timer_y];
					timer_x = 0;
					timer_y = 0;
					minimap.onMoveCenter([clientCoord[0] - e.clientX, clientCoord[1] - e.clientY],mapdiv_offset);
					
					return false;
				}
				//document.onmouseout = null;
			}
			
			return null;

		}
		

		
		
		
	}
}


ABovMap.afterBigMapSlide = false;

ABovMap.prototype.onMoveCenter = function(offset,offset2){

	var s = Math.pow(2,this.levelgap);
	var t = [(offset[0]+offset2[0])*s, (offset[1]+offset2[1])*s]; 

	var x = parseInt(this.centerDiv2.style.left);
	var y = parseInt(this.centerDiv2.style.top);
	var offx = x - this.centerDivloc[0] - offset2[0];
	var offy = y - this.centerDivloc[1] - offset2[1];

	if(Math.abs(offx) > this.centerDivsize[0] || Math.abs(offy) > this.centerDivsize[1]){
		this.ABMap.stopLastSlide();
		this.ABMap.checkmove(t,false);
		//this.stopLastSlide();
		this.slideBy([offset[0],offset[1]]);

	}else{
		this.mainMapSliding = true;
		
		this.afterBigMapSlide = function(){
			this.stopLastSlide();
			this.checkmove([offset[0],offset[1]]);
			this.moveScreenDiv([offset[0],offset[1]]);
			this.moveABmap_relocation();
		}
		
		this.ABMap.slideBy(t);
		
	}

}




ABovMap.prototype.patchUpImg = function( ){

	var len = this.mapDiv.childNodes.length;
	for(var i=0;i<len;i++)
		this.mapDiv.removeChild(this.mapDiv.childNodes[0]);
	
	var url;

	for(var i=0;i<this.img_src_x.length;i++){
		for(var j=0;j<this.img_src_y.length;j++){
			url = this.ABMap.getURL(this.img_src_x[i][0],this.img_src_y[j][0],this.mapZoom);

			var imgobj = this.ABMap.createImg(this.img_src_x[i][1], this.img_src_y[j][1], url);
			this.mapDiv.appendChild(imgobj);
		}
	}
}

ABovMap.prototype.fromPixelToImg = function(centerpix){
	this.img_src_x = [];
	this.img_src_y = [];
	
	ovCenterX = centerpix[0];
	ovCenterY = centerpix[1];
	
	var c_pix_n_x = Math.floor(ovCenterX/ABMap_piewidth);
	var c_pix_n_y = Math.floor(ovCenterY/ABMap_pieheight);
	
	var offset_x = this.mapWidth/2 - ovCenterX%ABMap_piewidth;
	var offset_y = this.mapHeight/2 - ovCenterY%ABMap_pieheight;
	
	this.img_src_x.push([c_pix_n_x,offset_x]);
	this.img_src_y.push([c_pix_n_y,offset_y]);
	
	
	if(offset_x>0)
		this.img_src_x.unshift([c_pix_n_x-1,offset_x-ABMap_piewidth]);
	else if ((offset_x+ABMap_piewidth)<this.mapWidth)
		this.img_src_x.push([c_pix_n_x+1,offset_x+ABMap_piewidth]);
	
	if(offset_y>0)
		this.img_src_y.unshift([c_pix_n_y-1,offset_y-ABMap_pieheight]);
	else if ((offset_y+ABMap_pieheight)<this.mapHeight)
		this.img_src_y.push([c_pix_n_y+1,offset_y+ABMap_pieheight]);
}



ABovMap.prototype.zoomTo = function(mainmap_newzoom){
	var defaultzoom = mainmap_newzoom+this.defaultlevelgap;
	var newzoom = defaultzoom>(ABMap_zoomlevel-1)?(ABMap_zoomlevel-1):defaultzoom;

	if(newzoom == this.mapZoom && defaultzoom<(ABMap_zoomlevel-1))
		return;	


	if(newzoom == (ABMap_zoomlevel-1) || this.mapZoom == (ABMap_zoomlevel-1)){
		this.levelgap = newzoom - mainmap_newzoom;
		
		var centerdiv_w = Math.round(this.ABMap.mapWidth/Math.pow(2,this.levelgap));
		var centerdiv_h = Math.round(this.ABMap.mapHeight/Math.pow(2,this.levelgap));
		
		var center_left = Math.round((this.mapWidth-centerdiv_w)/2)-2;
		var center_top = Math.round((this.mapHeight-centerdiv_h)/2)-2;
		
		this.centerDivsize = [centerdiv_w,centerdiv_h];
		this.centerDivloc = [center_left,center_top];
		
		this.initCenterDiv();
		
		if(centerdiv_w>=this.mapWidth || centerdiv_h >= this.mapHeight){
			this.centerDiv1.style.display = 'none';
			this.centerDiv2.style.display = 'none';
		}
	}


	var centerpix = this.ABMap.getCenterPixel();
	
	var zoom_off = mainmap_newzoom - newzoom;
	
	var s = Math.pow(2,zoom_off);
	
	var centerX_pixel_n = Math.round(centerpix[0]* s);
	var centerY_pixel_n = Math.round(centerpix[1]* s);
	
	this.mapZoom = newzoom;
	this.fromPixelToImg([centerX_pixel_n,centerY_pixel_n]);
	this.initValue();
	this.patchUpImg();

	
}



ABovMap.prototype.onMapMouseUp = function( ){

	this.stopLastSlide();

	var c_div1_left = parseInt(this.centerDiv1.style.left);
	var c_div1_top = parseInt(this.centerDiv1.style.top);

	this.centerDiv2.style.left = c_div1_left+"px";
	this.centerDiv2.style.top = c_div1_top+"px";
	
	var x = this.centerDivloc[0] - c_div1_left;   
	var y = this.centerDivloc[1] - c_div1_top;
		
	this.checkmove([x,y]);
	this.moveScreenDiv([x,y]);

	this.mainmap_checkmove_offx = 0;
	this.mainmap_checkmove_offy = 0;	
}


ABovMap.prototype.stopLastSlide = function(){	
    if (this.slideid!=null) {
		ABMap_goQueueManager.dequeue( this.slideid );
		var tmp = this.as.length;
		var len = tmp - this.pos_test;

		var last_x = 0;
		var last_y = 0;
		for(var i=0;i<len;i++){
			//last.push( this.as[tmp-i-1]);
			last_x += this.as[tmp-i-1][0];
			last_y += this.as[tmp-i-1][1];
		}
		
		if(!(last_x==0&&last_y==0)){
			this.checkmove([last_x,last_y]);
			this.moveScreenDiv([last_x,last_y]);
		}
		
		this.slideid = null;
	}
}


ABovMap.prototype.slideBy = function(offset){
	this.stopLastSlide();
   
	var x = offset[0];
	var y = offset[1];

	this.as = [];

    var absX = Math.abs(x);
    var absY = Math.abs(y);

    var distance = absX>absY?absX:absY;
    var steps = Math.round(distance/this.pixelsPerStep);
	
	if(steps == 0)
		return;
	
    var dx = dy = 0;

	dx = (x)/(steps*this.pixelsPerStep);
	dy = (y)/(steps*this.pixelsPerStep);


    var px=py=0;
	
    var i=0;
    while(i<steps-1){
        if (i>0){
          px+=this.as[i-1][0];
          py+=this.as[i-1][1];
        }

        var cx = px+Math.round(dx*this.pixelsPerStep);
        var cy = py+Math.round(dy*this.pixelsPerStep);
        this.as.push(new Array(cx-px,cy-py));
        i++;
    }
	if (i>0){
		px+=this.as[i-1][0];
    	py+=this.as[i-1][1];
	}
	this.as.push(new Array(x-px, y-py));


	this.slideid=ABMap_goQueueManager.enqueue(this.timePerStep,this,this.slide,[0]);
	
}



ABovMap.prototype.slide = function(pos)
{

    if (pos>=this.as.length){
		this.moveABmap_relocation();
		
		this.slideid=null;
		return;
	}

	this.checkmove(this.as[pos]); 
	this.moveScreenDiv(this.as[pos]);  
		
    pos ++;
	this.pos_test = pos;
    this.slideid=ABMap_goQueueManager.enqueue(this.timePerStep,this,this.slide,[ pos]);
}


ABovMap.prototype.moveScreenDiv = function(offset)
{	this.centerDiv2.style.left = (parseInt(this.centerDiv2.style.left) + offset[0])+"px";
	this.centerDiv2.style.top = (parseInt(this.centerDiv2.style.top) + offset[1])+"px";

	this.centerDiv1.style.left = (parseInt(this.centerDiv1.style.left) + offset[0])+"px";
	this.centerDiv1.style.top = (parseInt(this.centerDiv1.style.top) + offset[1])+"px";
}

ABovMap.prototype.moveScreenDiv1 = function(offset)
{	
	this.centerDiv1.style.left = (parseInt(this.centerDiv1.style.left) + offset[0])+"px";
	this.centerDiv1.style.top = (parseInt(this.centerDiv1.style.top) + offset[1])+"px";
}



/* - common.js - */
/*
    common functions
*/
function getDomain()
{
    var host=document.domain;
    var reg=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/;
    if( reg.test(host) == false )
        if(host!="localhost")
            return "aibang.com";
        else 
            return "";
    return host;    
}

function getImagesDomain()
{
	var host = window.location.hostname;
	var port = window.location.port;
	if(host != "localhost" && !port){
		if(!window['imgDomain']){
			window['imgDomain'] = 0;
		}
		window['imgDomain'] %= 3;
		var _str = "http://i"+parseInt(window['imgDomain'],10)+".aibangjuxin.com";
		window['imgDomain']++;
		return _str;
	}
	return "";
}


function setCookie(name,value,Days)
{    
    if(Days == null)
        Days = 30;
    var ex  = new Date();
    
    //delCookie(name); 
    if(Days != 0)
    {
        ex.setTime(ex.getTime() + Days*24*60*60*1000);
        document.cookie = name + "="+ encodeURIComponent(value) +";expires="+ex.toGMTString()+";path=/;domain="+getDomain();
    }
    else
    {
        document.cookie = name + "="+ encodeURIComponent(value) +";path=/;domain="+getDomain();    
    }
}

function getCookie(name)
{
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  if(arr != null &&  arr[2] != "deleted")
      return decodeURIComponent(arr[2]); 
  return '';
}

function delCookie(name)
{  
  var ex  = new Date();
  ex.setTime(ex.getTime()-1);
  document.cookie = name +"=;expires="+ex.toGMTString()+";path=/;domain="+getDomain();
}

function RefreshPic(o)
{
    $(o).src = "authimg.php?id="+Math.random();
}

function bytes(str)
{
    if(typeof(str)!='string'){
        str = str.value;
    }
    var len = 0;
    for(var i = 0; i < str.length; i++)
    {
        if(str.charCodeAt(i) > 127)
        {
            len++;
        }
        len++;
    }
    return len;
}

function lockScreen(msg)
{
    if(msg){
	   sORh(msg,"block");
	}
	else{
	  $("msg").show("block");
	}
}

function unlockScreen()
{
    $("msg").hide();
    try{
        $("msg2").hide();
    }catch(e){}
        try{
        $("msg_l").hide();
    }catch(e){}
    try{
        $("msg_city").hide();
    }catch(e){}

}

/**
 * 2009-06-29 增加参数position,用来区分是输入框前的城市还是右上角的城市。
 * 当Position没有定义或Position == 1时，为右上角的城市；
 * 当Position为3时，为输入框前的城市；之所以使用3，是为了与城市所在的A标签的ID相对应，该ID统一为city3。
 * Position == 2的情况暂时没有包含在内，因为city2被不明代码占用，所以跳过。
*/
function selectCity(event,flag,frm,position){
	var msg = $("msg");
	
	if(position == 3){
		msg = $("msg_city");
	}
    var mouse = onClick(event);
    var url;
    /*msg.style.top =mouse.y;
    msg.style.left =mouse.x;
    msg.style.width = "auto";
    msg.style.height = "auto";*/
    
    if(frm)
        s_frm="&frm="+frm;
    else
        s_frm="";
       
    switch(flag)
    {
        case 1: url = "/?area=com&cmd=shortcity&tag=index";break;
        case 2: url = "/?area=com&cmd=shortcity&tag=addbiz";break;
        case 3: url = "/?area=com&cmd=shortcity&tag=compass"; msg = $("msg2"); break;
        case 4: url = "/?area=com&cmd=shortcity&tag=bizsearch";break;
        case 5: url = "/?area=com&cmd=shortcity&tag=act";break;
        case 6: url = "/?area=com&cmd=shortcity&tag=mov";break;
        case 7: url = "/?area=com&cmd=shortcity&tag=index";msg = $("msg2");break;
        case 8: url = "/?area=com&cmd=shortcity&tag=traffic";break;
        case 9: url = "/?area=com&cmd=shortcity&tag=discount";break;
        case 10: url = "/?area=com&cmd=shortcity&tag=exp";break;		
        default: return; break;
    }
    new Ajax.Request(
        url,{
            method: 'get',
            onSuccess:function(transport){
                msg.innerHTML = transport.responseText;
                lockScreen(msg);
            }
        }
    );    
}

function showMsg(info)
{
    var msg = $("msg");
    msg.style.top = 600+"px";
    msg.style.left = 400+"px";
    
    $(msg).innerHTML = '<div class="pop_window">' +
            '<div class="close"><a href="javascript:unlockScreen();"><img src="images/icon/close.gif" width="16" height="16" /></a></div>' + 
            '<center><p>' + info + '</p></center>' +
            '<div>';
    lockScreen();
}

function userChangeCity(type)
{
    var tag = type ? type : "index"; //
    var urlbase = "";
    if(isCityDomain() == true){
		urlbase = "http://www.aibang.com";
	}
	var isMapView = false;
	if(typeof QueryState != "undefined"){
	   isMapView = true;
	}
	if(isMapView) {
	   tag = "mapview_search";
	}
	if($("what")){
	   setCookie("what",getWhat());
	}
    location.href = urlbase+'/files/MoreCity1.html?tag='+tag;
}
/*
    show or hide object
*/
function sORh(obj,type)
{
    if("object" != typeof $(obj) ){
        return;
    }
    if(type)//tell us the type is undefined
    {
        if($(obj)){
	   $(obj).style.display = ""+type;
	}
        return;       
    } 
    if("none" == $(obj).style.display)
    {
        $(obj).style.display = "block";
    }
    else
    {
        $(obj).style.display = "none";
    }   
}

function disableServerMsg(){sORh("pageMsg","none");}

//几个子域名
var domainAibang = '';
var domainBus='';

function loginOrLogout(i, fromURL){
	//通过formURL可以设置登陆后到达一个新的页面
	fromURL = (fromURL)?(encodeURIComponent(fromURL)):(encodeURIComponent(window.location.href));
    if("login" == i){
        location.href = domainAibang+"/?area=user&cmd=showlogin&backurl="+fromURL;
    }
    else if("logout" == i){
        location.href = domainAibang+"/?area=user&cmd=logout&backurl="+fromURL;
    }
    else if("getpwd" == i){
        window.open(domainAibang+"/?area=user&cmd=showlogin&gpwd=1&backurl="+fromURL,"_blank");
    }
}

function onClick(event)
{    
    ev = event || window.event;
    if(ev.pageX || ev.pageY)
    {
        return {x:ev.pageX+"px", y:ev.pageY+"px"};
    }
    return {
        x:(ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft),
        y:(ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop)
    };
}

function showLock()
{
    var lock = $('lock');

    var w = window.screen.width;
    var h = window.screen.height;
    lock.style.left = 0+"px";
    lock.style.top = 0+"px";
    lock.style.width = w+"px";
    lock.style.height = h+"px";
    lock.show('block');    
}

function hideLock()
{
    $('lock').hide();
}
function showWaiting(msg)
{
    //showLock();
    $("ajax_loading").innerHTML = '<img src="../images/ajax-loader.gif" />';    
    ajaxLoading(true);
    setTimeout( "closeWaiting",5000 );
}
function closeWaiting()
{
    //hideLock();
    ajaxLoading(false);    
}
function showAddrError(msg)
{
    $("addrError").innerHTML=msg;
    $("addrError").show("block");
    
    setTimeout("hideAddrError()",5000);
}
function hideAddrError()
{
    $("addrError").innerHTML="";
    $("addrError").hide();
}
function centerDiv(div)
{
    var deltaX = ABBrowser.getScrollLeft();
    var deltaY = ABBrowser.getScrollTop();
    var innerWidth = ABBrowser.getViewWidth();
    var innerHeight = ABBrowser.getViewHeight();
    var posX = deltaX+parseInt(innerWidth/2,10);
    var posY = deltaY+parseInt(innerHeight/2,10);
    
    div.style.left = posX+"px";
    div.style.top = posY+"px";
}
function ajaxLoading(isLoading, dPosX, dPosY)
{
    var loadingObj = $("ajax_loading");    
    if(isLoading == true){
        centerDiv(loadingObj);
        //对目前的坐标进行必要的修正
        if(dPosX)loadingObj.style.left = (parseInt(loadingObj.style.left) + dPosX) + "px";
        if(dPosY)loadingObj.style.top  = (parseInt(loadingObj.style.top)  + dPosY) + "px";
        loadingObj.show("block");
    }
    else{
        loadingObj.hide();
    }
}

if(!comAddr){
	var comAddr = "全市";//全 市
}
if(!comWhat){
	var comWhat = "";
}

String.prototype.replaceSs = function(){
    return this.replace(/\s+/, '');
}
function onMouseOver(addr)
{
    addr.style.cursor = "text";
    if(comAddr != addr.value.strip()){
        addr.select();
    }
    clearAddr(addr);
}
function onMouseOut(addr){
}
function clearAddr(addr)
{
    if(addr.value == comAddr){
        addr.value = "";
        addr.style.color = "#000";
    }
    //sORh("address_drop","none");
    //sORh("service_drop","none");
    addr.focus();
}

function clearInputName(obj)
{
	obj.value = "";
	obj.style.color = "#000";   
    obj.focus();
}


function resetAddr(addr)
{
    if(!addr.value){
        addr.value = comAddr;
        addr.style.color = "#999";
    }    
}


function clearWhat(what)
{
    if(what.value == comWhat){
        what.value = "";
        what.style.color = "#000";
    }
    //sORh("address_drop","none");
    //sORh("service_drop","none");
}

function resetWhat(what)
{
    if(!what.value){
        what.value = comWhat;
        what.style.color = "#999";
    }
}

function getWhat(obj)
{
	if(!obj){
		var what =  $('what').value;
	}
	else{
		var what = obj.value;
	}
    what = what.strip();
    if(what == comWhat)
        return ""
    return what;
}

function setWhat( what )
{
    var obj = $('what');
    var sbj = $('what_b');
    if(!what || what == comWhat)
    {
        if(obj){
            obj.value = comWhat;
            obj.style.color = "#999";
        }
        if(sbj){
            sbj.value = comWhat;
            sbj.style.color = "#999";
        }
    }
    else
    {
        if(obj){
            obj.value = what;
            obj.style.color = "#000";
        }
        if(sbj){
            sbj.value = what;
            sbj.style.color = "#000";
        }
    }        
}

function getAddr(obj)
{
	if(!obj){
		var addr =  $('addr').value;
	}
	else{
		var addr = obj.value;
	}
    addr = addr.strip();
    if(addr.replaceSs() == comAddr.replaceSs() || addr.replaceSs() == comAddr)
        return ""
    return addr;
}

function setAddr( addr)
{
    var obj = $('addr');
    var sbj = $('addr_b');
    if(!addr || addr == comAddr)
    {
        if(obj){
            obj.value = comAddr;
            //obj.style.color = "#999";
        }
        if(sbj){
            sbj.value = comAddr;
            //sbj.style.color = "#999"; 
        }
    }
    else
    {
        if(obj){
            obj.value = addr;
            obj.style.color = "#000";
        }
        if(sbj){
            sbj.value = addr;
            sbj.style.color = "#000";
        }
    }
}

function hideEmptyRecentAddr()
{
    for(var i=5; i > 0; i--)
    {
        var o = $("addr"+i);
        if ( o  && o.innerHTML)
        {
            o.show("block");
        }
        else
        {
            o.hide();
        }
    }
}

function defaultOnload(){
	var error;
    try{$("what").focus();}
    catch(error){}
    //setAddr(getCookie('addr'));
    //setWhat(getCookie('what'));
    //loadRecentAddr();
}

function channelChange(type)
{
    //#s delete or add type=mapview
    var arr = new Array();
    if(type == "mapview"){//map-view
        //var href= decodeURIComponent(location.href);
        var href= location.href;
        var i = href.indexOf( "#s=" );
        if(i>0)
        {//has hash
            var tmp = location.href.split("#s=");
            var url = tmp[0]+"&type=mapview";
            var str = decodeURIComponent(tmp[1]).split("\n");
            var __flag = 0;
            for(var i=0; i<str.length; i++)
            {
                var __name = str[i].split("\r")[0];
                var __value = str[i].split("\r")[1];
                if(__name == "type"){
                    __value = "mapview";
                    __flag = 1;
                }
                else if(__name == "city"){
                    __value = getCookie("city")?getCookie("city"):'北京';
                }
                else if(__name == "a"){
                    __value = getCookie("addr")?getCookie("addr"):'';
                }
                arr.push(__name+"\r"+__value);
            }
            if(!__flag){
                arr.push("type"+"\r"+"mapview");
            }
            url += "#s=" + encodeURIComponent(arr.join("\n"));
        }
        else
        {//none hash
            var re = /(?!&|\?)(.*?)=(.*?)(?=&|$)/ig;
            var r = location.href.match(re);
            var url="?area=bizsearch&cmd=bigmap&type=mapview#s=";       
            for(i=0;i<r.length;i++)
            {
                var pair=r[i].split("=");
                if(pair[0]=="cmd"){
                    arr.push(pair[0]+"\r"+"biz"); //map-view no cmd default value;
                }
                else if(pair[0].indexOf("?")>0){
                    //do nothing.
                }                
                else{
                    arr.push(pair[0]+"\r"+decodeURIComponent(pair[1]));
                }            
            }
            if(!arr['type']){
                arr.push("type"+"\r"+"mapview");
            }        
            url += encodeURIComponent(arr.join("\n"));
        }
    }
    else{//text-view        
        var urr = location.href.replace(/&type=mapview/g,"");
        var uri = urr.split("#s=");
        var url = "/?area=bizsearch&";
        var str = decodeURIComponent(uri[1]).split("\n");
        var __flag = 0;
        for(var i=0; i<str.length; i++)
        {
            var __name = str[i].split("\r")[0];
            var __value = str[i].split("\r")[1];
            if(__name == "type"){
                __value = "";
                __flag = 1;
                continue;
            }
            else if(__name == "city"){
                __value = getCookie("city")?getCookie("city"):'北京';
            }
            /*else if(__name == "a"){
                __value = getCookie("addr")?getCookie("addr"):'';
            }*/
            else if(__name == "cmd"){
                __value = "bigmap";
            }            
            arr.push(__name+"="+encodeURIComponent(__value));
        }
        if(!__flag){
            arr.push("type"+"="+"textview");
        }
        url += arr.join("&");
    }
    location.href = url;
}

function boldLiFont(attachID,selectObj)
{
    if((typeof document.getElementById(attachID)) != "object"){
        throw("bad attach id");
    }
    var oLi = document.getElementById(attachID).getElementsByTagName("LI");
    for(var i=0;i<oLi.length;i++)
    {
        if(oLi[i] == selectObj){
            selectObj.style.fontWeight='bold';
        }
        else{
            oLi[i].style.fontWeight='normal';
        }
    }
}

(function()
{
    if(document.addEventListener){
        document.addEventListener("click",function(){sORh("msg_l","none");sORh("msg","none");sORh("msg_city","none");/*sORh("address_drop","none");sORh("service_drop","none");*/},false);
    }
    else if(document.attachEvent){
        document.attachEvent('onmouseup',function(){sORh("msg_l","none");sORh("msg","none");sORh("msg_city","none");/*sORh("address_drop","none");sORh("service_drop","none");*/});
    }
})();


function selectKeyword(what)
{
    setWhat(what);
    //sORh('service_drop', 'none');
    //$('what').focus();
    setout('frt');
}

//deleted by xgliu ,2008-11-17
/*
function cityChangedUserEyeAttach(city)
{
    setAddr("");
    setCookie("addr","");
    $("city").innerHTML = city;
    $('change_city').innerHTML = '您已经切换到'+city+'市';
    $('change_city').style.display = '';
    setTimeout("cityChangedBySearch()",5000);
}
*/
function cityChangedBySearch()
{
    sORh('change_city','none'); 
}

function mouseOverAddr(obj)
{
    mouseOverDiv(obj,pulldownId);
}
function mouseOverWhat(obj)
{
    mouseOverDiv(obj,pulldownId);
}

function mouseOverDiv(obj,sbj)
{
	if(!sbj){
		sbj = pulldownId;
	}
    var oA = document.getElementById(sbj).getElementsByTagName("a");
    for(var i=0; i<totalResultNum-1; i++)
    {
        if(oA[i] == obj){
            curPosition = i;
            oA[i].className = 'drop_item';
        }
        else{
            oA[i].className = '';
        }
    }
}


function mouseOutDiv(obj)
{
    obj.className = '';
}

//deleted by xgliu 2008-11-17
/*
function forceChangeCity(aimerCity)
{
    $('fsubmit').focus();
    if(!aimerCity){return false;}
    var oInput = document.getElementById('address_drop').getElementsByTagName("INPUT");
    if(oInput.length == 0){//no matched address
        return false;//do not change
    }
    else{
        var _v = oInput[0].value;
        var _n = oInput[0].name;
        var _isEn = aimerCity.charCodeAt(0)<128;
        var _hasCity = aimerCity.split(""+_n)[1];
        var _isCity = -1;
        if(_hasCity){
            _isCity = _hasCity.indexOf("市");
        } 
        if((_v == 1 || _v == 3)&& (_isEn || !_hasCity || _isCity>-1)){//make sure the aimer is correct
            var city = oInput[0].name;
            cityChangedUserEyeAttach(city);//show city change  
            $('address_drop').innerHTML = "";
            return city; //force change
        }
        else{
            return false;
        }
    }
}
*/
function userLatestSearch(){
   var city = getCookie("city");
   var addr = getCookie("addr");
   var q    = getCookie("what");

   if(((addr && (addr.split("loc:"))[1]))||!q){
      return;
   }
   var __cr = getCookie("uls");//city::addr::q|||city::addr::q
   var __items = __cr.split("|||");
   var __iLength = __items.length;
   var __tmp = city+":::"+addr+":::"+q;
   var __swap = __tmp+"|||";
   var j = 1;
   for(var i=0; i<3; i++){
      if(__tmp != __items[i] && __items[i]){
         if(j == 3){
	    break;
	 }
	 if(i == __iLength-1){
	    __swap += __items[i];
	 }
	 else{
	    __swap += __items[i]+"|||";
	 }
	 j++;
      }
   }
   if(__cr != __swap){
      setCookie("uls",__swap);
   }
}
function setRecentEvents(){
    var city = getCookie("city");
    var addr = getCookie("addr");
    userLatestSearch();
    if(!addr || (addr.split("loc:"))[1]){
       return;
    }
    var __cr = getCookie("recentCR");//city:::addr|||city:::addr
    var __items = __cr.split("|||");
    var __iLength = __items.length;
    var __tmp = city+":::"+addr;
    var __swap = __tmp+"|||";
    var j = 1;
    for(var i=0; i<3; i++){
        if(__tmp != __items[i] && __items[i]){
        if(j == 3){
            break;
        }
        if (i == __iLength-1){
           __swap += __items[i];
        }
        else{
           __swap += __items[i]+"|||";
        }
        j++;
    }
    }
    if(__cr != __swap){
       setCookie("recentCR",__swap);
    }
}
//hot tag search
function hotSearch(obj)
{
    var what = obj.innerHTML;
    setWhat(what);
    setout("frttag");
}

function num2Char(num)
{
    switch ( num) {
        case 0: return "m1";
        case 1: return "m2";
        case 2: return "m3";
        case 3: return "m4";
        case 4: return "m5";
        case 5: return "m6";
        case 6: return "m7";
        case 7: return "m8";
        case 8: return "m9";
        case 9: return "m10";
        default: return "N";
    }
}

/*
    通过各种途径进入文本视图的总入口。
    目前只设计为搜索和本地指南专用。(2007-10-23)
    将来可能扩展包括点评和图片，但是不会包括社区。
    city:城市
    addr:地址
    what:查询内容
    extra:url中的附加信息（主要是为了统计运行所需数据的需要）;    
    tagert:window.open style
*/
function gotoTextView(city,addr,what,extra,target)
{
    if(!extra)	extra="";
    if(!what)	what="";
    if(!target)	target="_self";
    setCookie('what',what);
    var url = "/?area=bizsearch&cmd=bigmap&city="+$E(city)+"&a="+$E(addr)+"&q="+$E(what)+extra;
    window.open(url,target);
}

function selectBiz()
{
    var city = $('city').innerHTML;
    var addr = getAddr();
    //location.href = "/?area=common&cmd=services&city="+encodeURIComponent(city)+"&a="+encodeURIComponent(addr);    
    window.open("/?area=common&cmd=services&city="+encodeURIComponent(city)+"&a="+encodeURIComponent(addr),"_blank");    
}
/*
*   user
*/
function changeCityAddr(city,addr)
{
    setCookie("city",city);
    setCookie("addr",addr);
    gotoTextView(city,addr);
}

function changeCity(obj,tag)
{
   var city = obj.innerHTML.stripTags();
   $("city").innerHTML = city;
   if($("city3")){
   		$("city3").innerHTML = city;
   }
   setAddr("");
   setCookie("city",city);
   setCookie("addr","");
   var urlBase = "/";
   unlockScreen();
   switch(tag) {
	  case 'act': urlBase = activityChangeCityUrl(city); break;
	  case 'mov': urlBase = movieChangeCityUrl(city); break;
	  case 'traffic': urlBase = trafficChangeCityUrl(city); break;
      case 'discount': urlBase = discountChangeCityUrl(city); break;
	  case 'bizsearch': urlBase = searcjChangeCityUrl(city); break;
	  case 'exp': urlBase = expChangeCityUrl(city); break;	
	  default: break;
   }		
   window.open(urlBase, "_self");
}

var ABBrowser = {
    navi: navigator.userAgent.toLowerCase(),
    isIE: function(){
        var tmp = this;
        return (tmp.navi.indexOf("msie") != -1) && (tmp.navi.indexOf("opera") == -1) && (tmp.navi.indexOf("omniweb") == -1);
    },
    getBody: function(){
        return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
    },
    getScrollTop: function(){
        return this.isIE()?this.getBody().scrollTop:window.pageYOffset;
    },
    getScrollLeft: function(){
        return this.isIE()?this.getBody().scrollLeft:window.pageXOffset;
    },
    getAvailableHeight:function(){
        return this.getBody().offsetHeight>this.getBody().scrollHeight?this.getBody().offsetHeight:this.getBody().scrollHeight;
    },
    getAvailableWidth: function(){
        return this.getBody().offsetWidth>this.getBody().scrollWidth?this.getBody().offsetWidth:this.getBody().scrollWidth;        
    },
    getViewWidth: function(){
        return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
    },
    getViewHeight: function(){
        return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
    },
    getPointerPositionInDocument:function(evt){
       var eventObject = evt;
       var x = eventObject.pageX || (eventObject.clientX+ABBrowser.getBody().scrollLeft);
       var y = eventObject.pageY || (eventObject.clientY+ABBrowser.getBody().scrollTop);
       return {'x':x,'y':y};
    },
	getElementPosition: function(ebj){
	   if(typeof ebj.offsetParent != "undefined"){
	      for(var _x = 0, _y = 0; ebj; ebj = ebj.offsetParent) {
		      _x += ebj.offsetLeft;
			  _y += ebj.offsetTop;
		  }
		  return {"x":_x,"y":_y};
	   }
	   else{
	      return {"x":_x,"y":_y};
	   }
	}
}
var ABMessage = {
	_obj				: null,	//当前展示消息的div对象
	_top				: 0,	//需要显示的div的左上角坐标
	_left				: 0,	
	_height				: 470,	//需要显示的div的高度与宽度
	_width				: 600,
	_scrollTop			: 0,	//当前浏览器展示左上角坐标
	_scrollLeft			: 0,
	_availableHeight	: 0,	//当前浏览器展示的高度与宽度
	_availableWidth		: 0,
	_realHeight			: 0,	//浏览器实际的有用的高度与宽度
	_realWidth			: 0,
	setAvailableTopLeft: function(){
		ABMessage._scrollTop		= ABBrowser.getScrollTop();
		ABMessage._scrollLeft		= ABBrowser.getScrollLeft();
		ABMessage._availableHeight	= ABBrowser.getViewHeight();
		ABMessage._availableWidth	= ABBrowser.getViewWidth();
		//获得页面实际可见的高度和宽度
		if(ABMessage._realHeight && ABMessage._realHeight < ABMessage._availableHeight)
			ABMessage._availableHeight = ABMessage._realHeight;
		if(ABMessage._realWidth && ABMessage._realWidth < ABMessage._availableWidth)
			ABMessage._availableWidth = ABMessage._realWidth;
		ABMessage._top  = ABMessage._scrollTop  + (ABMessage._availableHeight - ABMessage._height)/2;
		ABMessage._left = ABMessage._scrollLeft + (ABMessage._availableWidth  - ABMessage._width)/2;
		if(ABMessage._top < ABMessage._scrollTop) ABMessage._top = ABMessage._scrollTop;
	},
	getMessageView: function(objId, url, realW, realH){
        new Ajax.Request(
            url,{
                method:'get',
                onSuccess: function(transport){
                    //如果返回内容的Header中包含ValidatePage字段，则说明用户的请求被过滤系统拦截了，需要跳转到验证页面
                     if(transport.getResponseHeader('ValidatePage')){
                        return window.open("/?area=common&cmd=validate&validate=1&url="+$E(location.href),"_self");

                    }
                    else if(transport.getResponseHeader('needlogin')){
                    	var backurl = (ABMessage._backUrl)?(ABMessage._backUrl):($E(location.href));
                    	var loginmsg = transport.getResponseHeader('loginmsg')?transport.getResponseHeader('loginmsg'):$E('您需要登录后，才能免费发送到手机')
                    	return window.open("/?area=user&cmd=showlogin&backurl="+backurl+"&msg="+loginmsg,"_self");
                    }
                    ABMessage.setAvailableTopLeft();
                    ABMessage._obj.style.top 		= ABMessage._top +"px";
                    ABMessage._obj.style.left 		= ABMessage._left + "px";
                    ABMessage._obj.style.position 	= "absolute";
                    ABMessage._obj.innerHTML 		= transport.responseText;
                    ABMessage._obj.style.display 	= "block";
                    if($('needfocus')) $('needfocus').focus();
                }
            }
        );
        ABMessage._obj = $(objId);
        if(realH) ABMessage._realHeight	= realH;
        if(realW) ABMessage._realWidth	= realW;
    },
     sendMessage:function(url,params,obj){
        new Ajax.Request(
            url,{
                method:'post',
                parameters:params,
                onSuccess: function(transport){
                    $(obj).innerHTML = transport.responseText;
                }
            }
        );
    },
    closeView:function(){
    	var obj =  ABMessage._obj;
    	ABMessage.__destructMSG(obj);
    },
    __destructMSG: function(obj){
        $(obj).innerHTML = '';
        $(obj).style.display = 'none';
        $(obj).style.top = 0;
        $(obj).style.left = 0;
    }
}

function emailView(bid, realW)
{
    var url = "/?area=msg&cmd=email&id="+bid+"&t="+new Date().getTime();
    if(realW) ABMessage.getMessageView('msg1', url, realW);
    else ABMessage.getMessageView('msg1', url);
}
function emailErrorView(bid,uri,realW)
{
    var url = "/?area=msg&cmd=email&id="+bid+""+uri;
    if(realW) ABMessage.getMessageView('msg1', url, realW);
    else ABMessage.getMessageView('msg1',url);
}

var contactsList;
var contactsDropList;
function mobileView(bid, realW, cmd)
{
	cmd = cmd?cmd:'mobile';
    var url = "/?area=msg&cmd="+cmd+"&id="+bid+"&t="+new Date().getTime();
	if(realW) ABMessage.getMessageView('msg1',url, realW);
    else ABMessage.getMessageView('msg1',url);
	
	var url = "/?area=user&cmd=contacts_list&input=ALL&tag=1";
	new Ajax.Request(
			url,
			{
				method:'get',
				 onSuccess: function (transport)
				 {
					var responseMsg = transport.responseText;
					if (responseMsg) {
						contactsList = responseMsg.split(",");
					}else{
						contactsList="";
					}
				}
			});
		
		
	var url = "/?area=user&cmd=contacts_list&input=ALL&tag=2";
	new Ajax.Request(
			url,
			{
				method:'get',
				 onSuccess: function (transport)
				 {
					contactsDropList = transport.responseText;
				}
			});		

}

/**
 *  拖动的函数
*/
var DragAndDrop = {
	
	//拖动的对象
	dragObj : null,
	//响应的对象 
	moveObj	: null,
	//拖动开始时拖动对象与鼠标事件的横坐标差
	deltaX : 0,
	//拖动开始时拖动对象与鼠标事件的纵坐标差
	deltaY : 0,

	//开始拖动，绑定响应事件，记录坐标差
	startdrag:function(obj,event){
	
		DragAndDrop.dragObj = $(obj);
		DragAndDrop.deltaX=parseInt(DragAndDrop.dragObj.style.left)-event.clientX-document.documentElement.scrollLeft;
		DragAndDrop.deltaY=parseInt(DragAndDrop.dragObj.style.top)-event.clientY-document.documentElement.scrollTop;
		attachEventListener(document.body,"mousemove",DragAndDrop.drag,false);
		attachEventListener(document.body,"mouseup",DragAndDrop.drop,false);
		
		var target =event.srcElement?event.srcElement:event.target;
		DragAndDrop.moveObj = target;
		DragAndDrop.moveObj.style.cursor="move";
		
		sORh(contactDropDownId,"none");
		
		if(pulldownAjax && pulldownAjax.abort){
			pulldownAjax.abort();
		}
		
		
	},

	//响应拖动事件
	drag:function(event){
		if(DragAndDrop.dragObj){
			DragAndDrop.dragObj.style.left=(event.clientX+DragAndDrop.deltaX+document.documentElement.scrollLeft)+"px";
			DragAndDrop.dragObj.style.top=(event.clientY+DragAndDrop.deltaY+document.documentElement.scrollTop)+"px";
		}
	},

	//拖动停止
	drop:function(event)
	{
		DragAndDrop.moveObj.style.cursor="pointer";
		DragAndDrop.dragObj = null;
		//此处写下取消前面定下的时间绑定函数，以避免内存泄露
	}
}

//记录当前的发送公交驾乘的方案号
var curMobileTraffic=0;

function mobileTrafficView(index){
	var objInputTag = (Tag.curType==1)?Tag.objInputBus:((Tag.curType==4)?Tag.objInputDrive:null);
    var x1 = objInputTag['x1'].value;
    var x2 = objInputTag['x2'].value;
    var y1 = objInputTag['y1'].value;
    var y2 = objInputTag['y2'].value;
    var start=$('bus_name1').value;
    var end=$('bus_name2').value;
    var city = $('g_city_name').innerHTML;
    
	
    var url = "/?area=msg&cmd=mobile_traffic";
    url += "&x1="+x1+"&x2="+x2+"&y1="+y1+"&y2="+y2+"&city="+$E(city)+"&origin="+$E(start)+"&end="+$E(end)+"&index="+(index-1);
    if(BusManage.getJuHe()) url += "&method=2";
	else{
    	if(BusManage.curOrderType) url += "&rc="+BusManage.curOrderType;
		if(BusManage.mark) url += "&method=1";
	}

    ABMessage.getMessageView('msg1',url);
    if(index > 0) curMobileTraffic = index;
	
	var url = "/?area=user&cmd=contacts_list&input=ALL&tag=1";
	new Ajax.Request(
			url,
			{
				method:'get',
				 onSuccess: function (transport)
				 {
					var responseMsg = transport.responseText;
					if (responseMsg) {
						contactsList = responseMsg.split(",");
					}else{
						contactsList="";
					}
				}
			});
		
		
	var url = "/?area=user&cmd=contacts_list&input=ALL&tag=2";
	new Ajax.Request(
			url,
			{
				method:'get',
				 onSuccess: function (transport)
				 {
					contactsDropList = transport.responseText;
				}
			});		
}

function mobileErrorView(bid,ep)
{
    var url = "/?area=msg&cmd=mobile&id="+bid+"&t="+new Date().getTime();
    if(ep){
        url += "&ep="+$E(ep);
    }
    ABMessage.getMessageView('msg1',url);
}


function cn2en(str)
{
    var length = str.length;
    var r = ""
    for(var i=0; i<length; i++)
    {
        if(str.charCodeAt(i)>65280 && str.charCodeAt(i)<65375)
        {
            r += String.fromCharCode(str.charCodeAt(i)-65248);
        }
        else{
            r += String.fromCharCode(str.charCodeAt(i));
        }
    }
    return r;
}

function ContactsDropClose()
{
	if($(contactDropDownId) && $(contactDropDownId).style.display == 'block'){
		sORh(contactDropDownId,'none');
	}	
}

function checkPhoneRepeat()
{
	with(document.mobile){
		var phones ="";	
        for(var i=0;i<5;i++){
			var sbj2 = 'p_name'+i;
			var sbj1 = 's_name'+i;
			var sbj4 = 's'+i;
			var sbj3 = 'p'+i;		
		
            var tmp = phone[i].value.strip();
			if ( tmp.length != 11 ) 
				continue;

			if (phones.search(tmp) != -1){
				sORh(sbj1,'none');
				$(sbj2).innerHTML = "";
				sORh(sbj2,'none');
				sORh(sbj3,'none');
				sORh(sbj4,'block');
			}
			else{
				if ( $(sbj4).style.display == "block" ){	
					var index = contactsList.indexOf(tmp);	
					if ( index != -1 ){	
						sORh(sbj1,'none');
						sORh(sbj3,'none');
						sORh(sbj4,'none');							
						$(sbj2).innerHTML = contactsList[contactsList.indexOf(tmp)+1];
						sORh(sbj2,'block');	
					}else{
						sORh(sbj1,'block');
						sORh(sbj3,'none');
						sORh(sbj4,'none');							
						$(sbj2).innerHTML = "";
						sORh(sbj2,'none');		
					}
				}
			}
			phones += tmp +",";	

		}
	}

}

/**
*	type :
		int
		onblur时选1，onkeyup时选0	 
*/
function checkContactsPhone(uid,idx,type)
{
    var phone_num = $('phone_'+idx).value.strip();
	var sbj2 = 'p_name'+idx;
	var sbj1 = 's_name'+idx;
	var sbj4 = 's'+idx;
	var sbj3 = 'p'+idx;
	
	//onblur时要保证手机号码为11位或0位，keyup时只需要保证不存在非法字符
	var patrn = "";
	if(type == 0){
		patrn=/^\d{0,11}$/;
	}
	else{
		patrn=/^(\d{11}){0,}$/;
	}
	if ( !patrn.exec(phone_num) )
	{
		sORh(sbj1,'none');
		$(sbj2).innerHTML = "";
		sORh(sbj2,'none');
		sORh(sbj3,'block');
		sORh(sbj4,'none');
		return;
	}
	else{
		sORh(sbj1,'none');
		$(sbj2).innerHTML = "";
		sORh(sbj2,'none');
		sORh(sbj3,'none');
		sORh(sbj4,'none');
	}
	
	
	
	//如果存在11个字符，则判断为手机，允许用户处理。
	if( phone_num.length == 11 ){
		var index = contactsList.indexOf(phone_num);
		if( index == -1 ){
			sORh(sbj3,'none');
			sORh(sbj4,'none');		
			$(sbj2).innerHTML = "";
			sORh(sbj2,'none');
			sORh(sbj1,'block');
			//return;
		 }
		 else {//手机在通讯录中
			if ( $(sbj4).style.display == "none" ){
			sORh(sbj1,'none');
			sORh(sbj3,'none');
			sORh(sbj4,'none');							
			$(sbj2).innerHTML = contactsList[index+1];
			sORh(sbj2,'block');	
			//return;
			}
		 }
		 checkPhoneRepeat()
    }
}

function checkEnCode(obj,sbj)
{
    var tmp = obj.value.strip();
    if(!tmp){
        return;
    }
    if(isNaN(tmp) && tmp){
        sORh(sbj,'block');
    }
    else{
        new Ajax.Request(
            "/",{
                method: 'post',
                parameters: "area=msg&cmd=code&code="+$E(tmp),
                onSuccess: function(transport){
                    if(transport.responseText == 1){
                        sORh(sbj,'none');
                    }
                    else{
                        sORh(sbj,'block');
                    }
                }
            }
        );        
    }
}

function copy(obj)
{
    try{
        var targetText = $(obj);
        targetText.focus();
        targetText.select();
        var clipeText = targetText.createTextRange();
        clipeText.execCommand("Copy");
    }
    catch(e){
        alert("您使用的浏览器不支持自动复制url功能，清选中url，以ctrl+c进行复制.");
    }  
}


function copy2Subject(obj)
{
    var uname = obj.value.strip();
    var str = document.email.subject.value;
    var flag = 0;
    for(var i=0; i< uname.length; i++)
    {
        if(uname[i] == str[i]){
            flag = 1;
        }
        else{
            flag = 0;
        }
    }
    if(flag == 0){
        document.email.subject.value = uname+str;
    }
}


function sendMobileMsg()
{
    with(document.mobile){
        var nos = "";
		var names = "";
		var checked = "";
        for(var i=0;i<5;i++)
		{		
		    var tmp = phone[i].value.strip();
			var tmp_name = name[i].value.strip();
			if( tmp_name == "姓名")
				var tmp_name = "";
			
			if($('s'+i).style.display == "block" || $('p'+i).style.display == "block"){
				return;
			}
					
			if( $('ckb_'+i).checked == true )
				checked += i +","; 			
			nos += cn2en(tmp) +",";
			names += tmp_name +",";	
				
			if(tmp.length ==0)
				continue;
			else 
				if(tmp.length!=11){
					sORh('p'+i,'block');
					$('p_name'+i).innerHTML = "";
					sORh('p_name'+i,'none');
					sORh('s_name'+i,'none');
					sORh('s'+i,'none');
					return;
				}
        }
			
        if(!nos){
            return;
        }
        var c = code.value.strip();
        if(isNaN(c) || c.length<5){
            sORh('cco','block');
            return;
        }  
        var ids = bid.value;
        var n = bname.value;
    }    
	
    var url = "/?mc="+$E(ids);

    var params = "area=msg&cmd=mmsg&no="+$E(c)+"&phone="+$E(nos)+"&name="+$E(n)+"&id="+$E(ids)+"&names="+$E(names)+"&checked="+$E(checked);
    ABMessage.sendMessage(url,params,"msg1");
}

function sendMobileTrafficMsg(uid)
{

     with(document.mobile){
        var nos = "";
		var names = "";
		var checked = "";
        for(var i=0;i<5;i++)
		{
		    var tmp = phone[i].value.strip();
			var tmp_name = name[i].value.strip();
			if( tmp_name == "姓名")
				var tmp_name = "";
				
			if($('s'+i).style.display == "block" || $('p'+i).style.display == "block")
			{
				return;
			}
			
			if( $('ckb_'+i).checked == true ) checked += i +","; 
			nos += cn2en(tmp) +",";
			names += tmp_name +",";	
				
			if(tmp.length ==0)
				continue;
			else 
				if(tmp.length!=11){
					sORh('p'+i,'block');
					$('p_name'+i).innerHTML = "";
					sORh('p_name'+i,'none');
					sORh('s_name'+i,'none');
					sORh('s'+i,'none');
					return;
				}	
        }
			
        if(!nos){
            return;
        }
		
        var c = code.value.strip();
        if(isNaN(c) || c.length<5){
            sORh('cco','block');
            return;
        }  
		
        var ids = bid.value;
    }  

    var x1 = document.mobile.x1.value;
    var x2 = document.mobile.x2.value;
    var y1 = document.mobile.y1.value;
    var y2 = document.mobile.y2.value;
    var city = document.mobile.city.value;
    var origin = document.mobile.origin.value;
    var end   = document.mobile.end.value;
    var index   = document.mobile.index.value; 
  

    var url = "/?area=msg&cmd=mmsg_traffic&no="+$E(c)+"&phone="+$E(nos)+"&names="+$E(names)+"&checked="+$E(checked);
	
    url += "&x1="+x1+"&x2="+x2+"&y1="+y1+"&y2="+y2+"&city="+$E(city)+"&origin="+$E(origin)+"&end="+$E(end)+"&index="+(index);
    
    if(BusManage.getJuHe()) url += "&method=2";
	else{
    	if(BusManage.curOrderType) url += "&rc="+BusManage.curOrderType;
		if(BusManage.mark) url += "&method=1";
	}
	
	ABMessage.getMessageView('msg1',url); 
}

function closeMsgViewAuto()
{
    sORh('msg1','none');
}
function printPage()
{
    window.print();
}

function sethp()
{
        new Ajax.Request(
            "/",{
                method: 'get',
                parameters: "area=common&cmd=sethomepage"
            }
        );        
}

function attachEventListener(target,eventType,functionRef,capture)
{
    if(!target){
        return;
    }
    if(typeof target.addEventListener != "undefined"){
        target.addEventListener(eventType,functionRef,capture);
    }
    else if (typeof target.attachEvent != "undefined"){
        var functionString = eventType + functionRef;
        target["e" + functionString] = functionRef;
        target[functionString] = function(event){
            if(typeof event == "window.event"){
                event = window.event;
            }
            target["e" + functionString](event);
        };
        target.attachEvent("on" + eventType,target[functionString]);
    }
    else{
        eventType = "on" + eventType;
        if(typeof target[eventType] == "function"){
            var oldListener = target[eventType];
            target[eventType] = function(event){
                oldListener();
                return functionRef;
            }
        }
        else{
            target[eventType] = functionRef;
        }
    }
}

function detachEventListener(target, eventType, functionRef,capture)
{
    if (typeof target.removeEventListener != "undefined"){
        target.removeEventListener(eventType, functionRef, capture);
    }
    else if (typeof target.detachEvent != "undefined"){
    var functionString = eventType + functionRef;
        target.detachEvent("on" + eventType, target[functionString]);
        target["e" + functionString] = null;
        target[functionString] = null;
    }
    else{
        target["on" + eventType] = null;
    }
}

function cancelEvent(e)
{
    var _e = e?e:window.event;
    if(e.stopPropagation){
        e.stopPropagation();
    }
    if(e.preventDefault){
        e.preventDefault();
    }
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}



function userSuggest(obj)
{
    var base = location.href;
    var url = obj.href+"&url="+$E(base);
    window.open(url,"__target");
}
/**
* 设为首页
*/
function setHomepage(obj)
{
	try{
	obj.style.behavior='url(#default#homepage)';
	obj.setHomePage('http://www.aibang.com');
	}
	catch(e){
		alert("您现在使用的浏览器无法自动设为首页，请手动设置~");
	}
}
/**
* 加入到收藏夹
*/
function addFavorite()
{
	var url = "http://www.aibang.com";
	var title = "爱帮 - 中国最大的生活搜索引擎 - 生活黄页 - 本地搜索 - 打折优惠 - 公交查询 - 城市指南";
	if (window.sidebar) {
		window.sidebar.addPanel(title, url,"");
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else if( window.opera && window.print ) {
		return true;
	}
}

/**
	弹出免费拨打400电话页面
*/
/*
function freePhone(id400)
{
	var url = "http://401.callpay.cn/aibang/ppcall.aspx?m="+id400+"&f="+encode64(id400);
	window.open(url,'AI_BANG_TONG', 'height=410, width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=yes');
}
*/

/**
	蚂蚁互动的URL编码函数
*/
/*
function encode64(input) {
	var keyStr = "ABCDEFGHIJKLMNOP" +
	"QRSTUVWXYZabcdef" +
	"ghijklmnopqrstuv" +
	"wxyz0123456789+/" +
	"=";
	input = escape(input);
	var output = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;

	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output = output +
		keyStr.charAt(enc1) +
		keyStr.charAt(enc2) +
		keyStr.charAt(enc3) +
		keyStr.charAt(enc4);
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";
	} while (i < input.length);

	return output;
}
*/

/*IE 处理背景图片缓存*/
attachEventListener(window,'load',function(){
	if(ABBrowser.isIE()){
		document.execCommand("BackgroundImageCache", false, true);//clear ie images cache
	}    
},false);

function isCityDomain()
{
	var arr = ["beijing","shanghai","tianjin","chongqing",
	"hefei","fuzhou","guangzhou","nanning",
	"guiyang","lanzhou","haikou","shijiazhuang",
	"zhengzhou","wuhan","changsha","haerbin",
	"changchun","nanjing","nanchang","shenyang",
	"huhehaote","taiyuan","xian","jinan",
	"chengdu","wulumuqi","kunming","hangzhou",
	"shenzhen","xiamen","ningbo","qingdao",
	"dalian","suzhou"];
	for(var i =0;i<arr.length;i++){
		if(location.hostname.indexOf(arr[i]) == 0){
			return true;
		}
	}
	return false;
}

/**
	下拉框相关内容
*/
var curPosition = -1; //initial is -1
var totalResultNum = 0; //initial is 0
var curInput = null;
var pulldownId = "address_drop";
//当前最后一个下拉框请求ajax队形
var pulldownAjax = null;

function responseInput(e,obj)
{
	if(!$(pulldownId)){
		return;
	}
	var oA = $(pulldownId).getElementsByTagName("a");
    if(!oA.length || $(pulldownId).style.display == "none"){
        return;
    }
    totalResultNum = oA.length;
    response(e,obj?obj:this,pulldownId);
    
}

function response(e,sbj,obj)
{
    var oA = document.getElementById(obj).getElementsByTagName("a");
    var oS = document.getElementById(obj).getElementsByTagName("input");

    if(e.keyCode == 38){//up
        curPosition -= 1; 
        if(curPosition <= -1){//is top
            curPosition = totalResultNum-2;//except close tip
            oA[0].className = ''; //release top style
        }
        else{
            //release pre style
            oA[curPosition+1].className = '';
        }
        //reset now
		//oS is address suggestion
		//oA is keyword suggestion
        sbj.value = oS[curPosition] ? oS[curPosition].name : oA[curPosition].innerHTML;           
        oA[curPosition].className = 'drop_item'; 
    }
    else if(e.keyCode == 40){//down
        curPosition += 1;
        if(curPosition >= totalResultNum-1){            
            oA[curPosition-1].className = '';
            curPosition = 0;
        }
        else if(curPosition > 0){
            //release pre style
            oA[curPosition-1].className = '';
        }
        //reset now
        sbj.value = oS[curPosition] ? oS[curPosition].name : oA[curPosition].innerHTML;           
        oA[curPosition].className = 'drop_item';
    }
}
/**
 * desc: suggest road addr in city
 * */
function suggestRoadAddrInCity(e,city)
{
   var _city = city ? city : getCookie("city");
   suggestAddr(e,_city,6);
}
/**
 * desc: suggest addr only in city
 * @para: e == event
 * @para: city,default value is undefined
 * */

function suggestAddrInCity(e,city)
{
   var _city = city ? city : getCookie("city");
   suggestAddr(e,_city,2);
}
/**
 * desc: grep all templates html files,only two way used
 * 1: suggestAddr(event);
 * 2: suggestAddr(event,string_type_city_value);
 * this kind of invoking is very confused.
 * solution:
 * suggestAddr support 3 parameters:event,city,mode
 * city and mode can be null
 * */
function suggestAddr(e,city,mode)
{
	var target = e.srcElement?e.srcElement:e.target;
	curInput = target;
    
	var _city = city;
	var _mode = parseInt(mode,10) ? parseInt(mode,10) : 2;
	if( !_city && !mode ){
		//query the address between city and address.
		_city = $('pulldownCity') ? $('pulldownCity').value : '';
		_mode = 3;
	}
    
	if(!_city){
		return;
	}
    
	//var city = getCookie("city");
	
    var _addr = getAddr(target);
    
    if(!_city){
    	return;
    }
    if(!_addr){
    	$(pulldownId).hide();
    	return;
    }
    var url = "/addr?mode="+$E(_mode)+"&s=addr&n=10&rc=1&city="+$E(_city)+"&key="+$E(_addr);
    suggestInput(e,url,target);
}

function suggestKeyword(e,city)
{
	var target = e.srcElement?e.srcElement:e.target;
	curInput = target;
	
	if( (!city && $('pulldownCity') && $('pulldownCity').value) ){
		city = $('pulldownCity').value;
	}
	else if( typeof(city) == "object"){
		city = city.value?city.value:city.innerHTML;
	}
	else if(!city){
		return;
	}
	
    var what = getWhat(target);
    
    if(!city ){
    	return;
    }
    if(!what){
    	$(pulldownId).hide();
    	return;
    }
    var url = "/key?mode=7&s=key&n=10&rc=1&city="+$E(city)+"&key="+$E(what);
    suggestInput(e,url,target);
}


function suggestCity(e)
{
	var target = e.srcElement?e.srcElement:e.target;
	curInput = target;
	var what = curInput.value;
    if(what == ""){
    	$(pulldownId).hide();
    	return;
    }
    //var url = "/key?mode=3&s=key&n=10&rc=1&city="+$E(city)+"&key="+$E(what);
    var url = "/?area=place&cmd=selectcity&query="+$E(what);
    suggestInput(e,url,target);
}

function blurContactsInput(obj)
{		
	//当失去焦点时判断一下	
	if(obj.value == ""){
		obj.value = "姓名";
		obj.style.color="#BBBBBB";	
	}
}

function focusContactsInput(obj, inputType){		//当获得焦点时判断一下

	if(obj.value == "姓名"){
		obj.value ="";
		obj.style.color="";	
	}
	try{//在IE中按TAB键，出现闪烁效果
		if(ABBrowser.isIE()){
			var selection=document.selection.createRange();
			if(!selection.text){
				selection.moveStart("character", 0);
				selection.select();
			}
		}
	}
	catch(e){}
}

suggestAllContacts.noRealSuggest = false;
function suggestAllContacts(e,obj)
{
	if (suggestAllContacts.noRealSuggest) {
		suggestAllContacts.noRealSuggest = false;
		return;
	}
	var target = e.srcElement?e.srcElement:e.target;
	
	curInput = target;
	
    setContactsDrop();
	
    suggestContactsInput(e,target);
}


function mouseOverContacts(obj)
{
    mouseOverContactsDiv(obj,contactDropDownId);
}

function mouseOverContactsDiv(obj,sbj)
{
	if(!sbj){
		sbj = contactDropDownId;
	}
    var oA = document.getElementById(sbj).getElementsByTagName("a");
    for(var i=0; i<totalContactNum-1; i++)
    {
        if(oA[i] == obj){
            curContactPos = i;
            oA[i].className = 'drop_item';
        }
        else{
            oA[i].className = '';
        }
    }
}

/**
	下拉框相关内容
*/
var curContactPos = -1; //initial is -1
var totalContactNum = 0; //initial is 0

var curInput = null;
var contactDropDownId = "contacts_drop";

//当前最后一个下拉框请求ajax队形
attachEventListener(window,"load",function(){
	//当下拉框div不存在时，创建之
	if(!$(contactDropDownId)){
		var div=document.createElement("div");
		div.id=contactDropDownId;
		document.body.appendChild(div);
	}
     	//当页面被点击时，关闭下拉框
		
 	attachEventListener(document,"click",function(){
		sORh(contactDropDownId,"none");
	},false);  
	
  	/*attachEventListener(document,"mouseup",function(){
		sORh(contactDropDownId,"none");
	},false); */

	//当tab键被按下时，关闭下拉框。
	attachEventListener(document,"keydown",function(event){
		var e = event || window.event;
		if(e && e.keyCode == 9){ 
			sORh(contactDropDownId,"none");
		}
	},false); 
	
},false);



function setContactsDrop()
{
   if(!$(contactDropDownId)){
	   return;
   } 
   var Input = curInput;
   var t = Input.offsetTop,  l = Input.offsetLeft;
    
	while (Input = Input.offsetParent)
	{
		t += Input.offsetTop; l += Input.offsetLeft;
	}

 	$(contactDropDownId).style.left = (l)+'px';
	$(contactDropDownId).style.top = (t)+'px';

	$(contactDropDownId).style.zIndex='100001';
	$("msg1").style.zIndex='100000'; 
}


function selectContactsItem(name)
{
	curInput.value = name;
	suggestAllContacts.noRealSuggest = true;
	curInput.focus();
	curInput.blur();
	
	sORh(contactDropDownId,'none');
	
}

function suggestContactsInput(e,target)
{   

	//return;
   if(!$(contactDropDownId) || !(contactsDropList)){
	   return;
   }
   
   if(e.keyCode == 38 || e.keyCode == 40){
        if($(contactDropDownId).innerHTML && $(contactDropDownId).style.display == 'none'){
            $(contactDropDownId).innerHTML = "";
        }
        return;
    }
    else if(e.keyCode == 13){
    	$(contactDropDownId).hide();
    	return;
    }
    else if(e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 ){
    	return;
    }
    
	//如果已经有ajax请求，不管是否已经完成，取消它
	if (contactsDropList)
	{
		var __tmp = contactsDropList;

		if(__tmp){
			$(contactDropDownId).innerHTML = "<iframe id='adir' frameborder='0' height='0'></iframe><div id='ssssss'>"+__tmp+"</div>";
		}
		else{
			$(contactDropDownId).innerHTML = "";
		}
		var obj = $(contactDropDownId).getElementsByTagName("INPUT");
		if($("ssssss")){		
 			if(ABBrowser.isIE() && obj.length >= 20){
				$('ssssss').style.height = "200px";
			}  
		}
		 if(__tmp){                    
				var o = $(contactDropDownId).style;
				
				if( $(contactDropDownId).visible()==false ){
					o.left = "-1000px";
				}
				
				$(contactDropDownId).show('block');
				
				var input = target;
				
				var t = target.offsetTop,  h = target.clientHeight, l = target.offsetLeft, p = target.type;
				var hasAbsoluteTarget = false;
				while (target = target.offsetParent){
					t += target.offsetTop; 
					l += target.offsetLeft;		
				}
				
				var cw = input.offsetWidth;
				//o.width=cw+"px";
				var ch = $("ssssss").offsetHeight;
				
				var dw = ABBrowser.getViewWidth(), dl = ABBrowser.getScrollLeft(), dt = ABBrowser.getScrollTop();

				if (ABBrowser.getViewHeight() + dt - t - h >= ch){ 
					o.top = ((p=="image")? t + h : t + h + 6)+"px";
				}
				else {
					o.top  = ((t - dt < ch) ? ((p=="image")? t + h : t + h + 6) : t - ch-2)+"px";
				}
				if (dw + dl - l >= cw) {
					o.left = l+"px"; 
				}
				else{
					o.left = ((dw >= cw) ? dw - cw + dl : dl)+"px";
				}		

			}
			else{
				sORh(contactDropDownId,'none');
			}                            
			curContactPos = -1; //initial is -1
			totalContactNum = 0; //initial is 0
	 }
}


function suggestInput(e,url,target)
{   
   if(!$(pulldownId)){
	   return;
   }
   if(e.keyCode == 38 || e.keyCode == 40){
        if($(pulldownId).innerHTML && $(pulldownId).style.display == 'none'){
            $(pulldownId).innerHTML = "";
        }
        return;
    }
    else if(e.keyCode == 13){
    	$(pulldownId).hide();
    	return;
    }
    else if(e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 ){
    	return;
    }
    //如果已经有ajax请求，不管是否已经完成，取消它
    if(pulldownAjax && pulldownAjax.abort){
    	pulldownAjax.abort();
    }
	//alert(url);
    pulldownAjax = new Ajax.Request(
        url,{
            method: 'get',
            onSuccess: function(transport){
                var __tmp = transport.responseText;
                if(__tmp){
                    $(pulldownId).innerHTML = "<iframe id='adir' frameborder='0' height='0'></iframe><div id='ssss'>"+__tmp+"</div>";
                }
                else{
                    $(pulldownId).innerHTML = "";
                }
                var obj = $(pulldownId).getElementsByTagName("INPUT");
                if($("ssss")){
                    var __height = $('ssss').clientHeight;
                    __height = __height?__height:18*(obj.length);
                    $('adir').style.height = __height+'px';
                }
                 if(__tmp){                    
                 		var o = $(pulldownId).style;
                 		
                 		if( $(pulldownId).visible()==false ){
                 			o.left = "-1000px";
                 		}
                 		
                 		$(pulldownId).show('block');
                        
                        var input = target;
                        var t = target.offsetTop,  h = target.clientHeight, l = target.offsetLeft, p = target.type;
						var hasAbsoluteTarget = false;
						while (target = target.offsetParent){
                        	t += target.offsetTop; 
							l += target.offsetLeft;
							if(ABBrowser.isIE()){
							   var _pl = target.style.paddingLeft;
							   _pl = _pl ? parseInt(_pl,10) : 0;

							   var _pt = target.style.paddingTop;
							   _pt = _pt ? parseInt(_pt,10) : 0;

							   var _bl = target.style.borderLeft;
							   _bl = _bl ? parseInt(_bl,10): 0;

							   var _bt = target.style.borderTop;
							   _bt = _bt ? parseInt(_bt,10) : 0;

							   var _ml = target.style.marginLeft;
							   _ml = _ml ? parseInt(_ml,10) : 0;

							   var _mt = target.style.marginTop;
							   _mt = _mt ? parseInt(_mt,10) : 0;
                               //alert("pl:"+_pl+" pt:"+_pt+" bl:"+_bl+" bt:"+_bt+" ml:"+_ml+" mt:"+_mt); 
							   var _tmp_l = _pl + _bl + _ml;
							   var _tmp_t = _pt + _bt + _mt;
							   //alert("tmp_l:"+_tmp_l+" tmp_t:"+_tmp_t);
							   if("msg_addr_down" == target.id){
							      hasAbsoluteTarget = true;
							   }
							   t -= _tmp_t;
							   if(!hasAbsoluteTarget){
							      l -= _tmp_l;
							   }
							   //alert("t:" +t+ " l:"+l);
							}
                        }
						
                        var cw = input.offsetWidth;
                        //o.width=cw+"px";
                        var ch = $("ssss").offsetHeight;
                        
                        var dw = ABBrowser.getViewWidth(), dl = ABBrowser.getScrollLeft(), dt = ABBrowser.getScrollTop();

                        if (ABBrowser.getViewHeight() + dt - t - h >= ch){ 
						    o.top = ((p=="image")? t + h : t + h + 6)+"px";
						}
                        else {
						    o.top  = ((t - dt < ch) ? ((p=="image")? t + h : t + h + 6) : t - ch-2)+"px";
					    }
                        if (dw + dl - l >= cw) {
						    o.left = l+"px"; 
						}
						else{
						    o.left = ((dw >= cw) ? dw - cw + dl : dl)+"px";
						}

                    }
                    else{
                        sORh(pulldownId,'none');
                    }                            
                    curPosition = -1; //initial is -1
                    totalResultNum = 0; //initial is 0
             }
        }
    );
}

function jumpToDefaultPage()
{
	var city = getCookie("city");
	var url = "/?city="+$E(city);
	window.open(url,"_self");
}
function locate(type,addr,grid,mapxy,radius)
{
	curInput.value = addr;
	if(1 == type) {
	   setCookie("city",addr);
	   delCookie("addr");
	   suggestChangeCityTip(addr);

	   setTimeout("jumpToDefaultPage()",1);
	   return ;
	}
	sORh(pulldownId,"none");
}


function selectItem(name)
{
	curInput.value = name;
	sORh(pulldownId,"none");
}


attachEventListener(window,"load",function(){
	//当下拉框div不存在时，创建之
 	if(!$(pulldownId)){
		var div=document.createElement("div");
		div.id=pulldownId;
		document.body.appendChild(div);
	} 
	//当页面被点击时，关闭下拉框
  	attachEventListener(document,"click",function(){
		sORh(pulldownId,"none");
		if(pulldownAjax && pulldownAjax.abort){
			pulldownAjax.abort();
		}
	},false); 
	
 	attachEventListener(document,"mouseup",function(){
		sORh(pulldownId,"none");
		if(pulldownAjax && pulldownAjax.abort){
			pulldownAjax.abort();
		}
	},false); 
	/*
	attachEventListener(document,"mousedown",function(){
		sORh(pulldownId,"none");
	},false); 
	*/
	//当tab键被按下时，关闭下拉框。
	attachEventListener(document,"keydown",function(event){
		var e = event || window.event;
		if(e && e.keyCode == 9){ 
			sORh(pulldownId,"none");
			if(pulldownAjax && pulldownAjax.abort){
				pulldownAjax.abort();
			}
		}
	},false);
},false);


attachEventListener(window,"load",function(){
	//删除电话中隐藏的混淆信息，以便于拷贝
	var list = document.getElementsByTagName('span');
    for(var i=0;i<list.length;i++){
    	var display="";
    	if(list[i].currentStyle){
    		display = list[i].currentStyle.display; 
    	}
    	else if(window.getComputedStyle){
    		display = window.getComputedStyle(list[i],null).display;
    	}
    	if(display  == "none" && /^m_\d+$/.test(list[i].className) == true ){
    		list[i].innerHTML="";
    	}
    }
},false);

//写日志，统计用
function sendAjaxGetForLog(frm)
{
	sendHtmlReqForlog(frm);
	return true;
}
function sendHtmlReqForlog(frm,obj,line_num,page_num){
	//发送url统计代码//
	var randnum = Math.random() * 9 + 1;
	var now =new Date();
	var randcode = now.getTime() + randnum;
	var tmpImage = new Image();
	var cookie = getCookie('PHPSESSID');
	if(obj == null){
			tmpImage.src="/files/StatUrl.html?randcode="+randcode+"&sid="+cookie+"&frm="+frm;
	}
	else{
		var turl =  obj.getAttribute("href");
		if(turl != null){
			if(line_num && page_num){
				tmpImage.src="/files/StatUrl.html?randcode="+randcode+"&sid="+cookie+"&turl="+encodeURIComponent(turl)+"&ln="+line_num+"&pn="+page_num+"&frm="+frm;
			}
			else{
				tmpImage.src="/files/StatUrl.html?randcode="+randcode+"&sid="+cookie+"&turl="+encodeURIComponent(turl)+"&frm="+frm;
			}
		}	
		else{
			tmpImage.src="/files/StatUrl.html?randcode="+randcode+"&sid="+cookie+"&frm="+frm;
		}
	}
	return true;
}

//功能：在页面DOM构建完成时调用，比onload更快
var DomReady={
	add:function(fn){
		DomReady.bind();
		if(DomReady.isReady) fn();
		else DomReady.funList.push(fn);
	},
	isReady: false,
	funList: [],
	run:function(){
		if(!DomReady.isReady){
			DomReady.isReady = true;
			if(DomReady.funList){
				for(var i=0; i<DomReady.funList.length; ++i){
					try{ DomReady.funList[i]();}//防止函数有bug
					catch(error){continue;}
				}
				DomReady.funList = null;
			}
		}
	},
	isBind: false,
	bind:function(){
		if(DomReady.isBind) return;
		DomReady.isBind = true;
		if(document.addEventListener){//FireFox
			document.addEventListener("DOMContentLoaded", function(){
				document.removeEventListener("DOMContentLoaded", arguments.callee, false);
				DomReady.run();
			}, false);
		}
		else if(document.attachEvent){//IE
			document.attachEvent("onreadystatechange", function(){//Iframe
				if(document.readyState==="complete"){
					document.detachEvent("onreadystatechange", arguments.callee);
					DomReady.run();
				}
			});
			if(document.documentElement.doScroll && window==window.top)(function(){//Top
				if(DomReady.isReady) return;
				try{document.documentElement.doScroll("left");}
				catch(error){setTimeout(arguments.callee, 0);return;}
				DomReady.run();
			})();
		}
		//绑到onload上，就算上面的绑定失败也没有问题，保证万无一失
		if(window.addEventListener) window.addEventListener("load", DomReady.run, false);
		else if(window.attachEvent) window.attachEvent("onload", DomReady.run);
		else window.onload = DomReady.run;
	}
};

var HeadSearch={//管理爱帮商户搜索框
	init:function(){
		//地址提示对象
		this.addrNote = document.getElementById('addr_note');
		
		//对“地址输入框”绑定事件focus、blur、keydown
		this.addrInput = document.getElementById('addr');
		if(!this.addrInput) return;
		attachEventListener(this.addrInput, 'focus', this.addrNoteShow, false);
		attachEventListener(this.addrInput, 'blur', this.addrNoteHide, false);
		attachEventListener(this.addrInput, 'keydown', this.addrNoteHide, false);
		
		//对document绑定事件click、mouseover
		attachEventListener(document, 'click', this.cancelAddrNote, false);
		attachEventListener(document, 'mousemove', this.cancelAddrNote, false);
	},
	cancelAddrNote:function(){//因为运行在全局空间，所以不能使用this
		if(document.attachEvent&&window.event.type=="mousemove"){//IE下的mousemove有bug，页面加载完成就有发几次mousemove消息
			HeadSearch.mouseCount = HeadSearch.mouseCount||0;
			++HeadSearch.mouseCount;
			if(HeadSearch.mouseCount>8) HeadSearch.addrNote.style.display="none";
			else return;
		}
		else HeadSearch.addrNote.style.display="none";
		//取消对document绑定
		detachEventListener(document, 'click', HeadSearch.cancelAddrNote, false);
		detachEventListener(document, 'mousemove', HeadSearch.cancelAddrNote, false);
	},
	addrNoteShow:function(){
		var curAddr = HeadSearch.addrInput.value;
		if(!curAddr || curAddr=='全市') HeadSearch.addrNote.style.display="block";
	},
	addrNoteHide:function(){HeadSearch.addrNote.style.display="none";}
}
DomReady.add(function(){HeadSearch.init();});
/* - ABTraffic.js - */
//######################全局的函数与变量######################
//地图对象
var mapObj = null;
//左侧sider对象
var objSider = null;
var siderSubHeight = 148;				//动态的修改这个值，188、168、148
function setSiderSize(subHeight){		//188、168、148，越小sider越高
	//设置左侧边框的高度(在地图的高度上减去一个常量)
	if(objSider==null) objSider = document.getElementById("traffic_sider");
	var map_height	= ABBrowser.getViewHeight()-55;
    objSider.style.height = map_height-subHeight+"px";
}
//设置地图和左边的边框div的高度与宽度
function setMapAndSiderSize()
{
	//获得地图的高度，宽度(总高度减去一个常量)
	var map_width	= ABBrowser.getViewWidth()-348;
    var map_height	= ABBrowser.getViewHeight()-55;
    //设置左侧边框的高度(在地图的高度上减去一个常量)
	setSiderSize(siderSubHeight);
    //设置地图的高度与宽度
    var obj = document.getElementById("myMap");
    obj.style.width		= map_width+"px";
    obj.style.height	= map_height+"px";
    mapObj.setMapSize([map_width,map_height]);
    //设置阴影的高度与宽度
    $('mask').style.width = map_width+5+"px";
    $('mask').style.height = map_height+15+"px";
    //重新设置这边站点确认的大小
    ConfirmStation.resize();
}
//初始化地图
function initMap(){
	//获得地图的高度，宽度(总高度减去一个常量)
	var map_width	= ABBrowser.getViewWidth()-348;
    var map_height	= ABBrowser.getViewHeight()-55;
    try{ //初始化地图对象
        var mapOptions 				= new ABMapOptions;
        mapOptions.mapContainerId 	= 'myMap';
        mapOptions.mapWidth 		= map_width;
        mapOptions.mapHeight 		= map_height;
        mapOptions.mapZoom 			= 5;
        mapOptions.zoomBarType 		= 1;
        mapOptions.isOVMap 			= true;
        mapObj 						= new ABMap(mapOptions);
    }
    catch(e){ alert("地图初始化失败"); }
}
//初始化所有需要初始化的名字空间
function initAllNameSpace(){
	//Tag的类型
	Tag.curType = parseInt($('g_typetag').innerHTML);
	if(Tag.curType>0 && Tag.curType<5) Tag.oldType = Tag.curType;
	//Tag:获得3个div的处于哪个step
	var stepBus 			= $('g_stepbus').innerHTML;
	var stepLine 		 	= $('g_stepline').innerHTML;
	var stepStation			= $('g_stepstation').innerHTML;
	var stepDrive 			= $('g_stepdrive').innerHTML;
	Tag.divStep['bus']		= (stepBus.length)?stepBus:'empty';
	Tag.divStep['line']		= (stepLine.length)?stepLine:'empty';
	Tag.divStep['station']	= (stepStation.length)?stepStation:'empty';
	Tag.divStep['drive'] 	= (stepDrive.length)?stepDrive:'empty';
	//Face:判断是否还有没有必要加载该div的face页面
	if(Tag.divStep['bus'] 		!= 'empty') Face.needLoadBus	= false;
	if(Tag.divStep['line'] 		!= 'empty') Face.needLoadLine	= false;
	if(Tag.divStep['station'] 	!= 'empty') Face.needLoadStation= false;
	if(Tag.divStep['drive'] 	!= 'empty') Face.needLoadDrive	= false;
	//给Face和ConfirmStation的title赋值
	var cityName = $('g_city_name').innerHTML;
	Face.title = cityName+'公交_'+cityName+'公交查询_'+cityName+'公交路线_爱帮公交网';
	ConfirmStation.title = cityName+'公交驾乘';
	DriveManage.title = cityName+'公交驾乘';
	//当前url
	CurrentURL.init();
	//BusManage初始化
	if(getCookie('bus_j')) BusManage.bJuHe = 1;//判断是否是聚合：1、cookie；2、url中
	else if(urlInfo.method) BusManage.bJuHe = 1;
}
//初始化的时候绘制地图上的点、线等
function initDrawMap(){
	if(!Tag.hasInit)Tag.init();		//初始化Tag
	MapManage.setCityCenter();		//防止定位失败，先把地图定位到城市的中心
	switch(Tag.curType){
		case 1://公交
			if(Tag.divStep['bus'] == 'face') Face.restore('bus');
			else if(Tag.divStep['bus'] == 'confirm'){//模拟用户点击
				ConfirmStation.selectStation(1, 1, Tag.curType, true);
				ConfirmStation.selectStation(1, 0, Tag.curType, true);
			}
			else if(Tag.divStep['bus'] == 'result'){
				BusManage.title = $('g_title').innerHTML;//首次，需要直接用当前的title，下次则会重新生成
				if(urlInfo.nomapbus) BusManage.mark=true;	//地图需要阴影
				if(urlInfo.busnoxy) BusManage.noXY=true;	//起点或者终点无法定位，但是存在方案
				BusManage.restore();
			}
			break;
		case 2://路线
			if(Tag.divStep['line'] == 'face') Face.restore('line');
			else if(Tag.divStep['line'] == 'result'){
				LineManage.title = $('g_title').innerHTML;
				if($('g_unfolkline').innerHTML == '1') LineManage.restore();
			}
			break;
		case 3://站点
			if(Tag.divStep['station'] == 'face') Face.restore('station');
			else if(Tag.divStep['station'] == 'result'){
				StationManage.title = $('g_title').innerHTML;
				StationManage.restore();
			}
			break;
		case 4://驾车
			Tag.oldType = 1;	//如果直接到驾车页面，那么切换tag应该到公交页面，这个bug好难发现啊
			if(Tag.divStep['drive'] == 'face') Face.restore('drive');
			else if(Tag.divStep['drive'] == 'confirm'){//模拟用户点击
				ConfirmStation.selectStation(1, 1, Tag.curType, true);
				ConfirmStation.selectStation(1, 0, Tag.curType, true);
			}
			else if(Tag.divStep['drive'] == 'result') DriveManage.restore();
			break;
	}
}
//######################名字空间######################
//公交页面的tag部分的所有操作
var Tag={
	"lock":false,												//对于Tag的lock，如果等于true，则不应响应tag输入，防止出问题
	"curType":0,												//当前tag状态	——1：公交；2：线路；3：站点；4：驾车
	"oldType":0,												//老的tag状态
	"cityInfo":{"xy":"", "name":""},							//当前城市信息2元组：(city_mapxy, city_name)
	"divStep":{"bus":"empty", "line": "empty", "station": "empty", "drive":"empty"},//表示这三个div中的内容的意义：empty-还没有内容 face-有首页 confirm-确定页面 result-搜索结果页
	"selectTag":function(type, notRestore){	//1、切换tag，2、恢复现场，——如果notRestore=true，则不需要恢复现场，值切换tag，在公交方案与驾车方案之间切换是用到
		if(Tag.lock) return false;						//等待上次完成，lock住tag
		if(!Tag.hasInit)Tag.init();						//初始化
		if(!type && Tag.oldType) type = Tag.oldType;	//如果没有给类型，则恢复老的类型
		
		///////////////////////////////////////////////////
		/*对于Tag的切换：1、当前处于公交换乘方案页，切换到驾车；2、当前处于驾车方案页，切换到公交换乘方案页*/
		if(Tag.checkTagChange && Tag.curType==1 && type==4 && Tag.divStep['bus']=='result' && !BusManage.noXY){
			Tag.checkTagChange = false;
			return Tag.viewDriveFromBus();
		}
		if(Tag.checkTagChange && Tag.curType==4 && type==1 && Tag.divStep['drive']=='result'){
			Tag.checkTagChange = false;
			return Tag.viewBusFromDrive();
		}
		///////////////////////////////////////////////////
		
		Tag.oldType = Tag.curType;						//保留当前类型作为老类型
		Tag.curType = type;								//保存类型
		if(Tag.curType<1 || Tag.curType>4 || Tag.curType==Tag.oldType) {return; Tag.lock=false;}//如果类型不对或者类型没有改变，直接返回
		
		//更改tag部分的显示
		switch(type){
			case 1://公交
				$('tag_drive').style.display	="none";
				$('tag_bus').style.display		="block";
				$('bus_input').style.display	="block";
				$('line_input').style.display	="none";
				$('station_input').style.display="none";
				$('radiobus').checked = true;
				$('radioline').checked = false;
				$('radiostation').checked = false;
				break;
			case 2://线路
				$('tag_drive').style.display	="none";
				$('tag_bus').style.display		="block";
				$('bus_input').style.display	="none";
				$('line_input').style.display	="block";
				$('station_input').style.display="none";
				$('radiobus').checked = false;
				$('radioline').checked = true;
				$('radiostation').checked = false;
				break;
			case 3://站点
				$('tag_drive').style.display	="none";
				$('tag_bus').style.display		="block";
				$('bus_input').style.display	="none";
				$('line_input').style.display	="none";
				$('station_input').style.display="block";
				$('radiobus').checked = false;
				$('radioline').checked = false;
				$('radiostation').checked = true;
				break;
			case 4://驾车
				$('tag_drive').style.display	="block";
				$('tag_bus').style.display		="none";
				break;
		}

		//先隐藏所有左下的div，再显示要显示的div，绘制地图
		Tag.objDiv['bus'].style.display		="none";
		Tag.objDiv['line'].style.display	="none";
		Tag.objDiv['station'].style.display	="none";
		Tag.objDiv['drive'].style.display	="none";
		MapManage.clearAll();	//清空地图，定位到城市中心
		Bottom.hide();			//先将sider设置为148的最高状态，接下来只有两个页面需要修改
		
		Mask.hide();			//去掉地图的阴影
		
		switch(type){//恢复现场(1、左侧的div；2、地图)，这个需要根据左侧div的step来看调用哪个类的restore
			case 1:
				Tag.objDiv['bus'].style.display="block";
				if(notRestore) return;
				if(Tag.divStep['bus'] == 'result') BusManage.restore();
				else if(Tag.divStep['bus'] == 'confirm') ConfirmStation.restore(type);
				else Face.restore(type);
				break;
			case 2:
				Tag.objDiv['line'].style.display="block";
				if(notRestore) return;
				if(Tag.divStep['line'] == 'result') LineManage.restore();
				else Face.restore(type);
				break;
			case 3:
				Tag.objDiv['station'].style.display="block";
				if(notRestore) return;
				if(Tag.divStep['station'] == 'result') StationManage.restore();
				else Face.restore(type);
				break;
			case 4:
				Tag.objDiv['drive'].style.display="block";
				if(notRestore) return;
				if(Tag.divStep['drive'] == 'result') DriveManage.restore();
				else if(Tag.divStep['drive'] == 'confirm') ConfirmStation.restore(type);
				else Face.restore(type);
				break;
		}
		return true;
	},
	"submitTag":function(type){//提交请求
		if(Tag.lock) return false;		//等待上次完成，lock住tag
		if(!Tag.hasInit) Tag.init();
		if(type)Tag.curType = type;
		switch(Tag.curType){
			case 1: Tag.submitSelectStation();break;
			case 2: Tag.submitLine();break;
			case 3: Tag.submitStation();break;
			case 4: Tag.submitSelectStation();break;
		}
		Bottom.hide();	//这些情况，都不需要bottom
		return false;
	},
	"exchangeInput":function(){//交换两个输入框
		if(Tag.lock) return false;		//等待上次完成，lock住tag
		if(!Tag.hasInit)Tag.init();
		//获得两个input
		var objInput = 	(Tag.curType==1)?Tag.objInputBus:(
						(Tag.curType==4)?Tag.objInputDrive:null);
		if(!objInput) return;
		//用一个子函数来交换input
		var exchangeFun=function(obj1, obj2){
			var tmpValue="";	//存input的中间值
			tmpValue	= obj1.value;
			obj1.value	= obj2.value;
			obj2.value	= tmpValue;
		}
		//交换开始啦
		exchangeFun(objInput['name1'],		objInput['name2']);
		exchangeFun(objInput['name_1'],		objInput['name_2']);
		exchangeFun(objInput['x1'],			objInput['x2']);
		exchangeFun(objInput['y1'],			objInput['y2']);
		exchangeFun(objInput['ori_name1'],	objInput['ori_name2']);
		exchangeFun(objInput['ori_x1'],		objInput['ori_x2']);
		exchangeFun(objInput['ori_y1'],		objInput['ori_y2']);
		
		//当交换后的内容无效时，使用默认的提示效果和问题
		if( objInput['name1'].value == "" || objInput['name1'].value == Tag.defaultStartText || objInput['name1'].value == Tag.defaultEndText ){
			objInput['name1'].value = Tag.defaultStartText;
			objInput['name1'].style.color = "gray";
		}
		else objInput['name1'].style.color = "";
		
		if( objInput['name2'].value == "" || objInput['name2'].value == Tag.defaultStartText || objInput['name2'].value == Tag.defaultEndText ){
			objInput['name2'].value = Tag.defaultEndText;
			objInput['name2'].style.color = "gray";
		}
		else objInput['name2'].style.color = "";
	},
	"defaultStartText":		'请输入起点',
	"defaultEndText":		'请输入终点',
	"defaultLineText":		'请输入线路名称',
	"defaultStationText":	'请输入站点名称',
	"getDefaultInputText":function(inputType){	//获得默认输入
		if(inputType == 'start')		return Tag.defaultStartText;
		else if(inputType == 'end')		return Tag.defaultEndText;
		else if(inputType == 'line')	return Tag.defaultLineText;
		else if(inputType == 'station')	return Tag.defaultStationText;
	},
	"focusInput":function(obj, inputType){		//当获得焦点时判断一下
		if(obj.value.strip() == Tag.getDefaultInputText(inputType)){
			obj.value ="";
			obj.style.color="";	
		}
		try{//在IE中按TAB键，出现闪烁效果
			if(ABBrowser.isIE()){
				var selection=document.selection.createRange();
				if(!selection.text){
					selection.moveStart("character", 0);
					selection.select();
				}
			}
		}
		catch(e){}
	},
	"blurInput":function(obj, inputType){		//当失去焦点时判断一下
		if(obj.value.strip() == ""){
			obj.value = Tag.getDefaultInputText(inputType);
			obj.style.color="#BBBBBB";	
		}
	},
	//提交进一步确认站点
	"submitSelectStation":function(){
		if(Tag.lock) return false;		//等待上次完成，lock住tag
		Mask.hide();//去掉地图的阴影
		if(!Tag.hasInit) Tag.init();
		//根据类型(公交、驾车)获得页面上的DOM对象
		var objInputTag;
		var typeName;
		if(Tag.curType==1){
			typeName='bus';
			objInputTag=Tag.objInputBus;
		}
		else if(Tag.curType==4){
			typeName='drive';
			objInputTag=Tag.objInputDrive;
		}
		else return;
		//拼接url，发送Ajax请求
		var start	= objInputTag['name1'].value.strip();
		var end		= objInputTag['name2'].value.strip();//??????????
		
		var _startIsNull = 0;
		var _endIsNull = 0;
		if(!start || start == Tag.defaultStartText){_startIsNull = 1;}
		if(!end || end == Tag.defaultEndText){_endIsNull = 1;}
		if(_startIsNull == 1 && _endIsNull == 1){objInputTag['name1'].value="";objInputTag['name1'].style.color="";objInputTag['name1'].focus(); return;}
		else if(_startIsNull == 1){objInputTag['name1'].value="";objInputTag['name1'].style.color="";objInputTag['name1'].focus(); return;}
		else if(_endIsNull == 1){objInputTag['name2'].value="";objInputTag['name2'].style.color="";objInputTag['name2'].focus(); return;}

		//如果用户没有修改输入框才可以使用原始的坐标
		var x1		= (start && start==(objInputTag['ori_name1'].value))?objInputTag['ori_x1'].value:"";
		var y1		= (start && start==(objInputTag['ori_name1'].value))?objInputTag['ori_y1'].value:"";
		var x2		= (end   && end  ==(objInputTag['ori_name2'].value))?objInputTag['ori_x2'].value:"";
		var y2		= (end   && end  ==(objInputTag['ori_name2'].value))?objInputTag['ori_y2'].value:"";
		var url = "/?area=abbd&cmd=confirm&type="+typeName+"&city="+encodeURIComponent(Tag.cityInfo['name'])+"&start="+encodeURIComponent(start)+"&end="+encodeURIComponent(end)+"&x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2;
		new Ajax.Request(url, {method:'get', onSuccess:Tag.submitSelectStationSuccess, onFailure:Tag.submitSelectStationFail});
		//加锁
		busying(1);
		
		if(Tag.curType==1){
			sendHtmlReqForlog('in_bus_to_confirm');
		}
		else if(Tag.curType==4){
			sendHtmlReqForlog('in_drive_to_confirm');
		}
		//修改title
		document.title = Tag.cityInfo['name']+'公交驾乘';
	},
	"submitSelectStationSuccess":function(transport){
		//解锁
		busying(0);
		//目前是公交的站点提示页面或者驾车的站点提示页面，设置恢复现场要用
		if(Tag.curType==4) Tag.divStep['drive'] = 'confirm';
		else Tag.divStep['bus'] = 'confirm';

		var ret=transport.responseText;
		if(ret && ret.length>4&& ret.substr(0,3)=="200"){
			//获得返回，修改页面
			retHtml = ret.substr(3);
			if(Tag.curType==4) Tag.objDiv['drive'].innerHTML = retHtml;
			else Tag.objDiv['bus'].innerHTML = retHtml;
			//重新设置高度
			ConfirmStation.resize();
			//模拟用户点击的第一个起点，第一个终点
			MapManage.clearAll();//清空地图
			//模拟用户点击，但是要保留输入框的输入，不修改用户的输入
			ConfirmStation.selectStation(1, 1, Tag.curType, true);
			ConfirmStation.selectStation(1, 0, Tag.curType, true);
			mapObj.zoomToPois();//显示这2个点
			//将焦点放到确认的确定上，这样方便用户直接回车
			$('confirm_button_'+Tag.curType).focus();
		}
		else if(ret && ret.length>4&& ret.substr(0,3)=="300"){//都是有一个结果，直接到达搜索结果页面
			if(Tag.curType==4) Tag.submitDriveSuccess(transport);
			else Tag.submitBusSuccess(transport);
		}
		else{
			if(Tag.curType==4) Tag.objDiv['drive'].innerHTML = retHtml;
			else {
				retHtml = ret.substr(3);
				Tag.objDiv['bus'].innerHTML = retHtml;
			}
		}
	},
	"submitSelectStationFail":function(){
		//解锁
		busying(0);
		//目前是公交的站点提示页面或者驾车的站点提示页面，设置恢复现场要用
		if(Tag.curType==4) Tag.divStep['drive'] = 'confirm';
		else Tag.divStep['bus'] = 'confirm';
	},
	//对于公交查询的相关函数
	"submitBus":function(){
		if(Tag.lock) return false;		//等待上次完成，lock住tag
		var start	= Tag.objInputBus['name_1'].value;
		var end		= Tag.objInputBus['name_2'].value;
		var x1		= Tag.objInputBus['x1'].value;
		var x2		= Tag.objInputBus['x2'].value;
		var y1		= Tag.objInputBus['y1'].value;
		var y2		= Tag.objInputBus['y2'].value;
		var method	= BusManage.getJuHe()?2:0;
		var url = "/?area=abbd&cmd=bus&city="+$E(Tag.cityInfo['name'])+"&start="+$E(start)+"&end="+$E(end)+"&x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2;
		if(method) url += '&method=2';
		new Ajax.Request(url, {method:'get', onSuccess:Tag.submitBusSuccess, onFailure:Tag.submitBusFail});
		//加锁
		busying(1);
		//发送到手机用到，登录后返回该页面
		var encodeCity = $E(Tag.cityInfo['name']);
		ABMessage._backUrl = $E("http://"+location.host+"/?area=abbd&cmd=traffic&city="+encodeCity+"&start="+$E(start)+"&end="+$E(end)+"&x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2);
		//修改title，保存title
		busTitle = "从"+start+"到"+end+"_"+Tag.cityInfo['name']+"公交_爱帮公交网";
		document.title = busTitle;
		BusManage.title = busTitle;
		//保存当前url信息
		urlInfo.start	= $E(start);
		urlInfo.end		= $E(end);
		urlInfo.x1		= x1;
		urlInfo.y1		= y1;
		urlInfo.x2		= x2;
		urlInfo.y2		= y2;
		//保存到BusManage，在更换排序方式的时候要用
		BusManage.StartEndInfo = {start:urlInfo.start, end:urlInfo.end, x1:urlInfo.x1, x2:urlInfo.x2, y1:urlInfo.y1, y2:urlInfo.y2};
	},
	"submitBusSuccess":function(transport){
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['bus'] = 'result';
		Bottom.hide();

		var ret=transport.responseText;
		if(ret && ret.length>4&& ret.substr(0,3)=="300"){
			retHtml = ret.substr(3);
			Tag.objDiv['bus'].innerHTML = retHtml;
			Tag.objDiv['bus'].style.display="";
			BusManage.lastClickBus=0;									//默认点击第一条线路
			BusManage.curOrderType=transport.getResponseHeader('rc');	//获得排序方式，这个来自服务器返回的HTTP头中
			if(!BusManage.curOrderType) BusManage.curOrderType = 0;		//如果没有值，则使用0——默认排序
			//BusManage.drawBus('1');			//绘制第一条线路
			MapManage.clearAll();
			
			BusManage.setUrl();				//设置url
			//判断是否要隐藏右侧地图
			if(transport.getResponseHeader('nomap')){
				BusManage.mark=true;
				Mask.show();
			}
			else{
				BusManage.mark=false;
				Mask.hide();
			}
			//起点或者终点无法定位，但是存在方案
			if(transport.getResponseHeader('nobusxy')) BusManage.noXY=true; 
			else BusManage.noXY=false;
			
			Bottom.show('bus', BusManage.curOrderType);
		}
		else if(ret && ret.substr(0,3)=="500"){
			retHtml = ret.substr(3);
			Tag.objDiv['bus'].innerHTML = retHtml;
			Tag.objDiv['bus'].style.display="";
		}
		else Tag.objDiv['bus'].innerHTML = ret;
		//公交的站点确认页面清空
		ConfirmStation.clear(1);
	},
	"submitBusFail":function(){
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['bus'] = 'result';
		Bottom.hide();
	},
	"showFirstLine":false,
	//对于线路查询的相关函数
	"submitLine":function(){//提交线路搜索
		if(Tag.lock) return false;						//等待上次完成，lock住tag
		var lineName = $("line_name").value.strip();	//对lineName进行处理
		if(!lineName || lineName == Tag.defaultLineText){$("line_name").value="";$("line_name").style.color="";$("line_name").focus();return;}
		var url = "/?area=abbd&cmd=line&city="+encodeURIComponent(Tag.cityInfo['name'])+"&line="+encodeURIComponent(lineName);
		new Ajax.Request(url, {method:'get', onSuccess:Tag.submitLineSuccess, onFailure:Tag.submitLineFail});
		busying(1);//加锁
		sendHtmlReqForlog('in_line_search');
		//修改title，保存title
		lineTitle = Tag.cityInfo['name']+lineName+'路_'+Tag.cityInfo['name']+lineName+'路公交_'+Tag.cityInfo['name']+lineName+'路线路_爱帮公交网';
		document.title = lineTitle;
		LineManage.title = lineTitle;
		//保存当前url信息
		urlInfo.line = encodeURIComponent(lineName);
	},
	"submitLineSuccess":function(transport){//成功
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['line'] = 'result';
		MapManage.clearAll();
		Bottom.hide();
		
		var ret=transport.responseText;
		if(ret && ret.length>4&& ret.substr(0,3)=="300"){
			retHtml = ret.substr(3);
			Tag.objDiv['line'].innerHTML = retHtml;	//获得返回
			LineManage.clear();						//清空上次的记录
			if(Tag.showFirstLine) LineManage.showLine();
			else Bottom.show('line');				//bottom需要修改，应该默认是放在showLine中实现的
			LineManage.setUrl();					//设置url
		}
		else Tag.objDiv['line'].innerHTML = ret;
		Tag.showFirstLine = false;
	},
	"submitLineFail":function(){//失败
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['line'] = 'result';
		MapManage.clearAll();
		Bottom.hide();
		Tag.showFirstLine = false;
	},
	//对于站点查询的相关函数
	"submitStation":function(){//提交站点搜索
		if(Tag.lock) return false;							//等待上次完成，lock住tag
		var stationName = $("station_name").value.strip();	//对stationName进行处理
		if(!stationName || stationName==Tag.defaultStationText){$("station_name").value="";$("station_name").style.color="";$("station_name").focus();return;}
		var url = "/?area=abbd&cmd=station&city="+encodeURIComponent(Tag.cityInfo['name'])+"&station="+encodeURIComponent(stationName);
		new Ajax.Request(url, {method:'get', onSuccess:Tag.submitStationSuccess, onFailure:Tag.submitStationFail});
		busying(1);//加锁
		sendHtmlReqForlog('in_station_search');
		//修改title，保存title
		stationTitle = "公交站点查询_"+Tag.cityInfo['name']+stationName+"站_爱帮公交网";
		document.title = stationTitle;
		StationManage.title = stationTitle;
		//保存当前url信息
		urlInfo.station = encodeURIComponent(stationName);
	},
	"submitStationSuccess":function(transport){//成功
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['station'] = 'result';
		MapManage.clearAll();
		Bottom.hide();
		var ret = transport.responseText;
		if(ret && ret.length>4 && ret.substr(0,3)=="300"){
			retHtml = ret.substr(3);
			Tag.objDiv['station'].innerHTML = retHtml;	//获得返回
			StationManage.clear();						//清空上次的记录
			StationManage.drawTextStation();			//绘制按文本匹配的站点
			StationManage.setUrl();						//设置url
		}
		else Tag.objDiv['station'].innerHTML = ret;
	},
	"submitStationFail":function(){//失败
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['station'] = 'result';
		MapManage.clearAll();
		Bottom.hide();
	},
	//对于驾车查询的相关函数
	"submitDrive":function(){//提交线路搜索
		if(Tag.lock) return false;		//等待上次完成，lock住tag
		var start	= Tag.objInputDrive['name_1'].value;
		var end		= Tag.objInputDrive['name_2'].value;
		var x1		= Tag.objInputDrive['x1'].value;
		var x2		= Tag.objInputDrive['x2'].value;
		var y1		= Tag.objInputDrive['y1'].value;
		var y2		= Tag.objInputDrive['y2'].value;//??????????????
		var url = "/?area=abbd&cmd=drive&city="+encodeURIComponent(Tag.cityInfo['name'])+"&start="+encodeURIComponent(start)+"&end="+encodeURIComponent(end)+"&x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2;
		new Ajax.Request(url, {method:'get', onSuccess:Tag.submitDriveSuccess, onFailure:Tag.submitDriveSuccess});
		busying(1);//加锁
		//修改title
		document.title = Tag.cityInfo['name']+'公交驾乘';
		//保存当前url信息
		urlInfo.start	= encodeURIComponent(start);
		urlInfo.end		= encodeURIComponent(end);
		urlInfo.x1		= x1;
		urlInfo.y1		= y1;
		urlInfo.x2		= x2;
		urlInfo.y2		= y2;
	},
	"submitDriveSuccess":function(transport){//成功
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['drive'] = 'result';
		Bottom.hide();
		
		var ret=transport.responseText;
		if(ret && ret.length>4&& ret.substr(0,3)=="300"){
			retHtml = ret.substr(3);
			Tag.objDiv['drive'].innerHTML = retHtml;	//获得返回
			DriveManage.drawDrive();					//绘制驾车
			DriveManage.setUrl();						//设置url
		}
		else Tag.objDiv['drive'].innerHTML = ret;
		//驾车的站点确认页面清空
		ConfirmStation.clear(4);
	},
	"submitDriveFail":function(){//失败
		//解锁，设置恢复现场要用到的变量
		busying(0);
		Tag.divStep['drive'] = 'result';
		Bottom.hide();
	},
	//从公交查询结果页面切换到驾车结果页面
	checkTagChange:false,//该变量防止viewDriveFromBus函数中调用selectTag时出现循环调用
	"viewDriveFromBus":function(){
		//将bus输入copy到drive的输入
		Tag.objInputDrive['name1'].value = Tag.objInputBus['name_1'].value;
		Tag.objInputDrive['name2'].value = Tag.objInputBus['name_2'].value;
		Tag.objInputDrive['name_1'].value = Tag.objInputBus['name_1'].value;
		Tag.objInputDrive['name_2'].value = Tag.objInputBus['name_2'].value;
		//使两个框的颜色变为正常
		Tag.objInputDrive['name1'].style.color="";
		Tag.objInputDrive['name2'].style.color="";
		
		Tag.objInputDrive['x1'].value = Tag.objInputBus['x1'].value;
		Tag.objInputDrive['x2'].value = Tag.objInputBus['x2'].value;
		Tag.objInputDrive['y1'].value = Tag.objInputBus['y1'].value;
		Tag.objInputDrive['y2'].value = Tag.objInputBus['y2'].value;
		//执行点击drive的tag
		Tag.selectTag(4, 1);
		//执行搜索
		Tag.submitDrive();
	},
	//从驾车结果页面切换到公交查询结果页面
	"viewBusFromDrive":function(){
		//将bus输入copy到drive的输入
		Tag.objInputBus['name1'].value = Tag.objInputDrive['name_1'].value;
		Tag.objInputBus['name2'].value = Tag.objInputDrive['name_2'].value;
		Tag.objInputBus['name_1'].value = Tag.objInputDrive['name_1'].value;
		Tag.objInputBus['name_2'].value = Tag.objInputDrive['name_2'].value;
		//使两个框的颜色变为正常
		Tag.objInputBus['name1'].style.color="";
		Tag.objInputBus['name2'].style.color="";
		
		Tag.objInputBus['x1'].value = Tag.objInputDrive['x1'].value;
		Tag.objInputBus['x2'].value = Tag.objInputDrive['x2'].value;
		Tag.objInputBus['y1'].value = Tag.objInputDrive['y1'].value;
		Tag.objInputBus['y2'].value = Tag.objInputDrive['y2'].value;
		//执行点击drive的tag
		Tag.selectTag(1, 1);
		//执行搜索
		Tag.submitBus();
	},
	"strProcess":function(strIn){//检查提交???????????????
		if(!strIn || !strIn.length) return false;
		return strIn;
	},
	//初始化相关函数和变量
	"objDiv":{"bus":null, "line": null, "station":null, "drive":null},			//指向div的对象：公交div容器对象，路线div容器对象，站点div容器对象，驾车div容器对象
	"objInputBus":  {"name1":null, "name2":null, "name_1":null, "name_2":null, "x1":null, "x2":null, "y1":null, "y2":null, "ori_name1":null, "ori_name2":null, "ori_x1":null, "ori_x2":null, "ori_y1":null, "ori_y2":null},//代表公交的输入起点、终点部分的信息
	"objInputDrive":{"name1":null, "name2":null, "name_1":null, "name_2":null, "x1":null, "x2":null, "y1":null, "y2":null, "ori_name1":null, "ori_name2":null, "ori_x1":null, "ori_x2":null, "ori_y1":null, "ori_y2":null},//代表驾车的输入起点、终点部分的信息
	"hasInit":false,	//是否进行了初始化
	"init":function(){	//初始化一些变量
		Tag.hasInit = true;
		
		Tag.cityInfo['xy']		= $('g_city_mapxy').innerHTML;
		Tag.cityInfo['name']	= $('g_city_name').innerHTML;
		
		Tag.curType				= parseInt($('g_typetag').innerHTML);
		
		Tag.objDiv['bus']		= $('content_bus');
		Tag.objDiv['line']		= $('content_line');
		Tag.objDiv['station']	= $('content_station');
		Tag.objDiv['drive']		= $('content_drive');
		
		Tag.objInputBus['name1']		= $('bus_name1');
		Tag.objInputBus['name2']		= $('bus_name2');
		Tag.objInputBus['name_1']		= $('bus_name_1');
		Tag.objInputBus['name_2']		= $('bus_name_2');
		Tag.objInputBus['x1']			= $('bus_x1');
		Tag.objInputBus['x2']			= $('bus_x2');
		Tag.objInputBus['y1']			= $('bus_y1');
		Tag.objInputBus['y2']			= $('bus_y2');
		Tag.objInputBus['ori_name1']	= $('bus_ori_name1');
		Tag.objInputBus['ori_name2']	= $('bus_ori_name2');
		Tag.objInputBus['ori_x1']		= $('bus_ori_x1');
		Tag.objInputBus['ori_x2']		= $('bus_ori_x2');
		Tag.objInputBus['ori_y1']		= $('bus_ori_y1');
		Tag.objInputBus['ori_y2']		= $('bus_ori_y2');
		
		Tag.objInputDrive['name1']		= $('drive_name1');
		Tag.objInputDrive['name2']		= $('drive_name2');
		Tag.objInputDrive['name_1']		= $('drive_name_1');
		Tag.objInputDrive['name_2']		= $('drive_name_2');
		Tag.objInputDrive['x1']			= $('drive_x1');
		Tag.objInputDrive['x2']			= $('drive_x2');
		Tag.objInputDrive['y1']			= $('drive_y1');
		Tag.objInputDrive['y2']			= $('drive_y2');
		Tag.objInputDrive['ori_name1']	= $('drive_ori_name1');
		Tag.objInputDrive['ori_name2']	= $('drive_ori_name2');
		Tag.objInputDrive['ori_x1']		= $('drive_ori_x1');
		Tag.objInputDrive['ori_x2']		= $('drive_ori_x2');
		Tag.objInputDrive['ori_y1']		= $('drive_ori_y1');
		Tag.objInputDrive['ori_y2']		= $('drive_ori_y2');
	}
};

//管理"确认站点"(它管理公交的站点和驾车的站点结果，所以存在两个isExist变量)
var ConfirmStation={
	"oldBusStation":[null, null],										//上次公交选择的站点，在本次选择中应该将其背景颜色恢复正常
	"oldDriveStation":[null, null],										//上次驾车选择的站点，在本次选择中应该将其背景颜色恢复正常
	"selectStation":function(index, iStartEnd, tagType, saveInput){		//选择一个站点，在地图上标记出来(iStartEnd=0起点,iStartEnd=1终点)
		if(!Tag.hasInit) Tag.init();
		//获得当前的对象，存储站点坐标和名字的对象
		var strName = (iStartEnd?'e_':'s_')+(index).toString()+'_'+(tagType).toString();
		var curObj = $(strName);
		if(!curObj || !curObj.nextSibling) return;
		var stationInfo = curObj.nextSibling.value;

		//修正被点击对象的背景颜色，清除上次被点击的对象的背景，保留本次被点击的对象
		curObj.style.backgroundColor = '#0065ca'
		curObj.className = 'curr';
		var oldStation = (tagType==1)?ConfirmStation.oldBusStation:
						 (tagType==4)?ConfirmStation.oldDriveStation:null;
		if(!oldStation) return;
		if(oldStation[iStartEnd] && oldStation[iStartEnd]!=curObj){//存在上次点击的对象，并且与本次点击的对象不是同一个
			oldStation[iStartEnd].style.backgroundColor = '#ffffff'
			oldStation[iStartEnd].className = 'uncurr';
		}
		oldStation[iStartEnd] = curObj;//保留
		
		//获得该站点信息，并进行绘制
		var pos = stationInfo.indexOf("|");
		if(pos == -1){
			alert("坐标有误，请刷新页面！");
			return;
		}
		var name=stationInfo.substr(pos+1);
		var xy=stationInfo.substr(0, pos).split(",");
		if(xy[0] && xy[1] && name){
			//获得界面上的DOM对象，可以设置他们的值
			if(!Tag.hasInit)Tag.init();//防止没有初始化，没有初始化那么这些值就为空
			var objInputTag = 	(tagType==1)?Tag.objInputBus:
								(tagType==4)?Tag.objInputDrive:null;
			if(!objInputTag) return;
			if(iStartEnd){//设置终点，绘制终点
				if(!saveInput) objInputTag['name2'].value = name;	//是否要保留用户的输入，当从服务器返回时不应该修改用户的输入，是有用户点击的时候才修改
				objInputTag['name_2'].value	= name;
				objInputTag['x2'].value		= xy[0];
				objInputTag['y2'].value		= xy[1];
				MapManage.drawSelectEnd(xy[0]+","+xy[1]);
			}
			else{//设置起点，绘制起点
				if(!saveInput) objInputTag['name1'].value = name;
				objInputTag['name_1'].value = name;
				objInputTag['x1'].value = xy[0];
				objInputTag['y1'].value = xy[1];
				MapManage.drawSelectStart(xy[0]+","+xy[1]);
			}
		}
		//将焦点放到确认的确定上，这样方便用户直接回车
		if($('confirm_button_'+tagType)) $('confirm_button_'+tagType).focus();
	},
	"onMouseOverOut":function(curObj, bFlag, type){//鼠标Over(bFlag=1)或者Out(bFlag=0)时，修改curObj的背景颜色
		//获得上次选择的站点
		var oldStation = (type==1)?ConfirmStation.oldBusStation:
						 (type==4)?ConfirmStation.oldDriveStation:null;
		if(!oldStation) return;
		//如果是上次选择的站点，则不应该响应这个事件
		if(curObj==oldStation[0] || curObj==oldStation[1]) return;
		//修改背景
		if(bFlag) curObj.style.backgroundColor = '#dfeffe';
		else curObj.style.backgroundColor = '#ffffff';
	},
	'title':'',
	"restore":function(type){	//重新绘制起点和终点，这边要防止绘图失败
		Bottom.hide();			//隐藏bottom
		MapManage.clearAll();	//清空地图
		if(!Tag.hasInit) Tag.init();
		tagType = (type)?type:Tag.curType;
		var objInputTag =	(tagType==1)?Tag.objInputBus:
							(tagType==4)?Tag.objInputDrive:null;
		if(!objInputTag) return;
		var xy1=objInputTag['x1'].value+','+objInputTag['y1'].value;
		var xy2=objInputTag['x2'].value+','+objInputTag['y2'].value;
		if(xy1.length>3) MapManage.drawSelectStart(xy1);
		if(xy2.length>3) MapManage.drawSelectEnd(xy2);
		if(xy1.length>3 && xy2.length>3)mapObj.zoomToPois();							//显示这2个点
		document.title = ConfirmStation.title;
	},
	"clear":function(type){			//清空成员变量
		if(type==1){
			ConfirmStation['oldBusStation'][0] = null;
			ConfirmStation['oldBusStation'][1] = null;
		}
		else if(type==4){
			ConfirmStation['oldDriveStation'][0] = null;
			ConfirmStation['oldDriveStation'][1] = null;
		}
	},
	"resize":function(){//重新设置站点确认的高度
		var divStart1	= $("start_station_1");
		var divEnd1		= $("end_station_1");
		var divStart4	= $("start_station_4");
		var divEnd4		= $("end_station_4");
		var allHeight	= parseInt($("traffic_sider").style.height);
		var curHeight	= parseInt((allHeight-180)/2);
		if(curHeight<40) curHeight=40;
		curHeight += 'px';
		if(divStart1 && divEnd1){
			divStart1.style.height = curHeight;
			divEnd1.style.height = curHeight;
		}
		if(divStart4 && divEnd4){
			divStart4.style.height = curHeight;
			divEnd4.style.height = curHeight;
		}
	}
};

//管理公交(展开)
var BusManage={
	"lastClickBus":0,			//上一次点击的id，如果为零表示不需要处理
	"hideAndShowBus":function(curObj,flag,listId){
		if(flag){//隐藏本次节点
			var currentObj=curObj.parentNode;
			currentObj.style.display="none";
			currentObj.nextSibling.style.display="block";
			currentObj.nextSibling.className="case case_visited";//将本次的节点颜色改变
		}
		else{//隐藏上次点击的节点
			var currentObj=curObj;
			if(BusManage.lastClickBus){
				var lastNode=document.getElementById('perbus1'+BusManage.lastClickBus);
				lastNode.style.display="none";
				lastNode.nextSibling.style.display="block";
				lastNode.nextSibling.className="case";//将上次的节点颜色恢复正常
			}
			BusManage.lastClickBus=listId;//记录本次节点下次使用
			//显示本次节点
			currentObj.style.display="none";
			currentObj.previousSibling.style.display="block";
			//显示地图
			BusManage.drawBus(listId);
		}
	},
	"showBusPage":function(page, curObj){//分页，显示第一页或者第二页
		//加锁，这里其实不用加锁，但是要给用户重新加载的感觉
		busying(1);
		var curNodeId="bus_";
		var curNodeObj=null;
		var i=0;
		//先隐藏全部
		while(++i){
			curNodeObj=document.getElementById(curNodeId+i);
			if(!curNodeObj) break;
			curNodeObj.lastChild.style.display="none";					//最后一个节点隐藏
			curNodeObj.lastChild.className="case";						//最后一个节点颜色恢复正常
			curNodeObj.lastChild.previousSibling.style.display="none";	//倒数第二个节点隐藏
			curNodeObj.style.display="none";							//最上层的div
		}
		if(curObj) curObj.parentNode.style.display="none";				//隐藏当前的分页按钮
		if(page==2){
			for(var i=6; i<=10; ++i){
				curNodeObj=document.getElementById(curNodeId+i);
				if(!curNodeObj) break;
				curNodeObj.lastChild.previousSibling.style.display="none";
				curNodeObj.lastChild.style.display="block";
				curNodeObj.style.display="block";//最上层的div
			}
			if(curObj)curObj.parentNode.nextSibling.style.display="block";						//显示另一个分页按钮
			MapManage.clearAll();
			//BusManage.lastClickBus=parseInt(curNodeObj.lastChild.getAttribute('id').substr(7));	//获得本页开头的节点编号，分页相当于点击了本页的第一个node，应该改变了排序方式这个值就可能不等于1了
			//BusManage.drawBus(BusManage.lastClickBus);											//更换行车路线
		}
		else{
			for(var i=1; i<=5; ++i){
				curNodeObj=document.getElementById(curNodeId+i);
				if(!curNodeObj)break;
				curNodeObj.lastChild.previousSibling.style.display="none";
				curNodeObj.lastChild.style.display="block";
				curNodeObj.style.display="block";//最上层的div
			}
			if(curObj)curObj.parentNode.previousSibling.style.display="block";					//显示另一个分页按钮
			MapManage.clearAll();
			//BusManage.lastClickBus=parseInt(curNodeObj.lastChild.getAttribute('id').substr(7));	//获得本页开头的节点编号，分页相当于点击了本页的第一个node，应该改变了排序方式这个值就可能不等于6了
			//setTimeout("BusManage.drawBus(BusManage.lastClickBus)",0);							//更换行车路线，这边必须这么干，不延时在IE7上可能会绘图失败，具体原因还没有找到
		}
		//解锁
		busying(0);
	},
	"drawBus":function(id){//画当前的公交线路方案，从elementID中读取坐标信息，要防止绘图出错
	    try{
	    	//清空地图
	    	MapManage.clearAll();
	    	
	    	//####画起点、换乘点等，这些点放下边没有关系####
	    	//获得所有点的坐标，从返回的结果中获取坐标
	    	var pointId = "buspoint"+id;
	    	var pointIdObj = $(pointId);
	    	if(!pointIdObj) return;
	    	var pointObj= pointIdObj.firstChild;
	    	if(!pointObj) return;
	    	var pointArray = new Array();
	    	var index=0;
	    	var startXY = ',';
	    	var endXY = ',';
	    	
	    	while(pointObj){
	    		pointArray[index] = pointObj.innerHTML.split('|||');
	    		pointObj = pointObj.nextSibling;
	    		if(pointArray[index][0] =='start'){
	    			startXY= pointArray[index][2]+","+pointArray[index][3];
	    		}
	    		else if(pointArray[index][0] =='end'){
	    			endXY= pointArray[index][2]+","+pointArray[index][3];
	    		}
	    		++index;
	    	}
	    	
	    	if(startXY=="," || endXY==",") return;
	    	//获得中间的线路并绘制
	    	var roadId = "busroad"+id;
	    	if($(roadId)==null || $(roadId).firstChild == null) return;
	    	var midRoadObj=$(roadId).firstChild;
	    	var midStr="";
	    	var tmpendXY;	//临时的步行终点
	    	while(midRoadObj){
	    		if(midRoadObj.value){
		    		midStr = MapManage.parserPolyCoords(midRoadObj.value);
		    		tmpendXY = midStr.split(";")[0];
		    		MapManage.drawFootLine(startXY+";"+tmpendXY);
		    		MapManage.drawBusLine(midStr,2);
		    		startXY = midStr.split(";")[midStr.split(";").length-1];
	    		}
	    		midRoadObj=midRoadObj.nextSibling;
	    	}
	    	MapManage.drawFootLine(startXY+";"+endXY);//最后一段步行
	    	
	    	//根据珍珍的建议，先画中间的隐藏点，再画两端及换乘点
	    	MapManage.drawBusHidePoint(pointArray);
	    	MapManage.drawBusShowPoint(pointArray);
	    	
	    	//调整
	    	mapObj.zoomToPolys();
	    	
	    	//只有画图成功了，才说明有正确的方案，给出排序方式
	    	Bottom.show('bus', BusManage.curOrderType);
	    }
	    catch(e){alert("公交线路绘图失败！");}
	},
	curOrderType:0,	//当前的排序方式：0、1、2、3、4
	title:'',
	noXY:false,		//无法获得起点或者终点的坐标，但是有公交方案。所以不应该显示“相关驾车方案”
	mark:false,		//当前的方案是否要隐藏地图
	restore:function(){
		//先隐藏底部，如果有线路，说明是正确的结果，才显示bottom
		Bottom.hide();
		if(BusManage.lastClickBus>0)BusManage.drawBus(BusManage.lastClickBus);
		else if($('buspoint1')){//显示底部排序
			if(!BusManage.curOrderType)BusManage.curOrderType = urlInfo.rc?urlInfo.rc:0;
		}
		if(busCount>0) Bottom.show('bus', BusManage.curOrderType);
		else busCount = 100;
		document.title = BusManage.title;
		BusManage.StartEndInfo = {start:urlInfo.start, end:urlInfo.end, x1:urlInfo.x1, x2:urlInfo.x2, y1:urlInfo.y1, y2:urlInfo.y2};
		if(this.mark) Mask.show();
		else Mask.hide();
	},
	url:'',
	setUrl:function(){BusManage.url = '&start='+urlInfo.start+'&end='+urlInfo.end+'&x1='+urlInfo.x1+'&y1='+urlInfo.y1+'&x2='+urlInfo.x2+'&y2='+urlInfo.y2;},
	getUrl:function(){
		if(this.bJuHe) return BusManage.url+'&method=2';		//聚合换乘方案
		else return BusManage.url+'&rc='+BusManage.curOrderType;	//需要追加一个排序方式
	},
	//用于线路聚合
	changeJuhe:function(flag){
		this.setJuHe(flag);
		//如果不想使用新方案，则清楚cookie
		if(!flag) this.setJuHeCookie(false);
		//提交请求
		Tag.submitBus();
	},
	setJuHe:function(flag){
		this.bJuHe = flag?1:0;
	},
	getJuHe:function(){return (this.bJuHe)?true:false;},
	setJuHeCookie:function(flag){
		this.bJuHe = flag;
		if(flag) setCookie('bus_j',1,30);
		else delCookie('bus_j');
	}
};

//管理公交的排序
var OrderBus={
	resetOrder:function(rc){//根据要求重新排序:0缺省,1换乘,2步行,3时间,4距离
		if(Tag.lock) return;
		if(!(rc>=0 && rc<=4)) return;			//保证输入的参数正确
		Tag.objDiv['bus'].style.display	="none";//隐藏当前的结果，给用户更好的体验
		//加锁
		busying(1);
		var url = "/?area=abbd&cmd=bus&city="+$E(Tag.cityInfo['name'])+"&start="+BusManage.StartEndInfo.start+"&end="+BusManage.StartEndInfo.end+"&x1="+BusManage.StartEndInfo.x1+"&y1="+BusManage.StartEndInfo.y1+"&x2="+BusManage.StartEndInfo.x2+"&y2="+BusManage.StartEndInfo.y2+"&rc="+rc;
		new Ajax.Request(url, {method:'get', onSuccess:Tag.submitBusSuccess, onFailure:Tag.submitBusFail});
	}
}

//管理路线，绘制路线
var LineManage={
	"curLine":1,		//当前显示的路线号
	"oldLine":1,		//上次显示的路线号
	"clear":function(){	//清空当前、上传的线路号，每次重新请求线路都应该清空
		LineManage.curLine = 0;
		LineManage.oldLine = 0;
	},
	"showLine":function(num){//显示第num条线路，将该线路绘制出来
		//如果给出了显示那条线路就进行显示，否则显示第一条
		LineManage.curLine = (num)?num:1;
		//隐藏上次的路线
		if(LineManage.oldLine){
			var objOldLineName 	 = $("line_name_"+LineManage.oldLine);
			var objOldLineDetail = $("line_detail_"+LineManage.oldLine);
			if(!objOldLineName || !objOldLineDetail) return;
			objOldLineName.style.display="block";
			objOldLineDetail.style.display="none";
		}
		//显示本次的路线
		if(LineManage.curLine){
			var objCurLineName 	 = $("line_name_"+LineManage.curLine);
			var objCurLineDetail = $("line_detail_"+LineManage.curLine);
			if(!objCurLineName || !objCurLineDetail) return;
			objCurLineName.style.display="none";
			objCurLineDetail.style.display="block";
		}
		//绘制路线图
		LineManage.drawLine();
		//将本次线路保存为老线路，下次点击其它线路就可以隐藏本次线路了
		LineManage.oldLine = LineManage.curLine;
	},
	"hideLine":function(num){//隐藏第num条线路
		//获得要隐藏的线路号
		var hideNum = (num)?num:LineManage.curLine;
		if(!hideNum) return;
		//隐藏本次线路
		var objCurLineName 	 = $("line_name_"+hideNum);
		var objCurLineDetail = $("line_detail_"+hideNum);
		if(!objCurLineName || !objCurLineDetail) return;
		objCurLineName.style.display="block";
		objCurLineDetail.style.display="none";
		//清空当前线路号和老线路号
		LineManage.curLine=0;
		LineManage.oldLine=0;
	},
	"drawLine":function(num){//绘制第num条线路
		//获得要绘制的线路号
		var drawNum = (num)?num:LineManage.curLine;
		if(!drawNum) return;
		//清空老的线路图
		MapManage.clearAll();
		//获得路线坐标,绘制路线
		if($("line_xy"+drawNum) == null) return;
		var lineXY = $("line_xy"+drawNum).innerHTML;
		if(lineXY.length<3) return;
		lineXY = MapManage.parserPolyCoords(lineXY);
		MapManage.drawBusLine(lineXY, 2);
		//获得各个公交站点坐标、各个公交站点名字，绘制公交站点
		var stationXY = $("line_station_xy"+drawNum).innerHTML;
		var stationName = $("line_station_name"+drawNum).innerHTML;
		var stationXYArray = stationXY.split(',');		//转化成数组
		var stationNameArray = stationName.split(' ');
		if(stationXYArray.length && stationNameArray.length && stationXYArray.length==2*stationNameArray.length){
			var stationArray = new Array();	//将坐标和名字放到这个数组，这样每个元素是一个三元组(x,y,name)
			for(var i=0,j=0; i<stationNameArray.length; ++i,++j){
				if(stationXYArray[2*i] && stationXYArray[2*i+1] && stationNameArray[i]){//防止坐标为空，画不出来该站点而报错，即不画坐标为空的站点，所以定义了j变量
					stationArray[j] 			= new Object();
					stationArray[j]['x']		= stationXYArray[2*i];
					stationArray[j]['y']		= stationXYArray[2*i+1];
					stationArray[j]['name']		= stationNameArray[i]+"(第"+(j+1).toString()+"站)"//"第"+(j+1).toString()+"站："+stationNameArray[i];
					stationArray[j]['serialId'] = "line"+(j+1).toString();
				}
				else{//可能会有站点没有坐标，防止绘制站点出错
					stationArray[j] 			= new Object();
					stationArray[j]['x']		= 0;
					stationArray[j]['y']		= 0;
					stationArray[j]['name']		= 0;
					stationArray[j]['serialId'] = 0;
				}
			}
		}
		MapManage.drawStation(stationArray);
		//定位地图中心点
		mapObj.zoomToPolys();
	},
	"stationOverOut":function(flag, serialId){//鼠标移进或者移出站点 flag=1移进 flag=0移出
		serialId = "line"+serialId;
		(flag)?(mapObj.showBusLabelById(serialId)):(mapObj.unshowBusLabelById(serialId));
	},
	"stationClick":function(serialId){
		serialId = "line"+serialId;
		mapObj.centerBusLabelById(serialId);
	},
	"title":'',
	"restore":function(){//tag切换回来的时候，恢复现场(2个情况：1、如果该tag没有打开过，即内容为空，需要取回其首页；2、重新绘制地图)
		//如果存在当前路线则进行绘制，否则定位到当前城市中心
		if(LineManage.curLine>0) LineManage.drawLine(LineManage.curLine);
		Bottom.show('line');	//bottom需要修改
		document.title = LineManage.title;
	},
	url:'',
	setUrl:function(){LineManage.url = '&line='+urlInfo.line;},
	getUrl:function(){return LineManage.url;}
};

//管理站点
var StationManage={
	curStatId:'',		//当前显示的站点号
	curLineId:'',		//当前显示的站点中的线路号
	statShow:function(statId, prefix){
		prefix = prefix?prefix:'';
		if(StationManage.curStatId){//隐藏老的
			if($('station_name_'+StationManage.curStatId)){
				$('station_name_'+StationManage.curStatId).show();
				$('station_detail_'+StationManage.curStatId).hide();
			}
			if($('dist_station_name_'+StationManage.curStatId)){
				$('dist_station_name_'+StationManage.curStatId).show();
				$('dist_station_detail_'+StationManage.curStatId).hide();
			}
		}
		$(prefix+'station_name_'+statId).hide();//显示新的
		$(prefix+'station_detail_'+statId).show();
		StationManage.curStatId = statId;//保存当前的站点号
		var curCentter = $('station_name_xy_'+statId).innerHTML.split('|||')[1];
		if(curCentter){
			mapObj.setMapCenter(curCentter);
			mapObj.setMapZoom(1);
		}
	},
	nameClick:function(statId){
		var curCentter = $('station_name_xy_'+statId).innerHTML.split('|||')[1];
		if(curCentter){
			mapObj.setMapCenter(curCentter);
			mapObj.setMapZoom(1);
		}
	},
	statHide:function(statId, prefix){
		prefix = prefix?prefix:'';
		$(prefix+'station_name_'+statId).show();
		$(prefix+'station_detail_'+statId).hide();
		StationManage.curStatId = '';
		StationManage.curLineId = '';
	},
	overStatId:'',		//当前响应mouseover的站点
	statOver:function(statId){
		if(statId==StationManage.overStatId || !statId) return;
		if(StationManage.overStatId){
			mapObj.unshowBigIconById('stattip_'+StationManage.overStatId);
			$('perstat_'+StationManage.overStatId).style.backgroundColor='#fff';
		}
		$('perstat_'+statId).style.backgroundColor='#F4F1F8';
		mapObj.showBigIconById('stattip_'+statId);
		StationManage.overStatId = statId;
	},
	lineClick:function(curObj){//打开线路
		var url='/?area=abbd&cmd=traffic&type=line&city='+$E(Tag.cityInfo['name'])+'&line='+$E(curObj.innerHTML)+'&unfolk=1';
		open(url);
		return false;
	},
	curLineId:'',
	lineOver:function(curLineId){
		//防止重复进入同一个线路
		if(curLineId && curLineId==StationManage.curLineId) return;
		//清楚上次的line的样式
		if(StationManage.curLineId) $('line_'+StationManage.curLineId).className='p2';
		//如果没有，则使用上次的线路，如果上次没有线路则返回
		if(!curLineId) curLineId = StationManage.curLineId;
		if(!curLineId) return;
		$('line_'+curLineId).className='p3';
		StationManage.curLineId = curLineId;
		return;
		//以下功能暂时不用，将来会用
		/*try{//清除上次的公交路线
			mapObj.removePoint('curStatLine');
			mapObj.removeAllPoly();
		}
		catch(e){return;}
		//绘制本次的公交
		var statXY = $('line_mapxy_'+curLineId).innerHTML;
		var lineXY = $('line_mapline_'+curLineId).innerHTML;
		if(lineXY.length<4) return;
		var lineXYArr = lineXY.split(',');
		var halfLen = Math.round(lineXYArr.length/2);
		halfLen = (halfLen%2)?(halfLen+1):halfLen;
		if(lineXYArr.length>4 && halfLen){
			var lineXY2 = lineXYArr.splice(halfLen, (lineXYArr.length-halfLen)).join(',');
			var lineXY1 = lineXYArr.join(',');
			lineXY2 = lineXYArr[halfLen-2]+","+lineXYArr[halfLen-1]+","+lineXY2;
			MapManage.drawBusLine(MapManage.parserPolyCoords(lineXY1),2,true);
			MapManage.drawBusLine(MapManage.parserPolyCoords(lineXY2),2);
		}
		else{
			MapManage.drawBusLine(MapManage.parserPolyCoords(lineXY),2,true);
		}
		mapObj.zoomToPolys();*/
	},
	'title':'',
	restore:function(){
		StationManage.drawTextStation();
		StationManage.lineOver();
		StationManage.statOver();
		document.title = StationManage.title;
	},
	drawTextStation:function(){//绘制所有字符匹配的站点
		var curStatMapObj = null;
		var curStatMapxy = '';
		var curTip = '';
		for(var i=1; ; ++i){
			curNameXYObj = $('station_name_xy_'+i);
			if(!curNameXYObj) break;
			curXY = curNameXYObj.innerHTML.split('|||')[1];
			if(!curXY) continue;
			StationManage.drawStationPoint(curXY, 'm'+i, '', false, 'stattip_'+i, false, '');
		}
		mapObj.zoomToPois();//显示所有这些站点
		//bottom需要修改
		Bottom.show('station');
	},
	clear:function(){
		StationManage.curStatId = '';
		StationManage.curLineId = '';
		StationManage.curLineId = '';
		StationManage.overStatId = '';
	},
	drawStationPoint:function(xy,icon,tip,isShow,id,isShowTip,tipStr){
	    var ps = new ABPointStyle();
	    ps.iconURL = "/images/"+icon+"a.gif";
	    ps.iconURL2 = "/images/"+icon+"b.gif";
	    ps.offset.iconX = 0;
	    ps.offset.iconY = -28;
	    ps.size.iconWidth = 20;
	    ps.size.iconHeight = 29;
	    ps.offset.iconX2 = 0;
	    ps.offset.iconY2 = -32;
	    ps.size.iconWidth2 = 24;
	    ps.size.iconHeight2 = 33;
	    
	    ps.showLabel = false;
	    ps.showTip = isShowTip;
	    
	    ps.tipId = id+"tip";
	    ps.tipParam = tipStr;
	    
	    var poi = new ABPointObject();
	    poi.serial_id = id;
	    var poicoor = Vqp.transformer(xy.split(",")).join(",");
	
	    poi.coord = poicoor;
	    poi.pointStyle = ps;
	    if(mapObj != null) mapObj.addPoint(poi);
	},
	url:'',
	setUrl:function(){StationManage.url = '&station='+urlInfo.station;},
	getUrl:function(){return StationManage.url;}
};

//管理驾车
var DriveManage={
	"drawDrive":function(){//绘制驾乘线路
		try{
			//清空地图
	    	MapManage.clearAll();
			//获得起点和终点
	    	var startXY	= Tag.objInputDrive['x1'].value+','+Tag.objInputDrive['y1'].value;
	    	var endXY	= Tag.objInputDrive['x2'].value+','+Tag.objInputDrive['y2'].value;
	    	if(startXY.length<3 || endXY.length<3) return;
		    //绘制起点、终点
	    	MapManage.drawPoint(startXY,"start.png","",false,'drive_start',	false,"",37,30);
	    	MapManage.drawPoint(endXY,	"end.png",	"",false,'drive_end',	false,"",36,30);
	    	//绘制路线
	    	var objMapXY = $('drive_mapxy');
	    	if(!objMapXY || !(objMapXY.innerHTML.length>3)){
	    		MapManage.clearAll();
	    		return;
	    	}
	    	var strMapXY = objMapXY.innerHTML;
	    	coord = MapManage.parserPolyCoords(strMapXY);
	    	var ls = new ABPolyStyle();
	        ls.strokeWidth = '4';
	        ls.strokeColor = "#e11a1f";
	        ls.strokeShape = 1;
	        ls.strokeOpacity = 0.85;
	        var line = new ABPolyObject();
	        line.serial_id = 1;
	        line.coord = coord;
	        line.polyStyle = ls;
	        line.polyType = 1;
	    	//重新定位地图
			mapObj.addPoly(line);
			mapObj.zoomToPolys();
			//隐藏底部
			Bottom.show('drive');
		}
		catch(e){ alert('驾车路线绘图失败！');}
	},
	"title":'',
	"restore":function(){
		//先隐藏底部，如果有线路，说明是正确的结果，才显示bottom
		Bottom.hide();
		setTimeout("DriveManage.drawDrive()", 0);
		document.title = DriveManage.title;
	},
	url:'',
	setUrl:function(){DriveManage.url = '&start='+urlInfo.start+'&end='+urlInfo.end+'&x1='+urlInfo.x1+'&y1='+urlInfo.y1+'&x2='+urlInfo.x2+'&y2='+urlInfo.y2;},
	getUrl:function(){return DriveManage.url;}
};

//代表所有页面的首页
var Face={
	"needLoadBus":		true,	//是否还有必要加载公交/路线/站点/驾车的首页
	"needLoadLine":		true,
	"needLoadStation":	true,
	"needLoadDrive":	true,
	"title":			'',
	"restore":function(tagtype){//恢复(包括：真正的恢复、服务器重新获取)
		document.title = Face.title;
		Bottom.hide();//隐藏底部
		switch(tagtype){//1、如果该页面还没有到达过，则需要重新加载；2、否则绘制右侧地图(1、如果是有商户则绘制商户；2、定位到城市中心)
			case 1:	if(Face.needLoadBus) 	Face.load('bus');		break;
			case 2:	if(Face.needLoadLine) 	Face.load('line');		break;
			case 3:	if(Face.needLoadStation)Face.load('station');	break;
			case 4:	if(Face.needLoadDrive) 	Face.load('drive');		break;
		}
		//均需要修正地图
		MapManage.clearAll();
		MapManage.setCityCenter();
		//判断是否需要绘制商户标点
		var bizName = $('g_biz_name').innerHTML;
		var bizMapXY = $('g_biz_mapxy').innerHTML;
		if(bizMapXY.length<3) return;
		var objInputTag = 	(Tag.curType==1)?Tag.objInputBus:(
							(Tag.curType==4)?Tag.objInputDrive:null);
		if(!objInputTag) return;
		if(bizName == objInputTag['name1'].value || bizName == objInputTag['name2'].value){
			Vqp.transformer(bizMapXY.split(",")).join(",");
			var precision=0;
			if(accuracy==9 || accuracy==10 || accuracy==20){
        		precision=1;
   			}
			if(precision)
				MapManage.drawPoint(bizMapXY, "jingque_big.gif",	 null, null, "r23", null, null, 22, 29, 0, -29);
			else
				MapManage.drawPoint(bizMapXY, "guji_big.gif",	 null, null, "r23", null, null, 22, 22, 0, -29);
			mapObj.setMapCenter(bizMapXY);
			setMapAndSiderSize();
		}
	},
	"load":function(typename){
		var cityName=$('g_city_name').innerHTML;
		var url='/?area=abbd&cmd=face&type='+typename+'&city='+$E(cityName);
		new Ajax.Request(url, {method:'get', onSuccess:Face.loadSuccess, onFailure:Face.loadFail});
		busying(1);
	},
	"loadSuccess":function(transport){
		var ret=transport.responseText;
		//1、如果首页加载成功，下次就不需要再加载；2、修改该div的状态为face
		if(ret && ret.length>4&& ret.substr(0,3)=="200"){
			retHtml = ret.substr(3);
			if(Tag.curType == 1){
				Tag.objDiv['bus'].innerHTML = retHtml;
				Face.needLoadBus=false;
				Tag.divStep['bus'] = 'face';
			}
			else if(Tag.curType == 2){
				Tag.objDiv['line'].innerHTML = retHtml;
				Face.needLoadLine=false;
				Tag.divStep['line'] = 'face';
			}
			else if(Tag.curType == 3){
				Tag.objDiv['station'].innerHTML = retHtml;
				Face.needLoadStation=false;
				Tag.divStep['station'] = 'face';
			}
			else if(Tag.curType == 4){
				Tag.objDiv['drive'].innerHTML = retHtml;
				Face.needLoadDrive=false;
				Tag.divStep['drive'] = 'face';
			}
			busying(0);
		}
	},
	"loadFail":function(){
		busying(0);
	}
};

//绘制地图
var MapManage={
	//路线中的起点和终点
	"idStart":	"id_end",
	"idEnd":	"id_start",
	//站点选择页面过程中的起点和终点，因为重新选择需要在地图上删除删除的点
	"idStartSelect":	"idStartSelect",
	"idEndSelect":		"idEndSelect",
	"clearAll":function(){//清空地图
		mapObj.removeAllPoly();
	    mapObj.removeAllPoint();
	},
	"setCityCenter":function(){
		var cityMapXY = $('g_city_mapxy').innerHTML;
		 if(cityMapXY.length>3) mapObj.setMapCenter(cityMapXY);
	},
	"drawBusLine":function(coord,route,endArrow){//绘制一根折线
	    try{
	    	var color = "";
	        switch(route){
	            case 0: color="#ff2222"; break;
	            case 1: color="#ee4444"; break;
	            case 2: color="#dd2222"; break;
	            case 3: color="#cc4444"; break;
	            case 4: color="#bb2222"; break;
	            case 5: color="#aa4444"; break;
	            case 5: color="#e11a1f"; break;
	        }
	        var ls = new ABPolyStyle();
	        ls.strokeWidth = '4';
	        ls.strokeColor = color;
	        ls.strokeShape = 1;
	        ls.strokeOpacity = 0.85;
	        if(endArrow)ls.endArrow = true;
	        
	        var line = new ABPolyObject();
	        line.serial_id = new Date().getTime();
	        line.coord = coord;
	        line.polyStyle = ls;
	        line.polyType = 1;
	        
	        mapObj.addPoly(line);
	    }
	    catch(e){ alert("公交线路绘图失败！！"); }
	},
	"drawFootLine":function(coord){//画一条人走的线路
	    try{
	        var ls = new ABPolyStyle();
	        ls.strokeWidth = '4';
	        ls.strokeColor = '#8888ff';
	        ls.strokeShape = 2;
	        ls.strokeOpacity = 0.7;
	        
	        var line = new ABPolyObject();
	        line.serial_id = new Date().getTime();
	        line.coord = coord;
	        line.polyStyle = ls;
	        line.polyType = 1;

	        mapObj.addPoly(line);
	    }
	    catch(e){ alert("公交线路绘图失败！！！"); }
	},
	//绘制公交站点
	"drawStation":function(stationArray){
		try{
			for(var i=0; i<stationArray.length; ++i){
				if(!stationArray[i]['x'] || !stationArray[i]['y'] || !stationArray[i]['name'] || !stationArray[i]['serialId']) continue;
				var ps = new ABPointStyle();
		        ps.iconURL = "/images/station.png";
		        ps.offset.iconX = -5;
		        ps.offset.iconY = -5;
		        ps.size.iconWidth = 11;
		        ps.size.iconHeight = 11;
		        ps.hasIcon = true;
		        
				var busLabel = new ABBusLabel();
				busLabel.labelContent = "<div style='padding:2px; color:#ffffff; background-color:#763ab9; border:1px solid #000000; white-space:nowrap;'>"+stationArray[i]['name']+"</div>";
				busLabel.offsetX = 5;
				busLabel.offsetY = 6;
				ps.busLabelObj = busLabel;
		        ps.showBusLabel = 1;
		        
		        var poi = new ABPointObject();
		        poi.serial_id = stationArray[i]['serialId'];
		        var perStationXY=[stationArray[i]['x'], stationArray[i]['y']];
		        var poicoor = Vqp.transformer(perStationXY).join(",");
		        poi.coord = poicoor;
		        poi.pointStyle = ps;
		        if (mapObj != null) mapObj.addPoint(poi);
			}
		}
		catch(e){ alert("绘制公交站点出错！"); }
	},
	//在地图上画一点
	"drawPoint":function(xy,icon,tip,isShow,id,isShowTip,tipStr,iconW,iconH,offsetX,offsetY){
	    try{
	        var ps = new ABPointStyle();
	        ps.iconURL = "/images/"+icon;
	        offsetX != null?ps.offset.iconX=offsetX:ps.offset.iconX=0;
	        offsetY != null?ps.offset.iconY=offsetY:ps.offset.iconY=-iconH;
	        /*
	        ps.offset.iconX = 0;
	        ps.offset.iconY = -iconH;
	        */
	        ps.size.iconWidth = iconW;
	        ps.size.iconHeight = iconH;
	        var poi = new ABPointObject();
	        poi.serial_id = id;
	        var poicoor = Vqp.transformer(xy.split(",")).join(",");
	        poi.coord = poicoor;
	        poi.pointStyle = ps;
	        if (mapObj != null)
	            mapObj.addPoint(poi);
	    }
	    catch(e){ alert("地点绘制出错！"); }
	},
	"drawSelectStart":function(xy_in){//绘制选择的起点，这个函数需要删除上次选择的起点，将该点定位为中心
		if(!xy_in || xy_in.length<4) return;
		mapObj.removePoint(MapManage.idStartSelect);
		MapManage.drawPoint(xy_in,"start.png","",false,MapManage.idStartSelect,false,"",37,30);
		mapObj.setMapCenter(xy_in);
		mapObj.refreshAcete();
	},
	"drawSelectEnd":function(xy_in){//绘制选择的终点，这个函数需要删除上次选择的终点，将该点定位为中心
		if(!xy_in || xy_in.length<4) return;
		mapObj.removePoint(MapManage.idEndSelect);
		MapManage.drawPoint(xy_in,"end.png","",false,MapManage.idEndSelect,false,"",36,30);
		mapObj.setMapCenter(xy_in);
		mapObj.refreshAcete();
	},
	"parserPolyCoords":function(str){//将字符串类型的坐标转换成数组类型的坐标
	    var tmp = str.split(",");
	    var length = tmp.length;
	    var coord = [];
	    for(var i=0,j=0; i< length; i++){
	        if(tmp[i] != "" && tmp[i] != ";"){
	            if(i%2 == 0){
	                coord[j] = tmp[i];
	            }
	            else{
	                coord[j] += ","+tmp[i];
	                j++;
	            }
	        }
	    }
	    startPoint = coord[0];
	    var temp = coord[coord.length-1].indexOf(",");
	    if(temp >0){
	        endPoint = coord[coord.length-1];
	    }
	    else{
	        endPoint = coord[coord.length-2];
	        coord.pop();
	    }
	    return coord.join(";");
	},
	//绘制公交的非隐藏点评
	"drawBusShowPoint":function(pointArray){
		var index=0, count=0,lastLabelText='';
		for(; index<pointArray.length; ++index,++count){
			if(pointArray[index][0] == 'station') continue;
			var ps = new ABPointStyle();
			ps.showLabel = false;
			ps.showTip = false;
	        ps.hasIcon = true;
	        ps.showBusLabel = 2;
			var buslabeltmp = new ABBusLabel();
	        if(pointArray[index][0] == "start"){
		        ps.iconURL = "/images/station.png";
		        ps.offset.iconX = -5;
		        ps.offset.iconY = -5;
		        ps.size.iconWidth = 11;
		        ps.size.iconHeight = 11;
		        var moreicon = new ABPointMoreIcon();
				moreicon.iconURL = "/images/start.png";
				moreicon.iconWidth = 37;
				moreicon.iconHeight = 30;
				moreicon.offsetX = 0;
				moreicon.offsetY = -30; 
				ps.moreIcon = [moreicon];
				buslabeltmp.offsetX = 37;
				buslabeltmp.offsetY = 10;
	        }
			else if(pointArray[index][0] == "end"){
				ps.iconURL = "/images/station.png";
				ps.offset.iconX = -5;
		        ps.offset.iconY = -5;
		        ps.size.iconWidth = 11;
		        ps.size.iconHeight = 11;
		        var moreicon = new ABPointMoreIcon();
				moreicon.iconURL = "/images/end.png";
				moreicon.iconWidth = 36;
				moreicon.iconHeight = 30;
				moreicon.offsetX = 0;
				moreicon.offsetY = -30; 
				ps.moreIcon = [moreicon];
				buslabeltmp.offsetX = 37;
				buslabeltmp.offsetY = 10;
			}
			else{
				ps.offset.iconX = -9;
		        ps.offset.iconY = -9;
		        ps.size.iconWidth = 18;
		        ps.size.iconHeight = 18;
				ps.iconURL = "/images/"+pointArray[index][0]+".gif";
				//错位，好看
				if(count == 1 || (count+2) == pointArray.length){
					buslabeltmp.offsetX = 10;
					buslabeltmp.offsetY = -20;
				}
				else if(count%2){
					buslabeltmp.offsetX = 10;
					buslabeltmp.offsetY = 10;
				}
				else{
					buslabeltmp.offsetX = 10;
					buslabeltmp.offsetY = -20;
				}
				//如果该站不是以“站”结束，则补充。
				if(pointArray[index][1].search(/站$/i) == -1){
					pointArray[index][1]+="站";
				}
			}
			if(lastLabelText == pointArray[index][1]){
				buslabeltmp.labelContent = "";
			}
			else{
				lastLabelText = pointArray[index][1];
				buslabeltmp.labelContent = "<div style='padding:2px; color:#ffffff; background-color:#763ab9; border:1px solid #000000; white-space:nowrap;'>"+pointArray[index][1]+"</div>";
			}
			ps.busLabelObj = buslabeltmp;
			var poi = new ABPointObject();
			poi.serial_id = "buspoint"+index;
			poi.coord = pointArray[index][2]+","+pointArray[index][3];
			poi.pointStyle = ps;
			if(mapObj!= null) mapObj.addPoint(poi);
	    }
	},
	"drawBusHidePoint":function(pointArray){
		var index=0, count=0;
		for(; index<pointArray.length; ++index,++count){
			if(pointArray[index][0] != 'station') continue;
			var ps = new ABPointStyle();
	        ps.iconURL = "/images/station.png";
	        ps.offset.iconX = -5;
	        ps.offset.iconY = -5;
	        ps.size.iconWidth = 11;
	        ps.size.iconHeight = 11;
	        ps.hasIcon = true;
	        
			var busLabel = new ABBusLabel();
			busLabel.labelContent = "<div style='padding:2px; color:#ffffff; background-color:#763ab9; border:1px solid #000000; white-space:nowrap;'>"+pointArray[index][1]+"</div>";
			busLabel.offsetX = 5;
			busLabel.offsetY = 6;
			ps.busLabelObj = busLabel;
	        ps.showBusLabel = 1;
	        
	        var poi = new ABPointObject();
	        poi.serial_id ="busstation"+index;
	        poi.coord =  pointArray[index][2]+","+pointArray[index][3];
	        poi.pointStyle = ps;
	        if (mapObj != null) mapObj.addPoint(poi);
		}
	}
};

var Bottom={
	"show":function(tag, busOrder){//参数：(bus/line/station/drive, 0/1/2/3/4)
		Bottom.hide();
		if(tag=='bus' && busOrder>=0 && busOrder<=4){//显示公交，将高度设置为188
			$('bottom_bus').style.display="block";
			if(!BusManage.mark && !BusManage.bJuHe){//1、没有线路坐标，则没有排序可以选择；2、不是线路聚合
				$('bussort'+busOrder).style.display="block";
			}
			siderSubHeight = 182;
			if(BusManage.noXY){//因为没有起点或站点坐标，不能切换到驾车方案
				$('getdrivefrombus').style.display="none";
			}
			else $('getdrivefrombus').style.display="block";
		}
		else if(tag=='line' || tag=='station'){//如果在结果页面则显示复制url功能，line和station是独立的，bus和drive里面已经自带了，不需要管
			$('bottom_url').style.display="block";
			siderSubHeight = 160;
		}
		else if(tag=='drive'){//显示驾车，将高度设置为168
			$('bottom_drive').style.display="block";
			siderSubHeight = 163;
		}
		setSiderSize(siderSubHeight);
	},
	"hide":function(){//隐藏全部，将边框高度设置为148
		siderSubHeight = 133;
		setSiderSize(siderSubHeight);
		$('bottom_bus').style.display	= "none";
		$('bussort0').style.display		= "none";
		$('bussort1').style.display		= "none";
		$('bussort2').style.display		= "none";
		$('bussort3').style.display		= "none";
		$('bussort4').style.display		= "none";
		$('bottom_drive').style.display	= "none";
		$('bottom_url').style.display	= "none";
	}
};

var Clipboard={//复制到剪切板
	falshVersion:function(){//获得flash的版本号
		var versionMajor = 0;
		var e;
		try{//IE
			var actObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			if(actObj){
				var versionStr = actObj.GetVariable("$version");
				var tempArray = versionStr.split(" ");				// ["WIN", "2,0,0,11"]
				var tempString = tempArray[1];						// "2,0,0,11"
				var version = tempString.split(",");
				versionMajor = version[0];
			}
		}catch(e){}
		//FireFox
		if(navigator.plugins!=null && navigator.plugins.length>0){
			if(navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]){
				var swVer2 = navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";
				var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
				var descArray = flashDescription.split(" ");
				var tempArrayMajor = descArray[2].split(".");			
				var versionMajor = tempArrayMajor[0];
			}
		}
		Clipboard.falshVersion = function(){return versionMajor}//记住本次的结果，以后就不需要计算了
		return versionMajor;
	},
	copy:function(content){//如果复制失败，返回false
		if(this.falshVersion()==8 || this.falshVersion()==9){//如果安装了Flash8和Flash9，可以直接复制
			var flashcopier = 'flashcopier';
			if (!document.getElementById(flashcopier)){
				var divholder = document.createElement('div');
				divholder.id = flashcopier;
				document.body.appendChild(divholder);
			}
			document.getElementById(flashcopier).innerHTML = '';
			var divinfo = '<embed src="/images/clipboard.swf" FlashVars="clipboard='+$E(content)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
			document.getElementById(flashcopier).innerHTML = divinfo;
			return true;
		}
		else if(window.clipboardData){//IE
			return clipboardData.setData("Text", content);
		}
		else return false;
	}
};

var CurrentURL={
	init:function(){
		if(urlInfo.type == 'bus')			BusManage.setUrl();
		else if(urlInfo.type == 'line')		LineManage.setUrl();
		else if(urlInfo.type == 'station')	StationManage.setUrl();
		else if(urlInfo.type == 'drive')	DriveManage.setUrl();
	},
	get:function(){
		if($('url_box_1').style.display=='block' || $('url_box_2').style.display=='block') return;
		//获得url
		var url = "http://"+location.host+"/?area=abbd&cmd=traffic&city="+encodeURIComponent(Tag.cityInfo['name'])+"&type=";
		switch(Tag.curType){
			case 1:	url+='bus'+BusManage.getUrl(); break;
			case 2:	url+='line'+LineManage.getUrl(); break;
			case 3:	url+='station'+StationManage.getUrl(); break;
			case 4:	url+='drive'+DriveManage.getUrl(); break;
			default:return false;
		}
		//显示给用户看
		if(Clipboard.copy(url)) this.middle($('url_box_1'), 250, 180);
		else{
			this.middle($('url_box_2'), 250, 180);
			$('cur_url').value = url;
			$('cur_url').select();
		}
	},
	middle:function(obj, height, width){
		var top = ABBrowser.getScrollTop() + (ABBrowser.getViewHeight() - height)/2;
		var left = ABBrowser.getScrollLeft() + (ABBrowser.getViewWidth() - width)*0.9/2;
		if(top<ABBrowser.getScrollTop()) top = ABBrowser.getScrollTop();
		obj.style.top 		= top +"px";
		obj.style.left 		= left + "px";
		obj.style.position 	= "absolute";
		obj.style.display 	= "block";
	},
	tmp:function(){
		if($('url_box_3').style.display=='block') return;
		this.middle($('url_box_3'), 250, 180);
		$('url_box_3').style.display='block';
	}
};

var Mask={
	show:function(){
		$('mask').show();
		CurrentURL.middle($('masktip'), 65, 0);//宽度忽略，需要考虑左边的spide
		$('masktip').show();
	},
	hide:function(){
		$('mask').hide();
		$('masktip').hide();
	}
}
//######################其它函数######################
//是否要展示正在加载
var loadingObj=null;//表示正在加载的图片对象
function busying(flag)
{
	(!loadingObj)&&(loadingObj=$('loading'));
	if(loadingObj){
		if(flag){
			Tag.lock=true;
			var moreSelectObj=$('more_select');
			if(moreSelectObj){moreSelectObj.style.display="none";}
		}
		else Tag.lock=false;
		
		loadingObj.style.display=flag?"block":"none";
	}
}
//打印公交路线
function printBusRoute(index)
{
	var x1=$('bus_x1').value;
	var x2=$('bus_x2').value;
	var y1=$('bus_y1').value;
	var y2=$('bus_y2').value;
	var city=$('g_city_name').innerHTML;
    var start=$('bus_name1').value;
    var end=$('bus_name2').value;
	url="/?area=abbd&cmd=busprint"+"&x1="+x1+"&x2="+x2+"&y1="+y1+"&y2="+y2+"&city="+$E(city)+"&start="+$E(start)+"&end="+$E(end)+"&index="+(index-1);
	if(BusManage.getJuHe()) url += "&method=2";
	else{
		if(BusManage.curOrderType) url += "&rc="+BusManage.curOrderType;
		if(BusManage.mark) url += "&method=1";
	}
    window.open(url,"","titlebar=0, height=680, width=680, top=200, left=200; toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, status=no");
}
function printDriveRoute(type)
{
    var x1=$('drive_x1').value;
	var x2=$('drive_x2').value;
	var y1=$('drive_y1').value;
	var y2=$('drive_y2').value;
	var city=$('g_city_name').innerHTML;
    var start=$('drive_name1').value;
    var end=$('drive_name2').value;
    var url = "/?area=abbd&cmd=driveprint";
    url += "&x1="+x1+"&x2="+x2+"&y1="+y1+"&y2="+y2+"&city="+$E(city)+"&origin="+$E(start)+"&end="+$E(end)+"&type="+type;
    window.open(url,"","titlebar=0, height=680, width=680, top=200, left=200; toolbar =no, menubar=no, scrollbars=yes, resizable=no, location=no, status=no");
}
//在20个城市DIV中点选城市
function trafficChangeCityUrl(city) {return "/?area=abbd&cmd=traffic&city="+$E(city);}

function bindEventForTraffic()
{
    var _city = $("g_city_name").innerHTML;
	var _bbj1 = $("bus_name1");
	var _bbj2 = $("bus_name2");
	var _dbj1 = $("drive_name1");
	var _dbj2 = $("drive_name2");
	
	if(_bbj1){
	   attachEventListener(_bbj1,'keyup',function(evt){
	      suggestRoadAddrInCity(evt,_city); 
	   },false);
	   attachEventListener(_bbj1,'keydown',function(evt){
	      responseInput(evt,this);
	   },false);
	}
    if(_bbj2){
	   attachEventListener(_bbj2,'keyup',function(evt){
	      suggestRoadAddrInCity(evt,_city); 
	   },false);
	   attachEventListener(_bbj2,'keydown',function(evt){
	      responseInput(evt,this);
	   },false);
	}
    if(_dbj1){
	   attachEventListener(_dbj1,'keyup',function(evt){
	      suggestRoadAddrInCity(evt,_city); 
	   },false);
	   attachEventListener(_dbj1,'keydown',function(evt){
	      responseInput(evt,this);
	   },false);
	}
    if(_dbj2){
	   attachEventListener(_dbj2,'keyup',function(evt){
	      suggestRoadAddrInCity(evt,_city); 
	   },false);
	   attachEventListener(_dbj2,'keydown',function(evt){
	      responseInput(evt,this);
	   },false);
	}
}

